问:
How connect Postgresql database with sqlalchemy python
I'm currently writing an program using Flask python. But I can not connect my database with my program. I'm use Postgresql for database.

```<code>import os

from sqlalchemy import create_engine

from sqlalchemy.orm import scoped_session, sessionmaker

engine = create_engine(os.getenv("DATABASE_URI"))

db = scoped_session(sessionmaker(bind=engine))
</code>```

This is the code what I'm using for it, But it didn't work. So please help me to connect my database

This is the error message that what I have got,
Error message

答:
db.py File which contains db connection(postgres url)

```<code>from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://postgres:postgres@localhost/DB_NAME'

db = SQLAlchemy(app)
</code>```

app.py This is your main file database tables will create when your server hits the first request.

```<code>from db import *
@app.before_first_request
def before():
    db.create_all()

enter code here......

</code>```

table_structure.py This file contains your table structure

```<code>from db import db
class UserProjects(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(140), nullable=False)

</code>```

Body:
I'm currently writing an program using Flask python. But I can not connect my database with my program. I'm use Postgresql for database.

import os

from sqlalchemy import create_engine

from sqlalchemy.orm import scoped_session, sessionmaker

engine = create_engine(os.getenv("DATABASE_URI"))

db = scoped_session(sessionmaker(bind=engine))

This is the code what I'm using for it, But it didn't work. So please help me to connect my database

This is the error message that what I have got,
Error message

Body:
db.py File which contains db connection(postgres url)

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://postgres:postgres@localhost/DB_NAME'

db = SQLAlchemy(app)

app.py This is your main file database tables will create when your server hits the first request.

from db import *
@app.before_first_request
def before():
    db.create_all()

enter code here......

table_structure.py This file contains your table structure

from db import db
class UserProjects(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(140), nullable=False)


来源: stackexchange

问:
Unable to write to AWS ClouldWatch from docker container
I'm running a .net core application in a windows container where it uses AWS SDK to connect to ClouldWatch. I have used Serilog.Sink.AWSCloudWatch for this integration.

CloudWatch integration works when I run it from my host machine however I'm getting below exception when I tried that from a windows docker container. As I am new to dockers, would you be able to help me to solve this issue.

```<code> Error initializing log stream. No logs will be sent to AWS CloudWatch. Exception was System.Net.Http.HttpRequestException: No such host is known.
 ---> System.Net.Sockets.SocketException (11001): No such host is known.
   at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean allowHttp2, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.GetHttpConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
   at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Net.Http.HttpClient.FinishSendAsyncUnbuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
   at Amazon.Runtime.HttpWebRequestMessage.GetResponseAsync(CancellationToken cancellationToken)
   at Amazon.Runtime.Internal.HttpHandler`1.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.Unmarshaller.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.ErrorHandler.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.CallbackHandler.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.EndpointDiscoveryHandler.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.EndpointDiscoveryHandler.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.CredentialsRetriever.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.RetryHandler.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.RetryHandler.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.CallbackHandler.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.CallbackHandler.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.ErrorCallbackHandler.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.MetricsHandler.InvokeAsync[T](IExecutionContext executionContext)
   at Serilog.Sinks.AwsCloudWatch.CloudWatchLogSink.CreateLogGroupAsync()
   at Serilog.Sinks.AwsCloudWatch.CloudWatchLogSink.EnsureInitializedAsync()
   at Serilog.Sinks.AwsCloudWatch.CloudWatchLogSink.EmitBatchAsync(IEnumerable`1 events).
</code>```

Docker file,

```<code>ROM mcr.microsoft.com/dotnet/core/runtime:3.1-nanoserver-1903 AS base
WORKDIR /app

FROM mcr.microsoft.com/dotnet/core/sdk:3.1-nanoserver-1903 AS build
WORKDIR /src
COPY *.sln .
COPY MyProject/*.csproj ./MyProject/
RUN dotnet restore

# copy full solution over
COPY . .
RUN dotnet build

FROM build AS release
WORKDIR "/src/MyProject"
RUN dotnet build "MyProject.csproj" -c Release -o /app/build

FROM build AS publish
WORKDIR "/src/MyProject"
RUN dotnet publish "MyProject.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /Users/ContainerUser/.aws
COPY credentials .

WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "MyProject.dll"]
</code>```

Thanks

答: Actual issue was I was running the application with vpn on, so https request was rejected by the vpn. I managed to solve this without vpn.</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm running a .net core application in a windows container where it uses AWS SDK to connect to ClouldWatch. I have used Serilog.Sink.AWSCloudWatch for this integration.

CloudWatch integration works when I run it from my host machine however I'm getting below exception when I tried that from a windows docker container. As I am new to dockers, would you be able to help me to solve this issue.

 Error initializing log stream. No logs will be sent to AWS CloudWatch. Exception was System.Net.Http.HttpRequestException: No such host is known.
 ---> System.Net.Sockets.SocketException (11001): No such host is known.
   at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean allowHttp2, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.GetHttpConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
   at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Net.Http.HttpClient.FinishSendAsyncUnbuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
   at Amazon.Runtime.HttpWebRequestMessage.GetResponseAsync(CancellationToken cancellationToken)
   at Amazon.Runtime.Internal.HttpHandler`1.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.Unmarshaller.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.ErrorHandler.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.CallbackHandler.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.EndpointDiscoveryHandler.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.EndpointDiscoveryHandler.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.CredentialsRetriever.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.RetryHandler.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.RetryHandler.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.CallbackHandler.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.CallbackHandler.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.ErrorCallbackHandler.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.MetricsHandler.InvokeAsync[T](IExecutionContext executionContext)
   at Serilog.Sinks.AwsCloudWatch.CloudWatchLogSink.CreateLogGroupAsync()
   at Serilog.Sinks.AwsCloudWatch.CloudWatchLogSink.EnsureInitializedAsync()
   at Serilog.Sinks.AwsCloudWatch.CloudWatchLogSink.EmitBatchAsync(IEnumerable`1 events).

Docker file,

ROM mcr.microsoft.com/dotnet/core/runtime:3.1-nanoserver-1903 AS base
WORKDIR /app

