AttributeError: module 'posts.views' has no attribute 'home'

Question: Learning from a Udemy course I am taking by Nick Walter on Django, I am writing my own "Credit Card Redaction" app. The basic functionality is in place. But now I am trying to add a blog post app to go with it.   I successfully initiated the app using $ python3 manage.py startapp posts. But as soon as I started filling in the urls.py, template and sub-views, my server has stopped running. I get:

File "/home//dev/projects/python/2018-and-2019/CC_Redact/CC_Redact/urls.py", line 10, in
url(r'^$', views.home, name='home'),

AttributeError: module 'posts.views' has no attribute 'home'

This is Django 2.0 with Python 3.6 using the built in test server (no where near production environment yet). I'm running my code inside an activated virtual environment. These are the contents of my requirements.txt:

Django==2.0.13
Pillow==5.4.1
psycopg2==2.7.7
psycopg2-binary==2.7.7
pytz==2018.9

Pretty basic, right?
urls.py in my primary project folder:
from django.contrib import admin
from django.urls import path
from . import views
from posts import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', views.home, name='home'),
    url(r'^result/', views.result, name='result'),
    url(r'^james/', views.posts, name='james'),

views.py (in app folder):
from django.shortcuts import render

# Create your views here.

def james(request):
    return render(request, 'posts/james.html')

As you can see, I've named my function "james", as well as my template.
Here is posts/templates/posts/james.html:
from django.shortcuts import render

# Create your views here.

def james(request):
    return render(request, 'posts/james.html')

Finally, here is my file tree and directory structure: .
When running the sever, I am expecting to see "You are in James' posts!" in bold text when navigating to localhost:8000/posts. Instead I am receiving:
python manage.py runserver
Performing system checks...
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f41c70286a8>
Traceback (most recent call last):
  File "/home/<user>/dev/projects/python/2018-and-2019/CC_Redact/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper
    fn(*args, **kwargs)
  File "/home/<user>/dev/projects/python/2018-and-2019/CC_Redact/venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run
    self.check(display_num_errors=True)
  File "/home/<user>/dev/projects/python/2018-and-2019/CC_Redact/venv/lib/python3.6/site-packages/django/core/management/base.py", line 364, in check
    include_deployment_checks=include_deployment_checks,
  File "/home/<user>/dev/projects/python/2018-and-2019/CC_Redact/venv/lib/python3.6/site-packages/django/core/management/base.py", line 351, in _run_checks
    return checks.run_checks(**kwargs)
  File "/home/<user>/dev/projects/python/2018-and-2019/CC_Redact/venv/lib/python3.6/site-packages/django/core/checks/registry.py", line 73, in run_checks
    new_errors = check(app_configs=app_configs)
  File "/home/<user>/dev/projects/python/2018-and-2019/CC_Redact/venv/lib/python3.6/site-packages/django/core/checks/urls.py", line 13, in check_url_config
    return check_resolver(resolver)
  File "/home/<user>/dev/projects/python/2018-and-2019/CC_Redact/venv/lib/python3.6/site-packages/django/core/checks/urls.py", line 23, in check_resolver
    return check_method()
  File "/home/<user>/dev/projects/python/2018-and-2019/CC_Redact/venv/lib/python3.6/site-packages/django/urls/resolvers.py", line 399, in check
    for pattern in self.url_patterns:
  File "/home/<user>/dev/projects/python/2018-and-2019/CC_Redact/venv/lib/python3.6/site-packages/django/utils/functional.py", line 36, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/<user>/dev/projects/python/2018-and-2019/CC_Redact/venv/lib/python3.6/site-packages/django/urls/resolvers.py", line 540, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/home/<user>/dev/projects/python/2018-and-2019/CC_Redact/venv/lib/python3.6/site-packages/django/utils/functional.py", line 36, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/<user>/dev/projects/python/2018-and-2019/CC_Redact/venv/lib/python3.6/site-packages/django/urls/resolvers.py", line 533, in urlconf_module
    return import_module(self.urlconf_name)
  File "/home/<user>/dev/projects/python/2018-and-2019/CC_Redact/venv/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/<user>/dev/projects/python/2018-and-2019/CC_Redact/CC_Redact/urls.py", line 10, in <module>
    url(r'^$', views.home, name='home'),
AttributeError: module 'posts.views' has no attribute 'home'

edit: btw: Here is my project on GitHub. I am accepting pull requests.
Comment: You have no view named `home` ; replace `def james(request)` by `def home(request)`
Answer: You really need to focus more on the course.
view.posts refers there is a def with name posts call that def.
In short view.posts calls posts def in view.
Change
def James(request):

To
def posts(request):
In view.py
U also need to have a def with name "home"
Comment: Make a def in views.py with name home.
Comment: As I said earlier views.posts calls posts def in views.py similarly views.home will call home def in views.py which doesn't exists yet
Comment: I changed `def james(request):` to `def posts(request):`.  Now my interpreter is saying: `AttributeError: module 'posts.views' has no attribute 'home'` I think this new issue is related to the importing of views in urls.py.  I tried swapping these two lines around which didn't fix the issue.
Comment: By defining both the `home` and `result` function inside posts.views, my server runs successfully now. I've pushed these changes up to my GitHub repo with the link updated above. Thank you for your advice so far. However these functions already exist inside a separate views.py, as you can see in my file tree image above. So now my `home` and `result` functions exist in two separate views.py's, which is redundant. How could I re-write my urls.py to keep the two functions as they appear in the original views.py?


VB Excel can't Copy and Paste Macro that Pulls the Cell Position

Question: I have a datasheet that looks like this
page 1
Costumer: josef
Id: 12345
I create a form that includes (Costumer and ID) more easily manually. Inside the form I have information.
I have an insert button that delivery the information to specific cells inside the page.
Private Sub CommandButton1_Click()

i = Cells(Rows.Count, 1).End(xlUp).Row + 23 'Get last empty cell in column A
Range("D" & i).Value = TextBox1
'Range("D1").Value = TextBox1
Range("D2").Value = TextBox4
Range("C4").Value = TextBox2
Range("C5").Value = TextBox3
    If OptionButton1.Value = True Then
       Range("A7").Value = OptionButton1.Caption
       ElseIf OptionButton2.Value = True Then
       Range("A7").Value = OptionButton2.Caption
       ElseIf OptionButton3.Value = True Then
       Range("A7").Value = OptionButton3.Caption
       Else
       Range("A7").Value = OptionButton4.Caption
     End If
Unload Me
End Sub

My problem is that I need to do the same in page 2 of the worksheet, when I copy and paste the macro to do the same in page 2, I need that values will be realease in the same position but in page 2, but the macro release the date in the same cells of the page 1, if you look the code I've set  Value = TextBox1 to "D1, I need a formula that after copy macro and I invoked the form, It paste in the active sheet, Not on the first page like it does right now.
Try placing a counter but that does not work. Any help will be appreciated.
on this picture you will see sheet1 "hoja1" and page1 "pagina 1" and the load form (datos del presupuesto)

I also have picture 2 with sheet one but page 2 (pagina 2), in this page i copy and paste the same I have in page 1 (macro and everything) and i press insertar button to load the form, when the sistem insert it does it in the 1th page not in the 2 page.

It should be a formula that can help me when i copy one page and pastes the macros pull all the cell values to the page I am paste all the data.
Comment: What do you call a page??? Is it a sheet? One of those named tabs you click in the bottom of the screen???
Comment: If that's the case, before all `Range` you find in your code, add `Sheet1.`, or `Sheet2.` and so on, representing the sheet you want to add the values.
Answer: When you want to take a range from a specific sheet, use that sheet before the range:
Sheet1.Range("D" & i).Value = TextBox1 'takes cell from first sheet.
Sheet2.Range..... 'takes cell from second sheet.

ActiveWorkbook.Worksheets("SheetName").Range.... 'you get sheets by their names

You can also put the sheet into a variable so you keep using it instead of repeating sheet name all over:
Dim TargetSheet as Worksheet
Set TargetSheet = ActiveWorkbook.Worksheets("SheetName")

TargetSheet.Range.....
TargetSheet.Range......
TargetSheet.Range......

So your code could be like this:
Private Sub CommandButton1_Click()

    'First thing: select your specific sheet:
    Dim MySheet as Worksheet
    Set MySheet = ActiveWorkbook.Worksheets("TheNameOfYourSheet")

    'Now, before every range or cell, take them FROM that specific sheet
    i = MySheet.Cells(Rows.Count, 1).End(xlUp).Row + 23 'Get last empty cell in column A

    'Select your pivot cell (don't forget MySheet)
    Dim PivotCell as Range
    Set PivotCell = MySheet.Range("D" & i)

    'Put the value in the pivot
    PivotCell.Value = TextBox1

    'Now you can start using the offsets (it's really better, as you commented)
    PivotCell.Offset(0,1).Value = TextBox4 'That would be D2 if Pivot is D1

    'I'm not sure if you can use negative offsets,
    'if not, take the top left cell of your target area as pivot -
    'But there surely will be an error if the offset falls to the left or above A1
    PivotCell.Offset(3, -1).Value = TextBox2 'That is C4 -
    PivotCell.Offset(4,-1).Value = TextBox3 'C5

    If OptionButton1.Value = True Then
        PivotCell.Offset(6,-3).Value = OptionButton1.Caption ' A7
    ElseIf OptionButton2.Value = True Then
        PivotCell.Offset(6,-3).Value = OptionButton2.Caption
    ElseIf OptionButton3.Value = True Then
        PivotCell.Offset(6,-3).Value = OptionButton3.Caption
    Else
        PivotCell.Offset(6,-3).Value = OptionButton4.Caption
    End If

    Unload Me
End Sub

One thing EVEN BETTER is to Name a cell. In the top left of the Excel screen, there is a text box where the selected cell coordinates are show (like "A1", "B2", ...). If you type a name in that box, you can use that named cell via code like this:
ActiveSheet.Range("NamedCell")

Comment: well it is hard to explain but let me show you pictures of what I have.
on this picture you will see sheet1 "hoja1" and page1 "pagina 1" and the load form (datos del presupuesto)
Comment: i found that ActiveCell.Offset(1, 0) can work around that, but still i need to like a pivote cell to map the other cells
Comment: Every cell is a `Range`, the `ActiveCell` is a range too. So, you can select your pivot cell from any sheet you like, and offset it. See edit in my answer using that.


GFCI buzzing on same circuit as dimmer

