text:
Q: TypeError with Django URL Regex Hi I'm always been confused with Regex, and I don't understand the responses to the other help threads.
Basically my question is, can i combine
r'^input/?$'

and
r'^input/index.html?$'

into this?
r'^input(/(index.html?)?)?$'

In Django, I get this error:
input() takes exactly 1 argument (3 given)

It only gives the error when it matches correctly, so maybe it's not a regex problem?

A: Personally, I would prefer not to combine the two regular expressions. I think that having two url patterns,
url(r'^input/?$', input, name="input"),
url(r'^input/index.html?$', input),

is more readable than one.
However, if you do want to combine the two, you can use non-capturing parentheses:
r'^input(?:/(?:index.html?)?)?$'

A quick example might help explain:
>>> import re
>>> # first try the regex with capturing parentheses
>>> capturing=r'^input(/(index.html?)?)?$'
>>> # Django passes the two matching strings to the input view, causing the type error
>>> print re.match(capturing, "input/index.html").groups()
('/index.html', 'index.html')
>>> # repeat with non capturing parentheses
>>> non_capturing=r'^input(?:/(?:index.html?)?)?$'
>>> print re.match(non_capturing, "input/index.html").groups()
()

See the Regular Expression Advanced Syntax Reference page for more info.

A: If you use this in your urlpatterns you don't need to write ? symbol because everything that comes after that you can parse in your view function. And the request to /input/index.html?param=2 will be correctly processed with r'^input/index.html$' regex. Then in the view function you can obtain parameters like so:
def my_view(request):
    param = request.GET.get('param', 'default_value')

Find more info here: https://docs.djangoproject.com/en/1.9/topics/http/urls/


text:
Q: how can i use replace function in JSP to escape single quote i just want to ask how to use REPLACE function  in JSP to escape  single quote
like addslashes() in PHP
my code is
String task_name= request.getParameter("task_name");
String rep_task_name=task_name.replace("\'","\\\'");
st2 = con.createStatement();
st2.executeUpdate("UPDATE taskes SET task_name='"+rep_task_name+"');

thanks

A: DO NOT use SQL statements constructed this way, USE PreparedStatement (why):
String task_name = request.getParameter("task_name");
st2 = con.prepareStatement("UPDATE tasks SET task_name = ?"); // missing WHERE?
st2.setString(1, task_name);
st2.executeUpdate();

The JDBC driver will sanitize the parameters for you.

A: thanks for ur replay
the full code is
<%
        request.setCharacterEncoding("UTF-8");
        String task_order = request.getParameter("task_order");
        //String task_id = request.getParameter("task_id");
        String task_name = request.getParameter("task_name");
        String implementation_phase = request.getParameter("implementation_phase");
        String what_has_thereon = request.getParameter("what_has_thereon");
        String executing_agency = request.getParameter("executing_agency");
        String note = request.getParameter("note");
        String end_date = request.getParameter("end_date");
        String task_id = request.getParameter("task_id");
        String team_id = request.getParameter("team_id");
        //String expression ="\'";
       // String replacement = "\'";
       // String rep_task_name=task_name.replace('v', 'q');
      String rep_task_name=task_name.replace("\'","\\\'");;

        try {

        Class.forName("com.mysql.jdbc.Driver");
        String hostname = "localhost:3306";
        String dbname = "teams_manage";
        String dburl = "jdbc:mysql://" + hostname + "/" + dbname;
        String user = "root";
        String pass = "";
             Connection con=DriverManager.getConnection( "jdbc:mysql://"+hostname+"/"+dbname+"?useUnicode=true&characterEncoding=UTF-8",user,pass);
            Statement st2 = null;

            st2 = con.createStatement();
           // session.getAttribute("role_die");
            st2.executeUpdate("UPDATE taskes SET task_order='"+task_order+"', task_name='"+rep_task_name+"',implementation_phase='"+implementation_phase+"', what_has_thereon='" + what_has_thereon + "', executing_agency='" + executing_agency + "', end_date='" + end_date + "', note='" + note + "' WHERE task_id =" + task_id + "");
            response.sendRedirect("index.jsp?dire="+session.getAttribute("role_die")+"&mmid="+session.getAttribute("memmber_id")+"&team_id="+session.getAttribute("team_id"));
        } catch (ClassNotFoundException ex) {
            throw new SecurityException("not fund" + ex.toString());
        }

    %>

so u mean i should be change the statements and use con.prepareStatement function

redpajama_set_name: RedPajamaStackExchange


text:
Q: ошибка с использованием Event event зачеркнут и появляется это пояснение:

Deprecated symbol used, consult docs for better alternative less
  Inspection info: Checks for using deprecated functions and variables.
  The validation orks in JavaScript, html, or jsp files.

function openCart(event) {
  event.preventDefault();
  $.ajax({
    url: '/cart/open',
    type: 'GET',
    success: function(res) {
      $('#cart .modal-content').html(res);
      $('#cart').modal('show');
    },
    error: function() {
      alert('Неизвестная ошибка');
    }
  })
}
Корзина

ошибка в браузере:

Uncaught ReferenceError: openCart is not defined
  at HTMLAnchorElement.onclick (VM32 :21)

A:
Из-за этого корзина просто не открывается.

Корзина не открывается из-за ошибки

Uncaught ReferenceError: openCart is not defined at
  HTMLAnchorElement.onclick (VM32 :21)

А эта ошибка возникает, потому что функция openCart определена внутри другой функции и, по этой причине, не видна в глобальной области видимости.


text:
Q: getting 2 different value from the same variable - React custom hook I created two componentes :
component useImgPicker - custom hook:

*

*responsible to open the camera

*user can take a picture

*save the image url to imgUrl variable
return:

*

*someFunction (function that open the camera and save the url)

*imgUrl (the state - string)

*component App - use the custom hook

*

*use the custom hook

*after the user click on the button, diplayImg function activated

*diplayImg function use the custom hook, and make change to hasTakePicture variable (become true).

*after hasTakePicture become true -> new <View> render with

the desire:  the source url inside the <Img> will change to the newUrl
the result: the value of newUrl inside <Img> is the same, but inside <Text> {newUrl} </Text>  the newUrl  is change
component ImgPicker  - custom react hook
import {useState} from 'react';
const useImgPicker = ()=>{
     const [imgUrl, setImgUrl] = useState(''); //string

     const someFunction = ()=>{
         // make chang to imgUrl
          const newUrl = "/some dumi url.png"
         setImgUrl(newUrl);
      }

return{ imgUrl, someFunction  }

}

export default useImgPicker;

component App - use the custom hook
import React,{useState} from 'react';
import useImgPicker from './ImgPicker.js'

const App = ()=>{

   const { imgUrl, someFunction  } = useImgPicker ();
  const [hasTakePicture, setHasTakePicture] = useState(false);

const diplayImg = ()=>{
     someFunction();
     setHasTakePicture(true);
     console.log(imgUrl); // here the value of imgUrl is -> ''  empty (default value)

}

    return(
         {hasTakePicture ? (
            <View>
              // inside the 'source' prop of the Image the value of imgUrl-> ''  empty (default value)
             <Image style={styles.image} source={{uri: imgUrl}} resizeMode='contain'/>

           {imgUrl}  // -> here the value of imgUrl is -> newUrl
         </View>

        ) :
        (
          <View></View>
        )
      }

      <Button title="Take Picture" onPress = {diplayImg } >
    )

}

A: diplayImg method should use useCallback hook with dependency of imgUrl, I guess this will solve also the update of image source.
if not, consider splitting it into a new method that gets the view to render and wrapped that method with memo from react (React.memo) with the relevant dependency. (only the method that shows EmptyView vs the Image view)


text:
Q: ASP.NET SignalR client-server authentication using (Azure active directory b2c) Json web token validation I have two application...... one is JavaScript signalR client and the other one is asp.net web application used as signalR server to broadcast the updates to the client. And I was trying to use azure active directory b2c service to offer authentication and authorization for user through client application to access the resources in the server. So, that only the authenticated user of JavaScript client can initiate signalR connection with the asp.net web application hosting signalR server after the token validation.
As, signalR uses web-sockets we cannot supply the token in the HTTP connection request header. It seems that I should use query string to supply authentication token in the signalR connection request.
After receiving that token in the asp.net server application I need to validate that token and allow the JavaScript client application to have a signalR connection.
I want to implement exactly the same thing in this blog post https://kwilson.io/blog/authorize-your-azure-ad-users-with-signalr/ but using azure active directory b2c.

A: It seems like others might also have same problem using ASP.NET SignalR Client and server architecture.
Actually, with lots of efforts I was able to solve this issue by customizing the AuthorizeModule of signalR hubs. Actually I override AuthorizeHubConnection() and AuthorizeHubMethodInvocation() using AuthorizeAttribute inheritance in CustomAuthorization class.
First of all I added the GlobalHost.HubPipeline.AddModule(module) in app.Map("/signalr", map =>{ .... } in startup Configuration. You can see it in the following startup.cs.
using Microsoft.Owin;
using Microsoft.Owin.Cors;
using Owin;
using Microsoft.AspNet.SignalR;
using TestCarSurveillance.RealTimeCommunication.AuthorizationConfiguration;
using Microsoft.AspNet.SignalR.Hubs;

[assembly: OwinStartup(typeof(TestCarSurveillance.RealTimeCommunication.Startup))]

namespace TestCarSurveillance.RealTimeCommunication
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            //After adding Authorization module in GlobalHost.HubPipeline.AddModule(module)
            //program was unable to create the log file so I have added it.
            log4net.Config.XmlConfigurator.Configure();

            // Branch the pipeline here for requests that start with "/signalr"
            //app.UseWelcomePage("/");
            app.Map("/signalr", map =>
            {
                // Setup the CORS middleware to run before SignalR.
                // By default this will allow all origins. You can
                // configure the set of origins and/or http verbs by
                // providing a cors options with a different policy.

                map.UseCors(CorsOptions.AllowAll);
                var hubConfiguration = new HubConfiguration
                {
                    EnableDetailedErrors = true,
                    // You can enable JSONP by uncommenting line below.
                    // JSONP requests are insecure but some older browsers (and some
                    // versions of IE) require JSONP to work cross domain
                    EnableJSONP = true
                };

                // Require authentication for all hubs
                var authorizer = new CustomAuthorization();
                var module = new AuthorizeModule(authorizer, authorizer);
                GlobalHost.HubPipeline.AddModule(module);

                map.RunSignalR(hubConfiguration);
            });
        }

    }
}

