text:
Q: How to pass basic auth header to SOAP endpoint from WS02 Api Manager? I am using API Manager 2.0, I have designed a new API and the production url is an end point of web service. In API I have added "Message Mediation Policies" to convert json to soap in request and convert back the soap to json in request. This works fine when there is no authentication.
When I tried to connect to an endpoint which is authenticated using basic am unable to send the auth header. Is it possible to pass and if so how to achieve it?
I have already tried Endpoint Security Schema and no success with that.

A: If you configure Endpoint Security Scheme properly, you should see Authorization property like below, in your api file, in repository/deployment/server/synapse-configs/default/api/ directory. Double check if it's there.
   <resource methods="GET" url-mapping="/menu" faultSequence="fault">
      <inSequence>
         <property name="api.ut.backendRequestTime"
                   expression="get-property('SYSTEM_TIME')"/>
         <filter source="$ctx:AM_KEY_TYPE" regex="PRODUCTION">
            <then>
               <property name="Authorization"
                         expression="fn:concat('Basic ', 'YmhhdGhpeWE6cGFzc3dvcmQ=')"
                         scope="transport"/>
               <send>
                  <endpoint name="admin--PizzaShackAPI_APIproductionEndpoint_1">
                     <http uri-template="https://localhost:9443/am/sample/pizzashack/v1/api/"/>
                     <property name="ENDPOINT_ADDRESS"
                               value="https://localhost:9443/am/sample/pizzashack/v1/api/"/>
                  </endpoint>
               </send>
            </then>
            <else>
               <property name="Authorization"
                         expression="fn:concat('Basic ', 'YmhhdGhpeWE6cGFzc3dvcmQ=')"
                         scope="transport"/>
               <send>
                  <endpoint name="admin--PizzaShackAPI_APIsandboxEndpoint_1">
                     <http uri-template="https://localhost:9443/am/sample/pizzashack/v1/api/"/>
                     <property name="ENDPOINT_ADDRESS"
                               value="https://localhost:9443/am/sample/pizzashack/v1/api/"/>
                  </endpoint>
               </send>
            </else>
         </filter>
      </inSequence>
      <outSequence>
         <class name="org.wso2.carbon.apimgt.usage.publisher.APIMgtResponseHandler"/>
         <send/>
      </outSequence>
   </resource>

A: You can do this by implementing a mediator which can be configured for the particular API. The class will be invoked before making ESB call during that you can inspect the request and set the header with the basic auth details.
Steps.
1. Create a mediator project
2. Implement the log in the mediator class (handleRequest Method)
3. Export this class as a jar file
4. Copy it in Carbon_home/repository/components/lib
5. Configure the mediator for the particular API file is located(C:\WSO2\wso2am-
  2.0.0\repository\deployment\server\synapse-configs\default\api)
6. add the configuration in the handlers section example

*Restart the server APM


text:
Q: How can I prevent an executable icon from appearing in the dock? I need to modify the source code of this program to prevent the icon from appearing in the macOS's dock when it is run. It generates an Unix executable. I'm not aware of developing programs for macOS.
The main problem is that a third program (Sublime text) runs that program. And if Sublime Text is full screen, it goes back to the main desktop.
#import <Foundation/Foundation.h>
#import <AppKit/AppKit.h>

@interface NSColor (NSColorHexadecimalValue)
@end

@implementation NSColor (NSColorHexadecimalValue)

// NSColorHexadecimalValue from http://developer.apple.com/library/mac/#qa/qa1576/_index.html
-(NSString *)hexValue {
  CGFloat redFloatValue, greenFloatValue, blueFloatValue;
  int redIntValue, greenIntValue, blueIntValue;
  NSString *redHexValue, *greenHexValue, *blueHexValue;

  // Convert the NSColor to the RGB color space before we can access its components
  NSColor *convertedColor = [self colorUsingColorSpaceName:NSCalibratedRGBColorSpace];

  if(convertedColor) {
    // Get the red, green, and blue components of the color
    [convertedColor getRed:&redFloatValue green:&greenFloatValue blue:&blueFloatValue alpha:NULL];

    // Convert the components to numbers (unsigned decimal integer) between 0 and 255
    redIntValue=redFloatValue*255.99999f;
    greenIntValue=greenFloatValue*255.99999f;
    blueIntValue=blueFloatValue*255.99999f;

    // Convert the numbers to hex strings
    redHexValue=[NSString stringWithFormat:@"%02x", redIntValue];
    greenHexValue=[NSString stringWithFormat:@"%02x", greenIntValue];
    blueHexValue=[NSString stringWithFormat:@"%02x", blueIntValue];

    // Concatenate the red, green, and blue components' hex strings together
    return [NSString stringWithFormat:@"%@%@%@", redHexValue, greenHexValue, blueHexValue];
  }
  return nil;
}

// color from hex found from http://www.karelia.com/cocoa_legacy/Foundation_Categories/NSColor__Instantiat.m
+ (NSColor *)colorFromHex:(NSString *)inColorString {
  NSColor *result = nil;
  unsigned int colorCode = 0;
  unsigned char redByte, greenByte, blueByte;

  if ([inColorString length] == 3) {
    NSString *newColor = [[NSString alloc] initWithFormat:@"%@%@%@%@%@%@",
      [inColorString substringWithRange: NSMakeRange(0,1)],
      [inColorString substringWithRange: NSMakeRange(0,1)],
      [inColorString substringWithRange: NSMakeRange(1,1)],
      [inColorString substringWithRange: NSMakeRange(1,1)],
      [inColorString substringWithRange: NSMakeRange(2,1)],
      [inColorString substringWithRange: NSMakeRange(2,1)]];
    inColorString = [newColor autorelease];
  }

  if (nil != inColorString) {
    NSScanner *scanner = [NSScanner scannerWithString:inColorString];
    (void) [scanner scanHexInt:&colorCode]; // ignore error
  }
  redByte   = (unsigned char) (colorCode >> 16);
  greenByte = (unsigned char) (colorCode >> 8);
  blueByte  = (unsigned char) (colorCode);  // masks off high bits
  result = [NSColor colorWithCalibratedRed:(float)redByte / 0xff
                                     green:(float)greenByte/ 0xff
                                      blue:(float)blueByte / 0xff
                                     alpha:1.0];
  return result;
}

@end

@interface Picker : NSObject <NSApplicationDelegate, NSWindowDelegate> {
  NSColorPanel *panel; // weak ref
}

- (void)show;
- (void)writeColor;
- (void)exit;

@end

@implementation Picker

- (void)show {
  // setup panel and its accessory view

  NSView *accessoryView = [[NSView alloc] initWithFrame:(NSRect){{0, 0}, {220, 30}}];

  NSButton *button = [[NSButton alloc] initWithFrame:(NSRect){{110, 4}, {110 - 8, 24}}];
  [button setButtonType:NSMomentaryPushInButton];
  [button setBezelStyle:NSRoundedBezelStyle];
  button.title = @"Pick";
  button.action = @selector(writeColor);
  button.target = self;

  NSButton *cancelButton = [[NSButton alloc] initWithFrame:(NSRect){{8, 4}, {110 - 8, 24}}];
  [cancelButton setButtonType:NSMomentaryPushInButton];
  [cancelButton setBezelStyle:NSRoundedBezelStyle];
  cancelButton.title = @"Cancel";
  cancelButton.action = @selector(exit);
  cancelButton.target = self;

  [accessoryView addSubview:[button autorelease]];
  [accessoryView addSubview:[cancelButton autorelease]];

  panel = [NSColorPanel sharedColorPanel];
  [panel setDelegate:self];
  [panel setShowsAlpha:NO]; // TODO: support for rgba() output values
  [panel setAccessoryView:[accessoryView autorelease]];
  [panel setDefaultButtonCell:[button cell]];

  // load user settings
  NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  NSString *color = [defaults stringForKey:@"startColor"];
  if (color != nil) {
    [panel setColor:[NSColor colorFromHex:color]];
  }
  [panel setMode:[defaults integerForKey:@"mode"]]; // will be 0 if not set, which is NSGrayModeColorPanel

  // show panel
  [panel makeKeyAndOrderFront:self];
  //[NSApp runModalForWindow:panel]; // resets panel position
}

- (void)writeColor {
  NSString *hex = [panel.color hexValue];

  // save color and current mode to defaults
  NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  [defaults setObject:hex forKey:@"startColor"];
  [defaults setInteger:panel.mode forKey:@"mode"];
  [defaults synchronize]; // force a save since we are exiting

  // write color to stdout
  NSFileHandle *stdOut = [NSFileHandle fileHandleWithStandardOutput];
  [stdOut writeData:[hex dataUsingEncoding:NSASCIIStringEncoding]];

  [self exit];
}

- (void)exit {
  [panel close];
}

// panel delegate methods

- (void)windowWillClose:(NSNotification *)notification {
  [NSApp terminate:self];
}

// application delegate methods

- (void)applicationDidFinishLaunching:(NSNotification*)aNotification {
  ProcessSerialNumber psn = {0, kCurrentProcess};
  TransformProcessType(&psn, kProcessTransformToForegroundApplication);
  SetFrontProcess(&psn);
  [self show];
}

@end

int main (int argc, const char * argv[]) {
  NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  NSApplication *app = [NSApplication sharedApplication];
  app.delegate = [[[Picker alloc] init] autorelease];
  [app run];
  [pool drain];
  return 0;
}

It shows an icon like this:

A: Instead of using kProcessTransformToForegroundApplication:
TransformProcessType(&psn, kProcessTransformToForegroundApplication);

Try kProcessTransformToUIElementApplication:
TransformProcessType(&psn, kProcessTransformToUIElementApplication);

I believe that only UIElementApplication can hide it's own dock icon.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Display time in irssi in 12-hour format In the irssi IRC client, the time and timestamps are displayed by default in 24-hour format. Is there any way to get it to default to 12-hour format?

A: I found the answer, I just did /set timestamp_format %I:%M.


text:
Q: Can the flag/close button be moved back to the bottom right corner? The old dialogue had the button in the bottom right hand corner.

The new one now has it in the bottom left corner.

This breaks workflow for those of us used to clicking in the old spot. Whilst I could get used to it muscle memory has already failed me every time so far on both mobile and desktop and it's quite annoying.
To me, and I'm not a UX expert at all, bottom right made more sense. You read left to right, top to bottom. By being in the bottom right corner it is signalling it is the last thing to do/read which it is.
Can we move it back to the bottom right corner?