FROM mcr.microsoft.com/dotnet/core/sdk:3.1-nanoserver-1903 AS build
WORKDIR /src
COPY *.sln .
COPY MyProject/*.csproj ./MyProject/
RUN dotnet restore

# copy full solution over
COPY . .
RUN dotnet build

FROM build AS release
WORKDIR "/src/MyProject"
RUN dotnet build "MyProject.csproj" -c Release -o /app/build

FROM build AS publish
WORKDIR "/src/MyProject"
RUN dotnet publish "MyProject.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /Users/ContainerUser/.aws
COPY credentials .

WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "MyProject.dll"]

Thanks


问:
Streaming huge json with Akka Stream
I have a problem of huge http response with a json slab, where only portion is point of interest.
I cannot change the response structure.
here is an example

```<code>{
  "searchString": "search",
  "redirectUrl": "",
  "0": {
    "numRecords": 123,
    "refinementViewModelCollector": {},
//    Lots of data here
    "results": [
      {
        "productCode": "123",
        "productShortDescription": "Desc",
        "brand": "Brand",
        "productReview": {
          "reviewScore": 0
        },
        "priceView": {
          "salePriceDisplayable": false,
        },
        "productImageUrl": "url",
        "alternateImageUrls": [
          "url1"
        ],
        "largeProductImageUrl": "url4",
        "videoUrl": ""
      },
      {
        "productCode": "124",
        "productShortDescription": "Desc",
        "brand": "Brand",
        "productReview": {
          "reviewScore": 0
         },
        "priceView": {
          "salePriceDisplayable": false,
        },
        "preOrder": false,
        "productImageUrl": "url",
        "alternateImageUrls": [
          "url1"
        ],
        "largeProductImageUrl": "url4",
        "videoUrl": ""
      }
    ]
    //lots of data here
  }
}
</code>```

My point of interest is entries in results Jason Array, but the are sitting in the middle of json

I created a small Play WS Client like this:

```<code>val wsClient: WSClient = ???
val ret = wsClient.url("url").stream()
ret.flatMap { response =>
  response.body.via(JsonFraming.objectScanner(1024))
    .map(_.utf8String)
    .runWith(Sink.foreach(println))
}
</code>```

this will not work because it will take whole json slab as Json object. I need to skip some data until "results": entry appear in the stream, then start parsing entries and skip all the rest.
Any ideas how to do this?

答:
Check out Alpakka's JSON module, which can stream specific parts of a nested JSON structure:</p>

```<code>response
  .body
  .via(JsonReader.select("$.0.results[*]"))
  .map(_.utf8String)
  .runWith(Sink.foreach(println)) // or runForeach(println)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Streaming huge json with Akka Stream

Body:
I have a problem of huge http response with a json slab, where only portion is point of interest.
I cannot change the response structure.
here is an example

{
  "searchString": "search",
  "redirectUrl": "",
  "0": {
    "numRecords": 123,
    "refinementViewModelCollector": {},
//    Lots of data here
    "results": [
      {
        "productCode": "123",
        "productShortDescription": "Desc",
        "brand": "Brand",
        "productReview": {
          "reviewScore": 0
        },
        "priceView": {
          "salePriceDisplayable": false,
        },
        "productImageUrl": "url",
        "alternateImageUrls": [
          "url1"
        ],
        "largeProductImageUrl": "url4",
        "videoUrl": ""
      },
      {
        "productCode": "124",
        "productShortDescription": "Desc",
        "brand": "Brand",
        "productReview": {
          "reviewScore": 0
         },
        "priceView": {
          "salePriceDisplayable": false,
        },
        "preOrder": false,
        "productImageUrl": "url",
        "alternateImageUrls": [
          "url1"
        ],
        "largeProductImageUrl": "url4",
        "videoUrl": ""
      }
    ]
    //lots of data here
  }
}

My point of interest is entries in results Jason Array, but the are sitting in the middle of json

I created a small Play WS Client like this:

val wsClient: WSClient = ???
val ret = wsClient.url("url").stream()
ret.flatMap { response =>
  response.body.via(JsonFraming.objectScanner(1024))
    .map(_.utf8String)
    .runWith(Sink.foreach(println))
}

this will not work because it will take whole json slab as Json object. I need to skip some data until "results": entry appear in the stream, then start parsing entries and skip all the rest.
Any ideas how to do this?

Body:
Check out Alpakka's JSON module, which can stream specific parts of a nested JSON structure:

response
  .body
  .via(JsonReader.select("$.0.results[*]"))
  .map(_.utf8String)
  .runWith(Sink.foreach(println)) // or runForeach(println)


问:
Uploading image to S3 and then resizing in node.js
I am building a web-site where a user will upload an image and then the image has to ultimately be stored in Amazon S3. Now, given the possibility of uploading directly from browser, I considered the following options:

Resize to all three sizes in the browser and then upload to S3 directly - this works but the problem is that I am uploading multiple images, which I doubt is a good way to this.

Upload the original image to S3, resize in node.js - I was thinking of actually uploading only original image but then using node.js to resize.

What is the best way to do 2) so that I can minimize the footprint of the service I need to deploy.

Appreciate any pointers!

Cheers
Vishal

答:
i suggest using an Image CDN to Speed Up Image Delivery. Check here

Amazon S3 is Slow and Images are Heavy

Amazon S3 is known to be slow when serving web content directly. One
  reason why it is slow is that a bucket is only located in one
  geographical location. The location is selected when you create the
  bucket. For example, if your bucket is created on Amazon servers in
  California, but your users are in India, then images will still be
  served from California. This geographical distance causes slow image
  loading on your website.

Further, it is not uncommon to see very heavy images on S3, with large
  dimensions and high byte size. One can only speculate on the reasons,
  but it is probably related to the publication workflow and the
  convenience of S3 as a storage space.

using image delivery like ImageEngine while keeping S3’s workflow
  and convenience level.

Trust me when I say its very simple to implement...
very very simple I repeat.

Once you do the nessary settings after creating account all you need is to
Reference images using the ImageEngine domain

```<code>http://wq77sh2y.cdn.imgeng.in/path/image.jpg
</code>```

OR

Reference images using the prefixing feature

```<code>http://wq77sh2y.cdn.imgeng.in/http://example.com/path/image.jpeg
</code>```

Body:
i suggest using an Image CDN to Speed Up Image Delivery. Check here

Amazon S3 is Slow and Images are Heavy

Amazon S3 is known to be slow when serving web content directly. One
  reason why it is slow is that a bucket is only located in one
  geographical location. The location is selected when you create the
  bucket. For example, if your bucket is created on Amazon servers in
  California, but your users are in India, then images will still be
  served from California. This geographical distance causes slow image
  loading on your website.

Further, it is not uncommon to see very heavy images on S3, with large
  dimensions and high byte size. One can only speculate on the reasons,
  but it is probably related to the publication workflow and the
  convenience of S3 as a storage space.

using image delivery like ImageEngine while keeping S3’s workflow
  and convenience level.

Trust me when I say its very simple to implement...
very very simple I repeat.

Once you do the nessary settings after creating account all you need is to
Reference images using the ImageEngine domain

http://wq77sh2y.cdn.imgeng.in/path/image.jpg

OR

Reference images using the prefixing feature

http://wq77sh2y.cdn.imgeng.in/http://example.com/path/image.jpeg


问:
Html entity problem in Struts2  tag parameter
Am passing some parameters through  in Struts2, and am getting below error when there is a HTML special Character in parameter value how can i over come this...?

A herf tage used:

```<code><a href="ManufacturerProducts.action?manufId=<s:property value="manufId"/>&mName=<s:property value="manufName"/>"><img src="<s:property value="manufLogo"/>" alt="<s:property value="manufName"/>" /></a>
</code>```

Error:

```<code>12:21:46,034 WARN  [OgnlValueStack] Error setting expression ' A Manufacturing Co' with value '[Ljava.lang.String;@4acc69'
ognl.ExpressionSyntaxException: Malformed OGNL expression:  A Manufacturing Co [ognl.ParseException: Encountered " <IDENT> "Manufacturing "" at line 1, column 4.
Was expecting one of:
    <EOF>
    "," ...
    "=" ...
    "?" ...
    "||" ...
    "or" ...
    "&&" ...
    "and" ...
    "|" ...
    "bor" ...
    "^" ...
    "xor" ...
    "&" ...
    "band" ...
    "==" ...
    "eq" ...
    "!=" ...
    "neq" ...
    "<" ...
    "lt" ...
    ">" ...
    "gt" ...
    "<=" ...
    "lte" ...
    ">=" ...
    "gte" ...
    "in" ...
    "not" ...
    "<<" ...
    "shl" ...
    ">>" ...
    "shr" ...
    ">>>" ...
    "ushr" ...
    "+" ...
    "-" ...
    "*" ...
    "/" ...
    "%" ...
    "instanceof" ...
    "." ...
    "(" ...
    "[" ...
    <DYNAMIC_SUBSCRIPT> ...
    "(" ...
    ]
    at ognl.Ognl.parseExpression(Ognl.java:112)
    at com.opensymphony.xwork2.ognl.OgnlUtil.compile(OgnlUtil.java:225)
    at com.opensymphony.xwork2.ognl.OgnlUtil.setValue(OgnlUtil.java:209)
    at com.opensymphony.xwork2.ognl.OgnlValueStack.trySetValue(OgnlValueStack.java:173)
    at com.opensymphony.xwork2.ognl.OgnlValueStack.setValue(OgnlValueStack.java:160)
    at com.opensymphony.xwork2.ognl.OgnlValueStack.setValue(OgnlValueStack.java:151)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.setParameters(ParametersInterceptor.java:288)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:199)
</code>```

Thank you.

答:
Try

```<code><a href="ManufacturerProducts.action?manufId=<s:property value='manufId'/>&mName=<s:property value='manufName'/>">
    <img src="<s:property value='manufLogo'/>" alt="<s:property value='manufName'/>" />
</a>
</code>```

or

```<code><a href="ManufacturerProducts.action?manufId=${manufId}&mName=${manufName}">
    <img src="${manufLogo}" alt="${manufName}" />
</a>
</code>```

or

```<code><s:url id="urlId" action="ManufacturerProducts.action">
    <s:param name="manufId" value="manufId" />
    <s:param name="mName" value="manufName" />
</s:url>
<a href="${urlId}">
    <img src="${manufLogo}" alt="${manufName}" />
</a>
</code>```

or (better)

```<code><s:a action="ManufacturerProducts.action">
    <s:param name="manufId">${manufId}</s:param>
    <s:param name="mName">${manufName}</s:param>
    <img src="${manufLogo}" alt="${manufName}" />
</s:a>
</code>```

or (better)

```<code><s:a action="ManufacturerProducts.action">
    <s:param name="manufId" value="manufId" />
    <s:param name="mName" value="manufName" />
    <img src="${manufLogo}" alt="${manufName}" />
</s:a>
</code>```

Body:
Am passing some parameters through  in Struts2, and am getting below error when there is a HTML special Character in parameter value how can i over come this...?

A herf tage used:

<a href="ManufacturerProducts.action?manufId=<s:property value="manufId"/>&mName=<s:property value="manufName"/>"><img src="<s:property value="manufLogo"/>" alt="<s:property value="manufName"/>" />

Error:

12:21:46,034 WARN  [OgnlValueStack] Error setting expression ' A Manufacturing Co' with value '[Ljava.lang.String;@4acc69'
ognl.ExpressionSyntaxException: Malformed OGNL expression:  A Manufacturing Co [ognl.ParseException: Encountered " <IDENT> "Manufacturing "" at line 1, column 4.
Was expecting one of:
    <EOF>
    "," ...
    "=" ...
    "?" ...
    "||" ...
    "or" ...
    "&&" ...
    "and" ...
    "|" ...
    "bor" ...
    "^" ...
    "xor" ...
    "&" ...
    "band" ...
    "==" ...
    "eq" ...
    "!=" ...
    "neq" ...
    "<" ...
    "lt" ...
    ">" ...
    "gt" ...
    "<=" ...
    "lte" ...
    ">=" ...
    "gte" ...
    "in" ...
    "not" ...
    "<<" ...
    "shl" ...
    ">>" ...
    "shr" ...
    ">>>" ...
    "ushr" ...
    "+" ...
    "-" ...
    "*" ...
    "/" ...
    "%" ...
    "instanceof" ...
    "." ...
    "(" ...
    "[" ...
    <DYNAMIC_SUBSCRIPT> ...
    "(" ...
    ]
    at ognl.Ognl.parseExpression(Ognl.java:112)
    at com.opensymphony.xwork2.ognl.OgnlUtil.compile(OgnlUtil.java:225)
    at com.opensymphony.xwork2.ognl.OgnlUtil.setValue(OgnlUtil.java:209)
    at com.opensymphony.xwork2.ognl.OgnlValueStack.trySetValue(OgnlValueStack.java:173)
    at com.opensymphony.xwork2.ognl.OgnlValueStack.setValue(OgnlValueStack.java:160)
    at com.opensymphony.xwork2.ognl.OgnlValueStack.setValue(OgnlValueStack.java:151)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.setParameters(ParametersInterceptor.java:288)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:199)

Thank you.

Body:
Try

<a href="ManufacturerProducts.action?manufId=<s:property value='manufId'/>&mName=<s:property value='manufName'/>">
    <img src="<s:property value='manufLogo'/>" alt="<s:property value='manufName'/>" />
</a>

or

<a href="ManufacturerProducts.action?manufId=${manufId}&mName=${manufName}">
    <img src="${manufLogo}" alt="${manufName}" />
</a>

or

<s:url id="urlId" action="ManufacturerProducts.action">
    <s:param name="manufId" value="manufId" />
    <s:param name="mName" value="manufName" />
</s:url>
<a href="${urlId}">
    <img src="${manufLogo}" alt="${manufName}" />
</a>

or (better)

<s:a action="ManufacturerProducts.action">
    <s:param name="manufId">${manufId}</s:param>
    <s:param name="mName">${manufName}</s:param>
    <img src="${manufLogo}" alt="${manufName}" />
</s:a>

or (better)

<s:a action="ManufacturerProducts.action">
    <s:param name="manufId" value="manufId" />
    <s:param name="mName" value="manufName" />
    <img src="${manufLogo}" alt="${manufName}" />
</s:a>


问:
Access-Control-Allow-Origin error on axios request even after enabling express CORS middleware
I am recently deployed my API on Heroku, and I'm having some CORS related issues. I've seen many other posts that  talk about enabling CORS (and I've done that in my code), but whenever I make the axios POST request, I still get the same error: Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin. I've also tried messing around with the configuration object for cors(), but nothing seems to work.

The actual post request from the frontend looks like this:

```<code>const axiosConfig = {
        headers: {
          "Content-Type": "multipart/form-data",
          Accept: "application/json",
        },
      };
  await axios
    .post("https://myapp-backend.herokuapp.com/register", data, axiosConfig)
    .then((_) => Message.success("Successfully registered! "))
    .catch((error) => Message.error(error.message));
</code>```

and my app.js on the backend looks like this.

```<code>const createError = require("http-errors");
const express = require("express");
const path = require("path");
const cookieParser = require("cookie-parser");
const bodyParser = require("body-parser");
const logger = require("morgan");
const multer = require("multer");
const cors = require("cors");

const app = express();
app.use(
  cors({
    allowedHeaders: ["authorization", "Content-Type"], // you can change the headers
    exposedHeaders: ["authorization"], // you can change the headers
    origin: "*",
    methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
    preflightContinue: false,
  })
);

// set up different routers
const indexRouter = require("./routes/index");
const usersRouter = require("./routes/users");
const registrationRouter = require("./registration/routes");
const retailRouter = require("./retail-info/routes");
const bookingRouter = require("./booking/routes");

const port = process.env.PORT || 8080;

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    if (file.originalname.startsWith("CODE_COVER_QLYag759")) {
      cb(null, "temp-storage/cover/");
    } else {
      cb(null, "temp-storage/");
    }
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + path.extname(file.originalname)); //Appending extension
  },
});

const upload = multer({
  // dest: "temp-storage/",
  storage: storage,
  limits: {
    fileSize: 5 * 1024 * 1024, // no larger than 5mb, change as needed.
  },
});

// view engine setup

app.use(logger("dev"));
app.use(express.json());
app.use(bodyParser.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, "public")));

app.use("/", indexRouter);
app.use("/users", usersRouter);
app.use("/register", upload.any(), registrationRouter);
app.use("/retail", retailRouter);
app.use("/booking", bookingRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.json({ error: err.message });
});

app.get("*", (req, res) => {
  res.sendFile(path.resolve(__dirname, "build", "index.html"));
});

app.listen(port, console.log(`MyApp backend started on port ${port}!`));

module.exports = app;
</code>```

I'd really appreciate it if someone could help me out!

答:
You can try adding this before adding your routes</p>

```<code>// every  response we send has these headers
app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE");
  res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
  next();
});

</code>```

Body:
I am recently deployed my API on Heroku, and I'm having some CORS related issues. I've seen many other posts that  talk about enabling CORS (and I've done that in my code), but whenever I make the axios POST request, I still get the same error: Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin. I've also tried messing around with the configuration object for cors(), but nothing seems to work.

The actual post request from the frontend looks like this:

const axiosConfig = {
        headers: {
          "Content-Type": "multipart/form-data",
          Accept: "application/json",
        },
      };
  await axios
    .post("https://myapp-backend.herokuapp.com/register", data, axiosConfig)
    .then((_) => Message.success("Successfully registered! "))
    .catch((error) => Message.error(error.message));

and my app.js on the backend looks like this.

const createError = require("http-errors");
const express = require("express");
const path = require("path");
const cookieParser = require("cookie-parser");
const bodyParser = require("body-parser");
const logger = require("morgan");
const multer = require("multer");
const cors = require("cors");

const app = express();
app.use(
  cors({
    allowedHeaders: ["authorization", "Content-Type"], // you can change the headers
    exposedHeaders: ["authorization"], // you can change the headers
    origin: "*",
    methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
    preflightContinue: false,
  })
);

// set up different routers
const indexRouter = require("./routes/index");
const usersRouter = require("./routes/users");
const registrationRouter = require("./registration/routes");
const retailRouter = require("./retail-info/routes");
const bookingRouter = require("./booking/routes");

const port = process.env.PORT || 8080;

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    if (file.originalname.startsWith("CODE_COVER_QLYag759")) {
      cb(null, "temp-storage/cover/");
    } else {
      cb(null, "temp-storage/");
    }
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + path.extname(file.originalname)); //Appending extension
  },
});

const upload = multer({
  // dest: "temp-storage/",
  storage: storage,
  limits: {
    fileSize: 5 * 1024 * 1024, // no larger than 5mb, change as needed.
  },
});

// view engine setup

app.use(logger("dev"));
app.use(express.json());
app.use(bodyParser.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, "public")));

app.use("/", indexRouter);
app.use("/users", usersRouter);
app.use("/register", upload.any(), registrationRouter);
app.use("/retail", retailRouter);
app.use("/booking", bookingRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.json({ error: err.message });
});

app.get("*", (req, res) => {
  res.sendFile(path.resolve(__dirname, "build", "index.html"));
});

app.listen(port, console.log(`MyApp backend started on port ${port}!`));

module.exports = app;

I'd really appreciate it if someone could help me out!

Body:
You can try adding this before adding your routes

// every  response we send has these headers
app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE");
  res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
  next();
});


答:
You can use a path you draw in svg like so:

img{-webkit-clip-path: url(#clip);;
clip-path: url(#clip);}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="https://assets.codepen.io/222579/darwin300.jpg" />
<svg height="0" width="0" class="svg-clip" style="position:absolute">
        <defs>
             <clipPath id="clip" clipPathUnits="objectBoundingBox">
               <path d="M0,0 L1,0 1,1 0,1 0,0M.75,.5A.25,.25 0 1 0 .25,.5A.25,.25 0 1 0 .75,.5z" />
            </clipPath>
        </defs>
</svg></code>```

Please observe that clipPathUnits="objectBoundingBox" and the path's values are between 0 and 1. Also the first part of the path is drawn clockwise while the second path (the hole) is drawn counterclockwise.

Title: how to clip a circle inside a shape

Body:
It's a rectangle inside a shape。

-webkit-clip-path: polygon(0% 0%, 0% 100%, 25% 100%, 25% 25%, 75% 25%, 75% 75%, 25% 75%, 25% 100%, 100% 100%, 100% 0%);
clip-path: polygon(0% 0%, 0% 100%, 25% 100%, 25% 25%, 75% 25%, 75% 75%, 25% 75%, 25% 100%, 100% 100%, 100% 0%);

how can i clip a circle inside?

Body:
You can use a path you draw in svg like so:

img{-webkit-clip-path: url(#clip);;
clip-path: url(#clip);}

<img src="https://assets.codepen.io/222579/darwin300.jpg" />
<svg height="0" width="0" class="svg-clip" style="position:absolute">
        <defs>
             <clipPath id="clip" clipPathUnits="objectBoundingBox">
               <path d="M0,0 L1,0 1,1 0,1 0,0M.75,.5A.25,.25 0 1 0 .25,.5A.25,.25 0 1 0 .75,.5z" />
            </clipPath>
        </defs>
</svg>

Please observe that clipPathUnits="objectBoundingBox" and the path's values are between 0 and 1. Also the first part of the path is drawn clockwise while the second path (the hole) is drawn counterclockwise.


问:
Need help figuring out why my app is crashing when I try to switch views
Hello I am developing apps on for 4.1 and on Xcode3.2. My Apps crash when press back button . When press back back button Last class is appeared slightly than crash, with no error or warning ....
Here are the code....crash on Back Function</p>

```<code>#import "TransactionSummaryDetailViewController.h"
#import "TransactionSummaryData.h"
#import "Constant.h"
#import "DataBase.h";
#import "Common.h"
#import "YPCardHolderServiceService.h"
#import "SelectionScreenViewController.h"

@implementation TransactionSummaryDetailViewController
@synthesize table,cardReference;
@synthesize waitIndicator,transactionsummary,keyArray,valueArray,isSummaryAvailable;
@synthesize startDate,endDate;

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/

-(void)getrowcount{
    if(transactionsummary.cardholdernmae !=nil){
        [keyArray addObject:@"Card Holder Name: "];
        [valueArray addObject:transactionsummary.cardholdernmae];
    }
    if(transactionsummary.cardnumber!=nil){
        [keyArray addObject:@"Card Number: "];
        [valueArray addObject:transactionsummary.cardnumber];
    }
    if(transactionsummary.debittransactioncount != nil){
        [keyArray addObject:@"Debit Tx. Count: "];
        [valueArray addObject:transactionsummary.debittransactioncount];
    }
    if(transactionsummary.debittransactionvalue!=nil){
        [keyArray addObject:@"Debit Tx. Value"];
        [valueArray addObject:transactionsummary.debittransactionvalue];
    }
    if(transactionsummary.credittransactioncount!=nil){
        [keyArray addObject:@"Credit Tx. Count: "];
        [valueArray addObject:transactionsummary.credittransactioncount];
    }
    if(transactionsummary.credittransactionvalue!=nil){
        [keyArray addObject:@"Credit Tx. Value: "];
        [valueArray addObject:transactionsummary.credittransactionvalue];
    }
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    appDelegate = [[UIApplication sharedApplication]delegate];
    keyArray = [[NSMutableArray alloc]init];
    valueArray = [[NSMutableArray alloc]init];
    [self getrowcount];
    NSLog(@"Key Array Count is %d",[keyArray count]);
    [table setBackgroundColor:[UIColor clearColor]];
    [table setSeparatorColor:TableViewCellSeperatorColor];
    [waitIndicator setHidden:YES];
    [self setTitle:@"Summary Details"];
    UIButton *button =  [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:[UIImage imageNamed:@"list.png"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(BacktoView) forControlEvents:UIControlEventTouchUpInside];
    [button setFrame:CGRectMake(0, 0, 76, 44)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    if(!isSummaryAvailable)
    {
        if([Common isNetworkAvailable])
        {
            [waitIndicator startAnimating];
            YPCardHolderServiceService *services = [[YPCardHolderServiceService alloc] init];
            YPTransactionsSummaryRequest *summaryRequest = [[YPTransactionsSummaryRequest alloc] init];
            summaryRequest.SC = appDelegate.SC;
            summaryRequest.userName = appDelegate.userName;
            summaryRequest.valid =TRUE;
            summaryRequest.cardReference =[NSString stringWithFormat:@"%@",cardReference];
            NSLog(@"Start Date Is %@ and End Date is %@",startDate,endDate);
            summaryRequest.startDate = startDate;
            summaryRequest.endDate = endDate;
            summaryRequest.applicationType = @"M";
            [services getTransactionsSummary:self action:@selector(getTransactionsSummaryHandlers:) transactionsSummaryRequest:summaryRequest];
            [summaryRequest release];
            [services release];
        }
    }

    [super viewDidLoad];
}

//Handle the Response of getTransactionsSummary
-(void)getTransactionsSummaryHandlers:(id) value
{
    [waitIndicator stopAnimating];
    // Handle errors
    if([value isKindOfClass:[NSError class]]) {
        NSLog(@"%@", value);
        return;
    }

    // Handle faults
    if([value isKindOfClass:[SoapFault class]]) {
        NSLog(@"%@", value);
        return;
    }

    // Do something with the YPLoginResponse* result
    YPTransactionsSummaryResponse* result = (YPTransactionsSummaryResponse*)value;
    if(result.statusCode == 0)
    {
        NSLog(@"Number of Transaction is =%d",[result.transactionSummaryList count]);
        NSLog(@"Step 1 ='%@'",appDelegate.userID);
        NSString *deleteQuery = @"delete from TransactionSummary where userid = ";
        NSLog(@"Step 1 ='%@'",appDelegate.userID);
        deleteQuery = [deleteQuery stringByAppendingString:[NSString stringWithFormat:@"%@ and cardreference = '%@'",appDelegate.userID,cardReference]];
        NSLog(@"delete query= '%@'",deleteQuery);
        [DataBase deleteDataFromTable:deleteQuery];
        NSLog(@"delete query= '%@'",deleteQuery);
        //for (int i =0; i< [result.transactionSummaryList count]; i++)
        for (int i =0; i< [result.transactionSummaryList count] -2; i++)
        {
            NSLog(@"for loop= %d",i);
            YPTransactionSummaryDetails *transactionSummary = (YPTransactionSummaryDetails*)[result.transactionSummaryList objectAtIndex:i];
            NSLog(@"cardholdername= '%@'",transactionSummary.cardholderName);

            /*NSString *insertQuery = @"Insert into TransactionSummary(cardholdername,cardnumber,debittransactioncount,debittransactionvalue,credittransactioncount,credittransactionvalue,userid) values(";
            insertQuery =[insertQuery stringByAppendingString:[NSString stringWithFormat:@"'%@','xxxx xxxx xxxx %@',%d,%d,%d,%d,'%@',%@)",
                                                               transactionSummary.cardholderName,transactionSummary.cardNumber,transactionSummary.debitTransactionCount,
                                                               transactionSummary.debitTransactionValue,transactionSummary.creditTransactionCount,transactionSummary.creditTransactionValue,
                                                               appDelegate.userID]];*/
            //Add by sarvesh
            NSString *insertQuery = @"Insert into TransactionSummary(cardholdername,cardnumber,debittransactioncount,debittransactionvalue,credittransactioncount,credittransactionvalue,cardreference,userid) values(";
            insertQuery =[insertQuery stringByAppendingString:[NSString stringWithFormat:@"'%@','%@',%d,%d,%d,%d,'%@',%@)",
                                                               transactionSummary.cardholderName,transactionSummary.cardNumber,transactionSummary.debitTransactionCount,
                                                               transactionSummary.debitTransactionValue,transactionSummary.creditTransactionCount,transactionSummary.creditTransactionValue,cardReference,
                                                               appDelegate.userID]];
            NSLog(@"Insert Query for Transaction Summary is %@",insertQuery);
            [DataBase InsertIntoTable:insertQuery];
        }
        //Read Update Data From DataBase and Refresh Table
            NSString *query = @"Select * from TransactionSummary where userid = ";
            query = [query stringByAppendingString:[NSString stringWithFormat:@"%@ and cardreference = '%@'",appDelegate.userID,cardReference]];
        NSLog(@"select query= %@",query);
            NSMutableArray *temp=[DataBase getTransactionSummaryTableData:query];
            if([temp count] > 0)
            {
                transactionsummary = (TransactionSummaryData*)[temp objectAtIndex:0];
                [keyArray removeAllObjects];
                [valueArray removeAllObjects];
            }
            [self getrowcount];
            [table reloadData];

    }
}