This Authorize module calls CustomAuthorize.cs class in each signalR hub OnConnected(), OnDisconnected(), OnReconnected() and hub methods that the client can call.
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using Microsoft.AspNet.SignalR.Owin;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Owin.Security.Jwt;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Security.Claims;

namespace TestCarSurveillance.RealTimeCommunication.AuthorizationConfiguration
{

    public class CustomAuthorization : AuthorizeAttribute
    {
        // These values are pulled from web.config for b2c authorization
        public static string aadInstance = ConfigurationManager.AppSettings["ida:AadInstance"];
        public static string tenant = ConfigurationManager.AppSettings["ida:Tenant"];
        public static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
        public static string signUpInPolicy = ConfigurationManager.AppSettings["ida:SignUpInPolicyId"];

        static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        //This method is called multiple times before the connection with signalR is established.
        public override bool AuthorizeHubConnection(HubDescriptor hubDescriptor, IRequest request)
        {
            var metadataEndpoint = string.Format(aadInstance, tenant, signUpInPolicy);
            // Extract JWT token from query string.
            var userJwtToken = request.QueryString.Get("Authorization");
            if (string.IsNullOrEmpty(userJwtToken))
            {
                return false;
            }

            // Validate JWT token.
            //var tokenValidationParameters = new TokenValidationParameters { ValidAudience = ClientId };
            //Contains a set of parameters that are used by a SecurityTokenHandler when validating a SecurityToken.
            TokenValidationParameters tvps = new TokenValidationParameters
            {
                // Accept only those tokens where the audience of the token is equal to the client ID of this app
                // This is where you specify that your API only accepts tokens from its own clients
                // here the valid audience is supplied to check against the token's audience
                ValidAudience = clientId,
                ValidateIssuer = false,
                // It is the authentication scheme used for token validation
                AuthenticationType = signUpInPolicy,
                //SaveSigninToken = true,

                //I've configured the "NameClaimType" of the "TokenValidationParameters" to use the claim named "objectidentifer" ("oid")
                //This will facilitate reading the unique user id for the authenticated user inside the controllers, all we need to call
                //now inside the controller is: "User.Identity.Name" instead of querying the claims collection each time

                //Gets or sets a String that defines the NameClaimType.
                NameClaimType = "http://schemas.microsoft.com/identity/claims/objectidentifier"
            };
            try
            {
                var jwtFormat = new JwtFormat(tvps, new OpenIdConnectCachingSecurityTokenProvider(metadataEndpoint));
                var authenticationTicket = jwtFormat.Unprotect(userJwtToken);

                if(authenticationTicket != null && authenticationTicket.Identity !=null && authenticationTicket.Identity.IsAuthenticated)
                {
                    var email = authenticationTicket.Identity.FindFirst(p => p.Type == "emails").Value;

                    // It is done to call the async method from sync method
                    //the ArgumentException will be caught as you'd expect, because .GetAwaiter().GetResult() unrolls the first exception the same way await does.
                    //This approach follows the principle of least surprise and is easier to understand.
                    // set the authenticated user principal into environment so that it can be used in the future
                    request.Environment["server.User"] = new ClaimsPrincipal(authenticationTicket.Identity);

                    return true;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                log.Error(ex);
                //throw ex;

            }

            return false;
        }

        public override bool AuthorizeHubMethodInvocation(IHubIncomingInvokerContext hubIncomingInvokerContext, bool appliesToMethod)
        {
            var connectionId = hubIncomingInvokerContext.Hub.Context.ConnectionId;
            //Check the authenticated user principal from environment
            var environment = hubIncomingInvokerContext.Hub.Context.Request.Environment;
            //ClaimsPrincipal supports multiple claims based identities
            var principal = environment["server.User"] as ClaimsPrincipal;
            if(principal != null && principal.Identity != null && principal.Identity.IsAuthenticated)
            {
                    // create a new HubCallerContext instance with the principal generated from token
                    // and replace the current context so that in hubs we can retrieve current user identity
                    hubIncomingInvokerContext.Hub.Context = new HubCallerContext(new ServerRequest(environment), connectionId);
                    return true;
            }
            return false;
        }
    }
}

After we receive the token from the query string we need to setup TokenValidationParameters use it in metadataEndpoint for token validation. The token validation is done in before having the hub connection so, that only the authorized user can have a connection and if the connection is not successful it returns 401 response. It is implemented in OpenIdConnectCachingSecurityTokenProvider.cs class. This class is being used by having following line of code in AuthorizeHubConnection() method.
var jwtFormat = new JwtFormat(tvps, new OpenIdConnectCachingSecurityTokenProvider(metadataEndpoint));
var authenticationTicket = jwtFormat.Unprotect(userJwtToken);

As, the last part of this authorization configuration I have inherited IIssureSecurityKeyProvider in OpenIdConnectCachingSecurityTokenProvider.cs class. The complete implementation of it can be seen in the following code.
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Owin.Security.Jwt;
//using System.IdentityModel.Tokens;

namespace TestCarSurveillance.RealTimeCommunication.AuthorizationConfiguration
{
    //IIssuerSecurityKeyProvider Interface Provides security Key information to the implementing class.

    // This class is necessary because the OAuthBearer Middleware does not leverage
    // the OpenID Connect metadata endpoint exposed by the STS by default.

    internal class OpenIdConnectCachingSecurityTokenProvider : IIssuerSecurityKeyProvider
    {
        //Manages the retrieval of Configuration data.
        public ConfigurationManager<OpenIdConnectConfiguration> _configManager;

        private string _issuer;
        private IEnumerable<SecurityKey> _keys;

        //this class will be responsible for communicating with the "Metadata Discovery Endpoint" and issue HTTP requests to get the signing keys
        //that our API will use to validate signatures from our IdP, those keys exists in the jwks_uri which can read from the discovery endpoint
        private readonly string _metadataEndpoint;

        //Represents a lock that is used to manage access to a resource, allowing multiple threads for reading or exclusive access for writing.
        private readonly ReaderWriterLockSlim _synclock = new ReaderWriterLockSlim();
        public OpenIdConnectCachingSecurityTokenProvider(string metadataEndpoint)
        {
            _metadataEndpoint = metadataEndpoint;
            //_configManager = new ConfigurationManager<OpenIdConnectConfiguration>(metadataEndpoint, new OpenIdConnectConfigurationRetriever());
            _configManager = new ConfigurationManager<OpenIdConnectConfiguration>(metadataEndpoint, new OpenIdConnectConfigurationRetriever());
            //_configManager = new ConfigurationManager<OpenIdConnectConfiguration>(metadataEndpoint);
            RetrieveMetadata();
        }

        /// <summary>
        /// Gets the issuer the credentials are for.
        /// </summary>
        /// <value>
        /// The issuer the credentials are for.
        /// </value>
        public string Issuer
        {
            get
            {
                RetrieveMetadata();
                _synclock.EnterReadLock();
                try
                {
                    return _issuer;
                }
                finally
                {
                    _synclock.ExitReadLock();
                }
            }
        }
        /// <summary>
        /// Gets all known security keys.
        /// </summary>
        /// <value>
        /// All known security keys.
        /// </value>
        public IEnumerable<SecurityKey> SecurityKeys
        {
            get
            {
                RetrieveMetadata();
                _synclock.EnterReadLock();
                try
                {
                    return _keys;
                }
                finally
                {
                    _synclock.ExitReadLock();
                }
            }
        }

        private void RetrieveMetadata()
        {
            _synclock.EnterWriteLock();
            try
            {
                //Task represents an asynchronous operation.
                //Task.Run Method Queues the specified work to run on the ThreadPool and returns a task or Task<TResult> handle for that work.
                OpenIdConnectConfiguration config = Task.Run(_configManager.GetConfigurationAsync).Result;
                _issuer = config.Issuer;
                _keys = config.SigningKeys;
            }
            finally
            {
                _synclock.ExitWriteLock();
            }
        }
    }
}

After implementing this we do not need to have [Authorize] attribute in any hub method and this middle-ware will handle the request authorization and only authorized user will have a signalR connection and only authorized user can invoke the hub method.
At last I would like to mention that for this client server architecture to work we need to have separate b2c tenant client application and b2c tenant server application and b2c tenant client application should have API access to the b2c tenant server application. Azure b2c application should be configured as in this example https://learn.microsoft.com/en-us/aspnet/core/security/authentication/azure-ad-b2c-webapi?view=aspnetcore-2.1
Although, it is for .net core but it is also valid for asp.net and only difference is that b2c configuration should be at web.config


text:
Q: CardView onClickListener to go to another intent I'm trying to write code code such that when clicked on any cardview, it moves to another activity screen. Here is my code for the xml and java part. When the app is running, the cardview can be displayed but, the new activity is not opening.
This the code for XML.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="10dp"
    android:background="@drawable/homepage"
    android:gravity="center"
    android:id="@+id/LinearLayout1">

    <!-- A CardView that contains a TextView -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_marginTop="200dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp">

        <LinearLayout
            android:clipToPadding="false"
            android:gravity="center"
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <androidx.cardview.widget.CardView
                android:foreground="?android:attr/selectableItemBackground"
                android:clickable="true"
                android:id="@+id/mypet"
                android:layout_width="160dp"
                android:layout_height="190dp"
                android:layout_margin="10dp">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical"
                    android:gravity="center">

                    <ImageView
                        android:layout_width="64dp"
                        android:layout_height="64dp"
                        android:src="@drawable/petlogo100"
                        android:padding="10dp"/>

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textStyle="bold"
                        android:layout_marginTop="10dp"
                        android:layout_gravity="center"
                        android:text="My Pet"/>

                    <View
                        android:layout_width="match_parent"
                        android:layout_height="1dp"
                        android:background="@color/lightgray"
                        android:layout_margin="10dp"/>

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:gravity="center"
                        android:text="Information about your Pet"
                        android:padding="5dp"
                        android:textColor="@android:color/darker_gray"/>

                </LinearLayout>

            </androidx.cardview.widget.CardView>

            <androidx.cardview.widget.CardView
                android:id="@+id/health"
                android:foreground="?android:attr/selectableItemBackground"
                android:clickable="true"
                android:layout_width="160dp"
                android:layout_height="190dp"
                android:layout_margin="10dp">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical"
                    android:gravity="center">

