text:
Q: What is 'tilt locking' of a laser cavity? In another question, jasonh mentions a scheme for locking a laser to a resonant cavity called 'tilt locking':

The signal is used for locking the frequency of a laser to a high finesse cavity. The lock has to be stable enough for intensity and phase fluctuations resulting from e.g. acoustic vibrations of the cavity to be strongly suppressed. The error signal is created via the tilt locking scheme, i.e. it is the difference of intensities on two halves of a split photo diode.

I'm familiar with Pound-Drever-Hall locking of a laser cavity, but I've never heard of 'tilt locking' before. How does it work?

A: Consider an optical cavity whose length you want to stabilize such that the cavity stays on resonance with the TEM00 mode of a laser. The basic idea of the tilt locking scheme is to use the phase of an off-resonant mode (TEM10) as a stable phase reference to which the changes in phase of the resonant part (TEM00) of the beam can be compared.
To expand a bit: Also very close to the cavity resonance some part of the TEM00 light is going to be reflected. The phase of this near-resonant light depends extremely sensitively on the exact cavity length (note that here and in what follows I always talk about the phase of the light reflected from the cavity). The phase actually changes sign on resonance so in principle the phase of the reflected TEM00 component could be used as an error signal which--if stabilized to zero using a feedback loop--would keep the cavity on resonance with the TEM00 of the laser.
Unfortunately, you can only measure the phase of the near-resonant mode by comparing it to a stable phase reference in an interferometric measurement. In the tilt locking scheme the TEM10 mode provides you with this phase reference. In most cavities, the TEM10 and TEM00 modes are not resonant simultaneously because of the difference in Gouy phase. Hence, if TEM00 is resonant, TEM10 is off-resonant which means that its phase is very insensitive to the exact cavity length.
To perform the required interferometric measurement you need a split photo diode which is simply a photo diode with two halves, left and right. A split photo diode can detect the intensity of the incoming light on both halves separately plus a circuit which yields the intensity on the left half minus the intensity on the right half. The rest is most easily understood by looking at the picture on page 4 of these nice slides on tilt locking: www.ligo.caltech.edu/docs/G/G000276-00.pdf.
If the beam which is reflected from the cavity is focused onto such a split photo diode the situation is as follows: TEM10 has a positive phase on, say, the left and a negative phase on the right half of the split photo diode. TEM00 on the other hand is completely symmetric and has approximately the same phase in the whole detection area. If TEM00 is exactly on resonance, its phase is zero so that the combined contributions of TEM00 and TEM10 yield the same intensities on both halves, hence the difference is zero.
If TEM00 goes off resonant its phase is not zero anymore. Assume it's positive. Then the light fields of TEM00 and TEM10 are going to interfere constructively on the left half (where also TEM10 has a positive phase) and destructively on the right half (where TEM10 is negative) so that the difference in intensities is positive and the split photo diode produces a positive output voltage.
If on the other hand, the cavity length (or laser frequency) fluctuates in the other direction, TEM00 will acquire a negative phase which means that constructive interference with TEM10 now happens on the right half of the detector and destructive interference on the left half. In this case the split photo diode will produce a negative output voltage.
Hence, the output voltage of the split photo diode can be used as an error signal. From here on everything works the same way as in a Pound-Drever-Hall lock. Advantage: no need for modulation of the laser beam; you only need to make sure that you're not aligning the beam too perfectly to the cavity so that some TEM10 component is present in the reflected beam. Problems may arise due to the high sensitivity of the error signal on the exact location of the beam on the split photo diode; hence, the photo diode should be fixed well and you should not introduce optical components before the split photo diode which may cause significant beam wander.


text:
Q: T[keyof T] cannot be used to index {} I am trying to implement an efficient group by alogrithm from Most efficient method to groupby on an array of objects and trying to put the types. But I get the error:
T[keyof T] cannot be used to index {}

Here is my attempt
 static groupBy<T>(xs:T[], key: keyof T) {
        return xs.reduce((rv, x)=> {
            (rv[x[key]] = rv[x[key]] || []).push(x);
            return rv;
        }, {});
    };

A: rv: any rv will be any.
class A {
  static groupBy<T>(xs: T[], key: keyof T) {
    return xs.reduce((rv: any, x) => {
      (rv[x[key]] = rv[x[key]] || []).push(x);
      return rv;
    }, {});
  }
}

How to use it:
interface Person {
  name: string;
  age: number;
  salary: number;
}
const data: Person[] = [
  {name:"deepak", age: 30, salary: 2000},
  {name:"deepak1", age: 32, salary: 1000},
  {name:"deepak", age: 29, salary: 3000}
]
class A {
  static groupBy<T>(xs: T[], key: keyof T) {
    return xs.reduce((rv: any, x) => {
      (rv[x[key]] = rv[x[key]] || []).push(x);
      return rv;
    }, {});
  }
}
console.log(A.groupBy(data, "name"))

Defination from Lodash:
groupBy(
            predicate?: Lodash.ListIterator<T, boolean> | Lodash.DictionaryIterator<T, boolean> | string,
            thisArg?: any,
        ): Lodash.Dictionary<T[]>;
        groupBy<R extends {}>(predicate?: R): Lodash.Dictionary<T[]>;

Sync group return an object and object cant have any other element as key other than string|number. Else you can follow more genric solution.
interface Any<T> {
  [key: string]: T[];
}
interface SMap<T> {
  [key: string]: T;
}
class A {
  static groupBy<T extends SMap<string>>(xs: T[], key: keyof T) {
    return xs.reduce((rv: Any<T>, x) => {
      if (!rv[x[key]]) {
        rv[x[key]] = [];
      }
      rv[x[key]].push(x);
      return rv;
    }, {});
  }
}

A: if you don't want to use any, you need properly define types to tell that reducer can combine data.
function groupBy<T extends {[LK in K]: keyof any}, K extends keyof T>(xs:T[], key: K) {
  return xs.reduce<{[LK2 in T[K]]?: Array<T>}>((rv, x) => {
            (rv[x[key]] = rv[x[key]] || [])?.push(x);
            return rv;
        }, {});
};

const result = groupBy([{ test: 'key' }], 'test');

result.key?.length; // 1

T is an object where type of passed key is something that can be used as a key (for rv).
for reducer - it starts with an empty object - we need to says that result will be an object where value of the key is an array of entities from the xs {[LK2 in T[K]]?: Array<T>}

A: Not as short as the original. However, it does not use "any" or "as" casting. It also supports any data type for the group key, hence, unknown.
export function groupBy<T>(xs: T[], key: keyof T): Map<unknown, T[]> {
  return xs.reduce((rv: Map<unknown, T[]>, entity: T) => {
    const value = entity[key];
    if (rv.has(value)) {
      rv.get(value)?.push(entity)
    } else {
      rv.set(value, [entity]);
    }
    return rv;
  }, new Map());
};

example of usage:
const badgesByTypes = groupBy(currentState.badges, 'type');
for (const [key, values] of badgesByTypes.entries()) {
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: In password reset view custom templates not loading? I am working on rest password via  custum templates in django,but  custom template not loading it is loading django's default template every time i load the /password_reset/ url.
I am using the url
 url('^', include('django.contrib.auth.urls')),

i have a registration folder in templates and using this link to work
https://simpleisbetterthancomplex.com/tutorial/2016/09/19/how-to-create-password-reset-view.html
and the template folder is:
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
                 ],

        'APP_DIRS': True,

        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                "cms.utils.context_processors.permission_based_hidding_of_sidebar",
            ],
            'libraries':{
                'template_tag': 'cms.templatetags.template_tag',
                'template_tag_time': 'cms.templatetags.tags',
            }
        },
    },
]

install apps in settings:-
INSTALLED_APPS = [
    'cms',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_extensions',
    'django_csv_exports',
    'django.contrib.auth',
    'django.contrib.admin',

]

A: See my comment below. Sure, you can hack it and remove the form in the distribution library. Very very naughty. A much better solution is to alter the order in which the apps are loaded in your settings file. Originally I had:

INSTALLED_APPS = ['django.contrib.auth', 'ana_access',]

I just changed this so my app loaded first. And lo. That did it.

INSTALLED_APPS = ['ana_access','django.contrib.auth', ]

Conclusion: if you keep seeing the default page DESPITE having the form in your templates/registration folder, then it might be because you are loading the default django.contrib.auth app before your own.

