text:
Q: scp to another linux system via ssh where not using port 22 I'm trying to copy a folder from one system to another using scp (secure copy) however I cannot work out how to specify the port.
I understand that to scp, I can...
scp /file/location/folderName user@192.***.*.***:/destination/location/

however I have changed the destination system's SSH port so I get get this error...

ssh: connect to host ..*.*** port 22: Connection refused lost
  connection

Is there some sort of -p command I can use to specify port number?
I also tried adding the port like this...
scp /file/location/folderName user@192.***.*.***:>>portNumHere<</destination/location/

Updated with solution...
I was struggling not only with using the wrong -P but also where to place. I know understand and this works for me...
scp -r -P >>portNumHere<< /file/location/folderName user@192.***.*.***:/destination/location/

A: Use a capital -P port.  The lower case -p option conflicts with the -p "preserve" option from cp.
Per the man page:
 scp [-12346BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file]
     [-l limit] [-o ssh_option] [-P port] [-S program]
     [[user@]host1:]file1 ... [[user@]host2:]file2

 ...

 -P port
         Specifies the port to connect to on the remote host.  Note that
         this option is written with a capital 'P', because -p is
         already reserved for preserving the times and modes of the
         file.


text:
Q: Closed form for improper definite integral involving trig functions and exponentials? Is it possible to calculate the following definite integral in a closed form?
$$ \int_0^\infty \left| \sin x \cdot \sin (\pi x) \right| e^{-x} \, dx$$

A: Let $f(x) = e^{-x} \sin(x)\sin(\pi x)$
Let $A=\{x : e^{-x}sin(x)\sin(\pi x) > 0\}$
Let $B=\{x : e^{-x}sin(x)\sin(\pi x) &lt 0\}$
A and B are disjoint and hence $\int_{0}^{\infty}f(x)=\int_A f \,du + \int_B  f\,du$
Range of $f(x)=0$ to $\kappa =\max(f(x))$
Split the range of $f(x)$ into n intervals, $n\rightarrow \infty$ such that
$\displaystyle \int_A f \,du = \lim_{n\to\infty}  \sum_{j=1}^{n} \left (\left(j+1\right)\frac{\kappa }{n}-j\frac{\kappa }{n} \right )  \int I_{A_j}$
$\displaystyle \int_B f \,du = \lim_{n\to\infty}  \sum_{j=1}^{n} \left (\left(j+1\right)\frac{\kappa }{n}-j\frac{\kappa }{n} \right )  \int I_{B_j}$
$\displaystyle \int_{A+B} f \,du = \lim_{n\to\infty} \frac{\kappa }{n} \sum_{j=1}^{n} \int I_{A_j} + I_{B_j}$
$\displaystyle A_j =\left (\frac{j\kappa }{n} &lt f(x) &lt \frac{(j+1)\kappa }{n} \right )$
$\displaystyle B_j =\left (\frac{j\kappa }{n} &lt -f(x) &lt \frac{(j+1)\kappa }{n} \right )$
$\displaystyle h(a,x,b) =
\begin{cases}
1 &\text{if } |a| &lt |x| &lt |b|, \\
0 &\text{if } otherwise.
\end{cases}
$
$\displaystyle I_{A_j} =\frac{1}{2}h\left(j\frac{\kappa }{n},f(x),\left(j+1\right)\frac{\kappa }{n} \right ) \left(1 + \frac{\left|f(x)\right|}{f(x)}\right)$
$\displaystyle I_{B_j} =\frac{1}{2}h\left(-1\left(j+1\right)\frac{\kappa }{n},-f(x),-j\frac{\kappa }{n} \right ) \left(1 - \frac{\left|f(x)\right|}{f(x)}\right)$
working on it.