                    <ImageView
                        android:layout_width="64dp"
                        android:layout_height="64dp"
                        android:src="@drawable/pethealth"
                        android:padding="10dp"/>

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textStyle="bold"
                        android:layout_marginTop="10dp"
                        android:text="Track Health"/>

                    <View
                        android:layout_width="match_parent"
                        android:layout_height="1dp"
                        android:background="@color/lightgray"
                        android:layout_margin="10dp"/>

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:gravity="center"
                        android:text="Follow the health of your Pet"
                        android:padding="5dp"
                        android:textColor="@android:color/darker_gray"/>

                </LinearLayout>
            </androidx.cardview.widget.CardView>

        </LinearLayout>

        <LinearLayout
            android:clipToPadding="false"
            android:gravity="center"
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <androidx.cardview.widget.CardView
                android:foreground="?android:attr/selectableItemBackground"
                android:clickable="true"
                android:id="@+id/vetVisit"
                android:layout_width="160dp"
                android:layout_height="190dp"
                android:layout_margin="10dp">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical"
                    android:gravity="center">

                    <ImageView
                        android:layout_width="64dp"
                        android:layout_height="64dp"
                        android:src="@drawable/vetvisit2"
                        android:padding="10dp"/>

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textStyle="bold"
                        android:layout_marginTop="10dp"
                        android:layout_gravity="center"
                        android:text="Visit Vet"/>

                    <View
                        android:layout_width="match_parent"
                        android:layout_height="1dp"
                        android:background="@color/lightgray"
                        android:layout_margin="10dp"/>

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:gravity="center"
                        android:text="Details about the medical schedule"
                        android:padding="5dp"
                        android:textColor="@android:color/darker_gray"/>

                </LinearLayout>

            </androidx.cardview.widget.CardView>

            <androidx.cardview.widget.CardView
                android:id="@+id/overall"
                android:foreground="?android:attr/selectableItemBackground"
                android:clickable="true"
                android:layout_width="160dp"
                android:layout_height="190dp"
                android:layout_margin="10dp">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical"
                    android:gravity="center">

                    <ImageView
                        android:layout_width="64dp"
                        android:layout_height="64dp"
                        android:src="@drawable/overall_health"
                        android:padding="10dp"/>

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textStyle="bold"
                        android:layout_marginTop="10dp"
                        android:text="Track Health"/>

                    <View
                        android:layout_width="match_parent"
                        android:layout_height="1dp"
                        android:background="@color/lightgray"
                        android:layout_margin="10dp"/>

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:gravity="center"
                        android:text="Follow the health of your Pet"
                        android:padding="5dp"
                        android:textColor="@android:color/darker_gray"/>

                </LinearLayout>
            </androidx.cardview.widget.CardView>

        </LinearLayout>

    </LinearLayout>

</LinearLayout>

This the code for JAVA.
    package com.example.healthypet;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private CardView petCard, healthCard,vetCard,overallCard;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        petCard = (CardView) findViewById(R.id.mypet);
        healthCard = (CardView) findViewById(R.id.health);
        vetCard = (CardView) findViewById(R.id.vetVisit);
        overallCard = (CardView) findViewById(R.id.overall);

    }

    @Override
    public void onClick(View v) {

        Intent i;

        switch (v.getId()){

            case R.id.mypet:

                i= new Intent(this,MyPetPage.class);
                startActivity(i);
                break;

            case R.id.health:

                i= new Intent(this,PetHealth.class);
                startActivity(i);
                break;

            case R.id.vetVisit:

                i= new Intent(this,VetPage.class);
                startActivity(i);
                break;

            case R.id.overall:

                i= new Intent(this,overall.class);
                startActivity(i);
                break;

                default:break;

        }

    }

}


text:
Q: How to get versionCode of app outside my own? I am attempting to add a function to that will check a json file on my server for the versionCode of an app outside of my own and if the versionCode in json on the server is greater than the one of the app outside of my own, then do an update action.
The update action works fine, however, I am experiencing issues getting the versionCode of the outside app. The versionCode always returns as 0 instead of the actual version of the outside app.

Why doesn't it return the proper version?

Here is my code for fetching the versionCode of the other app:
public static int getinstVersionCode(Context mContext) {
    if (mContext != null) {
        try {
            return mContext.getPackageManager().getPackageInfo(Constants.PACKAGE_NAME, 0).versionCode;
        } catch (PackageManager.NameNotFoundException ignored) {
        }
    }
    return 0;
}

The PACKAGE_NAME equals the com.example.app app package name that is held in the json file on my server:
static final String APK_VERSION_CODE = "versionCode";
static final String PACKAGE_NAME = "package";

And finally, the json file itself:
"versionCode":0,
"package":"com.example.app",

A: Check the exception, the application which version you are trying to get must be present on the device and exactly match the package name.


text:
Q: Strange Error regarding using Std::List as a Class Member Variable I am trying to implement an event handling system in C++ and encountered a compiler error for std::list which I am not able to figure out why.
There is an EventManager class whose role is to manage and fire events. There is a list which stores events to be processed.
If the std::list is declared as a class member, there is an error. Whereas if the list is declared as a local method variable, there is no error.
The class goes like this:
class EventManager
{
   //Queue for events. IEventPtr is a typedef of shared_ptr to an
   //Events class
   typedef std::list<IEventPtr> EventQueue;
   EventQueue m_eventQueue;

   virtual bool VQueueEvent(const IEventPtr& pEvent) const;
}

The definition for the VQueueEvent method is:
bool EventManager::VQueueEvent(const IEventPtr& pEvent) const
{
    //compiler highlighted an error for a class member list
    m_eventQueue.push_back(pEvent);

    //a locally declared list works. No compiler error
    std::list<IEventPtr> eventList;
    eventList.push_back(pEvent);

    return true;
}

From the above code, the compiler underlined the dot notation and had the message "No instance of overloaded function std::list<.....> matches the argument list and object (the object has type qualifiers that prevent a match. Argument types are (const IEventPtr). Object type is const EventManager::EventQueue"
When compiling, the compiler will show the error:
std::list<....>::push_back. 2 overloads have no legal conversion for 'this' pointer
What is causing this error and how to solve it?

A: The method EventManager::VQueueEvent is marked const. This means it can't modify class members.
However, the push_back method clearly needs to modify the content of the eventList member, and thus, the error.
Remove the const qualifier and it should be fine.

A: You wasn't able to push_back to a class member beacause you declared the member function as const which means you can't modify the class and any of its members.
The definition for the VQueueEvent method should be like this:
bool EventManager::VQueueEvent(const IEventPtr& pEvent) /* const */
{
    // Now this should work fine
    m_eventQueue.push_back(pEvent);

    return true;
}

and declaration like this:
virtual bool VQueueEvent(const IEventPtr& pEvent) /* const */;


text:
Q: GRASS GIS addon "extension not found"; could the problem be with the GRASS Addons server? I'm using GRASS GIS Ver 7.2.2. When I enter command mode and type "g.extension r.hypso" I get the message:
Downloading precompiled GRASS Addons ...
ERROR: Extension  not found
This happens with all of the extensions I've tried to download (attempts over a 3-day period). I re-installed GRASS with no luck.
I am able to query the server's directories and get a list its contents but not successfully add an Addon to GRASS GIS.

A: It's working already. I was able to install it successfully without change anything. So I guess they solve the problem!

A: The server was indeed apparently experiencing technical difficulties. I was finally able to install GRASS addons today using g.extension, something that I'd been trying to do for several days.

A: Same problem as you, can't download addons from repository, they seam to exist but can't find them when I try to install. About the platform I think this version (even win 10) is the Windows-8-62.9200 compiled binary, so don't worry it work perfectly, the problem is the server, I guess.

A: The windows precompiled versions of the addons don't appear to be located in the main repository at the moment (now at https://github.com/OSGeo/grass-addons), but at http://wingrass.fsv.cvut.cz.  The problem seems to be that the (incorrect) url is hardcoded in grass.
There is a ticket for this: https://trac.osgeo.org/grass/ticket/3455
Python scripts can be installed manually by copying the files as follows (example for v.transects.py):

v.transects.py to %APPDATA%\GRASS7\addons\scripts and link to \bin
v.transects.html to %APPDATA%\GRASS7\addons\docs\html\
image files to %APPDATA%\GRASS7\addons\docs\html\
Update %APPDATA%\GRASS7\addons\modules.xml to match the relevant section
  from https://grass.osgeo.org/addons/grass7/modules.xml
You might need to update the name of the script in modules.xml to add the py extension (or rename the file).

You can find the addon in the modules table of the layer manager under addons.

A: The windows repository seems to be hardcoded to http://wingrass.fsv.cvut.cz/grass74/x86_64/addons/grass-7.4.4/ (in grass 7.4 at least).
The files are actually located at http://wingrass.fsv.cvut.cz/grass74/x86_64/addons/grass-7.4.svn/
C:\>g.extension url="http://wingrass.fsv.cvut.cz/grass74/x86_64/addons/grass-7.4.svn/"
--verbose extension=v.tin.to.rast
Downloading precompiled GRASS Addons <v.tin.to.rast>...
Downloading source code for <v.tin.to.rast> from
<http://wingrass.fsv.cvut.cz/grass74/x86_64/addons/grass-7.4.4/v.tin.to.rast.zip>
which is identified as 'remote_zip' type of source...
ERROR: Extension <v.tin.to.rast> not found

Bug ticket https://trac.osgeo.org/grass/ticket/3455