A: Django 3.0. 2020. I solved the issue by adding template/registration/*.html  in the project directory. This solved my issue.  I don't need to change anything in the INSTALLED_APPS list.
Here are the steps:

*

*Do the following highlighted changes in "settings.py"

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')], # **ADD THIS
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'django.template.context_processors.media',
                'django.template.context_processors.static', # * (optional)
            ],
        },
    },
]

*Create templates/registration directories in your project root folder and add your registration templates here instead of your_app/templates/registration.

Project_root_folder/templetes/registration/*.html

No need to change anything in INSTALLED_APPS of settings.py

A: If you want to override the Django admin template you need to created admin folder inside your templates directory. And place all your admin's files and folders there...
templates
|__ admin
    |__ registration

Update: Also please correct the TEMPLATES DIR It should be
'DIRS': [os.path.join(BASE_DIR, 'templates')],


text:
Q: SSIS XML Configuration for Connection String and Server Name I made SSIS XML Configuration files a for the sake of simplicity I selected the option 'Reuse Existing' so multiple SSIS packages can share the same XML configuration file.  Can packages use the same config file only in the case that all packages share the same Connection Manager Name?

A: Yes indeed, as long as the package variables name are the same, you can use the same configuration file for multiple SSIS packages.
There will be warnings if the associated configuration file contains variables that are not found in the package.


text:
Q: Map.addLayer automation As in the Hillshade Example, I wanted to automate adding all Layer from one Image for visual inspection.
var band_names =Image.bandNames()
print(ee.String(band_names.get(0)))
  for (var i = 0; i < 4; i += 1) {
  Map.addLayer(Image.select(ee.String(band_names.get(i))), {}, ee.String(band_names.get(i)));
}

This returns the longest Error ever, not gonna post it entirely

2 Questions:

*

*the Layer name is a String:
print(ee.String(band_names.get(0)))

yields a string. What's wrong with this code?

*How do I call the number of Bands for the automation? I imagine something like :
ee.Number(ee.Image.bad

A: You can't use a computed object for the layer name, only literal strings.
You can download all of the band names from the server into a list of strings using getInfo(), and then it would work.
var band_names = Image.bandNames().getInfo()
for (var i = 0; i < 4; i += 1) {
    Map.addLayer(Image.select(band_names[i]), {}, band_names[i]);
}


text:
Q: Getting specific data from JSON response using Rest-Assured and java How can I get the sub-nodes EntityPropertyValue,ProductPropertyValueUId,ProductPropertyValueDisplayName that come under the parent node ["Name": "PriorityUId"] using Rest Assured ?
Below is the code snippet
RequestSpecification request = RestAssured.given();
request.header("Content-Type", "application/json");
JSONObject requestParams = new JSONObject();
requestParams.put("data", "somedata");
request.body(requestParams.toJSONString());
Response response = request.post("url");
 List<Map<String, String>> epv = response.jsonPath().getList("EntityPropertyValues");
        for(int i=0;i<epv.size();i++)
        {
            if(epv.get(i).containsValue("PriorityUId"))
            {
                System.out.println(epv.get(i));
                break;

            }
        }

I am doing a sysout and I get the entire below block of data in response.
{
      "Name": "PriorityUId",
      "Values": [
                    {
                      "EntityPropertyValue": "Critical",
                      "ProductPropertyValueUId": "00000019-0000-0000-0000-000000000033",
                      "ProductPropertyValueDisplayName": "Blocker"
                    },
                    {
                      "EntityPropertyValue": "Critical",
                      "ProductPropertyValueUId": "00000019-0000-0000-0000-000000000034",
                      "ProductPropertyValueDisplayName": "Critical"
                    },
                    {
                      "EntityPropertyValue": "High",
                      "ProductPropertyValueUId": "00000019-0000-0000-0000-000000000035",
                      "ProductPropertyValueDisplayName": "Major"
                    }
      ],
      "DataTypeUId": "00100002-0007-0000-0000-000000000000",
      "DisplayName": "Priority"
    }

How can I capture the fields I am looking for?
Below is the entire JSON response
{
  "ProductInstance": "00000000-0000-0000-0000-000000000000",
  "DataTypeUId": null,
  "EntityPropertyValues": [
    {
      "Name": "ModifiedAtSourceByUser",
      "Values": [],
      "IsPropertyExists": true
    },
    {
      "Name": "ModifiedAtSourceOn",
      "Values": []
    },
    {
      "Name": "PriorityUId",
      "Values": [
                    {
                      "EntityPropertyValue": "Critical",
                      "ProductPropertyValueUId": "00000019-0000-0000-0000-000000000033",
                      "ProductPropertyValueDisplayName": "Blocker"
                    },
                    {
                      "EntityPropertyValue": "Critical",
                      "ProductPropertyValueUId": "00000019-0000-0000-0000-000000000034",
                      "ProductPropertyValueDisplayName": "Critical"
                    },
                    {
                      "EntityPropertyValue": "High",
                      "ProductPropertyValueUId": "00000019-0000-0000-0000-000000000035",
                      "ProductPropertyValueDisplayName": "Major"
                    }
      ],
      "DataTypeUId": "00100002-0007-0000-0000-000000000000",
      "DisplayName": "Priority"
    }
  ]
}

A: Get a JsonPath view of the response body
JsonPath js = response.jsonPath();

Get the size of EntityPropertyValues
int size = js.getInt("EntityPropertyValues.size()");

Loop through the array until you find the desired value, currently - PriorityUId
If it matches use JsonPath to fetch the values,
    for (int i = 0; i < size; i++) {
        String detail = js.getString("EntityPropertyValues[" + i + "].Name");
        if (detail.equalsIgnoreCase("PriorityUId")) {
            List<Object> EntityPropertyValue = js
                    .getList("EntityPropertyValues[" + i + "].Values.EntityPropertyValue");
            List<Object> ProductPropertyValueUId = js
                    .getList("EntityPropertyValues[" + i + "].Values.ProductPropertyValueUId");
            List<Object> ProductPropertyValueDisplayName = js
                    .getList("EntityPropertyValues[" + i + "].Values.ProductPropertyValueDisplayName");
            System.out.println("Values for EntityPropertyValue : " + EntityPropertyValue);
            System.out.println("Values for ProductPropertyValueUId : " + ProductPropertyValueUId);
            System.out.println("Values for ProductPropertyValueDisplayName : " + ProductPropertyValueDisplayName);
            break;
        }
    }


text:
Q: Offcanvas menu not working with direction rtl I have a simple page with two offcanvas menus, one in which side, they both work normally when in english, but since I also need to support arabic, I use the dir="rtl" in the html tag, and with it the right offcanvas menu have some weird behaviour on Chrome, looks like a repaint issue, when I resize the window it goes to the right position (sometimes it goes randomly after a few seconds as well).
I'm using transform: translateX(); and transform: translate3d(); in the body to achieve this, and as far as I can see there's nothing wrong.
Here's a codepen example of the bug: http://codepen.io/Ghostavio/pen/WbgXXZ

A: Its a simple thing I did Hope This is your answer
What I did was made the body position Fixd
in body:
position: fixed

Your New CSS will look like this:
  box-sizing: border-box
body
  padding: 5%
  position: fixed    /*Changed Here*/
  overflow-x: hidden
  transition: .3s ease-in-out transform
  &.left-offcanvas-active
    transform: translateX(270px)
    //transform: translate3d(270px, 0, 0)
  &.right-offcanvas-active
    transform: translateX(-270px)
    //transform: translate3d(-270px, 0, 0)
header
  text-align: center
  position: relative
img, svg
  vertical-align: middle
a
  text-decoration: none
.logo img
  width: 240px
  max-width: 100%
.gc
  fill: #8E8E8E
.content
  text-align: justify
.hamburger-icon
  position: absolute
  top: 10px
  left: 0
  cursor: pointer
.second-icon
  left: auto
  right: 0
.left-offcanvas, .right-offcanvas
  witdh: 270px
  min-width: 270px
  height: 100%
  background-color: #BABACA
  position: fixed
  display: block
  top: 5%
.left-offcanvas
  left: -270px
.right-offcanvas
  right: -270px
.offcanvas-links
  display: block
  padding: 20px
  color: #117EBF
  border-bottom: 1px solid #E1E1E1
  font-weight: 800
  text-decoration: none
  span
    background-color: #C80428
    color: #FFF
    padding: 0 5px
    border-radius: 2px
    font-weight: 400
    float: right

Hope this helps you.

A: I had a similar issue creating a sticky header on a horizontal scrolling table for RTL. What I found is that in order to get position : sticky to work for RTL without JS, I had to assign z-index to both the sticky column (sticky header) and the scrollable columns.
At first I used JS to position everything and add offset padding to get the sticky header effect. But after a walking away in frustration and returning to it days later did I come up with a CSS only solution.
JSfiddle example


text:
Q: Highlighting comments containing TODO in Sublime Text 2 Is there a way to tell Sublime to highlight comments that contain the word "TODO"?
I've looked for plugins that do this but haven't really been able to find much.

A: I'm using the TodoReview plugin. It's very good and simple.
After installing it via Package Control, in order to use it on Windows, press Ctrl+Shift+p and type TodoReview: Project Files.
It will open up a tab with all TODOs in your project, where you can navigate with up/down and go to the TODOs location with enter.

A: Sublime Linter should do the trick. You can add underlining for custom static text.
All you need is the Sublime Package Manager:

*

*Press Ctrl/Cmd+Shift+P

*Search for "Package Control: Install Package"

*Search for "SublimeLinter"

As stated by jon in the first comment:

For ST3, the SublimeLinter-annotations plugin highlights TODO, FIXME etc.

A: Try this plugin : https://github.com/robcowie/SublimeTODO
Maybe it can meet your requirement.

A: The "highlight_code_remarks.py" plugin seems to do what you are looking for. It can be found on: https://bitbucket.org/theblacklion/sublime_plugins/src/
It requires some handwork to install, especially note that:

*

*You don't just need to copy the highlight_code_remarks.py file, but also the entire "support" folder.

*Read the Instructions on the beginning of highlight_code_remarks.py file. If you just want keyword highlighting, you may skip the part which explains how to install the key bindings.

In case of trouble also have a look at this forum post, that's where I originally found the plugin: http://www.sublimetext.com/forum/viewtopic.php?f=5&t=1745

...and just in case someone reading this has never installed a sublime plugin before: In Sublime Text, click "Preferences", then "Browse Packages..."

*

*Copy the files mentioned above belong to your "User" subfolder.

*The color scheme configuration files can be found in the "Color Scheme - Default" subfolder.

A: Try the
HighlightWordsPlugin. Worked great for me on Sublime Text 3


text:
Q: Compare two dataframe columns with binary data I have two columns with binary data (1s and 0s) And I want to check what's the percent similiarity between one column and the other. Obviously, as they are binary, it is important that the coincidence is based in the position of each cell, not in the global amount of 0s and 1s. In example:
column_1     column_2
   0            1
   1            1
   0            0
   1            0

In that case, in both columns there are the same equal number of 0s and 1s (which means a 100% coincidence) however, taking into account the order or position of each, there's just a  50% coincidence. That last steatment is the one I'm trying to figure out.
I know I could do it with a loop... however in case of larger lists that could be a problem.

A: This gets a binary vector that gives True where col 1 equals 2 and 0 else where, sums it up, and divides by the number of samples.
sim = sum( df.column_1 == df.column_2 ) / len(df.column_1)


text:
Q: JWT OpenIddict and ASP.Net Core 500 Internal Server Error When I use Postman to try authentication I get an error. I trace it all the way through and it does the signin and succeeds but then fails returning the ticket.
The DEBUG log is as follows:

System.InvalidOperationException: No authentication handler is configured to handle the scheme: ASOS
   at Microsoft.AspNetCore.Http.Authentication.Internal.DefaultAuthenticationManager.<SignInAsync>d__14.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.SignInResult.<ExecuteResultAsync>d__14.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeResultAsync>d__30.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeNextResultFilterAsync>d__28.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ResultExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeNextResourceFilter>d__22.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ResourceExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeAsync>d__20.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.<Invoke>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Angular2WebpackVisualStudio.Startup.<>c__DisplayClass5_0.<<Configure>b__0>d.MoveNext() in C:\Users\mhorton.NRH\Documents\Visual Studio 2017\Projects\AngularWebpackVisualStudio-master\src\AngularWebpackVisualStudio\Startup.cs:line 98
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Server.IISIntegration.IISMiddleware.<Invoke>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Hosting.Internal.RequestServicesContainerMiddleware.<Invoke>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Server.Kestrel.Internal.Http.Frame`1.<RequestProcessingAsync>d__2.MoveNext()
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 1950.2099ms 500

And here is my Startup.cs. I think the error is in the Startup.cs and I freely admit I don't fully understand it all.
I am authenticating against an ASP.Net Identity Core SQL DB that is accessed via IdentityContext. During the trace the information from this DB is fine, so I am sure that part is working properly. I am intending to use OpenIddict to issue JWT Token using a self signed certificate and I want to use this token in an Angular4 app to access the API on the same server.

using System;
using System.Linq;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Angular2WebpackVisualStudio.Repositories.Things;
using Angular2WebpackVisualStudio.Models;
using AngularWebpackVisualStudio.DBContexts;
using AngularWebpackVisualStudio.Models;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using System.Security.Cryptography.X509Certificates;
using Microsoft.AspNetCore.Identity;
using AngularWebpackVisualStudio.Shared;

namespace Angular2WebpackVisualStudio
{
    public class Startup
    {

        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy("AllowAllOrigins",
                    builder =>
                    {
                        builder
                            .AllowAnyOrigin()
                            .AllowAnyHeader()
                            .AllowAnyMethod();
                    });
            });

            var jwtSigningCert = new X509Certificate2(@"C:\Program Files (x86)\Windows Kits\10\bin\10.0.15063.0\x64\SIWWW.pfx", "Test123");
            services.AddOpenIddict()
                .AllowAuthorizationCodeFlow()
                .AddEntityFrameworkCoreStores<IdentityContext>()
                .EnableTokenEndpoint("/oauth2/token")
                .EnableAuthorizationEndpoint("/connect/token")
                .UseJsonWebTokens()
                .AllowPasswordFlow()
                .DisableHttpsRequirement()
                .AddSigningCertificate(jwtSigningCert);

            services.AddMvc();

            services.AddDbContext<IdentityContext>(options =>
            {
                options.UseSqlServer(Configuration.GetSection("ConnectionStrings")["DefaultConnection"]);
                options.UseOpenIddict();
            });
            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<IdentityContext>()
                .AddDefaultTokenProviders();

            services.AddScoped<IPasswordHasher<ApplicationUser>, SqlPasswordHasher>();

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            var angularRoutes = new[] {
                 "/home",
                 "/about",
                 "/contact",
                 "/login"
             };

            app.Use(async (context, next) =>
            {
                if (context.Request.Path.HasValue && null != angularRoutes.FirstOrDefault(
                    (ar) => context.Request.Path.Value.StartsWith(ar, StringComparison.OrdinalIgnoreCase)))
                {
                    context.Request.Path = new PathString("/");
                }

                await next();
            });

            app.UseCors("AllowAllOrigins");

            app.UseDefaultFiles();
            app.UseStaticFiles();
            app.UseIdentity();
            app.UseOAuthValidation();
            app.UseJwtBearerAuthentication(new JwtBearerOptions()
            {
                Audience = "414e1927a3884f68abc79f7283837fd1",
                Authority = "localhost:5000",
                AutomaticAuthenticate = true,
                RequireHttpsMetadata = false
            });

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

Any help much appreciated.

A:
When I use Postman to try authentication I get an error. I trace it all the way through and it does the signin and succeeds but then fails returning the ticket.

You must add app.UseOpenIddict(); after app.UseIdentity(); (and necessarily before app.UseMvc();).


text:
Q: What algorithm does babel use to convert a simple div into x.createElement('div')? I am curious how babel's algorithm works for converting JSX into
x.createElement(
  type,
  [props],
  [...children]
)

Can anyone explain how babel works for a simple JSX div?
<div id="hello-world" > Hello World </div>

A: Babel is a compiler. It's not that simple.
Most compilers break down into three primary stages: Parsing, Transformation, and Code Generation

*

*Parsing is taking raw code and turning it into a more abstract representation of the code. (Parsing working example: here. Go ahead, use your <div> example.)

*Transformation takes this abstract representation and manipulates to do whatever the compiler wants it to.

*Code Generation takes the transformed representation of the code and turns it into new code.
For a quick tutorial on compilers, see this.
Another great resource on Babel internal working. here.


text:
Q: SpringREST - RequestMethod.PUT not working I have created a SpringREST API using SpringBoot 1.2.6.
Below is my post method and it works. But when i created a Put method, its not working. Its not fetching the data in paramaters.
@CrossOrigin
    @RequestMapping(
            method = RequestMethod.POST,
            consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    public String createArticle(String article_name, String article_content, Long image_id, String category,
                                HttpServletRequest req, Authentication authentication) throws Exception {...}

PUT METHOD
// Edit Articles
@RequestMapping(value = "/{article_id}",
        method = RequestMethod.PUT,
        consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
        produces = MediaType.APPLICATION_JSON_VALUE)
public String editArticle(@PathVariable("article_id") Long article_id,
                          String article_name, String article_content, String category, HttpServletRequest req) throws Exception {...}

I have set the debugger, and below is the debug snapshot
Debug Image

A: By using PUT method, it's not supporting in spring boot. Whether I need to add any new configuration.
Put method works only the request not have any parameters. If I add any query parameter or form data it doesn't work.
You will implementing like below code.
@RequestMapping(value = "/", method = RequestMethod.PUT)

public @ResponseBody String createArticle(@RequestBody CreateArticle request) {
    LOG.info(request.toString());
    return "ok";
}

In that CreateArticle is request class which pass value in json format and including all parameters like String article_name, String article_content, Long image_id, String category, HttpServletRequest req, Authentication authentication.


text:
Q: How to select count(*) in criteria api? I have a query generated by hibernate criteria api which takes a pretty much time to execute:
select count (entity.id)
from table
where field1 in ('...') and field2 in ('...') and ...

I've replaced entity.id with '*':
select count (*)
from table
where field1 in ('...') and field2 in ('...') and ...

And for now it works pretty well for some reasons, but I can't generate this query by criteria api. I'am creating Root like this:
Root<MyEntity> root cq.from(MyEntity.class);

Is there any ways to generate sql query with select count(*) not with count(id)?

A: Use count(1) which is equivalent by doing criteriaBuilder.count(criteriaBuilder.literal(1))


text:
Q: Sums of Products of Two Normal Variables Suppose that $X_1 ,\ldots,X_n,Y_1,\ldots,Y_n$ are all independent normal random variables with different means and variances. What is the PDF of the following random variable?
$$X_1Y_1+\cdots+X_nY_n$$
or is there any way that I can find an approximation for its PDF?

A: You want to know the distribution of
$$
Z = \sum_{i=1}^n X_iY_i,
$$
where $X_i$ and $Y_i$ are all normal and independent but not identically distributed.  Let's calculate the mean and variance of $Z$:
$$
\mathrm E[Z] = \sum_{i=1}^n \mathrm E[X_iY_i] = \sum_{i=1}^n \mathrm E[X_i]\mathrm E[Y_i].
$$
You know the individual means of the normals, so the above sum can be calculated.  Now the variance, knowing that covariance terms drop out because of uncorrelation due to independence
$$
\mathrm{Var}[Z] = \sum_{i=1}^n \mathrm{Var}[X_iY_i] = \sum_{i=1}^n \mathrm E[Y_i]^2\mathrm{Var}[X_i]+\mathrm E[X_i]^2\mathrm{Var}[Y_i]+\mathrm{Var}[X_i]\mathrm{Var}[Y_i]
$$
Again, this is all in terms of quantities you know, the means and variances of the underlying distributions.
So, IF the CLT applies, your answer is that $Z\sim\mathcal{N}(\mathrm{E}[Z],\mathrm{Var}[Z])$.  Rigorously proving that this is true for your particular case and your particular distributions is up to you, but my claim is that it is true. I pastebinned some numerical calculations to support my claim.

A: The product  $Z_i=X_iY_i$ obeys the product normal distribution, which has a characteristic function given in: Characteristic function of product of normal random variables. As a result the characteristic function of your random variable is given by a product of the similar characteristic function (after matching to the various means and standard deviations). You can solve the question by approximating the Fourier transform of the resulting characteristic function.


text:
Q: How can I boot mysql? After I install mysql in my terminal like this
brew install mysql

I try to open it like this
mysql -uroot

but it appear an error:ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
What should I do

A: Try starting mysql server with this command: mysql.server start
and if this not help try: brew services start mysql


text:
Q: Whenever my app makes a fetch request the clickable components of my app don't work Description
For example whenever my app is loading an image of a url, you can't click a button, it doesn't work, it only works when you finish loading the image of the url, the same happens with fetch when I try to get anything from my api.
I've already created several apps and the same thing happens
What should I do?
Why is this happening?
I'm using the version of react
React Native version:
OS: Windows 10 10.0.18363
CPU: (2) x64 Intel(R) Pentium(R) CPU G2030 @ 3.00GHz
Memory: 1003.84 MB / 7.88 GB
Binaries:
Node: 12.10.0 - C:\Program Files\nodejs\node.EXE
Yarn: 1.17.3 - C:\Program Files (x86)\Yarn\bin\yarn.CMD
npm: 6.10.3 - C:\Program Files\nodejs\npm.CMD
Watchman: Not Found
SDKs: Android SDK:

API Levels: 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 28, 29 Build Tools: 27.0.3, 28.0.3, 29.0.2, 30.0.0 System Images: android-14 | ARM EABI v7a, android-15 | ARM EABI v7a, android-15 | Intel x86 Atom, android-15 | Google APIs ARM EABI v7a, android-15 | Google APIs Intel x86 Atom, android-16 | ARM EABI v7a, android-16 | MIPS, andro id-16 | Intel x86 Atom, android-16 | Google APIs ARM EABI v7a, android-16 | Google APIs Intel x86 Atom, android-17 | ARM EABI v7a, android-17 | MIPS, android-17 | Intel x86 Atom, android-17 | Google APIs ARM EABI v7a, android-17 | Goog le APIs Intel x86 Atom, android-18 | ARM EABI v7a, android-18 | Intel x86 Atom, android-18 | Google APIs ARM EABI v7a, android-18 | Google APIs Intel x86 Atom, android-19 | ARM EABI v7a, android-19 | Intel x86 Atom, android-19 | Google APIs ARM EABI v7a, android-19 | Google APIs Intel x86 Atom, android-21 | Android TV Intel x86 Atom, android-21 | ARM EABI v7a, android-21 | Intel x86 Atom, android-21 | Intel x86 Atom_64, android-21 | Google APIs ARM EABI v7a, android -21 | Google APIs Intel x86 Atom, android-21 | Google APIs Intel x86 Atom_64, android-22 | ARM EABI v7a, android-22 | Intel x86 Atom, android-22 | Intel x86 Atom_64, android-22 | Google APIs ARM EABI v7a, android-22 | Google APIs Intel x86 Atom, android-22 | Google APIs Intel x86 Atom_64, android-25 | Google APIs ARM EABI v7a, android-25 | Google Play Intel x86 Atom, android-26 | Intel x86 Atom, android-26 | Intel x86 Atom_64, android-26 | Google APIs Intel x86 Atom , android-26 | Google APIs Intel x86 Atom_64, android-26 | Google Play Intel x86 Atom, android-27 | Intel x86 Atom, android-27 | Intel x86 Atom_64, android-27 | Google APIs Intel x86 Atom, android-27 | Google Play Intel x86 Atom, andro id-28 | Intel x86 Atom, android-28 | Intel x86 Atom_64, android-28 | Google APIs Intel x86 Atom, android-28 | Google APIs Intel x86 Atom_64, android-28 | Google Play Intel x86 Atom, android-28 | Google Play Intel x86 Atom_64, android-2 9 | Intel x86 Atom, android-29 | Intel x86 Atom_64, android-29 | Google APIs Intel x86 Atom, android-29 | Google APIs Intel x86 Atom_64, android-29 | Google Play Intel x86 Atom, android-29 | Google Play Intel x86 Atom_64, android-R | G oogle APIs Intel x86 Atom, android-R | Google APIs Intel x86 Atom_64, android-R | Google Play Intel x86 Atom, android-R | Google Play Intel x86 Atom_64 Android NDK: 21.1.6352462 Windows SDK: Not Found IDEs: Android Studio: Version 4.0.0.0 AI-193.6911.18.40.6514223 Visual Studio: Not Found Languages: Java: Not Found Python: 2.7.16 - C:\Python27\python.EXE npmPackages: @react-native-community/cli: Not Found react: 16.13.1 => 16.13.1 react-native: 0.63.2 => 0.63.2 react-native-windows: Not Found npmGlobalPackages: react-native: Not Found
------------------------------------------------------------------------

Here is the sample code. In the flatlist I load a list containing images
/* This is an Login Registration example from https://aboutreact.com/ */
/* https://aboutreact.com/react-native-login-and-signup/ */

import React, { useState, useEffect } from 'react';

import {
    ActivityIndicator,
    View,
    StyleSheet,
    Text,
    StatusBar,
    Linking,
    Image,
    FlatList,
    TouchableOpacity,
    SafeAreaView,
    Alert, TouchableNativeFeedback, RefreshControl
} from 'react-native';

import AsyncStorage from '@react-native-community/async-storage';
import Cores from '../wapangola/Cores';
import {Button, Header, Icon, Badge} from 'react-native-elements';
import estilo from '../wapangola/Styles';
import Request, {ERROR_TYPE, VIEW_STATE} from '../wapangola/CustomRequest';
import Config from '../wapangola/Config';
import CustomError from '../wapangola/CustomError';
import Menu, { MenuItem, MenuDivider } from 'react-native-material-menu';
import {RandomNum, TerminarSessao} from '../wapangola/Utils';
import Loader from '../wapangola/Loader';
import PublicacaoItem from "../app/PublicacaoItem";
import EventBus from "react-native-event-bus";
import {NOTI_ACTION, WapEvents} from "../wapangola/WapEvents";
import PushNotification from "react-native-push-notification";
import RNFetchBlob from "rn-fetch-blob";

function MostraData(props) {

    const renderSeparator = () => {
        return (
            <View
                style={{
                    height: 0,
                    width: "80%",
                    alignSelf:'flex-end',
                    backgroundColor: "#eee",
                }}
            />
        );
    };

    const renderFooter = () => {
        return (
            <>

                <View>

                    { props.loadMore === true ?

                    <View
                        style={{
                            paddingVertical: 20,
                        }}>
                        <ActivityIndicator
                            color={Cores.primary}
                            animating size="large"
                        />
                    </View> :

                        <Button
                            type={"solid"}
                            containerStyle={{margin:10}}
                            buttonStyle={{backgroundColor: Cores.primary}}
                            title={"Carregar mais"}
                            onPress={()=>{

                                props.onLoadMore();

                                //EventBus.getInstance().fireEvent(WapEvents.CARREGAR_MAIS_PUBLICACAO, {});

                            }}
                        />
                    }
                </View>

            </>
        );
    };

    const renderHeader = () => {

        return (
            <>
                <View style={{flexDirection:"row", flex:1, backgroundColor:"#fff", margin:5, padding:10, elevation:3, borderRadius:10}}>
                    <Image source={{uri: props.foto}} style={{width:40, height:40, borderRadius:50, marginRight:10}} />
                    <Button
                    type={"clear"}
                    title={"Criar publicação"}
                    onPress={()=>{

                        props.navigation.navigate("Compor");

                    }}
                    titleStyle={{color:Cores.success}}
                    containerStyle={{alignSelf:"center"}}
                    buttonStyle={{width:"100%", alignSelf:"center"}}
                    />
                </View>

                <View style={{flexDirection:"column", flex:1, backgroundColor:"#fff", margin:5, padding:10, elevation:3, borderRadius:10}}>

                    <Text style={{alignSelf:"center", fontSize: 18, marginBottom:5}}>{props.dataMain.rei.rei_desc}</Text>
                    <Image source={{uri: props.dataMain.rei.rei_foto}} style={{width:100, height:100, borderRadius:50, alignSelf:"center"}} />

                    <Text style={{alignSelf:"center", fontSize:20, marginTop:5}} numberOfLines={1} ellipsizeMode={"tail"}>{props.dataMain.rei.rei_nome}</Text>

                    <Button
                        type={"clear"}
                        title={props.dataMain.rei.rei_text_btn}
                        titleStyle={{color:Cores.primary}}
                        onPress={()=>{
                            props.navigation.navigate("Perfil",{id: props.dataMain.rei.rei_id, foto: props.dataMain.rei.rei_foto, nome: props.dataMain.rei.rei_nome});
                        }}
                        buttonStyle={{alignSelf:"center"}}
                    />


text:
Q: HTML Form Number Type Unique User Input I am using the code below to ask users to rank (prioritize) which sweets they like the best. The users need to rank from 1-3 (1 being the best)
<form id="form1" name="form1" method="post" action="">
<input type="number" name="cake" id="cake" required="required" max="3" min="1"/>Cake

<input type="number" name="twizlers" id="twizlers"required="required" max="3" min="1"/>Twizlers

<input type="number" name="taffy" id="taffy" required="required" max="3" min="1"/>Taffy

<input type="submit" name="button" id="button" value="Submit" />
</form>

I am using HTML 5 coding to make sure that they only use numbers 1,2, and 3 but how can I make sure they do not use the same number twice? Is there an HTML input code that I can use or is there some javascript code needed? If javascript is needed, what do you suggest?

A:

This will work, otherwise you can use radio button.

A: You can go with a JS check that the user only rank 1 item with a single value and cant rank that item again. You can use JS to do this.Insert an ID for your input field and then
    document.getElementById("your_id").disabled = false;
    document.getElementById("your_id").disabled = false;
    document.getElementById("your_id").disabled = false;

    var var1 = document.getElementById("your_id");
    var1.onchange = function () {
    if (this.disabled == true) {
     document.getElementById("your_id").disabled = true;
     }
    }

Thus check this for three items.


text:
Q: Write a Boolean expression that evaluates to true and only if x and y are both not in the range 0 to 100 inclusive, and y is greater than x This is what I have done.
(((((x<0) and (x>100)) and (y<0) and (y>100))) and (y>x))

A: Your expression is wrong. How can any value be <0 and >100 at the same time? It will always be false.
One possible correct expression that uses the power of Python is
y>x and not 0<=x<=100 and not 0<=y<=100

See this demo


text:
Q: Search optimization using Apache Lucene I am working on a project to implement large scale indexing on twitter data for search optimization using Apache Lucene. Lucene provides inverted index to filter out the blocks which match the specified selection criteria.
To implement this project, how should I go about it - Should I install the Cloudera vm and proceed? or Should I deploy Hadoop from Apache on Ubuntu platform?
The reason I am asking this is because I am not able to confirm if Cloudera already uses Lucene to optimize search.
Please advise.

A: Cloudera gives you debian packages and software for automatic installation and cluster management. That's it. There is nothing about search (and it's optimization) in Hadoop stack. So you may choose either vanilla or cloudera for you project.
For search you can use Elasticsearch. It have integration with hadoop and uses Lucene internally


text:
Q: How to open dialog with edit text box when an item is selected from drop down list I am trying to build an android app in which I make a dropdownlist. When a specific item is  selected from  the drop-down, a dialog box with edit text and a button should open. How can I do this?
spiner.java
public class MainActivity extends Activity {

    private Spinner spinner1, spinner2;
    private Button button;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        addItemsOnSpinner2();
        addListenerOnButton();
        addListenerOnSpinnerItemSelection();
    }

    public void addItemsOnSpinner2() {

        spinner2 = (Spinner) findViewById(R.id.spinner2);
        List list = new ArrayList();
        list.add("Item 1");
        list.add("Item 2");
        list.add("Item 3");
        list.add("Item 4");
        ArrayAdapter dataAdapter = new
                ArrayAdapter(this, android.R.layout.simple_spinner_item, list);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner2.setAdapter(dataAdapter);
    }

    public void addListenerOnSpinnerItemSelection() {
        spinner1 = (Spinner) findViewById(R.id.spinner1);
        spinner1.setOnItemSelectedListener(new MyOnItemSelectedListener());
    }

    public void addListenerOnButton() {

        spinner1 = (Spinner) findViewById(R.id.spinner1);
        spinner2 = (Spinner) findViewById(R.id.spinner2);
        button = (Button) findViewById(R.id.button);

        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                Toast.makeText(MainActivity.this,
                        "Result : " +
                                "\nSpinner 1 : " + String.valueOf(spinner1.getSelectedItem()) +
                                "\nSpinner 2 : " + String.valueOf(spinner2.getSelectedItem()),
                        Toast.LENGTH_SHORT).show();
            }

        });
    }

    public class MyOnItemSelectedListener implements OnItemSelectedListener {

        @Override
        public void onItemSelected(AdapterView parent, View view, int pos, long id)
        {

            Toast.makeText(parent.getContext(), "Selected Country : " +
                    parent.getItemAtPosition(pos).toString(), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onNothingSelected(AdapterView parent) {

        }
    }
}


text:
Q: Amd drivers don't load on boot and I have to sudo modprobe it, possibly related to r8168-dkms failing to build After starting my system up, I get stuck on 1024x768, then I have to log in, open a terminal and type insudo modprobe amdgpu.
After that, the screen flashes a few times, becomes black with a flashing cursor and I have to Ctrl+Alt+2 to tty2, then Ctrl+Alt+1 back to tty1 and log in again.
After that I can tether my phone for a network connection.
My current setup. I tried to update to the pro drivers, because I get framedrops in multiple games.
7:00.0 VGA compatible controller: Advanced Micro Devices, Inc. [AMD/ATI] Ellesmere [Radeon RX 470/480/570/570X/580/580X/590] (rev e1)
Subsystem: Sapphire Technology Limited Nitro+ Radeon RX 570/580/590
Kernel driver in use: amdgpu
Kernel modules: amdgpu

It happened on 20.04, now I updated to 20.10 and it still the same and I have tried all solutions I could find, but none helped. Any ideas?


text:
Q: How to find out who added a user or modified IAM roles of a specific user in GCP? I tried but could not figure out that how to find out who added a user or modified IAM roles of a specific user in GCP.
is anyone aware of any method?

A: You can see this information through Logs Viewer please check the following URL for Logs Viewer query interfaces where you can find more information
And for this specific event you can use the following query to search it in your project:

*

*Go to Logs Viewer

*Select a Google Cloud project.

*Use the advanced query interface:

*Paste the following query:

protoPayload.authorizationInfo.permission="resourcemanager.projects.setIamPolicy"
protoPayload.response.bindings.members="user:emailuser@gmail.com"

Change the emailuser@gmail.com for the user you are looking for.

*Click on the start button.

And you will see something like:

On View Options you can click on Expand All for more information:

Also you can see those events on the Activity tab

I hope this information would be useful to you


text:
Q: what is the difference between "command && command" and "command ; command" I see these two usage on Ubuntu "command && command" and "command ; command",
 e.g. apt-get update && apt-get upgrade
What would differ if I use apt-get update; apt-get upgrade?
 I am not asking for this specific usage but in general what is the difference between these two usage?

A: && is a logical operator. ; is simple sequencing.
In cmd1 && cmd2, cmd2 will only be run if cmd1 exits with a successful return code.
Whereas in cmd1; cmd2, cmd2 will run regardless of the exit status of cmd1 (assuming you haven't set your shell to exit on all failure in your script or something).
On a related note, with cmd1 || cmd2, using the || 'OR' logical operator, cmd2 will only be run if cmd1 fails (returns a non-zero exit code).
These logical operators are sometimes used in scripts in place of a basic if statement. For example,
if [[ -f "$foo" ]]; then mv "$foo" "${foo%.txt}.mkd"; fi

...can be more concisely achieved with:
[[ -f "$foo" ]] && mv "$foo" "${foo%.txt}.mkd"

A: Syntax
command1 && command2

command2 is executed if, and only if, command1 returns an exit status of zero (true). In other words, run command1 and if it is successfull, then run command2.
command1 ; command2

Both command1 and command2 will be executed regardless. The semicolon allows you to type many commands on one line.
Related:
command1 || command2

command2 is executed if, and only if, command1 returns a non-zero exit status. In other words, run command1 successfully or run command2.

Example
&& operator:
$ rm /tmp/filename && echo "File deleted"

; operator:
$ echo "foo" ; echo "bar"

|| operator:
$ cat /tmp/filename 2>/dev/null || echo "Failed to open file"

External Links

*

*Linuxtopia.org

*Tldp.org


text:
Q: Sanitizing JSON data for usage as JavaScript object I'm going to be dynamically generating a JSON file which is then passed to SCEditor as the emoticons object; this data will come from the database, so essentially it should be safe, but one can never be 100% sure.
This is how it is being called:
// Create var to store emoticons
var emoticons = false;

$.getJSON('../../images/emoticons/default/emoticons.json')
.done(function(response) {
    emoticons = response;
    console.log(emoticons);
})
.always(function() {
    // always initialize sceditor
    $(".sceditor").sceditor({
        // Other options.....
        plugins: "bbcode",
        emoticons: emoticons,
    });
});

An example of the JSON file would look like:
{
    "dropdown": {
        ":)": "smile.png",
        ":angel:": "angel.png",
        ":angry:": "angry.png",
        "8-)": "cool.png",
        ":'(": "cwy.png",
    }
}

So the emoticon code and filename are pulled from the database. Is there anything I need to do here other than escape double quotes? Whilst this data will be coming from the database, it's possible the codes/filenames will be provided by the user.
When I store them in the database I will be stripping tags with PHP's strip_tags function.
I wanted to avoid turning the data into html entities as it doesn't seem to play nice with the editor as it doesn't turn the emoticons into smileys within the editor if you say set the code as :") - it will literally output in the editor as :") rather than show the smiley.
Edit: To see an example of how the code is used check out the SCEditor demo. Only difference is the demo uses the default codes provided within the JS file itself and mine will be provided via a JSON file passed as an option.
What is are my best options here?


text:
Q: couchdb GET _replicator database returns 500 I have a cluster where the _replicator database returns:
{"error":"nodedown","reason":"progress not possible"}
All other DBs are good, I don't have any replication beyond the cluster itself. I'd like just recreate the _replicator DB in the cluster since there is nothing to lose, how do I go about doing this?
Extra Background: Originally we had setup the cluster separately and started replicating from a single node instance, recently I removed the replication, upgraded the the single instance to v2.2 and added it as part of the cluster.

A: It happened to me as well, the _replicator DB was corrupted.
Issue DELETE to /_replicator and then PUT /_replicator to recreate the DB.
Naturally, you will have to recreate the replication jobs.


text:
Q: Filter out multiple items from array in Javascript/Angular I have a multi select dropdown in Angular. I want to filter it out based on name.

var users = [{
    name: 'John',
    email: 'johnson@mail.com',
    age: 25,
    address: 'USA'
  },
  {
    name: 'Tom',
    email: 'tom@mail.com',
    age: 35,
    address: 'England'
  },
  {
    name: 'Mark',
    email: 'mark@mail.com',
    age: 28,
    address: 'England'
  }
];

How will i filter out John and Tom both if i select them in my multi select dropdown. Assuming i am getting this from the multiselect dropdown.

this.selectedItems =
[
{"id":1,"name":"John"},
{"id":2,"name":"Tom"}
];

A: You can approach this by using filter method.
let selectedUserArray = ["John","Tom"]; //selected user names from the dropdown.

let finalArr = [];

selectedUserArray.forEach((item)=>{
    var name = users.filter( el=>el.name == item );
    finalArr.push.apply(finalArr,name);
});

console.log(finalArr); // This is the final Array you want to approach

A: const selectedUserNames = this.selectedItems.map(user => user.name);
const selectedUsers = users.filter(user => selectedUserNames.indexOf(user.name) > -1)


text:
Q: The effect of channel error on the determinant of transmitted matrix Assume the following matrix
$$
E:=\left(
\begin{array}{ccccc}
 e_1  & e_2  & \cdots  &  e_{p-1}  & e_{p}\\
 e_{p+1}  & e_{p+2}  & \cdots  &  e_{2p-1}  & e_{2p}  \\
\vdots    & \vdots    & \vdots  &  \vdots &\vdots    \\
 e_{p^2-p+1}  &  e_{p^2-p+2}  &   \cdots  &  e_{p^2-1}  & e_{p^2}
\end{array}
\right)_{p\times p}=(e_{i})\in {\Bbb{R}}^{p \times p}\, .
$$
Let the determinant of  the matrix $E$ is a number like $m$, and suppose $l_i$, $1\leq i \leq p^2$, is the number of decimal
digits in the $i$th entry of the matrix $E$. Imagine, we are as a sender in a communication system and we want to send the entries
of the matrix $E$, through a noisy channel. Suppose the channel error probability per decimal symbol is $q$.
We denote the received matrix $E$, by $\widehat{E}$. Consider, the entries
of the matrix $\widehat{E}$, are received with $k$ errors, where $2\leq k \leq p^2$. I mean, we have at least two errors.
 Now, my question it is, with which probability, the determinant of the received matrix $\widehat{E}$ is
equal the $m$, when $k$ entries of the matrix $\widehat{E}$, are received with errors. Notice that, $k$ errors can be
happen in the ${{p^2}\choose{k}}=\frac{p^2!}{k!\, (p^2-k)!}$ cases in the matrix $\widehat{E}$.
I would greatly appreciate for any suggestions.


text:
Q: C Programming. How to make method to print a string I am trying to make a function in C that will print a string taken as a parameter.  Is this even possible in C?
I have something like this in my header file, but string is not a valid identifier. I understand there are no strings in C, but what's the string.h class for?
#include <string.h>

#ifndef _NEWMAIN_H
#define _NEWMAIN_H

#ifdef __cplusplus
extern "C" {
#endif

    void print (string message){  //this is where i need help
        printf("%s", message);
    }

#ifdef __cplusplus
}
#endif

#endif /* _NEWMAIN_H */

A: In C, there is no native string type.
C handles strings as a null-terminated char array.
For example:
char* string = "this is a string";

The string.h exists to perform string manipulation functions on C strings, which are of type char*.
When printing a string using printf, one would pass in a variable of char*:
char* string_to_print = "Hello";
printf("%s", string_to_print);

For more information on strings in C, the Wikipedia page on C strings would be a good start.

A: void print (const char* message) {
            printf("%s", message);
}

A: After thinking about it briefly, for your homework assignment, which is to replace printf, you will want to use char * as pointed out by others, and use fwrite to stdout.
For a related question you can look at
C/C++ best way to send a number of bytes to stdout

A: There are no strings in C, since there are no classes in C.  string.h provides the routines for handling string text manipulation in C, using pointers to char.
You'll want to rewrite this like:
void print(const char* message) {
    printf(message); // You don't need the formatting, since you're only passing through the string
}

That being said, it's not really any different than just calling printf directly.


text:
Q: Is there a DBus command to toggle auto-hide on a KDE Plasma panel? Is there a DBus command (or some other way from the command line) to toggle auto-hide on a panel in KDE Plasma?  (I'm running KDE 4.6.)
I have a game I run in WINE that doesn't work right if it's autohidden and it would be nice to run it from a script that takes care of that for me.

A: You can do it easily through plasma desktop scripts, like this:
auto-hide on:
var panel = panelById(panelIds[0])
panel.hiding = 'autohide';

auto-hide off:
var panel = panelById(panelIds[0])
panel.hiding = 'none';

The bad news is there is no way to programatically run the script when you want it except perhaps for some kind of keyboard+mouse automation.
The closest you can get (per this discussion on KDE forum) is open the script in desktop console via
qdbus org.kde.plasma-desktop /MainApplication \
    loadScriptInInteractiveConsole /path/to/js/file

There is bug #238817 in KDE Bugzilla filed on this.

A: As of July 2018, the answer suggested by @che doesn't work.
Here is something that does work though:
qdbus org.kde.plasmashell /PlasmaShell evaluateScript "p = panelById(panelIds[0]); p.height = 32 - p.height;"

32 is the height I like. Set that to a different number as you like.
Relevant KDE Bug: https://bugs.kde.org/show_bug.cgi?id=396796

A: There is a kwin script that toggle panel
https://www.opendesktop.org/p/1266534/
and
https://www.opendesktop.org/p/1269113/
We can also add more feature to a panel by setting it up in (KDE System Settings - Window Manager - Window Rules - New - Detect Window Properties "And select your pannel"

A: I think you should check Re: Documentation for the dbus methods for plasma and for some example of how to use dbus Lauching K menu with DBus.
If a method is present it will easy to find.


text:
Q: the var doesn't become global but remains local From the following snippet i try to test NewGlobalRef and try to make clsStr global after declaring it in the local scope of if block.
jstring Java_Package_LocalAndGlobalReference_returnGlobalReference
 (JNIEnv *env, jobject obj) {
if(1) {
    printf("In function make global reference\n");
    jclass clsStr ;
    jclass cls = (*env)->FindClass(env,"java/lang/String");
    if( cls == NULL)
        return NULL;
    // create a global reference of clsStr
    clsStr = (*env)->NewGlobalRef(env,cls);
    // Delete the local reference, which is no longer userful
    (*env)->DeleteLocalRef(env,cls);
    if(clsStr == NULL)
        return NULL;
}
 return clsStr; // statement 31
}

When i run the above snippet i get the following errors :
W:\elita\jnitesters\workspace\c\LGR\LGR.c:31: error: 'clsStr' undeclared (first use in this function)
W:\elita\jnitesters\workspace\c\LGR\LGR.c:31: error: (Each undeclared identifier is reported only once
W:\elita\jnitesters\workspace\c\LGR\LGR.c:31: error: for each function it appears in.)

Why do i get the error saying that clsStr is undefined when i have made that var global using the satement clsStr = (*env)->NewGlobalRef(env,cls) ?

A: When you declare a variable in a block (in this case, you declare clsStr in the block if the if(1) { ... } statement), the scope of that variable (and its lifetime) is that block. That means it doesn't exist when you return clsStr after the block.
You can either

*

*move the return statement inside the block, or

*declare the variable clsStr before the if(1) { ... } statement

when i have made that var global using the statement clsStr = (*env)->NewGlobalRef(env,cls)

That is a misunderstanding - you can't make a variable global by assignment; you do that by declaration in the global scope. You can initialize a variable by assignment, but that doesn't have anything to do with its scope.


text:
Q: Facebook Feed dialogs Problem I'm working on adding Facebook dialog to my site I got the code from the developers pages . created an application on facebook and tried it with the example app-id It works but when I change the app-id to my app-id It doesn't work and I got the following error:
"Error with , try again later"
any suggestion?

A: The application needs to be running on the same url that is specified in the settings for your application.  I normally setup a host file entry for local testing.


text:
Q: Test in Michael Hartl's Tutorial Chapter 8 Fails I am working on Michael Hartl's Rails Tutorial and I am stuck at Chapter 8.4.6 with the Remember Test failing.
I am confused on what to do next.
Here is the test result
 FAIL["test_login_with_remembering", UsersLoginTest, 2015-08-25 15:26:59 +0100]
 test_login_with_remembering#UsersLoginTest (1440512819.22s)
    Expected nil to not be nil.
    test/integration/users_login_test.rb:52:in `block in <class:UsersLoginTest>'