A: One could give the following a try: Develop $|\sin x|$ into a Fourier series. You get
$$|\sin x|={2\over\pi}-{4\over\pi}\sum_{k=1}^\infty {1\over 4k^2 -1}\cos(2kx)\ .$$
Similarly
$$|\sin (\pi x)|={2\over\pi}-{4\over\pi}\sum_{k=1}^\infty {1\over 4k^2 -1}\cos(2\pi kx)\ .$$
Since the two series are absolutely convergent you can multiply them, obtaining a double series of the form
$$\sum_{k,l} 2c_{k,l}\cos(2kx)\cos(2\pi l x)=\sum_{k,l} c_{k,l}\bigl(\cos \bigl((2(k+\pi l)x\bigr)+\cos\bigl(2(k-\pi l) x\bigr)\bigr)\ .$$
Now $$\int_0^\infty \cos(q x)e^{-x}\ dx={1\over 1+q^2}\ ;$$
therefore you will end up with a huge double series containing terms of the form
$${c\over (4k^2-1)(4l^2-1)\bigl(1+4(k\pm \pi l)^2\bigr)}\ .$$
I wish you luck$\ldots$

redpajama_set_name: RedPajamaStackExchange


text:
Q: creating a static measure to get values in power bi dax I have the below two tables in power bi as below

based on the above two tables I want to create a matrix visual that should look like the image below "Output Matrix":

I also have a slicer for a month, based on the month column from Table 1, what I want is in the output matrix visual the "Total Users" should remain constant value when we change the month and the rest of the columns values change based on the month selected in the slicer.

A: Create the following 3 measures:
Measure 1
Active Users = DISTINCTCOUNT( Table1[user_id] ) + 0

Measure 2
Total Users = COUNT( Table2[user_id] ) + 0

Measure 3
Active Users % = DIVIDE( [Active Users], [Total Users], 0 )

Then create a Matrix Visual and drag the Manager column and the 3 measures.
This is the final output:


text:
Q: The second "that" could be removed from the clause? there:
I have a sentence. I'd like to know the second "that" could be removed?
The accident resulted from an outside sudden cause that the driver had no control and (that) occured without any warning signals, thus the accident was inevitable.
This sentence comes from two separate sentences. The first is: The accident resulted from an outside sudden cause that the driver had no control. The second is: The cause occurred without any warning signals.
I combined the two sentences together, but I am not sure whether the second "that" should be removed or not? I am often confused by this problem; anybody can give me a general rule?
Thanks!

A: If the two sentances are to be combined in that that way, i think the secon "that" is needed. However both original sentence had some other problems:

The accident resulted from an outside sudden cause that the driver had no control.

should be

The accident resulted from an outside sudden cause that the driver had no control over. (or perhaps "no control of", but "over" is better and more common.)
The cause occurred without any warning signals.

This seems awkward to me, although it might be less so if a specific cause were stated. I would favor a variant such as:

*

*The accident occurred without any warning signals.

*There were no warning signals before the accident occurred.

*The cause was not associated with any warning signals.

For an overall version:

The accident resulted from an outside sudden cause that the driver had no control over and that arose with no warning signals, thus the accident was unavoidable.

("Inevitable" would mean the accident was destined no matter what, "unavoidable" means that the driver had no way to avoid it.)


text:
Q: How to refresh BlackBerry ui page on button click? I may seem ignorant but I have not found much information about how to go about my problem developing my BlackBerry application.
Basically I have constructed a UI that contains a few image buttons. What I want to do is when I click on one of the buttons, I want an image at the center of the screen to switch seemlessly to another image.
I am currently not using any threads though from what I've gathered I need to?
Or do I simply have to push a new screen in my button listener and recall the class's constructor and rebuild the page with different images?
Sorry if this is unclear, I would really appreciate some basic info on how to do this or a link that explains page refreshing in detail for blackberry!
Thanks alot
EDIT : Okay here is a very small part of my code  :
This is basically the last thing I have tried in the listeners, I dont know how to change the image (flagField) when I press one of the two buttons! The only thing that worked for me was pushScreen(new Csps("americanflag")); every time I would press on a button, but the performance was bad and I was left with a stack of screens, not ideal.
I have been trying to do this all day long hehe... sigh , here goes:
public class CSP extends UiApplication
{
public static void main(String[] args)
{
    CSP theApp = new CSP();
    theApp.enterEventDispatcher();
}

public CSP()
{
    CSPS csps = new CSPS();
    pushScreen(csps);
}
}

class CSPS extends MainScreen implements FieldChangeListener
{

int width = Display.getWidth();
int height = Display.getHeight();

ButtonField backButton;

ImageButtonField canadianFlag;
ImageButtonField americanFlag;
Bitmap changeableFlag;
String currentFlag ="canada_flag.png";
BitmapField flagField;

canadianFlag = construct("canada_flag.png", 0.18);
americanFlag = construct("us.gif", 0.18);

    canadianFlag.setChangeListener(this);
    americanFlag.setChangeListener(this);

    add(flagField);
    add(canadianFlag);
    add(americanFlag);
//LISTENERS
public void fieldChanged(Field field, int context){

    if(field == canadianFlag){
        setCurrentFlagResource("canada_flag.png");
        BitmapField newFlagField = populateFlagField(currentFlag, 0.3);
        replace(flagField, newFlagField);

        this.invalidate();
        this.doPaint();
        this.updateDisplay();

    }
    else if(field == americanFlag){

        setCurrentFlagResource("american-flag.gif");
        BitmapField newFlagField = populateFlagField(currentFlag, 0.3);
        replace(flagField, newFlagField);

        this.invalidate();
        this.doPaint();
        this.updateDisplay();

    }

the setCurrentFlagRessource method sets the flagField attribute to the appropriate BitmapField

A: There is a method called setBitmap() in the BitmapField.
In the listeners you should simply call flagField.setBitmap(newbitmap). You can also use the method setImage(). There is no need to call invalidate(), updateUI etc.
If you get any IllegalStateException while using this method, simply get a lock on the Applicaton Event lock object or invokeLater() this code.

A: You will only need to use threads if you are getting your images from some place that might block (like a web server). You should only need to update the images, though you may need to call invalidate() on your button or screen. What would really help is some information on what you are doing. You didn't even tell us what class you're using to display the image, if you've extended it or not, etc.

A: I don't know what you are doing in your code; But The way of refresh the screen is not like that;
So, I change Your CSPS screen which you are trying to refresh the screen; See the below code...
class CSPS extends MainScreen implements FieldChangeListener
{

int width = Display.getWidth();
int height = Display.getHeight();

ButtonField backButton;

//ImageButtonField canadianFlag;
//ImageButtonField americanFlag;
Bitmap changeableFlag;
String currentFlag ="canada_flag.png";
BitmapField flagField;
public CSPS()
{
    createGUI();
}

public void createGUI()
{
    canadianFlag = construct("canada_flag.png", 0.18);
    americanFlag = construct("us.gif", 0.18);

        canadianFlag.setChangeListener(this);
        americanFlag.setChangeListener(this);

        add(flagField);
        add(canadianFlag);
        add(americanFlag);
    //LISTENERS
}

public void fieldChanged(Field field, int context){

    if(field == canadianFlag)
    {
        setCurrentFlagResource("canada_flag.png");
        BitmapField newFlagField = populateFlagField(currentFlag, 0.3);
        replace(flagField, newFlagField);

        deleteAll();
        createGUI();
        invalidate();
    }
    else if(field == americanFlag)
    {
        setCurrentFlagResource("american-flag.gif");
        BitmapField newFlagField = populateFlagField(currentFlag, 0.3);
        replace(flagField, newFlagField);

        deleteAll();
        createGUI();
        invalidate();
    }
}
}

*

*Construct a createGUI() method, in that write the code that what you have to design for that screen. Not only this screen; What ever you are creating do like this;
  and

deleteAll();
createGUI();
invalidate();

*

*For refresh the screen do the above three lines; delete all the fields and call again the createGUI() method; and at last invalidate();


text:
Q: Does a table I have code that makes a column header <th of a table disappear. I thought that making the column header disappear would make the children of that column, the actual cells also go away. That is incorrect, at least as I coded it below.

Hard for me to believe I can't access those items and make them disappear also? I realize that I can store a map of column headers and its children, but clearly React must be keeping this information. So the question is, how do I access them inside handleClick?
class StockTable extends React.Component {
    constructor(props) {
        super(props);
        this.state = {hidden: [], stockItems: []};
    }
    handleClick(event) {
        this.state.stockItems.forEach(function(stock) {
            console.log(stock);
        });

        event.currentTarget.style.display = 'none';
        //How do I make the children of this column display style also none?
    }
    render () {
        var items = [];
        for (var symbol in this.props.stocks) {
            var stock = this.props.stocks[symbol];

            items.push(<StockRow key={stock.symbol} stock={stock} bid={this.props.bid} ask = {this.props.ask} last={this.props.last} unwatchStockHandler={this.props.unwatchStockHandler}/>);
                this.state.stockItems.push(stock);

        }

        return (

                <colgroup>
                    <col class="maroon" />
                </colgroup>

                     this.handleClick(i)}>P/M
                    ....


text:
Q: pip install git+url within a docker environment I am using this Docker (FROM lambci/lambda:python3.6) and I need to install a private repository package. The problem is the Docker does not have git and I can not install git using apt-get or apk install because the Docker is not Linux.
Is there any possible way to fix this installing git? Or is there any other better method I could use to install this private repository package?

A: RUN python -m pip install git+URL_OF_GIT_REPO

A: add this to makefile:
# makefile
git clone REPO
cd REPO_DIR; python setup.py bdist_wheel
cp REPO_DIR/dist/* .
rm -rf REPO_DIR/

add this to dockerfile:
# dockerfile
RUN pip install REPO*.whl

and then the package is successfully installed within docker

A: in your dockerfile put this code before installing requirements and you will be fine:
RUN apt-get update && apt-get install -y git

A: FROM python:3.9 as builder
RUN pip install --target /tmp/site-packages "git+GIT_URL"

FROM public.ecr.aws/lambda/python:3.9
COPY --from=builder /tmp/site-packages /var/lang/lib/python3.9/site-packages

You could use python:3.9 which has git, or any other image to install dependancies and then copy it into the AWS image.
To find the site-packages location, just use python -m site in a lambda container

A: can you pip install the git repo next to your source code and mount it together with your code into the container?
cd WORKING_DIRECTORY
pip install --target ./ GIT_URL


text:
Q: Microsoft Graph API calls through Express app I am trying to follow this tutorial here: https://github.com/Azure-Samples/ms-identity-javascript-nodejs-tutorial/tree/main/2-Authorization/1-call-graph. It uses the microsoft-identity-express wrapper for msal-node, but I am having trouble with some Graph routes.
I have set up my Azure AD app permissions exactly as described in the tutorial.
I have successfully got the /profile route working, like this:
router.get('/profile',
    msid.isAuthenticated(),
    msid.getToken({
        resource: appSettings.protectedResources.graphAPI
    }),
    async (req,res,next) => {
        let output;

        try {
            const graphClient = graphManager.getAuthenticatedClient(req.session.protectedResources["graphAPI"].accessToken);

            output = await graphClient
                    .api('/me')
                    .get();

        } catch (error) {
            console.log(error);
            next(error);
        }
        res.send(output);
    }
);

My appSettings look like this:
    const appSettings = {
    appCredentials: {
        clientId: "zzz",
        tenantId: "yyy",
        clientSecret: "xxx"
    },
    authRoutes: {
        redirect: "/redirect",
        error: "/error", // the wrapper will redirect to this route in case of any error
        unauthorized: "/unauthorized" // the wrapper will redirect to this route in case of unauthorized access attempt
    },
    protectedResources: {
        graphAPI: {
            endpoint: "https://graph.microsoft.com/v1.0/me",
            scopes: ["user.read"]
        },
        armAPI: {
            endpoint: "https://management.azure.com/tenants?api-version=2020-01-01",
            scopes: ["https://management.azure.com/user_impersonation"]
        },
        joinedTeams: {
            endpoint: "https://graph.microsoft.com/v1.0/me/joinedTeams",
            scopes: ["user.read", "teamsettings.readwrite.all"]
        },
        myEvents: {
            endpoint: "https://graph.microsoft.com/v1.0/me/events",
            scopes: ["user.read", "calendars.readwrite"]
        },
        messages: {
            endpoint: "https://graph.microsoft.com/v1.0/me/messages",
            scopes: ["Mail.ReadWrite"]
        }
    }
};

And finally, my getAuthenticatedClient function from graphManager is:
const getAuthenticatedClient = (accessToken) => {
    // Initialize Graph client
    const client = graph.Client.init({
        // Use the provided access token to authenticate requests
        authProvider: (done) => {
            done(null, accessToken);
        }
    });

    return client;
};

graphManager and appSettings are set up exactly how the tutorial does it. I added more API endpoints to the protectedResources object as the tutorial says. I followed the same logic process as the /profile route for the extra Graph API routes. But I still get 401 errors whenever running this:
router.get('/me/events',
    msid.isAuthenticated(),
    msid.getToken({
        resource: appSettings.protectedResources.myEvents
    }),
    async (req,res,next) => {
        let output;

        try {
            const graphClient = graphManager.getAuthenticatedClient(req.session.protectedResources["myEvents"].accessToken);

            output = await graphClient
                    .api('/me/events')
                    .get();

        } catch (error) {
            console.log(error);
            next(error);
        }
        res.send(output);
    }
);

I can't understand why /me calls to the Graph API work but /me/events does not. The correct permissions are being passed to msid.getToken() and getAuthenticatedClient(), so why do the API calls fail?


text:
Q: # duplicate columns & possible reduce dimensionality key error 0 Python error I have the follow data set:

so as you can see, the shape is: 21 rows x 50 columns
So I would like to apply the follow condition:
If any row from "defaultstore"= 1, then the column "FinalSL" column will receive 4 times the value which "FCST:TOTAL" column contains.
So I create the follow function to do this calculation:

What should I do to avoid this kind of error ?


text:
Q: Sharepoint 2010 - Is it safe to delete doc library templates? If you have a doc library template, and you've created some doc library instances based off this template, is it safe to remove this template once you're done with it?

A: Libraries created from a template are not tied to the template, so the template can be removed if it is no longer required.  The same holds true for Site Templates.
Yes, the template can be removed.

A: If you meant list definition, the answer is NO.
We had a real situation at work, when deletion of a list definition which was previously deployed through a feature, broke the list instances which were created based on the definition.
In our particular situation, deletion of list definition produced exception 'Invalid file name' (0x81020030) on page load, when it was trying to access the collection of list views (in SPRequestInternalClass.GetViewsSchemaXml method).
The list definition was created as a List Definition project item in Visual Studio (with Schema.xml).
The screenshot of the error from the corresponding bug report:

You can check out the full-sized screenshot.
Eventually, I haven't found any resolution or workaround on this issue, and we had to restore the removed definitions.
So, even if it is not always true, you'd better check somewhere on staging environment :)

A: I don't think it's a good practice to remove any components from SharePoint, unless you've removed all provisioned instanced of this component in your case list instances. You can always change your List template and set Hidden attribute to TRUE so it won't appear in the UI.
<ListTemplate  Hidden="TRUE" />

A: If it's your own template. I would not delete OOTB template.


text:
Q: Error al sacar dato desde una relacion con laravel Tengo 2 tablas users y roles, estoy tratando con laravel sacar el nombre del rol el cual posee mi usuario, este es mi Model de roles
class Role extends Model
{
    protected $table = 'roles';

    public function user(){

        return $this->hasMany('App\User');

    }

}

Relacion Model User
public function role(){
    return $this->hasMany('App\Role', 'id');
}

trato de obtener el dato usando:
$user = \Auth::user();

echo $user->id_role->name;

Si uso unicamente:
echo $user->id_role;

me trae los datos sin problemas, el inconveniente es para sacar los datos de la tabla role. Me arroja el error

Trying to get property of non-object

A: La relación desde Role no es correcta, tu tienes esto
public function role(){
   return $this->hasMany(App\Role::class);
}

Cuando debiera de ser:
public function role(){
   return $this->belongsTo(App\Role::class);
}

Para recuperar el nombre de role solo tienes que hacer algo como:
$user->role->name;

A: Necesitaría ver la definicion de las tablas pero en principio para usar la relación tenés que llamar a la relación y no lo estás haciendo.
Deberías de hacer
$user->role->name;

Mi recomendación es que uses una relación Many to Many para hacer esto. De hecho el ejemplo de este tipo de relación en la documentación es con usuarios y roles.
Tabla users
- id
- name
Tabla roles
- id
- name
Tabla role_user
- id
- role_id
- user_id
Modelo User
public function roles()
{
    return $this
        ->belongsToMany('App\Role');
}

Modelo Role
public function users()
{
    return $this
        ->belongsToMany('App\User');
}

Con esto te funciona seguro
foreach ($user->roles as $role) {
    echo $role->name;
}


text:
Q: How does jTemplates perform? I'm working on a website that I plan to have a lot of JSON/AJAX generated lists (kind of like a social networks news feed).  How does jTemplates work with this kind of situation?  Is there a better solution?
From what I can see, it looks nice, but I've seen very little documentation, and running examples.

A: I've used jQote2 which is lightning fast. See this post with performance tests.
It's a slightly refactored version of client-side templating engine written by John Resig.


text:
Q: Appium cannot find ADB path even though appium-doctor passes Appium Doctor passes

This is in my bash_profile

I am still seeing this issue
org.openqa.selenium.WebDriverException: An unknown server-side error occurred while processing the command. Original error: Could not find adb Please set the ANDROID_HOME environment variable with the Android SDK root directory path. (WARNING: The server did not provide any stacktrace information)


text:
Q: How are the risks of opening doors in-flight on airplanes different from opening doors on submarines underwater? Why is it considered dangerous or risky to open doors on an airplane during flight, while opening doors on a submarine underwater is generally considered safe?
What are the scientific factors that make it dangerous to open a door on an airplane during flight?

A: Airplanes (submarines) operate in positive (negative) pressure relative to the surrounding air (water). The surrounding fluid pressure decreases (increases) with increasing height (depth) exponentially (linearly).
Airplanes are pressurized to 8000'. With an atmospheric half-height 16,000', the pressure difference is:
$$ \Delta P_A = (1\,{\rm atm})(2^{\frac{8000'}{16000'}} - 2^{\frac{35000'}{16000'}}) \approx
7\,{\rm lbs/in^2} $$
while a water pressure increases at (roughly) 1 atm per 10 meters. The estimated crush depth is 900 m (according to a search), so at maximum operating depth, the pressure difference is:
$$ \Delta P_S = (1\,{\rm atm})\frac{900\,{\rm m}}{10\,{\rm m}} = 1278
\,{\rm lbs/in^2}$$
With a human's cross sectional is around 2400 square inches, the force on the body from the pressure differential for an open airplane (submarine) door is 8 (1500) tons.
On an airplane, with 8 tons of force, you are going out the door. You can't hold on like in the movies. Regarding the submarine, with 1500 tons, everyone in the sub dies instantly. Submarines at crush depth implode in milliseconds.
People have been sucked out of airplanes while other passengers witnessed it. Submarines have been lost at crush depth, no one survived to tell the tale.
A good example of the dangers of pressure differential is the Byford Dolphin accident, in which divers went from 12 atm to 1 atm as fast as possible (https://en.wikipedia.org/wiki/Byford_Dolphin). The mechanical force ejected the diver near the door, in pieces, some 30 feet, while divers in the bell suffered instant bubbling of, and lipids precipitating out of, their circulator systems. (don't look at the photos).


text:
Q: How to write query for this requirement as in body? I want to print the hacker_id, name and the total number of challenges created by each student. Sort your results by the total number of challenges in descending order. If more than one student created the same number of challenges then sort the result by hacker_id. If more than one student created the same number of challenges and the count is less than the maximum number of challenges created then exclude those students from the result.
Hackers table

Challenges table

I have tried this query
SELECT b.hacker_id
    ,a.name
    ,count(b.hacker_id)
FROM hackers AS a
INNER JOIN challenges AS b ON b.hacker_id = a.hacker_id
GROUP BY b.hacker_id
    ,a.name
ORDER BY count(b.hacker_id);

But I am not getting output as expected.

A: SELECT a.hacker_id, ISNULL(count(c.challenge_id), 0)
FROM hackers a
LEFT JOIN challenges c ON c.hacker_id = a.hacker.id
group by a.hacker_id

With left join you will take all elements from left table ("hackers") and counting of challenges for each, if exist. if result of count(c.challenge_id) will be NULL, this will be replaced by 0 value


text:
Q: ldm_parse_tocblock(): Cannot find Tocblock, database may be corrupt I received following error when Fedora was booting up :
ldm_parse_tocblock(): Cannot find Tocblock, database may be corrupt.

My computer dual boots Fedora v.30 and Windows 10.
what is the solution for said error ?

A: I know this is an old question, but this just happened to me. I have Fedora 36 with Windows 11 dual boot, and this seems to be related to having dynamic disks (on NTFS). I had older HDDs and just plugged them in to have more space for my Steam library.
Found more information here, so this is nothing to worry about.


text:
Q: Link Break in SQL What's the symbol or expression for a line break in oracle sql?
Ive searched everywhere without success, so that an expression 'line1line2' is written :
line
line2 (One beneath the other)
This is the code:
SELECT NVL2(TRIM(NAME),TRIM(NAME),NULL)||CHR(13)|| NVL2(TRIM(STATE),TRIM(STATE),NULL)


text:
Q: Dismiss last ViewController after the new ViewController is presented I open the same ViewController with a different variable, in case that is important:
@IBAction func buttonNextPostTapped(_ sender: UIButton) {
    //let postCount = posts.count
    //let postNumber = Int.random(in: 0 ..< postCount)
    let currentVC = presentingViewController
    let storyBoard : UIStoryboard = UIStoryboard(name: "MainApplication", bundle: nil)
    let nextViewController = storyBoard.instantiateViewController(withIdentifier: "PostsViewController") as! PostsViewController
    //nextViewController.post = posts[postNumber]
    nextViewController.isFromRandom = true
    self.present(nextViewController, animated: true, completion: {
        currentVC?.dismiss(animated: true, completion: {})
        })
    }

When I tap the button, a new VC appears and the old VC moves to the background. When I tap the button multiple times, I have a lot VC in the background.
How can I dismiss the previous VC, when the new VC is presented, so I will not have a lot of VCs in the background?
Edit: With the current code, everything gets dismissed.


text:
Q: Edit attribute in magento I am using magento 1.8.1 and i want to edit the attribute which is already created. but the option such as show in layered navigation is disable.
enter image description here

Please tell me how to enable this option and edit it again?

A: There is an old extension which can be used
http://www.magentocommerce.com/magento-connect/flagbit-change-attribute-set.html
you have to modify it for magento 1.8

A: This is set at the time the attribute is created. To edit existing, you will have to edit in the database:
Edit column 'frontend_input' in eav_attribute. Also make sure your 'backend_type' supports the 'frontend_input' type. This is normally decided by Mage::getModel('eav/entity_attribute')->getBackendTypeByInput($frontend_input)


text:
Q: How to retrieve value of XML element using a Nokogiri SAX Parser? How does one access the text value of a nested element using a Nokogiri SAX parser?
require 'nokogiri'

  xml = <<-eos
   <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
      <sitemap>
        <loc>http://www.example.com/example-sitemap.xml</loc>
     </sitemap>
    </sitemapindex>
  eos

  class MySAXDoc < Nokogiri::XML::SAX::Document
     def start_element name, attrs=[]
        if name == "sitemap"
          # from here, how can one retrieve the value of the child element, `loc`?
        end
     end
  end

  sax_parser = Nokogiri::XML::SAX::Parser.new(MySAXDoc.new)
  sax_parser.parse(xml)

A: You can't read ahead, so you must keep track of the current context within the file yourself.  Something along these lines should do the trick:
def start_element(name, attrs = [])
  @element = name

  if name == 'sitemap'
    @sitemap = true
  end
end

def end_element(name)
  @element = nil

  if name == 'sitemap'
    @sitemap = false
  end
end

def characters(string)
  if @element == 'loc' && @sitemap
    # The local variable 'string' holds the text contents of the <loc> tag
    # so do something with it here
    puts string
  end
end

How this works: When a new element is started it checks to see if it is a  and if so sets a @sitemap variable.  On the next iteration when the element is  it checks @sitemap to see if it is within a sitemap and does something with its contents.


text:
Q: Discern between a cURL POST request and normal POST request in PHP Is there a way to discern if an incoming POST request has been initiated programmatically via cURL, or is a normal HTML POST request?
Can I differentiate between the two in PHP so that I can set a specific condition?

A: if you mean libcurl , i'm pretty sure the answer is no, it adds no identifying information in it's requests by default.
if you mean curl , yeah it's easy. the default useragent is curl/versionumber (on my system right now its curl/7.52.1)
if(1===preg_match('/^curl\/[\.\d]+/',$_SERVER['HTTP_USER_AGENT']??'')){
//curl's user-agent string. probably curl
} else {
//could be anything (including curl, perhaps with a masked user-agent)
}

a regex may even be overkill, maybe you could just do 0===strpos('curl/',$_SERVER['HTTP_USER_AGENT']??'')
an interesting note is that curl will not execute javascript, so if you add a (hidden?) input tag with javascript, curl will ignore it. like jsInputTag=document.createElement("input");jsInputTag.setAttribute("name","jsInputTag");document.getElementById("form").appendChild(jsInputTag);
curl will not add the jsInputTag to the form (nothing stops a programmer from adding it manually, though.)
but then again, many paranoid people don't run javascript on their browsers either, and most browsers have a way for turning it off.
by the way, if it's an X-Y problem, and what you really need is protection against automated scripts, you should use a captcha, not try to detect curl. for example: ReCaptcha


text:
Q: How to send Whatsapp invitation link to join a group using php Actually, i am working on a application which sends a whatsapp invitation link to user to join a group when we submit a from using php so can someone please suggest me something..
Thanks in advance.

A: Use a SMS API to send message to phone number submitted by user. Use the whatsapp group chat link in the SMS messsage body. There are several SMS API's available.


text:
Q: React.js Passport Authentication unable to get req.user from client I am trying to authenticate a user through some API configured with passportjs. When I run the authentication request I get the redirect to the success route, but I can't get req.user. I tried through Postman and it works. I don't know what I'm forgetting. Could anyone help me?
This is my success route:
app.get("/success", async (req, res) => {
    if (req.user){
        return res.status(200).json({
            user: req.user,
            message: "Logged"
        });
    }
    else {
        return res.status(401).json({
            message: "User authentication failed"
        });
    }
});

This is my react code:
const handleSubmit = (e) => {
        e.preventDefault();
        fetch("http://127.0.0.1:3001/login", {
            method:"POST",
            headers: {
                "Content-Type": "application/json",
                "Accept": "application/json",
            },
            redirect: "follow",
            body: JSON.stringify({email: email, password: password})
        }).then(resp => {
            return resp.json();
        }).then(data => console.log(data))
    }

A: While you are calling the success/ route you need to add the authorization header along with the fetch request. We need to add the Basic jwt | authentication token as the authorization key
const response = await fetch(apiURL, {
        method: 'GET',
        headers: {
            'Content-type': 'application/json',
            'Authorization': `Bearer ${token}`,
            // add the basic jwt | drf token for Authorization Key
        },
        body: JSON.stringify(yourNewData)
    })


text:
Q: How do I show hidden background processes waiting to close? When I shut down my computer, a few moments later Windows opens a window waiting for a background program that needs to close.
But it doesn't tell me what the background process is, unlike XP. It's just empty, like the picture in the linked question:

How do I force Explorer/Task Host Window to show me what the pending background processes are? Is there a registry key for this option?

A: There is no way to see the background processes. This is just a limitation of Explorer/DWM.

A: There is a Registry hack to allow the user to see the Verbose Information messages in Windows 7 in Shutdown, etc.
Here is a link with information on how to do this:
http://tutorials.viktorbabjak.eu/681/force-windows-7-to-display-verbose-information-during-startup-and-shutdown/
The article is pretty long, so I will leave it up the questioner to go to the link and get the information, rather than paste a bunch of things here.
I did this on one of my machines some time back, and it worked well; delivering some useful information.


text:
Q: Why won't json_encode encode this particular array but encodes other arrays with same structure? I made an API that encodes data from a table to an array then to json.
 <?php
header('Content-type: application/json');
header("Access-Control-Allow-Origin: *");

...(connection to db)... :p

        $query = "SELECT * FROM gdb.".$_GET['tb'];
        $result = mysqli_query($conn,$query);

$posts =array();

while ($row = mysqli_fetch_assoc($result))
{

    $posts[] = array('ONE'=>$row);

}

$all = array('ALL'=>$posts);
echo json_encode($all);//($posts);
mysqli_close($conn);
?>

it seems to work fine with other tables but with this particular table, json_encode doesn't seem t work..
This is the array from the table it won't encode to json:
array(1) {
  ["ALL"]=>
  array(61) {
    [0]=>
    array(1) {
      ["ONE"]=>
      array(12) {
        ["id_product"]=>
        string(1) "2"
        ["id_shop"]=>
        string(1) "1"
        ["id_lang"]=>
        string(1) "1"
        ["description"]=>
        string(72) "
 BUY 5-KILOS  RICE FREE SARDINES 155G.SAVE 10.00
"
        ["description_short"]=>
        string(0) ""
        ["link_rewrite"]=>
        string(20) "5-kilos-rice"
        ["meta_description"]=>
        string(0) ""
        ["meta_keywords"]=>
        string(0) ""
        ["meta_title"]=>
        string(0) ""
        ["name"]=>
        string(40) "5-KILOS RICE FREE SARDINES"
        ["available_now"]=>
        string(0) ""
        ["available_later"]=>
        string(0) ""
      }
    }
    [1]=>
    array(1) {
      ["ONE"]=>
      array(12) {
        ["id_product"]=>
        string(1) "3"
        ["id_shop"]=>
        string(1) "1"
        ["id_lang"]=>
        string(1) "1"
        ["description"]=>
        string(78) "
BUY 10-KILOS RICE FREE SARDINES RED 155G.SAVE 20.00
"
        ["description_short"]=>
        string(0) ""
        ["link_rewrite"]=>
        string(21) "10-kilos-rice"
        ["meta_description"]=>
        string(0) ""
        ["meta_keywords"]=>
        string(0) ""
        ["meta_title"]=>
        string(0) ""
        ["name"]=>
        string(41) "10-KILOS RICE FREE SARDINES"
        ["available_now"]=>
        string(0) ""
        ["available_later"]=>
        string(0) ""
      }
    }
}}

The arrays from the ones that my code were able to encode to json have the same structure. Just different number of fields and content so I dunno why with this particular array, it wouldn't work.
I figured. Maybe some of the description strings(did not include all in my sample) have quotes, doublequotes, slashes and that's why it can't encode to json so i did this in the while loop:
$posts[] =  array('ONE'=>array_map("addslashes",$row));

instead of this:
$posts[] = array('ONE'=>$row);

but it still doesn't encode to json. Did i use array_map wrong?? or is there another reason why it won't encode to json?

A: I just needed to add this
mysqli_set_charset($conn,"utf8");

before mysqli_select_db() after all :B


text:
Q: Finding the nth value of the Recaman sequence using a lambda expression I am studying the stream API and I have some questions. I will be very grateful if you can help.
My code 1:
public long recaman(long n) {
    HashSet<Long> s = new HashSet<>();
    s.add(0L);
    long prev = 0;
    for (int i = 1; i < n; i++) {
        long curr = prev - i;
        if (curr < 0 || s.contains(curr)) {
            curr = prev + i;
        }
        s.add(curr);
        prev = curr;
    }
    return prev;
}

My code 2:
public int recaman(int n) {
    int[] seq = new int[n];
    boolean[] check = new boolean[10 * n];

    seq[0] = 0;
    check[0] = true;
    for (int k = 1; k < n; k++)
    {
        int minusVal = seq[k - 1] - k;
        int plusVal = seq[k - 1] + k;
        if ((minusVal > 0) && (!check[minusVal]))
        {
            seq[k] = minusVal;
            check[minusVal] = true;
        } else
        {
            seq[k] = plusVal;
            check[plusVal] = true;
        }
    }
    return seq[n - 1];
}

How do I rewrite the code using a lambda expression (or use functional programming paradigm)?

A: In both functions you are iterating over an int variable (i in the first one, k in the second)
Your loops use the iteration variable explicitly (in long curr = prev - i; and in int minusVal = seq[k - 1] - k;). As such it is not a "pure" iteration variable anymore, but it's both an iteration variable and data.
One of the goals of Streams is to abstract iteration, and do away with iteration variables. In a lambda function, the position of an element in the stream is not available. Thus, what you ask for is impossible with the Java Stream API.
If you still want to use functional programming paradigm to solve this problem, you should use recursion (ie. Streams are not the right tool for your job, recursion is).


text:
Q: Percentage does not work with FlatList render item when horizontal is true I would like to use the screen's width on the render item of the horizontal FlatList. However, it does not work as expected. When the horizontal is false, the percentage value works. But when the horizontal is true, the percentage value does not work.
class App extends React.Component {
  _renderItem = ({ item }) => {
    return (
      <View
        style={{
          width: '100%',
          height: 100,
        }}>
        <Text>{item.key}</Text>
      </View>
    );
  };

  render() {
    return (
      <View style={styles.container}>
        <FlatList
          data={[{ key: 1 }, { key: 2 }, { key: 3 }]}
          renderItem={this._renderItem}
          horizontal={true}
        />
      </View>
    );
  }
}

Snack link when the FlatList is horizontal
Snack link when the FlatList is NOT horizontal

A: I think I remember someone mentionning something like that. Using Dimensions works here. See here: https://snack.expo.io/H1-wnC5HM
I rather solve it with flex or percentage but well.


text:
Q: Owl Carousel 2 how to display all slide titles on every slide I am working on a project for a client and he wants to have an Owl Carousel that displays all the slide titles on every slide and they are clickable.  To be more clear I have added a picture. Does anyone have a clue how to solve this thing.
Here is the closest I got
 var owl = $('.owl-carousel');
 owl.owlCarousel({
 loop: true,
 autoplay: true,
 items: 1,
 });

 owl.on('translated.owl.carousel', function(event) {
 var title = $(this).find('.active').find('img').attr('title');
 if(title) $('.titles').html(title);
 });

Slide Title

A: You can use each loop then iterate through each item div and get the img title of all images and add them inside your titles div . After that you can highlight the title according to current image shown in slider inside your owl.on('translated.owl.carousel', .. event .
Demo Code :

$(document).ready(function() {
  //show all title in one place..
  $(".item").each(function(i) {
    //you can manipulate..this html generated according to your need...
    //add `<a>` if needed
    $(".titles ul").append(`<li data-index="${i}">${$(this).find("img").attr("title")}</li>`)
  })
  $(".titles ul li:first").addClass("active");
  var owl = $('.owl-carousel');
  owl.owlCarousel({
    loop: true,
    autoplay: true,
    items: 1,
  });

  owl.on('translated.owl.carousel', function(event) {
    //get data-index..
    var index_ = $(this).find('.active').find("img").data("index")
    $(".titles li").removeClass("active")
    //for making active
    $("li[data-index=" + index_ + "]").addClass("active");

  });
})
.titles ul li {
  border: 1px solid black;
  display: inline-block;
  height: 25px;
  list-style-type: none;
  text-align: center;
  padding: 5px;
  width: 100px;
}

.active {
  background: yellow;
}

img {
  height: 300px;
  width: 60px;
}

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.1.3/assets/owl.carousel.min.css">


text:
Q: HMAC SHA512 output varies in Perl I have observed that the output of HMAC SHA512 for a given data and a key varies each time I execute the script.
first, I take an example of a script where the output does not vary:
#! /usr/bin/perl

use Digest::SHA qw(hmac_sha512_hex);
use warnings;

$data="test";
$key="20202020";

print hmac_sha512_hex($data,$key),"\n";

I run this script two times and get the same output:
perl test.pl
457a1ff378f11880defaa91675de4633d1f1e69712b5dccd2f86612224b825b4461a9215a37cce53
8e7f5de43a6900867667b9361af38df32fc58e54d7ce9a02

perl test.pl
457a1ff378f11880defaa91675de4633d1f1e69712b5dccd2f86612224b825b4461a9215a37cce53
8e7f5de43a6900867667b9361af38df32fc58e54d7ce9a02

now I modify the data variable in the script as follows:
#! /usr/bin/perl

use Digest::SHA qw(hmac_sha512_hex);
use warnings;

$data={'method' => 'test', 'value' => 21};
$key="20202020";

print hmac_sha512_hex($data,$key),"\n";

now the output is different each time I run the script:
perl test.pl
cb1a40ba7a7f52da39dc0a3f130399dfbecb5249946057fd19887b72a58701f28452f6e663153bb6
85a4b86f9d427de4af5904801e11cb6fcbc272344605c2a9

perl test.pl
73dd1678a4e7f29f8032a65cbe979248b3e41cd6ed7aa81e5b214b8b6232af1e7a6683412b8532b7
187313d2c2a96c7e5009a9362690f355028b56ca319825e4

how do I correct this?

A: The data that you pass into hmac_sha512_hex is interpreted as a string. You are passing it as a reference to a hash. You can verify this by printing the value of $data before passing it into the function.
Your reference is just a unique identifier for your hash. Perl doesn't guarantee that you'll get the same hash reference for the same data in different runs of your program. You are therefore passing different values into hmac_sha512_hex which will obviously give you different output.
If you want your output to be the same, then you need to find a way to pass the same string into the function each time. One simple approach might be to use the string that you get back from Data::Dumper's Dumper function.
Update: If you use Data::Dumper, then you'll need to set $Data::Dumper::Sortkeys to a true value.

A: When you pass $data to the hmac_sha512_hex function you are passing the address of the variable which will change every time you run the program. You will have to look into serializing your hash into a string in a consistent way.


text:
Q: How do I switch default directory for Apache? I'm trying to modify the default directory for Apache from /var/www to /var/www/public_html, and I can't find any resources specifically on how to do this. The httpd.conf and apache.conf files are empty. How would I go about this?

A: In some apache builds, the default site is defined, not in the httpd.conf file, but in /etc/apache2/sites-available/default.  Take a look there.
And this question over at SO should get you moving in the right direction.  The answer over there offers a basic virtualhost definition as well as a couple other things necessary to configure a site defined in sites-available
<VirtualHost *:80>
    ServerName www.mywebserver.com
    DocumentRoot /home/www/public_html/
    <Directory /home/www/public_html/>
        Options None
        Order deny,allow
        Allow from all
    </Directory>
</VirtualHost>


text:
Q: Jackson UnrecognizedPropertyException I am trying to convert JsonString to Java object.
Json object
{
"action": "added",
"data": {
    "Quote": {
        "TotalDiscountsAmount": 0,
        "Id": "test123"
    },
    "Owner": {
        "Username": "00000000",
        "Id": "00000000"
    },
    "Discount_Amount__c": 0,
    "Base_List_Price__c": 574.88,
    "TotalList": 574.88,
    "Id": "000000",
    "ExtendedTotalList": 574.88,
    "BaseListPrice": 474.88
}
}

My POJOs:
AddtocartJson.java
package com.product.json;

import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("org.jsonschema2pojo")
@JsonPropertyOrder({
  "action",
  "data"
})
public class AddToCartJson {
    @JsonProperty("action")
    private String action;
    @JsonProperty("data")
    private Data data;

    @JsonProperty("action")
    public String getAction() {
        return action;
    }

    @JsonProperty("action")
    public void setAction(String action) {
        this.action = action;
    }

    @JsonProperty("data")
    public Data getData() {
        return data;
    }

    @JsonProperty("data")
    public void setData(Data data) {
        this.data = data;
    }
}

Data.java
package com.product.json;

import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("org.jsonschema2pojo")
@JsonPropertyOrder({
  "Quote",
  "Owner",
  "Discount_Amount__c",
  "Base_List_Price__c",
  "TotalList",
  "Id",
  "ExtendedTotalList",
  "BaseListPrice"
})
public class Data {

    @JsonProperty("Quote")
    private com.product.json.Quote Quote;
    @JsonProperty("Owner")
    private com.product.json.Owner Owner;
    @JsonProperty("Discount_Amount__c")
    private Integer DiscountAmountC;
    @JsonProperty("Base_List_Price__c")
    private Double BaseListPriceC;
    @JsonProperty("TotalList")
    private Double TotalList;
    @JsonProperty("Id")
    private String Id;
    @JsonProperty("ExtendedTotalList")
    private Double ExtendedTotalList;
    @JsonProperty("BaseListPrice")
    private Double BaseListPrice;

    @JsonProperty("Quote")
    public com.product.json.Quote getQuote() {
        return Quote;
    }

    @JsonProperty("Quote")
    public void setQuote(com.product.json.Quote Quote) {
        this.Quote = Quote;
    }

    @JsonProperty("Owner")
    public com.product.json.Owner getOwner() {
        return Owner;
    }

    @JsonProperty("Owner")
    public void setOwner(com.product.json.Owner Owner) {
        this.Owner = Owner;
    }

    @JsonProperty("Discount_Amount__c")
    public Integer getDiscountAmountC() {
        return DiscountAmountC;
    }

    @JsonProperty("Discount_Amount__c")
    public void setDiscountAmountC(Integer DiscountAmountC) {
        this.DiscountAmountC = DiscountAmountC;
    }

    @JsonProperty("Base_List_Price__c")
    public Double getBaseListPriceC() {
        return BaseListPriceC;
    }

    @JsonProperty("Base_List_Price__c")
    public void setBaseListPriceC(Double BaseListPriceC) {
        this.BaseListPriceC = BaseListPriceC;
    }

    @JsonProperty("TotalList")
    public Double getTotalList() {
        return TotalList;
    }

    @JsonProperty("TotalList")
    public void setTotalList(Double TotalList) {
        this.TotalList = TotalList;
    }

    @JsonProperty("Id")
    public String getId() {
        return Id;
    }

    @JsonProperty("Id")
    public void setId(String Id) {
        this.Id = Id;
    }

    @JsonProperty("ExtendedTotalList")
    public Double getExtendedTotalList() {
        return ExtendedTotalList;
    }

    @JsonProperty("ExtendedTotalList")
    public void setExtendedTotalList(Double ExtendedTotalList) {
        this.ExtendedTotalList = ExtendedTotalList;
    }

    @JsonProperty("BaseListPrice")
    public Double getBaseListPrice() {
        return BaseListPrice;
    }

    @JsonProperty("BaseListPrice")
    public void setBaseListPrice(Double BaseListPrice) {
        this.BaseListPrice = BaseListPrice;
    }
}

Quote.java
package com.product.json;

import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("org.jsonschema2pojo")
@JsonPropertyOrder({
  "TotalDiscountsAmount",
  "Id"
})
public class Quote {
    @JsonProperty("TotalDiscountsAmount")
    private Integer TotalDiscountsAmount;
    @JsonProperty("Id")
    private String Id;

    @JsonProperty("TotalDiscountsAmount")
    public Integer getTotalDiscountsAmount() {
        return TotalDiscountsAmount;
    }

    @JsonProperty("TotalDiscountsAmount")
    public void setTotalDiscountsAmount(Integer TotalDiscountsAmount) {
        this.TotalDiscountsAmount = TotalDiscountsAmount;
    }

    @JsonProperty("Id")
    public String getId() {
        return Id;
    }

    @JsonProperty("Id")
    public void setId(String Id) {
        this.Id = Id;
    }
}

When I try to convert JSON to Java class using the mapper, it's throwing an UnrecognizedPropertyException. Seems likes even though I have a Quote object somehow mapper is not able to recognize the object.

org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "Quote" (Class com.product.json.Data), not marked as ignorable
      at [Source: java.io.StringReader@11547748; line: 1, column: 36] (through reference chain: com.product.json.AddToCartJson["data"]->       com.product.json.Data["Quote"])
          at org.codehaus.jackson.map.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:53)
          at org.codehaus.jackson.map.deser.StdDeserializationContext.unknownFieldException(StdDeserializationContext.java:267)
          at org.codehaus.jackson.map.deser.std.StdDeserializer.reportUnknownProperty(StdDeserializer.java:673)

How can I fix this?

A: The problem here is that OP mixes two different Jackson versions:

*

*1.9 from org.codehaus (org.codehaus.jackson.map.exc.UnrecognizedPropertyException shows that)

*2.x from com.fasterxml (visible in the imports import com.fasterxml.jackson.annotation.)

As pointed out by sam in the comments, OP should only use one version. Either use 2.x for deserialization or use annotations from the old 1.9 version.
But it is recommended to use the newest version from com.fasterxml, instead of the old one.

A: you might want to ignore undefined properties by using Jackson's class-level annotation:
@JsonIgnoreProperties


text:
Q: How to test child component render after api call on react testing library I want to test the child component render after click a display detail button. When click the button, it will call api getPokemonDetail to get the Pokemon detail and then change the PokemonDetail state.
The app is running well. But on my unit test, I can only get the Loading text after button click. I used axios-mock-adapter to mock axios request. If I disable the axios mock, it's running correct. Looks like the axios mock is not working after button click. How should I fix it? The below is my code.
Parent Component:
const getPokemonDetail = async (pokemonName) => {
    const queryName = pokemonName ?? "ditto"
    try {
        const result = await axios.get(`https://pokeapi.co/api/v2/pokemon/${queryName}`)
        console.log(result.data)
        const { name, id, weight } = result.data
        return Promise.resolve({ name, id, weight })
    } catch (error) {
        return undefined
    }
}
const ParentComponent = (props) => {
    const { pokemonName } = props
    const [pokemonDetail, setPokemonDetail] = useState({
        detail: null,
        loading: true,
    })
    const retrieveDisplayStatus = async () => {
        const getPokemonDetailResult = await getPokemonDetail(pokemonName)
        if (getPokemonDetailResult) {
            setPokemonDetail({
                detail: getPokemonDetailResult,
                loading: false,
            })
        }
    }
    const { showDetails, toggleDetails } = useToggleDetails(retrieveDisplayStatus)
    return (
        <>

Display Pokemon Detail

            <button onClick={toggleDetails}>Display Detail</button>
            <>
                {showDetails ? (
                    <>{
                        pokemonDetail.loading ?

Loading...
 :
                          <ChildComponent pokemonDetail={pokemonDetail.detail} />
                      }</>
                ) : null}
            </>
        </>
    )
}

Child Component:
const ChildComponent = (props) => {
    const { pokemonDetail } = props
    const { id, name, weight } = pokemonDetail
    return (
        <>

ChildComponent

id: {id}

name: {name}

weight: {weight}

        </>
    )
}
export default ChildComponent

On the Parent component test:
import { render, screen } from "@testing-library/react"
import ParentComponent from "../ParentComponent"
import userEvent from "@testing-library/user-event"
import axios from "axios"
import MockAdapter from "axios-mock-adapter"

describe("test", () => {
    let mock
    beforeAll(() => {
        mock = new MockAdapter(axios)
    })
    afterEach(() => {
        mock.reset()
    })
    test("Render child component after api call", async () => {
        render(<ParentComponent />)
        const heading = screen.getByText("Display Pokemon Detail")
        expect(heading).toBeInTheDocument()
        const toggleButton = screen.getByRole("button", { name: /display/i })
        expect(toggleButton).toBeInTheDocument()
        userEvent.click(toggleButton)
        const loadingText = await screen.findByText(new RegExp("Loading", "i"))
        expect(loadingText).toBeInTheDocument()
        // the below is not working, looks like the axios mock not working
        mock.onGet(`https://pokeapi.co/api/v2/pokemon/ditto`).reply(200, { name: "ditto", id: 132, weight: 40 })
        const childHeading = await screen.findByText("ChildComponent")
        expect(childHeading).toBeInTheDocument()
        const id = await screen.findByTestId("testId")
        expect(id).toHaveTextContent("132")
    })
})


text:
Q: Marshal returns empty json of my struct I'm working on a code that scan a repertory into a struct in order to export it to json.
Currently, my code scans finely a repertory with the ScanDir function, but when I try to Marshal my struct it only returns {}.
// file's struct
type Fic struct {
    nom     string    `json:"fileName"`
    lon     int64     `json:"size"`
    tim     time.Time `json:"lastFileUpdate"`
    md5hash []byte    `json:"md5"`
}

// folder's struct
type Fol struct {
    subFol []Fol     `json:"listFolders"`
    files  []Fic     `json:"listFiles"`
    nom    string    `json:"folderName"`
    tim    time.Time `json:"lastFolderUpdate"`
}

func main() {
    var root Fol
    err := ScanDir("./folder", &root)   // scan a folder and fill my struct
    check(err)
    b, err := json.Marshal(root)
    check(err)
    os.Stdout.Write(b)
}

func check(err error) {
if err != nil {
    fmt.Fprintf(os.Stderr, "Fatal error : %s", err.Error())
    os.Exit(1)
}

A: In order to marshal and unmarshal json, fields/property of struct needs to be public. To make the field/property of struct public it should start with Upper Case. In your all the fields are in lower case.
type Fic struct {
    Nom     string    `json:"fileName"`
    Lon     int64     `json:"size"`
    Tim     time.Time `json:"lastFileUpdate"`
    Md5hash []byte    `json:"md5"`
}

// folder's struct
type Fol struct {
    SubFol []Fol     `json:"listFolders"`
    Files  []Fic     `json:"listFiles"`
    Nom    string    `json:"folderName"`
    Tim    time.Time `json:"lastFolderUpdate"`
}


text:
Q: Can't install PyAudio on PyCharm So I've tied to download PyAudio on PyCharm. When it's downloading I get an error: "Error occurred when installing package 'PyAudio'. Details..." When I click "Details" I get:
Collecting PyAudio
 Using cached PyAudio-0.2.11.tar.gz (37 kB)
 Preparing metadata (setup.py): started
 Preparing metadata (setup.py): finished with status 'done'
Building wheels for collected packages: PyAudio
 Building wheel for PyAudio (setup.py): started
 Building wheel for PyAudio (setup.py): finished with status 'error'
 Running setup.py clean for PyAudio
Failed to build PyAudio
Installing collected packages: PyAudio
 Running setup.py install for PyAudio: started
 Running setup.py install for PyAudio: finished with status 'error'

 error: subprocess-exited-with-error

 python setup.py bdist_wheel did not run successfully.
 exit code: 1

 [14 lines of output]
 running bdist_wheel
 running build
 running build_py
 creating build
 creating build\lib.win-amd64-3.10
 copying src\pyaudio.py -> build\lib.win-amd64-3.10
 warning: build_py: byte-compiling is disabled, skipping.

 running build_ext
 creating build\temp.win-amd64-3.10
 creating build\temp.win-amd64-3.10\Release
 creating build\temp.win-amd64-3.10\Release\src
 cl.exe /c /nologo /O2 /W3 /GL /DNDEBUG /MD -DMS_WIN64=1 -IC:\Users\Pirnar\PycharmProjects\pythonProject\venv\include -IC:\Users\Pirnar\AppData\Local\Programs\Python\Python310\include -IC:\Users\Pirnar\AppData\Local\Programs\Python\Python310\Include /Tcsrc/_portaudiomodule.c /Fobuild\temp.win-amd64-3.10\Release\src/_portaudiomodule.obj
 error: command 'cl.exe' failed: None
 [end of output]

 note: This error originates from a subprocess, and is likely not a problem with pip.
 ERROR: Failed building wheel for PyAudio
 error: subprocess-exited-with-error

 Running setup.py install for PyAudio did not run successfully.
 exit code: 1

 [16 lines of output]
 running install
 C:\Users\Pirnar\PycharmProjects\pythonProject\venv\lib\site-packages\setuptools\command\install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
   warnings.warn(
 running build
 running build_py
 creating build
 creating build\lib.win-amd64-3.10
 copying src\pyaudio.py -> build\lib.win-amd64-3.10
 warning: build_py: byte-compiling is disabled, skipping.

 running build_ext
 creating build\temp.win-amd64-3.10
 creating build\temp.win-amd64-3.10\Release
 creating build\temp.win-amd64-3.10\Release\src
 cl.exe /c /nologo /O2 /W3 /GL /DNDEBUG /MD -DMS_WIN64=1 -IC:\Users\Pirnar\PycharmProjects\pythonProject\venv\include -IC:\Users\Pirnar\AppData\Local\Programs\Python\Python310\include -IC:\Users\Pirnar\AppData\Local\Programs\Python\Python310\Include /Tcsrc/_portaudiomodule.c /Fobuild\temp.win-amd64-3.10\Release\src/_portaudiomodule.obj
 error: command 'cl.exe' failed: None
 [end of output]

 note: This error originates from a subprocess, and is likely not a problem with pip.
error: legacy-install-failure

Encountered error while trying to install package.

PyAudio

note: This is an issue with the package mentioned above, not pip.
hint: See above for output from the failure.

I have tried downloadin it by typing this in to terminal
pip install pipwin
pipwin install pyaudio

Also I have downloaded C++ Build tools.
I am using windows 10 pro, python 3.10 and pycharm community edition 2022.1
What do I do?

A: Check out this link. You will find a solution to your problem. You have too prepare your environment before installation.

A: This is a well-known problem and the solution is already in the official docs


text:
Q: Salto de Linea en JSON.NET en vb.net estoy creando una clase persona y el objeto resultante tiene los campos Id, Nombre, Edad. Luego usando JSON.NET convierto ese objeto en un archivo .json y lo guardo en el disco duro pero al abrirlo todo queda en una sola lineea asi:
{"Id":4,"Nombre":"Juan Perez","Edad":18}

Yo quisiera que aparezca asi
{
 "Id":4,
 "Nombre":"Juan Perez",
 "Edad":18
}

Es decir con salto de lineas...necesito ayuda con esto...gracias

A: Aqui te va un ejemplo:
clase:
public class Account
{
    public string Email { get; set; }
    public bool Active { get; set; }
    public DateTime CreatedDate { get; set; }
    public IList<string> Roles { get; set; }
}

Utilizando en el "formateo" adecuado:
Account account = new Account
{
    Email = "james@example.com",
    Active = true,
    CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc),
    Roles = new List<string>
    {
        "User",
        "Admin"
    }
};

string json = JsonConvert.SerializeObject(account, Formatting.Indented);
// {
//   "Email": "james@example.com",
//   "Active": true,
//   "CreatedDate": "2013-01-20T00:00:00Z",
//   "Roles": [
//     "User",
//     "Admin"
//   ]
// }

Console.WriteLine(json);

Extraído de la documentación oficial: https://www.newtonsoft.com/json/help/html/SerializeObject.htm


text:
Q: How to I get the length or size or number of fields in a form in a django template? I would like to write a loop like this, so that I can spread the form fields out in a table. :
{% load widget_tweaks %}
{% load mathfilters %}
{% load get_range %}

{% for k in form|length|div:5|floatformat|add:1|get_range %}

        {% for field in form %}
        {% if forloop.counter >= k|mul:5 and forloop.counter <= k|mul:5|add:4 %}
            {{ field.label_tag }}{{ field.errors }}
        {% endif %}
        {% endfor %}

        {% for field in form %}
        {% if forloop.counter >= k|mul:5 and forloop.counter <= k|mul:5|add:4 %}
            {{ field|add_class:"span4" }}
        {% endif %}
        {% endfor %}

{% endfor %}

This doesn't work, but because the code above fails on form|length. In order for this to work, I need to get, in a template, the number of fields in a form. Does anyone know how to do this? I've searched all over but can't find anything. The following do NOT work:
form.len
form.length
form|length

Thanks!

A: I'm really not sure what you are looking for, but it sounds like this:
{% for field in form %}

        {% if forloop.counter0|divisibleby:5 %}
            {{ field.label_tag }}{{ field.errors }}
        {% else %}
            {{ field.label_tag }}{{ field.errors }}
        {% endif %}

{% endfor%}
{% for field in form %}

        {% if forloop.counter0|divisibleby:5 %}
            {{ field|add_class:"span4" }}
        {% else %}
            {{ field }}

{% endfor %}

A: I dont like this code, but it was my first idea.
{% for field in form %}

    {% if forloop.last %}
        {{ forloop.counter }}
    {% endif %}

{% enfor %}

A: form.fields I believe.
{% for field_name in form.fields %}

A: thanks for your suggestions - they helped! Here is what finally worked for me:
{% for field in form %}
    {% if forloop.counter0|divisibleby:5 %}

        {% for field in form %}
            {% if forloop.counter0 >= forloop.parentloop.counter0 and forloop.counter0 <= forloop.parentloop.counter0|add:4 %}
                {{ field.label_tag }}{{ field.errors }}
            {% endif %}
        {% endfor %}

        {% for field in form %}
            {% if forloop.counter0 >= forloop.parentloop.counter0 and forloop.counter0 <= forloop.parentloop.counter0|add:4 %}
                {{ field }}
            {% endif %}
        {% endfor %}

    {% endif %}
{% endfor %}


text:
Q: Log4Net works on VisualStudio Debug/Release, but not after deployment In order to make more complex logs, I've decided to use the Log4Net for my WPF desktop app. It works perfectly, creating both 'Debug' messages at the 'Output' and writes to a file all the logs...
BUT if I deploy it/install it (using visual studio's wizard to create a .MSI setup) it stops working. I can't find any file on the folder or anywhere on the computer related to it.
I'm using Caliburn.Micro to organize my code. And in order to have the logs, I 'centralized' it by using a public static class by the name of "Logging.cs".
The code inside "Initialize()" was put right now as a way to try out, but it doesn't seem to be doing anything.
public static class Logging
{

    //Declaration of the logger
    /// <summary>
    /// Logger for the Logging manager.
    /// </summary>
    private static log4net.ILog Logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    public static void Initialize()
    {
        log4net.Config.XmlConfigurator.Configure();
    }
    /// <summary>
    /// Creates a log in Fatal level accompanied by an expection
    /// </summary>
    /// <param name="message">The message to be logged</param>
    /// <param name="error">Exception thrown along with the log</param>
    /// <param name="senderType">From where the log comes from</param>
    public static void Fatal(string message, Exception error, Type senderType)
    {
        //Defines 'type' in the log.
        Logger = log4net.LogManager.GetLogger(senderType);
        Logger.Fatal(message, error);
    }
    /// <summary>
    /// Creates a log in Fatal level
    /// </summary>
    /// <param name="message">The message to be logged</param>
    /// <param name="senderType">From where the log comes from</param>
    public static void Fatal(string message, Type senderType)
    {
        //Defines 'type' in the log.
        Logger = log4net.LogManager.GetLogger(senderType);
        Logger.Fatal(message);
    }

    /// <summary>
    /// Creates a log in Error level accompanied by an expection
    /// </summary>
    /// <param name="message">The message to be logged</param>
    /// <param name="error">Exception thrown along with the log</param>
    /// <param name="senderType">From where the log comes from</param>
    public static void Error(string message, Exception error, Type senderType)
    {
        //Defines 'type' in the log.
        MessageBox.Show(error.ToString());
        Logger = log4net.LogManager.GetLogger(senderType);
        Logger.Error(message, error);
    }
    /// <summary>
    /// Creates a log in Error level
    /// </summary>
    /// <param name="message">The message to be logged</param>
    /// <param name="senderType">From where the log comes from</param>
    public static void Error(string message, Type senderType)
    {
        //Defines 'type' in the log.
        Logger = log4net.LogManager.GetLogger(senderType);
        Logger.Error(message);
    }

    /// <summary>
    /// Creates a log in Warn level accompanied by an expection
    /// </summary>
    /// <param name="message">The message to be logged</param>
    /// <param name="error">Exception thrown along with the log</param>
    /// <param name="senderType">From where the log comes from</param>
    public static void Warn(string message, Exception error, Type senderType)
    {
        //Defines 'type' in the log.
        Logger = log4net.LogManager.GetLogger(senderType);
        Logger.Warn(message, error);
    }
    /// <summary>
    /// Creates a log in Warn level
    /// </summary>
    /// <param name="message">The message to be logged</param>
    /// <param name="senderType">From where the log comes from</param>
    public static void Warn(string message, Type senderType)
    {
        //Defines 'type' in the log.
        Logger = log4net.LogManager.GetLogger(senderType);
        Logger.Warn(message);

    }

    /// <summary>
    /// Creates a log in Info level accompanied by an expection
    /// </summary>
    /// <param name="message">The message to be logged</param>
    /// <param name="error">Exception thrown along with the log</param>
    /// <param name="senderType">From where the log comes from</param>
    public static void Info(string message, Exception error, Type senderType)
    {
        //Defines 'type' in the log.
        Logger = log4net.LogManager.GetLogger(senderType);
        Logger.Info(message, error);
    }
    /// <summary>
    /// Creates a log in Info level
    /// </summary>
    /// <param name="message">The message to be logged</param>
    /// <param name="senderType">From where the log comes from</param>
    public static void Info(string message, Type senderType)
    {
        //Defines 'type' in the log.
        Logger = log4net.LogManager.GetLogger(senderType);
        Logger.Info(message);
    }
    /// <summary>
    /// Creates a log in Debug level accompanied by an expection
    /// </summary>
    /// <param name="message">The message to be logged</param>
    /// <param name="error">Exception thrown along with the log</param>
    /// <param name="senderType">From where the log comes from</param>
    public static void Debug(string message, Exception error, Type senderType)
    {
        //Defines 'type' in the log.
        Logger = log4net.LogManager.GetLogger(senderType);
        Logger.Debug(message, error);
    }
    /// <summary>
    /// Creates a log in Debug level
    /// </summary>
    /// <param name="message">The message to be logged</param>
    /// <param name="senderType">From where the log comes from</param>
    public static void Debug(string message, Type senderType)
    {
        //Defines 'type' in the log.
        Logger = log4net.LogManager.GetLogger(senderType);
        Logger.Debug(message);
    }
    /// <summary>
    /// Log created in Debug level containing not only a log message but also an object to be serialized and logged.
    /// </summary>
    /// <param name="message">The message to be logged (should be description of object)</param>
    /// <param name="obj">Object to be displayed</param>
    /// <param name="senderType">From where the log comes from</param>
    public static void ShowObject(string message, object obj, Type senderType)
    {
        //Defines 'type' in the log.
        Logger = log4net.LogManager.GetLogger(senderType);
        Logger.Debug(message + "\n<object>" + JsonConvert.SerializeObject(obj) + "</object>\n");
    }
}

Also, here is my log4net config file:
    <log4net>
    <root>
      <level value="ALL" />
      <appender-ref ref="console" />
      <appender-ref ref="file" />
    </root>
    <appender name="console" type="log4net.Appender.ColoredConsoleAppender">
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date %level %logger - [%message] // %exception%newline" />
      </layout>
    </appender>
    <appender name="file" type="log4net.Appender.RollingFileAppender">
      <file type="log4net.Util.PatternString" value="DesktopApp.log" />
      <appendToFile value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="5" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %level %logger - [%message] // %exception%newline" />
      </layout>
    </appender>
<appender name="FileAppender" type="log4net.Appender.FileAppender">
    <file value="log-file.txt" />
    <appendToFile value="true" />
    <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
    </layout>
</appender>
  </log4net>

And at the AssemblyInfo.cs, I've merely inserted this at the end:
[assembly: log4net.Config.XmlConfigurator(Watch = true,ConfigFile ="log4net.config")]

Thank you for your time, please comment if I can add any more details.
P.S.: The software is installed inside the AppData, so no file permission issues should arise, since I am using another framework to automatically update the app.
P.S.2: I used DebugView and in the middle of mostly info that seemed random I've found an error:
[5480] log4net:ERROR Failed to find configuration section 'log4net' in the application's .config file. Check your .config file for the <log4net> and <configSections> elements. The configuration section should look like: <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />

Still haven't tried fixing it, just keeping this question up to date. (Thanks Varun!)

A: I found the issue. I was looking at the wrong place all this time. When I checked the instalation folder, I noticed there was no log4net.config! ... This is why it worked well during debug (because the config was there) but not after deployment!
Sorry for the bother and thank you for all the help.


text:
Q: Using UNION ALL with INNER JOIN I have 3 tables. I have unified two of them using UNION ALL, but I cannot unify the third because there is only one field in common "receipt".
I want to get a output like:
costumerid/ amount  / receipt / saledate /cost
My code right now is:
SELECT t1.costumerid, t1.amount, t1.receipt, t1.saledate
FROM t1
WHERE t1.amount>'100' AND t1.saledate<Date()-180
UNION ALL
SELECT t2.costumerid, t2.amount, t2.receipt, t2.saledate
FROM t2
WHERE t2.amount>'100' AND t2.saledate<Date()-180

Any help?  Thanks in advance!

A: You can create alias for your outputs columns.
SELECT t1.costumerid, t1.amount, t1.receipt, t1.saledate FROM t1 WHERE t1.amount>'100' AND t1.saledate<Date()-180 UNION ALL SELECT t2.costumerid, t2.amount, t2.receipt, t2.saledate FROM t2 WHERE t2.amount>'100' AND t2.saledate<Date()-180 UNION ALL select null as 'costumerid',null as 'amount' t3.receipt , null as 'saledate' from t3

I don't know in which table you want to find the column cost but you just have to follow the logical.


text:
Q: In Gerrit, how can I push arbitrary tags to non-standard locations? I would like to push build tags to a non-standard location on gerrit, mainly to avoid them from showing up as an official tag and also to avoid polluting users with a bunch of build tags.
On old versions of gerrit, I was able to grant myself permissions to create refs and tags in, say, refs/builds/tags/*, and then do
git push origin refs/tags/BUILD-123:refs/builds/tags/BUILD-123

The beauty of the scheme is that this way, the build tags don't pollute ordinary users' git repos, but if someone is interested in the build tags, they can run:
git fetch origin 'refs/builds/tags/*:refs/tags/*'

and then all the build tags appear and become usable as tags.
It seems that on newer versions of gerrit (2.16?) direct push is limited to the standard locations.
It also appears as if one can only push tags of commits which are direct ancestors an existing branch, so if my build does anything unusual (for example rebase to the tip), it fails.
Is this configurable anywhere?

A: It turns out there is no such restriction, you just have to grant yourself all the required permissions, like so:
[access "refs/builds/*"]
    create = <me>
    createSignedTag = <me>
    createTag = <me>
    delete = <me>
    read = <me>

I forgot to give myself read permissions...
The restriction that does exist is where you cannot push a tag that is not for a commit that is an ancestor of an existing known branch. The reason this restriction exists is because access to commits is controlled via ACLs that feature wild carded refs as primary key to permissions. If someone knew a "forbidden" sha and was allowed to push a tag, this scheme can be bypassed.
The trick is to give up on pushing tags and to push branches instead. Branches can be pushed to non-standard locations just like tags, and if someone fetches them into refs/tags, they also act like lightweight tags.


text:
Q: How to pass order ID to Paypal Button? I create an order by my php sdk.
like this
$result = json_decode((string) $response->getBody());

echo $result->id; // id of the created order

and now i have this order id. but ... How to pass order ID to Paypal Button?
like this
`paypal.Buttons({

    // Set up the transaction
    createOrder: function(data, actions) { //I don't need create order,I have created an order
        return actions.order.create({
            purchase_units: [{
                amount: {
                    value: '88.44'
                }
            }]
        });
    },

    // Finalize the transaction
    onApprove: function(data, actions) {
        return actions.order.capture().then(function(orderData) {
            // Successful capture! For demo purposes:
            console.log('Capture result', orderData, JSON.stringify(orderData, null, 2));
            var transaction = orderData.purchase_units[0].payments.captures[0];
            alert('Transaction '+ transaction.status + ': ' + transaction.id + '\n\nSee console for all available details');

            // Replace the above to show a success message within this page, e.g.
            // const element = document.getElementById('paypal-button-container');
            // element.innerHTML = '';
            // element.innerHTML = '
Thank you for your payment!
';
            // Or go to another URL:  actions.redirect('thank_you.html');
        });
    }

}).render('#paypal-button-container');

A: Create two routes on your server, one to create an order (and return the resulting JSON), and one that takes an order id as a parameter and captures it (and returns the JSON result).
Both of these routes should return/output only JSON (no HTML or text).
Pair those two routes with this approval flow: https://developer.paypal.com/demo/checkout/#/pattern/server


text:
Q: R: What is the difference of the Lasso for variable selection between the packages glmnet and hdm For my PhD I use a Lasso approach in R for variable selection. Now, I used the package glmnet and also hdm. What is the difference of the basic lasso estimator for logistic regression in these two packages? I read the docs and also googled a lot but the only hint that I found was this one which was not very helpful for my exact purpose.
The reason for asking is because my models converge if I use glmnet and they sometimes do not converge when I use hdm. That is why I assume that the difference is in the optimization function. Here is a minimal example:
# Delete environment
rm(list = ls())

# Packages
library(glmnet)
#> Loading required package: Matrix
#> Loaded glmnet 4.1-4
library(hdm)

# get data
data = read.table("https://pastebin.com/raw/gmXk0h2P", sep = ",", header = T)

# do the lasso
lasso_hdm = rlassologit(dep ~ ., data = data)
#> Warning: from glmnet C++ code (error code -1); Convergence for 1th lambda value
#> not reached after maxit=100000 iterations; solutions for larger lambdas returned
#> Warning in getcoef(fit, nvars, nx, vnames): an empty model has been returned;
#> probably a convergence issue
lasso_glm = glmnet(as.matrix(data[,!(names(data) %in% c("dep"))]), data$dep, family = "binomial")

Created on 2022-05-31 by the reprex package (v2.0.1)
Additionally, please find my sessionInfo:
sessionInfo()
#> R version 4.2.0 (2022-04-22)
#> Platform: x86_64-pc-linux-gnu (64-bit)
#> Running under: Ubuntu 22.04 LTS
#>
#> Matrix products: default
#> BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.10.0
#> LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.10.0
#>
#> locale:
#>  [1] LC_CTYPE=en_GB.UTF-8       LC_NUMERIC=C
#>  [3] LC_TIME=de_DE.UTF-8        LC_COLLATE=en_GB.UTF-8
#>  [5] LC_MONETARY=de_DE.UTF-8    LC_MESSAGES=en_GB.UTF-8
#>  [7] LC_PAPER=de_DE.UTF-8       LC_NAME=C
#>  [9] LC_ADDRESS=C               LC_TELEPHONE=C
#> [11] LC_MEASUREMENT=de_DE.UTF-8 LC_IDENTIFICATION=C
#>
#> attached base packages:
#> [1] stats     graphics  grDevices utils     datasets  methods   base
#>
#> loaded via a namespace (and not attached):
#>  [1] rstudioapi_0.13   knitr_1.39        magrittr_2.0.3    R.cache_0.15.0
#>  [5] rlang_1.0.2       fastmap_1.1.0     fansi_1.0.3       stringr_1.4.0
#>  [9] styler_1.7.0      highr_0.9         tools_4.2.0       xfun_0.31
#> [13] R.oo_1.24.0       utf8_1.2.2        cli_3.3.0         withr_2.5.0
#> [17] htmltools_0.5.2   ellipsis_0.3.2    yaml_2.3.5        digest_0.6.29
#> [21] tibble_3.1.7      lifecycle_1.0.1   crayon_1.5.1      purrr_0.3.4
#> [25] R.utils_2.11.0    vctrs_0.4.1       fs_1.5.2          glue_1.6.2
#> [29] evaluate_0.15     rmarkdown_2.14    reprex_2.0.1      stringi_1.7.6
#> [33] compiler_4.2.0    pillar_1.7.0      R.methodsS3_1.8.1 pkgconfig_2.0.3

Created on 2022-05-31 by the reprex package (v2.0.1)
In the end I am interested in the theory of both packages and maybe I find a good reason to stick to the glmnet package as this converges.
Thank you so much in advance!


text:
Q: Solving $12n + 2n + 80 \times 2 \times 4.92 = 200n$ for $n$ Can someone please help me with this?
I'm studying chemistry for the medicine exam, and I haven't done math in a long time
$$12n + 2n + 80 \times 2 \times 4.92 = 200n$$
I need to find $n$.
If someone can please explain me how to do it, I would really appreciate it.

A: $12n + 2n + 80 \times 2 \times 4.92 = 200n$
$\Rightarrow 14n + 160 \times 4.92 = 200n$
$\Rightarrow 14n + 787.2 = 200n$
$\Rightarrow 782.2 = 200n - 14n$
$\Rightarrow 782.2 = 186n$
$\Rightarrow 186n = 782.2$
$\Rightarrow n = \dfrac{782.2}{186}$
$\Rightarrow n = 4.23226$

A: You can transpose the left side terms having $n$ to the RHS to get $80 \times 2 \times 4.92 = 186n \implies 4.92 = \dfrac{186n}{160} = \dfrac{93n}{80} \implies 93n = 393.6 = 93n \implies n = \dfrac{393.6}{93} = \dfrac{131.2}{31}$
Hope you get it (as well as what you get from the division).
It's a simple problem, actually...


text: Q: Hypergraph to graph preserving automorphisms Given a hypergraph, is there a general way to turn it into a stantard graph (i.e, one were the edges are just pairs of vertices) preserving the automorphism group? At first I thought you could just exchange every hyperedge by a complete subgraph but this doesn't work. Any ideas?


text:
Q: AspectJ - parse definitions failed - NullPointerException Here's MVCE
https://github.com/yami12376/AspectJ

*

*Add VM arguments to Run/Debug configuration of Junit test, in my case:
-javaagent:C:\aspectjWeaver\spring-instrument-3.0.4.jar
-javaagent:C:\aspectjWeaver\aspectjweaver-1.6.11.jar

*In my case i added this in JAVA build path: \target\classes\META-INF from src/main/resources

*Run Junit test
If you delete aop.xml it's still weaving type org.*
but on the other hand aop.xml should not weave it beacuse it has:
<include within="com.*"/>
Why does it weave something other than com.* ?
Finally i want that MyAspect will be called when running Junit test based on @Around("execution(* *(..))")
As you can see now it is not getting called.
I've made my example based on
https://docs.spring.io/spring/docs/current/spring-framework-reference/html/aop.html#aop-aj-ltw-first-example
When running JUnit test i see this error:
http://wklej.org/id/3066582/
 [AppClassLoader@18b4aac2] warning parse definitions failed -- (NullPointerException) null
null
java.lang.NullPointerException
    at org.aspectj.weaver.loadtime.definition.DocumentParser.resolveEntity(DocumentParser.java:177)
    at org.apache.xerces.util.EntityResolverWrapper.resolveEntity(Unknown Source)
    at org.apache.xerces.impl.XMLEntityManager.resolveEntity(Unknown Source)
    at org.apache.xerces.impl.XMLDocumentScannerImpl$DTDDispatcher.dispatch(Unknown Source)
    at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
    at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
    at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
    at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
    at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
    at org.aspectj.weaver.loadtime.definition.DocumentParser.saxParsing(DocumentParser.java:158)
    at org.aspectj.weaver.loadtime.definition.DocumentParser.parse(DocumentParser.java:123)
    at org.aspectj.weaver.loadtime.ClassLoaderWeavingAdaptor.parseDefinitions(ClassLoaderWeavingAdaptor.java:272)
    at org.aspectj.weaver.loadtime.DefaultWeavingContext.getDefinitions(DefaultWeavingContext.java:130)
    at org.aspectj.weaver.loadtime.ClassLoaderWeavingAdaptor.initialize(ClassLoaderWeavingAdaptor.java:156)
    at org.aspectj.weaver.loadtime.Aj$ExplicitlyInitializedClassLoaderWeavingAdaptor.initialize(Aj.java:340)
    at org.aspectj.weaver.loadtime.Aj$ExplicitlyInitializedClassLoaderWeavingAdaptor.getWeavingAdaptor(Aj.java:345)
    at org.aspectj.weaver.loadtime.Aj$WeaverContainer.getWeaver(Aj.java:319)
    at org.aspectj.weaver.loadtime.Aj.preProcess(Aj.java:113)
    at org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter.transform(ClassPreProcessorAgentAdapter.java:54)
    at sun.instrument.TransformerManager.transform(Unknown Source)
    at sun.instrument.InstrumentationImpl.transform(Unknown Source)
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.access$100(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)

I want to fix this error

A: Well, you have several strange issues and errors in your project:

*

*Obviously your POJO application does not use Spring. So you can get rid of Spring dependencies and also of spring-instrument.jar on your command line. You also do not need core-context.xml.

*Xerces is also not needed as far as I can see.

*If you use aspectjweaver.jar as a dependency, aspectjrt.jar is superfluous because the former is a superset and thus contains the latter.

*In aop.xml there is a package name typo: Please use com.mkyong in the aspect name, not com.mykong. Otherwise the aspect will never be found.

*In your include within tag you should use .. syntax in order to in-/exclude also subpackages.

*Your aspect class is a total mess:

*

*You use nested classes for no apparent reason.

*You use @Around, but JoinPoint instead of ProceedingJoinPoint in the advice signature.

*You use @Around, but never call proceed().

So how about this?
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.mkyong</groupId>
  <artifactId>NumberGenerator</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>NumberGenerator</name>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.8.10</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.0</version>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
    </plugins>
  </build>

</project>

aop.xml:
<?xml version="1.0" encoding="UTF-8"?>
<aspectj>
  <aspects>
    <aspect name="com.mkyong.MyAspect"/>
  </aspects>
  <weaver options="-verbose -showWeaveInfo">
    <include within="com.mkyong..*"/>
    <exclude within="org.jibx*..*"/>
  </weaver>
</aspectj>

Aspect:
package com.mkyong;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class MyAspect {
  @Around("execution(!static * *(..))")
  public Object dontLogDuplicates(ProceedingJoinPoint thisJoinPoint) throws Throwable {
    System.out.println(thisJoinPoint);
    return thisJoinPoint.proceed();
  }
}

Console log:
I see the following when adding -javaagent:/path/to/aspectjweaver.jar to my JUnit run configuration in IntelliJ IDEA:
[AppClassLoader@18b4aac2] info AspectJ Weaver Version 1.8.10 built on Monday Dec 12, 2016 at 19:07:48 GMT
[AppClassLoader@18b4aac2] info register classloader sun.misc.Launcher$AppClassLoader@18b4aac2
[AppClassLoader@18b4aac2] info using configuration /C:/Users/Alexander/Documents/java-src/yami12376-AspectJ/target/classes/META-INF/aop.xml
[AppClassLoader@18b4aac2] info register aspect com.mkyong.MyAspect
[AppClassLoader@18b4aac2] weaveinfo Join point 'method-execution(void com.mkyong.AppTest.testLengthOfTheUniqueKey())' in Type 'com.mkyong.AppTest' (AppTest.java:9) advised by around advice from 'com.mkyong.MyAspect' (MyAspect.java)
execution(void com.mkyong.AppTest.testLengthOfTheUniqueKey())
[AppClassLoader@18b4aac2] weaveinfo Join point 'method-execution(java.lang.String com.mkyong.App.generateUniqueKey())' in Type 'com.mkyong.App' (App.java:12) advised by around advice from 'com.mkyong.MyAspect' (MyAspect.java)
execution(String com.mkyong.App.generateUniqueKey())

But really, you should fix your POM and make sure that aspect weaving is done from there and not manually. It is really ugly like this.
Update: After all the criticism, let me also say one positive thing: You provided a MCVE, thanks for that. With code fragments, questions and answers we would never have found the many bugs in your files. So it was a smart and prudent decision to create the GitHub project. I could easily spot the problems. :-) If everyone did that, I would save a lot of time here.


text:
Q: Вёрстка для перевода в PDF У меня есть задание сверстать страницы, которые в будущем будут переведены в pdf.
Проблема в том, что footer и header должны повторяться на каждой странице. Каждые 320px должна быть новая страница с таким футером и хедером. Как это организовать по средствам CSS и HTML?
footer:

header:


text:
Q: Update one table from another table with duplicate keys I am trying to merge data from one table into another.
Table 1 (Tab1)
ID  col2    col3    col_to_update
1   s1      a1      null
2   s1      a2      null
3   s1      a2      null
4   s2      a1      null
5   s3      a1      null
6   s4      a1      null

Table 2 (Tab2)
ID  col2    col3    col4
10  s1      a1      v1
11  s1      a1      v2
12  s1      a2      v3
13  s2      a1      v4
14  s3      a1      v5
15  s4      a1      v6
16  s4      a1      v7

I am trying to map column col4 from table Tab2 into column col_to_update in table Tab1 based on matching Tab1.col2 = Tab2.col2 and Tabl.col3 = Tab2.col3 to get below expected output:
Expected Output
ID  col2    col3    col4
1   s1      a1      v1
2   s1      a2      v3
3   s1      a2      v3
4   s2      a1      v4
5   s3      a1      v5
6   s4      a1      v6

I tried unsuccessfully with below query:
MERGE INTO Tab1 x1
USING
(
    SELECT  t1.id as t1id, t2.id as t2id, t2.col2 t2col2, t2.col3 t2col3, t2.col4 from Tab2 t2
    JOIN Tab1 t1 ON t2.col2 = t1.col2 AND t2.col3 = t1.col3
) x2
ON (x1.id = x2.t1id)
WHEN MATCHED THEN UPDATE SET
x1.col_to_update = x2.col4;

Is there a way to get the expected output.

A: You simply want to update tab1:
update tab1
set col_to_update =
(
  select min(tab2.col4) -- or whichever value you want to use
  from tab2
  where tab2.col2 = tab1.col2
    and tab2.col3 = tab1.col3
);


text:
Q: Twilio unable to delete a sms command watever the status of the command The documentation of twilio say you can delete a command or a sms command if the status is sent or failed. But there is now explanation for the procedure.
I tried to delete by a call api to DELETE https://supersim.twilio.com/v1/Commands/{sid}...
The command didn't work.
here the documentation links

*

*https://www.twilio.com/docs/iot/supersim/api/command-resource#deleting-commands

*https://www.twilio.com/docs/iot/supersim/api/smscommand-resource#deleting-commands
What is the way to delete some commands?

A: Twilio developer evangelist here.
It turns out this was a mistake in the documentation. There is not a DELETE method for Commands or SmsCommands and that is why your attempt failed and why there are not methods for it in the Twilio helper libraries.
We are updating the docs now. Sorry for the inconvenience.


text:
Q: Windows batch file to move files to subfolders based on file name I had never built batches and I am having difficulty finding the syntax to do the following.
I have a ton of files stored in a single directory which I wish to move into subfolders(some already exist, others to be created) based on the following logic:
01202000088000.pdf

characters 1,2 -> first folder
characters 3,4 -> second folder
characters 5,6,7,8,9 -> third folder

I need to move 01202000088000.pdf file to 01\2020\00088\,
so renaming 01202000088000.pdf to
01\2020\00088\01202000088000.pdf.
I'd really appreciate your help.
Edit:
Thanks to the advice I also created the batch version:
@echo off
setlocal enabledelayedexpansion
rem For each file in your folder
for %%a in (*.pdf) do (
    echo filename=%%a
    rem check if the it is not our script
    if "%%a" NEQ "%0" (
        set foldername=%%a
        set foldername=..\!foldername:~0,2!\!foldername:~2,4!\!foldername:~6,5!\
        echo foldername=!foldername!
        rem check if forlder exists, if not it is created
        if not exist "!foldername!" mkdir "!foldername!"
        rem Move (or change to copy) the file to directory
        move "%%a" "!foldername!\"
    )
)

A: Here is a method of doing it.
I myself like the batch function (via call) which is why I use it.  Others like using () parens and delayed expansion.  Neither are wrong.
As mentioned below, the function could have been squashed into two lines but then you wouldn't be able to understand what I was doing with string parsing so I left it verbose.
    @echo off

    :: This script assumes that all PDFs req'd are in the
    :: current directory and all have names with the format
    :: 01202000088000.pdf

    :: Get all of the PDF files in the current directory.  Pass them
    :: to a function called ParseFilenameMoveFile one at a time
    for %%f in (*.pdf) do call :ParseFilenameMoveFile "%%f"
    goto :EOF

    :: ----------------------------------------------------------------
    :: this could be folded into two lines but wouldn't be readable.
    :: ----------------------------------------------------------------
    :ParseFilenameMoveFile
    set InputFile=%~1
    set firstFolderChars=%InputFile:~0,2%
    set secondFolderChars=%InputFile:~2,4%
    set thirdFolderChars=%ParsedFilename:~6,5%

    set outputFolder=%firstFolderChars%\%secondFolderChars%\%thirdFolderChars%

    if not exist %outputFolder% mkdir %outputFolder%
    move %InputFile% %outputFolder%

    goto :EOF

A: Unless you're doing historical research, there's no reason to learn batch. Use PowerShell:
$Source = 'c:\PDF Folder'
GEt-ChildItem $Source *.pdf | ForEach{
   $Destination = ($_.Name.Substring(0,2)),($_.Name.Substring(2,4)),($_.Name.Substring(6,5)) -join '\'
   If ( -not ( Test-Path $Destination )) {
       mkdir $Destination | out-null
   }
   Move-Item $_.FullName $Destination
}

A: If the syntax is the same, try using a free renaming utility like Bulk Rename Utility.  From there sorting them into directories can probably be easily done in Windows Explorer.