text:
Q: CPQ Clone Group - QCP I have a request to return a custom cumulative total for each quote line group based on the lines included in each group.  Thanks to this article, I've got the QCP looping through groups on the quote and then looping through each line and updating a this custom total field specific to each group.  I'm running into problems when a group is cloned.  Specifically - the user will clone a group and then click save within the quote line editor.  Upon the Group records being created for the quote, the cloned group record will not have an updated custom 'Total' field that I'm targeting within the QCP.  I've tried the methods included with the Custom Action Plugin to no avail.  Per this post (and it's related Idea), it looks like the beforeCloneLine/afterCloneLine methods provided aren't actually called when a user clones a group.
Does anyone know of a workaround I could try for this?


text:
Q: Decode .do URL Request unique ID I'm building an Excel script that will bypass a form on a website, and parse the request directly in a URL to generate the desired output (then pull that data into Excel).
I have everything working, but part of the solution is to include a parameter value that seems to be a combination of fixed and variable characters. The website is using a .do Java serverlet file for server side requests. The script apparently decodes this, and looks for something before executing. If any value is different in the generated codes, it will not execute.
Here are three examples. Each work successfullly. How can I go about decoding this, so that I may create a dynamic code of my own vs. re-using the same ID over and over?
My guess is that this would need to be some base conversion? Not sure if it's possible, but there's certainly a pattern in the codes, at least for the first and last few characters:
1:
H4sIAAAAAAAAAL2QTU_DMAyGf824VKrsdKvKwYeqHQIJbTAGO0wcQhq2SN1aJRkfUn48brsDMMQNbm9iW378BAQgERCQ8MxalStvmv1C2WoNjxS66p2WVm2jwhqvrZF976t-km3rRMwjsddv0sWb5mWU5BlwXdBIXExXOceki67Vyjwbda2l07cHbd-HNXHVcMuYdtpvm2rZFLKu-WNCh_1xRFf8zghO0Naup8rtxsWttHL3IOuDZmJBgCEhAQLCuMuTIac0Dxl9IQnn1Nqmyve82su6NK7lbTRcAFlPLwDTcRAMWRnnrVH-GwoeLZXHMjuI-tk_lzQY4JiSq2_kRttPJn7Uhv-uLaHZfLG8jIr5qpzOovvZ1fJ3mevTUzrBhEyIwITY4TEdMhrCB5_buH2_AgAA
2:
H4sIAAAAAAAAALWQTU8CMRCGfw1eNjZtF8hymEOziycjKERjiIfaHaHJwjZt8SPpj3d24aCinvT2ttPpPPMkwTnIJLgAcea9USbadndjfL3iD5C66gK1N5us9Dait7p_-4KP2rkgGbWwiK86sHX7PMhVwakuYSAvpneKYt7F4NDYJ2suUQe83qN_O4xhdUtPhrDFuGnrZVvqpqGLEex3xxas6VwAP0FbhZ5K-XVgTnu9vdXNHolYAhcpB8nFJA27PKIseRrDLBXwiSRNwPm2VjsaHXVT2eBoGhw24EVPT_-MZZIEWdsQvTXxC4o4WqqOZXKQ9b3_LulggOIYQjPXa_QfTHyrTfyVNnLhKozaNuFHYzncq2p2NZBlVrJszs4XS7Wc_q5ydbpIpxcE8QlOfCLv6Do4IhP8Hb4znrK-AgAA
3:
H4sIAAAAAAAAAG2PS2vDMBCEf016KYiV7AT3sAeRNqdA6YP2EHpQpU0icCyxkvsA_fjKdi-F3mZ3ZplviwRAWSRIhCtmq232YXi07A7whmVyn8iwPV9v2Wdib-bsJ72bGJMS9URk-jJJnMLHqtEdVF_hSu3uXnWVzSRTJOuP3u7JJHoYib-XGuFCjbR4oXwO7jlsTd_XxRrH4feEXJ27f9AOaabSfEoiGjaXF9OPVIkVgiwNKlBQ2kmvF73B-9LhH5Jyg5GD00Otzqa_9SnWNlw-gG6mVyA3bVEV0vmU2dv8A8nXYOAyAQAA

A: Does this:

|100=1|101=0&rrcActionRcrd[0]=|100=Search+Criteria|101=webapps2.rrc.texas.gov%3A80|102=%2FEWA|103=%2FspecificLeaseQueryAction.do|104=methodToCall|105=unspecified|108=0&rrcActionRcrd[0][searchArgs.paramValue]=|2=01|3=2020|4=01|5=2020|6=O|8=specificLease|9=prodAndTotalDisp|10=0|102=08|103=20164|204=district

make sense for your third example?
Here is the second one:

|100=2|101=1&rrcActionRcrd[0]=|100=Search+Criteria|101=webapps2.rrc.texas.gov%3A80|102=%2FEWA|103=%2FspecificLeaseQueryAction.do|104=methodToCall|105=unspecified|108=0&rrcActionRcrd[0][searchArgs.paramValue]=|2=01|3=2019|4=01|5=2020|6=O|8=specificLease|9=prodAndTotalDisp|10=0|102=08|103=20162|204=district&rrcActionRcrd[1]=|100=District%3A+08|101=webapps2.rrc.texas.gov%3A80|102=%2FEWA|103=%2FspecificLeaseQueryAction.do|104=methodToCall|105=search|106=slPager.paramValue|108=0&rrcActionRcrd[1][searchArgs.paramValue]=|2=01|3=2019|4=01|5=2020|6=O|8=specificLease|9=dispDetails|10=0|102=08|103=20162|203=YADON%2C+C.+P.-STATE|204=district&rrcActionRcrd[1][slPager.paramValue]=|1=1|2=10|3=13|4=0|5=2|6=10

and the first one:

|100=2|101=1&rrcActionRcrd[0]=|100=Search+Criteria|101=webapps2.rrc.texas.gov%3A80|102=%2FEWA|103=%2FspecificLeaseQueryAction.do|104=methodToCall|105=unspecified|108=0&rrcActionRcrd[0][searchArgs.paramValue]=|2=01|3=2020|4=01|5=2020|6=O|8=specificLease|9=prodAndTotalDisp|10=0|102=08|103=20164|204=district&rrcActionRcrd[1]=|100=District%3A+08|101=webapps2.rrc.texas.gov%3A80|102=%2FEWA|103=%2FspecificLeaseQueryAction.do|104=methodToCall|105=search|106=slPager.paramValue|108=0&rrcActionRcrd[1][searchArgs.paramValue]=|2=01|3=2020|4=01|5=2020|6=O|8=specificLease|9=prodAndTotalDisp|10=0|102=08|103=20164|203=NORTH+COWDEN+UNIT|204=district&rrcActionRcrd[1][slPager.paramValue]=|1=1|2=10|3=1|4=0|5=1|6=10

What you have here is a Base64 encoded gzip stream. So to decoded you need to Base64 decoded it into a .gz and then unzip it. That's what I did and this is how I did it:
I took your first encoded block and saved it to a file. I did the same thing with the other two blocks. Went to https://www.base64decode.org/ and loaded the first file; downloaded the converted version and saved it with a .gz extension. Did the same thing with the other two files. Then I gunziped them and got the decoded results. I did have some problems with the first and second blocks, but it was related to the way it was showing in the page. Once I took a look at source code of the page and copied it from there I did not have a problem.
You will have to generate the proper format, that should be easy, then you need to gzip it and then encoded it. It will work.


text:
Q: How do I store the html or text of a R helpfile into a variable I would like to store the helpfile of my R function into a variable. I would prefer to store the html version. I would like to do this so that I can write it into a local .html file.
For example, help(glm) generates the following text in the Help pane of Rstudio:
glm {stats} R Documentation
Fitting Generalized Linear Models
Description

glm is used to fit generalized linear models, specified by giving a symbolic description of the linear predictor and a description of the error distribution.
Usage
...

and the corresponding html version, with markdown, can be found at: https://stat.ethz.ch/R-manual/R-devel/library/stats/html/glm.html
However, I have not found anyway of storing a copy of this html as a variable. I have tried helptext <- help(glm), which gives
> str(helptext)
Class 'help_files_with_topic'  atomic [1:1] /usr/lib/R/library/stats/help/glm
  ..- attr(*, "call")= language help(topic = glm)
  ..- attr(*, "topic")= chr "glm"
  ..- attr(*, "tried_all_packages")= logi FALSE
  ..- attr(*, "type")= chr "html"

A: Thanks to the link posted by @Akrun, I realised a simple modification to the existing answer would generate a html file, by changing Rd2txt to Rd2HTML.
file <- help("glm")
pkgname <- basename(dirname(dirname(file)))
temp <- tools::Rd2HTML(utils:::.getHelpFile(file), out = tempfile("Rtxt"),
                  package = pkgname)
file.copy(temp,"~/test.html")


text:
Q: Remove Square Bracket From Array Key PHP I'm needing some help with an array. I know this is more than likely a simple solution, but I'm new so I apologize! I've been stuck on this for a while.
This is the current array that I've got:
Array ( [0] => 3 [1] => 2 [2] => 5 [3] => 2 )

I need the array to look like this:
Array ( 0 => 3, 1 => 2, 2 => 5, 3 => 2 )

I'm trying to pass this information to HighCharts and it won't accept the array in the format I currently have.
Thank you!!!

A: Something like this should work
// your array according to your question
$someArray = array();
$someArray[0] = 3;
$someArray[1] = 2;
$someArray[2] = 5;
$someArray[3] = 2;

// begin string output
$toHighCharts = 'Array(';

// loop through current array items
foreach($someArray as $k=>$v)
{
    // append string with desired format
    $toHghCharts.= $k.'=>'.$v.',';
}

// remove trailing comma
$toHighCharts = substr($toHighCharts, 0, -1);

// end string output
$toHghCharts.= ')';

// output string output
echo $toHighCharts;

A: have you tried to convert the Array to a JavaScript Array with jsonencode?
For example:
var jsarray= <?php echo json_encode($phparray); ?>;


text:
Q: Using polygon pours for small signals in PCB design I'm trying to improve my PCB routing skills. When I started out a few years back, I just layed out the components and ran tracks with a fixed width between them. I didn't even know about polygon pours. Then when I started working with switching regulators, I started noticing the nice polygon shaped traces i.e. TI uses in their datasheets for layout recommendations, to optimize for current flow. So I copied that and started working with power and GND planes and/or polygons. So basically most of my power paths in my designs are now built out of polygons instead of traces. It looks kind of neat.
But now in this current design I'm doing I'm starting to wonder why I shouldn't do more or even just all of my connections using polygons. It allows me to make nicer transitions between different pad sizes, keep better control over where my ground pour goes etc. while electrically speaking it probably doesn't have any added value. In wonder if this is good or bad practise from layout and/or manufacturing point of view.

Here's an example. It's a 2-layer board so I don't have the luxury of a power plane. The highlighted trace is my power net which is a big fat polygon. But I also used wide polygons to connect the 4 0402 resistors in the center to the large pads of a WiFi SoM on thew right (ESP). They could be tiny 6 mil traces like RXD and GPIO0 on the right, but somehow it 'feels' better to make the trace as wide as the pads they connect to. What is good practise for low power signals? Or is it just a matter of taste?
This also makes me wonder about the ground pour. Is it a benefit to have ground pours sitting between those pads or would it be better to even make the polygons larger to keep the pour from creeping between my signals polys? And what do I do with the ground pour creeping between the pads of the 4 0402 resistors in the center, is that good or bad?
-- edit--
Updated the layout have less chance of tombstoning. I guess I could also enable thermals on the polygons in places I need big traces in and small traces, out right?

A: I use Altium for layout and I try to avoid the polygons wherever I can. First, they are cumbersome to create, second you have to take care of the pour order and third, they obscure view of the other layers. I don't know if other layout tools have the same problems though. I use internal planes for boards with 4+ layer count that I want to have GND and/or power planes, which are much easier to create and give you a transparent view. Also as the others pointed out, mismatch of thermal drain between the pads of chip resistors and capacitors can lead to tombstoning in reflow processes.
Also, for routing high speed signals there are many guidelines which you can find on the web. These guidelines depend on the type of the signal and frequency. I would assume satisfying those requirements (minimal crosstalk, impedance and/or length matching, etc) with using polygons all the time would be very difficult if not impossible. My preference is using polygons only when necessary, which as you have pointed out if there is a need for maximizing copper area for an SMPS circuit power line, etc.
Regarding the GND pour creeping between the pads, I would also avoid that. The reason is that those copper areas will probably not be covered with soldermask for 0402 case, so the solder from the pads could creep to the bare copper and create shorts. For bigger components this may not be a problem. However, you should always take clearance and creepage rules into account based on the voltage differential between different nets, in addition to soldermask expansion and manufacturing processes. Solder creeping is also an issue with vias that are placed to close to the pads. If there is no soldermask between a via and a pad that are placed very close, the solder can fill the via during soldering process and then you will have a bad solder connection for that pad.
Also I noticed a couple of acute angles in your design. These also should be avoided for the long term reliability of the design. The reason is that the acute angles can trap the solution used to etch the traces, and that can lead to disconnection in the long term.

A: I would personally only consider them for power rails with high current and low impedance.
For GPIO pull ups, or heck, I guess that is a driver of some sort, I would say that time and extra effort arising from making these elaborate pour can be utilized elsewhere, ignorant to your application, say, return paths or achieving product maintainability.


text:
Q: Помогите достать имя файла без расширения PHP Мой код, здесь копируется название файла полностью
$textname= basename($_SERVER['REQUEST_URI'], '?' . $_SERVER['QUERY_STRING']);
echo $textname;

Помогите сделать копию имени файла без расширения

A: Вы можете использовать стандартную функцию pathinfo() и обратиться к элементу массива filename (doc)
Таким образом ваш код должен выглядеть примерно так:
$textname= basename($_SERVER['REQUEST_URI'], '?' . $_SERVER['QUERY_STRING']);
$pathInfo = pathinfo($textname);
echo $pathInfo["filename"];

A: Можно использовать функцию rtrim():
$filenameonly = rtrim($yourfilename,'.mp4');

Вместо '.mp4' можно поставить любое расширение.
А еще есть функция pathinfo(), которая возвращает массив с информацией о пути. Если путь является файлом, то в массиве с ключом ['filename'] будет имя файла без расширения.
$array = pathinfo($path);


text:
Q: Show Blue scree without Image The following code is not working on my SAP WebIDE. When I run the index.html it shows the blank page.
Code
index.html
<!DOCTYPE html >
  <!--Use the xml view from folder view -->
  <html>
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
        <meta charset="UTF-8">
        <title>OpenSAP - Developing Web Apps with SAPUI5</title>

        <script
            id="sap-ui-bootstrap"
            src="https://sapui5.hana.ondemand.com/resources/sap-ui-core.js"
            data-sap-ui-theme="sap_bluecrystal"
            data-sap-ui-libs="sap.m"
            data-sap-ui-compatVersion="edge"
            data-sap-ui-preload="async"
            data-sap-ui-resourceroots='{
              "opensap.myapp": "./"
            }'>
        </script>

    <script>
        sap.ui.getCore().attachInit(function () {
            sap.ui.xmlview({
                viewName: "opensap.myapp.week1u21.view.App"
            }).placeAt("content");
        });
    </script>
   </head>
   <body class="sapUiBody" id="content"></body>