-(void)viewDidAppear:(BOOL)animated
{
    CGFloat navBarHeight = 50.0f;
    CGRect frame = CGRectMake(0.0f, 20.0f, 320.0f, navBarHeight);
    [self.navigationController.navigationBar setFrame:frame];
    [super viewDidAppear:animated];
}

-(IBAction)BacktoView
{
    NSLog(@"in back function..TrasactionSummaryDetail");
    SelectionScreenViewController *screenView=[[SelectionScreenViewController alloc] initWithNibName:@"SelectionScreenViewController" bundle:nil];
    [self.navigationController popViewControllerAnimated:YES];
    [screenView release];
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleNone;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return cellHeightForGroupedTable;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section == 0)
        return [keyArray count];

    else
        return 0;

}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    NSString *title = nil;
    switch (section){
        case 0:{
            //title = @"Summary Details";
            break;
        }
    }
    return title;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if ([self tableView:tableView titleForHeaderInSection:section] != nil) {
        return tableHeaderHeight;
    }
    else {
        // If no section header title, no section header needed
        return 0;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    NSString *sectionTitle = [self tableView:tableView titleForHeaderInSection:section];
    if (sectionTitle == nil) {
        return nil;
    }

    // Create label with section title
    UILabel *label = [[[UILabel alloc] init] autorelease];
    label.frame = CGRectMake(20, 6, 300, 30);
    label.backgroundColor = [UIColor clearColor];
    label.textColor = HeaderTextColor;
    label.shadowColor = HeaderTextShadowColor;
    label.shadowOffset = CGSizeMake(0.0, 1.0);
    label.font = HeaderTextFontSize;
    label.text = sectionTitle;

    // Create header view and add label as a subview
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320,60)];
    [view autorelease];
    [view addSubview:label];

    return view;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = nil;

    NSString *cellIdentifier;

    cellIdentifier = @"SectionsTableIdentifier";
    int row = [indexPath row];

    CGRect nameLabelRect = CGRectMake(19 , 8, 240, 29);
    CGRect cardlabelRect = CGRectMake(19,31,240,15);
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:nameLabelRect];
    UILabel *cardnumber = [[UILabel alloc] initWithFrame:cardlabelRect];
    cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    if(cell == nil){
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
    }

    // Remove all subview from cell content view
    for (UIView *view in cell.contentView.subviews){
        [view removeFromSuperview];
    }

     [cell setAccessoryType:UITableViewCellAccessoryNone];
    [nameLabel setTextColor:firstLabelFontColor];
    [nameLabel setFont:firstLabelFont];
    [nameLabel setFont:firstLabelFontSize];

     nameLabel.textAlignment = UITextAlignmentLeft;
     nameLabel.text = [NSString stringWithFormat:@"%@ : %@",[keyArray objectAtIndex:row],[valueArray objectAtIndex:row]];

     [cell.contentView addSubview: nameLabel];

     cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell setBackgroundColor:[UIColor clearColor]];
    [cell setBackgroundColor:TableViewCellColor];

    [nameLabel setBackgroundColor:[UIColor clearColor]];
    [cardnumber setBackgroundColor:[UIColor clearColor]];

    [cardnumber release];
    [nameLabel release];
    return cell;
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {
    [table release];
    [waitIndicator release];
    [keyArray release];
    [valueArray release];
    [transactionsummary release];
    [super dealloc];
}