Question: Ok, is please bear with a little explanation:
My girlfriend had the master bath in her condo remodeled, and asked her contractor to install a new (GFCI) outlet. He apparently pulled it from the switch for the vanity light fixture. At the same time, he installed a dimmer switch for that same vanity light. The good news is there is no buzzing from the light fixture at all. The bad news is that the new outlet is buzzing and crackling like mad. These people told her there was nothing that could be done, and that it wouldn't hurt anything, it was because the dimmer and the GFCI amounted to two transformers on one circuit. This is a crock, but I wasn't around when the work was done. At this point I am wondering if anything can be done without pulling out the new sheetrock. The GFCI outlet works fine, it tests and resets normally, and you can use it nomally as well. It just sounds like an angry beehive. I was considering a lamp debuzzing coil, but my only experience with one of those, it made as much noise at this outlet is. Any suggestions?
Comment: [This](http://diy.stackexchange.com/questions/5812/why-gfci-clicks-even-when-turned-off) question might be worth a look.
Answer: I have never encountered the situation of a buzzing GFI before. Sounds a bit fishy to me. The trouble shooting procedure would be to turn off the power to the bathroom, unscrew the GFI from the box, pull it out a bit and remove the "load" side wires which should go to the dimmer and check that "line" screws are tight. Turn the power back on, if the dimmer is on the load side then the light with dimmer should be inoperative. Does the sound go away?  If it doesn't and the buzz remains, the GFI is probably defective.  Now turn the power back off, put the load wires back on and test again. If the buzz comes back then replace the dimmer or swap it for a regular switch. If neither of these subtitution tests stop the problem, call a different electrician.  Trust me, a buzz from a GFI or a dimmer is not a normal situation and could be a  potentially dangerous situation. Feel free to ask follow up questions if any of this doesn't make sense to you.  Maybe one of my buddies can do an edit to make this a bit easier to follow.
Comment: It sounds like either a bad connection (which should be fixed immediately, as it's a fire hazard), or a faulty GFCI (which also should be fixed - faulty is not a good quality in safety devices).
Comment: It's worth noting: the thing buzzes even when it is tripped with the test button, just keeps on . . .
Comment: do the lights go out when you trip the GFI?
Comment: no, they don't change at all.
Comment: The lights are not on the load side, be aware.  Did you do the tests I suggested?  Would love to hear some feedback.
Answer: I noticed several kitchen outlet GFIs all buzzing slightly yesterday. They buzzed both while ready and while tripped. I didn't check the wiring but they are all about one year old, installed by an electrician. I pulled one out, and it was cool to the touch.
This morning the buzzing had stopped!
I think the incoming line voltage may have varied and the GFIs buzzed when the voltage was a little low.
Comment: Why would a Gfci buzz with low voltage? Voltage swings are pretty normal, I've never noticed any Gfci buzz
Answer: Checking the wiring is one of the first things to do.  If you have the GFCI setup as a 'no equipment load' (the last load on the leg or additional loads are tied to the line side of the GFCI and not the load side) then make sure the load posts are not near any wiring in the box.   Also, if you are sharing the load posts for future wiring (either to another GFCI or by chance a future load that is not supposed to be protected (old code)) make sure there is nothing plugged in that could cause feedback.
TL/DR:
I had a GFCI that started to quiet buzz several months after installing.  It was one of many GFCIs in my bath all independent (load and line wires shared load posts).  My load posts were unused, however they were not screwed in and were sticking out. As a result, when the 20amp 12g wire was pushed into the box I believe the ground wire was close to the load post.  There was the original sticker on the load posts (hot and neutral) however the sticker came loose from the hot post.  I removed the receptacle and screwed the posts in, and reaffixed the sticker to the post, and ensured the ground and other wires were properly pushed into the back of the box.  The buzz is no longer present.

GFCI buzzing on same circuit as dimmer


Angular 9 Universal Server Side Rendering GRPC Error

Question: I cannot get npm run build:ssr && npm run serve:ssr to run correctly.
I have added Angular Universal to my project with: ng add @nguniversal/express-engine --clientProject SampleAngularApp
npm run build:ssr runs and builds perfectly but npm run serve:ssr does not.
Here is my error when trying to server:
Error: Cannot find module '/Users/mike/Desktop/Sites/SampleAngularApp/node_modules/grpc/src/node/extension_binary/node-v72-darwin-x64-unknown/grpc_node.node'
Require stack:
- /Users/mike/Desktop/Sites/SampleAngularApp/node_modules/grpc/src/grpc_extension.js
- /Users/mike/Desktop/Sites/SampleAngularApp/node_modules/grpc/src/client_interceptors.js
- /Users/mike/Desktop/Sites/SampleAngularApp/node_modules/grpc/src/client.js
- /Users/mike/Desktop/Sites/SampleAngularApp/node_modules/grpc/index.js
- /Users/mike/Desktop/Sites/SampleAngularApp/node_modules/@firebase/firestore/dist/index.node.cjs.js
- /Users/mike/Desktop/Sites/SampleAngularApp/node_modules/firebase/firestore/dist/index.cjs.js
- /Users/mike/Desktop/Sites/SampleAngularApp/dist/server.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:625:15)
    at Function.Module._load (internal/modules/cjs/loader.js:527:27)
    at Module.require (internal/modules/cjs/loader.js:683:19)
    at require (internal/modules/cjs/helpers.js:16:16)
    at Object.<anonymous> (/Users/mike/Desktop/Sites/SampleAngularApp/node_modules/grpc/src/grpc_extension.js:32:13)
    at Module._compile (internal/modules/cjs/loader.js:777:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:788:10)
    at Module.load (internal/modules/cjs/loader.js:643:32)
    at Function.Module._load (internal/modules/cjs/loader.js:556:12)
    at Module.require (internal/modules/cjs/loader.js:683:19) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/Users/mike/Desktop/Sites/SampleAngularApp/node_modules/grpc/src/grpc_extension.js',
    '/Users/mike/Desktop/Sites/SampleAngularApp/node_modules/grpc/src/client_interceptors.js',
    '/Users/mike/Desktop/Sites/SampleAngularApp/node_modules/grpc/src/client.js',
    '/Users/mike/Desktop/Sites/SampleAngularApp/node_modules/grpc/index.js',
    '/Users/mike/Desktop/Sites/SampleAngularApp/node_modules/@firebase/firestore/dist/index.node.cjs.js',
    '/Users/mike/Desktop/Sites/SampleAngularApp/node_modules/firebase/firestore/dist/index.cjs.js',
    '/Users/mike/Desktop/Sites/SampleAngularApp/dist/server.js'
  ]
}
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! email@example.com serve:ssr: `node dist/server`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the firstname.lastname@example.com serve:ssr script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/mike/.npm/_logs/2020-02-18T02_17_14_016Z-debug.log

Any insight would be greatly appreciated.
Answer: First of all, make sure that installing process of npm install -g firebase-tools completed successfully. If the problem still persists, rebuilding grpc module should fix your problem. Please run npm rebuild grpc. You can also rebuild all modules by running npm rebuild.


Angular 7 Fixed Header Table Examples Not Working

Question: I am running into a big problem with fixed header tables as it relates to my Angular application.  Using this this example (which is also this one) as a basis for my question, I thought originally it was my component, but now, I have attached this same code into my index.html page and eliminated the angular app from being implemented.  I should not that I am still using ng serve and having the application and page render on my local machine.  My css includes:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.0/css/bootstrap.min.css" />

And then right after that, in my html, I have the table:

          #	Name	Points

          1	Mike Adams	23

          2	Holly Galivan	44

        ...

And yet, this is what is displayed:

Can somebody help me understand why this can work in a variety of examples, but when I try to run it with my angular application on my local machine, even outside the app, it doesn't work?
UPDATE:
The issue may be that it's because I'm using Bootstrap 4 rather than Bootstrap 3.  Per jahller's explanation, when I changed my bootstrap to be 3.3.7, it works.  Unfortunately, I'm building my app with Bootstrap 4.  Can anyone point me to an example that works with Bootstrap 4?
UPDATE 2:
Per jahller's additional edit, the issue was that my columns were using the col-xs-{num} classes for the table columns.  By switching them to col-{num} classes, the scrollable table with fixed header works perfectly!
Comment: It is doing the sticky header correctly.  It is the formatting that is the problem.  The other examples show a table not only across the screen (width 100%) but also the columns correctly spaced. You noticed that the col-xs-2 and col-xs-8 classes are being used in my example, but they are not being implemented.  The columns are only spaced out by the data, not by the bootstrap classes.  Are they getting overwritten?  If so how?
Comment: what exactly is the problem? the functionality seems to be what you want, right? is it the formatting?
Answer: the example you were used is using bootstrap 3 instead of bootstrap 4
check the app.component.html in this stackblitz example https://stackblitz.com/edit/angular-v8mxae
there i imported the same bootstrap version that was used in your examples codepen
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />

with this version is works as expected
*Edit
for using bootstrap 4 just remove the xs part of col- classes.
the grid system was slightly changed from bootstrap 3 to 4.
so instead of col-xs-2 use col-2, instead of col-xs-4 col-4, etc.
Comment: I can see that it works with that version.  Can anyone point me to an example that works with bootstrap 4?
Comment: see my updated answer or check the official migration guide here https://getbootstrap.com/docs/4.0/migration/#grid-system-1
Comment: jahller, wouldn't you know it, that did it! I verified both in the angular app and in the page outside of it, just simply changing the column names worked.  Awesome, thank you!


How to create lines with Athens?

Question: I have no clue how to create lines with Athens. I took a look at Cairo docs but I cant see how Athens is related to Cairo.
http://zetcode.com/gfx/cairo/basicdrawing/
In the above link I cant find any equivalent for  cairo_set_line_width(cr, 1);  I tried to look inside Athens but is nowhere to be found. Overall I find the Athens architecture quite confusing though Cairo looks simple. Any idea how to makes this work ?
Answer: There is no separate canvas commands which represents 'draw a single line' action in Athens.
Instead one must generate path representing the line:
<code>surface drawDuring: [:canvas | | linePath |
linePath := canvas createPath: [:builder |
  builder
     absolute;
     moveTo: lineStartPoint;
     lineTo: lineEndPoint
 ].

stroke := canvas setStrokePaint: Color red.
stroke width: 10.

canvas drawShape: linePath.
].
</code>
You can look at Athens-Tutorial, where various aspects of path creation,
using of stroke paints and filling shapes explained in examples.
Comment: as a follow up.. i do not advise you to learn how to use Athens by looking on Cairo example. Athens designed as independent framework with owh API which can use various different backends. And Cairo is just one of them which currently supported.
Comment: Ah nice , it works now , thank you! So where I find documentation about Athens ?
Comment: right now it is tutorial and class comments in Athens itself.

How to create lines with Athens?


Replace dictionary key with a property of itself

Question: Let's say I have a Dictionary defined this way:
var Dict = Dictionary<Person, List<Car>>
With both Person and Car being objects. If I wanted to turn that dictionary into this:
var Dict = Dictionary<Person.Id, List<Car>>
What process would it need to go through?
Comment: In the first code fragment you have `List` and in your second code fragment you have `List`. Should they both be `List` or are they actually two different types?
Comment: You're trying to map the key mechanism of the dictionary object with a property of an object. That is illegal - you need to define the key with the object *type* that will be mapped to it, not a property of a type. In this case, that would be the object type that Person.Id is based on. (int, guid, etc.)
Answer: You can try to use ToDictionary method that creates another Dictionary by keys which you expect.
var result = Dict.ToDictionary(x=>x.Key.Id,z=>z.Value)