</html>

App.view.xml
<mvc:View
  displayBlock="true"
  xmlns:mvc="sap.ui.core.mvc"
  xmlns="sap.m">
  <Carousel>
    <Pages>
      <Image src="https://upload.wikimedia.org/wikipedia/commons/0/0e/GEO_Globe_10.jpg"
    height="400px"/>
      <Image src="https://upload.wikimedia.org/wikipedia/commons/b/b1/Globe_Atlantic.svg"
    height="400px"/>
    </Pages>
</Carousel>

My Folder path in SAP WebIDE is as under. Please review below screen link.

Please help me to find out the problem.

A: Hope this will help you, aggregation for the Carousel control is pages
<Carousel class="sapUiContentPadding" loop="true">
    <pages> <!-- this should in small letters -->
        <Image src="https://upload.wikimedia.org/wikipedia/commons/0/0e/GEO_Globe_10.jpg" height="400px"/>
        <Image src="https://upload.wikimedia.org/wikipedia/commons/b/b1/Globe_Atlantic.svg" height="400px"/>
    </pages>
</Carousel>

Note: Kindly see browser console for JavaScript errors.


text:
Q: Can't open and read content of an uploaded zip file with FastAPI I am currently developing a little backend project for myself with the Python Framework FastAPI. I made an endpoint, where the user should be able to upload 2 files, while the first one is a zip-file (which contains X .xmls) and the latter a normal .xml file.
The code is as follows:
@router.post("/sendxmlinzip/")
def create_upload_files_with_zip(files: List[UploadFile] = File(...)):
    if not len(files) == 2:
        raise Httpex.EXPECTEDTWOFILES
    my_file = files[0].file
    zfile = zipfile.ZipFile(my_file, 'r')
    filelist = []
    for finfo in zfile.infolist():
        print(finfo)
        ifile = zfile.open(finfo)
        line_list = ifile.readlines()
        print(line_list)

This should print the content of the files, that are in the .zip file, but it raises the Exception

AttributeError: 'SpooledTemporaryFile' object has no attribute 'seekable'

In the row ifile = zfile.open(finfo)
Upon approximately 3 days research with a lot of trial and error involved, trying to use different functions such as .read() or .extract(), I gave up. Because the python docs literally state, that this should be possible in this way...
For you, who do not know about FastAPI, it's a backend fw for Restful Webservices and is using the starlette datastructure for UploadFile. Please forgive me, if I have overseen something VERY obvious, but I literally tried to check every corner, that may have been the possible cause of the error such as:

*

*Check, whether another implementation is possible

*Check, that the .zip file is correct

*Check, that I attach the correct file (lol)

*Debug to see, whether the actual data, that comes to the backend is indeed the .zip file

A: This is a known Python bug:

SpooledTemporaryFile does not fully satisfy the abstract for IOBase.
Namely, seekable, readable, and writable are missing.
This was discovered when seeking a SpooledTemporaryFile-backed lzma
file.

As @larsks suggested in his comment, I would try writing the contents of the spooled file to a new TemporaryFile, and then operate on that. As long as your files aren't too large, that should work just as well.

A: This is my workaround
with zipfile.ZipFile(io.BytesIO(file.read()), 'r') as zip:


text:
Q: type=meeting for all events I have a requirement where I want to put type=='meeting' for all the events
type has a picklist data type where meeting is a value
Here is the trigger I have written but it is not working.
trigger FieldUpdaterofEvent on Event (before insert,before update) {
    list<event> toUpdate = new list <event>();
    for(Event eve:trigger.new){
        if(eve.type=='--None--'){
            eve.type='Meeting';
            toUpdate.add(eve);
        }
    }
    update toUpdate;
}

A: As per my understanding, you want all event records whose Type is not set, to be created with Type as Meeting.
This can be done by setting the default value to Meeting on the Type picklist field.
If you still want to do it by trigger, then this is how your trigger should be
trigger FieldUpdaterofEvent on Event (before insert,before update) {
    for(Event eve:trigger.new){
        if(string.isBlank(eve.type)){
            eve.type='Meeting';
        }
    }
}

*

*As you are writing the trigger for before insert and before update event, all the records won't be committed to database yet, hence you don't have to write explicit DML statements for it.

*When comparing the picklist value, you will have to check it against '' or null (You can use String.isBlank or String.isEmpty) and not --None--, unless you have --None-- as a picklist value which I doubt.


text:
Q: Possible complications for not closing database cursors? What are the possible complications and repercussions if you do not close cursors for your Oracle database?

A: Since your developers are complaining about the performance hit of repeatedly re-opening cursors, the proper solution in the database would be to close them in your code but set the session_cached_cursors parameter so that the database maintained a cache of the session's recently used cursors.  Having them not close their cursors is going to cause the ORA-01000 error that you're seeing and will waste other server resources.


text:
Q: Vue how to add next html element i would like to create some kind of html template and put data one after another like this:
<template>
  <app-timeline>
    <app-timeline-item
      title="Goal Achieved"
      subtitle="All milestones are completed"
      time="few minutes ago"
      variant="success"
    >

Nick

    </app-timeline-item

    <app-timeline-item
      title="Last milestone remain"
      subtitle="You are just one step away from your goal"
      time="3 minutes ago"
      variant="info"
    >

Mark

    </app-timeline-item>

    <app-timeline-item
      title="Your are running low on time"
      subtitle="Only 30 minutes left to finish milestone"
      time="21 minutes ago"
      variant="warning"
    >

Max

    </app-timeline-item>

    <app-timeline-item
      title="Client Meeting"
      subtitle="New event has been added to your schedule"
      time="36 minutes ago"
    >

Nico

    </app-timeline-item>

    <app-timeline-item
      title="Product Design"
      subtitle="Product design added in workflow"
      time="1 hour ago"
      variant="secondary"
    >

Tom

    </app-timeline-item>
  </app-timeline>
</template>

So as i assume te template should be:
<template>
  <app-timeline>
    <app-timeline-item
      title="{{ title }}"
      subtitle="{{ subtitle }}"
      time="{{ time}}"
      variant="{{ variant}}"
    >

{{ name }}

    </app-timeline-item>
  </app-timeline>
</template>

how should i create method which will create new <app-timeline-item> every time i receive data (some kind of loop)?

A: Based on what you asked you can use v-for in this case:

new Vue({
  data() {
   return {
    array: [
      {title: "Title one", subtitle: "Subtitle one", time: "Time one", variant: "Info", name: "Mark"},
      {title: "Title two", subtitle: "Subtitle two", time: "Time two", variant: "Danger", name: "Tag"},
      {title: "Title three", subtitle: "Subtitle three", time: "Time three", variant: "Success", name: "Robert"},
      {title: "Title four", subtitle: "Subtitle four", time: "Time four", variant: "Primary", name: "Sara"}
    ]
   }
  },
  methods: {
    addSomeItemsToArray() {
      this.array.push({title: "Title five", subtitle: "Subtitle five", time: "Time five", variant: "secoundary"})
    }
  }
})
<template>
  <app-timeline>
    <app-timeline-item
      v-for="item in array"
      :key="item.title"
      :title="item.title"
      :subtitle="item.subtitle"
      :time="item.time"
      :variant="item.variant"
    >

{{item.name}}

    </app-timeline-item>
</app-timeline>
</template>

If you want to add any item to the array you can do it with Array.push().
This will help you even when you want to add any item in an ajax request.


text:
Q: Single setup step in Locust 1.6.0? I have been trying out how to setup a resource only once and share with user that gets created with locust
This is what I have been trying:
from locust import HttpUser
from locust.user.task import task

class WebsiteUser(HttpUser):
    def setup(self):
        client = clients.HttpSession(base_url=self.host)
        token = client.post("get-token/", {'email': 'someemail', 'password': 'somepassword'})
        client.headers.update(
            {
                'Authorization': 'Bearer ' + token
            }
        )
    tasks = UserBehavior
    min_wait = 500
    max_wait = 900

As you see I wanted to fetch the token for once and share this with all other user instances that are created while load testing.
I can't figure out a way to achieve this.
Any sort of help would be really appreciated :)

A: You'll want to save the token in a variable accessible outside of the User to make it accessible by all users, otherwise each user would create its own.
from locust import HttpUser
from locust.user.task import task

token = ''

class WebsiteUser(HttpUser):
    def setup(self):
        global token
        client = clients.HttpSession(base_url=self.host)
        token = client.post("get-token/", {'email': 'someemail', 'password': 'somepassword'})
        client.headers.update(
            {
                'Authorization': 'Bearer ' + token
            }
        )
    tasks = UserBehavior
    min_wait = 500
    max_wait = 900

I'm not positive but you might also need to set the headers before each request instead of setting them once.


text:
Q: How to get top output in Solaris machine Looking for a very simple thing to do in Solaris.
I have a solaris box which has lot of zones ( so not only the host box, also the total available including zones ), i would want to see

*

*What is the total memory available, used and free.

*What is the total swap available, used, and free.

Am a linux guy, top gives me everything in Linux. What is the command to do it in Solaris.
Note: I cannot install any commands, so please tell me with the basic available commands that ship with OS installation.

A: One of them is prtdiag. Others like vmstat, iostat also worth taking a look

A: You really want prstat - it does what top does, but it can take setting some switches to get what you want.  For example prstat -L for lwp's.
The display is very much like top.  And if you require to look like top exactly then you will have to script things together.  Linux is BSD, Solaris is system V.  A different world.
In general, the the unix rosetta stone helps finding 'commands like xxx from zzz on yyy unix':
http://bhami.com/rosetta.html

A: hit
prstat -Z

to see all information about each zone consumption

A: prstat -aZ
Review prstat

Name prstat– report active process statistics Synopsis prstat
  [-acHJLmRrtTv] [-d u | d] [-C psrsetlist] [-h lgrplist]
       [-j projlist] [-k tasklist] [-n ntop[,nbottom]]
       [-p pidlist] [-P cpulist] [-s key | -S key ]
       [-u euidlist] [-U uidlist] [-z zoneidlist] [-Z]
       [interval [count]] Description The prstat utility iteratively examines all active processes on the system and reports statistics
  based on the selected output mode and sort order. prstat provides
  options to examine only processes matching specified PIDs, UIDs, zone
  IDs, CPU IDs, and processor set IDs.
The -j, -k, -C, -p, -P, -u, -U, and -z options accept lists as
  arguments. Items in a list can be either separated by commas or
  enclosed in quotes and separated by commas or spaces.
If you do not specify an option, prstat examines all processes and
  reports statistics sorted by CPU usage.
Options The following options are supported:
-a Report information about processes and users. In this mode prstat displays separate reports about processes and users at the same time.


text:
Q: nodejs multer diskstorage to delete file after saving to disk I am using multer diskstorage to save a file to disk.
I first save it to the disk and do some operations with the file and then i upload it to remote bucket using another function and lib.
Once the upload is finished, i would like to delete it from the disk.
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, '/tmp/my-uploads')
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now())
  }
})

var upload = multer({ storage: storage }).single('file')

and here is how i use it:
app.post('/api/photo', function (req, res) {
    upload(req, res, function (err) {
        uploadToRemoteBucket(req.file.path)
        .then(data => {
            // delete from disk first

            res.end("UPLOAD COMPLETED!");
        })
    })
});

how can i use the diskStorage remove function to remove the files in the temp folder?
https://github.com/expressjs/multer/blob/master/storage/disk.js#L54
update:
I have decided to make it modular and put it in another file:
const fileUpload = function(req, res, cb) {
    upload(req, res, function (err) {
        uploadToRemoteBucket(req.file.path)
        .then(data => {
            // delete from disk first

            res.end("UPLOAD COMPLETED!");
        })
    })
}

module.exports = { fileUpload };

A: You don't need to use multer to delete the file and besides _removeFile is a private function that you should not use.
You'd delete the file as you normally would via fs.unlink. So wherever you have access to req.file, you can do the following:
const fs = require('fs')
const { promisify } = require('util')

const unlinkAsync = promisify(fs.unlink)

// ...

const storage = multer.diskStorage({
    destination(req, file, cb) {
      cb(null, '/tmp/my-uploads')
    },
    filename(req, file, cb) {
      cb(null, `${file.fieldname}-${Date.now()}`)
    }
  })

const upload = multer({ storage: storage }).single('file')

app.post('/api/photo', upload, async (req, res) =>{
    // You aren't doing anything with data so no need for the return value
    await uploadToRemoteBucket(req.file.path)

    // Delete the file like normal
    await unlinkAsync(req.file.path)

    res.end("UPLOAD COMPLETED!")
})

A: Multer isn't needed. Just use this code.
const fs = require('fs')

const path = './file.txt'

fs.unlink(path, (err) => {
  if (err) {
    console.error(err)
    return
  }

  //file removed
})

A: You may also consider using MemoryStorage for this purpose, with this storage the file is never stored in the disk but in memory and is deleted from the memory automatically after execution comes out of controller block, i.e., after you serve the response in most of the cases.
When you will use this storage option, you won't get the fields file.destination, file.path and file.filename, instead you will get a field file.buffer which as name suggests is a buffer, you can convert this buffer to desired format to do operations on and then upload using a stream object.
Most of the popular libraries support streams so you should be able to use stream to upload your file directly, code for converting buffer to stream:
const Readable = require('stream').Readable;

var stream = new Readable();
stream._read = () => { }
stream.push(file.buffer);
stream.push(null);

// now you can pass this stream object to your upload function

This approach would be more efficient as files will be stored in memory which will result in faster access, but it does have a con as mentioned in multer documentation:

WARNING: Uploading very large files, or relatively small files in
large numbers very quickly, can cause your application to run out of
memory when memory storage is used.

A: To do it truly automatically across all routes I used this strategy :
when the request ends, we delete all the uploaded files (req.files). Before that, if you want to keep the files on the server, you need to save them in another path.
var express = require('express');
var app = express();
var http = require('http');
var server = http.Server(app);

// classic multer instantiation
var multer = require('multer');
var upload = multer({
    storage: multer.diskStorage({
        destination: function (req, file, cb) {
            cb(null, `${__dirname}/web/uploads/tmp/`);
        },
        filename: function (req, file, cb) {
            cb(null, uniqid() + path.extname(file.originalname));
        },
    }),
});
app.use(upload.any());

// automatically deletes uploaded files when express finishes the request
app.use(function(req, res, next) {
    var writeHead = res.writeHead;
    var writeHeadbound = writeHead.bind(res);
    res.writeHead = function (statusCode, statusMessage, headers) {
        if (req.files) {
            for (var file of req.files) {
                fs.unlink(file.path, function (err) {
                    if (err) console.error(err);
                });
            }
        }

        writeHeadbound(statusCode, statusMessage, headers);
    };

    next();
});

// route to upload a file
    router.post('/profile/edit', access.isLogged(), async function (req, res, next) {
        try {

// we copy uploaded files to a custom folder or the middleware will delete them
            for (let file of req.files)
                if (file.fieldname == 'picture')
                    await fs.promises.copy(file.path, `${__dirname}/../uploads/user/photo.jpg`);

        } catch (err) {
            next(err);
        }
    });

A: I have removed directory after file uploaded using fs-extra
const fs = require('fs-extra');

// after you uploaded to bucket

await fs.remove('uploads/abc.png'); // remove upload dir when uploaded bucket


text:
Q: Expire cached css on Tomcat 7 or Apache My employer's web app periodically makes small changes to the global styling sheet, maybe once or twice a month. We're using Tomcat 7.0.25 and Apache, each for different parts of the app.
Is there a way to configure Tomcat or Apache to tell visitors' browsers in the HTTP header to refresh the css file when it gets changed? Ideally, we'd like it to refresh only when the file changes, but it could also be fine to refresh it every time the server restarts, since most restarts coincide with an update to the app.


text:
Q: In angular directives, is it preferable to use restrict A or E over C? I'm doing a web site for a client that want the site itself to work as a template for other projects. I'm using directives like this one:
webApp.directive('layoutSection', function() {
    return  {
        restrict: 'C',
        templateUrl: 'templates/layout__section.template.html'
    }
})

The idea is to just put the class inside the element and the directives does the rest. Anyway this method does not seem to be popular. I see that most people prefer to do a custom data attributes like data-layout-section.
There is a reason for this? Is a bad idea to use the C over the other methods?

A: One could assume it's a best practice about Separation of concerns: use classes for CSS, data- attributes for javascript.
The angular documentation offers more insight about when to use either case: https://docs.angularjs.org/guide/directive

Best Practice: Prefer using directives via tag name and attributes over comment and class names. Doing so generally makes it easier to determine what directives a given element matches.


text:
Q: Copying sql files from JdbcTemplate wih Spring I try to write some datas in a sqlite3 database.
To do so, I execute :
jdbcTemplate.execute(".read java/tmp.sql");
Here, tmp.sql contains :
BEGIN TRANSACTION;