@end
</code>```

答:
just put

[self.navigationController popViewControllerAnimated:YES];

in your BacktoView method  and then check your previous page(SelectionScreenViewController)

Body:
Hello I am developing apps on for 4.1 and on Xcode3.2. My Apps crash when press back button . When press back back button Last class is appeared slightly than crash, with no error or warning ....
Here are the code....crash on Back Function

#import "TransactionSummaryDetailViewController.h"
#import "TransactionSummaryData.h"
#import "Constant.h"
#import "DataBase.h";
#import "Common.h"
#import "YPCardHolderServiceService.h"
#import "SelectionScreenViewController.h"

@implementation TransactionSummaryDetailViewController
@synthesize table,cardReference;
@synthesize waitIndicator,transactionsummary,keyArray,valueArray,isSummaryAvailable;
@synthesize startDate,endDate;

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/

-(void)getrowcount{
    if(transactionsummary.cardholdernmae !=nil){
        [keyArray addObject:@"Card Holder Name: "];
        [valueArray addObject:transactionsummary.cardholdernmae];
    }
    if(transactionsummary.cardnumber!=nil){
        [keyArray addObject:@"Card Number: "];
        [valueArray addObject:transactionsummary.cardnumber];
    }
    if(transactionsummary.debittransactioncount != nil){
        [keyArray addObject:@"Debit Tx. Count: "];
        [valueArray addObject:transactionsummary.debittransactioncount];
    }
    if(transactionsummary.debittransactionvalue!=nil){
        [keyArray addObject:@"Debit Tx. Value"];
        [valueArray addObject:transactionsummary.debittransactionvalue];
    }
    if(transactionsummary.credittransactioncount!=nil){
        [keyArray addObject:@"Credit Tx. Count: "];
        [valueArray addObject:transactionsummary.credittransactioncount];
    }
    if(transactionsummary.credittransactionvalue!=nil){
        [keyArray addObject:@"Credit Tx. Value: "];
        [valueArray addObject:transactionsummary.credittransactionvalue];
    }
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    appDelegate = [[UIApplication sharedApplication]delegate];
    keyArray = [[NSMutableArray alloc]init];
    valueArray = [[NSMutableArray alloc]init];
    [self getrowcount];
    NSLog(@"Key Array Count is %d",[keyArray count]);
    [table setBackgroundColor:[UIColor clearColor]];
    [table setSeparatorColor:TableViewCellSeperatorColor];
    [waitIndicator setHidden:YES];
    [self setTitle:@"Summary Details"];
    UIButton *button =  [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:[UIImage imageNamed:@"list.png"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(BacktoView) forControlEvents:UIControlEventTouchUpInside];
    [button setFrame:CGRectMake(0, 0, 76, 44)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    if(!isSummaryAvailable)
    {
        if([Common isNetworkAvailable])
        {
            [waitIndicator startAnimating];
            YPCardHolderServiceService *services = [[YPCardHolderServiceService alloc] init];
            YPTransactionsSummaryRequest *summaryRequest = [[YPTransactionsSummaryRequest alloc] init];
            summaryRequest.SC = appDelegate.SC;
            summaryRequest.userName = appDelegate.userName;
            summaryRequest.valid =TRUE;
            summaryRequest.cardReference =[NSString stringWithFormat:@"%@",cardReference];
            NSLog(@"Start Date Is %@ and End Date is %@",startDate,endDate);
            summaryRequest.startDate = startDate;
            summaryRequest.endDate = endDate;
            summaryRequest.applicationType = @"M";
            [services getTransactionsSummary:self action:@selector(getTransactionsSummaryHandlers:) transactionsSummaryRequest:summaryRequest];
            [summaryRequest release];
            [services release];
        }
    }

    [super viewDidLoad];
}

//Handle the Response of getTransactionsSummary
-(void)getTransactionsSummaryHandlers:(id) value
{
    [waitIndicator stopAnimating];
    // Handle errors
    if([value isKindOfClass:[NSError class]]) {
        NSLog(@"%@", value);
        return;
    }

    // Handle faults
    if([value isKindOfClass:[SoapFault class]]) {
        NSLog(@"%@", value);
        return;
    }

    // Do something with the YPLoginResponse* result
    YPTransactionsSummaryResponse* result = (YPTransactionsSummaryResponse*)value;
    if(result.statusCode == 0)
    {
        NSLog(@"Number of Transaction is =%d",[result.transactionSummaryList count]);
        NSLog(@"Step 1 ='%@'",appDelegate.userID);
        NSString *deleteQuery = @"delete from TransactionSummary where userid = ";
        NSLog(@"Step 1 ='%@'",appDelegate.userID);
        deleteQuery = [deleteQuery stringByAppendingString:[NSString stringWithFormat:@"%@ and cardreference = '%@'",appDelegate.userID,cardReference]];
        NSLog(@"delete query= '%@'",deleteQuery);
        [DataBase deleteDataFromTable:deleteQuery];
        NSLog(@"delete query= '%@'",deleteQuery);
        //for (int i =0; i< [result.transactionSummaryList count]; i++)
        for (int i =0; i< [result.transactionSummaryList count] -2; i++)
        {
            NSLog(@"for loop= %d",i);
            YPTransactionSummaryDetails *transactionSummary = (YPTransactionSummaryDetails*)[result.transactionSummaryList objectAtIndex:i];
            NSLog(@"cardholdername= '%@'",transactionSummary.cardholderName);

            /*NSString *insertQuery = @"Insert into TransactionSummary(cardholdername,cardnumber,debittransactioncount,debittransactionvalue,credittransactioncount,credittransactionvalue,userid) values(";
            insertQuery =[insertQuery stringByAppendingString:[NSString stringWithFormat:@"'%@','xxxx xxxx xxxx %@',%d,%d,%d,%d,'%@',%@)",
                                                               transactionSummary.cardholderName,transactionSummary.cardNumber,transactionSummary.debitTransactionCount,
                                                               transactionSummary.debitTransactionValue,transactionSummary.creditTransactionCount,transactionSummary.creditTransactionValue,
                                                               appDelegate.userID]];*/
            //Add by sarvesh
            NSString *insertQuery = @"Insert into TransactionSummary(cardholdername,cardnumber,debittransactioncount,debittransactionvalue,credittransactioncount,credittransactionvalue,cardreference,userid) values(";
            insertQuery =[insertQuery stringByAppendingString:[NSString stringWithFormat:@"'%@','%@',%d,%d,%d,%d,'%@',%@)",
                                                               transactionSummary.cardholderName,transactionSummary.cardNumber,transactionSummary.debitTransactionCount,
                                                               transactionSummary.debitTransactionValue,transactionSummary.creditTransactionCount,transactionSummary.creditTransactionValue,cardReference,
                                                               appDelegate.userID]];
            NSLog(@"Insert Query for Transaction Summary is %@",insertQuery);
            [DataBase InsertIntoTable:insertQuery];
        }
        //Read Update Data From DataBase and Refresh Table
            NSString *query = @"Select * from TransactionSummary where userid = ";
            query = [query stringByAppendingString:[NSString stringWithFormat:@"%@ and cardreference = '%@'",appDelegate.userID,cardReference]];
        NSLog(@"select query= %@",query);
            NSMutableArray *temp=[DataBase getTransactionSummaryTableData:query];
            if([temp count] > 0)
            {
                transactionsummary = (TransactionSummaryData*)[temp objectAtIndex:0];
                [keyArray removeAllObjects];
                [valueArray removeAllObjects];
            }
            [self getrowcount];
            [table reloadData];

    }
}

-(void)viewDidAppear:(BOOL)animated
{
    CGFloat navBarHeight = 50.0f;
    CGRect frame = CGRectMake(0.0f, 20.0f, 320.0f, navBarHeight);
    [self.navigationController.navigationBar setFrame:frame];
    [super viewDidAppear:animated];
}

-(IBAction)BacktoView
{
    NSLog(@"in back function..TrasactionSummaryDetail");
    SelectionScreenViewController *screenView=[[SelectionScreenViewController alloc] initWithNibName:@"SelectionScreenViewController" bundle:nil];
    [self.navigationController popViewControllerAnimated:YES];
    [screenView release];
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleNone;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return cellHeightForGroupedTable;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section == 0)
        return [keyArray count];

    else
        return 0;

}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    NSString *title = nil;
    switch (section){
        case 0:{
            //title = @"Summary Details";
            break;
        }
    }
    return title;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if ([self tableView:tableView titleForHeaderInSection:section] != nil) {
        return tableHeaderHeight;
    }
    else {
        // If no section header title, no section header needed
        return 0;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    NSString *sectionTitle = [self tableView:tableView titleForHeaderInSection:section];
    if (sectionTitle == nil) {
        return nil;
    }

    // Create label with section title
    UILabel *label = [[[UILabel alloc] init] autorelease];
    label.frame = CGRectMake(20, 6, 300, 30);
    label.backgroundColor = [UIColor clearColor];
    label.textColor = HeaderTextColor;
    label.shadowColor = HeaderTextShadowColor;
    label.shadowOffset = CGSizeMake(0.0, 1.0);
    label.font = HeaderTextFontSize;
    label.text = sectionTitle;

    // Create header view and add label as a subview
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320,60)];
    [view autorelease];
    [view addSubview:label];

    return view;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = nil;

    NSString *cellIdentifier;

    cellIdentifier = @"SectionsTableIdentifier";
    int row = [indexPath row];

    CGRect nameLabelRect = CGRectMake(19 , 8, 240, 29);
    CGRect cardlabelRect = CGRectMake(19,31,240,15);
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:nameLabelRect];
    UILabel *cardnumber = [[UILabel alloc] initWithFrame:cardlabelRect];
    cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    if(cell == nil){
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
    }

    // Remove all subview from cell content view
    for (UIView *view in cell.contentView.subviews){
        [view removeFromSuperview];
    }

     [cell setAccessoryType:UITableViewCellAccessoryNone];
    [nameLabel setTextColor:firstLabelFontColor];
    [nameLabel setFont:firstLabelFont];
    [nameLabel setFont:firstLabelFontSize];

     nameLabel.textAlignment = UITextAlignmentLeft;
     nameLabel.text = [NSString stringWithFormat:@"%@ : %@",[keyArray objectAtIndex:row],[valueArray objectAtIndex:row]];

     [cell.contentView addSubview: nameLabel];

     cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell setBackgroundColor:[UIColor clearColor]];
    [cell setBackgroundColor:TableViewCellColor];

    [nameLabel setBackgroundColor:[UIColor clearColor]];
    [cardnumber setBackgroundColor:[UIColor clearColor]];

    [cardnumber release];
    [nameLabel release];
    return cell;
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {
    [table release];
    [waitIndicator release];
    [keyArray release];
    [valueArray release];
    [transactionsummary release];
    [super dealloc];
}

@end


问:
.Net Core application running on a linux container
Following this link I build a .Net Core application and was able to run the application in a docker container. My host machine OS is Windows 10, and I now want to try to run the linked application in a Linux container. I have switched to Linux containers with Docker Desktop.

When I'm building the docker image I get this error:

```<code>failed to register layer: error creating overlay mount to /var/lib/docker/overlay2/f3e5279484774002c78a8eb66702c9ee7bca7038b59f4eeca7085b88dcbe25d9/merged: too many levels of symbolic links
</code>```

The Dockerfile I've Used:

```<code>FROM mcr.microsoft.com/dotnet/core/runtime:3.1-nanoserver-1903 AS base
WORKDIR /app