IdentityServer4 IsValidReturnUrl returns false for valid url

Question: I've a test project with this client configuration:
public class Clients : IClientStore
    {
        public Task<Client> FindClientByIdAsync(string clientId)
        {
            return Task.FromResult(new Client
            {
                ClientId = "client.webforms",
                ClientName = "WebForms Client",
                AllowedGrantTypes = GrantTypes.Hybrid,
                AllowAccessTokensViaBrowser = false,

                ClientSecrets =
                    {
                        new Secret("1234".Sha256())
                    },

                RedirectUris = { "http://localhost:9869/signin-oidc" },
                PostLogoutRedirectUris = { "http://localhost:9869/" },

                AllowedScopes =
                    {
                        IdentityServerConstants.StandardScopes.OpenId,
                        CstIdSrvScopeTypes.TestWebForms
                    },
                AllowOfflineAccess = false,
                RequireConsent = false,

                AlwaysIncludeUserClaimsInIdToken = true
            });
        }
    }

When I try to validate it in LoginController I'm getting false result (this is from Immediate Window:
returnUrl
"http://localhost:9869/signin-oidc"
this.identityServer.IsValidReturnUrl(returnUrl)
false

Also this.identityServer.GetAuthorizationContextAsync(returnUrl) result is null. Am I doing something wrong?
Comment: Having this same issue
Comment: Have you found a solution for this? The `returnUrl` for myself is valid, exists in my data store, and is being sent across the wire from the client.
Comment: As that issue suggests, if you are trying to put your login UI on a different website than the identity server logic, its not yet fully implemented. You could remove the `IsValidReturnUrl` check for now, but I feel other things will eventually break
Comment: I believe @Yes is correct. Don't confuse what happens here with a proper, working redirect that should be happening from an external Client. If that is set up properly, the `GetAuthorizationContextAsync` call will return a non-null result. It looks for URIs that have been configured in IdentityServer4, so URLs such as `~/` or `/Login` may not work (unless configured).
Comment: @DanielL, it's not absolutely clear what you want. The open issue concerns only the UI for IdSrv living on another host than IdSrv. Most of your (and the original) question refers "just a client" which is a totally different story -- when configured properly -- just works according to oidc spec.
Answer: Yes - you need to add a single RedirectUri when you configur your client that is one of the RedirectUris  that is in the list you have above.
Something like
#
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
        {
            SignInAsAuthenticationType = Settings.AuthenticationType,
            Authority = config.Authority,
            RedirectUri = config.RedirectUri
        }


PHP: How to change search behaviour of include/require function?

Question: Standard include or require function first of all looking for an included file in directories set in include_path variable. After that it searches the file in the current directory.
// Standard behaviour
inlcude "needed_file.php";

// 1. Looking for in include_path directories
// ...
// 2. Looking for in the current directories
// ...

But is it possible to implement the reverse behaviour: first of all look at current dir, and after that into dir in include_path variable?
// Necessary behaviour
inlcude "needed_file.php";

// 1. Looking for in the current directories
// ...
// 2. Looking for in include_path directories
// ...

I can write a script that do this task like that:
function include_file_inverted( $filename ) {
  // Looking for a file in the curret dir
  if (file_exists(dirname(__FILE__) . $filename)) {
     include (dirname(__FILE__) . $filename);
  } else {
     // Looking for a file in the include_path
     include $filename;
  }
}

But are there another posibilities to invert search behaviour of include function?
UPDATE
Instead of dirname(__FILE__) or __DIR__ it is necessary to use getcwd(). Because the function can be described in other included file.
// This function is described in ./admin/ directory,
// but it is called from other places.
function include_file_inverted( $filename ) {
  // Looking for a file in the curret dir
  if (file_exists(getcwd() . $filename)) {
     include (getcwd() . $filename);
  } else {
     // Looking for a file in the include_path
     include $filename;
  }
}

UPDATE 2
I slightly change my question.
If the needed file is absent in the current directory and it is only in the include_path, the last file should be called.
// Main working script try to include needed file
include "the_needed_file.php";

// It is located in the included_path and is called from where.
/{included_path}/the_needed_file.php

If the needed file is in the current directory, it does something and after that it should include file with the same name in the included_path directory.
// Main working script try to include needed file
include "the_needed_file.php";

// the_needed_file is in the current directory.
// {current_dir}/the_needed_file.php
<?
  // It does something
  // ...

  // And it includes file from a system directory decribed in include_path

  // When I write this code
  include "the_needed_file.php";
  // it recursively calls the current file. It is an error.

  // So I need to write something like that
  include "/{included_path}/the_needed_file.php";
?>

Any suggestion how to improve this code?
Comment: just use `__DIR__` instead of `dirname(__FILE__)`
Comment: `set_include_path('.' . PATH_SEPARATOR . get_include_path());`
Comment: @Tschallacka Not `__DIR__` not `dirname(__FILE__)`, only `getcwd()`. See update.
Comment: @IvanZ it depends where the file is located. Is it located to your current executing file or relative to your current include file. If you wish to include a "brother" file that resides in the same directory as the file you're running the include from or a subdirectory then you will want to use `__DIR__` it all depends on use case.
Answer:
But is it possible to implement the reverse behaviour: first of all look at current dir, and after that into dir in include_path variable?

Make the current dir the first one in the list of directories this setting contains.
http://php.net/manual/en/ini.core.php#ini.include-path:

Using a . in the include path allows for relative includes as it means the current directory.

The default value for this setting is .;/path/to/php/pear, so that would search the current directory first already. (On a unix system, the separator is : instead of ;)
If you need this on systems where you don't know the configuration up-front, check if the first entry is a ., and if not, add it. (You might want to make sure it doesn't occur again later in the list, so as to not have the same directory searched twice.)
get_include_path and set_include_path can be used, or ini_get and ini_set.
Comment: Excelent. This work! Adding a point '.' in include_path do what I want.


What would be a good split character for splitting concatenated base64 strings?

Question: I have a number of base64 strings that I need to concatenate to send over HTTP.
Is there a good character to use to split the strings (I'm guessing a character that is invalid inside a base64 string).
-thanks for the help
Answer: Since base64 only contains characters, digits and + and /, anything else should do - how about a space, a comma (',') or a pipe symbol ('|') ?
Comment: well, it could also contain '=' as padding character. But yes, I'd recommend any whitespace or comma, that way it'd be easier to visually read as well as parse.
Comment: Note that it's "common" to display base64 by putting a \n every 76 characters (at least on Linux). So if you want to use whitespace, you probably want to go for \n\n or something.
Comment: I think pipe symbol would be the best option.


How to implement oAuth 2.0 in Tizen

Question: I'm trying to implement google authentication using oAuth 2.0 in Tizen. I'm following the step from here. Based on the instructions from the link, I can able to obtain the user code. but i'm always getting invalid request for obtaining the access and refresh token. My request is as follows.
var urlToken ="https://accounts.google.com/o/oauth2/token?"+
        encodeURI("client_id=<<my client id>>&" +
        "client_secret=<<my client secret>>&" +
        "code=<<Device code received in first step>>&" +
        "grant_type=authorization_code");
$.ajax({
    url:urlToken,
    type:"POST",
    headers:{
        "Content-Type": "application/x-www-form-urlencoded",
        "Content-length" : "250"
    },
    accepts: "applicatin/json",
    success:function(response){
        console.log("access token response success");
        console.log(response.access_token)
    },
    error:failure
});

I couldn't able to figure out what goes wrong. Please update it there is any other way to implement the same.
Note: I'm trying to implement this from the Tizen Webapp.
Comment: Why are you setting `"Content-length" : "250"` header by hand? What do you mean by "I'm always getting invalid request" - does google returns this information? Or does the request fail on some transportation layer before it is even send?
Comment: Content-length is one of the option i got in other questionnaire. Removing that also gives me the same result. invalid request is the return response i can able to see using rest client of firefox. It is giving 400 Bad request. Yes i'm receiving the response from google. A
Comment: Have you tried to make it work outside of Tizen? I'm not familiar with that library so I'm not sure if and how i may affect your requests.
Comment: Yeah. I tried to do it by simple ajax request using restclient (Firefox add-on).
Comment: And...? Result was the same "invalid request"?
Comment: yes. it is giving the same response.
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/26458/discussion-between-wtk-and-brune)
Answer: I got things working with the following code. I made a mistake by marking the data in query string as well as setting content-type and content-length explicitly. Content-type is the by default "application/x-www-form-urlencode". Got the solution by random click.
var urlToken ="https://accounts.google.com/o/oauth2/token"+
var dataValue = "client_id=<<my client id>>&" +
        "client_secret=<<my client secret>>&" +
        "code=<<Device code received in first step>>&" +
        "grant_type=http://oauth.net/grant_type/device/1.0";
$.ajax({
    url:urlToken,
    data:dataValue,
    crossDomain:true,
    type:"POST",
    success:function(response){
      if(response.error != null){
            <<Call the same function again>>;
        }
        else{
            console.log("Access Token :" + response.access_token);
            console.log("Token Type : " + response.token_type);
            console.log("Expires : " + response.expires_in);
            console.log("Refresh Token : " + response.refresh_token);
        }
    },
    error:failure
});

Thanks WTK
I believe this and this will be helpful
Comment: Hi @Brune, I'm trying to develop tizen web application with google login, can you please help me with this.
Comment: @venky Sure.. But I've touched google auth & tizen for sometime now. I'm not sure whether the info i provide will help you.. If I'm correct the version i used in tizen is obsolete now.. but yeah, shoot your query.. I'll try..

How to implement oAuth 2.0 in Tizen


Android sqlite delete

Question: I am trying to develop an android application but I have a problem with SQLite.
in the application I can add or delete values in the database,
and in general  it works perfectly, but when I add "1.50" or "1.250" my method is unable to remove.
Method to remove a value :
    public int removeContenuWithTitre(String value){

    return bdd.delete(TABLE_CONTENU, COL_VALEUR + " = " +value, null);
}

Code that uses the method:
        buttonSup.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View actuelView)
        {
            // Si la zone de texte n'est pas vide :
            if(text3.getText().length() != 0)
            {

                ContenuBDD contenuBdd = new ContenuBDD(MainActivity.this);
                contenuBdd.open();

                String valText3 = text3.getText().toString();

                if(contenuBdd.recherche(valText3) == true)
                {

                    //not removed because the value is not the database

                }
                else
                {
                    // deleting the value in the database :
                    contenuBdd.removeContenuWithTitre(valText3);

                }

                contenuBdd.close();
            }
            else
            {

            }
        }
    });