text:
Q: Trying to get a Dymo 4XL to work using a Pi Zero W as a print server I'm so lost. I don't know what to do.
I followed these instructions until I got to the part where it had me download the SDK. I didn't know how to follow the steps after that.
So, what I did was followed these instructions after that, up until it had me add the printer. Instead I followed the old instructions after that and did it through the web interface. However, when I go to add the printer, it doesn't have the dymo 4xl listed as a model. It only has one model and that's "dymo label printer (en)".
So...what should I do? What did I do wrong?

A: In your first link the SDK part has an incorrect link. Try downloading the file from:
http://www.dymo.com/en-US/dymo-label-sdk-and-cups-drivers-for-linux-dymo-label-sdk-cups-linux-p--1#
After you download the file you will need to extract the drivers as follows:
tar zxvf dymo-cups-drivers-1.4.0.tar.gz

That will create a dymo-cups-drivers-1.4.0.5 folder, then you should be able to continue on with your setup.

A: Just FYI: If you need a label printer, do not buy a DYMO from this point in time onwards.
I have contacted their customer support and although not properly mentioned on their website, they have stopped supporting Linux as of this point in time.


text:
Q: Test for convergence of the series $\sum\limits_{n=3}^\infty\frac{1}{(\ln \ln n)^{\ln n}}$
Test for convergence of the series $\sum\limits_{n=3}^\infty\frac{1}{(\ln \ln n)^{\ln n}}$

I test the series by this steps
$(\ln \ln n)^{\ln n} = (e^{\ln \ln \ln n})^{\ln n}= (e^{ \ln n})^{\ln \ln \ln n }=n^{\ln \ln \ln n}$.
Then
$(\ln{ {\ln \ln{n}}}) > 2$.
Thus,  $\frac{1}{(\ln \ln n)^{\ln n}} < \frac{1}{n^2}$
and thus the series converges by the comparison test.
Is this work..!? are there some wrongs ..!?


text:
Q: How to detect when an R function with system command is done then start running the next function? I have to use two functions in an R package and put them in a script to run the processes:
#!/usr/bin/env Rscript

library(pkg)

function1()
function2()

Both function 1 & 2 includes system() command to run some bash scripts. function2 needs the output from function1 as input.
The problem is when I run the above script in macOS or Ubuntu, both functions run at the same time so function2 would raise errors. I wonder if there's any way in R not to trigger function2 until function1 is done?


text:
Q: How can I make this work without an array? The program prints out the sum of the square of the first 12 integers following the number entered by the user. My teacher assigned me this as homework but we haven't studied arrays yet in class; so how can I do it without using them?
Output example:
If the users enters:1 the program should print out the result of(1^2 + 2^2 + 3^2 + 4^2 + 5^2 and so on)
SAMPLE INPUT:1
SAMPLE OUTPUT:650

Code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int num,i,sum;

void main(){
    int num[13];//cuz stores the first number and the 12 following

    printf("Enter a number:");
    scanf("%d",&num[i]);

    for(i=1;i<=num[0]+12;i++)
    {
        sum=sum+pow(num[i],2);
        num[i+1]=num[i]+1;
    }
    printf("sum of the 12 following number each squared:%d",sum);
}

A: You can calculate each numbers and add that to sum. After adding, the calculated numbers can be discarded because they won't be used later.
#include <stdio.h>

int main(void){
    int num,i,sum=0;
    printf("Enter a number:");
    scanf("%d",&num);

    for(i=0;i<12;i++)
    {
        sum=sum+(num+i)*(num+i);
    }

    printf("sum of the 12 following number each squared:%d",sum);

    return 0;
}

Also:

*

*Generally, using global variables should be avoided if they can. Note that global variables are implicitly initialized to zero but non-static local variables won't be implicitly initialized.

*You should use standard int main(void) in hosted environment instead of void main(), which is illegal in C89 and implementation-defined in C99 or later, unless you have some special reason to use non-standard signature.

*pow() is for dealing with floating-point number. Floating-point calculation may produce some errors and should be avoided when dealing with integers.

A: #include <stdio.h>
#include <math.h>
int main() {
int N, I, SUM=0;

printf("Entre any value: "); scanf("%d", &N);

for(I = 0; I < 12; I++)
{
    SUM += pow(N, 2);
    N++;
}

printf("%d", SUM);

return 0;

}

A: #include <stdio.h>
#include <stdlib.h>
#include <math.h>

int num,i,sum;
void main(){
    printf("Enter a number:");
    scanf("%d",&num);
    for(i=1;i<12;i++)
    {
      sum=sum+(num+i)*(num+i);
    }
    printf("sum of the 12 following number each squared:%d",sum);
}


text:
Q: Rails redirect_to SyntaxError Well, I'm not a web developer. Just a curious and programming enthusiast.
I was trying to learn ruby on rails following this tutorial: Ruby on Rails 3.2 Blog in 15 minutes step by step.
I've accomplished almost all of it, but when I was configuring the comments I started having some problems. First of all, I'm using a different version of rails (4.0.4), so I had to change a little bit my app/controllers/comments_controller.rb. The code recommended by the article was:
class CommentsController < ApplicationController
        def create
                @post = Post.find(params[:post_id])
                @comment = @post.comments.create!(params[:comment])
                redirect_to @post
        end
end

