text:
Q: Amplitude of periodic function I want to find the amplitude of a periodic function. The function happens to be a sum of different sawtooth functions each with amplitude 1 but different periods.  (The period of the sum function is just the lowest common multiple of the components.)
Now, if the function was a sum of continuous functions, I gather we could differentiate the function and the maxima and minima would occur where the derivative equals zero.  However, sawtooth functions are discontinuous and can't be differentiated at the points of discontinuity.  In a sum of sawtooth functions, the maxima and minima occur at points of discontinuity.  So, is there another way to determine the amplitude of the sum function?
Eg. consider 3 sawtooth functions $f(A), f(B), f(C)$ each having amplitude 1, and period $1$, $2$ and $3$ respectively.  The sum function is, say, $f(X) = f(A) + f(B) - f(C)$.  The $f(A)$ component with period $1$ results in points of discontinuity at every integer value.
In this particular simple example, the period of the sum function is $6$, and the amplitude is approximately $2.2$, with a maximum of approximately $1.1$ at $x=4$ and minimum of approximately $-1.1$ at $x=2$.  However, in the sum function there are local maxima and minima, with points of discontinuity, at every integer value.

Thanks.


text:
Q: Property 'productForm' has no initializer and is not definitely assigned in the constructor I was trying to make a reactive form but this error "Property 'productForm' has no initializer and is not definitely assigned in the constructor."
Code for TypeScript file is -
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-create-product',
  templateUrl: './create-product.component.html',
  styleUrls: ['./create-product.component.css']
})
export class CreateProductComponent implements OnInit {
  productForm:FormGroup;

  constructor() { }

  ngOnInit(){
    this.productForm = new FormGroup({
      name: new FormControl(null),
      email: new FormControl(null),
      number: new FormControl(null),
      address: new FormControl(null)
    });
  }

  onSubmit(){
    console.log(this.productForm)
  }
}

And HTML file for this corresponding file is-
<form [formGroup]="productForm" (ngSubmit)="onSubmit()">

        Name
        <input type="name" class="form-control" formControlName="name"/>

      Email address
      <input type="email" class="form-control" formControlName="email" />

        Mobile Number
        <input type="number" class="form-control" formControlName="number" />

        Address
        <input type="address" class="form-control" formControlName="address" />

    <button type="submit" class="btn btn-primary">Submit</button>
</form>

Can anyone tell me what can I do?

A: the rules of your linter confguration except any property to be initialized either when declaring the property or into the constructor.
You can change the rules or move the initialization to the constructor (or the declaration) :
productForm:FormGroup;

  constructor() {
    this.productForm = new FormGroup({
      name: new FormControl(null),
      email: new FormControl(null),
      number: new FormControl(null),
      address: new FormControl(null)
    });
  }

  ngOnInit() {
  }

A: The simple approach for this problem:
Go to your angular project "tsconfig.json" file and add "strictPropertyInitialization": false in the compilerOptions section.