FROM mcr.microsoft.com/dotnet/core/sdk:3.1-nanoserver-1903 AS build
WORKDIR /src
COPY ["NetCore.Docker/NetCore.Docker.csproj", "NetCore.Docker/"]
RUN dotnet restore "NetCore.Docker/NetCore.Docker.csproj"
COPY . .
WORKDIR "/src/NetCore.Docker"
RUN dotnet build "NetCore.Docker.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "NetCore.Docker.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "NetCore.Docker.dll"]
</code>```

Thanks

答: reason for this is I was using wrong image, had to change the image which support linux containers</p>

Body:
Following this link I build a .Net Core application and was able to run the application in a docker container. My host machine OS is Windows 10, and I now want to try to run the linked application in a Linux container. I have switched to Linux containers with Docker Desktop.

When I'm building the docker image I get this error:

failed to register layer: error creating overlay mount to /var/lib/docker/overlay2/f3e5279484774002c78a8eb66702c9ee7bca7038b59f4eeca7085b88dcbe25d9/merged: too many levels of symbolic links

The Dockerfile I've Used:

FROM mcr.microsoft.com/dotnet/core/runtime:3.1-nanoserver-1903 AS base
WORKDIR /app

FROM mcr.microsoft.com/dotnet/core/sdk:3.1-nanoserver-1903 AS build
WORKDIR /src
COPY ["NetCore.Docker/NetCore.Docker.csproj", "NetCore.Docker/"]
RUN dotnet restore "NetCore.Docker/NetCore.Docker.csproj"
COPY . .
WORKDIR "/src/NetCore.Docker"
RUN dotnet build "NetCore.Docker.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "NetCore.Docker.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "NetCore.Docker.dll"]

Thanks


问:
PowerShell module-qualified names and Command Prefix
I'm trying to make use of module-qualified names[1] and a DefaultCommandPrefix and not have it break if the module is imported with Import-Module -Prefix SomethingElse. Maybe I'm just doing something really wrong here, or those two features aren't meant to be used together.

Inside the main module file using "ModuleName\Verb-PrefixNoun args..." works as long as "Prefix" matches the DefaultCommandPrefix in the manifest (the module-qualified syntax seems to require the prefix used for the import[2]). But importing the module with a different prefix, all module-qualified references inside the module breaks.

After a bit of searching and trial and error, the least horrible solution I've managed to get working is to use something like the following hackish solution. But, I can't help wonder if there isn't some better way that automatically handles the prefix (just as Import-Module obviously manages to add the prefix, my first naive though was that using just ModuleName\Verb-Noun would automatically append any prefix to the noun, but evidently not[2].

So this is the hack I came up with, that looks up the modules prefix and appends it, then using "." or "&" to expand/invoke the command:

# (imagine this code in the `ModuleName.psm1`, and a manifest with some `DefaultCommandPrefix`)

Function MQ {
    param (
        [Parameter()][string]
        $Verb,
        [Parameter()][string]
        $Noun,
        [string]
        $Module='ModuleName'
    )
    "$Module\$Verb-$((Get-Module $Module).Prefix)$Noun"
}

Function Verb-Noun {
    # This works even when importing with a prefix,
    # but can I be guaranteed that it's not some
    # other module's cmdlet?
    Verb-OtherNoun 1 2 3 '...'

    #ModuleName\Verb-OtherNoun 1 2 3 '...'
    . (MQ 'Verb' 'OtherNoun') 1 2 3 '...'
    # or:
    & (MQ 'Verb' 'OtherNoun') 1 2 3 '...'
}
```

(MQ could be made more user friendly by also accepting a single string MQ "Verb-Noun" and split/recombine automatically, and so on, etc. and all the usual disclamers)

Note: I know it would be possible to hard-code the name instead of using DefaultCommandPrefix, e.g. as PSReadLine does (and a bunch of other modules). But, to be honest that feels like a workaround.