code of the method "recherche" to see if a value is in the database :
public boolean recherche(String titre){

    Cursor c = bdd.query(TABLE_CONTENU, new String[] {COL_ID, COL_VALEUR}, COL_VALEUR + " LIKE \"" + titre +"\"", null, null, null, null);
    if(c.moveToFirst() == false)
    {
        return true;
    }
    else
    {
        return false;
    }

}

Answer: Try:
String[] args = {value};
bdd.delete(TABLE_CONTENU, COL_VALEUR + "=?", args);

Android sqlite delete


How to estimate and compare operating costs of gas vs electric furnace?

Question: My home has an old electric, central furnace. All of my neighbors are on natural gas. I pay 5-6 times as much as they do on my heating bills during winter months.
I can either convert my home to natural gas or install an electric heat pump. Air conditioning is not at all important where I live, so considered an insignificant part of the math.
Current rates are:

$0.34 per therm, for natural gas
$0.14 per kilowatt hour for electricity

As my electric bills are so high, I need to buy the most efficient equipment possible. Upfront costs will be $8-10k regardless of whether I put in a gas or electric furnace.
Based on current rates, what equipment specs and math are needed to estimate the monthly cost of a natural gas furnace vs an electric heat pump?
Update:
Climate average lows in winter:
Oct: 29°F
Nov: 18°F
Dec: 11°F
Jan: 11°F
Feb: 16°F
Mar: 20°F
Apr: 24°F
May: 33°F
I learned my state offers mail in rebates of $200-375 for installing gas furnaces and a $2000 tax credit for electric heat pumps. Is that indicative of lower costs?
Comment: It sounds like you're looking for a TCO (total cost of ownership) calculation - those are notoriously complicated. You can get closer to an operational cost by converting your "therm" and "kWh" to BTU or another unit of heat energy, these are directly comparable and depend on the efficiency and capabilities of the equipment.
Comment: Knowing the insulation of the house is important also, wondering if your neighbours have good insulation and you don't.
Comment: @crip659 I am also working on adding insulation, replacing windows with more efficient ones, etc.
Comment: The new upgrades of insulation/windows will probably do more to lessen  your cost of heating, than the type of heating system you buy.  Check with locals for any rebates for upgrades.
Comment: Are you in the U.S.? Which state? Many states offer rebates for different types of equipment which will affect the answers. Your climate also makes a much bigger impact on the cost to operate a heat pump than a natural gas furnace.
Comment: In the UK, all new builds *must* be electric. Gas is being outlawed, for cost & 'green' reasons. Heat pumps these days are very efficient.
Answer: Heat pumps usually supply air conditioning too so they would be part of the equation. The fact that your neighbors all have converted to a gas furnace should tell you something, maybe that gas is the way to go. your neighbors are a reliable source of information, much more than trying to do the math on a bunch of assumed variables. You didn't state where you live and that's important. If you're in a very cold area, heat pumps might not provide all the heat you need where as a furnace would. Heat pimps usually have a shorter life span because they are used year round where a separate AC and furnace split the seasons.  As far as equipment specs, you'd have to get them from different manufacturers and they will differ greatly. you'd also need to know the R value of your insulation. Check around and see what the local vendors in your area are recommending. If you get the specs and know your R value you'll need multi-variable calculus and differential equations to answer your question.. (just kidding)
I spend a lot of time in Chicago,Il and Miami,Fl. There are gas furnaces in Chicago and heat pumps in Miami. Older units in Florida are electric strip heaters and their cost to operate is through the roof. Luckily, we don't need them much.
Comment: @manassehkatz you don't need to believe in climate change, just peak oil and oil wars.  The cure is the same.   Vast fields of oil and gas were recently discovered in, well, actually, roughly the rectangle of Kharkiv, Severodonetsk, Donetsk, Popasna, and Dnipro.   So if Ukraine joins the EU, who need Russia?
Comment: I'm assuming the gas was installed back in the 1970s when the neighborhood was put in, so I don't know that's the best way to decide based on what neighbors are doing. Is there no simple value, telling me "this uses X Watts per hour" and "this uses Y Therms per hour" to make the comparison?
Comment: Average low temperature in January is:  11 °F, Record low: −20 °F.
Comment: @Village Those variables would be different for each size unit and would also be different based on efficiency ratings and manufactures.  What you're asking is like asking "what's the miles per gallon for a car?"
Comment: Suppose I'm looking at the same manufacturer even, similar product on the outside, just internals they change for gas or electric.
Comment: @Village  Then they should specify the those numbers for the product/ model number.  Usually neighborhoods/subdivisions stick with the same type of heating/cooling when they're built. the changes come after the first units get replaced. Talk to them.... I think it's your best answer.
Comment: The neighbors were putting in gas furnaces back before heat pumps worked very well.  It's a different situation today, both with the technology and the non-financial cost of fossil fuel addiction.  https://www.youtube.com/watch?v=MFEHFsO-XSI
Comment: @Harper-ReinstateMonica Generally speaking, if someone isn't gung ho about climate change mitigation, they aren't going to be convinced easily, if at all, about *the non-financial cost of fossil fuel addiction*. But $ works for most people. Show them that they'll save $1,000 a year and pay for a $4,000 more expensive system (making up numbers) in 4 years that is expected to last 10 years or more, and they'll be sold.
Comment: (And they may be not convinced because they don't believe it is happening/human caused, or simply because they don't care because it isn't their direct problem. The reason really doesn't matter. The solution is to make it worthwhile ($) to do something that happens to help anyway. Similarly, don't try to force electric cars based on "better for the environment", make them better because of overall total cost of ownership and/or fast/fun to drive.)
Comment: I have a heat pump with gas auxiliary heat, I opted out of the resistance heat.  That was put in about 15 years ago. So far it has been trouble free.  I went through the calculations and the heat pump was the cheapest to operate but then electricity keeps going up and it is now cheaper to use gas to heat. The switchover was simply pushing a button on the stat turning on emergency heat (gas) what a dr0p in energy cost. I am located in Northern Michigan.


Which 14.04 distro for Core2 Duo with 4 GB RAM? 32 bit?

Question: So, does my 6-yr old Core-2 Duo 32-bit processor system work best with the 32-bit distro, or will the 64 bit version work?
Answer: I would recommend reading For better performance should I install 32-bit or 64-bit? and I installed a 64-bit OS in a 32-bit processor
But the truth is, if you do not have the following hardware specs ready, 64 bit is not for you yet:

CPU is 64 bit capability
Motherboard that supports 64 bit (It should if the CPU is 64 bit)
At least 4 GB of RAM. IF you have less than 4 GB it is recommended to stay on 32 bit because 64 bit will not have a optimal performance.

To test this out, simply insert the Live Ubuntu DVD/USB on your computer and see if it runs. If it runs and you see the desktop, then you have a 64 bit capable CPU. If you get a architectural error then you can only use the 32 bit version of Ubuntu.
Another way to check this is to run the lscpu command. Here is what mines look like:
cyrex@cyrex:~$ lscpu
Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                8
On-line CPU(s) list:   0-7
Thread(s) per core:    2
Core(s) per socket:    4
Socket(s):             1
NUMA node(s):          1
Vendor ID:             GenuineIntel
CPU family:            6
Model:                 60
Stepping:              3
CPU MHz:               800.000
BogoMIPS:              6811.87
Virtualization:        VT-x
L1d cache:             32K
L1i cache:             32K
L2 cache:              256K
L3 cache:              8192K
NUMA node0 CPU(s):     0-7

If you see the line that says CPU op-mode it shows that it supports 32 bit and 64 bit. The Architecture line shows what Ubuntu arch I am using at the moment, which would be the 64 bit one.
Lastly, I am sure (I might be wrong so please correct me) that all Core 2 Duo are 64 bit capable. I just checked all Core 2 Duo Processors and none of them were 32-bit only. I checked all 2006, 2007 and 2008. So if you could add what model your CPU is, it would help more.
If I am correct, then for your case I recommend 64 bit. You have 4 GB of RAM and a good CPU for Ubuntu 64 bit.
Answer: You cannot install a 64-bit Operating System (or any other 64-bit software) on a 32-bit processor (System). While 64-bit processor supports any 32-bit application, reverse is not true. Hence you can run any 32-bit application(i386) on a 64-bit processor/System (amd64) but not the other way around. 64-bit Operating-Systems/Aplications are made specifically only for 64-bit processors.
That leaves you with no choice but to install 32-bit distro/version of Ubuntu IF you have a 32-bit processor.
I remembered Core 2 duo to be 64-bit and Wikipedia page 'Inter Core Family' confirms it
You can also check typing in terminal:
lscpu

and check CPU op-mode entry, if 64-bit is supported then it will be mentioned there,
Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit

Comment: I think all CoreDuo systems are 64 bit. I have run 64 bit since 9.10 on these two systems from 2006. Laptop with 1.5GB RAM
Intel(R) Core(TM)2 CPU T5500 @ 1.66GHz AND:
Desktop with 4GB RAM
Intel(R) Core(TM)2 CPU          6600  @ 2.40GHz
Comment: i too think so, but just in case you can check using `lscpu`


javascript works on page but not respods on iframe page

Question: java-script works on page but not responds on i frame page
Im working in a basic php page(ill call it home.php), I'm trying to code a progress bar that moves from left to right (onclick using JS).  The problem i have is I'm using iframes to load in "set content", when the user clicks on "set content" via iframs, it appears the progress bar will only respond to code on the home page(it seems to ignore any js code on a page which is loaded using iframes).
if you want more details here is the code:

<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

<button class="w3-button w3-light-grey" onclick="move()">Click Me</button>

<button class="tablinks" onclick="move()">My Resume</button>

Answer: In the past, you can call to a "move" function belong to the parent page from an iframe by calling parent.move(). But, now you need to care about CSP - Content Security Policy too.
Open the console to see if something like "Blocked a frame with origin..." appears. Then fix it by updating the CSP until it works.
Comment: actually im getting an error message in console: "ReferenceError: move is not defined"
Comment: okay, have an update! not sure if i didn't explain my problem well enough, but i think i have found a solution (at least one that dose not generate errors in console!).  your talking about parents got me thinking, and i found out i could target the parent php page within the loaded iframe php content...it looks something like: onclick="parent.move()"...which seems to be working! Thanks for pointing me in the right direction Dong!


jQuery animate() to hide and show elements by sliding left and right

Question: I'm trying to animate something using jQuery.
UPDATE
I have it working the way I want it. This is the jQuery:
    $(document).ready(function() {

        // go chat button
        $('#go-chat input').click(function() {
            $('#search, #go-chat').animate({width: '0px'}, 1000, function() {
                    $(this).hide();
                    $('#login, #go-search').animate({width: '573px'}, 1000, function() {
                            $(this).show();
                        }
                    );
                }
            );
        });
        $('#go-search input').click(function() {
            $('#login, #go-search').animate({width: '0px'}, 1000, function() {
                    $(this).hide();
                    $('#search, #go-chat').animate({width: '573px'}, 1000, function() {
                            $(this).show();
                        }
                    );
                }
            );
        });
    });

The problem now is that the text is wrapping as the slide happens and it is very ugly. How could I make it so that the text slides in/out as the search bar and the input fields without it wrapping as the width narrows/expands?
Thanks.
OLD QUESTION
Basically, I want to slide in the search bar to the left, essentially hiding it, and then slide out the 4 inputs below it. For now, I've placed them under the search bar but my plan is to hide them, and when the "Go Chat" button is pressed, the search slides out to the left and the 4 inputs slide in to the right.
Right now, the search box slides in to the center and doesn't disappear fully. How can I make it so it functions as I want it? If my explanation is unclear as to what I'm looking for, please ask for clarification.
Thanks.
Answer: Try changing
$('#search').animate({
                    width: '0px',
                },
                    '1000'
                );

to
$('#search').animate({ width: '0px' }, 1000, function() {
                $(this).hide();
             });

Once the animation is complete, the element will be hidden.
I also noticed that the 'Search' text isn't animated well.
Before doing the animate, try removing (or fading out) the text. Remember to show it again when toggling back. Eg:
$('#search-label').hide();

OR
$('#search-label').fadeOut();

Comment: Thanks. Now, how would I handle the slide effect... I want it to slide to the left, not the center as it is doing currently?
Comment: Yes I got it working. I'll post my solution after I fix some minor visual details.
Answer: I figured it out. To make it slide to the left, I gave the corresponding surrounding
s a width and margin-left: 0px;. Then I had the issue of the text wrapping as the width narrowed/widened. To fix that, I added white-space: nowrap; to the CSS for the corresponding
s.
Here's the jQuery:
$(document).ready(function() {
    $('#go-chat input').click(function() {
        $('#search, #go-chat').animate(
            {
                width: '0px'
            }, 1000, function() {
                $(this).hide();
                $('#login, #go-search').animate(
                    {
                        width: '573px'
                    }, 1000, function() {
                        $(this).show();
                    }
                );
            }
        );
    });
    $('#go-search input').click(function() {
        $('#login, #go-search').animate(
            {
                width: '0px'
            }, 1000, function() {
                $(this).hide();
                $('#search, #go-chat').animate(
                    {
                        width: '573px'
                    }, 1000, function() {
                        $(this).show();
                    }
                );
            }
        );
    });
});

... and the CSS:
#search {
    border: 1px solid #999999;
    -moz-border-radius: 5px;
    width: 573px;
    height: 40px;
    margin: auto;
    margin-top: 100px;
    margin-left: 0px;
    position: relative;
}