... somes inserts

COMMIT;

Doing so gives me this error message :
java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database (near ".": syntax error)
As a consequence, would you know a way to copy a sql file using sqlite3 and Spring's jdbctemplate ?

A: JdbcTemplate execute method with one string argument needs a sql query here.
If you need execute all file it will be better to use ResourceDatabasePopulator
http://docs.spring.io/spring/docs/3.0.x/api/org/springframework/jdbc/datasource/init/ResourceDatabasePopulator.html


text:
Q: How to use observable object in wrapped textfield class So I have 4 textfields with lines underneath them all. When the user enters a number into the first textfield it jumps to the next and so on until a number it entered into the last field at that point the keyboard will just resign and the pin will be evaluated. I want to be able to change the color of the lines depending on which textfield is focused the time.
What I have tried
So far I've tried making an instance of an observable object in a representable swift file that makes up my textfield. So I'll change the Observable Object when nextField becomes first responder and I'll change a state variable in my SwiftUI file. When I try to make an instance of my Observable Object in my representable file I get an error that states "Class 'SchoolCode_WrappableTextField' has no initializers". Overall I'm essentially just trying to change the color of the underline depending on which textfield is focused at the time. Any help is appreciated, thanks.
@objc func textChanged(sender: UITextField) {
    if (sender.text?.count)! > 0 {
        if let nextField = sender.superview?.superview?.viewWithTag(sender.tag + 1) as? UITextField{

            nextField.becomeFirstResponder()
        }else{
            sender.resignFirstResponder()
        }
    }
}`

UI


text:
Q: Git: copy local branch into another local directory Sorry for asking this dumb question.
I am trying to copy my repo (local) into another local directory. If I simply do CMD + c and CMD + v of my repo, I actually copy all the branches of my local repo. How do I only copy one branch?
Thanks

A: Every git repository contains the whole git commit tree, so you cannot get a git repository only with a single branch by copy and paste git folder.
Butgit worktree is designed for this situation.

Just type this command in your original git repository.
git worktree add -b <your-new-branch-name> <your-new-directory> <your-base-branch>

This command means that you'll create a new folder in the path your-new-directory, and then create a new branch named your-new-branch-name based on the your-base-branch branch.
For example, you can type this below to create a folder named MyAnotherFolder beside your original one, and create a new branch temp/my-copy based on master.
git worktree add -b temp/my-copy ../MyAnotherFolder master

If you delete the folder in the future, type this command to remove the worktree reference.
git worktree prune

A: I had the same problem when we were moving our repo to a new server.
I just did from my old repo:
git push <path_to_new_local_repo> <branch_name>
and it worked perfect.

A: It seems like what you're saying you want is a new repo in the second directory, that contains only a single branch.  It can be done, though it's a bit unusual and I wonder if it's really the best way to do whatever you're trying to do...
Well, anyway, in most cases if you want to copy a repo it's better to use git clone than to use external tools to copy the files.  In this case, you could say
git clone --single-branch --branch <branch_name> file://localhost/path/to/existing/repo

This initializes a new repo and fetches just the history and objects required for the branch named <branch_name>.  The new repo will refer to the existing local repo as a remote named origin.  You can undo this if you want by cding into the new repo and saying
git remote remove origin

If your local repo has a remote, and you want the new repo to also use that remote as its origin, then it's probably easier to clone from the remote instead of from the local copy.


text:
Q: JScrollPane muito curto no JTextArea Estou com um problema relacionado ao scroll da area de texto do java swing, ele não mostra os items que estão fora da area de visão do JTextArea, independente de quantas linhas o texto possui.
vídeo do problema >>> https://youtu.be/o-Rf2QkyK8o
Esse código é para o trabalho da faculdade.
Arquivo 01:
package View.Fields;
import java.awt.Dimension;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import View.Elements.Terminal;
public class TerminalField extends JPanel{
    Terminal shell = new Terminal();
    JScrollPane scroll = new JScrollPane(shell, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    public TerminalField(){
         super();
         scroll.setPreferredSize(new Dimension(200, 150));
         super.add(scroll);

         /* Gen txt for test */
         for( int i = 0; i <= 1000; i++){
              shell.append(i + " a\n");
         }
         shell.setEditable(true);
      }
}

Arquivo 02:
    package View.Elements;
    import java.awt.Dimension;
    import javax.swing.JTextArea;
    public class Terminal extends JTextArea{
        public Terminal(){
            super();
            super.setMaximumSize(new Dimension(200,150));
            super.setMinimumSize(new Dimension(200,150));
            super.setPreferredSize(new Dimension(200,150));
            super.setEditable(false);
            super.setWrapStyleWord(true);
            super.setLineWrap(true);
        }
 }

A: Ao que me parece, o problema do scroll que tu estás tendo é porque o JScrollPane tem exatamente o mesmo tamanho do JTextArea. Quando tu defines o tamanho to JTextArea, ele fica com o tamanho fixo e corta o texto excedente.
No teu caso, tu não deverias ter definido os tamanhos máximo e preferidos para o campo de texto. Assim, o campo iria se expandir dentro do JScrollPane conforme o número de linhas da tua String e, como o JScrollPane tem o tamanho definido, a barra de rolagem ficaria "melhor" e o tamanho do container ficaria igual.
Tenta isso... Espero que ajude.
Tu também podes encontrar mais informações nesse tutorial da Oracle
Esse é um exemplo de código que tu podes usar (extraído do link acima de forma resumida):
JScrollPane jScrollPane1;
JTextArea textArea;

textArea = new JTextArea();
textArea.setColumns(20); //define a largura
textArea.setRows(5);     //define a altura (em linhas de texto)

jScrollPane1 = new JScrollPane(textArea); //adiciona à um scrollPane

A: Além de definir os tamanhos para o componente, como mencionado na resposta do Leonardo, você também não inicializou o componente informando quantas linhas e colunas ele vai possuir. Por isso o comportamento esperado não ocorreu.
É com base no número de linhas e colunas que o java vai dimensionar este componente e vai definir internamente um tamanho preferido através do gerenciador de layout, e assim fazer com que o componente de scroll se ajuste ao tamanho e ao texto excedente.
Para limitar o tamanho de uma caixa de texto, você pode utilizar um container a parte, como um JPanel, e este sim possua o tamanho fixo que você necessita. No código em questão, é possível resolver o problema modificando apenas 2 coisas:

*

*iniciando o JTexArea corretamente, informando linhas e colunas;

*ajustando o tamanho preferido para a classe TerminalField.

Caso essa ultima classe não seja exclusiva para acomodar a caixa de texto, você pode criar um JPanel inline e jogar o scroll dentro dele.
Veja o código abaixo:
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

public class TextAreaTeste {

    public TextAreaTeste() {

        JFrame f = new JFrame();
        f.setPreferredSize(new Dimension(400, 300));
        f.getContentPane().add(new TerminalField());
        f.pack();
        f.setVisible(true);

        f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(TextAreaTeste::new);
    }

}

class Terminal extends JTextArea {

    public Terminal() {
        // aqui deve ser iniciado dessa forma
        // primeiro paramentro é numero de linhas
        // segundo parametro é numero de colunas
        super(9, 15);

        /* nao mais necessário */
//        super.setMaximumSize(new Dimension(200,150));
//        super.setMinimumSize(new Dimension(200,150));
//        super.setPreferredSize(new Dimension(200,150));

        super.setEditable(false);
        super.setWrapStyleWord(true);
        super.setLineWrap(true);
    }
}

class TerminalField extends JPanel {

    Terminal shell = new Terminal();
    JScrollPane scroll = new JScrollPane(shell, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

    public TerminalField() {
        // aqui criei um painel pra acomodar apenas a caixa de texto
        JPanel painelTexto = new JPanel();
        // aqui eu defini o tamanho que eu quero para o componente
        painelTexto.setPreferredSize(new Dimension(200, 150));
        painelTexto.add(scroll);

        super.add(painelTexto);

        /* Gen txt for test */
        for (int i = 0; i <= 1000; i++) {
            shell.append(i + " a\n");
        }
    }
}

Também é importante comentar que você está herdando duas classes de componentes para não fazer praticamente nada do que elas já não fariam, ou que você poderia fazer sem gastar a herança. Lembre-se que em java você só consegue herdar uma classe por vez e deve-se sempre analisar com calma a necessidade de usar o recurso.
Caso as alterações que você faça nos dois componentes herdados sejam apenas as do código da pergunta, poderia fazer um método q retornasse o componente modificado.

Recomendado:
O que são os conceitos de coesão e acoplamento?


text:
Q: Faster multiplication of two polynomials over a field Let $f(x),g(x)\in \mathbb{F}[x]$ are given two monic polynomials each of degree $i$.  I want to compute the product of these two polynomials (i.e.) the coefficients of resulting polynomials. Here  operations will field operations like addition and multiplication etc.
Brute force Algorithm : Just as usual multiply the coefficients, computing the one coefficient of resulting polynomial will take $i+1$ many multiplications and addition of two degree $i$ polynomials takes $i+1$ operations. I will adding $i$ times, so overall operations are $i \times (i+1)$ +$(i+1)\times i$.

Questions : Is it possible to in $i^2 -2i +1$ many operations? please explain

A: Methods like Karatsuba can compute products using a smaller operation count. As the degree gets large, methods based on Fourier transforms can achieve rather small operation counts, almost linear in $i$.
Operation counts for polynomial multiplication algorithms usually only count how many multiply operations you do, for two reasons:

*

*Multiplying scalars is often slower than adding them

*Usually the number of additions is proportional to the number of multiplications, so you can infer the total operation count just from the multiplies.

A: Let $f$ be a polynomial of degree $I$ and let $g$ be a polynomial of degree . So product $fg$ needs $i-1$ multiplications and $i-1$ many additions, so to $i^2 - 2i +1$ many operations required.


text:
Q: 64k AU size - master, model, msdb Should master, model and msdb reside on drives with 64k AU size? Is it necessary? Recommended?
All of our SQL servers are on VMware. If necessary, I would like to be able to recover a VM from a snapshot that restores OS, SQL executables and system databases. Then restore application databases from SQL backups.
I'm trying to determine if I should install SQL server to C: (4k AU) and place the system databases on D: (64k AU). And application databases on E:, F:, etc. (64k AU). Log files on G: (64k AU).  TempDB on T: (64k AU).  Would snap C and D.

A:
Should master, model and msdb reside on drives with 64k AU size? Is it necessary? Recommended?

In general, make a standard and use it. To directly answer your question, if all other filesystems are going to be formatted for 64KB, then why not stick to it - though, regardless, I'd go with the storage vendor's recommendation. Let's look per DB:

*

*Master: In general it doesn't have much "extra" data put in it and shouldn't really be growing or heavily transactional. Allocating 64k or 4k isn't going to make much of a difference.

*Model: There should be no transactional activity happening in this database, in general, by default. There might be some additional objects added but this should be similar to master where it's largely static.

*MSDB: This database is actually used more than both of the previous database. It holds things such as Jobs, Mail, Backup Information, etc. This database could grow to be very large when not properly looked after.

Without going into a large amount of technical detail, you should choose whatever the storage behind the virtualization layer likes as it's preferred or most optimized transfer size, that's what I'd use for my allocation unit size. This is because it matches what the storage layer likes the most and will be the most optimized.
If you want to get a little more technical, uniform extents are 8 contiguous pages which just happens to be 64k. This happens to nicely line up with a 64k allocation unit size. The largest possible log block can be 60k, which again fits nicely... but generally is much less, which results in space waste, and could not be the optimized size that the storage layer likes.
The allocation unit size is just the smallest possible fragment given to a file. Thus an AU of 64k means a file, holding just a single bit would still have an on disk size of 64k. Normally, larger AU sizes result in lower on disk fragmentation which may or may not matter, depending on the storage array's physical storage medium. In an example of this, SSDs and NVME hold internal translation tables for pages (not the same as DB pages) for wear leveling and write amplification. In this case, there is no idea of where the physical data will be saved, and thus may or may not be physically sequential.
Thus, again, I'd go with the value specified by the storage layer vendor. If you don't happen to know what that is, 4k and 64k are both well supported (though larger AU sizes may not support certain NTFS technologies, which shouldn't be used with SQL Server anyway - but for completeness I added it).
Really, what will make the largest difference is whether the storage layer has mixed 512 and 512e/h storage representations (which is the physical block size). This will cause more issues that allocation unit size of the filesystem.

If necessary, I would like to be able to recover a VM from a snapshot that restores OS, SQL executables and system databases. Then restore application databases from SQL backups.

In a highly unrelated note, I'd double and triple check that this meets your disaster recovery or business continuity requirements/SLAs. Allocation Unit sizes should not impact this.


text:
Q: Where can I download Sharepoint DLLs I need to get hold of the Sharepoint DLL's.  I understand that these are available from the Sharepoint server however the company I work for is quite large and the server is not anywhere I can get close to to copy the DLL's.  Is there somewhere I can download these so I can start to develop my VB.NET application locally!

A: You need to be developing on a Virtual Machine with SharePoint installed on that machine. If your company has an MSDN subscription you should have the ability to download installation media, if it is not already available.
However Microsoft has guidance on doing this on your physical machine here.

A: You can download the Sharepoint Foundation installer from here:  http://www.microsoft.com/downloads/en/details.aspx?FamilyID=49c79a8a-4612-4e7d-a0b4-3bb429b46595&displaylang=en
No MSDN is required - this is a free download, and Sharepoint Foundation is completely free, as long as you already have SQL Server and Windows Server already licensed.
As Nat has mentioned, it is highly recommended to do development on a virtual machine, and to have the full Sharepoint setup installed there.
Here is a setup guide, but there are many others out there:
http://www.drowningintechnicaldebt.com/DennisBottjer/archive/2009/11/30/sharepoint-2010-foundation-development-demonstration-installation-guide.aspx
After you have Sharepoint installed on your VM, you can find the DLLs under c:\program files\common files\microsoft shared\web server extensions\14\ISAPI

A: Install Windows SharePoint Services to get it.
You can download it from below URL
http://www.microsoft.com/en-us/download/details.aspx?id=14117
is located in Local_Drive:\Program Files\Common Files\Microsoft Shared\web server extensions\14\TEMPLATE\SiteTemplates\sts


text:
Q: Extracting sub-data from a SAS dataset & applying to a different dataset I have written a macro to use proc univariate to calculate custom quantiles for variables in a dataset (say dsn1) %cust_quants(dsn= , varlist= , quant_list= ). The output is a summary dataset (say dsn2)that looks something like the following:
q_1      q_2.5      q_50      q_80      q_97.5      q_99      var_name
1        2.5        50        80        97.5        99        ex_var_1_100
-2       10         25        150       500         20000     ex_var_pos_skew
-20000   -500       -150      0         10          50        ex_var_neg_skew

What I would like to do is to use the summary dataset to cap/floor extreme values in the original dataset. My idea is to extract the column of interest (say q_99) and put it into a vector of macro-variables (say q_99_1, q_99_2, ..., q_99_n). I can then do something like the following:
/* create summary of dsn1 as above example */
%cust_quants(dsn= dsn1, varlist= ex_var_1_100 ex_var_pos_skew ex_var_neg_skew,
             quant_list= 1 2.5 50 80 97.5 99);

/* cap dsn1 var's at 99th percentile */
data dsn1_cap;
  set dsn1;

  if ex_var_1_100 > &q_99_1 then ex_var_1_100 = &q_99_1;
  if ex_var_pos_skew > &q_99_2 then ex_var_pos_skew = &q_99_2;
  /* don't cap neg skew */
run;

In R, it is very easy to do this. One can extract sub-data from a data-frame using matrix like indexing and assign this sub-data to an object. This second object can then be referenced later. R example--extracting b from data-frame a:
> a <- as.data.frame(cbind(c(1,2,3), c(4,5,6)))
> print(a)
  V1 V2
1  1  4
2  2  5
3  3  6
> a[, 2]
[1] 4 5 6
> b <- a[, 2]
> b[1]
[1] 4

Is it possible to do the same thing in SAS? I want to be able to assign a column(s) of sub-data to a macro variable / array, such that I can then use the macro / array within a 2nd data step. One thought is proc sql into::
proc sql noprint;
  select v2 into :v2_macro separated by " "
  from a;
run;

However, this creates a single string variable when what I really want is a vector of variables (or array--no vectors in SAS). Another thought is to add %scan (assuming this is inside a macro):
proc sql noprint;
  select v2 into :v2_macro separated by " "
  from a;
run;

%let i = 1;
%do %until(%scan(&v2_macro, &i) = "");
  %let var_&i = %scan(&v2_macro, &i);
  %let &i = %eval(&i + 1);
%end;

This seems inefficient and takes a lot of code. It also requires the programmer to remember which var_&i corresponds to each future purpose. Is there a simpler / cleaner way to do this?
**Please let me know in the comments if this is enough background / example. I'm happy to give a more complete description of why I'm doing what I'm attempting if needed.

A: First off, I assume you are talking about SAS/Base not SAS/IML; SAS/IML is essentially similar to R and has the same kind of operations available in the same manner.
SAS/Base is more similar to a database language than a matrix language (though has some elements of both, and some elements of an OOP language, as well as being a full-featured functional programming language).
As a result, you do things somewhat differently in order to achieve the same goal.  Additionally, because of the cost of moving data in a large data table, you are given multiple methods to achieve the same result; you can choose the appropriate method for the required situation.
To begin with, you generally should not store data in a macro variable in the manner you suggest. It is bad programming practice, and it is inefficient (as you have already noticed).  SAS Datasets exist to store data; SAS macro variables exist to help simplify your programming tasks and drive the code.
Creating the dataset "b" as above is trivial in Base SAS:
data b;
set a;
keep v2;
run;

That creates a new dataset with the same rows as A, but only the second column.  KEEP and DROP allow you to control which columns are in the dataset.
However, there would be very little point in this dataset, unless you were planning on modifying the data; after all, it contains the same information as A, just less.  So for example, if you wanted to merge V2 into another dataset, rather than creating b, you could simply use a dataset option with A:
data c;
merge z a(keep=v2);
by id;
run;

(Note: I presuppose an ID variable of some form to combine A and Z.)
This merge combines the v2 column onto z, in a new dataset, c.  This is equivalent to vertically concatenating two matrices (although a straight-up concatenation would remove the 'by id;' requirement, in databases you do not typically do that, as order is not guaranteed to be what you expect).
If you plan on using b to do something else, how you create and/or use it depends on that usage.  You can create a format, which is a mapping of values [ie, 1='Hello' 2='Goodbye'] and thus allows you to convert one value to another with a single programming statement.  You can load it into a hash table.  You can transpose it into a row (proc transpose).  Supply more detail and a more specific answer can be provided.


text:
Q: $\lim_{x \to 0} (e^x - 1)/x^8$ . I want to know how to solve this limit problem with Maclaurin's series expansion of only $e^x$ in the neighborhood of $x=0$.

A: You can certainly apply l'Hôpital here, provided you distinguish between the limits from the right and from the left. Since
$$
\lim_{x\to0^+}\frac{e^x}{8x^7}=\infty
$$
you can certainly conclude that
$$
\lim_{x\to0^+}\frac{e^x-1}{x^8}=\infty
$$
Similarly
$$
\lim_{x\to0^-}\frac{e^x}{8x^7}=-\infty
$$
and therefore
$$
\lim_{x\to0^-}\frac{e^x-1}{x^8}=-\infty
$$
Hence the two-sided limit doesn't exist.
What about Taylor (or Maclaurin, if you prefer to call it this way)? The Taylor expansion is $e^x-1=x+o(x)$ so you have, from the right,
$$
\lim_{x\to0^+}\frac{e^x-1}{x^8}=\lim_{x\to0}\frac{x+o(x)}{x^8}=\infty
$$
(you get $\infty$ because you know that the function is positive in a right punctured neighborhood of $0$). Similarly for the limit from the left and you get the same result as before.

A: The limit does not exist. $(e^x-1)/x^8$ approaches infinity as $x$ approaches $0$ from the positive end, but $(e^x-1)/x^8$ approaches negative infinity as $x$ approaches $0$ from the negative end. L'Hôpital's rule states that if $f(x) \to 0$ and $g(x) \to 0$ as $x$ approaches $a$, then
$$
\lim_{x \to a}\frac{f(x)}{g(x)}=\lim_{x \to a}\frac{f'(x)}{g'(x)}
$$
provided that
$$
\lim_{x \to a}\frac{f'(x)}{g'(x)}
$$
exists. In this case, that limit does not exist, and so L'Hôpital is not applicable.

A: $$\frac{e^x-1}{x^8}=\frac{1+x+o(x^2)-1}{x^8}.$$
You can conclude.