Here is my user_login_test.rb
require 'test_helper'

    class UsersLoginTest < ActionDispatch::IntegrationTest

      def setup
        @user = users(:microte)
      end

      test "login with invalid information" do
        get login_path
        assert_template "sessions/new"
        post login_path, session: { email: "", password: "" }
        assert_template "sessions/new"
        assert_not flash.empty?
        get root_path
        assert flash.empty?
      end

      test "login with valid information" do
        get login_path
        post login_path, session: { email: @user.email, password: 'microte' }
        assert_redirected_to @user
        follow_redirect!
        assert_template "users/show"
        assert_select "a[href=?]", login_path, count: 0
        assert_select "a[href=?]", logout_path
        assert_select "a[href=?]", user_path(@user)
      end

      test "login with valid information followed by logout" do
        get login_path
        post login_path, session: { email: @user.email, password: 'microte' }
        assert_redirected_to @user
        follow_redirect!
        assert_template "users/show"
        assert_select "a[href=?]", login_path, count: 0
        assert_select "a[href=?]", logout_path
        assert_select "a[href=?]", user_path(@user)
        delete logout_path
        assert_not is_logged_in?
        assert_redirected_to root_url
        # simulate a user clicking logout in a second window.
        delete logout_path
        follow_redirect!
        assert_select "a[href=?]", login_path
        assert_select "a[href=?]", logout_path, count: 0
        assert_select "a[href=?]", user_path(@user), count: 0
      end

        test "login with remembering" do
        log_in_as(@user, remember_me: '1')
        assert_not_nil cookies['remember_token'] #line 52
      end

      test "login without remembering" do
        log_in_as(@user, remember_me: '0')
        assert_nil cookies['remember_token']
      end
    end