` "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "noImplicitOverride": true,
    "noPropertyAccessFromIndexSignature": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2017",
    "module": "es2020",
    "lib": [
      "es2020",
      "dom"
    ],
    "strictPropertyInitialization": false
  }

redpajama_set_name: RedPajamaStackExchange


text:
Q: React native setState array I need to change the state of an array element. This changing leads to change the color of the view, and an image.
How I can change the state in react native and upload the changes?

A: If you are changing the theme of your app (with static colors and image urls) it is better to handle it in css and save the theme's name in state, like this:

class App extends React.Component {
  state = {
    theme: 'green-theme'
  }

  handleClick = () => {
    this.setState({ theme: 'red-theme' })
  }

  render(){
    const { theme } = this.state;
    return (
      <button className={theme} onClick={this.handleClick}>change theme</button>
    )
  }
}

ReactDOM.render(<App />, document.getElementById('root'))
.green-theme {
  background-color: lightgreen;
  /* background-image: url('path/to/img1'); */
}

.red-theme {
  background-color: lightcoral;
  /* background-image: url('path/to/img2'); */
}


text:
Q: 2 Controls, 1 event Forms http://img101.imageshack.us/img101/6970/stackoverflowquestion.png
I have 2 input textboxes that take a host or IP.  When the user leaves an input box an event is fired that checks the input to see if it is actually a live computer.  The results are then put into the appropriate label.
My question is, should I be using separate events for each input box, since they update different labels?  Or, can I use 1 event and check who the caller was, then update the appropriate label?

A: As they update separate labels I'd go for two event handlers. It's cleaner and doesn't require any logic.
These can call a utility method that does the actual update if you want to keep that code in one place.

A: short answer yes.
If you just have two then you could write a switch statement. But then you would be tightly coupled to the actual labels.
The other option to to place the label in the Tag property, then when you get the sender get the tag of the sender, cast as a label and set the text.

A: Another alternative is a custom control that contains the textbox and label, and build the event handler into the control's textbox_leave event, assuming you've got consistent logic for all controls.

A: You can do it either way, but i would say that you should use 2 different event handlers then you don't need any logic to decide what to do based on the caller.  It makes for cleaner, easier to understand code.

A: Use two events and have the handlers call a common method which takes the label as the parameter.

A: Maybe have one main event handler (not a real event handler, but similar) that accepts a reference to a label, and individual event handlers that call the main one, something like:
private void AnyTextBox_Leave(object sender, EventArgs e, Label labelToUpdate)
{
  // Do stuff
}

private void TextBox1_Leave(object sender, EventArgs e)
{
  AnyTextBox_Leave(sender, e, lbl1);
}
private void TextBox2_Leave(object sender, EventArgs e)
{
  AnyTextBox_Leave(sender, e, lbl2);
}

A: I would register two separate events one for each label.


text:
Q: SimpleXML not printing XML declaration I'm created a dynamically generated XML document with SimpleXML in PHP7.
The issue I'm facing is that the XML is not being produced with the XML declaration - and I've tried various methods unsuccessfully of doing it - currently I have the following:
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><urlset />');

//more code

header('Content-Type: application/xml');

echo($xml->asXML());

The XML declaration should be this, at the top of the document:
<?xml version="1.0" encoding="utf-8"?>

I've also tried sketchy things like printing the declaration before the XML - to no avail.
If you need more info please let me know!
Related question = XML Declaration Tag using SimpleXML

A: Browser was hiding it :(
To verify, save the XML to file and run cat file.xml in a terminal.


text:
Q: How to change routes in ruby on rails? I just installed Ruby on Rails and created a scaffold called posts. RoR generated controllers and other required files for me.
I created a new method in posts_controller, but I can't access it. I looked at other methods that are in the controller and looks like I need to access them by /posts/[MY POST ID]/[MY METHOD NAME].
Assuming I created my custom method hello in the controller, how do i access it?
I looked at routes.rb, but there's no configuration for it.
Updated:
I understand that I can manually configure it in routes.rb, but how do all the other methods work? For example, I have "edit", and "update" methods in the "posts_controller.rb" controller. How do those two methods work without configuring routes?
  # GET /posts/1/edit
  def edit
    @post = Post.find(params[:id])
  end

I can't find a configuration that matches /posts/[0-9]/edit pattern.

A: The documentation you're looking for is Rails Routing From the Outside In. Once you've read this you'll understand everything Rails does to take your request and point it at method in your controller.

A: You need to add a route for it to routes.rb. For example:
# Previous routes
# resources :posts

# Updated routes
resources :posts do
  get "hello", :on => :member
end

Have a look at this Rails guide about routing, it should help you understand Rails routing.

A: This will give you a good head start on the routes: http://guides.rubyonrails.org/routing.html
Not every method you make will have its own path, rails is built on the rest principle, and your scaffold created methods in the post controller that follow those paths, like index, show etc....
You can force your method to have a route added to it, but in reality you rarely actually need to do so as following the convention is far easier.

A: In Rails 3.x
match 'posts/hello' => 'posts#hello'
Available at example.com/posts/hello

A: When you used scaffold to generate post, it added a line resources :posts in your routes.rb file.  That line configures routes for all the controller actions that were generated.  As Caleb mentions above, not every action has a dedicated path.  A single path can correspond to multiple actions because rails also takes into account the HTTP method.  So, for instance, the path /posts with the HTTP method GET corresponds to the controller action index, while the same path with the HTTP method PUT corresponds to the controller action update.  You can see these associations when you run rake routes from the console.  I agree with Jordan and Caleb that the Rails Guides is a good read and will help you understand routes.


text:
Q: Javascript code doesnot work on safari , rails on change submit $(document).ready(function() {
  $('.instant-submit').on('change', function() {
     this.form.submit();
  });
});
<%= form_with(url: profile_path, method: :get) do |form| %>
  <select class="form-control filter instant-submit" id="data" name="data" >
  <option <%= params[:data] == "Weekly" ? "selected" : "" %> value="Weekly" > <%=
 link_to "Weekly",class: 'form-control'%> </option>
 <option <%= params[:data] == "Daily" ? "selected" : "" %> value="Daily"> <%= link_to
"Daily", class: 'form-control' %></option>
</select>
<% end %>

THis is my code, it doesnot work on safari ? I am trying to submit form on change select. It works on chrome and other browser but not in safari. Why ?
THis is my code,


text:
Q: Accidentally Deleted Local Key Pair I am running an AWS EC2 VM for a school project. I accidentally deleted the local key pair on my computer then emptied my recycle bin on my Mac. I dont see a way to redownload the keypair.
There are important things running on the VM that I need.
Is it possible to redownload the local keypair?
I cant even seem to regenerate a new keypair to that instance.

A: There are two ways to recover the access.

*

*AWS Systems Manager (SSM) automation
To recover access to your Linux instance using AWS Systems Manager (SSM) automation, run the AWSSupport-ResetAccess Automation automation document. For more information, see Reset Passwords and SSH Keys on Amazon EC2 Instances.

*Manually recover access
To manually recover access to your Linux instance, create a new key pair to replace the lost key pair. For more information, see Connecting to Your Linux Instance If You Lose Your Private Key.


text:
Q: How to avoid repeating same scripts and styles sections in MVC views I have an MVC 5 project (.NET Framework) where a set of Views have the same set of @section styles and @section scripts blocks.
@section styles {
    <link href="~/Content/DataTables/css/jquery.dataTables.css" rel="stylesheet" />
    <link href="~/Content/DataTables/css/buttons.dataTables.css" rel="stylesheet" />
}
@section scripts {
    <script src="~/Scripts/DataTables/jquery.dataTables.js"></script>
    <script src="~/Scripts/DataTables/dataTables.buttons.js"></script>
    <script src="~/Scripts/DataTables/buttons.print.js"></script>
    <script src="~/Scripts/DataTables/buttons.html5.js"></script>
    <script src="~/Scripts/jszip.js"></script>
    <script>
        $(() => {
            // source js file defined in BundleConfig.cs
            TableController.init();
        });
    </script>
}

Just as the one TableController.init() jQuery function rests in a single location and can be called in any View I choose, is there a way I can have only a single definition of this set of <link> and <script> elements be able to call it in any view I choose?  The reason I did not put this in the _Layout file is that I might not want it on all Views -- just most of them.
I don't know what this technique is called, or even if it is possible in MVC. I just figured that it would be a useful way to avoid repeating myself. Furthermore, if I wanted to make any tweaks, I would only make a change in one place and not multiple Views.
Is there a technique I can use to achieve this goal?

A: You can create Bundles for anything you want, You can create a Bundle for an area or a single page.
//scripts
    bundles.Add(new ScriptBundle("~/bundles/Custom").Include(
                    "~/Scripts/Custom.js"));
    bundles.Add(new ScriptBundle("~/bundles/Custom2").Include(
                    "~/Scripts/Custom2.js"));
//styles
    bundles.Add(new StyleBundle("~/Content/Custom").Include(
                           "~/Content/Custom.css"));
    bundles.Add(new StyleBundle("~/Content/Custom2").Include(
                           "~/Content/Custom2.css"));

Now you can separate theese scripts and styles and add them only on page that you need.
Also I suppose it's good to define 2 sections in your _Layout.cshtml in head tag.
<head>
    //other scripts and styles here
    @RenderSection("scriptslib", required: false)
    @RenderSection("csslib", required: false)
</head>

So now in your Views (Cabinet.cshtml and AdminPanel.cshtml) you can place your libs where they suppose to be like this:
@section scriptslib{
    @Scripts.Render("~/bundles/Custom")
    @Scripts.Render("~/bundles/Custom2")
    }

By doing this it allows you to build complete bundles for sections or pages to use how you wish.
**

EDIT: thanks Adrian

**
You can add bundles as folders for future scripts using wildcards so you do not have to recompile, aswell as place a custom.js and custom.css in each folder for future edits or overrides you may want to add.
ADDING A CUSTOM FOLDERS:

*

*Scripts

*

*Custom

*

*YourFiles.js

*YourFiles.min.js

*Content

*

*Custom

*

*YourFiles.css

*YourFiles.min.css

Custom Bundles:

    bundles.Add(new ScriptBundle("~/bundles/Custom").Include(
                    "~/Scripts/Custom/*.js"));
    bundles.Add(new ScriptBundle("~/bundles/Custom2").Include(
                    "~/Scripts/Custom/*.*.js"));

    bundles.Add(new StyleBundle("~/Content/Custom").Include(
               "~/Content/Custom/*.css"));
    bundles.Add(new StyleBundle("~/Content/Custom2").Include(
               "~/Content/Custom/*.*.css"));

Now anything you place in those folders will be processed with a IIS App restart, I usually add a function to my applications to be able to perform the App Restart.
Hope this helps

A: Try the pool pro's idea, it's a great answer. For me I simply prefer to use partial views for referencing it.
Why ?
You need to compile the code again once you modify the c# file and add a another CSS or JS file. If you use partial views you don't need to compile the project again, you can just change views and upload.

A: Not pretty: You could use partialview and use it in views you want your links.
Put your partialview in your shared folder.
Then call this inside your view @await Html.PartialAsync("_SomeNamePartial")
More beautiful: Put all css in 1 file and all javascript in 1 file.
Best way and as it should be: Your way of doing it, @section is there for a reason.


text:
Q: Jquery popup display at once time on the same page I have set my code like this, that when the page is refreshed it will show a popup and make the counter one. And once the counter is one popup should not be displayed again.
I am having this issue that it is showing and again on the same page and I want it to show the popup on the same page. When then is changed to another, then same process is to be repeated.
var counter = 0;
counter ++;

if(counter == 1)
{
    setInterval(function () {
    $('.popup2, .overlay2').fadeIn();
}, 1500);

}
else {
    $('.popup2, .overlay2').fadeout();
}

I have also tried this code but it is not working
    if ($ .cookie("popup_1_2") == null) {
    setInterval(function () {
        $('.popup2, .overlay2').fadeIn();
    }, 1500);
    $ .cookie("popup_1_2", "2");
}

A: You want to be using setTimeout for a single action after a time interval. SetInterval is for infinitely repeating events (until canceled)
I don't know why you need the counter though. Instead just activate the popup on page load
$(document).ready(function() {
    setTimeout(function () {
       $('.popup2, .overlay2').fadeIn();
    }, 1500);
})

if The counter was meant to somehow be aware if the same user had come back to the page a second time (and therefore don't show the popup, you could use localStorage, like
$(document).ready(function() {
    let beentheredonethat = localStorage.getItem('popupviewed')
    if (!beentheredonethat){
       setTimeout(function () {
          $('.popup2, .overlay2').fadeIn();
       }, 1500);
       localStorage.setItem('popupviewed','true');
    }
})


text:
Q: Law of Demeter: Argument method clarification So the law of demeter essentially aims to reduce coupling between modules. I am working on writing out some examples to ensure that I understand the concept conceptually. The code that I have written is below, and would just like clarification. From my understanding the set of preferred classes include: the classes of instance variables of class car, argument classes of method foo or the class car itself. Because of the 3rd line where truck is being acted upon via a method of the car class itself, it is my understanding that this upholds the law of demeter. Can anyone give me clarification?
public void foo( vehicle car ) {
    vehicle truck = car;
    truck.do(truck);
}

The above code does not

A: Yes, it does violate the law of Demeter. It reaches through truck to get to car.do(), using truck (an alias for parameter car) as a parameter. Car is being passed itself as a parameter)


text:
Q: Better way to write this regex to match multi-ordered property list? I've been whacking on this regex for a while, trying to build something that can pick out multiple ordered property values (DTSTART, DTEND, SUMMARY) from an .ics file.  I have other options (like reading one line at a time and scanning), but wanted to build a single regex that can handle the whole thing.
SAMPLE PERL
# There has got to be a better way...
my $x1 = '(?:^DTSTART[^\:]*:(?<dts>.*?)$)';
my $x2 = '(?:^DTEND[^\:]*:(?<dte>.*?)$)';
my $x3 = '(?:^SUMMARY[^\:]*:(?<dtn>.*?)$)';
my $fmt = "$x1.*$x2.*$x3|$x1.*$x3.*$x2|$x2.*$x1.*$x3|$x2.*$x3.*$x1|$x3.*$x1.*$x2|$x3.*$x2.*$x1";

if ($evts[1] =~ /$fmt/smo) {
printf "lines:\n==>\n%s\n==>\n%s\n==>\n%s\n", $+{dts}, $+{dte}, $+{dtn};
} else {
print "Failed.\n";
}

SAMPLE DATA
BEGIN:VEVENT
UID:0A5ECBC3-CAFB-4CCE-91E3-247DF6C6652A
TRANSP:OPAQUE
SUMMARY:Gandalf_flinger1
DTEND:20071127T170005
DTSTART,lang=en_us:20071127T103000
DTSTAMP:20100325T003424Z
X-APPLE-EWS-BUSYSTATUS:BUSY
SEQUENCE:0
END:VEVENT
SAMPLE OUTPUT
lines:
==>
20071127T103000
==>
20071127T170005
==>
Gandalf_flinger1

A: CPAN is your friend:
vFile
iCal parser
You will pull your hair out until bald without a parser on vFile format (other than trivial files.) Regex for this is very hard.

A: Instead of permuting the three regexes into one big pattern with ORs, why not test the three patterns separately, since (given the anchoring $s, ) they cannot overlap?
my $x1 = qr/(?:^DTSTART[^:]*:(?<dts>.*?)$)/smo;
my $x2 = qr/(?:^DTEND[^:]*:(?<dte>.*?)$)/smo;
my $x3 = qr/(?:^SUMMARY[^:]*:(?<dtn>.*?)$)/smo;

if ($evts[1] =~ $x1 and $evts[1] =~ $x2 and $evts[1] =~ $x3)
{
    # ...
}

(I also turned the x variables into patterns themselves, and removed the unneeded escape in the character classes.)

A: It's better to use three regexes and some extra logic. This problem isn't a good match for regexes.

A: That's ugly... I think that the "better way" is to match each property, once at a time.


text:
Q: I can run the model which I made with simpletransformers in google colab, but when I run it in spyder or visual studio, it gives an error from simpletransformers.classification import ClassificationModel
import torch
Bert_model = ClassificationModel(
    "bert", "bert_model")
a=Bert_model.predict(["kötü"])
print(a)
def run():
    torch.multiprocessing.freeze_support()
    print('loop')

if __name__ == '__main__':
    run()

2022-08-09 09:00:57.159758: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'cudart64_110.dll'; dlerror: cudart64_110.dll not found2022-08-09 09:00:57.159911: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
0%|                                                                                | 0/1 [00:00<?, ?it/s]2022-08-09 09:01:03.293148: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'cudart64_110.dll'; dlerror: cudart64_110.dll not found
2022-08-09 09:01:03.293547: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
Traceback (most recent call last):
File "", line 1, in
File "C:\Users\gokhan\AppData\Local\Programs\Python\Python39\lib\multiprocessing\spawn.py", line 116, in spawn_main
exitcode = _main(fd, parent_sentinel)
File "C:\Users\gokhan\AppData\Local\Programs\Python\Python39\lib\multiprocessing\spawn.py", line 125, in _main
prepare(preparation_data)
File "C:\Users\gokhan\AppData\Local\Programs\Python\Python39\lib\multiprocessing\spawn.py", line 236, in prepare
_fixup_main_from_path(data['init_main_from_path'])
File "C:\Users\gokhan\AppData\Local\Programs\Python\Python39\lib\multiprocessing\spawn.py", line 287, in _fixup_main_from_path
main_content = runpy.run_path(main_path,
File "C:\Users\gokhan\AppData\Local\Programs\Python\Python39\lib\runpy.py", line 268, in run_path
return _run_module_code(code, init_globals, run_name,
File "C:\Users\gokhan\AppData\Local\Programs\Python\Python39\lib\runpy.py", line 97, in _run_module_code
_run_code(code, mod_globals, init_globals,
File "C:\Users\gokhan\AppData\Local\Programs\Python\Python39\lib\runpy.py", line 87, in _run_code
exec(code, run_globals)
File "C:\Users\gokhan\Desktop\code\python\FLASK\aa.py", line 5, in
a=Bert_model.predict(["kötü"])
File "C:\Users\gokhan\AppData\Local\Programs\Python\Python39\lib\site-packages\simpletransformers\classification\classification_model.py", line 2062, in predict
eval_dataset = self.load_and_cache_examples(
File "C:\Users\gokhan\AppData\Local\Programs\Python\Python39\lib\site-packages\simpletransformers\classification\classification_model.py", line 1815, in load_and_cache_examples    dataset = ClassificationDataset(
File "C:\Users\gokhan\AppData\Local\Programs\Python\Python39\lib\site-packages\simpletransformers\classification\classification_utils.py", line 278, in init
self.examples, self.labels = build_classification_dataset(
File "C:\Users\gokhan\AppData\Local\Programs\Python\Python39\lib\site-packages\simpletransformers\classification\classification_utils.py", line 244, in build_classification_dataset
with Pool(args.process_count) as p:
File "C:\Users\gokhan\AppData\Local\Programs\Python\Python39\lib\multiprocessing\context.py", line 119, in Pool
return Pool(processes, initializer, initargs, maxtasksperchild,
File "C:\Users\gokhan\AppData\Local\Programs\Python\Python39\lib\multiprocessing\pool.py", line 212, in init
self._repopulate_pool()
File "C:\Users\gokhan\AppData\Local\Programs\Python\Python39\lib\multiprocessing\pool.py", line 303, in _repopulate_pool
return self._repopulate_pool_static(self._ctx, self.Process,
File "C:\Users\gokhan\AppData\Local\Programs\Python\Python39\lib\multiprocessing\pool.py", line 326, in _repopulate_pool_static
w.start()
File "C:\Users\gokhan\AppData\Local\Programs\Python\Python39\lib\multiprocessing\process.py", line 121, in start
self._popen = self._Popen(self)
File "C:\Users\gokhan\AppData\Local\Programs\Python\Python39\lib\multiprocessing\context.py", line 327, in _Popen
return Popen(process_obj)
File "C:\Users\gokhan\AppData\Local\Programs\Python\Python39\lib\multiprocessing\popen_spawn_win32.py", line 45, in init
prep_data = spawn.get_preparation_data(process_obj._name)
File "C:\Users\gokhan\AppData\Local\Programs\Python\Python39\lib\multiprocessing\spawn.py", line 154, in get_preparation_data
_check_not_importing_main()
File "C:\Users\gokhan\AppData\Local\Programs\Python\Python39\lib\multiprocessing\spawn.py", line 134, in _check_not_importing_main
raise RuntimeError('''
RuntimeError:
An attempt has been made to start a new process before the
current process has finished its bootstrapping phase.

    This probably means that you are not using fork to start your
    child processes and you have forgotten to use the proper idiom
    in the main module:

        if __name__ == '__main__':
            freeze_support()
            ...

    The "freeze_support()" line can be omitted if the program
    is not going to be frozen to produce an executable.

A: I think the error already solve your question
Set the
if __name__ == '__main__':
        freeze_support()
        ...

on your main.py code to multi thread the jobs.


text:
Q: The correct place to write queries in asp.net mvc Let's say i have a blog with posts by different authors, and the authors should be able see what articles they have written.
Now i write a query using db context of entity framework.
Now the question is where should the query go in the specific action method of the controller or the model class.
I am kinda new and this thing has been confusing me.

A: Controllers should be as lean as possible
So the best place to put the query is outside the controller action, typically place for the all kind of the persistence queries are repositories (Repository Pattern) or some business logic layer - really depends of the complexity of the application.
In short Repository Pattern is really about that there is only one place in the application that contains the knowledge of the persistence and how to query it, typically we can find CRUD operations in there. Also typically you have one repository per "domain context" (Order, Blog post, ...).
For example (the workflow for a small app):
OrderController -> OrderRepository -> Persistance
CreateOrderAction -> SaveOrder -> Query

Because. Think about it. What if you have OrderController and then let's say a SpecialOrderController but both needs the Order data? In that case you end up with query code duplication, if a case of the repository pattern you avoid this "trap". As you know DRY principle is one of the greatest in our craftsmanship.

A: I would put those kinds of queries into a repository class; that way you are enabling the use of the same queries in multiple parts of your application.

A: It depends on the layers of your application. The fact that it's MVC doesn't matter. Do you have a data layer? If so, it goes there.
This is a little bit like asking where your queries would go in a WinForms app. Again, if this is a non-trivial app, you probably have a UI, maybe a service layer, a business logic layer, and a data layer. The data layer is where your queries go.
In an MVC app, the controller knows how to react to events in the view. In apps that I've worked on, the controller will make a call to the business logic layer, and the BLL will then connect to the data layer. This would be overkill in trivial apps, but I'm not sure how extensive your application is.
The BLL and DAL are your model. So, the short answer is:

The queries belong in the model, not the controller.


text:
Q: How to fix 403 error on xmlrpc.php in nginx? I am using nginx on my server. Now i am trying to allow ip to access xmlrpc.php file in wordpress nginx.conf file using below code.
location = /xmlrpc.php {
    allow XXX.XXX.XXX.XX; #example ip
    deny all;
    access_log off;
    log_not_found off;
}

But this is still not working. Can you please check what i am doing wrong in above


text:
Q: Laravel - Undefined index: current_timestamp in Nested foreach In my Laravel-5.8, I am trying to use Nested foreach statement in the view blade:
I have this controller:
public  function index()
{
    try{
    $client = new Client();
    $res = $client->request('GET','https://example.com/tracking/JKK998', [
       'query' => ['key' => 'jkkkm7725']
   ])->getBody();
    $geoLocation = json_decode($res->getContents(), true);
    $geoLocationData = collect($geoLocation)->sortBy(function ($data) {
        return Carbon::parse($data['current_timestamp'])->format('d-m-Y h:i:s');
    })->all();
    $currentLocation = collect($geoLocation)->sortByDesc(function ($data) {
        return Carbon::parse($data['current_timestamp'])->format('d-m-Y h:i:s');
    })->first();
    $currentLocationGroup = collect($geoLocation)->groupBy(function ($data) {
        return Carbon::parse($data['current_timestamp'])->format('d-m-Y');
    })->all();
    $currentLocationFilter = explode(',', $currentLocation['current_coord'] ?? '');
    return view('index', [
        'currentLocation' => $currentLocation,
        'currentLocationGroup' => $currentLocationGroup,
        'currentLocationFilter' => $currentLocationFilter,
        'geoLocation' => $geoLocation,
        'geoLocationData' => $geoLocationData
    ]);
    }catch (Exception $exception) {
        Log::error($exception);
        return back();
    }
}

dd($currentLocationGroup);
gives:
array:14 [▼
  "22-06-2020" => Illuminate\Support\Collection {#297 ▼
    #items: array:25 [▼
      0 => array:30 [▼
        "current_timestamp" => "2020-06-22T11:53:29Z"
        "trip_status" => "DISPATCHED"
      ]
      1 => array:31 [▶]
      2 => array:31 [▶]
      ...

While dd($geoLocationData); gives:
array:554 [▼
 0 => array:30 [▼
  "current_timestamp" => "2021-01-22T12:30:25.4698261Z"
  "client_tracking_id" => "ddd3321"
  "current_asset_position_name" => "2, Adelaide, Australia"
  "trip_status" => "DISPATCHED"
]
1 => array:31 [▼
  "current_timestamp" => "2021-02-23T20:51:50.3066741Z"
  "client_tracking_id" => "TRIP-20200621007"
  "current_asset_position_name" => "20, Adelaide, Australia"
  "trip_status" => "AROUND CUSTOMER LOCATION"
]
....

View blade:

@foreach($currentLocationGroup as $groupValue)

  {{ \Carbon\Carbon::parse($groupValue['current_timestamp'])->format('d-m-Y') }}

@foreach($geoLocationData as $value)
 @if(\Carbon\Carbon::parse($groupValue['current_timestamp'])->format('d-m-Y') == \Carbon\Carbon::parse($value['current_timestamp'])->format('d-m-Y') )

     {{ \Carbon\Carbon::parse($value['current_timestamp'])->diffForHumans() ?? 'N/A' }}

Trip Status: {{ $value['trip_status'] }}

Location: {{ $value['current_name'] ?? '' }}

Time: {{ \Carbon\Carbon::parse($value['current_timestamp'])->format('d-m-Y h:i:sA') ?? 'N/A'  }}

@endif
endforeach

But I got this error:

ErrorException
Undefined index: current_timestamp

C:\xampp\htdocs\tracking-app\vendor\laravel\framework\src\Illuminate\Collections\Collection.php:1414

public function offsetExists($key)
{
    return isset($this->items[$key]);
}

But it exists.
How do I get this resolved?
Thanks


text:
Q: Example of $\sum a_n$ convergent but $\sum \sqrt{a_{2^k}}$ divergent? The problem is this:

Prove that the convergence of $\sum a_n$ implies the convergence of $$\sum \frac{\sqrt{a_n}}{n},$$ if $a_n\geq 0.$

I'm using the Cauchy's method:
$\sum \frac{\sqrt{a_n}}{n}$ converges $\iff$ $\sum2^k\frac{\sqrt{a_{2^k}}}{2^k}=\sum\sqrt{a_{2^k}}$ converges.
If $\sum a_n$ converges $\implies$ $\sum \sqrt{a_{2^k}}$ converges is true, I'm done.
Since $\sum a_n$ converges $\implies$ $a_n\to 0$, at least we have $\sqrt{a_{2^k}}\to 0$. But the thing is, near $0$, squarerooting makes it greater. So I can't use comparison test.
But we are choosing $a_{2^k}$ with great distance betwwen them, it will decay much faster. Like $2^k$ faster. So I'm highly confident that it will converge. However, I can't find $N$ such that $n>N$ implies $\sqrt{a_{2^n}}\leq a_n.$ Actually, I think there would be a counterexample (so the title is).
How do I proceed from here? And is there a counterexample?

A: The problem that you want to solve is easy to solve using the Cauchy-Schwarz inequality and the fact that the series $\sum_{n=1}^\infty\frac1{n^2}$ converge.
On the other hand, your approach is wrong, since the Cauchy condensation test assumes that he sequence $(a_n)_{n\in\mathbb N}$ is non-increasing, and you are not assuming that.
Finally, if$$a_n=\begin{cases}\frac1{k^2}&\text{ if $n=2^k$ for some $k$}\\0&\text{ otherwise,}\end{cases}$$then $\sum_{n=1}^\infty a_n$ converges, but $\sum_{k=0}^\infty\sqrt{a_{2^k}}$ diverges.

A: $\sum \frac {\sqrt a_n} n \leq (\sum a_n)^{1/2} (\sum \frac 1 {n^{2}})^{1/2} <\infty$ by Cauchy Schwarz inequlaity.


text:
Q: copying from one excel to other using VBA I need to copy information from one excel file to other using VBA. Code makes new workbook in certain destination (*C:\Users\eliza_000\Desktop\aaa*) for whole sheet (inv) but I need only range A1:E32 in the new workbook.
Here is the code what I use to copy all sheet
Sub SaveInvWithNewName()

Dim NewFN As Variant
'Copy Invoice to a new workbook
ActiveSheet.Copy
NewFN = "C:\Users\eliza_000\Desktop\aaa\inv" & Range("E6").Value & ".xlsx"
ActiveWorkbook.SaveAs NewFN, FileFormat:=xlOpenXMLWorkbook
ActiveWorkbook.Close

End Sub

A: Something like:
Dim WB As Workbook
Dim WB2 As Workbook
Dim NewFN As String

Set WB = ThisWorkbook
Set WB2 = Workbooks.Add(1)

WB.ActiveSheet.Range("A1:E32").Copy WB2.Sheets(1).Range("a1")

NewFN = "C:\Users\eliza_000\Desktop\aaa\inv" & Range("E6").Value & ".xlsx"
NewFN = "C:\temp\stuff.xlsx"
WB2.SaveAs NewFN, FileFormat:=xlOpenXMLWorkbook
WB2.Close

A: Consider:
Sub dural()
    ActiveSheet.Copy
    Rows("33:1048576").Delete
    Columns("F:xfd").Delete
End Sub

Adjust if you are using a version of Excel pre-2007.


text:
Q: Higher order function using Boolean as argument I have been reading a book on JavaScript namely Eloquent JavaScript and I have come across the following function. I could not understand how it actually works?
function noisy(f) {

  return function(arg) {
    console.log("calling with", arg);
    var val = f(arg);
    console.log("called with", arg, "- got", val);
    return val;
  };
}
noisy(Boolean)(0);
// → calling with 0
// → called with 0 - got false

What kind of Argument is Boolean and what does passing two arguments one after another does it JavaScript. I would be thankful if anyone could explain how this is working? Thanks in advance.

A: To address what I think your questions are:

*

*Boolean is a function — it's the standard constructor for the object wrapper type for boolean primitives;

*noisy() is a function that takes a function as its argument and returns another function;

*... therefore calling noisy(Boolean) results in a function, so that function can be called with another parenthesized argument list.

So
noisy(Boolean)(0)

calls the noisy() function and then calls the returned function. The returned function logs messages (which I guess is why it's called "noisy") and shows what the originally-passed function (Boolean) does.

A: Boolean is a built-in function/constructor, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean.
f(x)(y) means: Call f, passing x as an argument. Then take the returned value (which must be another function), and call that, passing y as an argument. It works like var tmp = f(x); tmp(y);.
noisy(Boolean) returns
function(arg) {
    console.log("calling with", arg);
    var val = f(arg);
    console.log("called with", arg, "- got", val);
    return val;
};

where f is bound to Boolean.
Then calling that function with 0 executes
console.log("calling with", arg);
var val = f(arg);
console.log("called with", arg, "- got", val);
return val;

where f = Boolean and arg = 0, i.e.
console.log("calling with", 0);
var val = Boolean(0);
console.log("called with", 0, "- got", val);
return val;

A: Boolean is a javascript primitive type constructor
noisy(Boolean) would return the following function
function(arg) {
    console.log("calling with", arg);
    var val = Boolean(arg); // <- see the Boolean here
    console.log("called with", arg, "- got", val);
    return val;
}

so noisy(Boolean)(0); would execute the above function passing 0 as the argument 9arg)


text:
Q: Accessing current IPrinciple in a Master View in Asp.Net MVC I currently have a abstract controller class that I all my controllers inherit from.
I want to be able to use the current user (IPrinciple) object in my master page.
I read that I could use the contructor of my abstract base controller class, that is I could do something like
public BaseController()
    {
        ViewData["UserName"] = this.User.Identity.Name;
    }

I could then access ViewData["UserName"] etc from my master page.
My problem is that this.User is null at this point.
Does anybody know of a different approach?
Thanks in advance.

A: You could write an ActionFilter and in the OnActionExecuted event put the user inside ViewData:
public class UserActionFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        base.OnActionExecuted(filterContext);
        filterContext.Controller.ViewData["UserName"] = filterContext.HttpContext.User.Identity.Name;
    }
}

And then decorate your base controller with this attribute:
[UserActionFilter]
public abstract class BaseController: Controller
{ }


text:
Q: How to format date in single quoted string "yyyy-mm-dd" in python? How to format date in single quoted string "yyyy-mm-dd" in python that matches the following regex?
r'max_p_range_day\s*=\s*\'\d*[-,]?\d*[-,]?\d*\''

The code:
pmax=df5.iloc[:,-5]  # maximum pressure
pmin=df5.iloc[:,-4]   # minimum pressure

df5['PressureDiff']=pmax-pmin
pm=df5["PressureDiff"].max()
df5=df5.loc[df5.PressureDiff==pm]
df5=pd.to_datetime(df5['Day']).dt.date

from datetime import datetime
max_p_range_day = ## format as yyyy-mm-dd enclosed in single quotes
t=open("handson_date.txt",'w')
t.write("max_p_range_day = %s" % max_p_range_day)

For testing the file where I wrote my answer, code is as follows:
x=open("handson_date.txt",'r')
out=x.read()
res=re.findall(r'max_p_range_day\s*=\s*\'\d*[-,]?\d*[-,]?\d*\'', out)[0].replace(' ', '').replace("'", "")

How to format the date to match the following regex?

A: To format datetime you have strftime()
For today date
 datetime.datetime.now().strftime("'%Y-%m-%d'")

Result (and ' ' is part of result)
'2021-01-08'

You can even use it with other text
datetime.datetime.now().strftime("max_p_range_day = '%Y-%m-%d'")

Result
max_p_range_day = '2021-01-08'

And the same you can do even in DataFrame
import datetime
import pandas as pd

one_day = datetime.timedelta(days=1)
today = datetime.datetime.today()

df = pd.DataFrame({'date': [today, today-one_day, today+one_day]})
print(df)

result = df['date'].dt.strftime("max_p_range_day = '%Y-%m-%d'")
print(result)

Result
                        date
0 2021-01-08 10:12:51.295168
1 2021-01-07 10:12:51.295168
2 2021-01-09 10:12:51.295168

0    max_p_range_day = '2021-01-08'
1    max_p_range_day = '2021-01-07'
2    max_p_range_day = '2021-01-09'
Name: date, dtype: object

EDIT:
You have to add ' ' around %s in "max_p_range_day = '%s'"
from datetime import datetime
import re

max_p_range_day = datetime.today().strftime("%Y-%m-%d")   # <-- without `' '`
print('data:', max_p_range_day)

t = open('handson_date.txt', 'w')
t.write("max_p_range_day = '%s'" % max_p_range_day)  # <-- add `' '`
t.close()   # need it to correctly save all data

# ---------------------

x = open('handson_date.txt')
out = x.read()

print('out:', out)

res = re.findall(r'max_p_range_day\s*=\s*\'\d*[-,]?\d*[-,]?\d*\'', out)

if res:
    res = res[0].replace(' ', '').replace("'", "")
    print('found:', res)
else:
    print('?')

Or you have to use ' ' in strftime("'%Y-%m-%d'")
from datetime import datetime
import re

max_p_range_day = datetime.today().strftime("'%Y-%m-%d'")  # <-- add `' '`

print('data:', max_p_range_day)

t = open('handson_date.txt', 'w')
t.write("max_p_range_day = %s" % max_p_range_day)  # <-- without `' '`
t.close()   # need it to correctly save all data

# ---------------------

x = open('handson_date.txt')
out = x.read()

print('out:', out)

res = re.findall(r'max_p_range_day\s*=\s*\'\d*[-,]?\d*[-,]?\d*\'', out)

if res:
    res = res[0].replace(' ', '').replace("'", "")
    print('found:', res)
else:
    print('?')


text:
Q: html flex components not combining in a flex: 1 0 auto layout I have built a landing page with the below HTML.
I have also carefully constructed a bootply, showing exactly how the pink div expands too far, and does not cover the screen as intended.

https://www.bootply.com/bYlAS71OWw

I have a pink region that should resize to take up the available space filling the browser, but not creating a scrollbar.
It appears that the breadcrumb, and the heading are not being subtracted from the overall area used.

*

*heading is in a col, and is flex,

*.breadcrumb is flex.

The page creates scroller for the combined height of the the heading and breadcrumb.
<app-dashboard>

          Home

          Property Locations

        <router-outlet></router-outlet>
        <ng-component class="d-flex flex-grow w-100">

               HEADING

              THIS SHOULD GROW, BUT NOT CREATE A SCROLLBAR

        </ng-component>

      Pander.

</app-dashboard>

The CSS for flex-grow is:
.flex-grow {
  flex: 1 0 auto;
}

A: Please simplify the example (remove custom tags for example). I get only roughly what you are trying to achieve, but a few things first:

*

*What grows and shrinks is flex item, not flex container. And an element only becomes a flex item when its immediate parent is a flex container. Your div with bg-pink-300 is not a flex item because its immediate parent is just a row

*It appears that you want to use flexbox to make your div automatically fill the available vertical space. But all your flex containers are horizontal containers, hence vertically you are really just relying on the percentage height.

Generally, your main container should be a vertical flexbox that defines the total vertical space which should not overflow. Your breadcrumb, header, and the pink div all go into this container as flex items. Breadcrumb and header do not need to grow or shrink, they should have flex: none. The pink div can be defined to have flex: 1 1 0 so that it grows and shrinks to obsorb whatever space within the main container after breadcrumb and header have taken their cut.


text:
Q: How to save data from notification received when the app is in the background I want to know how to save the information received from data payload of firebase cloud messaging.
What actually I want is, I am receiving the fields called notification_type and other stuff from data payload and I want to save it somewhere when the application is in the background and retrieve it when ever I open my application and update my UI based on that.
Till now I have tried saving it on Sharedprefrences, external file, and lastly on local db, all these worked fine and saved the data when the app was in the foreground, but they did not work when the app was in the background.
Below is the code that I tried recently, to save the data in the local db, works fine when the app is in the foreground, but does not work when the app is in the background.
FireBaseMsgService.class
public class FireBaseMsgService extends FirebaseMessagingService {
     @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
       // for normal notifications
        super.onMessageReceived(remoteMessage);
        if(remoteMessage.getData().get("Notification_type").equals("2")){
            String Org_Id=remoteMessage.getData().get("Org_Id");
            String Unit_Id=remoteMessage.getData().get("Unit_Id");
            String User_Id=remoteMessage.getData().get("User_Id");
            String PatientId=remoteMessage.getData().get("PatientId");
            String Notification_type=remoteMessage.getData().get("Notification_type");
            if (remoteMessage.getNotification() != null){
                String Click_Action=remoteMessage.getNotification().getClickAction();
                User_Id=remoteMessage.getNotification().getTag();
                saveNotificationDataToDb(getApplicationContext(),Notification_type);
                FirebaseNotificationService firebaseNotificationService=new FirebaseNotificationService(
                        getApplicationContext(),
                        remoteMessage.getNotification().getTitle(),
                        remoteMessage.getNotification().getBody(),
                        Click_Action,
                        User_Id,
                        Org_Id,
                        Unit_Id,
                        PatientId,
                        Notification_type);
                firebaseNotificationService.createNotification(remoteMessage.getNotification().getTitle(),
                        remoteMessage.getNotification().getBody(),
                        User_Id);
                BusProvider.postOnMain(BusProvider.getInstance(),new NotifyingEvent(Notification_type));

                //sendNotificationToFilesystem(Notification_type);

            }
        }
        //for normal notifications
        else{
            if (remoteMessage.getNotification() != null){
                String User_Id=remoteMessage.getNotification().getTag();
                FirebaseNotificationService firebaseNotificationService=new FirebaseNotificationService(
                        getApplicationContext(),
                        remoteMessage.getNotification().getTitle(),
                        remoteMessage.getNotification().getBody(),
                        User_Id);
                firebaseNotificationService.createNotification(remoteMessage.getNotification().getTitle(),
                        remoteMessage.getNotification().getBody(),
                        User_Id);
            }
        }
    }

    private void saveNotificationDataToDb(Context context , String notification_type) {
        RecievedNotificationDbtable recievedNotificationDbtable=new RecievedNotificationDbtable(context);
        recievedNotificationDbtable.open();
        recievedNotificationDbtable.insertEntry(notification_type);
        recievedNotificationDbtable.close();
    }
}

A: I was going wrong at the basics of firebase docs, as in the docs its clearly said that if the notification payload is there then that notification will be handled by firebase sdk and not the onMessageReceived method , so i changed the from sending both data payload and notification payload to just data payload and after that , when ever i get a notification of data payload the onMessageReceived is called and i can insert the data payload to my local db. so i changed my code to something like this
FirebaseMsgService.class
 @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
    if(remoteMessage.getData().get("Notification_type").equals("2")){
            String Org_Id=remoteMessage.getData().get("Org_Id");
            String Unit_Id=remoteMessage.getData().get("Unit_Id");
            String User_Id=remoteMessage.getData().get("User_Id");
            String PatientId=remoteMessage.getData().get("PatientId");
            String Notification_type=remoteMessage.getData().get("Notification_type");
            String Click_Action=remoteMessage.getData().get("click_action");
            String title=remoteMessage.getData().get("title");
            String body=remoteMessage.getData().get("body");
            FirebaseNotificationService firebaseNotificationService=new FirebaseNotificationService(
                        getApplicationContext(),
                        title,
                        body,
                    Click_Action,
                        User_Id,
                        Org_Id,
                        Unit_Id,
                        PatientId,
                        Notification_type);
                firebaseNotificationService.createNotification(title,
                        body,
                        User_Id);
            saveNotificationDataToDb(getApplicationContext(),Notification_type);
            BusProvider.postOnMain(BusProvider.getInstance(),new NotifyingEvent(Notification_type));

        }
}

and saved to db using this method
private void saveNotificationDataToDb(Context context , String notification_type) {
        RecievedNotificationDbtable recievedNotificationDbtable=new RecievedNotificationDbtable(context);
        recievedNotificationDbtable.open();
        recievedNotificationDbtable.insertEntry(notification_type);
        recievedNotificationDbtable.close();
    }


text:
Q: Excel: Search within Hyperlink Address I have a spreadsheet that has hundreds of links to other files and folders on a network share.  The share was recently re-organized and I need to update my links.
I was hoping to do a 'find and replace', but the search in excel does not seem to find text that occurs with the hyperlink text.  So, when I search for say \\servername\, no results are returned, although this does appear in the hyperlink address:

I tried all possible settings for the 'Look in:' (formulas, values, comments)
Is there a way to Find and Replace part of the Address in a hyperlink?
Note: I'm not using the hyperlink() function. I've simply entered text into a cell and used Ctrl+k to assign the link.

A: I don't think there's an in-excel solution for this.  The availability of 3rd party solutions such as Office Add-ins Advanced Find & Replace  seem to confirm this.
However, there is a trick which has worked for me before.

*

*Save the file as XML Spreadsheet 2003 (*.xml).

*Open the file in (say) Notepad++

*Perform your find & replace within Notepad++

*Save the file

*Open it again in Excel.

If you haven't made any other changes, it should open correctly in excel complete with any changes you made from Notepad++

A:     Dim hLink As Hyperlink

      For Each hLink In ActiveSheet.Hyperlinks
            hLink.Address = Replace(hLink.Address, "\\servername\", _
                    "\\NEW servername\")

      Next hLink
    MsgBox "done - hyperlink addresses corrected"


text:
Q: Check value prior to form submit in POST controller Sorry if the subject is inaccurate, but basically upon submit of a Form I want to compare the previous value of the model's Foreign Key.
My model is:
public class Booking
{
    public int ID { get; set; }

    [ForeignKey("Store")]
    public int StoreID { get; set; }
    public virtual Store Store { get; set; }

    public string BookedBy { get; set; }
    public DateTime? DateBooked { get; set; }
    public string Description { get; set; }
    public DateTime FromDate { get; set; }
    public DateTime ToDate { get; set; }

    public string Status { get; set; }
}

After editing a booking in Edit view and submitting, I want to check if the StoreID has been modified, so that I can perform a required action.
I was creating an instance of Booking as oldBooking and then comparing StoreID with booking.StoreID passed back from View, but this created an Attach error when I saved the Edited form.
Any suggestions?
Edited 27/1/15:
public ActionResult Edit([Bind(Include = "ID,StoreID,BookedBy,DateBooked,Agreement,Description,FromDate,ToDate")] Booking booking, string returnURL)
{
  if (ModelState.IsValid)
  {
    Booking oldBooking = db.Bookings.Find(booking.ID);
    int prevStoreID = oldBooking.StoreID;
    db.Entry(booking).State = EntityState.Modified;
    db.SaveChanges();
    if(prevStoreID == booking.StoreID)
    {
      sendStoreChangeEmail(prevStoreID, booking.StoreID);
    }
    return RedirectToAction("Index", "Home", null);
  }
  ViewBag.StoreID = new SelectList(db.Stores, "ID", "ID", booking.StoreID);
  return View(booking);
}

When attempt to update db entry state I get this error:

"Attaching an entity of type 'uatlab2.Models.Booking' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate."

A: After reading a couple of other posts and googling 'detach', i read this article:
ASP MVC How to update DB entry with collections field
and after I have got prevStoreID do this:
((IObjectContextAdapter)db).ObjectContext.Detach(oldBooking);
And it works.
Thanks for your help and inspiration.
C


text:
Q: How to use blocking.cv When i try to run the following code
rdesc <- makeResampleDesc("CV", blocking.cv = TRUE,iters=5L,folds=10)

i take this error
Error in makeResampleDescCV(blocking.cv = TRUE, iters = 5L, folds = 10) :
  unused arguments (blocking.cv = TRUE, folds = 10)

A: blocking.cv is a new argument that isn't in the latest released version of mlr yet. You'll need to use the development version from github to use it. See the tutorial for instructions.
Further, iters and folds describe the same thing here, so only specify one of them.


text:
Q: WordPress hook to call a function in dashboard other than admin Is there any WordPress hook that can be called on dashboard other than admin.
i have this hook
add_action('admin_head','upgrade_notification_free_user');
it works fine for the admin account but when i login from another account it do not fires.
Any suggestions?

A: According to the WordPress Code Reference the 'admin_head' action should fire in the head section of all admin pages.
Alternatively you could try 'admin_init' or 'in_admin_footer' depending on what your function is trying to accomplish.
Try installing the Query Monitor plugin it will show you all hooks that are fired when a page is loaded. Make sure to use a special authentication cookie - see here for details - so non-administrators will also see Query Monitor's output.


text:
Q: ASP .NET Repeater Control containing LinkButton I am displaying a list of accounts objects in a repeater. Each object contains three fields namely studentID, studentName and studentAge. I have wrapped it with a link button. As a result the each individual item which is displayed is clickable. I have also added a click handler to the link button. The problem is that how am I supposed to know which student was clicked? Because originally I want to navigate to the next page and display that particular student's details. Once I know which student is clicked then I can store his details in a session object and then navigate to the new page and get it back.
Thanks for your help.

A: In your case, it would be better to use a normal hyperlink, pass the ID as query string, and have the new page get the details.
<asp:HyperLink runat="server"
               NavigateUrl='<%# Eval("studentID", "StudentDetails.aspx?id={0}") %>'
               Text="Details" />

Update:
To get the studentID on the same page, use the ItemCommand event instead and have the LinkButton as follows:
<asp:LinkButton runat="server"
                CommandName="StudentDetails"
                CommandArgument='<%# Eval("studentID") %>' />

The studentID will be stored into the CommandArgument property, which value will be passed to the ItemCommand event handler.

A: <asp:HyperLink ID="HyperLink1" runat="server"
               NavigateUrl='<%# DataBinder.Eval(Container.DataItem,"studentID", "StudentDetails.aspx?Id={0}") %>'
               Text="Details" />


text:
Q: Rotate center of image using pygame So I'm not sure if I'm doing it right but I want to rotate a circular image around its center...this is my attempt so far. When I try to run this it just opens a black pygame screen that closes off immediately and doesn't tell me what the problem is
from __future__ import division
import math
import sys
import pygame

class MyGame(object):
    def __init__(self):
        # """Initialize a new game"""
        pygame.mixer.init()
        pygame.mixer.pre_init(44100, -16, 2, 2048)
        pygame.init()

        # set up a 640 x 480 window
        self.width = 800
        self.height = 600
        self.screen = pygame.display.set_mode((self.width, self.height))

        # load image
        self.img = pygame.image.load("basketball.png")

        # use a white background
        self.bg_color = 255, 255, 255

        # Setup a timer to refresh the display FPS times per second
        self.FPS = 30
        self.REFRESH = pygame.USEREVENT+1
        pygame.time.set_timer(self.REFRESH, 1000//self.FPS)

    def run(self):
        #"""Loop forever processing events"""
        running = True

    def rot_center(image, rect, angle):
        # Rotate function
        rot_image = pygame.transform.rotate(image, angle)
        rot_rect = rot_image.get_rect(center=rect.center)
        return rot_image, rot_rect

        rect = self.img.get_rect()
        self.img2 = rot_center(self.img, rect, 90)

        while running:
            event = pygame.event.wait()

            # player is asking to quit
            if event.type == pygame.QUIT:
                running = False
            # time to draw a new frame
            elif event.type == self.REFRESH:
                self.draw()
            else:
                pass # an event type we don't handle

    def draw(self):
        # Update the display
        # everything we draw now is to a buffer that is not displayed
        self.screen.fill(self.bg_color)

        rect = self.img.get_rect()
        rect = rect.move(self.width//2-rect.width//2, self.height//2-rect.height//2)

        self.screen.blit(self.img2)

        # flip buffers so that everything we have drawn gets displayed
        pygame.display.flip()

MyGame().run()
pygame.quit()
sys.exit()

A: *

*You never call rot_center

*You want the while running: loop outside of rot_center (perhaps in run) and call rot_center in the loop

Specifically, put the while running loop in run, since that's what you want it to do, run the loop. Then in the second elif, call rot _ center before you refresh the frame. And take out the recursive call to rot_center, otherwise you'll never get out of the recursive calls

A: So, init is called, then run() is called, then pygame is closed, then the program exits. You need to end up in an event loop.


text:
Q: getting unknown column error even when the column is present in mysql table select tab1.*(
        select a.*
        from fw_invi a left join fw_resp b on a.id=b.did,
             fw_resp fra left join(
                           select *
                           from fw_type
                          ) tab4 on fra.qaild=tab4.qdetailid //this causing error

      )tab1 left join jos_users u on tab1.consu=u.id order by tab1.createdon desc

On running the above query in mysql i am getting the following error,which should not be the case as the specified missing column is present in that table.i think i am doing the wrong nested table aliasing.
Unknown column 'tab4.qdetailid' in 'on clause'

1.Why i am getting the error even though the column is present.?
2.Is my above query syntax correct?
Thanks in advance.

A: * can't  be used with  aliases. Aliases are used for named  columns.


text:
Q: GameplayKit: Fine tune control of GKAgent I'm testing out gameplaykit using spritekit.  I've added a GKAgent to my GKEntity and I am making my Entity seek my touches by creating an endAgent at touch position.
This works great.  The agent moves naturally and chases my touches.  However, I have two questions..
How can I stop the agent when it reaches its destination.  The agent will circle around forever trying to exactly land on the point.   I've tried agent.behavior.removeAllGoals()  I'd figure that would stop the agent right away since it has no goals.. but nothing happens.
Second question is how can I fine tune movement.  An agent would be ideal for something like a missile chasing an airplane.  The problem is that it decelerates when reaching its target.  The movement pattern is so specific.  I've tried playing with the properties mass, maxSpeed maxAcceleration etc..  Anything I'm missing?

A: The API describes agents in terms of their motivation, but in some ways they act more like physics bodies — that is, they follow Newton's First Law and stay in motion unless "motivated" to change their speed or direction.
To stop an agent when it reaches its destination, you need to make stopping be its primary goal. Check per-frame what your distance to the target is, and when you get "close enough" (whatever counts as that for your gameplay), take out the seek goal and replace it with a target-speed goal whose speed is zero.
For the "heat-seeking missile" behavior, you might try using an intercept-agent goal instead of a seek-agent goal and varying the prediction time to see how that affects the pursuit speed. (And you probably don't need the missile to remain in the scene once it gets close enough to the airplane, so if you can limit the slowdown to "within explosion distance" you can ignore it.)


text:
Q: Why my date element is displayed with this format : datetime.date(2018, 6, 30) in MySQL (in terminal)? I use python to insert a date into MySQL. Before I insert the date I changed the date format to:
start_datetime_object = datetime.datetime.strptime(str(stDate), '%Y-%m-%d')
end_datetime_object = datetime.datetime.strptime(str(enDate), '%Y-%m-%d')

d_stDate= start_datetime_object.strftime('%Y-%m-%d')

d_enDate= end_datetime_object.strftime('%Y-%m-%d')

When I use logging.debug("DATES---->" + d_enDate +'-- '+ d_stDate)
I get the result as I should in a %Y-%m-%d format.
At the moment I'm stuck with datetime.date(2018, 6, 30)
Edit:
My query is:
cursor1.execute("INSERT INTO "+MYSQL_DB+".events ( `name`, `type`, `startDate`,`endDate`, `location` ) VALUES (%s,%s,%s,%s,%s)",[ str(name), str(types), str(d_stDate),str(d_enDate),str(location)])


text:
Q: Convert dateFromString to another format - SWIFT Sorry if this has been asked before.
I have a date from MySQL populating a tableview in Swift. I am converting the MySQL date to NSDate
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateString = "\(dateLabelSource)"
if let dateAdded = dateFormatter.dateFromString(dateString)
{
    self.dateLabel.text = "\(dateAdded)"
}

This produces the correct date but now I need to change the output to read more like:
Monday 7 September 2015

but can't work out how to do this.
Any help is appreciated.

A: This should produce the output you want. Note: NSDateFormatters are expensive objects to create, so it is best to reuse a single instance as much as you can.
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateString = "\(dateLabelSource)"
if let dateAdded = dateFormatter.dateFromString(dateString)
{
    dateFormatter.dateFormat = "EEEE d MMMM yyyy"
    self.dateLabel.text = "\(dateFormatter.stringFromDate(dateAdded))"
}

The Data Formatting Guide has a section dealing with formatting dates. Data Formatting Guide

A: This will Help
var formatter: NSDateFormatter = NSDateFormatter()
formatter.dateFormat = "EEEE d MMMM yyyy"
let stringDate: String = formatter.stringFromDate(NSDate())
println(stringDate)

A: Use this code to format date:
let dateFmt: NSDateFormatter = NSDateFormatter()
dateFmt.dateFormat = "EEEE d MMMM yyyy"
dateFmt.locale = NSLocale(localeIdentifier: "en_US") // If you consider to not localise date
println(dateFmt.stringFromDate(dateAdded))


text:
Q: uimaFIT creating type system When creating types, what are the benefit of having different type descriptors for each type rather than use a one type descriptor.

A: Your reason might be purely cosmetic. For example, you could want to group types into different files depending on their use. E.g. you might want to keep type related to document structure in one file while you put put types related to semantic relations into another file. When you write a program, you also usually don't put all code into one file.
There could also be a technical reason. E.g in DKPro Core, the jcasgen-maven-plugin is used to automatically generate JCas classes for some type system files. These JCas classes are not checked in to the version control system. However, specific type system files are excluded from this automatic generation and the respective JCas classes are actually checked in to the version control system because they contain custom modifications - i.e. extra manually implemented methods.
Disclosure: I am a working on both, uimaFIT and DKPro Core.


text:
Q: PowerShell replace text in string after certain expression I am trying to replace everything in a string after a certain expression is found: In this case ",=dc".
Im kinda new to PowerShell so would appreciate any help. My code only replaces any ",=dc" but not what is behind that
$array += @()
$array += "vu=doc,vu=noc,dc=zet,dc=zez"
$array += "vu=doc,vu=nud,dc=gut,dc=zrt"
$array += "vu=doc,vu=nud,vu=dit,dc=gut,dc=zrt,dc=opt"

foreach ($value in $array){
$arraytype -replace "(?<=(,=dc)).*"
}

I want to only get back the "vu=doc,vu=noc"-part. Everything after the first ",=dc" should be deleted.

A: You can use IndexOf method to find the position of the string and use Substring method to slice the string up to that position.
$array = @()
$array += "vu=doc,vu=noc,dc=zet,dc=zez"
$array += "vu=doc,vu=nud,dc=gut,dc=zrt"
$array += "vu=doc,vu=nud,vu=dit,dc=gut,dc=zrt,dc=opt"

foreach ($value in $array){
    $index = $value.IndexOf(",dc=")
    if($index -eq -1) {
        Write-Output $value
    } else {
        Write-Output $value.Substring(0, $index)
    }
}

Note: I think you have a typo in the first line($array = @())

A: It's easier to use an indexed loop if you want the values in the array updated. Also, You can define an array simply by using a comma between the elements. Avoid concatenating with += as this means every time the entire array needs to be recreated in memory, which is both time and memory consuming.
Try
$array = "vu=doc,vu=noc,dc=zet,dc=zez",
         "vu=doc,vu=nud,dc=gut,dc=zrt",
         "vu=doc,vu=nud,vu=dit,dc=gut,dc=zrt,dc=opt"

for ($i = 0; $i -lt $array.Count; $i++) {
    $array[$i] = ($array[$i] -replace 'dc=[^,]+,?').TrimEnd(",")
}

$array

Result:
vu=doc,vu=noc
vu=doc,vu=nud
vu=doc,vu=nud,vu=dit

Regex details:
dc=       Match the character string "dc=" literally (case insensitive)
[^,]      Match any character that is NOT a ","
   +      Between one and unlimited times, as many times as possible, giving back as needed (greedy)
,         Match the character "," literally
   ?      Between zero and one times, as many times as possible, giving back as needed (greedy)


text:
Q: Why select field not displaying? I'm trying to add select field by both ways first is dynamically and giving values to select fields.
while trying with dynamically so it is working well. but when trying to display some select field by
giving value to '1st room child' select field so first time im receiving the output but second time its
doesn't worked

$(function () {
 /*here my values to increment whenever added newly form */
 var i = 1;
 i++;
 var max_fields = 6;
 var this_button_work_for_click_to_add_rooms = $(".this_button_work_for_click_to_add_rooms");
 var this_is_field_wrapper = $(".this_is_field_wrapper");

 //here we starting counting...
 var input_count = 1;
 //add buttong dynamically over here...
 $(this_button_work_for_click_to_add_rooms).click(function (event) {
  /* Act on the event */
  if (input_count < max_fields) {
   input_count++;
   var add_fields = '

Options -

Adults(12+)
<select id="selected_adults[]" name="selected_adults[]" class="form-control"><option   value="1">1</option><option selected="selected" value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option></select>

' + input_count + ' Room

Child(0-12)
<select id="selected_childs[]" name="selected_childs[]" onchange="displayingNumberOfChildAge(this);" class="form-control"><option>select</option><option id="first_child_col"  value="1">1</option><option id="second_child_col"  value="2">2</option></select>

remove

';
   $(this_is_field_wrapper).append(add_fields);
  }
 });
 $(this_is_field_wrapper).on('click', '.remove_input_button', function (e) {
  e.preventDefault();
  $(this).parent('div').remove();
  input_count--;
 });
});
function addFields() {
 var number = document.getElementById("selected_childs[]").value;
 var childage = document.getElementById("childage0");

 //Create array of options to be added
 var array = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"];

 while (childage.hasChildNodes()) {
  childage.removeChild(childage.lastChild);
 }
 if (number == 1) {
  // statement
  for (i = 0; i < number; i++) {
   var h = document.createElement("h6");
   h.setAttribute("id", "firstever");
   var h1 = document.createElement("h6");
   h1.appendChild(document.createTextNode("select child age"));
   childage.appendChild(h1);

   h.appendChild(document.createTextNode("Children Age " + (i + 1)));
   childage.appendChild(h);

   var selectList = document.createElement("select");
   selectList.setAttribute("id", "mySelect");
   selectList.setAttribute("class", "form-control");
   childage.appendChild(selectList);
   childage.appendChild(document.createElement("br"));

   //Create and append the options
   for (var j = 0; j < array.length; j++) {
    var option = document.createElement("option");
    option.setAttribute("value", array[j]);
    option.text = array[j];
    selectList.appendChild(option);
   }
  }
 } else {
  // statement
  for (i = 0; i < number; i++) {
   childage = document.getElementById("childage" + i);
   var h1 = document.createElement("h6");
   h1.setAttribute("id", "secondever");
   h1.appendChild(document.createTextNode("select child age"));
   childage.appendChild(h1);
   var h = document.createElement("h6");
   h.appendChild(document.createTextNode("Children Age " + (i + 1)));
   childage.appendChild(h);

   var selectList = document.createElement("select");
   selectList.setAttribute("id", "mySelect");
   selectList.setAttribute("class", "form-control");
   childage.appendChild(selectList);
   childage.appendChild(document.createElement("br"));

   //Create and append the options
   for (var j = 0; j < array.length; j++) {
    var option = document.createElement("option");
    option.setAttribute("value", array[j]);
    option.text = array[j];
    selectList.appendChild(option);
   }
  }

 }
}
<!DOCTYPE html>

      <title>Welcome|Home</title>

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

      <form method="POST" action="<?php echo base_url(); ?>index.php/dynamically_added_controller/Dynamically/addingValues">

Options -

Adults(12+)

                     <select id="selected_adults[]" name="selected_adults[]" class="form-control">
                        <option   value="1">1</option>
                        <option selected="selected" value="2">2</option>
                        <option value="3">3</option>
                        <option value="4">4</option>
                        <option value="5">5</option>
                     </select>

1st Room

Child(0-12)

                     <select id="selected_childs[]" name="selected_childs[]" value="" onchange="addFields()" class="form-control">
                        <option>--select--</option>
                        <option value="1">1</option>
                        <option value="2">2</option>
                     </select>

                     Click & Add Rooms

         <button type="submit" value="submit">click to submit</button>
      </form>

As you have seen the problem is while attempting second time to display select field by giving value to '1st room child' select field so it is not working.

A: Your problem is something called "delegation." When you dynamically add something to the DOM that wasn't there when it was first loaded, you have to look through a pre-existing parent first.
Consider this. You have an existing element:

Then, you dynamically add something in that div: <button type="button" id="someButton">
In order to get to listen for that click, you have to go through the parent div since it's an original part of the DOM.
$('#loaded').on('click', '#someButton', function () {
   //do something
});


text:
Q: Macro call vs macro definition environment in Julia I am trying to make sense out of a statement in the Julia's Metaprogramming documentation on macro hygiene. The documentation claims that

Julia's macro expander solves these problems in the following way. First, variables within a macro result are classified as either local or global. A variable is considered local if it is assigned to (and not declared global), declared local, or used as a function argument name. Otherwise, it is considered global. Local variables are then renamed to be unique (using the gensym() function, which generates new symbols), and global variables are resolved within the macro definition environment. Therefore both of the above concerns are handled; the macro's locals will not conflict with any user variables, and time and println will refer to the standard library definitions.

I wrote a small program to see whether global variables were indeed resolved in the macro definition environment. I wrote the following:
f(x) = x + 100

macro g()         # According to Julia docs, ...
  :(f(x) + 5)     # ... f is global, x is local, right?
end               # if so, f should refer to the f above?

(function main()
  local x = 3
  f(x) = x - 100  # f in the call environment subtracts 100
  println(@g())   # So why does this do -92?
end)()

If I am to understand the Julia docs correctly, part of macro hygiene is to make sure whichever functions are called in the macro's returned expression don't get hijacked by functions of the same name inside the caller's environment. But this is exactly what happens here, the function f that was used was the one that was defined locally.
I would have thought I would have to use esc in order to use the f in scope at the point of call. But this is not so, why?
And in addition, I noticed that the the variable x inside the macro result is considered local, so a new gensymed variable name should have been generated for it, so as not to clash with the x in the macro call environment. But this did not happen either!
How am I to read the documentation to make any sense out the reason that esc need not be used here?
EDIT (CLARIFICATION)

*

*When I claim f is global and x is local, according to the docs, I do so because I see that x is used as a function argument. I understand x is not being written to nor declared local, and it certainly looks global, but those docs claim function arguments should be global too!

*I know the usual part of hygiene where the gensymming of locals ensures that variables of the same name in the macro caller's context are not inadvertently plastered. However, the docs claim that for functions, the ones that are seen in the macro definition's context are protected from the caller using their own. This is the part that makes no sense to me, because my experiment shows otherwise.

A: This is a bug. It's an old issue of Julia 0.5 and earlier, and has been fixed in Julia 0.6. See https://github.com/JuliaLang/julia/issues/4873 for more information.


text:
Q: convert Map with JSONPath to json string I have a map like following:
"key1": "value1",
"list[0].key1": "listkeyvalue1"
"list[0].key2": "listkeyvalue2"
"list[1].key1": "listkeyvalue1"
"list[1].key2": "listkeyvalue3"

Is there a framework which converts this key-value pairs into an json object/string for me, regarding the [x] instead of just flat? When currently using something like Jackson ObjectMapper I just get the flat output
I know of ways doing it on my own, just searching for a more elegant way
new ObjectMapper().writeValueAsString(map);

leads to JSON String
{
"key1": "value1",
"list[0].key1": "listkeyvalue1"
"list[0].key2": "listkeyvalue2"
"list[1].key1": "listkeyvalue1"
"list[1].key2": "listkeyvalue3"
}

but I want the output to be:
{
    "key1": "value1",
    "list": [
        {
            "key1": "listkeyvalue1",
            "key2": "listkeyvalue2"
        },
        {
            "key1": "listkeyvalue1",
            "key2": "listkeyvalue3"
        }
    ]
}

A: Library Josson function unflatten() with parameter '.[]' as the delimiter characters.
https://github.com/octomix/josson
Josson josson = Josson.fromJsonString(
    "{\"key1\": \"value1\"," +
    "\"list[0].key1\": \"listkeyvalue1\"," +
    "\"list[0].key2\": \"listkeyvalue2\"," +
    "\"list[1].key1\": \"listkeyvalue1\"," +
    "\"list[1].key2\": \"listkeyvalue3\"}");
JsonNode node = josson.getNode("unflatten('.[]')");
System.out.println(node.toPrettyString());

Output
{
  "key1" : "value1",
  "list" : [ {
    "key1" : "listkeyvalue1",
    "key2" : "listkeyvalue2"
  }, {
    "key1" : "listkeyvalue1",
    "key2" : "listkeyvalue3"
  } ]
}

A: Among Jackson's configuration options is pretty-printing: https://github.com/FasterXML/jackson-databind#user-content-10-minute-tutorial-configuration


text:
Q: PayPal REST API (PHP) not completing transaction I'm relatively new to PayPal's REST APIs, so I may be missing a key element here, but what I've done is set up a similar to their example in GitHub:
https://github.com/paypal/rest-api-sdk-php/blob/master/sample/payments/CreatePaymentUsingPayPal.php
I follow this pretty close, in that I set the API context to the Client ID and Secret in the app I created on PayPal's Developer site (first using the sandbox and now the live ones).  Here's the part after I create the apiContext:
            $payer = new Payer();
            $payer->setPayment_method("paypal");

            $item = new Item();
            $item -> setName($itemDescription)
                    -> setCurrency("USD")
                    -> setQuantity(1)
                    -> setPrice($itemPrice);

            $itemList = new ItemList();
            $itemList->setItems(array($item));

            $amount = new Amount();
            $amount->setCurrency("USD")
                    ->setTotal($itemPrice);

            $transaction = new Transaction();
            $transaction->setAmount($amount)
                    ->setItemList($itemList)
                    ->setDescription($itemDescription);

            $redirectURLs = new RedirectUrls();
            $redirectURLs->setReturnUrl($successURL);
            $redirectURLs->setCancelUrl($cancelURL);

            $payment = new Payment();
            $payment->setIntent("sale");
            $payment->setPayer($payer);
            $payment->setRedirectUrls($redirectURLs);
            $payment->setTransactions(array($transaction));

            try {
                    $payment->create($apiContext);
            }
            catch (PayPal\Exception\PPConnectionException $ex) {

                    print "Exception:  " . $ex->getMessage() . PHP_EOL;
                    var_dump($ex->getData());
                    exit(1);
            }

            # get the redirect URL to pass the user on to PayPal for payment processing
            $redirectURL = "";
            foreach ( $payment->getLinks() as $link ) {
                    if ( $link->getRel() == "approval_url" ) {
                            $redirectURL = $link->getHref();
                            break;
                    }
            }

            // if we get a URL, redirect the user to PayPal's website
            if ( $redirectURL != "" ) {

                    $ppPayID = $payment->getId();

                    # write the ID to the DB
                    $dbQuery = "update members set ppPayID = '" . dbAccess("sanitize", $ppPayID) . "' where memberID = $memberID;";

                    # update the DB
                    $dbResults = dbAccess("query", $dbQuery);

                    //header("Location: $redirectURL");
                    print "<script language='JavaScript'>location.href = '$redirectURL';</script>";
                    exit;
            }
            else {
                    return false;
            }

Everything seems to work fine:  I see the item information when passed through to PayPal, I can cancel the transaction and get back to my PHP app via the cancel URL, and I even was able to submit a payment using a live account and get bounced back to my app via the success URL.  Here's what it looks like;
http://example.com/scripts.php?pp=success&memberID=1&token=EC-7G861271R3854####&PayerID=77PAUYJCFJ###
(where the #s are also alphanumeric characters removed just in case)
The problem I have is that though it appears to be successful, the transaction does not show up anywhere on my merchant account, nor does it appear on my personal account.  Any idea what is going on here?

A: So, the example was missing a key portion of the transaction process:  executing the payment.  For anyone else struggling with this, here's the necessary piece of code to make this happen:
https://developer.paypal.com/docs/api/#execute-an-approved-paypal-payment
NOTE:  you need to capture both the $payment->getID, as I did in the database, and send URL PayerID back.

A: There are two parts to that example. The second portion is to receive that URL that comes back on success, and process the request.
As you can see it in https://github.com/paypal/PayPal-PHP-SDK/blob/master/sample/payments/ExecutePayment.php, you need to execute the payment using the ID provided back from the request.
As per your use case, I would go ahead and see if I could merge that page with this, so that it becomes move obvious to the people. If not, I would want to make it very very clear somehow in the sample code, that there is more than that php file in that example.


text:
Q: Redefine standard OData service - SAP Gateway NetWeaver in my project, i'm using Sales_Order_Create Service. In my use case, it is required to change some business logic in the backend: Gateway Netweaver (create deep entity method).
I used the approach of create new Project(child), and then Redefine > OData service(GW). But when i debugg and start my Fiori sales order create app(extended app), i see that it sometimes  still using the standard service methods(Parent) , especially in order creation .
Should i overwrite extended service? but how can i get my standard service again once it's overwritten in case i want to reuse it in other projects ?
If no, is there any solution to modify business logic(redefine methods) in child service?
How to make my Fiori extended application use this child service, (even if i replaced the service with New > Extension > Replace Service).
Thank you.

A: Once you have created an extension application you need to assign the extension application to the testing user. You need to do this by creating a custom business catalog role(new launch pad .. new application .. new catalog .. new role with tile catalog) and assign it to testing user.


text:
Q: Cursors vs. While loop - SQLServer Say I have a bunch of rows in a DB (SQLServer 2008 in this case) that can be used to create equations.
 -----------------------------------------------------
 OperationID | EquationID | Operation | Amount | Order
 -----------------------------------------------------
     1       |     1      |     +     |   12   |  1
     2       |     1      |     +     |   12   |  2
     3       |     2      |     /     |   2    |  3
     4       |     2      |     +     |   12   |  1
     5       |     2      |     -     |   2    |  2
 -----------------------------------------------------

I need come up with a way to evaluate the equations in this table.

Equation 1: 12 + 12 = 24
  Equation 2: (12 - 2)/2 = 5

I cannot think of a way to get these results without iterating through the rows.  The only ways I know how to do this is with a cursor or through the use of a temp table and a while loop.  Are there any better ways to do this? If not generally what will perform better cursors or while loops?
Note: This is somewhat simplified and at this stage in the project we can only conjecture about what the data will look like.  The assumption is that each 'equation' will have around 100 to 1000 operations and that there will be a few thousand 'equations' each day that will need to be processed.

A: It's been demonstrated that a recursive CTE performs better than a loop for coming up with running totals.  This is just a running total with a variable operator really, so the performance benefit should apply here.
The way to create a recursive CTE which behaves like a loop is like so:
        ;WITH cte AS (
        SELECT equation, number, order FROM table WHERE order = 1
        UNION ALL
        SELECT table.equation,
            CASE WHEN table.operation = '+' THEN cte.number + table.number
                 WHEN table.operation = '-' THEN cte.number - table.number END AS number, --etc.
table.order FROM table INNER JOIN cte ON table.order = cte.order + 1 AND table.equation = cte.equation
        )
    SELECT equation, number, order
    FROM cte
    OPTION (MAXRECURSION 1000);

The first SELECT grabs your leftmost number, and the UNION all does the following operations on the number returned by it.  The maxrecursion option limits the number of operations in one equation to 1000.  You can, of course, set this higher.
This answer is somewhat incomplete, because the final select query would return intermediate results.  That's fairly simple to filter though.

A: I've cleaned up/fleshed out mootinator's answer a bit and am presenting that code here. I've marked this answer community wiki because mootinator deserves the credit for the answer. This was just the simplest way to present that code without editing his answer.
declare @equations table (
    OperationID int,
    EquationID int,
    Operation char(1),
    Amount int,
    [Order] int
)

insert into @equations
    (OperationID, EquationID, Operation, Amount, [Order])
    values
    (1, 1, '+', 12, 1),
    (2, 1, '+', 12, 2),
    (3, 2, '/',  2, 3),
    (4, 2, '+', 12, 1),
    (5, 2, '-',  2, 2)

;with cteCalc as (
    select EquationID, Amount, [Order]
        from @equations
        where [Order] = 1
    union all
    select e.equationid,
           case when e.Operation = '+' then c.Amount + e.Amount
                when e.Operation = '-' then c.Amount - e.Amount
                when e.Operation = '*' then c.Amount * e.Amount
                when e.Operation = '/' then c.Amount / e.Amount
           end AS Amount,
           e.[Order]
        from @equations e
            inner join cteCalc c
                on e.EquationID= c.EquationID
        where e.[Order] = c.[Order] + 1
),
cteMaxOrder as (
    select EquationID, MAX([Order]) as MaxOrder
        from cteCalc
        group by EquationID
)
select c.EquationID, c.Amount
    from cteMaxOrder mo
        inner join cteCalc c
            on mo.EquationID = c.EquationID
                and mo.MaxOrder = c.[Order]
    order by c.EquationID
    option (maxrecursion 1000)


text:
Q: Creating a List , document library, content type as Features using VS , VERSUS using CA to create these In the past I have used the Central administrator to add lists, document libraries, apps, site collection, etc. and I did not use the visual Studio to create any of these items.
But now as I gained more experience on SharePoint , so I need to know if I should start using Visual Studio to develop things such as list, announcement lists, document libraries instead of using central administrator UI.?
Second question currently I move my SharePoint web site from one environment tot another , by backuping a site collection and restore it on the  new environment. But I am thinking of a scenario where a client might ask to modify an already existing site collection. So in this way I need to find a way to develop let say a list and a  content type on one environemnt , then to be able to move these new items to another site collection , without having to restore the whole site collection.

A: John,
In the question you are discussing two different things, one is the SCHEMA i.e. Lists, Content Types, Document Libraries etc., the second thing is CONTENT.
SCHEMA
Yes you can develop everything using Visual Studio, you can create your custom templates (just like Team Site template, Publishing Site Template etc.).. and implement a class that inherits SPWebProvisioningProvider to add your custom lists, content types, activate default features etc.
This great article discusses this approach
SharePoint and Web Templates
CONTENT
About the content, well you can't ask users to stop adding items while you are developing some features.. so what I will suggest is that you develop in a Development/Beta environments, let the users test the new updates.. and once satisfied, move the updates to Production AND ALL OF THIS SHOULD BE DONE FROM VISUAL STUDIO..
We usually have Code Upgrader Feature, that on activation creates new lists, content types, even pages etc. That saves us from restoring sites on Production and worrying about data.


text:
Q: How to migrate AppBundle.php with Symfony4 update With the update of Symfony4, AppBundle/ will be abolished and will be under src/.
I have set the following actions in AppBundle.php, how is the best way to migrate?
Code
AppBundle.php
class AppBundle extends Bundle
{
    /**
     * {@inheritdoc}
     */
    public function boot()
    {
        parent::boot();

        // Make the container accessible from static methods
        Parameters::setContainer($this->container);

         // Don't throw an exception when SwiftMailer uses an RFC-violating address(consecutive dots, @immediately preceding dot)
         // Change the regular expression for address checking.
         // (use reflection to change private variables)
        $swiftMimeGrammar = \Swift_DependencyContainer::getInstance()->lookup('mime.grammar');
        $prop = new \ReflectionProperty('\Swift_Mime_Grammar', '_grammar');
        $prop->setAccessible(true);
        $_grammar = $prop->getValue($swiftMimeGrammar);
        $_grammar['addr-spec'] = '.*';
        $prop->setValue($swiftMimeGrammar, $_grammar);
    }


text:
Q: How can I parse DOM nodes more quickly? I have a chrome extension content script that attempts to match strings from an array of objects with textcontent from html nodes. If there is a match, the extension will replace the the html that contains the match with new html.
I am having problems with the matching. The array that contains the strings is made up of 2367 objects, with each object containing a name property.
I implemented a TreeWalker to narrow down the nodes I am parsing to only those that contain text with words.
Basically, I am trying to find the intersection of nodes that contain string matches. However, every approach I have taken for this problem has results in execution times that take  5 minutes or longer and/or CPU bottlenecking. I am hoping you guys may be able to point out what I am doing wrong or send me in different direction. Thanks in advance!
So far, all my attempts at finding matches have included some implementation of RegEx. replace() seems to be the most taxing, but test() does not provide much improvement.
For looping through the array of nodes and the Array of string objects, I have tried for..of loops, for loops, forEach() with a nested forEach(), and a filter() with a nested some().
Here is a simple version of the content script.
const test = (players) => {
  let body = document.body;
  let bodyCopy = body.cloneNode(true)
  let treeWalker = document.createTreeWalker(
    bodyCopy,
    NodeFilter.SHOW_TEXT,
    node => {

      let regex = /\w+/gi
      if (regex.test(node.textContent)) {
        return NodeFilter.FILTER_ACCEPT;
      } else {
        return NodeFilter.FILTER_SKIP;
      }
    }
  );

  let nodes = [];

  while (treeWalker.nextNode()) {
    nodes.push(treeWalker.currentNode);
  }
  const intersection = (_players, _nodes) => {
    let matchedPlayers = [];
    matchedPlayers = _players.filter(player => {
      return _nodes.some((node) => {
        let re = new RegExp(player.name.full, 'i')
        return re.test(node.textContent)
      })
    })
    console.log (matchedPlayers);
  }
  return intersection(players, nodes)
}

chrome.runtime.onMessage.addListener(
  function (request, sender, sendResponse) {
    if (request.message === "test") {
      console.log(request.players)
      test(request.players)
      sendResponse({ gotIt: "Got it!" })
    }
  }
)

Here is what an object from the request.players array looks like

{
    "name": {
        "full": "Austin Adams",
        "first": "Austin",
        "last": "Adams",
        "ascii_first": "Austin",
        "ascii_last": "Adams",
    },
    "owned": false
}


text:
Q: Is the evaluation strategy of Agda specified anywhere? Given that all Agda programs terminate, the evaluation strategy doesn't matter for denotational semantics but it does matter for performance (in case you ever run your Agda programs).
So, what evaluation strategy does Agda use? Does using codata (♯, ♭) instead of data change evaluation strategy? Is there a way to force call-by-need aka lazy evaluation?

A: Type checking might require evaluation to normal form, so it does matter even if you don't run your programs (but yes, evaluation during type checking could be regarded as running the program). Agda evaluates expressions in normal order, which means that functions are applied before their arguments are evaluated. Data types are also evaluated only on demand.
For example, suppose I have this definition of natural numbers and some operations on them:
data ℕ : Set where
  zero : ℕ
  suc  : ℕ → ℕ

{-# BUILTIN NATURAL ℕ #-}
-- Older Agda versions might require you to specify
-- what is zero and what is suc.

infixl 4 _+_
infixl 5 _*_
infixr 6 _^_

_+_ : (m n : ℕ) → ℕ
zero  + n = n
suc m + n = suc (m + n)

_*_ : (m n : ℕ) → ℕ
zero  * n = zero
suc m * n = n + m * n

_^_ : (m n : ℕ) → ℕ
m ^ zero = suc zero
m ^ suc n = m * m ^ n

Since we are working with unary numbers, evaluating 2 ^ 16 will take a fair amount of time. However, if we try to evaluate const 1 (2 ^ 16), it will finish in almost no time at all.
const : ∀ {a b} {A : Set a} {B : Set b} →
  A → B → A
const x _ = x

The same thing goes for data types:
infixr 3 _∷_

data List {a} (A : Set a) : Set a where
  []  : List A
  _∷_ : A → List A → List A

record ⊤ {ℓ} : Set ℓ where

Head : ∀ {a} {A : Set a} → List A → Set _
Head         []      = ⊤
Head {A = A} (_ ∷ _) = A

head : ∀ {a} {A : Set a} (xs : List A) → Head xs
head []      = _
head (x ∷ _) = x

replicate : ∀ {a} {A : Set a} → ℕ → A → List A
replicate 0       _ = []
replicate (suc n) x = x ∷ replicate n x

Again, head (replicate 1000000 1) will evaluate almost instantly.
However, normal order is not call-by-need, namely computations are not shared.
open import Data.Product
open import Relation.Binary.PropositionalEquality

slow : 2 ^ 16 ≡ 65536
slow = refl

slower₁ : (λ x → x , x) (2 ^ 16) ≡ (65536 , 65536)
slower₁ = refl

slower₂ :
  let x : ℕ
      x = 2 ^ 16
  in _≡_ {A = ℕ × ℕ} (x , x) (65536 , 65536)
slower₂ = refl

In this case, type checking slower₁ and slower₂ will take roughly twice the time slow needs. In comparison, call-by-need would share the computation of x and compute 2 ^ 16 just once.

Note that during type checking, you have to evaluate expressions to normal form. If there are any binders around (λ or Π), you have to go under the binder and evaluate the inner expression as well.
λ n → 1 + n   ==>   λ n → suc n

How does codata change the picture? The interaction with reduction is actually fairly straightforward: ♯ x does not evaluate any further unless you apply ♭ to it.
This is also why ♯ is known as delay and ♭ as force.

You can also compile Agda down to Haskell. There's also JavaScript, but I don't know how that is compiled, so I'll stick with compilation to Haskell.
The evaluation strategy is mostly whatever the Haskell compiler uses. As an example, here's what happens to the following definitions:
data ℕ : Set where
  zero : ℕ
  suc  : ℕ → ℕ

_+_ : (m n : ℕ) → ℕ
zero  + n = n
suc m + n = suc (m + n)

data Vec {a} (A : Set a) : ℕ → Set a where
  []  : Vec A zero
  _∷_ : ∀ {n} → A → Vec A n → Vec A (suc n)

And after compilation:
-- ℕ
data T1 a0 = C2
           | C3 a0

-- Vec
data T12 a0 a1 a2 = C15
                  | C17 a0 a1 a2

-- _+_
d6 (C2) v0 = MAlonzo.RTE.mazCoerce v0
d6 v0 v1
  = MAlonzo.RTE.mazCoerce
      (d_1_6 (MAlonzo.RTE.mazCoerce v0) (MAlonzo.RTE.mazCoerce v1))
  where d_1_6 (C3 v0) v1
      = MAlonzo.RTE.mazCoerce
          (C3
             (MAlonzo.RTE.mazCoerce
                (d6 (MAlonzo.RTE.mazCoerce v0) (MAlonzo.RTE.mazCoerce v1))))

Yup, the last one is a bit crazy. But if you squit a bit, you can see:
d6 C2 v0 = v0
d6 (C3 v0) v1 = C3 (d6 v0 v1)