#go-chat {
    width: 575px;
    margin: auto;
    margin-top: 36px;
    margin-left: 0px;
    padding-top: 5px;
    white-space: nowrap;
}

#login {
    border: 0px;
    width: 0px;
    display: none;
    margin: auto;
    margin-top: 100px;
    margin-left: 0px;
    position: relative;
}

#go-search {
    width: 0px;
    margin: auto;
    margin-top: 36px;
    margin-left: 0px;
    padding-top: 5px;
    white-space: nowrap;
    display: none;
}

If anyone has suggestions on the way I formatted the jQuery, please let me know what you think... do you like the way I formatted? I feel like it looks a bit awkward.
Answer: $('#search').animate({width: '0'}, 1000, function(){
    $(this).hide();
});

The page kind of freaks out on toggle...mind your selectors.
Comment: Thanks. Now, how would I handle the slide effect... I want it to slide to the left, not the center as it is doing currently?
Comment: Probably you want to animate the position or margin simultaneously to the width:0 animation.

.animate({width: '0', left:'150px'});

Something like that.


How to write Riemann sums to find definite integral

Question: I'm doing a question where I need to prove that a function, $x^2 + 2x$ is Riemann integrable on the interval $[-3,3]$.
The question also gives me the interval $2n$, first $n$ intervals in $[-3,-1]$ with the width of $2/n$ and second $n$ intervals in $[-1,3]$ with the width of $4/n$.
I have already been given the suggested workings but I cannot seem to understand.
The workings given to me for lower Riemann are as follows:
$$
\sum_{i=1}^n f\left(-1-\frac{2i}{n}\right)\frac{2}{n}
+ \sum_{i=1}^n f\left(-1-\frac{4i}{n}\right)\frac{4}{n}
$$
Which ends at $18-\frac{36}{n}+\frac{12}{n^2}$ which equals to 18 when $n$ approaches infinity.
I can understand the intervals $\frac{2}{n}$ and $\frac{4}{n}$. But I cannot understand the brackets with $(-1-\frac{2i}{n})$ and $(-1-\frac{4i}{n})$.
Why is $-1$ the start and not $-3$?
Comment: I guess $f$ is the name of the function $x\mapsto x^2+2x$, The bracke are added probably to disambiguate the formulæ. It starts with $-1$ and ends with $-3$ – this doesn't change the sum.
Comment: Your sums are not correct
Comment: @hamam_Abdallah yea that's what I thought that's why I'm doubting the model answers. Yet it ends at the right answer that's why I'm so confused.
Answer: hint
If the function $ f $ is Riemann integrable at $ [a,b] $ then
$$\lim_{n\to+\infty}\frac{b-a}{n}\sum_{i=1}^nf(a+i\frac{b-a}{n})=\int_a^bf(x)dx$$
With $ (a,b)=(-3,-1) $, the sum becomes
$$\frac 2n\sum_{i=1}^nf(-3+i\frac 2n)$$
and with $ (a,b)=(-1,3) $, it gives
$$\frac 4n\sum_{i=1}^nf(-1+i\frac 4n)$$
Comment: Is this applicable to lower riemann sum?
Comment: @jeff What do you call "lower" Riemann sum.


Using Index for joining two tables when FK field is NULL

Question: We started to maintain a new project that uses SQL Server and there are some problems regarding to the data in some tables as explained below. There are 2 tables called Employee and Pass and the Pass table keeps the in and out of every Employee.
Employee
|| ID       || Name       || CardNo ||
======================================
|| 1        || John       || 101    ||
|| 2        || Christof   || 102    ||
|| 3        || Jurgen     || 103    ||
|| 4        || Jose       || 104    ||
|| 5        || Mary       || 105    ||

Pass
|| ID       || EmployeeID || CardNo ||
======================================
|| 1        || NULL       || 101    ||
|| 2        || NULL       || 105    ||
|| 3        || NULL       || 103    ||
|| 4        || NULL       || 101    ||
|| 5        || NULL       || 102    ||
|| 6        || NULL       || 104    ||
|| 7        || NULL       || 104    ||
|| 8        || NULL       || 103    ||
|| 9        || NULL       || 105    ||
|| 10       || NULL       || 101    ||

On the other hand, as the EmployeeID column of the Pass table is empty for every pass, we have to use CardNo column in order to join two tables.
But using the JOIN clause as shown below causes the query to be executed more time and I think there might be a better way by using index, etc. instead of PK to optimize the query. We have tried to create index, but could not create for CardNo column.
Could you please clarify us on how to fix the problem? Thanks...
SELECT *
FROM Pass p
LEFT JOIN Employee e ON RIGHT(e.CardNo, 8) = RIGHT(p.CardNo, 8) --I have to trim card no as the digit sizes are different

Update :
I tried to apply the following scripts, but only this part is worked:
alter table Pass add cardno8 as RIGHT(CardNo, 8);
alter table Employee add cardno8 as RIGHT(CardNo, 8);

And this part gives error: "Column 'cardno8' in table 'Pass' is of a type that is invalid for use as a key column in an index."
create index idx_tEvent_cardno8 ON Pass(cardno8);
create index idx_tEmployee_cardno8 ON Employee (cardno8);

Any idea?
Comment: "We have tried to create index, but could not create for CardNo field."  Why not?  Did you get an error?  I see no obvious reason that you couldn't create such an index.
Comment: "I have to trim card no as the digit sizes are different" - `pass.cardno` is not equal to corresponding `employee.cardno`? can you show an example?
Comment: Unfortunatela Card Numbers are saved 11 digit to Employee while it saved 10 digit to Pass table leading zeros. For this reason I had to take the last 8 digits of card numbers.
Comment: You probably have to `cast()` the `right()` function to an appropriate type.
Comment: Do you mean that I just cast the CardNo field in the query without changing it's data type from varchar to int? On the other hand should I create index that you suggested before? Thanks.
Comment: @GordonLinoff Any help please?
Answer: If the problem is the performance of the query, then you simply need an index on Employee(CardNo):
create index idx_employee_cardno on employee(cardno);

If you are interested in only one or two other columns (such as name or id), you can add them to the index after cardno.
The only reason that I can think of (apart from permissions) to explain why index creation would fail is that cardno has the wrong type.  To quote the documentation:

Columns that are of the large object (LOB) data types ntext, text,
  varchar(max), nvarchar(max), varbinary(max), xml, or image cannot be
  specified as key columns for an index.

