text:
Q: Why am I getting AttributeError: 'NoneType' object has no attribute 'send' and how to avoid it? I get the following error when running scrapeBackend.py
AttributeError: 'NoneType' object has no attribute 'send'

I am trying to use the send_topic method inherited from the ProducerConsumer class in customKafka.py
import time
import pymongo
from pymongo import MongoClient
from customKafka import ProducerConsumer

class scrapeBackend(ProducerConsumer):

    def run(self):
        ARTICLE_SCRAPED_KAFKA_TOPIC = "raw_text"
        ARTICLE_LIMIT = 20
        print("Generating raw article")
        print("generating every 3 seconds")

        for i in range(1,ARTICLE_LIMIT):
            data={
                "article_id": i,
                "source" : "bbc",
                "article" : "this is an article"
            }
            super().send_topic("raw_text",data)
            #collection.insert_one(data)
            print(f"done sending {i}")
            time.sleep(3)

scrap1=scrapeBackend(True,False,"raw_text","localhost:29092")

scrap1.run()

customKafka.py
from kafka import KafkaConsumer
from kafka import KafkaProducer
import json
class ProducerConsumer:
    __isProducer=None
    __isConsumer=None
    __producer=None
    __consumer=None

    def __init__(self,isProducer,isConsumer,topic,bootstrap_servers):
        if (self.__isProducer):
            self.__producer=KafkaProducer(bootstrap_servers=bootstrap_servers)
        if (self.__isConsumer):
            self.__consumer= KafkaConsumer(
                topic,
                bootstrap_servers=bootstrap_servers,
                auto_offset_reset='earliest',
                enable_auto_commit=True,
                consumer_timeout_ms = 10000)

    def get_producer(self):
        return self.__producer

    def get_consumer(self):
        return self.__consumer

    def send_topic(self,topic,data):
        self.get_producer().send(topic, json.dumps(data).encode("utf-8"))

Looks like the getProducer() is returning None however it should return something since I initaliazed before running

A: The issue is in your __init__ function of parent class.
It should be implemented like this:
def __init__(self,isProducer,isConsumer,topic,bootstrap_servers):
        if isProducer:
            self.__producer=KafkaProducer(bootstrap_servers=bootstrap_servers)
        if isConsumer:
            self.__consumer= KafkaConsumer(
                topic,
                bootstrap_servers=bootstrap_servers,
                auto_offset_reset='earliest',
                enable_auto_commit=True,
                consumer_timeout_ms = 10000)

Notice the difference in the if statements. Hope this helps!!

A: you should call super() in your __init__ of the subclass then, you should be able to call the function send_topic from the object scrap1
class scrapeBackend(ProducerConsumer):
    def __init__(self, *args, **kwargs):
        super(scrapeBackend, self).__init__(*args, **kwargs)

    def run(self):
        ARTICLE_SCRAPED_KAFKA_TOPIC = "raw_text"
        ARTICLE_LIMIT = 20
        print("Generating raw article")
        print("generating every 3 seconds")

        for i in range(1,ARTICLE_LIMIT):
            data={
                "article_id": i,
                "source" : "bbc",
                "article" : "this is an article"
            }
            self.send_topic("raw_text", data)
            #collection.insert_one(data)
            print(f"done sending {i}")
            time.sleep(3)

and your __init__ of ProductConsumer can't deal with input parameters (the 2 if-conditions), it should be implemented like this:
class ProducerConsumer:
    def __init__(self,isProducer,isConsumer,topic,bootstrap_servers):
        if isProducer:
            self.__producer = KafkaProducer(bootstrap_servers=bootstrap_servers)
        if isConsumer:
            self.__consumer = KafkaConsumer(
                topic,
                bootstrap_servers=bootstrap_servers,
                auto_offset_reset='earliest',
                enable_auto_commit=True,
                consumer_timeout_ms = 10000)

    def get_producer(self):
        return self.__producer

    def get_consumer(self):
        return self.__consumer

    def send_topic(self,topic,data):
        self.get_producer().send(topic, json.dumps(data).encode("utf-8"))


text:
Q: Synctex don't work with tabularray package With the tabular environment I can jump to the correct line with inverse search: ctrl click in the pdf output (with Texstudio or Texworks). Why it doesn't work with the tabularray package?
\documentclass{article}
\usepackage{tabularray}

\begin{document}
\begin{tabular}{|l|l|}
    \hline
    a & b \\
    \hline
    c & d \\
    \hline
    e & f \\
    \hline
\end{tabular}

\begin{tblr}{|l|l|}
    \hline
    a & b \\
    \hline
    c & d \\
    \hline
    e & f \\
    \hline
\end{tblr}
\end{document}

A: You can use my new package. Currently it's not on CTAN yet, so it's subject to change.
You need to get the source code on https://github.com/user202729/TeXlib and compile the file with LuaLaTeX.
%! TEX program = lualatex
\documentclass{article}
\usepackage{tabularray}
\usepackage{cprotectinside}
\cprotectinsideEnableSyncInner

\begin{document}

\cprotectinside{!}{
\begin{tblr}{|l|l|}
    \hline
    !a! & !b! \\
    \hline
    !c! & !d! \\
    \hline
    !e! & !f! \\
    \hline
\end{tblr}
}

\cprotectinside{!}{
\begin{tblr}{|l|l|}
    \hline
    !a! & !b\hspace{0pt}! \\
    \hline
    !c! & !d\hspace{0pt}! \\
    \hline
    !e! & !f\hspace{0pt}! \\
    \hline
\end{tblr}
}

a%
a%
a
a%
a%
a%

\end{document}

Remark:

*

*as you can see, you need to manually wrap each cell (although this can be somewhat "automated" by using regex etc. to parse the table content)

*you need to add some space for synctex to work properly. The first table doesn't work because there's no space, the second table works even if a zero-width space is added.
This is an inherent limitation in TeX, as you can see in the last paragraph there are 6 as; however synctex is only accurate on a "word" level (where there are space between), it cannot distinguish between the 3 first a or 3 last a since there's no "space" between them.
It appears that tabular environments uses "real space" to split the rows so this is not necessary; however for tabularray it's necessary because (I assume) it uses a different mechanism to arrange the table.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Update redux in the reactjs function, then use the state I need to open a search aid and select a value there and get it back.
When I click on the button, I open a search help, I put the data I selected into a store, but how can I use it when I come back?
I need to write the data I selected from the search help directly into an input on the front side.
   async showPopup(){
      const LazyLoadingComponent=await import('../../CP/SearchHelp/searchHelp');
      this.setState({lazyLoadComponent:React.createElement(LazyLoadingComponent.default)});
      await ShowPopup('http://localhost:3070/api/WorkCenter/GetWorkCenters');
      console.log(this.state.selectedRow);
      if(this.state.selectedRow!==''){
        this.setState({WorkCenterCode:this.state.selectedRow.WorkCenterCode});
      }
    }

Here in some way I have to wait until the page is imported.
In the showpopup, I actually show the data that needs to be updated by updating the redux in the search help.
export async function ShowPopup(apiUrl){
    var apiData=await APIGetWorkCenters(apiUrl);
    SearchHelApiData(await JSON.parse(apiData.data));
    SearchHelPopupOpen(true);
}

export const SearchHelPopupOpen=(popupOpen)=>{
    store.dispatch({
        type:'SearchHelp_popupOpen',
        popupOpen:popupOpen
    });
}

export const SearchHelApiData=(apiData)=>{
    store.dispatch({
        type:'SearchHelp_apiData',
        apiData:apiData
    });
}

Here I need to make my searchhelp component async and component until closing.
I share the codes of the searchhelp component below.
class SearchHelp extends BasePage {

  constructor(props){
    super(props);
    this.connect(['SearchHelp']);
    this.onSelectionChanged = this.onSelectionChanged.bind(this);
  }

  componentDidMount(){
    SearchHelSelectedRow('');
  }

    toggle = () => {
      SearchHelApiData('');
      SearchHelPopupOpen(false);
    }

    onSelectionChanged({ selectedRowsData }) {
      const data = selectedRowsData[0];
      SearchHelSelectedRow(data);
      SearchHelApiData('');
      SearchHelPopupOpen(false);
    }

    render() {
      return (
        <MDBContainer>
          <MDBModal  size="md" isOpen={this.state.popupOpen} toggle={this.toggle} centered backdrop={false}>
            <MDBModalHeader className="" toggle={this.toggle}></MDBModalHeader>
            <MDBModalBody>
            <DataGrid
                dataSource={this.state.apiData}
                selection={{ mode: 'single' }}
                showBorders={true}
                hoverStateEnabled={true}
                keyExpr={'WorkCenterId'}
                onSelectionChanged={this.onSelectionChanged} >
              </DataGrid>
            </MDBModalBody>
          </MDBModal>
        </MDBContainer>
        );
    }
}

I'm waiting for your help..
----------EDIT-------------
I solved my problem with the componentDidUpdate() method.
  componentDidUpdate(){
      if(this.state.selectedRow!=='' && this.state.selectedRow!==undefined){
        SearchHelSelectedRow('');
        if(this.state.selectedRow.WorkCenterId!==undefined){
        this.setState({WorkCenterCode:this.state.selectedRow.WorkCenterCode});}
        if(this.state.selectedRow.ReasonCode!==undefined){
          this.setState({ReasonCode:this.state.selectedRow.ReasonCode});}
      }
    }

    async showPopupWorkCenter(){
      await ShowPopup('http://localhost:3070/api/WorkCenter/GetWorkCenters');
    }

    async showPopupReasons(){
      await ShowPopup('http://localhost:3070/api/Reason/GetReasons');
    }

A: In order for you to use Redux in your SearchHelp component and gain access to the Redux store, you need to connect your component to the store which I don't see you doing.
You need to three things basically to get things working, a reducer, actionCreator and a store to hold state changes. When you have these then you would have to connect your component to the store by using the connect higher order function which takes two arguments and wraps your component giving you access to the data stored in the store.
As an example, given your component SearchHelp, you can connect to the store by doing this:
import { connect } from 'redux'

class SearchHelp extends BasePage { ... }

function mapStateToProps(state) {
   // this function has access to your redux store, so you can access the properties there
   // it should return an object
   return {
      stateProp1: state.stateProp1,
      stateProp2: state.stateProp2,
      ...
   }
}

function mapDispatchToProps() {
   // this function is not required as you could simply pass in your actions directly
}
export default connect(mapStateToProps, mapDispatchToProps)(SearchHelp)