Just calling Verb-OtherNoun seems fragile to me, as the most recent one is used[3]. So I would imagine that for example just before the call adding an Import-Module statement with a module that exports a Verb-OtherNoun would cause the wrong (not this module's) cmdlet being called. (Perhaps a more real world scenario is a module being loaded after this module has been loaded, but before calling Verb-Noun.)

Is there perhaps some syntax for module-qualifiaction I'm not aware of that would do something akin to Import-Module(e.g. Module\\Verb-Noun or Module\Verb+Noun that would resolve and inject Module's prefix) and now that I think of it, is there some reason why Module\Verb-Noun doesn't handle prefixes, or just that no one wrote the code for it? (I can't see how it would break things more than how using DefaultCommandPrefix would break v2/v3[2])

[1] https://www.sapien.com/blog/2015/10/23/using-module-qualified-cmdlet-names/

[2] https://github.com/PoshCode/PowerShellPracticeAndStyle/issues/23#issuecomment-106843619

[3] https://stackoverflow.com/a/22259706/13648152

答:
You can avoid the problem by not using a module qualifier  not using a noun prefix when you call your module's own functions.

That is, call them as Verb-Noun, exactly as named in the target function's implementation.

This is generally safe, because your own module's functions take precedence over any commands of the same name defined outside your module.

The sole exception is if an alias defined in the global scope happens to have the same name as one of your functions - but that shouldn't normally be a concern, because aliases are used for short names that do not follow the verb-noun naming convention.

It also makes sense in that it allows you to call your functions module-internally with an invariable name - a name that doesn't situationally change, depending on what the caller decided to choose as a noun prefix via Import-Module -Prefix ....

Think of the prefix feature as being a caller-only feature that is unrelated to your module's implementation.

As an aside: As of PowerShell 7.0, declaring a default noun prefix via the DefaultCommandPrefix module-manifest property doesn't properly integrate with the module auto-loading and command-discovery features - see this GitHub issue.

Body:
I'm trying to make use of module-qualified names[1] and a DefaultCommandPrefix and not have it break if the module is imported with Import-Module -Prefix SomethingElse. Maybe I'm just doing something really wrong here, or those two features aren't meant to be used together.

Inside the main module file using "ModuleName\Verb-PrefixNoun args..." works as long as "Prefix" matches the DefaultCommandPrefix in the manifest (the module-qualified syntax seems to require the prefix used for the import[2]). But importing the module with a different prefix, all module-qualified references inside the module breaks.

After a bit of searching and trial and error, the least horrible solution I've managed to get working is to use something like the following hackish solution. But, I can't help wonder if there isn't some better way that automatically handles the prefix (just as Import-Module obviously manages to add the prefix, my first naive though was that using just ModuleName\Verb-Noun would automatically append any prefix to the noun, but evidently not[2].

So this is the hack I came up with, that looks up the modules prefix and appends it, then using "." or "&" to expand/invoke the command:

# (imagine this code in the `ModuleName.psm1`, and a manifest with some `DefaultCommandPrefix`)

Function MQ {
    param (
        [Parameter()][string]
        $Verb,
        [Parameter()][string]
        $Noun,
        [string]
        $Module='ModuleName'
    )
    "$Module\$Verb-$((Get-Module $Module).Prefix)$Noun"
}

Function Verb-Noun {
    # This works even when importing with a prefix,
    # but can I be guaranteed that it's not some
    # other module's cmdlet?
    Verb-OtherNoun 1 2 3 '...'

    #ModuleName\Verb-OtherNoun 1 2 3 '...'
    . (MQ 'Verb' 'OtherNoun') 1 2 3 '...'
    # or:
    & (MQ 'Verb' 'OtherNoun') 1 2 3 '...'
}

(MQ could be made more user friendly by also accepting a single string MQ "Verb-Noun" and split/recombine automatically, and so on, etc. and all the usual disclamers)

Note: I know it would be possible to hard-code the name instead of using DefaultCommandPrefix, e.g. as PSReadLine does (and a bunch of other modules). But, to be honest that feels like a workaround.

Just calling Verb-OtherNoun seems fragile to me, as the most recent one is used[3]. So I would imagine that for example just before the call adding an Import-Module statement with a module that exports a Verb-OtherNoun would cause the wrong (not this module's) cmdlet being called. (Perhaps a more real world scenario is a module being loaded after this module has been loaded, but before calling Verb-Noun.)

Is there perhaps some syntax for module-qualifiaction I'm not aware of that would do something akin to Import-Module(e.g. Module\\Verb-Noun or Module\Verb+Noun that would resolve and inject Module's prefix) and now that I think of it, is there some reason why Module\Verb-Noun doesn't handle prefixes, or just that no one wrote the code for it? (I can't see how it would break things more than how using DefaultCommandPrefix would break v2/v3[2])

[1] https://www.sapien.com/blog/2015/10/23/using-module-qualified-cmdlet-names/

[2] https://github.com/PoshCode/PowerShellPracticeAndStyle/issues/23#issuecomment-106843619

[3] https://stackoverflow.com/a/22259706/13648152


问:
Time difference query using MS SQL
I'm trying to take out difference between two times, first and second time using AM , PM
I've columns:

```<code>FirstTime    SecondTime
10:14:42 PM  1:05:25 AM.
</code>```

When i'm using DateDiff function it return wrong value and also i want access this in whole table not for single row and max is required on particular table

I've tried following queries:

```<code>select DATEDIFF(MINUTE, first_time, second_time) AS 'Duration'  FROM tbl_weight

SELECT max (DATEDIFF(MINUTE, first_time, second_time)) AS 'Duration' , sr_no
    FROM tbl_weight where first_weight != '0' and  second_weight != '0' group by sr_no  ;
</code>```

but in both it return wrong value.

答:
I just understand from the comments that you think -1269 is wrong while it's not.

You need to reverse the order of the columns to get the desired results, because the FirstTime should be <= SecondTime. Or use ABS() function to get a positive number

```<code>SELECT DATEDIFF(Minute, FirstTime, SecondTime) FirstWay,
       ABS(DATEDIFF(Minute, SecondTime, FirstTime)) SecondWay
FROM
(
    VALUES
    ('1:05:25 AM', '10:14:42 PM')
    --FirstTime should be < than SecondTime to get the desired outputs
    -- or use ABS() function to get positive number
) T(FirstTime, SecondTime)
</code>```

Here is a db<>fiddle

Title: Time difference query using MS SQL

Body:
I'm trying to take out difference between two times, first and second time using AM , PM
I've columns:

FirstTime    SecondTime
10:14:42 PM  1:05:25 AM.

When i'm using DateDiff function it return wrong value and also i want access this in whole table not for single row and max is required on particular table

I've tried following queries:

select DATEDIFF(MINUTE, first_time, second_time) AS 'Duration'  FROM tbl_weight

SELECT max (DATEDIFF(MINUTE, first_time, second_time)) AS 'Duration' , sr_no
    FROM tbl_weight where first_weight != '0' and  second_weight != '0' group by sr_no  ;

but in both it return wrong value.

Body:
I just understand from the comments that you think -1269 is wrong while it's not.

You need to reverse the order of the columns to get the desired results, because the FirstTime should be <= SecondTime. Or use ABS() function to get a positive number

SELECT DATEDIFF(Minute, FirstTime, SecondTime) FirstWay,
       ABS(DATEDIFF(Minute, SecondTime, FirstTime)) SecondWay
FROM
(
    VALUES
    ('1:05:25 AM', '10:14:42 PM')
    --FirstTime should be < than SecondTime to get the desired outputs
    -- or use ABS() function to get positive number
) T(FirstTime, SecondTime)

Here is a db<>fiddle


问:
Can't find the bin folder of Julia?
I had installed Julia Programming Language in my Windows 10 Laptop. I want to add this to PATH variable in my system's Environment Variables but I am unable to locate the executable file. Can you please help me to solve this problem?</p>

答:
With the current Julia version the path has slightly changed and is:

```<code>C:\Users\your-user-name\AppData\Local\Programs\Julia\Julia-1.4.2\bin
</code>```

Julia in Windows normally installs itself to the Start Menu. Hence, if you forgot the location of your installation go to the Start menu, type julia and launch the Julia REPL command line.

Having the command line running you can ask Julia where it is:

```<code>julia> println(Sys.BINDIR)
C:\Users\your-user-name\AppData\Local\Programs\Julia\Julia-1.4.2\bin
</code>```

I would advise against creating the *.bat file suggested in another answer because when you update Julia in the future (which always means a new directory) you might forget where your *.bat file was and commands such as println(Sys.BINDIR) will not help (however in Windows there is a good-to-know command where julia.exe that shows how your Julia executable will be found in PATH).

Title: Can't find the bin folder of Julia?

Body:
With the current Julia version the path has slightly changed and is:

C:\Users\your-user-name\AppData\Local\Programs\Julia\Julia-1.4.2\bin

Julia in Windows normally installs itself to the Start Menu. Hence, if you forgot the location of your installation go to the Start menu, type julia and launch the Julia REPL command line.

Having the command line running you can ask Julia where it is:

julia> println(Sys.BINDIR)
C:\Users\your-user-name\AppData\Local\Programs\Julia\Julia-1.4.2\bin

I would advise against creating the *.bat file suggested in another answer because when you update Julia in the future (which always means a new directory) you might forget where your *.bat file was and commands such as println(Sys.BINDIR) will not help (however in Windows there is a good-to-know command where julia.exe that shows how your Julia executable will be found in PATH).


问:
Concatenate Strings and Variables of two conditions while iterating in python
I have an iteration over a dataframe, but for the example here I used a list.

```<code>seq = [0, -1, 0, 1, 2, 1, 0, -1, -2, -3, -4, -5, -4, -3, -2, -1]
box = []

for i in range(1, len(seq)):
    if seq[i] > seq[i-1]:
        box.append(seq[i])
    else:
        box.append(seq[i-1]+10)

box
</code>```

Now i would like to add to each appended value a string prefix like this:

For all values from the If statement letter 'A-'

For all values from else statement letter 'B-'

My desired output is:

```<code>[B-10, A-0, A-1, A-2, B-12, B-11, B-10......
</code>```

I tried it with .join and with simple comma or + inside the append method, but none of it works.
Any suggestions how to accomplish this ?

答:
Idiotic one-liner:

```<code>box = map(lambda p: "A-" + str(p[1]) if p[1] > p[0] else "B-" + str(p[0] + 10), [(seq[i-1], seq[i]) for i,_ in enumerate(seq[:])][1:])
</code>```

But in all seriousness just use string concatenation, but convert the integer value to string before concatenating:

```<code>seq = [0, -1, 0, 1, 2, 1, 0, -1, -2, -3, -4, -5, -4, -3, -2, -1]
box = []

for i in range(1, len(seq)):
    if seq[i] > seq[i-1]:
        box.append("A-" + str(seq[i]))
    else:
        box.append("B-" + str(seq[i-1]+10))

print (box)
</code>```

Body:
I have an iteration over a dataframe, but for the example here I used a list.