The code with the tweak that I had to made:
class CommentsController < ApplicationController
  def create
            @post = Post.find(params[:post_id])
            @comment = @post.comments.create!(params.require(:comment).permit(:comment_text,:link)
            redirect_to @post

  end
end

But I'm getting the following message:

SyntaxError in CommentsController#create
  /Users/gustavorpaiva/quick_blog/app/controllers/comments_controller.rb:5: syntax error, unexpected tIDENTIFIER, expecting ')' redirect_to @post ^
Rails.root: /Users/gustavorpaiva/quick_blog

I would really appreciate if someone could gie me a hand here. It's probably a real silly mistake, but I just don't know what else to do...
Thanks!

A: You are missing a closing parenthesis on the second line of your create definition, the line should look as follows:
@comment = @post.comments.create!(params.require(:comment).permit(:comment_text,:link))


text:
Q: In HTML and Angular dart, is there a way to change the style of an element based on a function? I am using angular dart. I have a simple dialog that I contains a list. I want the selected item in the list to be a different highlighted color. I have this working, but there has to be a better way than what I am doing.

In my HTML code I have 2 different elements inside my list and I am showing one or the other based on some logic (rowIsSelected function). Is there a way to have just one element and change its style based on the same function?
<modal *ngIf="visible" [visible]="visible">
    <material-dialog headered class="headered-dialog">

{{caption}}

        <form (ngSubmit)="onSubmit()" #heroForm="ngForm">

{{item.name}}

{{item.name}}

        </form>

            <button (click)="onSubmit()" type="submit" class="btn btn-primary closebuttons">OK</button>
            <button (click)="onClose()" type="button" class="btn closebuttons">Cancel</button>

    </material-dialog>
</modal>

My CSS looks like this...
p {
  margin: 8px;
}

.list-body{
    width: 300px;
    max-height: 500px;
    overflow-y:auto;
    overflow-x:auto;
    border: 1px solid black;
}

ul {
  list-style: none;
  padding-left: 0;
}

li {
  line-height: 2em;
  cursor: pointer;
}

li:hover {
  background-color: #EEEEEE;
}

.selectedrow {
  background-color: #0072a3;
  color: white;
}

.closebuttons {
  width:100px;
}


text:
Q: React router with Admin Layout I have developed a mini web-portal which has a react based form for saving records and a retrieval page to search those records / delete and edit them.. When I click edit. Then I want my form to get open which can be done through routers.
I have have routed to my form page but it is hiding all the panels and menus and showing just the page.
Can anybody help what am I doing wrong with the router?
Retrieval JSX file
import React, { Component } from "react";
import { BrowserRouter as Router, Route} from 'react-router-dom'
import { Grid, Row, Col, Table } from "react-bootstrap";

import Card from "components/Card/Card.jsx";
import { thArray } from "variables/Variables.jsx";
import { FormInputs } from "components/FormInputs/FormInputs.jsx";
import Button from "components/CustomButton/CustomButton.jsx";
import NotificationSystem from "react-notification-system";
import UserProfile from "./UserProfile";

class TableList extends Component {

  constructor(props) {
    super(props)
    this.state = {
        error: null,
        transaction: [],
        defaultTransactionState: [],
        _notificationSystem: null
    }
    this.editEntry = this.editEntry.bind(this);
  }

  // values on page loadup..
  componentDidMount() {
    const apiUrl = 'http://localhost:3000/api/str/';
    fetch(apiUrl)
      .then( (response) => {
          return response.json();
        })
      .then((data) => {
          this.setState({ transaction: data.response })
          this.setState({ defaultTransactionState: data.response })
        })
        .catch((error) => console.log(error));
  }

  handleNotificationClick = position => {
    var color = Math.floor(Math.random() * 4 + 1);
    var level;
    switch (color) {
      case 1:
        level = "success";
        break;
      case 2:
        level = "warning";
        break;
      case 3:
        level = "error";
        break;
      case 4:
        level = "info";
        break;
      default:
        break;
    }
    this.state._notificationSystem.addNotification({
      title: ,
      message: (

Challan Deleted Successfully!

      ),
      level: level,
      position: position,
      autoDismiss: 5
    });
  };

  editEntry = () => {
    console.log("in edit.")
    this.props.history.push('/userProfile');
  }

  deleteEntry = challanNo => {
    const transactions = this.state.transaction;
    console.log('inside delete.. with Challan No' + challanNo)
    const requestOptions = {
      method: 'DELETE'
    };
    this.setState({
      transaction: transactions.filter(trn => trn.CHALLAN_NO !== challanNo)
    })
    fetch("http://localhost:3000/api/str/delete/" + challanNo, requestOptions)
      .then((response) => {
      return response.json();
    })
    .then((data) => {
      console.log('Done with delete.. Now: ' + typeof data.response)
      this.handleNotificationClick(1)
     // this.setState({ transaction: data.response })
    })
    .catch((error) => console.log(error));
  }
      // reset the rows on backspace..
      onKeyDown = (e) => {
        if (e.keyCode === 8) {
         this.setState({ transaction: this.state.defaultTransactionState })
         console.log('delete');
        }
      }

   // filter data set on change event of field values..
   filterChallan = (event) => {

    console.log(this.state.transaction)
    let transaction = this.state.transaction

    transaction = transaction.filter((challan) => {
      let challanNo = challan.CHALLAN_NO
      console.log(event.target.value)
      return challanNo.toString().search(event.target.value) !== -1
    })
    this.setState({
        transaction: transaction
    })
   }

   filterEntityName = (event) => {

    console.log(this.state.transaction)
    let transaction = this.state.transaction

    transaction = transaction.filter((challan) => {
      let entityName = challan.ENTITY_NAME
      console.log(event.target.value)
      return entityName.toString().toLowerCase().search(event.target.value.toLowerCase()) !== -1
    })
    this.setState({
        transaction: transaction
    })
  }

  render() {
    return (

        <Grid fluid>
          <Row>
            <Col md={12}>
              <Card
                title="Filter Criteria"
                category="Search the Fee Payment Details for Specific Challan Info"
                ctTableFullWidth
                ctTableResponsive
                content={

                  <FormInputs
                      ncols={["col-md-2", "col-md-4"]}
                      properties={[
                        {
                          label: "Challan #",
                          type: "text",
                          bsClass: "form-control",
                          placeholder: "Challan #",
                          onChange: this.filterChallan,
                          onKeyDown: this.onKeyDown
                        },
                        {
                          label: "Entity Name",
                          type: "text",
                          bsClass: "form-control",
                          placeholder: "Entity Name",
                          onChange: this.filterEntityName,
                          onKeyDown: this.onKeyDown
                        }
                      ]}
                    />

                        {thArray.map((prop, key) => {
                          return {prop}	;
                        })}

                    {this.state.transaction.map((str) => (

                        {str.CHALLAN_NO}
                        {str.ENTITY_NAME}
                        {str.ENTITY_TYPE}
                        {str.CITY}
                        {str.EMAIL}

                        <Button bsStyle="info" fill onClick={this.editEntry}
                                className="btn btn-primary btn-sm mr-2">
                          Edit
                        </Button> <Button bsStyle="info" fill onClick={() => this.deleteEntry(str.CHALLAN_NO)}
                                className="btn btn-primary btn-sm mr-2">
                          Delete
                        </Button>

                       ))}

                }
              />
            </Col>
          </Row>
        </Grid>

    );
  }
}

export default TableList;

Form JSX File

import React, { Component } from "react";
import {
  Grid,
  Row,
  Col,
  FormGroup,
  ControlLabel,
  FormControl
} from "react-bootstrap";

import { Card } from "components/Card/Card.jsx";
import { FormInputs } from "components/FormInputs/FormInputs.jsx";
import { UserCard } from "components/UserCard/UserCard.jsx";
import Button from "components/CustomButton/CustomButton.jsx";

import avatar from "assets/img/faces/face-3.jpg";

class UserProfile extends Component {

  constructor() {
    super()
    this.state = {
      challan_no:                 '',
      challan_amount:             '',
      entity_name:                '',
      entity_address:             '',
      city:                       '',
      district:                   '',
      province:                   '',
      telephone:                  null,
      mobile:                     null,
      email:                      '',
      entity_type:                '',
      registraton_no:             null,
      registering_authority_name: '',
      principal_lob:              ''
    }
    this.onChange = this.onChange.bind(this)
    this.insertRecord = this.insertRecord.bind(this)
  }
  onChange(e){
    this.setState({[e.target.name]: [e.target.value]})
}

  insertRecord(event) {
    event.preventDefault();

    fetch('http://localhost:3000/api/str/insert', {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
       body: JSON.stringify( {
        challan_no:                 this.state.challan_no,
        challan_amount:             this.state.challan_amount,
        entity_name:                this.state.entity_name,
        entity_address:             this.state.entity_address,
        city:                       this.state.city,
        district:                   this.state.district,
        province:                   this.state.province,
        telephone:                  this.state.telephone,
        mobile:                     this.state.mobile,
        email:                      this.state.email,
        entity_type:                this.state.entity_type,
        registration_no:            this.state.registration_no,
        registering_authority_name: this.state.registering_authority_name,
        principal_lob:              this.state.principal_lob

  })
   }).then(res => res.json())
   .then(data => console.log(data))
   .catch(err => console.log(err));
  }

  render() {
    return (

        <Grid fluid>
          <Row>
            <Col md={8}>
              <Card
                title="Add Fee Payment Details"
                content={
                  <form>
                    <FormInputs
                      ncols={["col-md-5", "col-md-3", "col-md-4"]}
                      properties={[
                        {
                          label: "Challan #",
                          type: "text",
                          name: "challan_no",
                          bsClass: "form-control",
                          placeholder: "Challan #",
                          value: this.state.challan_no,
                          onChange: this.onChange
                        },
                        {
                          label: "Challan Amount",
                          type: "number",
                          name: "challan_amount",
                          bsClass: "form-control",
                          placeholder: "Challan Amount",
                          value: this.state.challan_amount,
                          onChange: this.onChange
                        },
                        {
                          label: "Entity Name",
                          type: "text",
                          name: "entity_name",
                          bsClass: "form-control",
                          placeholder: "Entity Name",
                          value: this.state.entity_name,
                          onChange: this.onChange
                        }
                      ]}
                    />
                    <FormInputs
                      ncols={["col-md-6", "col-md-6"]}
                      properties={[
                        {
                          label: "Entity Address",
                          type: "text",
                          name: "entity_address",
                          bsClass: "form-control",
                          placeholder: "Entity Address",
                          value: this.state.entity_address,
                          onChange: this.onChange
                        },
                        {
                          label: "City",
                          type: "text",
                          name: "city",
                          bsClass: "form-control",
                          placeholder: "City",
                          value: this.state.city,
                          onChange: this.onChange
                        }
                      ]}
                    />
                    <FormInputs
                      ncols={["col-md-6", "col-md-6"]}
                      properties={[
                        {
                          label: "District",
                          type: "text",
                          name: "district",
                          bsClass: "form-control",
                          placeholder: "District",
                          value: this.state.district,
                          onChange: this.onChange
                        },
                        {
                          label: "Province",
                          type: "text",
                          name: "province",
                          bsClass: "form-control",
                          placeholder: "Province",
                          value: this.state.province,
                          onChange: this.onChange
                        }
                      ]}
                    />
                    <FormInputs
                      ncols={["col-md-4", "col-md-4", "col-md-4"]}
                      properties={[
                        {
                          label: "Telephone",
                          type: "number",
                          name: "telephone",
                          bsClass: "form-control",
                          placeholder: "Telephone",
                          value: this.state.telephone,
                          onChange: this.onChange
                        },
                        {
                          label: "Mobile",
                          type: "number",
                          name: "mobile",
                          bsClass: "form-control",
                          placeholder: "Mobile",
                          value: this.state.mobile,
                          onChange: this.onChange
                        },
                        {
                          label: "Email",
                          type: "text",
                          name: "email",
                          bsClass: "form-control",
                          placeholder: "Email",
                          value: this.state.email,
                          onChange: this.onChange
                        }
                      ]}
                    />
                  <FormInputs
                      ncols={["col-md-4", "col-md-4", "col-md-4"]}
                      properties={[
                        {
                          label: "Entity Type",
                          type: "text",
                          name: "entity_type",
                          bsClass: "form-control",
                          placeholder: "Entity Type",
                          value: this.state.entity_type,
                          onChange: this.onChange
                        },
                        {
                          label: "Registration #",
                          type: "text",
                          name: "registration_no",
                          bsClass: "form-control",
                          placeholder: "Registration #",
                          value: this.state.registraton_no,
                          onChange: this.onChange
                        },
                        {
                          label: "Registration Authority Name",
                          type: "text",
                          name: "registering_authority_name",
                          bsClass: "form-control",
                          placeholder: "Registration Authority Name",
                          value: this.state.registering_authority_name,
                          onChange: this.onChange
                        }
                      ]}
                    />

                    <Row>
                      <Col md={12}>
                        <FormGroup controlId="formControlsTextarea">
                          <ControlLabel>Principal Line of Business</ControlLabel>
                          <FormControl
                            rows="5"
                            componentClass="textarea"
                            bsClass="form-control"
                            name="principal_lob"
                            value={this.state.principal_lob}
                            onChange= {this.onChange}
                            placeholder="Enter the details of your Principal Line of Business"
                          />
                        </FormGroup>
                      </Col>
                    </Row>
                    <Button bsStyle="info" pullRight fill onClick={this.insertRecord}>
                      Save
                    </Button>

                  </form>
                }
              />
            </Col>
            <Col md={4}>
              <UserCard
                bgImage="https://ununsplash.imgix.net/photo-1431578500526-4d9613015464?fit=crop&fm=jpg&h=300&q=75&w=400"
                avatar={avatar}
                name="Mike Andrew"
                userName="michael24"
                description={

                    "Lamborghini Mercy

                    Your chick she so thirsty

                    I'm in that two seat Lambo"

                }
                socials={

                    <Button simple>

                    </Button>
                    <Button simple>

                    </Button>
                    <Button simple>

                    </Button>

                }
              />
            </Col>
          </Row>
        </Grid>

    );
  }
}

export default UserProfile;

** Router file **
import React from "react";
import ReactDOM from "react-dom";

import { BrowserRouter, Route, Switch, Redirect } from "react-router-dom";

import "bootstrap/dist/css/bootstrap.min.css";
import "./assets/css/animate.min.css";
import "./assets/sass/light-bootstrap-dashboard-react.scss?v=1.3.0";
import "./assets/css/demo.css";
import "./assets/css/pe-icon-7-stroke.css";

import AdminLayout from "layouts/Admin.jsx";
import UserProfile from "views/UserProfile";

ReactDOM.render(
  <BrowserRouter>
    <Switch>
      <Route path="/admin" render={props => <AdminLayout {...props} />} />
      <Route path='/userProfile' component={UserProfile} />
      <Redirect from="/" to="/admin/dashboard" />
    </Switch>
  </BrowserRouter>,
  document.getElementById("root")
);

A: If you want to prevent other components from disappearing, you need to adjust your path accordingly. For example: path='/admin shows panels and menus and admin welcome page, right? Then you need to create a path like this path='/admin/edit' for your panels and menus to show up in your edit route.


text:
Q: Strict standards: Only variables should be passed I have image upload script which shows this (Strict standards: Only variables should be passed by reference in C:\wamp\www\Fcomail-Final\cpanel\fcomail\Gallery.php on line 33
Call Stack) error Line no 33 is
require('../conn/include.php');
require('quick.php');
$query="SELECT * FROM category";
$result=mysql_query($query);
$project=$_POST['project'];
$alttext=$_POST['alttext'];
$relation=$_POST['Section'];;

if(isset($_FILES['image'])) {
    $errors=array();
    $allowed_ext=array('jpg','png','jpeg','JPG');
    $filename=$_FILES['image']['name'];
    $name=stripslashes($filename);
    **Line 33** $type=strtolower(end(explode('.',$filename)));
    $size=$_FILES['image']['size'];
    $file_tmp=$_FILES['image']['tmp_name'];
if(in_array($type,$allowed_ext) ===false) {
    $errors[]= "Extenstion Not Allowed";
}if($size > 1048576) {
    $errors[]= "File must be less then 2mb";
}if(file_exists('../../images/fcomail/gallery/'.$filename)) {
   $errors[]= "File $filname Already Exists in directory";
}if(empty($errors)) {
    if(move_uploaded_file($file_tmp, '../../images/fcomail/gallery/'.$filename)) {
        $insert="Insert into `my`.gallery(name,alttext,project,relation)VALUES('$name','$alttext','$project','$relation')";
        //echo $insert;
        $que=mysql_query($insert);
    echo "File $filname Uploaded Sucessfully";
    }
}else {
    foreach($errors as $error) {
        echo $error,'
';
    }
}
}

A: You need to break the below line
$type=strtolower(end(explode('.',$filename)));

to
$fname = explode('.',$filename);
$filename = end($fname);
$type=strtolower($filename);

Reason :
From the documentation of end() in PHP Manual.

The array. This array is passed by reference because it is modified by
  the function. This means you must pass it a real variable and not a
  function returning an array because only actual variables may be
  passed by reference.


text:
Q: MIPS program to determine pass/fail for test grades I'm writing a MiPS program that will examine a list of 15 test scores. And it is going to input from the terminal. The passing criterion is the score of 50. The outputs to the terminal will include the scores in each category and the number of students passing and failing. I should use input prompts and output statement. Please I need some help, just need some advice how to do it.
main:
 li $t1,15         #load 15 into $t1

 la $a1,array      #load a pointer to array into $a1

I have a loop:
addi $t1,$t1,-1

li $v0,4

la $a0,prompt

syscall

A: I don´t want to give it away, so i´ll throw some guidelines.
You should read Assemblers, linkers and the Spim simulator. It´s a lot of help.
So here it goes.
Create two 15- word arrays.
 .data
 fail_vector: .word  -1,-1,-1 ...    #15 invalid words
 passed_vector: .word  -1,-1,-1 ...  #15 invalid words

Load on some  register the loop control variable.
 li $t1,15
 beq $t1,$zero,END
 addiu $t1,$t1,-1

Now inside this loop read values
 syscall...     #SYS_READ

Then read this value (suppose you have it in register t4) and decide whether to store it in fail vector, or pass vector.
     addiu t4,t4,-50     #subtract 50 from input value.
     blez  t4,FAILED     #If its lower than 0, then read value is lower than 50 ->FAIL
PASSED:
     #STORE VALUE INTO passed_vector

FAILED:
     #STORE VALUE INTO failed_vector

When you are done with all the 15 values, print out the vectors. This is kind of tricky.
Before using your program, you should fill both vectors with some invalid value, like -1.
So when you are printing vector to screen, you should stop when you find one of this invalid values. And while you are at it, keep a counter to show how many passed / failed.
In pseudo-code
for both arrays
   for (i in (0,15) and array[i] not -1)
        print array[i]
        add 1 to scores count //to count passed - failed test scores.

assembly (fill in the blanks)
END:
     li $t4,15
     li $t1,0
     beq $t1,$t4,EXIT   #condition. While ( i < 15) kind of thing.
     addiu $t1,$t1,-1

     #print out vectors and keep count on other registers
     #then print them out.

     syscall... #SYS_WRITE

EXIT: #exit syscall here.

Another tricky issue is the indexing of these vectors. Since they are arrays of words, then you should multiply by 4 (assuming 32 bit words) the loop control variable (classical i variable in C) to index the vector. If they were byte arrays, then no multiplication would be needed. And if they were short arrays...(well, you get my point)
For example:
passed_vector[i] #(C style sintax)

and let variable i be stored in register $t1
would turn out as:
  sll $t2,$t1,2             #i * sizeof(word)
  la  $a0,passed_vector     #$a0 points to passed_vector
  add $a0,$a0,$t2           #$a0 now points to passed_vector + i

So now you could load/store to passed_vector[i]
  sw  $t3,0($a0)            #0($a0) is passed_vector[0]
  lw  $t3,0($a0)

One way of solving these kind of things (that is, writing in assembly) is to write the program in C ( or some other language that you know ), and then translating it to assembly, instruction by instruction.

A: Ok, here's how to load both integer arrays (and only that)
.data
#These are two integer arrays. Each position is 32 bits long.
passed_vector: .word -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
failed_vector: .word -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1

.text

         #
         # Previous code here.
         #

         li $t5,50             #For comparing test_scores against.

         li $t0,0              # for (0..15)
         li $t6,15             #

LOOP:    beq $t0,$t6,CONTINUE  # loops while i<15

         li  $v0,5
         syscall
         move $t1,$v0           #read test score and move it to register $t1

         bge $t1,$t5,PASSED    #if score >=50, load into passed_vector
FAILED:                        # else: test score lower than 50. Loads into failed vector

         #dont forget to increment the failed counter here
         sll $t2,$t0,2
         sw  $t1,failed_vector($t2)

         addiu $t0,$t0,1       #i++
         b     LOOP

PASSED:

         #dont forget to increment the passed counter here.
         sll $t2,$t0,2
         sw  $t1,passed_vector($t2)

         addiu $t0,$t0,1       #i++
         b     LOOP

CONTINUE: #other code


text:
Q: In JavaScript, how can I create one function that takes two numbers and a mathematical operator + - / * perform a calculation with the given numbers Just starting learn js, how can I get results like what shows in the examples.
So the require is like this:
Create a function that takes two numbers and a mathematical operator + - / * and will perform a calculation with the given numbers.
Examples
calculator(2, "+", 2) ➞ 4
calculator(2, "*", 2) ➞ 4
calculator(4, "/", 2) ➞ 2
Notes
If the input tries to divide by 0, return: "Can't divide by 0!"
function calculator (a, b) {
  let output = 0;
  output = a+b;
  return output;
}
console.log(calculator(2,2));

Here is what I wrote, only for performing "+".
I thought maybe I should try to add another parameter to repersent "+*/", but I can't get it right.
Anyone can help with it?
Thanks

A: This should work
function calculator (a, b, c) {
  let output = 0;

  try {

    switch(c) {
      case '+':
        output = a + b
        break;

      case '*':
        output = a * b
        break;

      case '-':
        output = a - b
        break;

     case '/':
        if (b === 0) {
          throw "Can't divide by 0!"
        } else {
          output = a / b
        }
        break;
    }
  }
  catch(e) {
    console.log("There's an error: ", e)
  }

  return output;
}

console.log(calculator(2,2,'*'));

A: Here is the function:

const calculator = (a, b, operation) => {
  if (operation === '+') return a + b;
  if (operation === '-') return a - b;
  if (operation === '*') return a * b;
  if (operation === '/') return b === 0 ? "Can't divide by 0!" : a / b;
}

console.log(calculator(10, 10, "*"));


text:
Q: How to determine the correct size to set a JLabel to if it's going to be initialized later to a known String I have a JLabel which at creation is going to be blank.
Later it's going to be initialized to a string "Hello World"
If I setText to "Hello World" later on, my whole layout gets screwed up (FWIW, I am using GridBagLayout).
This is the only way I found to avoid this issue.
JLabel tmp = new JLabel("Hello World");
Dimension d = tmp.getPreferredSize();

JLabel actual = new JLabel();
actual.setPreferredSize(d);

Is there no better way to do this?

A: What is the full context of the question? Why is it so important if the size changes? Does the change in size affect the grid of the GridBagLayout?
Maybe you need a better design of the form so that a changing size in the text of the label does not affect the layout of the other components on the form? That is, maybe you need to nest different panels with different layout managers.
For example you could use a panel with a CardLayout and then have each label as a card for the panel. Then instead of changing the text, you swap the labels. This way the panel will reserve the space for the largest card in the layout.


text:
Q: What is the best way to shield / jam ultrasound? I've downloaded SoniControl and it works somewhat well as a jammer, but I am looking for more options.
I'm trying to shield from / jam Ultrasonic Cross-Device Tracking (uxDT). (See "data over audio" and "data over sound")
Does anyone have any insight?
I am a programmer, and not an engineer, so my options are somewhat limited (I cannot build a jammer, unless it is only software).


text:
Q: Java's System.exit(0); vs C++ return 0; When we learn C++ in school, our professor will tell us to write return 0; at the last line of codes in the main function and it is considered as a good programming practice.
In Java, I realise some people writes System.exit(0); at the last line of the main method.
However, in C++, if I use exit(0); I get penalized by my professor, because (in school) for procedural programming, we are expected to let the program flow till the end of main and let the program stop naturally.
My question: Is Java's System.exit(0); similar to C++'s return 0; ? (Or is it similar to C++'s exit(0))
Is it bad practice to use System.exit(0) in java when it is unnecessary (I.e.: writing it in last line of main method)?

A: In Java System.exit(0),System.exit(1),System.exit(-1) is used to know if the execution of the program went good or bad. 0 is used when execution went fine. 1, -1, whatever != 0 when some error occurred, you can use different values for different kind of errors.
You can also say it like this:
0  mean everything Okay
1  means something which I expecting to go wrong went wrong
-1 means something which I didn't expect went wrong
The Java Doc says:

The argument serves as a status code; by convention, a nonzero status
  code indicates abnormal termination.

Is Java's System.exit(0); similar to C++'s return 0; ?

Yes they both are similar.

Is it bad practice to use System.exit(0) in java when it is
  unnecessary

I would not say it is a bad practice but yes you should be aware of when to use it and where to use it. You can use it to throw an error for a command line tool via a exit code instead of throwing an exception. System.exit(0) terminates the JVM so you should be very much sure where to use that.
An example for that:
try {
    runTheWholeApplication();
    System.exit(0);  // Signifying the normal end of your program
} catch (Throwable t) {
    reportErrorSomehow(t);
    System.exit(1);  // Signifying that there is an error
}

A:
When we learn C++ in school, our professor will tell us to write return 0; at the last line of codes in the main function and it is considered as a good programming practice.

That's debatable. Has he also told you that return 0; is implicit inside main? Personally, I never write the redundant return 0; inside main, and I almost never see it in other people's code either.

A: Yes. Java's System.exit(0); is a direct analogue because the prototypical Java main method is defined as
public static void main(String[] args) {
}

So it literally cannot return an int (although it can simply return;). In C++ you could exit(0); which is also equivalent.

A: The original operating system Unix heavily relied on command line scripts using and combining many small programs. A return code of a program was used for the control flow. Return code 0 meaning everything okay, non-zero for errors.
So the C int main(...) is a direct mapping, and return 0; at the end appropiate. An exit there is like throwing an exception, bypassing any return. It also disables calling the main from another program.
In Java public void main(...) this was simplified, and 0 is implicit. System.exit(0); has the same bad assumption that no other program calls main. Though in general void mirrored the 99% usage, now System.exit(...); is inevitable for a non-zero error code.
This must also be seen as a more general design decision; C heavily relies on return codes of functions, which makes the control flow difficult or error prone, whereeas Java introduced the usage of Exceptions as possible obligatory control flow, with a freely chooseable catch. Nowadays an alternative to System.exit(13) might be throw new IllegalArgumentException("Unlucky");.

A: Java's System.exit(0) is like C++'s exit(0) in that

*

*It terminates the process

*It can be called from anywhere in the program.

The latter point makes it an "unstructured" control-flow construct that academic types tend to frown on.  (In this case, they've got a good reason: If a function reports a failure via an exception (or old-fashioned return code), it's possible for the caller to recover from the error, but exit burns that bridge.  Of course, sometimes errors do need to be treated as fatal.)
In C++, return 0 is equivalent to exit(0) if it's in the main function.  (In other functions, it doesn't mean anything special.)
The relevant different between C++ and Java here is the return type of main.

*

*In C++, main must return int.  Normally, this would mean that it must have a return statement, but the C++ standard makes main a special case with an implied return 0; as the end if you don't write one.

*In Java, main must return void.

In C++, it's common to write return statements in main, even though it's technically redundant, for stylistic consistency with all the other non-void functions in your program.
In Java, you can't return the exit code from main because it's a void function.  So, if you want to explicitly specify an exit code, you have to use System.exit.
It's not wrong to end every Java main function with System.exit(0), but it's just not idiomatic to do so unless you've got a construct like
public static void main(String[] args) {
   try {
       //... do the work
       System.exit(0);
   } catch (Throwable t) {
       //... report the error
       System.exit(1);
   }
}


text:
Q: Formatting Date with abbreviated month, while adhering to culture date structure Developing a multilanguage application, and trying to format a DateTime object to string within a limited space in a table. Full month names might be too long, so we have to use abbreviations.
Some cultures have the format "Oct 12", some have "12. okt" and so on.
The standard .ToString("m") is almost what I want, but with abbreviations:
https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings#MonthDay
Similar question, but the answer won't work for us, as this dictates the order of month and day:
Formatting Date String abbreviating month
Is there any way of getting the overall structure of a culture's date formatting, like order of day and month, with or without "." after the number etc? Or another way of generating the required string? This feels like it should be fairly straight forward, as all the pieces are already present.

A: As per the documentation you linked, the custom date and time format "m" is defined by a CultureInfo's DateTimeFormat.MonthDayPattern property. So I'd look that up for the current culture and customize the format string. Then use the modified format string with ToString.

A: I was able to solve this myself using the culture's DateTimeFormat wich provides a MonthDayPattern. By simply replacing "MMMM" with "MMM" this will solve the challenge, at least for the locales that we plan to support. I have not tested with all possible locales.
(I know it won't work for "ja-JP", wich has special characters in their pattern)
DateTime date = DateTime.Now;
CultureInfo culture = new("en-US", false);

DateTimeFormatInfo dateTimeFormat = culture.DateTimeFormat;
string pattern = dateTimeFormat.MonthDayPattern.Replace("MMMM", "MMM");
string formatted = date.ToString(pattern, culture);

The pattern for "en-US" goes from "MMMM d" to "MMM d" giving "Oct 13"
The pattern for "nb-NO" goes from "d. MMMM" to "d. MMM" giving "13. okt."


text:
Q: harmonic curvature versus Einstein metric A metric is said to have harmonic curvature if the exterior derivative of the Ricci tensor vanishes. It is known that there exists manifolds with dRic=0 that are not Einstein. My question is whether or not there are examples of manifolds that admit a metric with harmonic curvature but don't admit an Einstein metric.

A: There are many $3$-manifolds that admit a metric with harmonic curvature that don't admit an Einstein metric because in dimension $3$, 'Einstein' is equivalent to constant sectional curvature, while in dimension $3$, harmonic curvature is the same as conformally flat with constant scalar curvature.
Since one can take connected sums of conformally flat manifolds and get conformally flat manifolds and since, by Schoen's solution of the Yamabe problem, every compact $3$-manifold has a conformal change to one with constant scalar curvature, one sees that there are many more compact $3$-manifolds that admit a metric with harmonic curvature than there are compact $3$-manifolds that have an Einstein metric.


text:
Q: ERROR: This expression is not callable. Type 'TransactionOptions' has no call signatures tengo un problema con un test que estoy haciendo a un servicio de Nestjs
dicho servicio hace uso de transacciones con Sequelize ORM
la cuestion es la siguiente:
estoy intentando hacer un spyOn a la transactions de sequelize
const transactionSpy = jest
  .spyOn(sequelize, 'transaction')
  .mockImplementation((transactionCB) =>
    transactionCB({ transaction: {} } as any),
  );

y eso me dice como tengo en el titulo de la pregunta: This expression is not callable.
Type 'TransactionOptions' has no call signatures
no se como lidiar con esto alguien de buen corazon que me ayude por favo :)


text:
Q: Отправить данные из JS в PHP и записать в Mysql Есть JS, он находится на стороне клиента.
JS должен отправить данные на сайт в index.php
index.php должен эти данные записать в бд.
Я не понимаю, вроде всё правильно делаю но он их не пишет.
JS:
function send_data(){
   var request = new XMLHttpRequest();
   var one = "123";
   var two = "456"
   request.open("POST", "http://sitename/index.php");
   request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
   request.send('one=' + one + 'two=' + two);
}

PHP:
<?php
if(isset($_POST['one']) && isset($_POST['two'])){
$link = mysqli_connect($host, $user, $password, $database)
    or die("Ошибка " . mysqli_error($link));

$one = htmlentities(mysqli_real_escape_string($link, $_POST['one']));
$two = htmlentities(mysqli_real_escape_string($link, $_POST['two']));
$query = "INSERT INTO data VALUES('$one', '$two')";
$result = mysqli_query($link, $query) or die ("Ошибка " . mysqli_error($link));
mysqli_close($link);
}
?>

A: Умм, решилось.
Вот так:
function send_data(){
   var request = new XMLHttpRequest();
   var one = "123";
   var two = "456"
   var send = 'one=' + encodeURIComponent(one) + '&two=' +encodeURIComponent(two);
   request.open("POST", "http://sitename/index.php");
   request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
   request.send(send);
}


text:
Q: Add data validation and Formulas in one cell I am trying in google sheets to add a data validation where users can select ( Today, Incomplete) then if selected "Today" the cell will display today's date, and if "incomplete" then just display it as it is.
I did the formula
if(E2:2="Today",(TODAY()),"Incomplete")
But then add validation removes the formula if selected Today. Can someone help me, please.

A: Create a tab called 'DVs'
in A2 of that tab write "Incomplete".
in A3 of that tab, manually put today's date.
then point your Data Validation at those two cells.
then Tools>Script Editor.
then erase the code that is there that looks like this:
function myFunction(){

}

then paste this code.
function setToday(){
var date = new Date();
date.setHours(0,0,0,0);
SpreadsheetApp.getActive().getSheetByName('DVs').getRange('A3').setValue(date);
}

then Save.
Then click on the little alarm clock at the left to open the triggers.
Then at the bottom right, click on the button to add a trigger.
then choose the function, and set a "time driven" trigger that runs every day after midnight.
Then Save.
That should do it.


text:
Q: render html, gin GOLANG I want to render an html page with the items it has
in my database
func (h Handler) ListUser(c *gin.Context) {

    var listUsers []Users

    //listUsers = make([]Users, 0)
    listUsers = append(listUsers, Users{})
    c.HTML(http.StatusOK, "listar.html", gin.H{
        "listUsers": listUsers,
    })
    h.DB.Find(&listUsers)

}

func main() {
    db := Init()
    h := OpenDB(db)

    r := gin.Default()
    r.Static("/static", "./public")

    list := r.Group("/list")
    r.LoadHTMLFiles("listar.html")
    {
        list.GET("/list", h.ListUser)
    }

    r.POST("/upload", h.Postform)

    r.Run(":7878")
}

I want my database items (Name and Email) to be rendered in my html page, but when I run my code, the html page comes up blank


text:
Q: Why use (regressor.layers[0].input, regressor.layers[-1].output) instead of just regressor in DeepExplainer? Hi everyone i came across an example of how to use shap on lstm  Time-step wise feature importance in deep learning using SHAP. I'm curious why the author chose to use
e = shap.DeepExplainer((regressor.layers[0].input,
regressor.layers[-1].output),data)

instead of just
e = shap.DeepExplainer(regressor,data)

I suspect the reason is very important but I cannot be sure. Anyone can shed some light on this?
Partial code below
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from keras.models import load_model
import shap
regressor = load_model('lstm_stock.h5')
pred_x = regressor.predict_classes(X_train)
random_ind = np.random.choice(X_train.shape[0], 1000,
replace=False)
print(random_ind)
data = X_train[random_ind[0:500]]
e = shap.DeepExplainer((regressor.layers[0].input,
regressor.layers[-1].output),data)
test1 = X_train[random_ind[500:1000]]
shap_val = e.shap_values(test1)
shap_val = np.array(shap_val)...

A: The solution is quite simple. Let's look at the DeepExplainer documentation. This is the __init__ function:
__init__(model, data, session=None, learning_phase_flags=None)

Your confusion is about the first argument, that is, model. According to the documentation, for Tensorflow, model is:

a pair of TensorFlow tensors (or a list and a tensor) that specifies
the input and output of the model to be explained.

So that's it. The first argument is just a pair indicating the input and the output of the model. In this case:
(regressor.layers[0].input, regressor.layers[-1].output)

Update:
In the example Front Page DeepExplainer MNIST Example it is however shown this piece of code:
import shap
import numpy as np

# select a set of background examples to take an expectation over
background = x_train[np.random.choice(x_train.shape[0], 100, replace=False)]

# explain predictions of the model on three images
e = shap.DeepExplainer(model, background)
# ...or pass tensors directly
# e = shap.DeepExplainer((model.layers[0].input, model.layers[-1].output), background)
shap_values = e.shap_values(x_test[1:5])

From this it seems that, besides the pair of tensors, it is also possible to use the model as input, just like it is possible for Pytorch. Indeed in Pytorch, instead of the pair, you can also use a nn.Module object.
At this point then I guess that the one for Tensorflow is just an undocumented feature. It should then be equivalent to use directly the model or the pair of tensors.


text:
Q: Output log file to cluster option I'm submitting jobs to slurm/sbatch via snakemake. I'm trying to send the log from sbatch to a file in the same directory tree of the rule's output.
For example, this works:
rm -rf foo
snakemake -s test.smk --jobs 1 --cluster "sbatch --output log.txt"

but it fails (i.e. slurm job status is FAILED) if I try:
rm -rf foo
snakemake -s test.smk --jobs 1 --cluster "sbatch --output {output}.log"

presumably, because {output} points to foo/bar/ which does not exist. But snakemake should have created it, right?
This is test.smk:
rule all:
    output:
        'foo/bar/done.txt'
    shell:
        """
        touch {output}
        """

So, how can I send logs to a directory tree not yet existing but created by the rule? (I'm reluctant in including code in the snakefile that create dirs in anticipation).
snakemake -v
4.8.0


text:
Q: How to delete records on MDS using SQL code? I am trying to delete records on MDS using the staging table, and although I already updated the records to the ImportType 4 (Delete record):

On MDS it appears not only the correct line (Code 29355) but also the other ones that should have been deleted:

A: Solution found:
Instead of updating only the ImportType value in Leaf Staging Table with 4 the ImportStatus_ID must also be updated to 0.
! Be careful: one of the errors raised was related with deleting members that had already been deleted --> To correct this, it was added to the update statement referred above the condition of only updating to (ImportType = 4, ImportStatus_ID = 0) the records that have the ImportType = 0 (new members).


text:
Q: AWS ELB health check failing when trying to force HTTPS through NGINX for my single page application I'm trying to force https on my http endpoints using NGINX like so:
server {
    location / {
        root /data/www;
        if ($http_x_forwarded_proto != 'https') {
            rewrite ^ https://$host$request_uri? permanent;
        }
    }
    location /images/ {
        root /data;
    }
}

Note that all im serving from nginx are static files (an HTML file, javascript file, and a coupl
My ELB health check is hitting HTTP:80/. So what I think it's happening, is that ELB tries to ping my server, hits that rewrite, and gets returned a 301? I've seen a lot of answers for ruby and node, but this is just static assets. Help!

A: Yep, ELB will hit your server via its IP (thus getting the default server block) and anything other than a 2xx request will be handled as a failure.
We use a default server block for ELB to ping:
server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    location = /status {
      return 200;
      access_log off;
    }
}

A: What I ended up doing was doing a health check again TCP:80 not HTTP:80


text:
Q: Crash report for iOS App I am having problem with my in-app purchase section in my app. The problem is only on iPhone 6, 6s and iPad Air. The app is crashing when tapping any in-app purchase.
This is the crash report:
*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 18446744073709551615 beyond bounds for empty array'
*** First throw call stack:
(
    0   CoreFoundation                      0x000000010b86ef65 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x000000010b241deb objc_exception_throw + 48
    2   CoreFoundation                      0x000000010b752a94 -[__NSArrayM objectAtIndex:] + 212
    3   Chubby Vikings Free                 0x0000000106654366 -[MKStoreManager addToQueue:] + 294
    4   Chubby Vikings Free                 0x0000000106653fde __52-[MKStoreManager buyFeature:onComplete:onCancelled:]_block_invoke + 526
    5   Chubby Vikings Free                 0x00000001065ac2ae +[MKSKProduct verifyProductForReviewAccess:onComplete:onError:] + 174
    6   Chubby Vikings Free                 0x0000000106653d46 -[MKStoreManager buyFeature:onComplete:onCancelled:] + 502
    7   Chubby Vikings Free                 0x00000001065d5a79 -[DBPurchaseManager makePurchase:onComplete:onCancel:] + 313
    8   Chubby Vikings Free                 0x00000001065e1fd1 -[vShopCoinsPopup clickCoinsPack1:] + 225
    9   CoreFoundation                      0x000000010b75d85c __invoking___ + 140
    10  CoreFoundation                      0x000000010b75d6ae -[NSInvocation invoke] + 286
    11  Chubby Vikings Free                 0x00000001066a0773 -[CCMenuItem activate] + 67
    12  Chubby Vikings Free                 0x000000010669d80e -[CCMenu ccTouchEnded:withEvent:] + 286
    13  Chubby Vikings Free                 0x00000001066edfae -[CCTouchDispatcher touches:withEvent:withTouchType:] + 1598
    14  Chubby Vikings Free                 0x00000001066eea3e -[CCTouchDispatcher touchesEnded:withEvent:] + 78
    15  Chubby Vikings Free                 0x0000000106670a64 -[CCTouchView touchesEnded:withEvent:] + 84
    16  UIKit                               0x0000000108b67aa3 -[UIWindow _sendTouchesForEvent:] + 835
    17  UIKit                               0x0000000108b68691 -[UIWindow sendEvent:] + 865
    18  UIKit                               0x0000000108b1a752 -[UIApplication sendEvent:] + 263
    19  UIKit                               0x0000000108af5fcc _UIApplicationHandleEventQueue + 6693
    20  CoreFoundation                      0x000000010b79b0a1 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    21  CoreFoundation                      0x000000010b790fcc __CFRunLoopDoSources0 + 556
    22  CoreFoundation                      0x000000010b790483 __CFRunLoopRun + 867
    23  CoreFoundation                      0x000000010b78fe98 CFRunLoopRunSpecific + 488
    24  GraphicsServices                    0x000000010dabbad2 GSEventRunModal + 161
    25  UIKit                               0x0000000108afb676 UIApplicationMain + 171
    26  Chubby Vikings Free                 0x00000001065977c4 main + 100
    27  libdyld.dylib                       0x000000010bd5292d start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)

A: The size of the array is zero. So, You tried to call [array objectAtIndex:0]. 0 is beyond the bounds of an empty array (not surprising – anything is beyond the bounds for an empty array).


text:
Q: Array ( [0] => Array ... problems extracting array values I am trying to run a function that gets information from a DB and returns an array of the values, so I can then extract it on the page.
Inside the function, after my query I have the following code:
$example_array = array();
while ($row = mysql_fetch_assoc($query) {
    $example_array[] = $row;
}
return $example_array;

And there ends my function. Outside of it, I have this:
extract($example_array);

And I would assume I could then directly echo any of the variables that were previously in $example_array, e.g. <?= $example_var ?> but they do not contain any data.
Running print_r($example_array); gives an array that looks like this:
Array ( [0] => Array ( [example_var] => Example String ) )

The start of that code makes me think my array is somehow "lost" inside another array's first ([0]) value, and as such is not extracting correctly.
Have I gone about adding data to that initial $example_array incorrectly?

A: The issue is that mysql_fetch_array would have meant $row['row_name'] was valid.
As you added $row to the array $example_array, you now need to access it via it's array id too, such as;
$example_array[0]['row_name'], $example_array[1]['row_name'] etc.
What exactly are you trying to achieve? May be easier to offer assistance if we know.

A: Maybe :
$example_array = array();
while ($row = mysql_fetch_assoc($query) {
    array_push($example_array, $row['exemple_var']);
}
return $example_array;

A: When you do $example_array[] = $row;, you assign the current row to a new index of $example_array. If you want to access it like $example_array['row_name'], you'd have to assign it like this:
$example_array = $row;

But when you do this, $example_array will be overwritten until it has reached the last row (which means that $example_array will always contain the last row from the query). If you just want the first row, you can do this and skip the whole while loop:
$example_array = mysql_fetch_assoc($query);


text:
Q: Client gets disconnected from the server after sending data I am creating a client-server remote screenshot capture application. I can successfully exchange screenshots between the server and the client. But the client gets disconnected from the server as soon as it captures and sends the screenshot to the server. I want the client to stay connected after capturing a screenshot. I am quite a newbie to java input/outout and also network programming. Can anyone help me by pointing out mistake?
Here is the complete code for client. If the code for the server is also required to solve this problem I will upload my server code also.
CLIENT
public class ScreenClient {

    public static void main(String[] args) throws Exception {
        Robot robot = new Robot();
        BufferedImage screen;
        Socket server = new Socket("localhost", 5494);
        BufferedReader bf = new BufferedReader(new InputStreamReader(server.getInputStream()));
        String s;
        s = bf.readLine();

        System.out.println(s);

        if (s.contains("execute")) {
            Rectangle size = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());

            screen = robot.createScreenCapture(size);

            int[] rgbData = new int[(int) (size.getWidth() * size.getHeight())];

            screen.getRGB(0, 0, (int) size.getWidth(), (int) size.getHeight(), rgbData, 0, (int) size.getWidth());

            OutputStream baseOut = server.getOutputStream();

            ObjectOutputStream out = new ObjectOutputStream(baseOut);

            out.writeObject(size);

            for (int x = 0; x < rgbData.length; x++) {

                out.writeInt(rgbData[x]);

            }

            out.flush();
        }
    }
}

SERVER
public class ScreenServer extends JFrame implements ActionListener {

    String uname;
    BufferedReader br;
    static JTextArea taMessages, taUserList;
    JTextField tfInput;
    static Socket client;//
    JButton btnCapture, btnExit, btnGetUsers;
    static ArrayList<String> users = new ArrayList();
    PrintWriter os;

    public static void main(String[] args) throws Exception {

        Robot robot = new Robot();

        BufferedImage screen;
        ScreenServer screenServer = new ScreenServer();
        screenServer.buildInterface();
        ServerSocket server = new ServerSocket(5494);
        while (true) {

            client = server.accept();
            users.add(client.getInetAddress().getHostName());
            InetAddress inet1 = client.getInetAddress();

            broadcast(inet1.getHostName(), " Has connected!");

            ObjectInputStream in = new ObjectInputStream(client.getInputStream());

            Rectangle size = (Rectangle) in.readObject();

            int[] rgbData = new int[(int) (size.getWidth() * size.getHeight())];

            for (int x = 0; x < rgbData.length; x++) {

                rgbData[x] = in.readInt();

            }

            screen = new BufferedImage((int) size.getWidth(), (int) size.getHeight(), BufferedImage.TYPE_INT_ARGB);

            screen.setRGB(0, 0, (int) size.getWidth(), (int) size.getHeight(), rgbData, 0, (int) size.getWidth());
            InetAddress clientAddress = client.getInetAddress();
            String clientName = clientAddress.getHostName();
            String t = (new Date()).toString();
            ImageIO.write(screen, "png", new File(clientName + ".png"));
        }

    }

    public void buildInterface() {
        btnCapture = new JButton("Capture Screen");
        btnExit = new JButton("Exit");
        btnGetUsers = new JButton("Get Users");

        //chat area
        taMessages = new JTextArea();
        taMessages.setRows(10);
        taMessages.setColumns(50);
        taMessages.setEditable(false);
        //online users list
        taUserList = new JTextArea();
        taUserList.setRows(10);
        taUserList.setColumns(10);
        taUserList.setEditable(false);
        //top panel (chat area and online users list
        JScrollPane chatPanel = new JScrollPane(taMessages, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        JScrollPane onlineUsersPanel = new JScrollPane(taUserList, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        JPanel tp = new JPanel(new FlowLayout());
        tp.add(chatPanel);
        tp.add(onlineUsersPanel);
        add(tp, "Center");
        //user input field
        tfInput = new JTextField(50);
        //buttom panel (input field, send and exit)
        JPanel bp = new JPanel(new FlowLayout());
        bp.add(tfInput);
        bp.add(btnCapture);
        bp.add(btnExit);
        bp.add(btnGetUsers);

        add(bp, "South");
        btnCapture.addActionListener(this);
        tfInput.addActionListener(this);//allow user to press Enter key in order to send message
        btnExit.addActionListener(this);
        btnGetUsers.addActionListener(this);

        setSize(500, 300);
        setVisible(true);
        pack();
    }

    @Override
    public void actionPerformed(ActionEvent evt) {

        if (evt.getSource() == btnExit) {
            taMessages.setText(this.client + " has disconnected");
            users.remove(this.client);

            System.exit(0);
        } else if (tfInput.getText().contains("!getusers")) {
            taUserList.setText(" ");
            this.getUsersOnline();

        } else if (evt.getSource() == btnCapture) {
            MessagesThread mt=new MessagesThread(client);
           mt.start();
        }

        if (evt.getSource() == btnGetUsers) {
            taUserList.setText("");
            try {
                // putUserOnline(this.client.getInetAddress().getHostName());
                getUsersOnline();
            } catch (NullPointerException nl) {
                System.out.println("ERROR--> No Client Connection Found");
            }
        }
    }

    private void getUsersOnline() {
        for (String s : users) {
            putUserOnline(s);
        }

    }

    public static void broadcast(String user, String message) {
        // send message to all connected users
        putMessage(user, message);

    }

    public static void putMessage(String uname, String msg) {
        taMessages.append(uname + ": " + msg + "\n");
    }

    public static void putUserOnline(String name) {
        taUserList.setText(name + ": " + "\n");
    }

    public class MessagesThread extends Thread {

        Socket client;

        public MessagesThread(Socket client) {
            this.client = client;
        }

        @Override
        public void run() {
            String ClientName = tfInput.getText();
            try {
                String response = "execute";
                if (users.contains(ClientName)) {

                    os = new PrintWriter(client.getOutputStream(), true);
                    os.println(response);

                }
            } catch (IOException ex) {
                Logger.getLogger(ScreenServer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}


text:
Q: Assigning the Result of a BASH Command to a Variable I'm trying to execute the following command inside of a BASH script and I've tried all of the reasonable permutations of $(), ${}, and `` that I can think of but I just haven't been able to get it to work.  I'd like to assign the result of this command to a variable:
"scale=2; $var1/$var2" | bc
Thank you in advance for your time and help.

A: You need to echo the commands into bc, like this:
var=$(echo "scale=2; $var1/$var2" | bc)

Or, as suggested in the comments (thanks!) and you're using BASH, you could use <<< instead:
var=$(bc <<< "scale=2; $var1/$var2")

While we're at it, you could also use a here document:
var=$(bc << EOF
scale=2; $var1/$var2
EOF
)

Here's a test showing that they all do the same thing:
var1=10
var2=2
out1=$(echo "scale=2; $var1/$var2" | bc)
out2=$(bc <<< "scale=2; $var1/$var2")
out3=$(bc << EOF
scale=2; $var1/$var2
EOF
)
echo "$out1 $out2 $out3"

output: 5.00 5.00 5.00


text:
Q: Как сделать обратный перенос в CSS flex? Я хочу сделать вот так:

Но у меня получается вот так:

Вот код:

div {
    display: flex;
    flex-wrap: wrap;
}
aside {
    height: 300px;
    flex: 1 1 24vw;
    min-width: 225px;
    background-color: #dddddd;
}
aside:nth-child(even) {
    background-color: #838383;
}

A:


text:
Q: What is the proper term for a moderate-size artificial stone-clad elevation? In Paris, as you walk along the Quai Francois Mitterrand, one option is to go down the steps to the paved riverside pedestrian path (where cars are allowed only in movies).
It is a quaint little space between the two bridges (the Pont Neuf and the Pont de Beaux Arts).
You can continue along the edge or you could opt for climbing the stone-clad elevation with the sloping sides (alternatively, you can walk along the bottom of the elevation and run up those steps in the middle), and sit on the bench in the shadow of the tree.
In the photo, there are two red arrows pointing at the elevation.
Is there a proper term for this kind of ... structure, or whatever it is? Something like an "urban hillock" or some such? Or something more architectural-sounding?

A: This is an embankment.

(Cambridge Dictionary) an artificial slope made of earth and/or stones:
a river/road/railway embankment

The particular one shown by the Seine is but one among many possibilities along the same principle.
You will find here a great variety of constructions of that type.

A69-Haltwhistle-highway-embankment-western-end

Embankments


text:
Q: Using InheritableThreadLocal with ThreadPoolExecutor -- or -- a ThreadPoolExecutor that doesn't reuse threads I am trying to use both InheritableThreadLocal and a ThreadPoolExecutor.
This breaks down because ThreadPoolExecutor reuses threads for each pool (it is a pool, after all), meaning the InheritableThreadLocal doesn't work as expected. Now the problem seems obvious to me, but it was particularly snarly to track down.
I use InheritableThreadLocal so that each of several top-level processes has its own database connection for itself and any sub-processes it spawns. I don't just use one shared connection pool because each top-level process will do a lot of multi-step work with its connection before committing to the database and/or preparing a lot of PreparedStatements that are used over and over.
I use a shared ThreadPoolExecutor between these top-level processes because there are certain behaviors that need to be gated. e.g. Even though I might have 4 top-level processes running, I can only have any one process writing to the database at a time (or the system needs to gate on some other shared resource). So I'll have the top-level process create a Runnable and send it to the shared ThreadPoolExecutor to make sure that no more than one (or two or three as the case may be) are running at the same time across the entire system.
The problem is that because the ThreadPoolExecutor reuses its threads for the pools, the  InheritableThreadLocal is picking up the original value that was run in that pool rather than the value that was in the top-level process which sent the Runnable to the ThreadPoolExecutor.

*

*Is there any way to force the worker pool in the ThreadPoolExecutor to use the InheritableThreadLocal value that was in the context of the process which created the Runnable rather than in the context of the reused thread pool?

*Alternatively, is there any implementation of ThreadPoolExecutor that creates a new thread each time it starts a new Runnable? For my purposes I only care about gating the number of simultaneously running threads to a fixed size.

*Is there any other solution or suggestion people have for me to accomplish what I've described above?
(While I realize I could solve the problem by passing around the database connection from class to class to subthread to subthread like some kind of community bicycle, I'd like to avoid this.)
There is a previous question on StackOverflow, InheritableThreadLocal and thread pools, that addresses this issue as well. However, the solution to that problem seems to be that it's a poor use case for InheritableThreadLocal, which I do not think applies to my situation.
Thanks for any ideas.

A: using InheritedThreadLocal is almost surely wrong. Probably you'd have not asked the question if you can fit that bizarre tool.
First and foremost it's horribly leak-prone and often the value(s) escapes in some totally strange threads.
As for the Runnable being associate w/ a context.
Override publicvoid execute(Runnable command) of the ExecutorPool and wrap the Runnable withing some context carrying the value you want in the first place from the InheritedThreadLocal.
The wrapping class shall look something like
class WrappedRunnable extends Runnable{
  static final ThreadLocal<Ctx> context=new ThreadLocal<Ctx>();
  final Runnable target;
  final Ctx context;
  WrappedRunnable(Ctx context, Runnable target){...}

  public void run(){
    ctx.set(context);
    try{
      target.run();
    }finally{
      ctx.set(null);//or ctx.remove()
    }
  }
}

Alternatively, is there any implementation of ThreadPoolExecutor that creates a new >thread each time it starts a new Runnable? For my purposes I only care about gating the >number of simultaneously running threads to a fixed size.

While truly bad from performance point of view, you can implement your own, basically you need only execute(Runnable task) method for the Executor that spawns new thread and starts it.

A: Instead of using a ThreadPoolExecutor to protect shared resources, why not use a java.util.concurrent.Semaphore? The sub tasks you create would run to completion in their own threads, but only after having acquired a permit from the semaphore, and of course releasing the permit when done.

A: We had the same issue earlier and we solved this issue by writing ThreadLocalContextMigrator which basically copies the thread local context to the task that will be executed using a thread from the pool. The Task, while executing will collect more context info and upon completion of the task we copy it back.

A: Why not just pass the current connection on to any sub-tasks spawned by the main task?  maybe some sort of shared Context object?


text:
Q: Problem with React-Bootstrap/InputGroup caused by  I have been encountering a problem that I didn't have before.
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
I have a Searchbar.jsx component in my React that I export and then I import it in my Navigation.jsx component. The Searchbar component looks like this:
import { useHistory } from 'react-router-dom';
import { useState } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faSearch } from '@fortawesome/free-solid-svg-icons';
import Form from 'react-bootstrap/Form';
import { Collapse, InputGroup } from 'react-bootstrap';
import Button from 'react-bootstrap/Button';
import './Searchbar.scss';

export default function Searchbar() {
  const history = useHistory();
  const [searchQuery, setSearchQuery] = useState('');
  const [open, setOpen] = useState(false);

  const onSubmit = (e) => {
    history.push(`/dashboard/?s=${searchQuery}`);
    e.preventDefault();
  };

  return (
    <Form className="d-inline-block" bsPrefix="form" onSubmit={onSubmit}>
      <InputGroup>
        <InputGroup.Prepend>
          <Button
            variant=""
            id="button-addon1"
            onClick={searchQuery.length < 1 ? () => setOpen(!open) : onSubmit}
          >
            <FontAwesomeIcon icon={faSearch} className="searchIcon" />
          </Button>
        </InputGroup.Prepend>
        <Collapse in={open} className="collapse d-sm-block">
          <Form.Control
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            type="text"
            id="header-search"
            placeholder="Search..."
            name="s"
            className="border border-secondary"
          />
        </Collapse>
      </InputGroup>
    </Form>
  );
}

This is how I import it later in my Navigation.jsx:
    import Searchbar from './Searchbar/Searchbar';
    /*...
    ...
    a bunch of code
    ...
    ... */

      return (
        <>
          <Navbar bg="white" className="mb-3 px-3" bsPrefix="navbar">
            <Container className="justify-content-start d-flex-inline col-9 col-sm-6">
              <Navbar.Brand href="/dashboard">
                <img style={{ width: '100px' }} src={logo} alt="Logo" />
              </Navbar.Brand>
            </Container>
            <Searchbar />
        <>

I have made sure that export and import stuff the correct way.
As you can see I use React-Bootstrap/InputGroup and the problem seems to be caused by <InputGroup.Prepend> tag because as soon as I remove it, the error disappears.
What is more weird is that I don't get this error when I run it on my laptop despite it being the same exact code. So naturally I thought that is might be caused by different versions of react-bootstrap or, react-router-dom or even google chrome but I checked all of those and they are the same across my stationary computer and laptop. I get the same error across different web browsers on my stationary as well. I am really lost and I don't know how to solve this issue.
Any help or guidance will be appreciated.
// I just updated node version on my laptop and then yarn install in my web-app folder and now I'm getting the same error on my laptop as well. Could this be an issue with node or react-bootstap or react-router-dom? In that case what can I do?
//edit I have include my package.json
{
  "name": "profet-web-app",
  "version": "0.1.0",
  "private": true,
  "proxy": "https://localhost:5001",
  "dependencies": {
    "@emotion/react": "^11.9.3",
    "@emotion/styled": "^11.9.3",
    "@fortawesome/fontawesome-svg-core": "^1.2.36",
    "@fortawesome/free-solid-svg-icons": "^5.15.4",
    "@fortawesome/react-fontawesome": "^0.1.17",
    "@mui/material": "^5.8.7",
    "@testing-library/jest-dom": "^5.11.9",
    "@testing-library/react": "^11.2.5",
    "@testing-library/user-event": "^12.6.3",
    "@types/jest": "^27.4.1",
    "@types/node": "^17.0.23",
    "@types/react": "^18.0.2",
    "@types/react-dom": "^18.0.0",
    "axios": "^0.21.1",
    "bootstrap": "^5.2.0",
    "chart.js": "^3.7.1",
    "jwt-decode": "^3.1.2",
    "moment": "^2.29.1",
    "nodemon": "^2.0.7",
    "react": "^17.0.1",
    "react-bootstrap": "^2.5.0",
    "react-chartjs-2": "^4.0.1",
    "react-dom": "^17.0.1",
    "react-ga": "^3.3.0",
    "react-icons": "^4.3.1",
    "react-number-format": "^4.4.4",
    "react-responsive": "^9.0.0-beta.6",
    "react-router-bootstrap": "^0.26.2",
    "react-router-dom": "^5.2.0",
    "react-router-hash-link": "^2.4.3",
    "react-scripts": "^5.0.0",
    "swiper": "^8.0.7",
    "typescript": "^4.6.3",
    "validator": "^13.7.0",
    "web-vitals": "^1.1.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "lint": "eslint .",
    "lint:fix": "eslint --fix ."
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@types/react-router-dom": "^5.2.0",
    "@typescript-eslint/eslint-plugin": "^5.19.0",
    "@typescript-eslint/parser": "^5.19.0",
    "eslint": "^8.13.0",
    "eslint-config-airbnb": "^19.0.4",
    "eslint-config-airbnb-typescript": "^17.0.0",
    "eslint-config-prettier": "^8.5.0",
    "eslint-plugin-import": "^2.26.0",
    "eslint-plugin-jsx-a11y": "^6.5.1",
    "eslint-plugin-prettier": "^4.0.0",
    "eslint-plugin-react": "^7.29.4",
    "eslint-plugin-react-hooks": "^4.4.0",
    "prettier": "^2.6.2",
    "sass": "^1.39.0"
  }
}

A: I think I found why this happens.
I went through react bootstrap documentation and found this:
dropped InputGroupPrepend and InputGroupAppend. Buttons and InputGroupText can now be added as direct children.
Link:https://react-bootstrap.netlify.app/migrating/#inputgroup


text:
Q: App "lost property office" with ViewPager, Fragment, ListView, JSON I'm doing a lost property office application. It consists of four tabs, each tab must display announcement feed uploaded by users. By clicking on a particular item opens a new activity to derive more information.(Well, sort of news feed). I take the data from the API site in the form of JSON.
    I did four tabs using ViewPager, Fragment. image my fragments
    I have tried to place every Fragment listview and display their data with JSON with AsynTask. And caused AsyncTask for  each fragment also called the same JSON in the first fragment. May be it is not right.
    So, please tell me the correct move.

*

*What used to for display data into listview from json

*How to display information on a new activity that opens when you press the listview item?

*Send to fragment over the intent or download a JSON again?

*How to realize adding ads by user?
If possible, write the steps. Thank you very much, I will be glad of any help.
P.S Sorry for bad English

A: First of all you can use a simple list adapter to be able to put JSON data into a listview, you can see a tutorial of this here.
Second to be able to see details about a item in a list view you can use a onListItemClick, with extending ListActivity. An example of doing this would be:
MyListActivity.java
public class MyListActivity extends ListActivity {
// . . .

    protected void onListItemClick(ListView l, View v, int position, long id) {
         //handle the list click here
         intent = new Intent(this, ListDetails.class);
         //convert the position int into a string to pass to the intent
         value = String.valueOf(position);
         //put the value into the intent
         intent.putExtra("key", value);
         //start the activity here
         MyListActivity.this.startActivity(intent);
     }
}

ListDetails.java
public class ListDetails extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         //gets the value sent with the intent
         Intent intent = getIntent();
         final String helpView = intent.getStringExtra("key");
         // . . .
}

This is assuming that you are using a ListActivity to make the list and it really depends on what sort of information you want to display, if you want to display all the data, you could pass the JSON data as a string through the intent, then get it like in the example above.
Thirdly if you want to keep the JSON data you can just pass it along with the intent and then when the user presses back, just pass it back to the original activity once again through the intent. If you want to re-download the JSON data, you can, but to save with users mobile internet connection going over (especially for large JSON files repeatedly), in would not recommend using this option. If you want to download the JSON data again, you will need to use a AsyncTask to download the data, so not to disrupt the user interface and that it will raise a error when you try to do this (believe me, I have pulled my hair out over this). A example of a AsyncTask is (from the android project I am working on, that uses google maps to calculate a route):
private class ReadTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... url) {
        String data = "";
        try {
            HttpConnection http = new HttpConnection();
            data = http.readUrl(url[0]);
        } catch (Exception e) {
            Log.d("Background Task", e.toString());
        }
        return data;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        Log.i("Log","Parser Task Started");
        Log.i("Log",result);
        new ParserTask().execute(result);
    }
}

private class ParserTask extends
        AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {

    @Override
    protected List<List<HashMap<String, String>>> doInBackground(
            String... jsonData) {

        JSONObject jObject;
        List<List<HashMap<String, String>>> routes = null;

        try {
            jObject = new JSONObject(jsonData[0]);
            PathJSONParser parser = new PathJSONParser();
            routes = parser.parse(jObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return routes;
    }

    @Override
    protected void onPostExecute(List<List<HashMap<String, String>>> routes) {
        //process the JSON data here
    }
}

You would place this inside a activity, adding in the necessary processing for the JSON data inside the onPostExecute in ParserTask. To download the JSON data, you would call (replacing the url with your url for getting the JSON data):
String url = "http://www.example.com"
ReadTask downloadTask = new ReadTask();
downloadTask.execute(url);

EDIT:
Lastly to show the latest or most important/relevant lost property adverts, you can once again use JSON to get this from your backend website. In PHP you can customise server responses, sending back JSON responses depending on values in the GET (?thisIsTheGet=blahblahblah). To add advertisements you can create a seperate activity, with EditTexts etc, to create a form, then send the data through a GET request to your backend server (where the JSON is held), so the server can update the advertisement list. Once again you can use a AsyncTask to send the GET request to the server, perhaps using methods above to send back from the server the success of the adding of the advertisement. A example of what your form could look like (XML) would be:
activity_add_advertisement.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="your.activity.class.root.activityAddAdvertisement"
    tools:showIn="@layout/activity_add_advertisement"
    android:id="@+id/LLMainContent"
    android:orientation="vertical"
    >
    <EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/edittext1"/>
    <EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/edittext2"/>
    <Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/submitButton"/>
</LinearLayout>

Then set a on click listener for the button being pressed inside the activity:
activityAddAdvertisement.java
public class activityAddAdvertisement {
    // . . .
    Button submitButton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // . . .
        submitButton = (Button) findViewById(R.id.submitButton);
        submitButton.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View view) {
                   //call the methods from above to send a request to a url, with the contents of the edit texts in the GET request
              }
    }
}

You can add more EditTexts and other elements and inside the contents inside the GET request. The server will then edit the JSON to include the new advertisements. The PHP won't be too hard, if you need some tutorials on PHP, W3Schools has good tutorials and examples for you to use.
Further Reading:
Android Intents


text:
Q: How to change a text file into a list? I already know how to get a text file into python but...I now want to turn that file into a list.
My file:
1
2
3

My code:
file = open("File.txt", "r")
file = list(file)

Is there a way to actually make it into something that works? And if you find an answer please make it simple.

A: EDIT
My final solution.
Thanks to @juanpa.arrivillaga for the hint that the intermediate iterator-operation is not necessary
map(str.strip, open('asd.txt'))

Or if you like it more, then this:
[x.strip() for x in open('File.txt')]

A: $ echo -e "one\ntwo\nthree" > /tmp/list.txt
$ cat /tmp/list.txt
one
two
three
$ python -c "fh = open('/tmp/list.txt'); print(fh.readlines())"
['one\n', 'two\n', 'three\n']

A: Try this:
f = open('filename.txt').readlines()
f = [int(i.strip('\n')) for i in f]

print(f)

A: you could use numpy's loadtxt if your entries are numbers
import numpy as np
data = np.loadtxt('test.txt')