My session_controller.rb
class SessionsController < ApplicationController
      def new
      end

      def create
        user = User.find_by(email: params[:session][:email].downcase)
        if user && user.authenticate(params[:session][:password])
          log_in user
          params[:session][:remember_me] == '1' ? remember(user) : forget(user)

          redirect_to user
        else
          flash.now[:danger] = "Invalid e-mail/password combination"
          render "new"
        end
      end

      def destroy
        log_out if logged_in?
        redirect_to root_url
      end
    end

My test_helper.rb
ENV['RAILS_ENV'] ||= 'test'
    require File.expand_path('../../config/environment', __FILE__)
    require 'rails/test_help'
    require "minitest/reporters"
    Minitest::Reporters.use!

    class ActiveSupport::TestCase
      # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
      fixtures :all

      # Add more helper methods to be used by all tests here...

      # Returns true if a test user is logged in.
      def is_logged_in?
        !session[:user_id].nil?
      end

      # Log in a test user.
      def log_in_as(user, options = {})
        password = options[:password]     || 'password'
        remember_me = options[:remember_me]  || '1'
        if integration_test?
          post login_path, session: { email:        user.email,
                                      password:     password,
                                      remember_me:  remember_me }
        else
          session[:user_id] = user.id
        end
      end

        private

        # Returns true inside an integration test.
        def integration_test?
          defined?(post_via_redirect)
        end
    end