seq = [0, -1, 0, 1, 2, 1, 0, -1, -2, -3, -4, -5, -4, -3, -2, -1]
box = []

for i in range(1, len(seq)):
    if seq[i] > seq[i-1]:
        box.append(seq[i])
    else:
        box.append(seq[i-1]+10)

box

Now i would like to add to each appended value a string prefix like this:

For all values from the If statement letter 'A-'

For all values from else statement letter 'B-'

My desired output is:

[B-10, A-0, A-1, A-2, B-12, B-11, B-10......

I tried it with .join and with simple comma or + inside the append method, but none of it works.
Any suggestions how to accomplish this ?

Body:
Idiotic one-liner:

box = map(lambda p: "A-" + str(p[1]) if p[1] > p[0] else "B-" + str(p[0] + 10), [(seq[i-1], seq[i]) for i,_ in enumerate(seq[:])][1:])

But in all seriousness just use string concatenation, but convert the integer value to string before concatenating:

seq = [0, -1, 0, 1, 2, 1, 0, -1, -2, -3, -4, -5, -4, -3, -2, -1]
box = []

for i in range(1, len(seq)):
    if seq[i] > seq[i-1]:
        box.append("A-" + str(seq[i]))
    else:
        box.append("B-" + str(seq[i-1]+10))

print (box)


问:
React Native : UIkitten Icons typeerror: undefined is not an object (evaluating 'iconsPack.name')
I was trying to use the Eva Icons in UI Kitten but ended up getting this error, digging my head on this problem for a while, new to React and Reavt-Native, will be glad if someone could help me (:</p>

```<code>render()
const FacebookIcon = (props) => (
  <Icon name='facebook' {...props} />
);
return(
  <Input
    value={this.state.id}
    label="FB ID"
    size="medium"
    placeholder="Enter your fb_id"
    onChangeText={(enteredText) => this.setState({ fbId: enteredText })}
    accessoryLeft={FacebookIcon}
/>

)

</code>```

答:
First, run this command :

```<code>npm i @ui-kitten/eva-icons react-native-svg
</code>```

Then register an icon package with IconRegistry.

As it's mentionned in the docs

```<code>import React from 'react';
import * as eva from '@eva-design/eva';
import { ApplicationProvider, IconRegistry, Layout, Text } from '@ui-kitten/components';
import { EvaIconsPack } from '@ui-kitten/eva-icons';

const HomeScreen = () => (
  <Layout style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
    <Text category='h1'>HOME</Text>
  </Layout>
);

export default () => (
  <>
    <IconRegistry icons={EvaIconsPack} />
    <ApplicationProvider {...eva} theme={eva.light}>
      <HomeScreen />
    </ApplicationProvider>
  </>
);
</code>```

Body:
I was trying to use the Eva Icons in UI Kitten but ended up getting this error, digging my head on this problem for a while, new to React and Reavt-Native, will be glad if someone could help me (:

render()
const FacebookIcon = (props) => (
  <Icon name='facebook' {...props} />
);
return(
  <Input
    value={this.state.id}
    label="FB ID"
    size="medium"
    placeholder="Enter your fb_id"
    onChangeText={(enteredText) => this.setState({ fbId: enteredText })}
    accessoryLeft={FacebookIcon}
/>

)

Body:
First, run this command :

npm i @ui-kitten/eva-icons react-native-svg

Then register an icon package with IconRegistry.

As it's mentionned in the docs

import React from 'react';
import * as eva from '@eva-design/eva';
import { ApplicationProvider, IconRegistry, Layout, Text } from '@ui-kitten/components';
import { EvaIconsPack } from '@ui-kitten/eva-icons';

const HomeScreen = () => (
  <Layout style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
    <Text category='h1'>HOME</Text>
  </Layout>
);

export default () => (
  <>
    <IconRegistry icons={EvaIconsPack} />
    <ApplicationProvider {...eva} theme={eva.light}>
      <HomeScreen />
    </ApplicationProvider>
  </>
);


问:
how to use SQLITE in qt webassembly
I want to use sqlite in my application. I compile sqlite in desktop and it compile successfully but when I compile it with qt web-assembly I get ERROR: Unknown module(s) in QT: sql with emsdk 1.38.27-64bit.So I use emsdk 1.38.30-64bit with thread feature but I could not compile a simple example.</p>

答: QtSql is not supported by Qt webassembly. See here.</p>

Title: how to use SQLITE in qt webassembly


问:
Replicating exp function with multiple inputs from R in python
I am attempting to replicate an R script in python, and have come across an exponential function that I do not understand:

```<code>exp(-var1-var2-var3)
</code>```

If I were to use 0.8, 1.2, and 0.3 as variables here, R would give me the answer 0.1002588. However, I do not know how this is arrived at. I understand that the equivalent of exp in python is **, and know how to replicate this function with only one number as input but I see no way to do this with multiple numbers. I have tried -var1**-var2**-var3, which gives me -1.235241.

How do I interpret this function, and what would the equivalent python code be for this?

答:
I ran the exp function with the exact same values and it outputs the right result:

```<code>from math import exp

# 0.8, 1.2, and 0.3 as variables here, R would give me the answer 0.1002588.
var1 = 0.8
var2 = 1.2
var3 = 0.3
res = exp(-var1-var2-var3)

print (res)
OUT: 0.10025884372280375
</code>```

Body:
I am attempting to replicate an R script in python, and have come across an exponential function that I do not understand:

exp(-var1-var2-var3)

If I were to use 0.8, 1.2, and 0.3 as variables here, R would give me the answer 0.1002588. However, I do not know how this is arrived at. I understand that the equivalent of exp in python is **, and know how to replicate this function with only one number as input but I see no way to do this with multiple numbers. I have tried -var1**-var2**-var3, which gives me -1.235241.

How do I interpret this function, and what would the equivalent python code be for this?

Body:
I ran the exp function with the exact same values and it outputs the right result:

from math import exp

# 0.8, 1.2, and 0.3 as variables here, R would give me the answer 0.1002588.
var1 = 0.8
var2 = 1.2
var3 = 0.3
res = exp(-var1-var2-var3)

print (res)
OUT: 0.10025884372280375


问:
Octave one line two plot differ from multiple line plot
I'm fitting some data, but when I plot the data and fit in one-line-plot (see left figure) the drawn graph is correct

```<code>plot(x, y, '.b;data;', [0.05 2], phi(1)+phi(2)*[0.05 2], '--r;fit;', [0.05 2]);
</code>```

But when I used two separated plot (see right figure) the graph differs from mention above

```<code>hold on;

plot(x, y, '.b;data;', [0.05 2]);
plot(phi(1)+phi(2)*[0.05 2], '--r;fit;', [0.05 2]);

hold off;
grid on;
</code>```

Data

```<code>[x, y]
ans =
    0.050000     3571.000000
    0.100000     6567.000000
    0.200000    12760.000000
    0.300000    20512.000000
    0.400000    25480.000000
    0.500000    32088.000000
    1.000000    63223.000000
    2.000000   128690.000000
</code>```

Calculate Linear Regression

```<code>A = [N, sum(x); sum(x), sum(x.*x)];
b = [sum(y); sum(x.*y)];
phi = inv(A)*b;
</code>```

Is there any way to solve this?

答:
When the x-axis values are not specified then 1:numel(y) are considered to be the x-axis values.

In your code:

```<code>%Your first graph:
plot(x, y, '.b;data;', [0.05 2], phi(1)+phi(2)*[0.05 2], '--r;fit;', [0.05 2]);
                                                                     %^^^^^^^

%Your second graph:

plot(x, y, '.b;data;', [0.05 2]);
                      %^^^^^^^^^

plot(phi(1)+phi(2)*[0.05 2], '--r;fit;', [0.05 2]);
    %!!!!!!!!!!!!!!!!!!!!!!             %^^^^^^^^^

</code>```

The parts highlighted with ^ in above plot commands have x=[1 2] and y=[0.05 2] and the part highlighted with ! has x=[1 2] and y=phi(1)+phi(2)*[0.05 2]. You can see those lines being drawn if you zoom at that area.

So your first plot command should be:

```<code>plot(x, y, '.b;data;', [0.05 2], phi(1)+phi(2)*[0.05 2], '--r;fit;');
</code>```

and it should be split like this:

```<code>plot(x, y, '.b;data;');
hold on;
plot([0.05 2], phi(1)+phi(2)*[0.05 2], '--r;fit;');
</code>```

Body:
I'm fitting some data, but when I plot the data and fit in one-line-plot (see left figure) the drawn graph is correct

plot(x, y, '.b;data;', [0.05 2], phi(1)+phi(2)*[0.05 2], '--r;fit;', [0.05 2]);

But when I used two separated plot (see right figure) the graph differs from mention above

hold on;

plot(x, y, '.b;data;', [0.05 2]);
plot(phi(1)+phi(2)*[0.05 2], '--r;fit;', [0.05 2]);

hold off;
grid on;

Data

[x, y]
ans =
    0.050000     3571.000000
    0.100000     6567.000000
    0.200000    12760.000000
    0.300000    20512.000000
    0.400000    25480.000000
    0.500000    32088.000000
    1.000000    63223.000000
    2.000000   128690.000000

Calculate Linear Regression

A = [N, sum(x); sum(x), sum(x.*x)];
b = [sum(y); sum(x.*y)];
phi = inv(A)*b;

Is there any way to solve this?

Body:
When the x-axis values are not specified then 1:numel(y) are considered to be the x-axis values.

In your code:

%Your first graph:
plot(x, y, '.b;data;', [0.05 2], phi(1)+phi(2)*[0.05 2], '--r;fit;', [0.05 2]);
                                                                     %^^^^^^^

%Your second graph:

plot(x, y, '.b;data;', [0.05 2]);
                      %^^^^^^^^^

plot(phi(1)+phi(2)*[0.05 2], '--r;fit;', [0.05 2]);
    %!!!!!!!!!!!!!!!!!!!!!!             %^^^^^^^^^

The parts highlighted with ^ in above plot commands have x=[1 2] and y=[0.05 2] and the part highlighted with ! has x=[1 2] and y=phi(1)+phi(2)*[0.05 2]. You can see those lines being drawn if you zoom at that area.

So your first plot command should be:

plot(x, y, '.b;data;', [0.05 2], phi(1)+phi(2)*[0.05 2], '--r;fit;');

and it should be split like this:

plot(x, y, '.b;data;');
hold on;
plot([0.05 2], phi(1)+phi(2)*[0.05 2], '--r;fit;');


问:
npm install error Unexpected end of JSON input while parsing near
```<code>0 info it worked if it ends with ok
1 verbose cli [
1 verbose cli   'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'install',
1 verbose cli   'react-bootstrap',
1 verbose cli   'bootstrap'
1 verbose cli ]
2 info using npm@6.14.4
3 info using node@v12.17.0
4 verbose npm-session 4004d1d4d37ac517
5 silly install loadCurrentTree
6 silly install readLocalPackageData
7 http fetch GET 200 https://registry.npmjs.org/react-bootstrap 521ms
8 silly fetchPackageMetaData error for react-bootstrap@latest Unexpected end of JSON input while parsing near '...,"requirejs":"~2.1.9"'
9 http fetch GET 200 https://registry.npmjs.org/bootstrap 521ms
10 silly fetchPackageMetaData error for bootstrap@latest Unexpected end of JSON input while parsing near '...7bc2df7ec608869c9c8",'
11 timing stage:rollbackFailedOptional Completed in 0ms
12 timing stage:runTopLevelLifecycles Completed in 3560ms
13 verbose stack SyntaxError: Unexpected end of JSON input while parsing near '...,"requirejs":"~2.1.9"'
13 verbose stack     at JSON.parse (<anonymous>)
13 verbose stack     at parseJson (C:\Program Files\nodejs\node_modules\npm\node_modules\json-parse-better-errors\index.js:7:17)
13 verbose stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\node-fetch-npm\src\body.js:96:50
13 verbose stack     at processTicksAndRejections (internal/process/task_queues.js:97:5)
14 verbose cwd D:\Talk2Tutor\material-kit-react-master
15 verbose Windows_NT 10.0.17134
16 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "react-bootstrap" "bootstrap"
17 verbose node v12.17.0
18 verbose npm  v6.14.4
19 error Unexpected end of JSON input while parsing near '...,"requirejs":"~2.1.9"'
20 verbose exit [ 1, true ]
</code>```

I got above error while running npm i react-bootstrap bootstrap. After the error occurred, I tried npm cache clean --force but it didn't resolve my problem. Then I reinstalled node and tried to install dependencies but I still get an error and installation is failed. Any one fixed this error. I tried all the things mentioned in the related question. But it didn't solve my problem. I use node v12.17.0 and npm 6.14.4.

答: Popper.js is required if you're using Bootstrap JS. Check the docs</p>

Body:
0 info it worked if it ends with ok
1 verbose cli [
1 verbose cli   'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'install',
1 verbose cli   'react-bootstrap',
1 verbose cli   'bootstrap'
1 verbose cli ]
2 info using npm@6.14.4
3 info using node@v12.17.0
4 verbose npm-session 4004d1d4d37ac517
5 silly install loadCurrentTree
6 silly install readLocalPackageData
7 http fetch GET 200 https://registry.npmjs.org/react-bootstrap 521ms
8 silly fetchPackageMetaData error for react-bootstrap@latest Unexpected end of JSON input while parsing near '...,"requirejs":"~2.1.9"'
9 http fetch GET 200 https://registry.npmjs.org/bootstrap 521ms
10 silly fetchPackageMetaData error for bootstrap@latest Unexpected end of JSON input while parsing near '...7bc2df7ec608869c9c8",'
11 timing stage:rollbackFailedOptional Completed in 0ms
12 timing stage:runTopLevelLifecycles Completed in 3560ms
13 verbose stack SyntaxError: Unexpected end of JSON input while parsing near '...,"requirejs":"~2.1.9"'
13 verbose stack     at JSON.parse (<anonymous>)
13 verbose stack     at parseJson (C:\Program Files\nodejs\node_modules\npm\node_modules\json-parse-better-errors\index.js:7:17)
13 verbose stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\node-fetch-npm\src\body.js:96:50
13 verbose stack     at processTicksAndRejections (internal/process/task_queues.js:97:5)
14 verbose cwd D:\Talk2Tutor\material-kit-react-master
15 verbose Windows_NT 10.0.17134
16 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "react-bootstrap" "bootstrap"
17 verbose node v12.17.0
18 verbose npm  v6.14.4
19 error Unexpected end of JSON input while parsing near '...,"requirejs":"~2.1.9"'
20 verbose exit [ 1, true ]

I got above error while running npm i react-bootstrap bootstrap. After the error occurred, I tried npm cache clean --force but it didn't resolve my problem. Then I reinstalled node and tried to install dependencies but I still get an error and installation is failed. Any one fixed this error. I tried all the things mentioned in the related question. But it didn't solve my problem. I use node v12.17.0 and npm 6.14.4.


问:
Javascript Hexadecimal, Binary, Decimal & Octal Converter
```<code><div class="featurebox">
    <h1>Javascript Learning</h1>
    <div class="bag">
        <p>Input Your Value here :
            <input id="numb" placeholder="provide your value here">
            <button class="btn"  onclick="myfunction()">Result</button>
        </p>

        <table border="1px solid black">
            <tr>
                <td>Decimal Value</td>
                <td>Hexadecimal Value</td>
                <td>Octal Value</td>
                <td>Binary Value</td>
            </tr>
            <tr>
                <td><p id="text1"></p></td>
                <td><p id="text2"></p></td>
                <td><p id="text3"></p></td>
                <td><p id="text4"></p></td>
            </tr>
        </table>
    </div>
    <footer>&copy Copyright Reserved by Shah Imran </footer>
</div>

<script>
    function myfunction(){
        var val,text1,text2,text3,text4;
        val = document.getElementById("numb").value;

        document.getElementById("text1").innerHTML= val.toString(10);
        document.getElementById("text1").innerHTML= val.toString(16);
        document.getElementById("text1").innerHTML= val.toString(8);
        document.getElementById("text1").innerHTML= val.toString(2);
    }
</script>
</code>```

<p>Is there any problem in the code? I didn't attached the css code here. But the output showing the same value in every field. Why is this happening? Is there any problem related to the variables? </p>

答:
You first need to parse the string value to an integer:

```<code>val = document.getElementById("numb").value;
</code>```

should be

```<code>val = parseInt(document.getElementById("numb").value);
</code>```

function myfunction() {
  var val, text1, text2, text3, text4;
  val = parseInt(document.getElementById("numb").value);

  document.getElementById("text1").innerHTML = val.toString(10);
  document.getElementById("text2").innerHTML = val.toString(16);
  document.getElementById("text3").innerHTML = val.toString(8);
  document.getElementById("text4").innerHTML = val.toString(2);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="featurebox">
  <h1>Javascript Learning</h1>
  <div class="bag">
    <p>Input Your Value here :<input id="numb" placeholder="provide your value here">
      <button class="btn" onclick="myfunction()">Result</button>
    </p>

    <table border="1px solid black">
      <tr>
        <td>Decimal Value</td>
        <td>Hexadecimal Value</td>
        <td>Octal Value</td>
        <td>Binary Value</td>
      </tr>
      <tr>
        <td>
          <p id="text1"></p>
        </td>
        <td>
          <p id="text2"></p>
        </td>
        <td>
          <p id="text3"></p>
        </td>
        <td>
          <p id="text4"></p>
        </td>
      </tr>
    </table>
  </div>
  <footer>&copy Copyright Reserved by Shah Imran </footer>
</div></code>```

Body:
Javascript Learning

Input Your Value here :
            <input id="numb" placeholder="provide your value here">
            <button class="btn"  onclick="myfunction()">Result</button>

                Decimal Value
                Hexadecimal Value
                Octal Value
                Binary Value

    &copy Copyright Reserved by Shah Imran

Is there any problem in the code? I didn't attached the css code here. But the output showing the same value in every field. Why is this happening? Is there any problem related to the variables?

Body:
You first need to parse the string value to an integer:

val = document.getElementById("numb").value;

should be

val = parseInt(document.getElementById("numb").value);

function myfunction() {
  var val, text1, text2, text3, text4;
  val = parseInt(document.getElementById("numb").value);

  document.getElementById("text1").innerHTML = val.toString(10);
  document.getElementById("text2").innerHTML = val.toString(16);
  document.getElementById("text3").innerHTML = val.toString(8);
  document.getElementById("text4").innerHTML = val.toString(2);
}

<div class="featurebox">
  <h1>Javascript Learning</h1>
  <div class="bag">
    <p>Input Your Value here :<input id="numb" placeholder="provide your value here">
      <button class="btn" onclick="myfunction()">Result</button>
    </p>

    <table border="1px solid black">
      <tr>
        <td>Decimal Value</td>
        <td>Hexadecimal Value</td>
        <td>Octal Value</td>
        <td>Binary Value</td>
      </tr>
      <tr>
        <td>
          <p id="text1"></p>
        </td>
        <td>
          <p id="text2"></p>
        </td>
        <td>
          <p id="text3"></p>
        </td>
        <td>
          <p id="text4"></p>
        </td>
      </tr>
    </table>
  </div>
  <footer>&copy Copyright Reserved by Shah Imran </footer>
</div>


问:
How to adjust TextField width?
I'm re-writing a simple app which calculates averages. However, I have a hard time with a TextField. I would like it to be exactly as on a first screenshot.

The TextField's width is stretched, I don't want that. I want it to be exactly as it is on the screenshot.

Desired look:

What I have:

Code:

import 'package:flutter/material.dart';
import 'package:easy_localization/easy_localization.dart';

class ArithmeticAverageScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('arithmetic_average_title').tr(),
      ),
      body: Container(
        padding: EdgeInsets.all(16.0),
        child: Column(
          children: <Widget>[
            Card(
              child: Container(
                padding: EdgeInsets.symmetric(vertical: 20.0),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    ListTile(
                      leading: Icon(Icons.help),
                      title: Text('arithmetic_average_help').tr(),
                      subtitle: Text('arithmetic_average_help_content').tr(),
                    )
                  ],
                ),
              )
            ),
            SizedBox(height: 16.0),
            Card(
              child: Container(
                padding: EdgeInsets.symmetric(vertical: 20.0, horizontal: 20.0),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: <Widget>[
                    Text('arithmetic_average_your_grades', style: Theme.of(context).textTheme.headline5).tr(),
                    SizedBox(height: 16.0),
                    Text('arithmetic_average_grades_one_at_a_time', style: Theme.of(context).textTheme.headline6,).tr(),
                    SizedBox(height: 16.0),
                    Text('arithmetic_average_grade', style: Theme.of(context).textTheme.subtitle2).tr(),
                    TextField()
                  ],
                ),
              ),
            )
          ],
        ),
      )
    );
  }
}
```

答:
Use Row Widget, and put Expanded Widget as child Widget and inside that put your widgets, as Expanded will take up equal space.</p>

```<code>return Row(
  children: [
    Expanded(
       child: TextField();
    ),
    Expanded(
       child: Button();
    )
  ],
);
</code>```

Title: How to adjust TextField width?

Body:
Use Row Widget, and put Expanded Widget as child Widget and inside that put your widgets, as Expanded will take up equal space.

return Row(
  children: [
    Expanded(
       child: TextField();
    ),
    Expanded(
       child: Button();
    )
  ],
);