An example reducer looks like below:
function reducerName(state = {}, action) {
   switch(action.type) {
      case ACTION_TYPE:
      return { stateProp1: action.data // };
      ...

      default:
      return state;
   }
}


text:
Q: How to receive layer data features in geoserver? I'm developing module in GeoServer that needs Layer feature members.
I can get it easily with WFS request like this
ows?service=WFS&version=1.0.0&request=GetFeature&typeName=workspace:layer&maxFeatures=50

But I need to achieve it internally in GeoServer(I mean something like this catalog.getFeatureMembersByName("workspace:layer"))
I know that I can send request in GeoServer internally but I don't think that is proper way. I don't want to talk directly with database because I need in this module GeoFence features.
Is it possible to achieve this?

A: Something like this (might need minor corrections) should work:
FeatureTypeInfo info = catalog.getFeatureTypeByName(getLayerId(MockData.BASIC_POLYGONS));
SimpleFeatureSource fs = (SimpleFeatureSource) info.getFeatureSource(null, null);
try(SimpleFeatureIterator fi = fs.getFeatures().features()) {
    SimpleFeature sf = fi.next();
    System.out.println(sf);
}


text:
Q: Laravel Authentication Problems First off I am fairly new to Laravel.
So I have a form in my header on each page and that is pointing to a POST request. I know that I have the proper user email and password in my mySQL database but when I try to login the 'if(Auth::attempt($userdata))' always fails.
Form:
@if(Auth::check())

Home

Profile

Logout
    @else

    {{ Form::open(array('url' => '/account/sign-in')) }}

        <input type="email" name="email" class="form-control input-sm" placeholder="Email">
        <input type="password" name="password" class="form-control input-sm" placeholder="Password">

          <input type="checkbox"> Remember me

        <button type="submit" class="btn btn-default btn-sm">Login</button>
    {{ Form::close() }}

POST:
Route::post('/account/sign-in', function(){
        $userdata = array(
            'email' => Input::get('email'),
            'password' => Input::get('password')
        );

        if(Auth::attempt($userdata)){
            return 'Success';
        }else{
            return 'Fail';
        }
     });

I also have included the $fillable in my User.php model:
protected $fillable = array('firstname', 'lastname', 'password', 'email', 'code', 'active');

Registration method:
public function postCreate(){
    $validator = Validator::make(Input::all(),
        array(
            'firstname' => 'required',
            'lastname' => 'required',
            'email'    => 'required|max:50|email', // make sure the email is an actual email
            'password' => 'required|alphaNum|min:3', // password can only be alphanumeric and has to be greater than 3 characters
            'password_confirmation' => 'required|same:password'
        )
    );

    if($validator->fails()){
        return Redirect::route('account-create')->withErrors($validator)->withInput();
    }else{

        //Activation Code
        $code = str_random(60);

        $user = new User;
        $pass1 = Input::get('password');
        $pass2 = Input::get('password_confirmation');
        $firstname = Input::get('firstname');
        $user->firstname = Input::get('firstname');
        $user->lastname = Input::get('lastname');
        $user->email = Input::get('email');
        $user->code = $code;
        $user->active = 0;
        if($pass1 == $pass2){
        $user->password = Hash::make(Input::get('pass1'));
        }else{
            return Redirect::to('register/');
        }
        $user->save();
    }

        if($user){
            //send email
            Mail::send('emails.auth.activate', array('link' =>URL::route('account-activate', $code), 'firstname' => $firstname), function($message) use($user){
                $message->to($user->email, $user->firstname)->subject('Activate your Account');
                });

            return Redirect::to('/')->with('global', 'Your account has been create! We have sent you an email to activate your account');
        }
}

Sign in method in UsersController:
public function postSignIn(){
    $validator = Validator::make(Input::all(),
        array(
            'email' => 'required',
            'pasword' => 'required'
        )
    );

    if($validator->fails()){
        return Redirect::to('/')->withErrors($validator)->withInput();
    }else{
        $user = array(
            'active' => 1,
            'email' => Input::get('email'),
            'password' => Input::get('password')
        );

        if(Auth::attempt($user)){
            //Redirect to intended page
            return Redirect::intended('/')->with('global', 'Success!!');
        }else{
            /*return Redirect::to('/')->with('global', 'Failed to login');*/
            return Input::all();
        }
    }
    return Redirect::to('/')->with('global', 'There was a problem signing in. Did you activate?');
}

View:

    @if(Auth::check())

Home

Profile

Logout

    @else

    {{ Form::open(array('url' => '/account/sign-in')) }}

        <input type="email" name="email" class="form-control input-sm" placeholder="Email">
        <input type="password" name="password" class="form-control input-sm" placeholder="Password">

          <input type="checkbox"> Remember me

        <button type="submit" class="btn btn-default btn-sm">Login</button>
    {{ Form::close() }}

Register

    @endif

Thanks

A: From your files at dropbox, your postSignIn method at UsersController has 'pasword' => 'required'.


text:
Q: TeamViewer does not start automatically, how do I make sure it does? After installing TeamViewer x86 on Ubuntu, it will not start automatically on boot, even when telling it to do so via the application settings ("Start TeamViewer with system"). How do I make sure TeamViewer starts with the system, before even logging in?

A: TeamViewer provides a script called teamviewerd.sysv available in /opt/teamviewer/tv_bin/script. Here's an excerpt:
#!/bin/bash
#
# /etc/init.d/teamviewerd
#
# chkconfig: 2345 95 05
# description: daemon for TeamViewer
#
# processname: teamviewerd
# config: /etc/teamviewer/global.conf
# pidfile: /var/run/teamviewerd.pid

### BEGIN INIT INFO
# Provides:          teamviewerd
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Required-Start:    $all
# Required-Stop:     $local_fs $network $named
# Short-Description: TeamViewer remote control daemon
# Description:       TeamViewer remote control daemon
### END INIT INFO

All you need to do is make sure this script runs on startup. Making sure of this is relatively simple, just copy it to /etc/init.d like so:
cd /opt/teamviewer/tv_bin/script
sudo cp teamviewerd.sysv /etc/init.d/

Don't forget to make the script non-writable to anyone but the owner!
sudo chmod 755 /etc/init.d/teamviewerd.sysv

Then run
sudo update-rc.d teamviewerd.sysv defaults

The service will now start automatically with each boot. If you don't feel like rebooting, you can start the service manually with:
sudo service teamviewerd.sysv start

2019 EDIT: This answer was written in 2013. Since then, systemd has arrived in force and is normally used for constructing services that start upon boot. For instructions on how to achieve this in systemd instead, please see this question: How do I run a single command at startup using systemd?

A: I was using Teamviewer version 9 and there is option Start TeamViewer with system. By enabling this option, teamviewer register as a system service and automatically start with the system. Reboot system and it starts with the system before logging in.

In Teamviewer 11, it can be enabled from the main desk.

A: Create a soft-line of teamviewer in your run level file location. You can do that by using:
sudo ln -s /usr/bin/teamviewer /etc/init.d/

or if your system is using systemctl then use:
sudo ln -s /usr/bin/teamviewer /etc/rc.d/rc5.d/

A: The simplest way is:
In TeamViewer, go to Extras > Options > General > check the box next to "Start TeamViewer with system"/
You will need to assign the computer to your account otherwise passwords can change anytime.


text:
Q: Limit of the smallest eigenvalue of a random Gram matrix $XX^T/n$. Let $X\in\mathbb{R}^{n\times d}$ be a random matrix with independent rows which satisfy that $\mathbb{E}(X_iX_i^T) = I_d$ and $\mathbb{E}(X_i) = 0$. The results of P. Yaskov provide conditions on when the minimum eigenvalue of the covariance matrix $X^TX/n\in\mathbb{R}^{d\times d}$ is lower bounded in the case that $d/n \to \rho <1$.
Is it possible to obtain conditions on when the smallest eigenvalue of $XX^T/n\in\mathbb{R}^{n\times n}$ (so the smallest positive eigenvalue of $X^TX/n$)  is lower bounded in the case that $d/n \to \rho \geq 1$.


text:
Q: Causing a rotating arc to touch another curve and not intersect it (Matlab code) I want to write a code where an arc stops rotating as soon as it comes in contact with a semi-circle.
I have written a code to do so, my arc does not just touch the circle but it slightly intersects it.
I have put rotation of arc inside a while loop by using linspace() to change theta. I used polyxpoly() for finding intersection. Condition for the while loop is that as long as I have empty array the loop continues, but as soon as I get a value from polyxpoly() my loop stops.
However, at the place of touch the theta value exceeds what I needed, so as a result I get an intersection.
How do I modify the code so that the arc will touch the semi-circle and not intersect it?
Here is the output. Click the link below
Image of intersection but I need touch and not intersection
clc,clear
R = 5;                     % radius of a circle
r = 10;                    % radius of arc
aa = 60*pi/180;            % arc angle
ap = 0*pi/180;             % arc position angle

% defining the semi-circle about the origin

t = linspace(0,pi);
[x,y] = pol2cart(t,R);      % circle data

% Shifting circle centre to (3.5,0)
x=x+3.5;
y=y+0;

% defining the arc about the origin
t1 = linspace(0,aa)-aa/2+ap;
[x1,y1] = pol2cart(t1,r); % arc data

% shifting arc-lower-end to (14,0)
delx=14-x1(1); % Finding the x difference between arc-lower-end x-coordinate & 14
dely=0-y1(1); % Finding the y difference between arc-lower-end y-coordinate & 0

x1=x1+delx;
y1=y1+dely;

theta =linspace(0,pi,1000);
i=1;
xc=[];
yc=[];

while isempty(xc)&& isempty(yc)

    % create a matrix of these points, which will be useful in future calculations
    v = [x1;y1];

    % choose a point which will be the center of rotation
    x_center = 14;
    y_center = 0;

    % create a matrix which will be used later in calculations
    center = repmat([x_center; y_center], 1, length(x1));

    % define a 60 degree counter-clockwise rotation matrix
    R = [cos(theta(i)) -sin(theta(i)); sin(theta(i)) cos(theta(i))];

    % do the rotation...
    s = v - center;     % shift points in the plane so that the center of rotation is at the origin
    so = R*s;           % apply the rotation about the origin
    vo = so + center;   % shift again so the origin goes back to the desired center of rotation

    % this can be done in one line as:
    % vo = R*(v - center) + center
    % pick out the vectors of rotated x- and y-data
    x_rotated = vo(1,:);
    y_rotated = vo(2,:);

    [xc,yc] = polyxpoly(x_rotated,y_rotated,x,y)
    [xc1,yc1] = polyxpoly(x1,y1,x,y)

    i=i+1;
end

% make a plot
plot(x,y)
hold on

plot(x1, y1, 'k-', x_rotated, y_rotated, 'r-', x_center, y_center, 'bo');
axis equal

I need to find way it contacts a circle and does not intersect it.
The code is in matlab.
Any suggestions are welcome.

A: This is the problem of collision detection. Most, if not all, methods I know of in collision detection requires the computer to check for intersections of some sort. It's very difficult (if not impossible) to have two objects "just touch" in simulations, because you'll need the precise (analytically solved) location of the boundaries of those objects.
polyxpoly() is a function to return the intersection of two polygons. So unfortunately, if you insist that the arc cannot touch, then you cannot use polyxpoly(). In that extreme case, you'll have to solve some mathematical equation for when the tip of the arc coincides with a point on the circle perfectly, then simulate up until that point in time.
But realistically, what you need is a finer simulation (although I personally think what you have alone is good enough). So in every simulation step, you calculate a smaller movement, so that when the arc eventually intersects, only a very small amount of the arc intersects.


text:
Q: Google Sheet Custom Function works on one sheet, fails on another - same permissions I have two sheets, similar columns, where a custom function returns a value from subsequent cells in the row. Both sheets are in the same folder and I have the same edit permission on both.
On one sheet, the function works perfect. On another sheet, the function fails with a

"You do not have permission to access the requested document."

In most cases this error either indicates you are accessing another doc/sheet or the person running the script does not have access to the current (active) sheet. I believe it can also happen if attempting to use .setValue().
However, this is a custom function and I am neither accessing any other sheet/document. My access allows me to edit the sheet, though custom functions do not run as a given user and have some restrictions.
I did some research and found I could not run any of these commands. This is NOT exhaustive, just some of the data gathering functions I cannot run.
sheet.getLastColumn();
cell.getValue();
sheet.getRange(rangeParameters).getValues();

I can, however, use:
sheet.getRange(rangeParameters);
cell.getRow();
cell.getColumn();

So, in effective, I can create a range object, a cell object, a sheet object, but I cannot return any values. Odd also that I cannot get the last column (or last row) of a sheet but can get the row or column of a cell.
Again - the exact code runs perfectly on one sheet, fails on the other.
Due to the organization I work for I cannot share much more information. Suffice to say, all scripts and sheets allowed to run scripts to through an approval process. I work on the team that provides that access. Both spreadsheets have the same access granted.
I have not found anything limiting script access in the Workspace admin console. However, here is some code I wrote that works on one sheet, fails on the other.
function returnStatus(input) {
  const ws = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = ws.getActiveSheet();
  const cell = sheet.getActiveCell();
  const row = cell.getRow();
  const column = cell.getColumn();
  const cellVal = cell.getValue();  //FAILS HERE
  return row;
}

I've noted where it fails.
I'm curious if anyone knows why a custom function this simple would fail with that error. Are there Workspace settings that I'm missing?


text:
Q: Using map in scheme I've created a procedure called movies-satisfying:
(define movies-satisfying
    (lambda (movies pred selector)
      (map (pred movies))))

This is how I call the procedure.
(movies-satisfying our-movie-database
               (lambda (movie)
                 (= (movie-year-made movie) 1974))
               movie-title)

the movie title = car.
our-movie-database is a database of movies.
Which returns a lot of information about the movie from a database starting with movie title, director, date it was made, and actors. How do I return just the movie title instead of the entire list?
This is what currently gets returned:
 (((amarcord)
  (federico fellini)
  1974
  ((magali noel) (bruno zanin) (pupella maggio) (armando drancia)))

A: It's not possible to give a perfect answer without knowing more of the code (as stated in my comment), but I can outline the answer, the trick is to make two passes - of course, assuming that both the predicate and the selector are correctly defined. For example, a search in particular will look like this:
(map (lambda (movie) ; 2nd pass: obtain the names of the movies returned by 1st pass
       (movie-title movie))
     (filter (lambda (movie) ; 1st pass: obtain only the movies of a given year
               (= (movie-year-made movie) 1974))
             our-movie-database))

To write the above as a parameterizable function, just pass the lambdas along, as parameters:
(define movies-satisfying
  (lambda (movies pred selector)
    (map selector (filter pred movies))))

Also be aware that filter must be used to find matches for a given predicate, map will always return a list of the same size of the original input list.


text: Q: Modular Inverse Notation I know how to get a inverse but I don't know how to put it into equations.  So let $5^{-1}$ exist in mod m.  Is $5^{-1}$, $1/5$, $-5$, or the modular inverse number.  To put it more generally, is $5^{-1}$ a notation or really a power of $-1$?


text:
Q: jquery sortable: change the css of current drag item I using jquery-ui sortable, and I am having trouble change the way of how dragged-item look when it being dragged. What I want is text value of the component inside the red bg container when I drag. Please help
here is what I got so far http://jsfiddle.net/Fyd48/5/. This is about 90% working. If you drag super dooper it have bg color red like I want it, but it still have the gray box around, that make it look weird. , I dont know where that gray box come from, but please help remove it.
$( "#container" ).sortable({
start: function(event, ui){
   var text = $.trim(ui.item.text());
   ui.item.startHtml = ui.item.html();

   ui.item.html('
' + text + '
');
},
stop: function(event, ui){
   ui.item.html(ui.item.startHtml);
}
});
$( "#container" ).disableSelection();

A: You have background-color: rgb(245, 245, 245); as a css style in each of your draggable divs, if you remove it the gray box will not be there when you drag.
Fiddle : http://jsfiddle.net/Fyd48/10/

A: The gray background comes from these DIVs:

The red DIV that you create on drag is smaller than the containing div, letting the parent background color show through. Try setting height and width to 100% on the red DIV:
ui.item.html('
' + text + '
');

(Of course better to put the styling attributes in the style tag, instead of having inline styling)


text:
Q: Web Api Content.ReadAsAsync method not found, but code compiles I am using System.Net.Http.HttpClient to access a rest service. This code compiles and runs just fine:
var client = new HttpClient();
var result = client.GetAsync(ServiceUrl + "/whatever").Result;
var content = result.Content.ReadAsAsync<StatusReport>().Result;

However the ReadAsAsync method is colored red in my IDE, and intellisense cannot find it. I have made sure to update all of my nuget packages. Referenced and added using statement for System.Net.Http.Formatting, but error persists (and resharper tells me the using statement is unused).
I am not sure if this is a problem with visual studio 2012, or with resharper 7. Sometimes restarting visual studio helps, and sometimes it doesn't. I suspect I may have some older version of some assembly referenced, or something like that, but I have updated everything I know how and the problem is still intermittent.
What else can I try?

A: Try clearing your resharper cache. (ReSharper > Options > Environment > General > Clear Caches)
HttpClient is new in 4.5 AFAIK and maybe your assemblies are cached from 4.0 or something?

A: You must add reference from Nuget "ASP.NET Web API 2 Client". Microsoft.AspNet.WebApi.Client


text:
Q: Displaying negative values in a DataGridView without parentheses I have a DataGridView object on my form that is linked to a dataTable populated based on a variable SQL query.
My problem comes with the way that negative values are displayed with the .DefaultCellStyle.Format value set to "c" for currency.  For some reason, it places negative values within parenthesis, i.e. (100 000) instead of - 100 000
I use :
dgvprod.Columns[2].DefaultCellStyle.Format = "c0";
dgvprod.Columns[2].DefaultCellStyle.FormatProvider = CultureInfo.GetCultureInfo("fr-SN");

and Its displays by exemple (400 000) rather than -400 000
someone could help me to change it please ?
thank you in advance

A: Try the format
"#,0 CFA;-#,0 CFA"

The first section applies to 0 and positive values, the second to negative values.
Or simply
"#,0 CFA"

But the result depends on the specific culture and culture settings in Windows.
The value must be of a numeric type. If it is a string, it cannot be formatted.
See also: Custom numeric format strings


text:
Q: Creating a work hours component - How to useState with multiple values going into an array To clarify my question - I'm build a component that will set the work hours for a worker during the week. I don't need the work day as I'm just gonna use the index of the array for the work day (0 - Sunday, 1 - Monday.. etc). So currently the workingDaysOfWeek is just to display them. There will be 2 textfields to enter in a start time and an end time. I need to figure out how to add these times to an array.. which eventually will be added to one big array that will determine which work day those hours correspond too. So in short. I need an array that holds 2 values.. a start and end time. The 0 index should be the start and 1 index should be the end. Here is kind of the schema I'm looking for and also the component
The current code below will keep giving undefines when I change the text fields... I tried using unshift and push however this only worked for one of them and not the other. I'm not use how to add these times seperately into the array or if using useState is the best idea.
{
  "working_hours": [
    ["09:00:00Z-07:00:00", "17:00:00Z-07:00:00"], // Monday
    ["09:00:00Z-07:00:00", "17:00:00Z-07:00:00"],
    ["09:00:00Z-07:00:00", "17:00:00Z-07:00:00"],
    ["09:00:00Z-07:00:00", "17:00:00Z-07:00:00"],
    ["09:00:00Z-07:00:00", "15:00:00Z-07:00:00"],
    null, // Saturday
    null // Sunday
  ]
}

WorkingDays
const WorkingDays = () => {
  const workingDaysOfWeek = [
    'Monday',
    'Tuesday',
    'Wednesday',
    'Thursday',
    'Friday',
    'Saturday',
    'Sunday'
  ]
  const [workingDaysHours, setWorkingDaysHours] = useState([])

  function handleStartChange(e){
    console.log(e.target.value)
    setWorkingDaysHours(e.target.value)
    console.log(workingDaysHours)
  };

  function handleEndChange(e) {
    console.log(e.target.value)
    setWorkingDaysHours(e.target.value)
    console.log(workingDaysHours)
  }

  return (
    <form noValidate>
        {
          workingDaysOfWeek.map((days,index) => (
            <Grid container direction={'row'}>
            <Grid item xs={2}>
              <Typography >
                {days}
              </Typography>
            </Grid>
          <Grid item xs={2}>
          <TextField
          id={index}
          label="Start Time"
          type="time"
          onChange={handleStartChange}
          InputLabelProps={{
          shrink: true,
        }}
          inputProps={{
          step: 300, // 5 min
        }}
          />
          </Grid>
          <Grid item xs={4}>
          <TextField
          id="end_time"
          label="End Time"
          type="time"
          onChange={handleEndChange}
          InputLabelProps={{
          shrink: true,
        }}
          inputProps={{
          step: 300, // 5 min
        }}
          />
          </Grid>
            </Grid>
          ))
        }
    </form>
  )
}

export default WorkingDays

A: It seems like you are setting a value for a day over the entire array. You are calling setWorkingDaysHours with a single value and it replaces your whole array.
It might work better if your update functions were
function handleStartChange(day, hours) {
    const newArray = [...workingDaysHours];
    newArray[day][0] = hours;
    setWorkingDaysHours(newArray);
}
function handleEndChange(day, hours) {
    const newArray = [...workingDaysHours];
    newArray[day][1] = hours;
    setWorkingDaysHours(newArray);
}

Then your callback should be called like
// Day being the variable taken from the map method
onChange={ev => handleStartChange(day, ev.target.value)}


text:
Q: How to read fortran 77 unformatted binary file into python I have a script in IDL which reads an unformatted binary file (F77) and outputs it as a .sav file but I want to convert this script to python and save as an .npz file and I am having trouble on the read line.
IDL Code:
;create save file for QBO model output

;---------------------------------------------------------------------
;input data here (Only adjust this info)
;---------------------------------------------------------------------

  time=7300  ;duration from fortran code
  tstep=5   ;time step from fortran code
  inputfile='/home/cwilliams/Metr_205/qbo/uvwtom.'; binary file from fortran
  outputsavefile='~cwilliams/Metr_205/qbo/qbo_FULLX.sav'; name of save file with     variables
;--------------------------------------------------------------------------------
;--------------------------------------------------------------------------------

;==============================================================================
;   Do Not Adjust the Following Code
;==============================================================================
fname='dat'
nstep=time/tstep ;time/timestep
nm=nstep-1

um=fltarr(17,34)
vm=fltarr(17,34)
wm=fltarr(17,34)
tm=fltarr(17,34)
pm=fltarr(17,34)
om=fltarr(17,34)
vpm=fltarr(17,34)
vdm=fltarr(17,34)

u=fltarr(17,34,nstep)
v=fltarr(17,34,nstep)
w=fltarr(17,34,nstep)
temp=fltarr(17,34,nstep)
pressure=fltarr(17,34,nstep)
ozone=fltarr(17,34,nstep)

date=findgen(nstep)*(2.*tstep/365.)
ulevels2=[-30, -25, -20, -15, -10, -5, 5, 10, 15,  20, 25, 30]
ulevels3=findgen(15)*3.-12
lab=findgen(20)*0+1
lat=findgen(17)*2.7-1.35

ht=findgen(34)*0.5+17.

openr,37,inputfile+fname,/f77_unformatted & title='base'
for n=0,nm do begin
    readu,37,um,vm,wm,tm,om,pm
    u(*,*,n)=um/100.
    v(*,*,n)=vm
    w(*,*,n)=wm
    temp(*,*,n)=tm*700000./2.87e6
    pressure(*,*,n)=pm/10000.
    ozone(*,*,n)=om
endfor
close,37

save,filename=outputsavefile,u,v,w,temp,pressure,ozone,date,ulevels2,ulevels3,lab,$
lat,ht
stop
end

Python Code:
    #create save file for QBO model output
#---------------------------------------------------------------------
#input data here (Only adjust this info)
#---------------------------------------------------------------------

time=7300  #duration from fortran code
tstep=5   #time step from fortran code
inputfile='/home/cwilliams/metr51/lab12/uvwtom.dat'# binary file from fortran
outputsavefile='~cwilliams/metr51/lab12/qbo_FULLX.sav'# name of save file with variables
#--------------------------------------------------------------------------------
#--------------------------------------------------------------------------------

import numpy as n

#==============================================================================
#   Do Not Adjust the Following Code
#==============================================================================
nstep=time/tstep #time/timestep
nm=nstep-1

um=n.empty((17,34))
vm=n.empty((17,34))
wm=n.empty((17,34))
tm=n.empty((17,34))
pm=n.empty((17,34))
om=n.empty((17,34))
vpm=n.empty((17,34))
vdm=n.empty((17,34))

u=n.empty((17,34,nstep))
v=n.empty((17,34,nstep))
w=n.empty((17,34,nstep))
temp=n.empty((17,34,nstep))
pressure=n.empty((17,34,nstep))
ozone=n.empty((17,34,nstep))

date=n.arange(nstep)*(2.*tstep/365.)
ulevels2=n.array([-30, -25, -20, -15, -10, -5, 5, 10, 15,  20, 25, 30])
ulevels3=n.arange(15)*3.-12
lab=n.arange(20)*0+1
lat=n.arange(17)*2.7-1.35

ht=n.arange(34)*0.5+17.

This is where I need some assitance:
f=open(inputfile,'rb')
data=f.read()
for i in range(nm+1):
#    readu,37,um,vm,wm,tm,om,pm
#    u(:,:,i)=um/100.
#    v(:,:,i)=vm
#    w(:,:,i)=wm
#    temp(:,:,i)=tm*700000./2.87e6
#    pressure(:,:,i)=pm/10000.
#    ozone(*,*,n)=om
#
#n.savez(filename=outputsavefile,u=u,v=v,w=w,temp=temp,pressure=pressure,ozone=ozone,date=date,ulevels2=ulevels2,ulevels3=ulevels3,lab=lab,lat=lat,ht=ht)

I know there is an issue with the row/column order between IDL and Python but I think I can fix this once I read the code in.

A: First off, I have to assume that you wrote the original Fortran file using sequential access rather than direct access, this is a very important distinction.  I do know IDL and the read command you have set up in your example is consistent with sequential access.
This matters because Fortran sequential access adds 'record markers' to the file for every call to WRITE(), so you'll have to account for that in your Python read routine, much as in the answer that george linked in the comments.
As to row/column order, it really just matters which dimension is iterating the fastest in memory.  A Fortran 2D array, for example, will write in memory with the first array dimension as the fastest iterating.  When you read the same thing into a 2D Python variable, it will be the last dimension - keep that in mind when reshaping a flat array, and you'll have to transpose it if you want to keep your indexing.
I think the following code will do approximately what you want, for brevity I just included your um and vm variables:
import numpy as np

um=np.empty((34,17), dtype='float32') # Make these dimensions "backwards" for easier reshaping
vm=np.empty((34,17), dtype='float32') # Also watch out, I believe the default type is float64

f = open(inputfile,'rb')
recl = np.zeros(1,dtype=np.uint32)
for i in range(nm+1):
    recl = np.fromfile(f, dtype='uint32', count=1)
    tmpu = np.fromfile(f, dtype='float32', count=um.size) # These arrays will be flat
    tmpv = np.fromfile(f, dtype='float32', count=vm.size)
    recl = np.fromfile(f, dtype='uint32', count=1)

    um = np.transpose(np.reshape(tmpu, um.shape))
    vm = np.transpose(np.reshape(tmpv, vm.shape))

Then you may also do whatever you wish in the loop with your other variables, and you should be able to index um and vm like you are used to in IDL or Fortran.  This might not be the easiest or best way to do it, but I think it will at least get you started.


text:
Q: [__NSArrayM objectAtIndex:]: index 197 beyond bounds [0 .. 8] I have product table in database. Product table i have id & product_image column. Each image having id. I'm getting these id from database and taken to cat_imageidArray, Then getting images & taken to productimg_array. Assign the productimg_array image value to imgView1 (UIButton). I'm using [productimg_array objectAtIndex:i]. Here index is 0 to 7 or etc. But cat_imageidArray having value of 183,184,190 etc. When i click imgView1 button i'm getting these error [__NSArrayM objectAtIndex:]: index 197 beyond bounds [0 .. 8]. I understood the problem is array value is not matching. How to assign the cat_imageidArray value to productimg_array index. Maybe then it will work.
const char *sql = "SELECT id,cat_id,product_image,order_by,description FROM product where cat_id = ?";

        NSLog(@"sql is %s",sql);

        sqlite3_stmt *statement;

        if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL) == SQLITE_OK) {
            // We "step" through the results - once for each row.

            if (sqlite3_bind_int(statement, 1, categoryId) != SQLITE_OK)
                NSLog(@"%s: bind failed: %s", __FUNCTION__, sqlite3_errmsg(database));

            while (sqlite3_step(statement) == SQLITE_ROW) {

                cat_iamgeId = sqlite3_column_int(statement, 0);
                NSLog(@"cat_iamgeId is %ld",(long)cat_iamgeId);
                [cat_imageidArray addObject:@(cat_iamgeId)];

                product_image = [[NSString alloc] initWithUTF8String:
                                 (const char *) sqlite3_column_text(statement, 2)];
                NSLog(@"product_image is %@",product_image);
                [productimg_array addObject:product_image];
            }
        }

for (int i = 0; i<[productimg_array count]; i++ ) {

            NSLog(@"productimg_array_index %@", productimg_array[i]);
            imgView1=[[UIButton alloc]initWithFrame:CGRectMake(20+(i*74), 0, 72, 72)];
            Width = Width + 20+(i*74);
            for (int i=0; i<[cat_imageidArray count]; i++){

               NSLog(@"index %@", cat_imageidArray[i]);
               tag=[[cat_imageidArray objectAtIndex:i]intValue];
               imgView1.tag=tag;
               NSLog(@"tag is %d",tag);
            }

            [imgView1 addTarget:self action:@selector(dbsofaClicked:) forControlEvents:UIControlEventTouchUpInside];
            [imgView1 setImageWithURL:[NSURL URLWithString:[productimg_array objectAtIndex:i]]forState:UIControlStateNormal];

           [scrollview addSubview:imgView1];
       }

imgView1 button click:

-(void)dbsofaClicked:(id)sender{

   NSLog(@"button %d is clicked.", [sender tag]);
             mmageView=[[UIImageView alloc]initWithFrame:CGRectMake(50,50,150,150)];

    [mmageView setUserInteractionEnabled:YES];

       [mmageView setImageWithURL:[NSURL URLWithString:[productimg_array objectAtIndex:[sender tag]]] placeholderImage:nil options:SDWebImageProgressiveDownload completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {

    }];

NSLog productimg_array:
productimg_array (
"http://center.net/projects/View/images/img.png",
"http://center.net/projects/View/images/img1.png",
"http://center.net/projects/View/images/img2.png",
"http://center.net/projects/View/images/img3.png",
"http://center.net/projects/View/images/img4.png",
"http://center.net/projects/View/images/img5.png",
"http://center.net/projects/View/images/img6.png",
"http://center.net/projects/View/images/img7.png",
"http://center.net/projects/View/images/img8.png"
)

When i use singleTap the image i didn't get correct description from database value. that's why i need to set id instead of index
- (void)singleTap:(UIGestureRecognizer *)singletap {
  NSLog(@"singleTap1");
    UIView *view = singletap.view;
    switch (view.tag) {
        case 0:

            txtt=[[UITextView alloc]initWithFrame:CGRectMake(50, 100, 200, 100)];

            txtt.text=[descript_array objectAtIndex:0];

            txtt.editable=NO;

            NSLog(@"text is %@",txtt.text);

            [self.view addSubview:txtt];

            break;

        case 1:

            txtt1=[[UITextView alloc]initWithFrame:CGRectMake(50, 100, 200, 100)];

            txtt1.text=[descript_array objectAtIndex:1];

            NSLog(@"text1 is %@",txtt1.text);

            [self.view addSubview:txtt1];

            break;

        case 2:

            txtt2=[[UITextView alloc]initWithFrame:CGRectMake(50, 100, 200, 100)];

            txtt2.text=[descript_array objectAtIndex:2];

            NSLog(@"text2 is %@",txtt2.text);

            [self.view addSubview:txtt2];

            break;

        case 3:

            txtt3=[[UITextView alloc]initWithFrame:CGRectMake(50, 100, 200, 100)];

            txtt3.text=[descript_array objectAtIndex:3];

            NSLog(@"text is %@",txtt3.text);

            [self.view addSubview:txtt3];

            break;

A: Remove inner for loop that solve your problem
for (int i = 0; i<[productimg_array count]; i++ ) {

        NSLog(@"productimg_array_index %@", productimg_array[i]);
        imgView1=[[UIButton alloc]initWithFrame:CGRectMake(20+(i*74), 0, 72, 72)];
        Width = Width + 20+(i*74);
        //for (int i=0; i<[cat_imageidArray count]; i++){ **This line doesn't need**

           NSLog(@"index %@", cat_imageidArray[i]);
           tag=[[cat_imageidArray objectAtIndex:i]intValue];
           **Changed**//imgView1.tag=tag;
           imgView1.tag = i;
           NSLog(@"tag is %d",tag);
        //}

        [imgView1 addTarget:self action:@selector(dbsofaClicked:) forControlEvents:UIControlEventTouchUpInside];
        [imgView1 setImageWithURL:[NSURL URLWithString:[productimg_array objectAtIndex:i]]forState:UIControlStateNormal];

       [scrollview addSubview:imgView1];
   }


text:
Q: Multi slider function I created a function slider that fades the next section in and out, but not happy how I created the functions as I need to change the function each time I create a new section.
There a way to change this setup where only one function is needed so I can have 100 sections and just one function? Not 100 functions for each section to add/remove classes?

$('#toSlide-2').on('click', function (event) {
       event.preventDefault();
       $('#slide-1').removeClass('in-view').addClass('out-of-view');
       $('#slide-2').addClass('in-view');
 })
 $('#toSlide-3').on('click', function (event) {
       event.preventDefault();
       $('#slide-2').removeClass('in-view').addClass('out-of-view');
       $('#slide-3').addClass('in-view');
 })
 $('#toSlide-4').on('click', function (event) {
       event.preventDefault();
       $('#slide-3').removeClass('in-view').addClass('out-of-view');
       $('#slide-4').addClass('in-view');
 })
.out-of-view{
  opacity:0;
  }
.in-view{
  opacity:1;
 }

<form id="slide-1" class="in-view">

form 1

  <button id="toSlide-2">button</button>
</form>

<form id="slide-2" class="out-of-view">

form 2

    <button id="toSlide-3">button</button>
</form>

<form id="slide-3" class="out-of-view">

form 3

    <button id="toSlide-4">button</button>
</form>

<form id="slide-4" class="out-of-view">

form 4 - done

</form>

A: This is a simplified version of a working solution using jQuery.

$('.buttons').on('click', function (event) {
       event.preventDefault();
       $(this).parent().removeClass('in-view').addClass('out-of-view');
       $(this).parent().next().addClass('in-view');
 })

<form id="slide-1" class="in-view">

form 1

  <button class="buttons">button</button>
</form>

<form id="slide-2" class="out-of-view">

form 2

    <button class="buttons">button</button>
</form>

<form id="slide-3" class="out-of-view">

form 3

    <button class="buttons">button</button>
</form>

A: you can use the data attribute to determine which element id would be showed next like so:

function init() {
  $('.in-view').show();
  $('.out-of-view').hide();
}

function slide(slideId1, slideId2) {
  $(`#${slideId1}`).hide();
  $(`#${slideId2}`).show();
}

$('.slide-btn').on('click', function (event) {
  event.preventDefault();
  slide($(this).parent().attr("id"), $(this).data("next"));
});

init();

<form id="slide-1" class="in-view">

form 1

  <button class="slide-btn" data-next="slide-2">button</button>
</form>

<form id="slide-2" class="out-of-view">

form 2

    <button class="slide-btn" data-next="slide-3">button</button>
</form>

<form id="slide-3" class="out-of-view">

form 3

    <button class="slide-btn" data-next="slide-4">button</button>
</form>

<form id="slide-4" class="out-of-view">

form 4 - done

</form>

A: Here is a pure JS function that will dynamically take the elements using a class selector and iterate over them and use the key word this in an event listener to select the next element sibling and add/remove class names.
Note: I added a class named forms and use that to get the element list of forms to use in the forEach loop.
Also, I suggest using display: none/block instead of opacity. This will keep the elements from pushing down the page with each iteration of selecting a button.

// get your element list
const forms = document.querySelectorAll(".forms");

// iterate over the element list using forEach()
forms.forEach(function(v){
  // foreach value in the list, set a click event listener
  v.addEventListener('click', function(e){
    e.preventDefault();
    // now use the key word 'this' to add/remove class names
    // then target the next sibling in the list to add/remove class names
    this.classList.remove("in-view");
    this.classList.add("out-of-view");
    this.nextElementSibling.classList.remove('out-of-view');
    this.nextElementSibling.classList.add('in-view');
  })
})
.out-of-view{
  display:none;
  }
.in-view{
  display:block;
 }

<form id="slide-1" class="in-view forms">

form 1

  <button id="toSlide-2">button</button>
</form>

<form id="slide-2" class="out-of-view forms">

form 2

    <button id="toSlide-3">button</button>
</form>

<form id="slide-3" class="out-of-view forms">

form 3

    <button id="toSlide-4">button</button>
</form>

<form id="slide-4" class="out-of-view forms">

form 4 - done

</form>

JQuery Version:
No matter how many form elements in your HTML, as long as they have the class forms, they will be iterated over and processed in the function.
Also, use less lines of code and change the css directly in your JQuery using .css()

// get your element list
const $forms = $(".forms");

// iterate over the element list using.each()
$forms.each(function() {
  // use $(this) to define the element being clicked on
  $(this).click(function(e) {
    e.preventDefault();
    $(this).css('display', 'none');
    $(this).next().css('display', 'block');
  })
})
.out-of-view {
  display: none;
}

.in-view {
  display: block;
}

<form id="slide-1" class="in-view forms">

form 1

  <button id="toSlide-2">button</button>
</form>

<form id="slide-2" class="out-of-view forms">

form 2

  <button id="toSlide-3">button</button>
</form>

<form id="slide-3" class="out-of-view forms">

form 3

  <button id="toSlide-4">button</button>
</form>

<form id="slide-4" class="out-of-view forms">

form 4 - done

</form>


text:
Q: Access Vue.js component property inside Ajax function The following code refers to a component function which fetches data from an url and tries to set that data to a property. It's not working, seems like this is not accessible form the ajax clousure scope.
var MyComp = Vue.extend({
props: {
        html_prop: {}
        ....
},
methods: {
        fetchCondiciones: function(url){

            $.ajax({
                    type: "GET",
                    url: url,
                    cache: false,
                    data: vardata ,
                    success: function(data,status,error) {
                        if( data!=''){
                            this.html_prop = data;
                        }
                    },
                    error: function(data,status,error){
                        alert(error);
                    }
            });

        }

        ...
    }
})

How could I make this accessible?

A: You can provide a context option and set it to this like so:
$.ajax({
  context: this,
  ..
})

Which I prefer over binding this as it seems more readable, too.
From the jQuery AJAX docs:

The this reference within all callbacks is the object in the context option passed to $.ajax in the settings; if context is not specified, this is a reference to the Ajax settings themselves.

A: You need to .bind the this context, as the callback is not naturally called in the context of the component:
var MyComp = Vue.extend({
props: {
        html_prop: null,
},
        // ....
        fetchCondiciones: function(url){

            $.ajax({
                    type: "GET",
                    url: url,
                    cache: false,
                    data: vardata,
                    success: function(data,status,error) {
                        if(data != ''){
                            this.html_prop = data;
                        }
                    }.bind(this), // bind this here
                    error: function(data,status,error){
                        alert(error);
                    }.bind(this) // bind this here
            });

        }

        // ...
});

You can learn more about .bind and this here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind

A: As already answered, .bind will fix the issue on this, however, I like to use a different approach, and store this in a variable before any Ajax calls or nested functions. Very helpful when your code grows inside the method. It is also easier to read.
You can save this to a var called self for example. Then use self anywhere inside that method without a problem.
var MyComp = Vue.extend({
props: {
    html_prop: null,
},
    // ....
    fetchCondiciones: function(url){

        var self = this;

        $.ajax({
                type: "GET",
                url: url,
                cache: false,
                data: vardata,
                success: function(data,status,error) {
                    if(data != ''){
                        self.html_prop = data;
                    }
                }
                error: function(data,status,error){
                    alert(error);
                }
        });

    }

    // ...
});

UPDATE:
Today we could just use ES6 arrow function syntax.
The value of this inside the function is determined by the surrounding scope, and there is no need to create a new variable, or to use bind:
    // ....
    fetchCondiciones: url => {
        $.ajax({
                type: "GET",
                url: url,
                cache: false,
                data: vardata,
                success: (data,status,error) => {
                    if(data != ''){
                        this.html_prop = data;
                    }
                }
                error: (data,status,error) => {
                    alert(error);
                }
        });
    }

Or:
    // ....
    fetchCondiciones(url) {
        $.ajax({
                type: "GET",
                url: url,
                cache: false,
                data: vardata,
                success(data,status,error) {
                    if(data != ''){
                        this.html_prop = data;
                    }
                }
                error(data,status,error) {
                    alert(error);
                }
        });
    }

A: You can also use arrow functions since ES6, arrow functions do not bind their own this, instead, they inherit the one from the parent scope, which is called "lexical scoping".
so instead of
//....
  success: function(data,status,error) {
                        if( data!=''){
                            this.html_prop = data;
           }
  }
//...

you can do
//....
  success: (data,status,error) => {
                        if( data!=''){
                            this.html_prop = data;
            }
  }
//...


text:
Q: Python modules I've just installed in my virtual env, are not found I'm using Ubuntu 20.04.5 LTS. Output of python3 --version command: Python 3.8.10
When I type pip in terminal and press TAB, it responds with the following options: pip, pip3, pip3.10 and pip3.8
But, when I use any of then with the --version flag, it all prints the same output, which is: pip 22.3.1 from /home/myuser/.local/lib/python3.8/site-packages/pip (python 3.8)
When I use "pip list" command, I can see the "virtualenv" package version(which is 20.17.0)
Then I create my virtual environment using this following command: python3 -m venv .env
Then I activate it using source .env/bin/activate command
Before installing the modules, I update virtual environment's pip, using the following command:
.env/bin/python3 -m pip install --upgrade pip

Also, I have a file called requirements.txt with the packages names I need in it:
wheel
numpy
matplotlib
sklearn
seaborn

So I install them using the following command:
.env/bin/pip install -r requirements.txt --no-cache-dir --use-pep517

Finally, I try to run my python program using ".env/bin/python kmeans3.py" command, it prints this error:
Traceback (most recent call last):
  File "kmeans3.py", line 10, in <module>
    from sklearn.cluster import KMeans
ModuleNotFoundError: No module named 'sklearn'

obs: This is the first 12 lines of the file:
"""
.env/bin/python3 -m pip install --upgrade pip
.env/bin/pip install -r requirements.txt --no-cache-dir --use-pep517
"""

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
from sklearn.preprocessing import MinMaxScaler

A: Looks ok to me.
If your environment is activated try to just run
python kmeans3.py

or
python3 kmeans3.py

A: I don't know why is that, but I solved this problem installing "scikit-learn" package before install "sklearn"


text:
Q: Trying to install kubuntu from CD, but Windows10 overrides saying boot config is wrong I'm trying to install kubuntu on my old laptop. I upgraded it to Win10 this summer, but wasn't happy with the result, so I've decided to give kubuntu a try. At first I tried to install it inside windows (the CD just self-launched and I went with it). During that, the installation froze, and I was forced to shutdown the computer holding the power button. After I went into BIOS and change the boot order to boot CD/DVD device first I got this message when trying to boot:

Recovery
Your PC/Device needs to be repaired
The Boot Configuration Data for you PC is missing or contains errors.
File: \Boot\BCD Error code: 0xc000014c
You'll need to use recovery tools. If you don't have any installation
  media (like a disc or USB device), contact your PC Administrator or
  PC/Device manufacturer.

All with a Windows 10 layout in the background. Why does the system not allow me to boot directly from the CD? I don't care about whether Win10 likes it or not. Does anyone know how to go about this?
The CD boots on my desktop computer.

A: I guess problem is with win10 boot mechanism. It doesn't accept Linux boot loader. You should try with new Ubuntu/Kubuntu version (made after windows 8) or install Linux on second physical drive (if you have one), then before boot you choose, which drive computer should start from (should be keyboard shortcut set in BIOS, on my computer this is F12).
If both are not possible you may try to upgrade grub, however I've never been doing this so I don't know what you should expect.


text:
Q: Continuity of a Logarithmic Integral Define $L:(0,\infty)\to\mathbb{R}$ by
$$L(x)=\int_{1}^{x}\frac{dt}{t}.$$
How can I show that $L$ is continuous on $(0,\infty)$?
I know that the definition of continuity states the following:

A function $f:A\to\mathbb{R}$ is continuous at a point $c\in A$ if, for all $\epsilon>0$, there exists a $\delta>0$ such that whenever $|x-c|<\delta$ (and $x\in A$), it follows that $|f(x)-f(c)|<\epsilon$.
If $f$ is continuous at every point in the domain $A$, then we say that $f$ is continuous on $A$.

I have tried applying this definition by letting $x,c\in(0,\infty)$. Then
$$\left|L(x)-L(c)\right|=\left|\int_{1}^{x}\frac{dt}{t}-\int_{1}^{c}\frac{dt}{t}\right|=\left|\int_{1}^{x/c}\frac{dt}{t}\right|=\left|L(x/c)\right|<\epsilon,$$
but no matter how hard I look, I cannot seem to find the connection between that and $|x-c|<\delta$, because these are integrals, and I cannot perform algebraic manipulations to reach the desired inequality.
Do you guys have any ideas?

A: The proofs one can use depend on what has been proved so far. There are two alternatives. One could question you about whether various theorems have been proved, in your course, or one could guess. I will guess that only very basic properties of the definite integral have been proved rigorously.
Let $c\in (0,\infty)$. We show that $L$ is continuous at $c$. That means that for any $\epsilon \gt 0$, we must produce (or at least show the existence of) a $\delta \gt 0$ such that if $|x-c| \lt \delta$, then $|L(x)-L(c)| \lt \epsilon$. Note that
$$|L(x)-L(c)|=\left|\int_1^x\frac{dt}{t} -\int_1^c\frac{dt}{t}\right|=\left|\int_c^x\frac{dt}{t}\right|.$$
We estimate the last integral. If $\frac{1}{t} \lt M$ in the interval from $c$ to $x$ (but $x$ could be to the left of $c$), we have
$$\left|\int_c^x\frac{dt}{t}\right| \le |x-c|M.$$
We first of all make $\delta<c/2$. That makes sure that $t$ does not dip below $c-c/2=c/2$, so in the interval of integration, $\frac{1}{t}$ is bounded above by $M=\frac{2}{c}$.
If we make that restriction on $\delta$, then if $|x-c| \le \delta$, we have
$$\left|\int_c^x\frac{dt}{t}\right| \le |x-c|M \le \delta\frac{2}{c}\tag{$\ast$}.$$
Make $\frac{2\delta}{c} \lt \epsilon$, that will do it! So let's make $\delta \lt c\epsilon/2$.  For definiteness, make $\delta=c\epsilon/5$, why not? That's not quite right, remember that we wanted $\delta<c/2$. So make $\delta$ equal to the minimum of $c/2$ and $c\epsilon/5$. This ties down everything. Part of it was overkill, as protection against the possibility that as a joke we are given $\epsilon=1000$. If we look only at small $\epsilon$, say less than $1$, then $\delta=c\epsilon/5$ is plenty good enough, indeed $\delta=c\epsilon/2$ is good enough.
The paragraph above is of very slight importance. In essence, once we had the inequality $(\ast)$, it was clear that by appropriate choice of $\delta$ we could make $|L(x)-L(c)|$ as small as we wished.
Remark: The approach you tried also works, and the details are not all that different. It requires first proving the fact that the difference is $\int_1^{x/c}\frac{dt}{t}$, but I imagine that was done in your course. (That special fact would not be available if we had say $1/\sqrt{t}$ instead of $1/t$.) Then we can find an upper bound for the absolute value, of the shape $|x/c-1|M$, where $M$ is as in the solution above. Finally, we need to estimate $|x/c-1$ in terms of $|x-c|$, that part is easy.

A: $f$ be integrable on the $[a,b]$, then $F=\int_{a}^{x}f(t)dt$ is continuous apply this result to prove L is continuous

A: To show continuity on $(0,\infty)$, it is sufficient to show that $L$ is continuous on the interval $(a,\infty)$ for any $a>0$. The advantage of doing this is that you can easily bound $t \mapsto \frac{1}{t}$ on the interval $(a, \infty)$ by $\frac{1}{a}$.
The we have, for $x,y \in (a, \infty)$,
$$| L(x)-L(y) | = |\int_y^x \frac{1}{t} dt | \leq \frac{1}{a} | x-y|.$$
Choosing $\delta < a \epsilon$, then you have the required result, ie, if $|x-y| < \delta$, then $| L(x)-L(y) | \leq \frac{1}{a}
\delta < \epsilon$.
Since $a>0$ was arbitrary, you can conclude that $L$ is continuous on $(0,\infty)$.

A: Take a close interval containing c, there the function f(t)=1/t is bounded.
 Then use  monotony of integral between c to x.
(For x sufficient close to c you are working in the close interval you took).


text:
Q: Stay on same component of page after refresh browser in ReactJS I am very new to ReactJS. My query is I want to stay on same component of page in ReactJS. Below is my code.
App.js
import React, { Component } from 'react' import { BrowserRouter as Router, Route } from 'react-router-dom'

import { authenticationService } from './_service/authentication.service'

import { PrivateRoute } from './components/Routes/PrivateRoute';
import Navbar from './components/Navbar/Navbar'
import Landing from './components/Landing/Landing'
import Login from './components/Login/Login'
import Register from './components/Register/Register'
import Home from './components/Home/Home'
import SideBar from './components/SideBar/SideBar';

class App extends Component {   render(){
    return (
      <Router>

          <Navbar />
          {authenticationService.currentUserValue ? <SideBar/> : null}
          <Route exact path="/" component={Landing} />

            <Route exact path="/register" component={Register} />
            <Route exact path="/login" component={Login} />
            <PrivateRoute exact path="/home" component={Home} />

      </Router>
    )   } }

Above route is main route file of my project after login it redirects me to home page. On Home page i am loading Header, Sidebar and Content(Component). Here the content(Component) is different which depends on sidebar links.
Home.js
import React, { Component } from 'react'
import { BrowserRouter as Router} from 'react-router-dom'

// import Home from './components/Home/Home'
import { authenticationService } from '../../_service/authentication.service'
// import Navbar from '../Navbar/Navbar'
import Sidebar from '../SideBar/SideBar'
// import Landing from '../Landing/Landing'
import Profile from '../Profile/Profile'
import AboutUs from '../Profile/AboutUs'

class Home extends Component {
    constructor(props){
        super(props);

        if (authenticationService.currentUserValue) {
            // this.props.history.push('/home');
            this.props.history.push('/home');//this.state.initialPage
        }
        this.state={
            initialPage:<Profile/>
        }
    }

    routeSidebar = (flag) => {

        switch(flag) {
            case 'AboutUs':
                this.setState({
                    initialPage:<AboutUs/>
                })
                break;
            default:
                this.setState({
                    initialPage:<Profile/>
                })
                break;
        }
    }
    render() {
        const {initialPage} = this.state;
        return (
                <Router>

                    <Sidebar routeSidebar={this.routeSidebar} />
                    {initialPage}

                </Router>
        );
    }
  }

  export default Home;

A: You can do it in two different way either you can use localStorage, cookie or you can user props.location as code shown below.
import React from 'react';
import { Route, Redirect } from 'react-router-dom';

import { authenticationService } from '../../_service/authentication.service';

export const PrivateRoute = ({ component: Component, roles, ...rest }) => (
    <Route {...rest} render={props => {
        const currentUser = authenticationService.currentUserValue;

        if (!currentUser) {
            // not logged in so redirect to login page with the return url
            return <Redirect to={{ pathname: '/', state: { from: props.location } }} />
        }

        // check if route is restricted by role
        if (roles && roles.indexOf(currentUser.role) === -1) {
            // role not authorised so redirect to home page
            return <Redirect to={{ pathname: '/'}} />
        }

        // authorised so return component
        return <Component {...props} />
    }} />
)


text:
Q: T-sql use local variable like a as clause I want to use that i declare local variable like a as clause,
for example
i get last year and current year
declare @lastYear varchar(4)=datepart(YEAR,DATEADD(year,-1,GETDATE()));
declare @currentYear varchar(4)=datepart(YEAR,DATEADD(year,0,GETDATE()));

and
i want to use like a above,

select a.totalCountLy  as @lastYear,
a.totalCountLy as @currentYear from TableName as a (nolock

And result is like
2011          2012
------------------
1000          5000
400           1000

Any suggestions.
Thanks.

A: How about this, using dynamic SQL?
declare @lastYear varchar(4)=datepart(YEAR,DATEADD(year,-1,GETDATE()));

declare @sql nvarchar(max) =
    N'select a.total as [' + convert(nvarchar(24), @lastYear) + N'] from TableName as a'

exec sp_executesql @sql


text:
Q: How can i calculate $H_i(S^2 \times S^1)$? How can i calculate $H_i(S^2 \times S^1)$? I'm ultimately trying to show that $S^2 \times S^1$ is not homeomorphic to $\mathbb{R}P^2 - \{p\} \cong \mathbb{R}P$

A: Building on ThorbenK's suggestion, set $U=D_1\times S^1$, $V=D_2\times S^1$ where each $D_j$ is a (slightly fattened) hemisphere (i.e. a disc, so, contractible). Obviously $U\cap V= (D_1\cap D_2)\times S^1=(-c,c)\times S^1\times S^1$, which retracts to a $2$-torus.
So
$$H_*(U)=\mathbb{Z},\mathbb{Z}, 0,0$$
$$H_*(V)=\mathbb{Z},\mathbb{Z}, 0,0$$
$$H_*(U\cap V)=\mathbb{Z},\mathbb{Z}\oplus\mathbb{Z}, \mathbb{Z},0$$
Set $X=S^2\times S^1=U\cup V$. By the Mayer-Vietoris sequence
$$0\to H_3(X)\to H_2(U\cap V)\to H_2(U)\oplus H_2(V)\to H_2(X)\to H_1(U\cap V)\to H_1(U)\oplus H_1(V)\to H_1(X)\to H_0(U\cap V)\to H_0(U)\oplus H_0(V)\to H_0(X)\to 0$$
Or, as we already know the homology groups of $U$, $V$ and $U\cap V$,
$$0\to H_3(X)\to \mathbb{Z}\to 0 \to H_2(X)\to \mathbb{Z}^2\to \mathbb{Z}^2\to H_1(X)\to \mathbb{Z}\to \mathbb{Z}^2\to H_0(X)\to 0$$
We immediately see that $H_3(X)=\mathbb{Z}$.
The maps $\rho_j:H_j(U\cap V)\to H_j(U)\oplus H_j(V)$ are given by $((i_1)_*, (i_2)_*)$  where $i_1:U\cap V\to U$ and $i_2:U\cap V\to V$ are the inclusions.
So, at the level $0$, homology is generated by the class of a point; given $[p]\in H_0(U\cap V)$, then obviously $\rho_0([p])=([i_1(p)], [i_2(p)])$, so $\rho_0:\mathbb{Z}\to\mathbb{Z}^2$ is $\rho_0(x)=(x,x)$, hence the cokernel is
$$H_0(X)=\mathbb{Z}$$
As $\rho_0$ is injective, the map $H_1(X)\to H_0(U\cap V)$ has image $0$ and its kernel, which is $H_1(X)$, is the image of $\sigma:H_1(U)\oplus H_1(V)\to H_1(X)$, which is then surjective. Therefore $H_1(X)=(H_1(U)\oplus H_1(V))/\rho_1(H_1(U\cap V))$.
Moreover, consider two generators of $H_1(U\cap V)$: the cycle $[\gamma]$ given by the $S^1$ that is also a factor of $X$ and the cycle $[\gamma']$ given by the intersection between the two disc $D_1$ and $D_2$ (the equator of $S^2$). We have that $(i_j)_*([\gamma])=[i_j\circ\gamma]$, whereas $(i_j)_*[\gamma']=0$. So $\rho_1:\mathbb{Z}^2\to\mathbb{Z}^2$ is $\rho_1(x,y)=(x,x)$.
Its kernel is $\mathbb{Z}$ and it is homomorphic to $H_2(X)$.
On the other hand, its image is $\mathbb{Z}$, therefore $H_1(X)=\mathbb{Z}^2/(1,1)\mathbb{Z}=\mathbb{Z}$.
In conclusion
$$H_*(X)=\mathbb{Z}, \mathbb{Z},\mathbb{Z},\mathbb{Z}$$


text:
Q: Openpgpjs wont read key I'm trying to encrypt text with OpenPGPJS in react application.
I have a function in react class:
const openpgp = require('openpgp');
...
class XYZ extends React.Component{
...
    async encrypt(text, targetKey){
        await openpgp.initWorker({ path: 'openpgp.worker.js' });
        var publicKey = (await openpgp.key.readArmored(targetKey.trim())).keys;

        console.log(publicKey);

        const result = await openpgp.encrypt({
            message: openpgp.message.fromText(text),
            publicKeys: publicKey
        });
        console.log(result.data);
    }
...
const public_key = `-----BEGIN PGP PUBLIC KEY BLOCK----- .......`
const text = 'encrypt this'
this.encrypt(text, public_key);

for encryption.
I get an error message: Unhandled Rejection (Error): Error encrypting message: No keys, passwords, or session key provided.
I find out that (await openpgp.key.readArmored(targetKey.trim())).keys; return empty array, idk why.


text:
Q: Inequality involving $x^n$ This is probably not very exciting, but can't get my head around this for a while. Here's the inequality:
$$
x_1^3-\epsilon x_1^2 -(2+\epsilon(1-x_1^n))x_1+(1+\epsilon)>0
$$
where $\epsilon>0, n \in \mathbb{Z^{+}}$. Please just give me hints, don't solve it for me.
EDIT: $x_1>0$
EDIT2: it seems that the solution to inequality $1-x_1-x_1^2>0$ is the trick. For (see EDIT 1) $0<x_1<\frac{\sqrt{5}-1}{2} \approx 0.618$ the main inequality above is true for all $n, \epsilon$. If $x_1$ is larger than $\approx 0.618$, then it is true for some $\epsilon>0$ iff $n$ is not very large. The condition $\epsilon>0$ is crucial.

A: If it is wished that the inequality be true for all positive $x_1$, it will need modification.  For example, let $n=1$. Then we are looking at
$$x^3-(2+\epsilon)x+1+\epsilon.$$
This is not necessarily positive. Imagine $\epsilon$ very close to $0$. The function reaches a minimum at $x=\sqrt{(2+\epsilon)/3}$, and the minimum value is negative, though not by much. I chose a small $\epsilon$, because presumably that is what is intended. But if we pick $\epsilon$ large, like $10$, we are looking at $z^3-12x+11$, which is $-5$ at $x=2$.
There will be similar difficulties with $n=2$. And for any $n\ge 3$, and small $\epsilon$, we can reproduce the same problem.


text:
Q: Android webView focus on specific part of image I have an image inside of my web view. The image is so big and I've enabled scrolls but the problem is that I want to set default view (first look on image before doing scroll or zoom ) to specific part of image. Any idea ?
            WebView callUsView2= (WebView) rootView.findViewById(R.id.callUsView2);

            WebSettings callUsView2Setting = callUsView2.getSettings();

            callUsView2Setting.setBuiltInZoomControls(true);
            callUsView2Setting.setDisplayZoomControls(true);
            callUsView2.setVerticalScrollBarEnabled(true);
            callUsView2.setHorizontalScrollBarEnabled(true);

            callUsView2.loadUrl("file:///android_asset/map.png");

Result >

What I want >

ANSWER >>
                callUsView2.setWebChromeClient(new WebChromeClient(){
                @Override
                public void onProgressChanged(WebView view, int progress) {

                    if ( view.getProgress()==100) {
                        // I save Y w/in Bundle so orientation changes [in addition to
                        // initial loads] will reposition to last location
                        jumpToY(1000 , 1800 );
                    }
                }

                private void jumpToY (final int xLocation , final int yLocation ) {
                callUsView2.postDelayed( new Runnable () {
                      @Override
                      public void run() {
                        callUsView2.scrollTo(xLocation, yLocation);
                      }
                  }, 300);
                }

             } );

A: If the image is big and you want to show a specific part, you may want to zoom and scroll to a specific part.
What you can do is for example change the scale:
callUsView2.setInitialScale(some value which fits your needs);

and scroll if you wish to change the position:
callUsView2.scrollTo(x,y);


text:
Q: How can I create an app icon folder in the files app and copy items to it? I want to transfer some files (sound, texts, etc.) from an iOS app to the files app. In addition, I want to put all these items into a folder which has the same name as my app - as it is the case with GarageBand or KeyNote, for example.
In Xcode, I did enable the iCloud Documents capability - I did also define a Container "iCloud.xxx.yyy" - see code below.
guard let fileURL = Bundle.main.url(forResource: "test", withExtension: "aiff") else { return }

guard let containerURL = FileManager.default.url(forUbiquityContainerIdentifier: "iCloud.xxx.yyy") else { return }

if !FileManager.default.fileExists(atPath: containerURL.path) {
    try FileManager.default.createDirectory(at: containerURL, withIntermediateDirectories: true, attributes: nil)
}

let backupFileURL = containerURL.appendingPathComponent("test.aiff")
if FileManager.default.fileExists(atPath: backupFileURL.path) {
    try FileManager.default.removeItem(at: backupFileURL)
    try FileManager.default.copyItem(at: fileURL, to: backupFileURL)
} else {
    try FileManager.default.copyItem(at: fileURL, to: backupFileURL)
}

When I run my code, it seems to work - anyhow, I can't see nor folder representing my app name, nor "test.aiff" file in the files app. What is wrong with my approach?

A: You don't need to copy/move any file. What you need is to allow your app documents to be accessible from the other apps. Just go to your Info plist and allow "Supports Document Browser". All documents in your Documents directory will be automatically available there.


text:
Q: Import text from txt file into button text (html) I have this button in my html file:
<button id="btn1" name="subject" type="submit" class="btn btn-primary" value="html_j">kll</button>

And then I have a SendButton.txt file with the id 'sendBtn' in which I have just 1 row:
Send Message

I want that the message from the .txt file to be the text for the button. Any hints, please? T_T
I've tried successfully to set a default message to the button by writing this in main.js:
var y = document.getElementById('sendBtn');
y.innerText = "Sendddd"

But I don't know how to import the text from a file...

A: You cannot do that. You can read/write to a file using Node.js. It is not possible to read the contents of the file from frontend.


text:
Q: PostgreSQL - Function with local variables - Column reference is ambiguous I have had a look at other questions that match my subject but in my case the ambiguity, I believe, comes from variable having the same name as a column.
Here is a simplified version of the function I am trying to create:
CREATE OR REPLACE FUNCTION get_user_id(username TEXT)
RETURNS INTEGER AS $$
  DECLARE
    user_id BIGINT;
    other_param TEXT;
  BEGIN
    SELECT INTO user_id user_id FROM users WHERE users.username = get_user_id.username;

    SELECT INTO other_param users.value FROM users WHERE users.user_id = user_id;

    RETURN user_id;
  END
$$ LANGUAGE PLPGSQL

The problem is that the user_id on the right hand side of the WHERE is treated as a reference to the column.
I definitely need user_id in a local variable as it will be used in UPDATE and DELETE operations further along the function, but I won't get the it passed as a parameter, only username.
Upon some reading and having previously had some problems with parameters too I realised I can use get_user_id.username but it only applies to parameters, not local variables (if I use it with variable the query with fail as there is not FROM-clause for get_user_id).
Therefore am I missing something (not so) obvious about using variables in queries inside a function?
--- edit
Apologies I oversimplified the function, of course there's a first query that gets the user_id, and that part is working fine.

A: Any local variable can be qualified by block label
create table foo(a integer);
insert into foo values(10);

do $$
<<mylabel>>
declare
  a int default 5;
  r record;
begin
  select foo.a into r
    from foo
    where foo.a = mylabel.a + 5;
  raise notice '%', r.a;
end;
$$;
NOTICE:  10
DO

Usually all possible conflict local variables has prefix - common prefix is _.

A: I prefix parameters and variables so they are less likely to conflict with column names:
CREATE OR REPLACE FUNCTION get_user_id (in_username TEXT)
RETURNS INTEGER AS $$
  DECLARE
    v_user_id BIGINT;
  BEGIN
    SELECT u.user_id  INTO v_user_id FROM users u WHERE u.user_id = in_user_id;

    RETURN v_user_id;
  END
$$ LANGUAGE PLPGSQL

Presumably, though, you want to compare user names:
    SELECT u.user_id  INTO v_user_id FROM users u WHERE u.username = in_username;

A: https://www.postgresql.org/docs/current/static/plpgsql-implementation.html

Sometimes it is impractical to fix all the ambiguous references in a
  large body of PL/pgSQL code. In such cases you can specify that
  PL/pgSQL should resolve ambiguous references as the variable

and so on... thus:
t=# CREATE OR REPLACE FUNCTION get_user_id(username TEXT)
RETURNS INTEGER AS $$
#variable_conflict use_variable
  DECLARE
    user_id BIGINT;
    other_param TEXT;
  BEGIN
    SELECT INTO user_id users.user_id FROM users WHERE users.username = username;
    RETURN user_id;
  END
$$ LANGUAGE PLPGSQL
;
CREATE FUNCTION

let's check:
t=# create table users (user_id int, username text);
CREATE TABLE
t=# insert into users values (1,'a');
INSERT 0 1
t=# select get_user_id('a');
 get_user_id
-------------
           1
(1 row)

Attention - this check has big sense, and if you disable it, you can get some very ugly and very invisible errors. This is pretty dangerous. Don't do it, please.
Don't use it, unless you see invisible errors or you hold EVERY line under control

A: It is not missing username filtering? I think you wanted something like:
SELECT users.user_id INTO user_id FROM users WHERE users.username = username;

Is that way, the value of users.user_id will be set in user_id variable after a username filtering.


text:
Q: Powerbuilder Passing a Datastore / object i have a datastore that when retrieve and has results, the rows should be displayed in another window

ds_1.Retrieve()

IF ds_1.RowCount() > 0 THEN

i_str_pass.po[1] = ds_1

OpenWithParm(w_error, i_str_pass)

END IF

i_str_pass is a structure and po is a powerobject
i want to display the results of ds_1 in w_error's datawindow without needing to retrieve it again
i tried calling in w_error

str_pass i_str_pass
i_str_pass = Message.PowerObjectparm
dw_1 = i_str_pass.po[1]

i debugged and saw that I passed it correctly
but the data that was retrieved were not showing at all
anything im doing wrong? thanks in adv.

A: Use
i_str_pass.po[1]. DYNAMIC ShareData(dw_1)

instead of
dw_1 = i_str_pass.po[1]

Surprised the latter wasn't a runtime error, since you're assigning a DataStore to a DataWindow.
GetFullState/RowsCopy is all fine too, but incurs a memory penalty since you're making a copy of that data (which may or may not be something you're concerned about)

A: You could take a look at GetFullState()/SetFullState() :
blobl lbl_data
if i_str_pass.po[1].GetFullState(lbl_data) = 1 then
    dw_1.SetFullState(lbl_data)
end if

You could also take a look at ShareData() to establish a "link" between 2 DataStores or DataWindows.


text:
Q: How can i change the number of product to 4 in grid view to appear in one line in bazar theme woocommerce plugin I have been trying to accomplish the above without any luck...any suugestions would be appretiated.
here is a link to my page : http://umsi.me/uniikmedia/?post_type=product
i have added this code to my functions.php file :
   add_filter('loop_shop_columns', 'loop_columns');
   if (!function_exists('loop_columns')) {
   function loop_columns() {
   return 4; // 3 products per row
   }
   }

I also tried disabling the shop-sidebar.php file.
I was able to make it work on all desktop browsers but on mobile browers it wasn't loading up the image in the right size, but keeping the width of 1200px.
Here is the css i used to make it work
 html body.archive div.bg-shadow div#wrapper.container div#primary.sidebar-left   div.container div.row div#content-shop.span9 ul.products {
  width: 1200px;
  float: right;

 }

Thanks,


text:
Q: x86 Assemby : Finding length of string taking by user I am trying to find number of characters in string taken by user.However lengthof returns me initializing size of string
This is my code , it returns 11
INCLUDE Irvine32.inc
.data

MAX = 10
stringIn BYTE MAX+1 DUP (?)

.code
 main PROC

      mov  edx,OFFSET stringIn
      mov  ecx,MAX
      call ReadString

      call writeString
      mov eax,lengthof stringIn
      call writeint

main ENDP

END main

A: The length of the string returns in register EAX after calling ReadString :

*

*http://math.uaa.alaska.edu/~afkjm/cs221/handouts/procedures.pdf

*http://programming.msjc.edu/asm/help/source/irvinelib/readstring.htm
Search the text "readstring" in next example :

*

*http://cursos.itam.mx/akuri/2004/OPC/MASM615/Examples/Lib32/Irvine32.asm


text:
Q: How to slow down 240V AC bathroom fan I have a small toilet fan which is quite noisy and far too powerful for what we need. I'm looking for a solution where I could reduce AC 240V to AC 110-150V with minimum amount of components. Any transformer is out of question. Simply, no room for it. Initially, fan had a PIR sensor in the middle which was removed and now I have some space for components. 6x5cm and 2cm height. I know, it's not wise to use a resistor to reduce the voltage. Is there anything simple I could use in that space? I have more than basic experience in electronics but I didn't practice for 30 years. Sill, I understand components, diagrams, PCBs, multi-meters and can use a soldering gun. Anything I could get on ebay or assembly myself? Thank you all.

A: Simply use capacitor in series. You are talking about bathroom fan, so I think this power is about 20...30W, it means current is about 0.1A, so to loose 100V you need reactance about 1kohm - so something between 1.8...3.3uF should be enough. Of course, DO NOT use electrolytic capacitors - only HV MKSE, MKS or polypropylene capacitors with breakdown voltage > 600V.


text:
Q: Connect:Direct(NDM) Support in Apache Camel I have a requirement in my application to send data via FTP, SFTP, Email, MQ and Connect:Direct. I found Apache Camel was a good choice since it supports many protocols out of the box.
However, I have checked the apache camel documentation and could not find any component for file transfer via Connect:Direct (NDM). Does anyone knows if this is supported by Apache Camel ?


text:
Q: RPA supplier invoices I was wondering if anyone has automated the processing of supplier invoices with an RPA system
My question is as invoices come in in different formats depending on the supplier do you need one robot per supplier?
Many thanks

A: Actually no, one robot can have different procedures for different invoice formats and choose them during the processing. Nevertheless it may be pretty hard to maintain, let's say, more than 3 formats.

A: Divide the process of invoice capturing into two parts.
Gather data & insert data.
While insert data into SAP or another application is same for each invoicing company.
Gathering of the data is more challenging topic.

*

*You can define each customer as a template. You will use keywords on the invoice to distinguish between invoices and then parse data which are necessary to capture.

*Use third party software to gathering of the data. Usually AI taking care of gathering the data. You just need to insert couple of invoice as an example for the AI. Do not want to make any propagation, but there are companies like: https://rossum.ai/, https://typless.com/ etc..

A: Each supplier has its own format/pattern of invoice and your invoice parser should be trained with each format/pattern. Sometime you may have to train/tune the AI model within the parser to achieve more than 90% accuracy.
So, from RPA standpoint, there could be one bot that will trigger the AI invoice parser and invoice parser needs to be trained with each pattern of invoices.


text:
Q: How to search for a whole word with special char using oracle contains? I have a column short_desc in my table that is context indexed.
When i search like below
select * from table1 where CONTAINS (short_desc,'{product\_id}') > 0

I get results like

abc product_id
abc product id

The escaped character behaves like an OR and the query searches for 'product_id' or 'product id'
How can i search for the whole word 'product_id' only?
Thanks in advance

A: According to Oracle*Text documentation non-alphabetic characters are treated as whitespace (so product$id and product_id both treated as 'product id').
This behavior demonstrated at this SQLFiddle. Don't matter which non-aplhanumeric symbol placed between 'product' and 'id'.
To alter that you must define underscore as printjoin in lexer used by CONTEXT index.
I can't demonstrate this in SQLFiddle because access to ctx_ddl package restricted here, but this code must do the job:
create table table1(short_desc varchar2(200))
/

-- Add lexer definition and set '_' as "printjoin"
begin
  ctx_ddl.create_preference('mylex', 'BASIC_LEXER');
  ctx_ddl.set_attribute('mylex', 'printjoins', '_');
end;
/

-- Specify new lexer definition while creating index
create index table1_ctx_index on table12(short_desc)
  indextype is ctxsys.context
  parameters ( 'LEXER mylex' )
/

insert into table1(short_desc) values('1 product id 2')
/
insert into table1(short_desc) values('3 product_id 4')
/
insert into table1(short_desc) values('5 product#id 6')
/
insert into table1(short_desc) values('7 productXid 8')
/
insert into table1(short_desc) values('9 product-id 10')
/

alter index table1_ctx_index rebuild
/

A: can try this
 select * from table1 where CONTAINS (short_desc,'{product'||'\_id}') > 0


text:
Q: How to make a number appear in a range from 0 to 9? I am currently completing a project and have come across an error in my coding.
I have a button which calls a JS prompt box asking to enter an integer between 0 and 9.
This number is then used as a game where 3 random integers from 0 and 9 appear every second and when you click on the matching number your score increases.
This is my code so far:

I want to know exactly how to display random integers in a range from 0 and 9.
Is a code like this on the right track?

Can anyone point me in the right direction?
Cheers.

A:

var txt;

function chooseNum()
{

var person = prompt("Choose an integer between 0 and 9:");
if (person == null || person == "") {
    txt = "User cancelled the prompt.";
} else {
    txt = person;
}

document.getElementById("chosen").innerHTML = txt;
}
chooseNum() ;
var id = window.setInterval(function(){randomNumber();},1000);

function randomNumber()
{
var rand = Math.floor(Math.random()* 9 + 1);
 $('#number1').html(rand);

}


text:
Q: Duplicating multiple powerpoint slides using docx4j I'm trying to duplicate a couple slides using docx4j but I am running into some trouble.
I have a .pptx file with 3 pages and I am looking to duplicate each page several times. This is my code so far (based off samples from here:
    PresentationMLPackage presentationMLPackage = (PresentationMLPackage) OpcPackage.load(new File(args[0]));

    MainPresentationPart pp = (MainPresentationPart)presentationMLPackage.getParts().getParts().get(
            new PartName("/ppt/presentation.xml"));

    List<SlidePart> slideParts = pp.getSlideParts();

    int index = 1;

    for(SlidePart slidePart : slideParts){

        SlideLayoutPart layoutPart = (SlideLayoutPart)presentationMLPackage.getParts().getParts().get(new PartName("/ppt/slideLayouts/slideLayout" + index + ".xml"));
        Sld copied = XmlUtils.deepCopy(slidePart.getContents(), slidePart.getJAXBContext());

        SlidePart slide = new SlidePart(new PartName("/ppt/slides/slide" + index + ".xml"));
        slide.setContents(copied);

        pp.addSlide(1, slide);

        slide.addTargetPart(layoutPart);

        index++;
    }

    presentationMLPackage.save(new java.io.File("test.pptx"));

My code runs fine without any errors and when I open the file, I am alerted of an error within the powerpoint and it asks to repair the file and when you do, the page is blank and the page did not duplicate.
How do I get this working properly?

A: In the general case, this isn't so straight forward.  You need to take care of the slide rels etc.
For this reason, we have a commercial solution in Docx4j Enterprise, which you can find at https://www.plutext.com/m/index.php/products


text:
Q: order should be paid before save or not? I have a logical question about magento checkout
is orders should be saved after a payment received or not?
i saw there is a placeOrder function in js files of paypal braintree or even simplegateway module ! ... is it called before payment received by this modules or not?


text:
Q: Compilation hangs when minted precedes istgame I can't get the following code to compile on my Windows machine after upgrading to TeX Live 2021. This used to work fine with TeX Live 2019.
\documentclass{article}

\usepackage{istgame}
\usepackage[outputdir=./.temp]{minted}

\begin{document}

\begin{minted}{text}
    hello
\end{minted}

\begin{istgame}
    \istroot(0)
    \endist
\end{istgame}

\end{document}

latexmk --output-directory=.temp -latexoption=--shell-escape test.tex

The log gets to this point, and then it hangs indefinitely
D:\test>set  /p x=D:\test\.venv\Scripts\pygmentize.exe 0<nul: 1>>test.aex

D:\test>set  /p x= 0<nul: 1>>test.aex

D:\test>set  /p x= 0<nul: 1>>test.aex
system returned with code 1
 (.temp/test.aux) (./.temp/_minted-test/default-pyg-prefix.pygstyle)
(./.temp/_minted-test/default.pygstyle)
(./.temp/_minted-test/437E267D5159CB3E1880E2F59933381F37A68874F7479A9FD91AC7B65
D4A9BC0.pygtex)

When I forcefully terminate it, the following is logged
!Terminating on signal SIGINT(2)
 Interruption.
\istownerstyle code ...owner@text@font \endcsname
                                                  {#1}\fi
l.14     \endist
              (.venv)

If I move the minted environment after the istgame one, then it works just fine. If I remove either the minted or istgame environment, it also starts to work. The order of \usepackage does not seem to matter.
I tried to reproduce this in a container using the texlive/texlive:latest image, but it compiles fine in there. I am at a loss for how to debug this further.

A: Hangs with TeX Live 2020 as indicated, but not with TeX Live 2021.
Workaround:
\documentclass{article}

\usepackage{minted}
\usepackage{istgame}

\istownertextfont{@firstofone}% <----

\begin{document}

\begin{minted}{text}
    hello
\end{minted}

\begin{istgame}
    \istroot(0)
    \endist
\end{istgame}

\end{document}

But, really, istgame should not state \istownertextfont{ } with a space.