Users.yml
microte:
      name: Lord Microte
      email: lord@microte.com
      password_digest: <%= User.digest('password') %>

I really would appreciate if someone could help out.

A: I had the same problem and it was because of password_digest in yml file
you need to choose one and commit to it.
ex:
in yml file:
password_digest: <%= User.digest('example') %>

then
in test_helper.rb
def log_in_as(user, options = {})
    password = options[:password]     || 'example'

and in user_login_test.rb
post login_path, session: { email: @user.email, password: 'example' }

A: i'm at the same chapter with the same problem. I've tried a lot of way to pass the test, and the strange thing is that the cookies['remember_token'] is nil only in test environment, while all works fine in development environment (i can see the remember_token cookie by inspecting it on the browser).
Anyway, i finished the chapter and start the exercises (the 2nd one), and guess?
Defining user as a instance variable (@user) in the current_user method in session_helper.rb and using assert_equal cookies['remember_token'], assigns(:user).remember_digest do the test pass.
I don't know why in the tutorial in 8.15 listing the test is GREEN, because everwhere i looked i found people with the same problem.
Hope this will help.

A: Was experiencing the same issue and went through the chapter again - and found in my app/helpers/sessions_helper.rb
def remember(user)
    user.remember
    cookies.permanent.signed[:user_id] = user.id
    cookies.permanent.signed[:remember_token] = user.remember_token