That seems unlikely given the sample data.  If this is an issue, then change the type to something more appropriate (or use a computed column for the same purpose).
Also, your query should use qualified column names everywhere (or you'll get an error):
SELECT *
FROM Pass p LEFT JOIN
     Employee e
     ON e.CardNo = p.CardNo;
--------^

Comment: Many thanks for your helps. Actually this question is related to [Join multiple tables by multiple grouping](http://stackoverflow.com/questions/35668526/join-multiple-tables-by-multiple-grouping/35668881?noredirect=1#comment59019450_35668881) and I just cretae a separate ticket as the problem is different. So, I voted ıp your answer on that question, but unfortunately could not create index. On the other hand, you saw on that question that there is another problem that makes me forcing t use RIGHT function.
Comment: I updated my question above, could you please clarify me step by step on which procedures should I follow to solve this problem? Thanks...
Comment: You are right, the problem is actually datatype of CardNo field (Varchar). So, that mean if it was int, we could create index and use as FK, **is that true?**
Comment: @hexadecimal . . . I think any types other than the ones mentioned in the documentation are suitable for an index.


How to install KDiff3 version 1.9.4 on Ubuntu 20.04?

Question: How can i install / update KDiff3 version 1.9.4 on Ubuntu 20.04. I have installet Version 1.8.1 (64bit) and want update to the actuell version https://github.com/KDE/kdiff3
Answer: First of all, official kdiff3 page is at https://apps.kde.org/kdiff3/ .
Then about newer version. You can install Git-version 1.9.70~git20220123-1~focal1 from some third-party PPA using command below:
sudo add-apt-repository ppa:blaze/kf5
sudo apt-get update
sudo apt-get install kdiff3

If you do not like it, remove it with the PPA by
sudo apt-get install ppa-purge
sudo ppa-purge ppa:blaze/kf5

If you do not like PPAs, you can use 1.9.4 version from Flatpak as follows:
sudo apt install flatpak
flatpak remote-add --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo
flatpak install flathub org.kde.kdiff3

Comment: Works. Many thanks.


Text extraction from PDF with search criteria

Question: I need to extract text from a PDF, I have a list of keywords which tell me what text part I need to extract.
PDF looks something like this:

Schema element: Keyword1 This is my keyword

Fontsize: 14 I dont need this

Guide to complete schema element: Text text. This is the text I need and it can between 2 and 3 lines long. And even contain multiple sentences.

Schema element: Keyword2 This is my keyword

Fontsize: 18 I dont need this

Guide to complete schema element: Text text, this is the text I need and it can between 2 and 3 lines long. And even contain multiple sentences. This text is different from the text above.

This is my code so far:
library(pdftools)
library(pdfsearch)
library(tidyverse)
pdf <- pdf_text(dir(pattern = "*.pdf")) %>%
read_lines()
Keyword_list <- c("swDisproportionateCost", `"swDisproportionateCostOtherEULegislation", "swExemptionsTransboundary","swDisproportionateCostAlternativeFinancing","swDisproportionateCostAnalysis","swDisproportionateCostScale")`

Then I tried using keyword_search but it only told me which line the keyword was in.
I would like to extract the text in cursive into a new column in my keyword_list. I think it can be done with regex using the keyword and the text in bold as start and stops.
Here is a link to the pdf.
https://www.dropbox.com/s/kyyzr5wnh8z87if/FINAL%20Draft4_WFD_Reporting_Guidance_2022_resource_page.pdf?dl=0
Comment: where do you get the function pdf_text()?
Comment: Hi Rafn. This would certainly be possible, but we need to see the actual pdf. Is there a way you can add a link to it via dropbox or similar? Otherwise, this is like trying to shoot at a target blindfolded with someone just _describing_ where the bullseye is.
Comment: Hi @AllanCameron The text i search for is the word after Schema element and the text i need to extract is text after Guidance on completion of schema element in the corrosponding box in the PDF. I added some information in the post.
Comment: @Rafn thanks for posting the link. It would not have been possible to get the answer without this.
Comment: pdfminer.six is a great package for this in Python. @Rafn Is it an option for you to use Python with reticulate?
Comment: We do have Python as a tool to work with, though i have never used it.
Answer: This is just a rather pedestrian text extraction job. There are many ways to do it, and I'm sure there are more elegant ways to do it than this, but this one does the job:
library(pdftools)
library(dplyr)

keywords <- pdf_text("mypdf.pdf") %>%
strsplit("Schema element:") %>%
  lapply(function(x) x[-1]) %>%
  lapply(function(x) sapply(strsplit(x, "\r\n"), `[`, 1)) %>%
  unlist %>%
  trimws()

text <- pdf_text("mypdf.pdf") %>%
  strsplit("Guidance on completion of schema element:") %>%
  lapply(function(x) x[-1]) %>%
  lapply(function(x) sapply(strsplit(x, ":"), `[`, 1)) %>%
  lapply(function(x) sapply(strsplit(x, "\r\n"),
                            function(y) paste(y[-length(y)], collapse = ""))) %>%
  unlist() %>%
  {gsub("  ", " ", .)} %>%
  trimws() %>%
  strsplit("Guidance on contents") %>%
  sapply(`[`, 1)

df <- tibble(keywords, text)

So the result looks like this:
df
#> # A tibble: 15 x 2
#>    keywords                       text
#>    <chr>                          <chr>
#>  1 swExemption44Driver            "Required. Select from the enumeration list the driver~
#>  2 swExemption45Impact            "Required. Select from the enumeration list the impact~
#>  3 swExemption45Driver            "Required. Select from the enumeration list the driver~
#>  4 swDisproportionateCost         "Required. Indicate if disproportionate costs have bee~
#>  5 swDisproportionateCostScale    "Conditional. Select from the enumeration list the  sc~
#>  6 swDisproportionateCostAnalysis "Conditional. Select from the enumeration list the  an~
#>  7 swDisproportionateCostAlterna~ "Conditional. Select from the enumeration list the  al~
#>  8 swDisproportionateCostOtherEU~ "Conditional. Indicate whether the costs of basic  mea~
#>  9 swTechnicalInfeasibility       "Required. Report how 'technical infeasibility' has be~
#> 10 swNaturalConditions            "Required. Select from the enumeration list the  eleme~
#> 11 swExemption46                  "Required. Select from the enumeration list the reason~
#> 12 swExemption47                  "Required. Select from the enumeration list the  modif~
#> 13 swExemptionsTransboundary      "Required. Indicate whether the application of  exempt~
#> 14 swExemptionsReference          "Required. Provide references or hyperlinks to the  re~
#> 15 driversSWExemptionsReference   "Required. Provide references or hyperlinks to the  re~

Comment: Hi @Allan Cameron

I am getting an error:  Error in strsplit(x, "\r\n") : non-character argument.

I added a new link to the full PDF, i thought it was confidential but apparantly it's not.
Your code worked on the 4 pages i sent you first, but it doesn't work on the full PDF.
Comment: @Rahl I wouldn't expect it to work on a different pdf. Text parsing requires knowledge of the exact document you are trying to parse, which is why I asked you to include a link to the pdf you wanted parsed. Effectively, I have wasted my time parsing a document you didn't need parsed!
Comment: Sorry that was my mistake thinking i was working with a confidential report. It was my understanding that these scripts could be translated to work on similar jobs, but i will try and rework your code so it fits. Thank you very much for your time.
Comment: Hi @Allan Cameron could you by any chance help me with a expansion of this problem in this thread https://stackoverflow.com/questions/62650928/how-do-i-extract-text-from-pdf-and-add-to-df-in-r?


how to get the top 10 countries based on no. of occurence in excel column

Question: I have a excel sheet like this
<code>       _____________________________________________________
       |        A             B               C     |   D   |
|-----------------------------------------------------------|
|  1   |      Device   |    Country    |            |       |
|-----------------------------------------------------------|
|  2   |      Android  |     iNDIA     |            |       |
|-----------------------------------------------------------|
|  3   |      aNDROID  |     India     |            |       |
|-----------------------------------------------------------|
|  4   |      Android  |   Bangladesh  |            |       |
|-----------------------------------------------------------|
|  5   |      Android  |    Pakistan   |            |       |
|-----------------------------------------------------------|
</code>
Now I India has two occurence, Pakistan has 1 occurence and Banglasdesh too has one ocuerence
I just want is that the top 10 countries(based on their occuerences) will be listed along with their occuerneces
C will have top 10 countries and D will have no. of their ocurences.
How can i acheive that
EDIT: I am very weak at excel sheet, any idea will be helpfull. I know how to write formula in the formula bar, just tell me what formula shall i write
Answer: Pivot tables are extremely useful in your circumstance. Put Country into Row field and Country again into Values field - you can sort by largest to smallest


Capistrano restarts wrong version of puma when upgrading ruby version and puma

Question: I'm upgrading a Rails application, deployed with capistrano and running puma, from ruby  2.2.0/puma 3.2 to ruby 2.3.1/puma 3.4.  When I deploy puma seems to be restarting in the wrong version.
Before my deploy, Puma is running under pid 4717 / version 3.4
vagrant@vagrant-master:/mnt/code/shared/tmp/pids$ ps -ef | grep -i puma
vagrant   4717     1  0 20:53 ?        00:00:00 puma 3.4.0 (unix:///mnt/code/shared/tmp/sockets/code-puma.sock) [20160510205039]
vagrant   4720  4717 12 20:53 ?        00:00:10 puma: cluster worker 0: 4717 [20160510205039]

When I deploy the old version (puma 3.2 / Ruby 2.2.0), puma restarts, its now running under pid 5466:
vagrant@vagrant-master:/mnt/code/shared/tmp/pids$ ps -ef | grep -i puma
vagrant   5466     1  0 20:56 ?        00:00:00 puma 3.4.0 (unix:///mnt/code/shared/tmp/sockets/code-puma.sock) [20160510205440]
vagrant   6154  5466  0 20:56 ?        00:00:00 puma: cluster worker 0: 5466 [20160510205440]

And my puma error log shows that its running 2.3.1 instead of 2.2.0
/usr/local/rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/bundler-1.12.3/lib/bundler/spec_set.rb:95:
in `block in materialize': Could not find active_attr-0.8.5 in any of the sources (Bundler::GemNotFound)

However, it should have switched to Puma 3.2/ruby 2.2.0.  When I force kill puma, it restarts (via monit) with the correct version (Puma 3.2 in this case)
vagrant@vagrant-master:/mnt/code/shared/tmp/pids$ kill -9 5466

vagrant@vagrant-master:/mnt/code/shared/tmp/pids$ ps -ef | grep -i puma
vagrant  17834     1  0 21:04 ?        00:00:00 puma 3.2.0 (unix:///mnt/code/shared/tmp/sockets/code-puma.sock) [20160510205440]
vagrant  17837 17834 90 21:04 ?        00:00:01 puma: cluster worker 0: 17834 [20160510205440]

The relevant lines from the deploy log:
DEBUG [07f95004] Running /usr/bin/env [ -f /mnt/code/shared/tmp/pids/puma.pid ] as vagrant@vagrant-master
DEBUG [07f95004] Command: [ -f /mnt/code/shared/tmp/pids/puma.pid ]
DEBUG [07f95004] Finished in 0.007 seconds with exit status 0 (successful).

DEBUG [42d98483] Running /usr/bin/env kill -0 $( cat /mnt/code/shared/tmp/pids/puma.pid ) as vagrant@vagrant-master
DEBUG [42d98483] Command: kill -0 $( cat /mnt/code/shared/tmp/pids/puma.pid )
DEBUG [42d98483] Finished in 0.007 seconds with exit status 0 (successful).

INFO [e81875a3] Running RBENV_ROOT=/usr/local/rbenv RBENV_VERSION=2.2.0 /usr/local/rbenv/bin/rbenv exec bundle exec pumactl -S /mnt/code/shared/tmp/pids/puma.state restart as vagrant@vagrant-master
DEBUG [e81875a3] Command: cd /mnt/code/current && ( export PATH="/usr/local/rbenv/shims:/usr/local/rbenv/bin:$PATH" RBENV_ROOT="/usr/local/rbenv" RBENV_VERSION="2.2.0" RACK_ENV="vagrant" ; RBENV_ROOT=/usr/local/rbenv RBENV_VERSION=2.2.0 /usr/local/rbenv/bin/rbenv exec bundle exec pumactl -S /mnt/code/shared/tmp/pids/puma.state restart )
DEBUG [e81875a3]    Command restart sent success

Here is part of my puma config in capistrano
set :puma_bind,       "unix://#{shared_path}/tmp/sockets/#{fetch(:application)}-puma.sock"
set :puma_state,      "#{shared_path}/tmp/pids/puma.state"
set :puma_pid,        "#{shared_path}/tmp/pids/puma.pid"
set :puma_preload_app, false
set :puma_prune_bundler, true

How can I deploy ruby-version and puma-version changes without having to kill the puma process?  Why does puma start with the wrong version?
Thanks
Comment: cap puma:halt puma:start seems to do the trick for getting puma restarted, but its not seemless
Comment: FWIW, running bundle exec cap puma:restart or bundle exec cap puma:phased-restart does not help - it still is running the wrong version after executing those commands.
Answer: Check if puma.rb config file is specifying puma.pid and puma.state paths:
pidfile '/mnt/code/shared/tmp/pids/puma.pid'
state_path '/mnt/code/shared/tmp/pids/puma.state'

Also check if deploy/production.rb is specifying that paths to:
set :puma_state,      "#{shared_path}/tmp/pids/puma.state"
set :puma_pid,        "#{shared_path}/tmp/pids/puma.pid"

I had a similar problem, and after setting this it worked well.
Comment: I have both those set - generally deploys restart puma workers just fine, but upgrading ruby and puma did not.


Grails start two in-memory databases for dev/test?

Question: Is there a way to start up two in-memory databases with grails? Specifically, I'd like to integration test my ETL process and allow reporting to be runnable in both development and test environments.
Answer: You should be able to do this with the Datasources Plugin
Comment: Any datasource listed in datasources as 'memory' gets started automatically.


Can I get 120 from a leg of 240 in this setup

Question: Similar questions have been asked but not exactly.
This is a 240V fuse box that the air conditioner installers recently put in. It has 2 legs of 120 and a ground wire coming from the junction box.
Is there a straightforward way to get a 120 VAC connection from this fuse box without doing anything shady? I need this to connect a sprinkler timer--there are no functioning 120 outlets within 100 ft.
I know that I could cut the plug off the sprinkler timer cable, run it into the fuse box and tie it between one of the legs and ground. But I don't know how kosher that would be.
The 3 photos below illustrate my setup.
Edit to address some of the comments:
I added 2 pictures of the back of the junction box. It appears to have a safety ground screwed to it. I also checked continuity between the green wire (apparently connected to neutral) and the safety ground of a plug in the house. This neutral wire is not isolated from ground. It is shorted.
I also got a picture of the inside of the fuse box door, with a bonus shot of my shiny head.
Comment: At first read, this thing is choc-a-bloc with code violations.  Why not use or tap the existing 120V outlet that Code absolutely requires to be installed near the air conditioning unit (so the installer can run a vampire pump to recover coolant)?
Comment: What's behind that hole in the wall? conduit, or something else? Any chance you could pull an additional wire into that junction box?
Comment: Can you upload a picture of the inside front door label? It references ground and neutral and may be critical to figuring this out.
Comment: Can you get us a photo clearly showing the back of the box the conduit run originates in, please?
Comment: @LShaver: All I can say for sure is junction box with apparent safety ground connected. See added photos
Comment: @ manassehkattz: You were sure right about that. I added a photo.
Comment: @ ThreePhaseEel: Yes. added.
Comment: @Harper-ReinstateMonica -- because that 120V serviceperson's outlet is nowhere to be found...
Comment: @mtp -- can you post a photo of the nameplate on your A/C's outdoor unit please?
Comment: @Harper-ReinstateMonica was just having this discussion... where in the code would I find this requirement?
Comment: @LShaver NEC 210.63.
Comment: Can you find anywhere inside where that original cable jacket can be seen?  I want to know a) what the insulating jacket type is (UF, NM, SE, SE-R, several possibilities), b) whether it is copper or aluminum, and c) the wire size in AWG.
Answer: Yes it can be done not even a tough conversion.
I would make some minor changes and change that outside box into a breaker panel.
A simple 4 slot nema R3 (outside rated) would work.
You have a real ground in the back of the box.
Make sure that neutral is going to the main panel along with the ground. .
This new sub panel allows for your breaker and disconnect right there outside.
The other breaker is for the service receptacle.
Now that there is a breaker that is a separate circuit according to code.
I have this same setup but I have lockouts on my 2 double pole breakers so no disconnects are required as my breakers having lockouts are legal.
My systems were installed prior to 240v requiring GFCI you will need a double pole GFCI to meet current code if on 2021 NEC.
GFCI receptacle & heavy duty cover. In a bell box create your service receptacle.
The white is the neutral. The black & red are hot and the ground is ground. On the sub the neutral has to be isolated
That's not only how I would do it but how I have done it at my personal home and customers, a small sub and GFCI breaker.
No need to run 100' of wire.
Answer: You've got a couple of different issues involved:
Is that Ground or Neutral?
Green = Ground. Not two ways around that. However, in the wall junction you have white (neutral) connecting to the green that goes to this disconnect. Assuming the wiring is: Panel inside the wall -> wall junction -> fuse box -> A/C, then the green wires here are actually neutral! Which is a very good thing.
If indeed these green wires are actually neutral, then you should be able to switch them for white wires (both the short piece to the wall junction and a longer piece to the A/C). In addition, there may be a change in how the wires are connected inside this box - it is not clear and we need additional details, such as the full label from the door, to figure that out.
If the installers used green here because they don't need neutral for the A/C but do need ground, then the (a) you can add a separate white neutral wire and (b) connect the green wire at the junction box to an actual ground wire.
The good news is that your wires are in conduit. So adds/changes are not a big deal. The really good news is that your wires are in metal conduit. If that is the case end-to-end and installed properly then you likely do not need any ground wires at all and can safely replace green with white instead of having to add a totally new wire.
Can you add to this circuit?
Generally speaking, a large installed appliance (like an air conditioner) has a circuit of its own. Adding a small additional 120V load (like the sprinkler timer) may or may not be permitted, depending on the size of the loads, the size of the circuit and the instructions provided with the sprinkler timer.
On the other hand, your wires are in conduit. You can probably (depends on conduit size) simply add an additional hot/neutral pair of wires to the same conduit, connect them to a separate breaker (typically 15A or 20A) in the panel and connect them to the sprinkler timer.

Update based on additional details in Question:
This appears to be a DiversiTech DDS-30 or similar.
As I understand the label, it is referring to use of this disconnect box as "Service Equipment" - i.e., the first box after the meter as a disconnect/master fuse. In that situation, like a typical "main panel", neutral and ground are one and the same.
However, when used any place else, ground and neutral need to be kept totally separate.
In this particular case, it appears that the middle screws with the green wires are (a) for ground, not neutral and (b) bonded to the case. If that's true, then it should not be used for neutral. An ordinary shutoff/disconnect doesn't need to bother with neutral - neutral gets to just pass through.
Unfortunately, I couldn't find much additional information on the DiversiTech site. My hunch - but hopefully an HVAC pro or electrician can confirm - is the following:

The box requires ground but does not require neutral.
Since it is a metal box and metal conduit, ground can be provided via the conduit itself, but can be done using green wire.
The green wire absolutely should not be connected to the white wire (in the wall junction box).
The green wire (unless removed) should be connected with a screw to the wall junction box to provide a continuous ground and must be disconnected from the white wire.
If the HVAC actually needs a neutral (i.e., has any 120V components) then a white wire should be connected to the white wire in the wall junction box and pass through (either as one long wire or split and joined with a wire nut in the disconnect box) the disconnect box to the HVAC equipment.
If the green is connected to anything other than ground/metal case on the HVAC equipment then it needs to be disconnected.

The way to tell for sure whether the HVAC actually needs a neutral connection is model #s or wiring diagram.
Comment: Thanks for this extensive answer. Please see my updates when you have a moment.
Answer: Fuggedaboutit, for a bunch of reasons. But let's start with the deal killer.
You can't put a receptacle on a dedicated hardwired appliance circuit
Anytime you have a large appliance circuit like that, with a hardwired load, you cannot fit receptacles on that circuit if the hardwired load accounts for more than 50% of circuit ampacity. And it always does because large appliances are expected to have dedicated circuits.
So it wouldn't even matter if the receptacle was 240V.
It's too bad your thing isn't 240V and hardwired... if so it could share this circuit.
It's moot anyway, because of the next change you must make.
Since you said this is recent work, it must comply with recent codes which  require a 120V convenience receptacle near the heat pump unit.  As discussed above, this must be on a separate circuit.
This is normally done as part of the normal outdoor receptacle wiring that houses are supposed to/obliged to have.
So once you correct that deficiency, you can plug your appliance in there.
... and there's an easy way to do that.
EDIT: OK, so I had it wrong.  I thought you had conduit; you actually have a 4-conductor cable.  But "It's still good!" the cost just went up a little bit.
You need an air conditioning disconnect right where you have one.  Fusing isn't required, but it is allowed.  A funny thing about a *subpanel - while it is many things, it is also a disconnect.
So since you have 4 wires coming here, we need to change that A/C disconnect out to be a sub panel.  That will allow us to support both the air conditioner and the required 120V receptacle.
3 breaker spaces needed - 2 for the A/C and 1 for the 120V receptacle.  Note that you could get this done with a "2-space, 4-circuit" panel, using a 30/20 quadplex.  Or you could go with a larger panel, like a 6-space, 12-space or even 40-space... it's completely at your discretion.  I would think about the size of the supply wires vs the size of the loads, think about what else you could support out here, and "err on the large side".  Let's presume 6-space.
The sub panel must have isolated neutral and ground, and its own ground bus.

How to make that work at the wall surface? Fairly straightforward.  Get an outdoor rated "extension box" that bolts over top of the existing box using the existing mounting screws.., and has 1/2" knockouts or fittings on the side.
Replace the one conduit with two conduits that go straight into the side of the extension box.  One for the feeder to the sub panel, the other to come back to serve a receptacle (or two) mounted in the extension box.
Extend hots, neutral and ground from this box to the sub panel's two hot lugs, neutral lug and ground lug. The hots+neutral must be in the same conduit. Safety ground can go through the other conduit, since it doesn't normally carry current.
As far as wire size, see my followup question about type, metal and size of old cable in the walls.
Now, hook up the A/C 2 hots to the breaker, and ground to the ground bar.
Now, get black, white, green #12 THHN, fit a receptacle in the extension box, and run to the 15A breaker, neutral and ground. Use the conduit that the #8 feeder did not use.
In fact,  you could use a 2-gang extension box, and fit two receptacles side by side (in a domed cover).  They could each be on different 120V circuits, since you can have up to 4 circuits in the pipe that is not being used by the feeder.
Comment: I suspect that that *is* a cable (you can see the jacket on it in the very last shot), but a SER type cable, which means they could quite readily fit a subpanel in place of the A/C disconnect...
Comment: That would be much better.  How about you take that one? :)
Comment: That cable looks a lot bigger than the wires going to/from the disconnect. So if the wires to/from the disconnect are 10 AWG then the cable has to be at least 8 AWG - upbreaker and subpanel.


Removing Scotch tape residue

Question: Scotch tape and residue were gently scraped off the outdoor facing side of a wooden white door.  I would like to completely remove the residue.
Is there a clever method / tool / chemical to remove the residue without damaging the white paint?
Comment: Probably depends on the kind of white paint, what would work in your situation.
Answer: I've had good success with WD-40 or similar product.  For really stubborn residue there is this stuff that often works where others don't:
https://www.amazon.com/Original-Formula-Sticker-Remover-California/dp/B003TZQPTS/ref=asc_df_B003TZQPTS
Comment: Sticker remover (not this particular brand) is my go to solvent for these kinds of residues, however I'm not sure if it'll discolour the white paint. I would test this on the side of the door first, somewhere less visible. And the trick is probably in applying it briefly in a rubbing motion, to maximise its effectiveness while minimising its contact with the paint.
Comment: @jwh20  Thanks for the reply.  Have you tried the AMZN product cited?
Comment: I have.  My wife uses it in her scrapbooking and I borrow it sometimes.  It sometimes works on those very stubborn residues.
Comment: Almost forgot, I use rubbing alcohol immediately afterward to remove any remaining sticker remover. This stuff can melt certain kinds of plastic (PP comes to mind), I'm sure extensive prolonged exposure would damage a fair number of materials.
Answer: Goo-Gone or Goof-Off are popular choices but good ol' Windex works impressively well for sticker residue.
As always, test in an inconspicuous location first!!!
Also, you might find that the cleaned area is cleaner than then rest of the door.

Removing Scotch tape residue


How can I define an abstract odd function in mathematica? With respect to derivatives

Question: I want "to work symbolically" but not only with function but with derivatives. For instance I would like
f'[x] - f'[-x]

to be simplified to zero.
Comment: Neither of the ways, suggested here, did not help me.
Answer: They kind of works but now you need to create rules for Derivative not to f really. And since Derivative is not even protected you can do something like:
Derivative[n_][f][-x_] := -Derivative[n][f][x]

f''[x] + f'''''''[-x] + f''[-x] + f[x] + f'''''''[x]

f[x]

is this ok?
Comment: @quinque by all you mean all degrees?


Pycord - how to make SubCommands or SlashCommands Groups?

Question: Can you tell me if there is a way to create subcommands or groups of slashcommands?
I found on the docs here this: "class discord.ext.bridge.BridgeCommandGroup(callback, *args, **kwargs)" but I do not understand how to use it. Do you have an example for me?
Thank you!
My goal was to create a command
/ticket
command with the following subcommands:
/ticket open
/ticket close
/ticket config
/ticket add_person
but for the moment I made a SlashCommand for each command.
Comment: Please provide enough code so others can better understand or reproduce the problem.
Answer: The class you've mentioned, BridgeCommandGroup, appears to be a class that allows running both traditional and slash commands in the same function. Slash Command Groups are somewhat an entirely separate matter, as they do not allow execution of traditional commands from its collection of slash commands.
For your main question, Slash Command Groups can be made inside a Cog file or in your main bot file.
Slash Command Groups are fairly simple to implement in PyCord.
In Main Bot File
bot = discord.Bot()
foo = bot.create_group("foo", "This does something...")

bot.add_application_command(foo) #add the group of functions to the bot

In Cog Class:
#in the class "Baz"
bar = discord.SlashCommandGroup("bar", "This does something else...")

@bar.command(name="ping") #assign the command under the SlashCommandGroup
async def ping(self, ctx):
    await ctx.respond("pong")

#outside Cog class
bot.add_cog(Baz(bot))

This sample shows creating instances of Slash Command Groups. As for subgroups, they can be implemented from the main Slash Command Groups themselves.
foo = discord.SlashCommandGroup("foo", "Group 1")
bar = foo.create_subgroup("bar", "Group 2 of Group 1")
# the bar group gets assigned under foo, our first slash command group

More information on creating slash commands can be found in the docs.
create_group()
discord.SlashCommandGroup


Conditions for $\sqrt{\mathfrak{a + b}} = \sqrt{\mathfrak{a}} + \sqrt{\mathfrak{b}}$

Question: Let $A$ be a commutative ring with identity and, $\mathfrak{a}$ and $\mathfrak{b}$ ideals.I'm trying to find sufficient and necessary conditions for  $\sqrt{\mathfrak{a + b}} = \sqrt{\mathfrak{a}} + \sqrt{\mathfrak{b}}$ holds. I think that it holds for any UFD. I could not find any counter-example (for any ring) nor prove the reciprocal for the UFD assertion above.
Thanks in advance.
Comment: The product of ideals $\frak{ab}$ is the ideal whose elements are finite sums of elements of the form $ab$ for $a \in \frak{a}, b \in \frak{b}$. The radical of an ideal $\sqrt{\frak{a}}$, is the ideal of all elements $x$ such that $x^n$ is in $\frak{a}$ for some positive integer $n$.
Comment: @JoeZeng $\mathfrak{a}$ and $\mathfrak{b}$ are ideals!!Not numbers.
Comment: @JoeZeng the square root means the radical
Comment: For that matter, what does the square root of an ideal even mean?
Comment: I know. That ended up confusing me.
Answer: The question is whether the sum of two radical ideals is radical. In general this is far from being true, for example we have $(y)+(x^2-y)=(x^2,y)$ in $k[x,y]$.
There is an algebro-geometric explanation for this: If $I,J$ are radical ideals of a commutative ring $A$, this means that we have reduced subschemes $V(I)$ and $V(J)$ of the affine scheme $\mathrm{Spec}(A)$, but their intersection $V(I) \times_{\mathrm{Spec}(A)} V(J) = V(I+J)$ doesn't have to be reduced. In the above example we intersect the parabola $y=x^2$ with the axis $y=0$, this gives a point of multiplicity $2$.
It seems plausible that $V(I+J)$ is reduced iff $V(I)$ are $V(J)$ are transversal iff the intersection multiplicities are $\leq 1$ (whenever these notions are well-defined, for example for smooth curves).
Some observations in the positive direction:
Lemma. Let $A$ be a commutative ring. If every localization of $A$ has the property that the sum of two radical ideals is radical, then this also holds for $A$.
Proof. Let $\mathfrak{a},\mathfrak{b} \subseteq A$ be radical ideals, we have to show that $A/(\mathfrak{a}+\mathfrak{b})$ is reduced. This is well-known to be a local property. Quotients and sums of ideals commute with localizations. Besides, the localization of a radical ideal is easily seen to be a radical ideal. QED
Proposition. In a $1$-dimensional integral domain the sum of two radical ideals is radical.
Proof. By the Lemma we may assume that $A$ is local, say with maximal ideal $\mathfrak{m}$. The only prime ideals are $0$ and $\mathfrak{m}$, so these are only the only radical ideals. But these are obviously closed under sum. QED
For rings with zero divisors this fails.
Example. Let $k$ be a field and $A = k[x,y]/(y(x^2  - y))$. We have $\dim(A)=1$. The quotients $A/(y)=k[x]$ and $A/(x^2-y)=k[x,y]/(x^2-y)$ are reduced, but $A/(y,x^2-y)=k[x]/(x^2)$ is not.
I doubt (but cannot prove) that there is any $2$-dimensional finitely generated $k$-algebra with the property.
Comment: Well, suppose $R$ is an integral domain such that every monic polynomial from $R[X]$ has a root in $R$.  (These are called ``absolutely integrally closed'' domains.  Taking the integral closure of any domain in an algebraic closure of its fraction field will produce such a ring.)  Then M. Artin showed in 1971 that for any $p, q \in \Spec R$, $p+q$ is either prime or equal to $R$.  I imagine that any such domain should satisfy the property, and if $A$ is any 2-dim domain and $R$ the int closure of $A$ in $L=\bar{K}$, $K = frac(A)$, then $R$ is certainly 2-dimensional.
Comment: The result which @neilme is referring to is shown in the paper "On the Joins of Hensel Rings" if you are curious.
Comment: Nice answer!  Do you know of any example of a $2$-dimensional domain for which the result holds?
Comment: Unfortunately not.
Comment: Thanks, nice answer, I need a time to digest it.
Comment: Take any 2-dimensional valuation ring $A$. Then $A$ is a domain, and its ideals are totally ordered by inclusion. That is, $\mathfrak{a}$ $\subseteq$ $\mathfrak{b}$ or $\mathfrak{b}$ $\subseteq$ $\mathfrak{a}$.
Comment: I think we also want a finitely generated $k$-algebra.
Answer: If $A$ is a commutative ring, one clearly has $\sqrt{\mathfrak{a + b}} = \sqrt{\mathfrak{a}} + \sqrt{\mathfrak{b}}$ for all ideals $\mathfrak{a},\mathfrak{b}\leq A$ if and only if $\sqrt{aA + bA} = \sqrt{aA} + \sqrt{bA}$ for all $a,b\in A$. For, assuming the latter, if $z\in\sqrt{\mathfrak{a + b}}$, then $z^{n}=a+b$ for some $a\in\mathfrak{a}$, $b\in\mathfrak{b}$,  $n\in\mathbb{N}$, so that $z\in\sqrt{aA + bA}=\sqrt{aA} + \sqrt{bA}\subseteq\sqrt{\mathfrak{a}} + \sqrt{\mathfrak{b}}$.
It follows that any $A$ can be embedded in a ring in which the radical ideals are closed under taking sums. Indeed, let $\widetilde{A}$ be the quotient of the polynomial ring $A[X_{\tau},Y_{\tau},S_{\tau},T_{\tau}]$, where $\tau$ runs over all triplets $(a,b,z)\in(A-\{0\})^{3}$ with $z\in\sqrt{aA+bA}$, modulo the ideal generated by the elements $z-X_{\tau}-Y_{\tau},X_{\tau}^{2}-aS_{\tau},Y_{\tau}^{2}-bT_{\tau}$ for all $\tau$. Then $A\subseteq\widetilde{A}$, and for all $\tau=(a,b,z)$ in $(A-\{0\})^{3}$ with $z\in\sqrt{aA+bA}$ in $A$, we have $z=X_{\tau}+Y_{\tau}$ with $X_{\tau}\in\sqrt{a\widetilde{A}}$ and $Y_{\tau}\in\sqrt{b\widetilde{A}}$ in $\widetilde{A}$. Letting $A_{0}:=A$ and $A_{n+1}:=\widetilde{A_{n}}$ for all $n$, we obtain a ring $B:=\bigcup_{n}A_{n}$ containing $A$, in which the set of radical ideals is closed under addition. Moreover, $B$ is a domain iff $A$ is.
Additivity of radicals holds for Prüfer domains $A$, but these are generally not Noetherian (if $A$ is Prüfer and Noetherian, then dim$(A)\leq 1$, so $A$ is just a Dedekind domain or a field). However, for domains, being Prüfer is much stronger than having all sums of radical ideals being radical: simply consider rings such as the $B$ described just now.
If $A$, domain or not, is of finite type over a field $k$ and dim$(A)\geq 2$, then by Noether Normalization there exist $x,y\in A$ which are algebraically independent over $k$. With $x$ and $y$ carefully chosen, the counterexample given by Martin can be replicated - that is, we can have $yA$ and $(x^{2}-y)A$ radical ideals of $A$ with $x\notin yA+(x^{2}-y)A=(x^{2},y)$.