end

instead of:
def remember(user)
    user.remember
    cookies.permanent.signed[:user_id] = user.id
    **cookies.permanent[:remember_token] = user.remember_token**
end

Hope that helps!


text:
Q: Safari linear gradient I have a trouble using linear-gradient in Safari 15.2.
I wanna to create a block with fade effect at the end if children do not fit.
I have created an example: https://codepen.io/serejich/pen/xxXLvEG.
Code:

Element 1

Element 2

Element 3

* {
  margin: 0;
}

.gradient-container {
  background-color: coral;
  width: 200px;
  height: 30px;
  position: relative;
  display: flex;
  align-items: center;
}

.elements {
  padding: 0 10px;
  display: flex;
  column-gap: 10px;
  overflow-x: hidden;
}

.elements p {
  color: #fff;
  white-space: nowrap;
}

.gradient {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(to right, rgba(255, 255, 255, 0) calc(100% - 50px), coral);
}

If you will open this in Safari, there would be something like a white area at the right of block.
What causes this and are there any ways to fix it?

A: This is a bug in safari that has to do with the way browsers interpolate between gradients.
A common answer is to do what you did, using rgba(255, 255, 255, 0), however, Safari still interprets this as white and leads to that unwanted additional of white to the gradient. A fix is to use the same color you are transitioning from (coral in this case) and set it to transparent, which for coral would be rgba(255, 127, 80, 0). The example below uses the code from your pen with the fix applied for safari.
See this stack for more

* {
  margin: 0;
}

.gradient-container {
  background-color: coral;
  width: 200px;
  height: 30px;
  position: relative;
  display: flex;
  align-items: center;
}

.elements {
  padding: 0 10px;
  display: flex;
  column-gap: 10px;
  overflow-x: hidden;
}

.elements p {
  color: #fff;
  white-space: nowrap;
}

.gradient {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  /*RGBA equivalent to coral html color with alpha set to 0 - fixes safari interpolation bug*/
  background: linear-gradient(to right, rgba(255, 127, 80, 0) calc(100% - 50px), coral);
}

Element 1

Element 2

Element 3


text:
Q: Reduce the width of Bootstrap navbar item containing image I was designing a bootstrap navbar with a YouTube logo. Instead of aligning to right it is awkwardly placed in center. It seems the width of anchor is more than the size of image as result the image is pushed to right. How can I move it to right.

.navbar-brand{
  font-family: Lilita One;
}

.navbar-top{
  padding: 0 0;
}

.navbar{
  padding: 0 5% 0 2%;
}

.yt-img{
  width: 6%;
  position: relative;
}

.yt-img-a{
  width: 100%;
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Education Side</title>

  <link rel="icon" href="images\Icon.ico">

  <link rel="preconnect" href="https://fonts.gstatic.com">
  <link href="https://fonts.googleapis.com/css2?family=Lilita+One&family=Montserrat:wght@500&display=swap" rel="stylesheet">

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">

  <link rel="stylesheet" href="css/styles.css">

        Education
Side
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo02">

        </button>

              Counselling

              Recruitment

              Contact

enter image description here

A: The ms-auto class makes your ul to be placed on the right side.

 // ms-auto removed

Codepen Link: https://codepen.io/emmeiWhite/pen/JjRMxQw
Have fixed that and also added flex-grow:1 where ever needed  :)
Full Code:

.navbar-brand{
  font-family: Lilita One;
}

.navbar-top{
  padding: 0 0;
}

.navbar{
  padding: 0 5% 0 2%;
}

.yt-img{
  width: 6%;
  position: relative;
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Education Side</title>

  <link rel="icon" href="images\Icon.ico">

  <link rel="preconnect" href="https://fonts.gstatic.com">
  <link href="https://fonts.googleapis.com/css2?family=Lilita+One&family=Montserrat:wght@500&display=swap" rel="stylesheet">

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">

  <link rel="stylesheet" href="css/styles.css">

        Education
Side
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo02">

        </button>

              Counselling

              Recruitment

              Contact

A: Instead of setting the image width to 6%, use a px value such as 30px.
.yt-img{
  width: 30px;
  position: relative;
}

Demo


text:
Q: Firebase Error : Module not found: Error: Package path . is not exported from package I tried to implement Firebase on my React.JS app for authentification. However, I keep getting this error

ERROR in ./src/Pages/UserPage/contexts/AuthContext.js 8:0-32

Module not found: Error: Package path . is not exported from package /Users/Aarnav/Desktop/JavaScript/my-app copy 2/node_modules/firebase (see exports field in /Users/Aarnav/Desktop/JavaScript/my-app copy 2/node_modules/firebase/package.json)

My firebase setup looks like this,
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";

const firebaseConfig = {
  apiKey: "AIzaSyCPSbjZ9F1TgI43T0SH68rUi9TMHBXRw - s",
  authDomain: "csia-41409.firebaseapp.com",
  databaseURL: "https://csia-41409-default-rtdb.firebaseio.com",
  projectId: "csia-41409",
  storageBucket: "csia-41409.appspot.com",
  messagingSenderId: "714268776254",
  appId: "1:714268776254:web:93d9ef26a5d9c7d7f8be6f",
};

const app = initializeApp(firebaseConfig);

export const auth = getAuth();

and my authcontext looks
import React, { useContext, useState, useEffect } from "react"
import { auth } from "firebase";

const AuthContext = React.createContext();

export function useAuth() {
  return useContext(AuthContext);
}

export function AuthProvider({ children }) {
  const [currentUser, setCurrentUser] = useState();
  const [loading, setLoading] = useState(true);

  function signup(email, password) {
    return auth.createUserWithEmailAndPassword(email, password);
  }

  function login(email, password) {
    return auth.signInWithEmailAndPassword(email, password);
  }

   useEffect(() => {
     const unsubscribe = auth.onAuthStateChanged((user) => {
       setCurrentUser(user);
       setLoading(false);
     });

     return unsubscribe;
   }, []);

  auth.onAuthStateChanged((user) => {
    setCurrentUser(user);
  });

  const value = {
    currentUser,
    login,
    signup,
  };
  return (
    <AuthContext.Provider value={value}>
      {!loading && children}
    </AuthContext.Provider>
  );
}

Also for some reason my entire website is a blank white screen no matter which router(page) I am on. I believe this is because of the error mentioned on top but I am not sure.
At first I thought it was because I was using firebase version 9.14 however, I updated my setup for firebase but it was to no avail and the error still presisted. I have no idea how to remove the error.

A: In firebase V9, you should do signup and login with email and password in this way:
import { createUserWithEmailAndPassword, getAuth, signInWithEmailAndPassword } from "firebase/auth";

const auth = getAuth();

function signup(email, password) {
  return createUserWithEmailAndPassword(auth, email, password);
}

function login(email, password) {
  return signInWithEmailAndPassword(auth, email, password);
}


text:
Q: Facebook token log out invalidation I want to know if a user that logs out of Facebook even with 60 days access token (long lived) invalidates the token and I cannot access the user information.
If so, is there any way to solve this?
Thank you


text:
Q: Combine all columns into one with empty cells I want to combine large number of columns having similar data into one column. Rows in dataframe have a lot of empty cells as each row has its own column for this similar data. For eg:
Name    Weight  Addressw    Addressx    Addressy    Addressz
A       10                  11 g place
B       15      6, corner
C       24      15, lane                garbage
D       33                                          51, street

In the C row, as two columns contain info, I would like to take the first one, ie "15, lane" into new column. So the resulting dataframe would look like so:
Name    Weight  Address
A       10      11 g place
B       15      6, corner
C       24      15, lane
D       33      51, street

A: IIUC, you could do:
df['Address'] = df.lookup(np.arange(len(df)), (~df.iloc[:, 2:].isna()).idxmax(1))
result = df[['Name', 'Weight', 'Address']]

print(result)

Output
  Name  Weight     Address
0    A      10  11 g place
1    B      15   6, corner
2    C      24    15, lane
3    D      33  51, street

The approach will take the first valid address from each row.

A: If possible one or more addresses per rows use join in lambda function with remove possible missing values:
f = lambda x: ' '.join(y for y in x if pd.notna(y))
df = df.set_index(['Name', 'Weight']).agg(f, axis=1).reset_index(name='Address')
print (df)
  Name  Weight           Address
0    A      10        11 g place
1    B      15         6, corner
2    C      24  15, lane garbage
3    D      33        51, street

If exist always only one use ffill for forward filling missing values and selecting last column:
df = df.set_index(['Name', 'Weight']).ffill(axis=1).iloc[:, -1].reset_index(name='Address')
print (df)
  Name  Weight           Address
0    A      10        11 g place
1    B      15         6, corner
2    C      24  15, lane garbage
3    D      33        51, street


text:
Q: Ajax not firing in div populated by ajax I have a div which is populated via an ajax request.
Within the div is a form which when completed should use the same type of ajax request to populate a further div. I have used the same method to create both but the second javascript does not run:
First one (which works):

<form name="searchbysurname">
            Search by Surname: <input class="inline" type="text" name="q">
            <input type="submit"></form>

Second one (which is in the resultstable div) that doesnt work:
<? require_once("dbcontroller.php");
$db_handle = new DBController();

$q = ($_POST['q']);
$employees=array();
$sql = "SELECT employees.employeeid, employees.firstname, employees.surname FROM employees  where UCASE(employees.surname) LIKE UCASE('%".$q."%')";
$employees = $db_handle->runQuery($sql); ?>

<?
          if(isset($employees) && !empty($employees)){
          foreach($employees as $k=>$v) {
         ?>

<?php echo $employees[$k]["firstname"]; ?>  <?php echo $employees[$k]["surname"]; ?>
    <div id="viewemployeedetails<? echo $employees[$k]["employeeid"]?>">
        <form>
            <input type="hidden" name="id" value="<? echo $employees[$k]["employeeid"]?>">
            <input type="submit" value="View">
        </form>

A: I know it's not related to your question but you shouldn't be using the PHP short tag notation, it has been deprecated: https://softwareengineering.stackexchange.com/questions/151661/is-it-bad-practice-to-use-tag-in-php
Your first block of code is HTML with inline Javascript, which is an awful way to do things, you will get hard to debug errors if you insist on using Javascript in this way. You should be putting your Javascript in a separate file from the HTML and including it just before the final body tag. Ideally you should be using window.onload (or other similar methods, like a closure or jQuery's .ready() method) to ensure that DOM traversing elements of your script are only parsed after the DOM is fully loaded.
Your second block of Javascript code will never run because it doesn't exist when the browser parses the HTML. It's only injected later but Javascript doesn't work that way. You can inject javascript dynamically but not like that. You would have to do something like this:
var headID = document.getElementsByTagName("head")[0];
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = 'http://www.somedomain.com/somescript.js';
headID.appendChild(newScript);

I took this code from here: http://www.hunlock.com/blogs/Howto_Dynamically_Insert_Javascript_And_CSS


text:
Q: Perfomance Displaying Record In Single Page Application Rails I want displaying data from some model on one view. I'm build one page site.
def index
 @content = Content.where(:publish => true)
 @myaccount = Myaccount.where(:publish => true)
 @sliders = Slider.where(:publish => true)
end

I know, I can display them following like this:

  <% @myaccounts.each do |ma|  %>
   <%= ma.name %>
  <% end %>

  <% @contents.each do |co| %>
   <%= co.menu %>
  <% end %>

  <% @myaccounts.each do |mac|  %>
   <%= mac.title %>
  <% end %>

  <% @sliders.each do |sl|  %>
   <%= image_tag(sl.image_url) %>
  <% end %>

  <% @contents.each do |con|  %>
   <%= con.body %>
  <% end %>

Time
Completed 200 OK in 4679ms (Views: 1515.1ms | ActiveRecord: 2601.2ms)

If use <%= render 'file' %> , Time :
Completed 200 OK in 2673ms (Views: 2652.2ms | ActiveRecord: 18.0ms)

Is the correct way to display record on rails? If yes, is there a simple structure way to get them?

A: you could use partial for each model like,
show.erb.html

 render :partial => "my_accounts", :locals=>{myaccounts => @myaccounts}

and in  _my_accounts.erb.html

  <% @myaccounts.each do |ma|  %>
    <%= ma.name %>
  <% end %>

but your code will work fine, using partial will make it a bit cleaner.


text:
Q: Gstreamer record buffer to binary file I have some question about Gstreamer. I want to use Gstreamer to write buffer to file descriptor when receiving audio/video. I've tried to look up in GstBuffer function but It's cannot decoding binary file to audio. (I've been using Audacity to convert this raw binary file to media.) Please suggest me to implement that.
PS. Sorry for my bad in English, I'll try to more practices. :)


text:
Q: Qualcomm Atheros AR9485WB-EG network card wifi not working I recently installed Xubuntu on my laptop, dual booted with Windows.
Everything works perfectly on the Windows side, but Xubuntu for some reason either doesn't recognise or can't access my network card, so I can't connect to the wifi. I have updated the Kernel and Ubuntu itself, I have checked for driver updates for my network card and I couldn't find any (it's a Qualcomm Atheros AR9485WB-EG).
I know almost nothing about Linux and Ubuntu so I am clueless on how to solve this but I really need it to work as fast as possible so all help would be highly appreciated.
Edit:
lshw -c net
*-network DISABLED
   description: Wireless interface
   product: AR9485 Wireless Network Adapter
   vendor: Qualcomm Atheros
   physical id: 0
   bus info: pci@0000:03:00.0
   logical name: wlan0
   version: 01
   serial: 24:0a:64:cb:f1:7f
   width: 64 bits
   clock: 33MHz
   capabilities: pm msi pciexpress bus_master cap_list rom ethernet physical wireless
   configuration: broadcast=yes driver=ath9k driverversion=3.16.0-41-generic firmware=N/A latency=0 link=no multicast=yes wireless=IEEE 802.11bgn
   resources: irq:18 memory:f7900000-f797ffff memory:f7980000-f798ffff
  *-network
   description: Ethernet interface
   product: QCA8171 Gigabit Ethernet
   vendor: Qualcomm Atheros
   physical id: 0
   bus info: pci@0000:04:00.0
   logical name: eth0
   version: 10
   serial: bc:ee:7b:46:f6:ed
   size: 100Mbit/s
   capacity: 1Gbit/s
   width: 64 bits
   clock: 33MHz
   capabilities: pm pciexpress msi msix bus_master cap_list ethernet physical tp 10bt 10bt-fd 100bt 100bt-fd 1000bt-fd autonegotiation
   configuration: autonegotiation=on broadcast=yes driver=alx duplex=full ip=192.168.1.2 latency=0 link=yes multicast=yes port=twisted pair speed=100Mbit/s
   resources: irq:52 memory:f7800000-f783ffff ioport:d000(size=128)

uname -a
Linux XubuntoV2 3.16.0-41-generic #57~14.04.1-Ubuntu SMP Thu Jun 18 18:01:13 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux

rfkill list all
0: phy0: Wireless LAN
Soft blocked: no
Hard blocked: no

1: acer-wireless: Wireless LAN
Soft blocked: yes
Hard blocked: no

4: hci0: Bluetooth
Soft blocked: no
Hard blocked: no

A: Used this command:
echo "blacklist acer_wmi" | sudo tee -a /etc/modprobe.d/blacklist.conf

Then this one:
sudo nano /etc/modprobe.d/ath9k.conf

Set the option
options ath9k nohwcrypt=1

Then saved it, did unblock all
rfkill unblock all

and restarted, works perfectly now.


text:
Q: `[ "$(...)" = *FAIL* ]` not working in POSIX sh script Here's a sample from .sh script:
#!/bin/sh

........

if [ "$(tail -n 1 log_file.txt)" = *"FAIL"* ]; then
  exit 1
else
  # some command here
  exit 0
fi

It must match last line of some file with pattern "FAIL" and if result of matching is true return exit code 1 otherwise 0.
In this case script is always terminated with exit code 0 even for those strings that don't contain FAIL substring.
Please help me to fix if statement.
P.S. shebang must be #!/bin/sh not #!/bin/bash

A: If you want fnmatch/glob-style matches in sh, use case, not if.
case "$(tail -n 1 log_file.txt)" in
  *"FAIL"*) exit 1;;
  *)        : "some command here"; exit 0;;
esac

A: You don't need an if statement, as you want to exit immediately in either case. Just make the check the last command of the script.
In this case, the exit status of the script would be the negation of the exit status of grep (which exits 0 if it finds a match and 1 if not).
! tail -n 1 log_file.txt | grep '.*FAIL.*'


text:
Q: Invisble ReCaptcha: preventing image challenge before submiting form I've added Google invisible recaptcha to an Ajax (Javascript / PHP) form on a web page (see html + js on client side below). Everything works fine except that too often Google invisible Recaptcha launches the image challenge at webpage load and at form submission.
This is very annoying because the page including this submission form is the homepage of the website (in fact it's a petition signing website for an association).
Which leads to the problem that the user can see image challenge even before getting main information from the website and deciding to sign or not the petition. This is a bad user experience.
Is there a way to prevent this behavior. Configuring Google Recaptcha in such a way that It's not challenging before the user clicks on the submit button?
Thanks a lot for your precious help :o)!
Laurent
Javascript code:
    window.onScriptLoad = function () {

        var htmlEl = document.querySelector('.g-recaptcha');

        var captchaOptions = {

          'sitekey': 'xxxxxxxxxxxxxxxxxxxxxxxxxxx',
          'size': 'invisible',
          'badge': 'inline',
          callback: window.onUserVerified

         };

        var inheritFromDataAttr = true;

        recaptchaId = window.grecaptcha.render(htmlEl, captchaOptions, inheritFromDataAttr);

        console.log('recaptchaId=', recaptchaId);

        window.grecaptcha.execute(recaptchaId);

    };

    window.onUserVerified = function (token) {

        console.log('token=', token);

    };

    function onSubmitBtnClick () {

      var token = window.grecaptcha.getResponse(recaptchaId);

      console.log('token=', token);

      if (!token) {

         window.grecaptcha.execute(recaptchaId);
         return;

      }

      $.ajax({

            url: 'process.php',
            type: 'post',
            dataType: 'json',
            data : {

                'lastname'   : $("#lastnameField").val(),
                'firstname'  : $("#firstnameField").val(),
                'city'       : $("#cityField").val(),
                'postalCode' : $("#postalcodeField").val(),
                'g-recaptcha-response' : token

            },

            success:function(data) {

                // informs user that form has been submitted
                // and processed

                },

            error: function(xhr, textStatus, error){

                  console.log(xhr.statusText);
                  console.log(textStatus);
                  console.log(error);
            }

       });

HTML code:

    ...

     <form id="petitionForm" onsubmit="return false;">

         <input id="lastnameField" type="text" name="lastname" placeholder="Lastname" required value="Doe">
         <input id="firstnameField" type="text" name="firstname" placeholder="Firstname" required value="John">
         <input id="postalcodeField" type="text" name="postalCode" placeholder="Postal Code" required value="ABCDEF">
         <input id="cityField" type="text" name="city" placeholder="City" value="Oslo">
         ....

         <input type="submit" name="login" class="g-2" data-sitekey="xxxxxxxxxxxxxxxxxxxxxxx" id="signButton" data-callback='' value="Signer" onclick="onSubmitBtnClick();">

       </form>

       ...

A: For me in onScriptLoad function you must remove
window.grecaptcha.execute(recaptchaId);

I guess this execute recaptcha onload