text:
Q: React-admin: useQuery not fetching data on Dashboard after logging in I have react-admin set up with GraphQL and works fine for the most part... however there seems to be an issue with logging in initially and having the Dashboard make a query; the issue being that it will not resolve upon initial loading. It goes from logging in -> Dashboard and I'm met with a component that loads forever with no data or errors.
My Admin is set up like this:
const routes = [
    <Route exact path="/support-chat-list" component={SupportChatPage} noLayout />,
    <Route exact path="/group-chat" component={GroupChatPage} noLayout />,
    <Route exact path="/" component={Dashboard} />,
];

const App = () => (
    <Admin dashboard={Dashboard} layout={MyLayout} customRoutes={routes} dataProvider={dataProvider} authProvider={authProvider} i18nProvider={i18nProvider}>
        {/* my resources... */}
    </Admin>
);

and my Dashboard looks like this:
const requestOptions = (startingAfter, startingBefore) => {
    return {
        type    : 'getList',
        resource: 'appointments',
        payload : {
            pagination: {
                perPage: 100,
                page   : 0,
            },
            sort      : {
                field: 'start_at',
                order: 'asc'
            },
            filter    : {
                startingAfter: startingAfter.toString(),
                startingBefore: startingBefore.toString(),
            }
        }
    };
};

const handleSelectEvent = (event, e, redirectTo) => {
    redirectTo('show', ROUTES.APPOINTMENTS, event.resource.id);
};

const initialState = {
    middleDate: DateTime.local().startOf('day'),
    startDate: DateTime.local().minus({days: 3}).startOf('day'),
    endDate: DateTime.local().plus({days: 3}).endOf('day'),
};

export function Dashboard() {
    useAuthenticated();
    const redirectTo = useRedirect();
    const [dateRanges, setDateRanges] = useState(initialState);
    const {data, loading, error} = useQueryWithStore(requestOptions(dateRanges.startDate, dateRanges.endDate));

    if (error) return <Error />;

    return (
        <Card>
            <Title title="Admin" />
            <CardContent>
                {loading && <Loading/>}
                {!loading &&
                    <Calendar
                        events={translateAppointmentData(data)}
                        //.......

I've tried playing around with useQuery and useQueryWithStore but nothing seems to work. It will only resolve when I refresh the page, and only then it will load everything.
I have a suspicion that it has to do with my authProvider, which is a class that handles authentication. It's a bit bloated so I'll try my best to show the things related to login:
async login({username, password}) {
        const response = await authClient.passwordGrant(username, password, ACCESS_TOKEN_SCOPES);
        await this.processTokenResponse(response);

        return Promise.resolve();
    }

authClient.passwordGrant looks like this:
passwordGrant(username, password, scopes) {
        const request = new Request(`${this.url}/oauth/access_token`, {
            method: 'POST',
            body: JSON.stringify({
                username: username,
                password: password,
                client_id: this.clientId,
                client_secret: this.clientSecret,
                grant_type: 'password',
                scope: scopes.join(' '),
            }),
            headers: new Headers({ 'Content-Type': 'application/json' }),
        });

        return fetch(request)
            .then(response => {
                if (response.status < 200 || response.status >= 300) {
                    throw new Error(response.statusText);
                }

                return response.json();
            });
    }

while processTokenResponse looks like this:
processTokenResponse(response) {
        const now = DateTime.local();
        localStorage.setItem(TOKEN_STORAGE_KEY, response.access_token);
        localStorage.setItem(TOKEN_EXPIRY_STORAGE_KEY, now.plus({seconds: response.expires_in - EXPIRY_BUFFER}).toString());

        localStorage.setItem(SCOPES_STORAGE_KEY, JSON.stringify({scopes: response.scopes}));

        localStorage.setItem(REFRESH_TOKEN_STORAGE_KEY, response.refresh_token);
        localStorage.setItem(REFRESH_TOKEN_EXPIRY_STORAGE_KEY, now.plus({seconds: response.refresh_token_expires_in - EXPIRY_BUFFER}).toString());

        return this.fetchActiveUserData();
    }

and fetchActiveUserData looks like this:
async fetchActiveUserData() {
        let dataProvider = new ActiveUserDataProvider();

        return await dataProvider.getOne({}).then((response) => {
            return this.processLoadUserResponse(response.data);
        })
    }

in which my dataProvider looks like this:
import apolloClient from '../apolloClient';
import { BaseResourceDataProvider } from './baseResourceDataProvider';
import {FetchMeQuery} from "../graphql/users";

const FetchMeQuery = gql`
    query FetchMe {
        me {
            id
            firstName
            lastName
            name
            username
            timezone
        }
    }
`;

class ActiveUserDataProvider extends BaseResourceDataProvider {
    getOne({ id }: { id?: string }) { // maybe something wrong here?
        return apolloClient.query({
            query: FetchMeQuery,
            fetchPolicy: 'cache-first'
        }).then((result) => {
            return {
                data: result.data.me,
            };
        });
    }
}

I apologize for the long post but I'm completely lost on why my Dashboard isn't querying data once initially logged in, and needing a refresh for it to work. I'm hoping someone can point where something's wrong. Thank you.

A: After much digging, it turned out to be how I set up my ApolloClient. Previously I was using Apollo Link to set up my auth middleware, and discovered that it wasn't calling the middleware at all.
I discovered this question and replaced ApolloLink with setContext and it worked perfectly. This is the code now:
const authMiddleware = setContext(async (_, { headers }) => {
    const token = await authProvider.checkAuth();

    return {
        headers: {
            ...headers,
            authorization: token ? `Bearer ${token}` : '',
        }
    }
});

const apolloClient = new ApolloClient({
    cache: new InMemoryCache(),
    link: from([
        authMiddleware,
        httpLink
    ]),
});


text:
Q: Convert String To Json with nested array list I want to convert a string into class object. The example string is Like this :
[{
    "MESSAGE": "Successfully!",
    "ORIGINAL_ERROR": "",
    "ERROR_STATUS": false,
    "RECORDS": true,
    "Data": [{
        "Id": "1",
        "Name": "Third AC"
    }, {
        "Id": "2",
        "Name": "Second AC"
    }, {
        "Id": "3",
        "Name": "First AC"
    }, {
        "Id": "4",
        "Name": "AC Chair Car"
    }, {
        "Id": "5",
        "Name": "First Class"
    }, {
        "Id": "6",
        "Name": "Sleeper Class"
    }, {
        "Id": "7",
        "Name": "Second Class Unreserved"
    }, {
        "Id": "8",
        "Name": "3AC Economy "
    }, {
        "Id": "9",
        "Name": "Second Seating"
    }, {
        "Id": "10",
        "Name": "Executive Class"
    }]
}]

And I Want to convert the string to the class object. the Class Is
class TrainClassData {
  String MESSAGE;
  String ORIGINAL_ERROR;
  String ERROR_STATUS;
  String RECORDS;
  List<TrainClass> Data;

  TrainClassData({
    this.MESSAGE,
    this.ORIGINAL_ERROR,
    this.ERROR_STATUS,
    this.RECORDS,
    this.Data,
  });

  factory TrainClassData.fromJson(Map<String, dynamic> json) {
    return TrainClassData(
      MESSAGE: json['Id'] as String,
      ORIGINAL_ERROR: json['Name'] as String,
      ERROR_STATUS: json['Name'] as String,
      RECORDS: json['Name'] as String,
      Data: json['Data'].map<TrainClass>((json) => TrainClass.fromJson(json)).toList()
    );
  }
}

class TrainClass {
  String Id;
  String Name;

  TrainClass({
    this.Id,
    this.Name,
  });

  factory TrainClass.fromJson(Map<String, dynamic> json) {
    return TrainClass(
        Id: json['Id'] as String, Name: json['Name'] as String);
  }
}

I am using a service, but when ever i am trying to use this class to get data it gives me error. My Service Call Is Like This.
static Future<List<TrainClassData>> GetTrainClass() async {
    String url = 'http://ttreturn.itfuturz.com/AppService.asmx/TrainClassMaster?type=trainclass';
    print("train class URL: " + url);
    final response = await http.get(url);
    try {
      if (response.statusCode == 200) {
        List<TrainClassData> list = [];
        if (response.body != "" && response.body.toString() != "[]") {
          final parsed = json.decode(response.body).cast<Map<String, dynamic>>();
          var trainClassData = parsed.map<TrainClassData>((json) => TrainClassData.fromJson(json));
          if(trainClassData.ERROR_STATUS == false) {
            list = trainClassData.Data;
          }
          else {
            list = [];
          }
        }
        return list;
      } else {
        throw Exception(MESSAGES.INTERNET_ERROR);
      }
    } catch (e) {
      print("Kapil Erorr : " + e.toString());
      throw Exception(MESSAGES.INTERNET_ERROR);
    }
  }

I am getting error.

NoSuchMethodError: Class 'MappedListIterable,
  TrainClassData>' has no instance getter 'ERROR_STATUS'.

Please Help Me. Thanks in advance.

A: There were some personal mistakes that cause issues.
1) Dart convert package takes care of casting the data. So You should use the proper type for the properties. (e.x. ERROR_STATUS should be bool, not string).
2) The response is an array. you should check types and classes you use. the corrected example is here:
class TrainClassData {
  String MESSAGE;
  String ORIGINAL_ERROR;
  bool ERROR_STATUS;

  bool RECORDS;
  List<TrainClass> Data;

  TrainClassData({
    this.MESSAGE,
    this.ORIGINAL_ERROR,
    this.ERROR_STATUS,
    this.RECORDS,
    this.Data,
  });

  factory TrainClassData.fromJson(Map<String, dynamic> json) {
    return TrainClassData(
        MESSAGE: json['MESSAGE'] as String,
        ORIGINAL_ERROR: json['ORIGINAL_ERROR'] as String,
        ERROR_STATUS: json['ERROR_STATUS'] as bool,
        RECORDS: json['RECORDS'] as bool,
        Data: json['Data']
            .map<TrainClass>((json) => TrainClass.fromJson(json))
            .toList());
  }
}

class TrainClass {
  String Id;
  String Name;

  TrainClass({
    this.Id,
    this.Name,
  });

  factory TrainClass.fromJson(Map<String, dynamic> json) {
    return TrainClass(Id: json['Id'] as String, Name: json['Name'] as String);
  }
}

And for the service:
List<TrainClass> list = [];
    final parsed = json.decode(response.body).cast<Map<String, dynamic>>();
    var trainClassData = parsed
        .map<TrainClassData>((json) => TrainClassData.fromJson(json))
        .toList();
    if (trainClassData[0].ERROR_STATUS == false) {
      list = trainClassData[0].Data;
    } else {
      list = [];
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: I want increment a global variable conditionally for a list of items I am rendering an array of strings. I have a global variable "structureCount". I have some strings stored in redux store. I want to increment "structureCount" whenever strings from redux store matches the strings from the array I am rendering. And if the strings don't match
"structureCount" will be 0 for those.
let addedStr = 0;
    if (data.structures.structures) {
      data.structures.structures.forEach((str) => {
        if (str) {
          this.costCentre.forEach((centre) => {
            if (centre === str.cost_centre) {
              addedStr += 1;
            } else {
              addedStr = 0;
            }
          });
        } else {
          console.log("Not Exists");
        }
      });
    }


text:
Q: Standard deviation of predictive distribution of query points using a pipeline I am trying to do a simple regression task using a pipeline to assign the degree of the polynomial used for the regression (degree = 3). So I define:
pipe = make_pipeline(PolynomialFeatures(3), BayesianRidge())

And then the fitting:
pipe.fit(X_train, y_train)

And finally the prediction bit:
y_pred = pipe.predict(X_test)

BayesianRidge() of the sklearn has a return_std parameter for its predict method that when set to True, it returns standard deviation of predictive distribution of query points.
Is there anyway that I can get this standard deviation array using a pipeline?

A: You need to install the latest version of scikit-learn from their github repository. Next you would simply need to use partial  from functools. I have used the example similar to the one mentioned in Bayesian Ridge Regression docs.
from sklearn import linear_model
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import make_pipeline
from functools import partial

clf = linear_model.BayesianRidge()

#Make the pipeline
pipe = make_pipeline(PolynomialFeatures(3), clf)

#Patch the predict function of the classifier using partial
clf.predict = partial(clf.predict,return_std=True )

#Fit the pipeline
pipe.fit([[0,0], [1, 1], [2, 2]], [0, 1, 2])

#Retrieve the prediction and standard deviation
y_pred, y_std = pipe.predict([[1,2]])
#Output : (array([ 1.547614]), array([ 0.25034696]))

Note : Apparently this was a bug in sklearn's pipeline module as described here. It is now fixed in the latest version.
Reference:

*

*How partial works in Python


text:
Q: Bullets don't move forward, but stay stuck in the gun's location When the game starts on the client [localserver], the bullets don't move forward in space. They just stay fixed in the gun's location. See the image below for an illustration of the issue:

 Network Manegar: https://imgur.com/mfcBo61
Player: https://imgur.com/DuOIy67
Bullet: https://imgur.com/cVq5HFU

and this my script
    void Update()
   {
      if (!isLocalPlayer)
      {
         return;
      }
      if (Input.GetKey(KeyCode.Mouse0))
      {
         CmdBulletFire();
      }
   }
  [Command]
  void CmdBulletFire()
  {
    // create the bullet prefab
    GameObject bullet = Instantiate(bulletPrefab, bulletSpawn.position, bulletSpawn.rotation);

    //add velocity to bullet
    bullet.GetComponent<Rigidbody>().AddForce(transform.TransformDirection(Vector3.forward * 50000f));
    //Spawn the bullet
    NetworkServer.Spawn(bullet);
    //Destroy the bullet
    Destroy(bullet, 5f);
  }

What could the issue be, and how do I resolve it?
Still the Problem :(

A: In your update function, you have to make sure that this is the isLocalPlayer before calling CmdBulletFire().
Your new Update function:
void Update()
{
    if (!isLocalPlayer)
    {
        return;
    }

    if (Input.GetKey(KeyCode.Mouse0))
    {
        CmdBulletFire();
    }
}

Finally, make sure you do the following:
1.Attach NetworkTransform and NetworkIdentity components to the prefab.
2.Register the prefab to the NetworkManager:
enter image description here


text:
Q: A continuous map induced by a continuous map? (Munkres) I'm having trouble understanding this exercise from a topology book by Munkres.
The point of the exercise is to prove if $h:S^1 \to S^1$ is antipode-preserving and continuous, then $h$ is not homotopic to a constant map.

(a) Let $p : S^1 \to S^1$ be the map $p(z) = z^2$, $z \in \mathbb{C}$. Show that $h$ induces a continuous map $g : S^1 \to S^1$ such that $p \circ h = g \circ p$.
(b) Show that if $f$ is any path in $S^1$ from $x$ to its antipode $-x$ then $p \circ f$ is a loop in $S^1$ that is not path homotopic to a constant.
(c) Show that $p$ and $g$ induce monomorphisms of the fundamental groups.
(d) Conclude $h$ is essential (i.e. not homotopic to a constant map).

Now, I know what the induced homomorphism of a continuous map is. But I don't understand what it means for a continuous map to induce another continuous map with the same domain and codomain.
I was also thinking perhaps it wanted something like $g(e^{i\theta}) = h(e^{i\theta/2})^2$, though I don't see how that fits into the direction of the exercise.
Unfortunately my prof. just distributed this one photocopied page from the book, so perhaps the issue is explained elsewhere that I don't see. Any clarification from someone who is familiar with this book, or has seen this type of construction before, is much appreciated!

A: "induces" in this setting means that there exists a (unique, though this is not very important map such that the diagram
$$
\newcommand{\ra}[1]{\!\!\!\!\!\!\!\!\!\!\!\!\xrightarrow{\quad#1\quad}\!\!\!\!\!\!\!\!}
\newcommand{\da}[1]{\left\downarrow{\scriptstyle#1}\vphantom{\displaystyle\int_0^1}\right.}
%
\begin{array}{ll}
S^1 & \ra{p}& S^1\\
\da{g} & & \da{h}  \\
S^1 & \ra{p} & S^1 \\
\end{array}
$$
commutes.
And as for "one page from the book", you guys do have a library, no?


text:
Q: How do I recursively apply PKGREPOSITORY when calling make package-recursive in FreeBSD? I'm trying to create a package of Apache and its dependencies:
sudo make package-recursive \
__MAKE_CONF=~/make.apache22.conf \
PKGREPSOITORY=/usr/home/gvkv

Everything works fine; Apache and its dependencies compile and install and apache22.tbz is in gvkv.  The problem is that the dependency packages are built in their respective ports/<package> directories!  There are about fifteen of them and while it's easy enough to retrieve them with find and a perl one-liner, surely there must be a way to tell make to run in an environment such that the dependency packages end up in gvkv.

A: Part of the fun of using FreeBSD is dealing with the ports subsystem.  It's good in many ways--easy installation and upgrading within the FreeBSD ecosystem but poor in others--setting variables via make configuration files or environment don't work as expected or even as advertised.
Nevertheless, SirDice has come to the rescue with a neat little trick:
mount -t nullfs /directory/for/pkgs /usr/ports/packages

which is really cool because it bypasses the use of environment variables and you can set the destination directory for wherever you want.  Very helpful if you're (like me) using a 'build-jail' to make packages that are installed on different systems or other jails.
The /usr/ports/packages directory is where PACKAGES points to (if it exists) which is supposedly able to point somewhere else but didn't work for me.  The man page stipulates setting PKGREPOSITORY which only works if you are building a single package.

A: I've read that that PKGREPOSITORY is dependent on PACKAGES.
You can set PACKAGES in /etc/make.conf. For example:
DISTDIR= /opt/portbuild/distfiles
PACKAGES=/opt/portbuild/packages


text:
Q: AppCenter can't find Swift project I am using Microsoft's AppCenter to distribute an app.
After connecting to a branch I receive an error page

I set the scheme of the app to shared as required. Anyone have any experience with similar issue?

A: I'd suggest you reach out to App Center support (via the chat bubble at bottom right of the portal). We can then look into details of your application. If it's something others can run into too, we can circle back and share what happened.


text:
Q: The form's view data is expected to be an instance of class My\(...), but is a(n) array Error that appears:

The form's view data is expected to be an instance of class
  My\FrontendBundle\Entity\Intro, but is a(n) array. You can avoid this
  error by setting the "data_class" option to null or by adding a view
  transformer that transforms a(n) array to an instance of
  My\FrontendBundle\Entity\Intro.

What is wrong?
In DefaultController.php I have
public function formularzAction(){
        $Repo = $this->getDoctrine()->getRepository('MyFrontendBundle:Intro');
        $Register = $Repo->findAll();
        $form = $this->createForm(new EditType(), $Register);
        return array(
            'form' => $form->createView(),
            'rows' => $Register
        );
    }

my EditType.php
<?php
namespace My\FrontendBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class EditType extends AbstractType{
    public function getName(){
        return 'register_form';
    }
    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder
                ->add('info', 'textarea', array(
                    'constraints' => array(
                        ),
                    'label' => 'Informacje dodatkowe'
                ))
            ;
    }
    public function setDefaultOptions(\Symfony\Component\OptionsResolver\OptionsResolverInterface $resolver) {
        $resolver->setDefaults(array(
            'data_class' => 'My\FrontendBundle\Entity\Intro'
        ));
        }
}

my Intro.php:
<?php

namespace My\FrontendBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Intro
 *
 * @ORM\Table()
 * @ORM\Entity
 */
class Intro
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="info", type="string", length=2500)
     */
    private $info;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set info
     *
     * @param string $info
     * @return Intro
     */
    public function setInfo($info)
    {
        $this->info = $info;

        return $this;
    }

    /**
     * Get info
     *
     * @return string
     */
    public function getInfo()
    {
        return $this->info;
    }
}

A: Your form is waiting ONE and only ONE INtro entity.
Your findAll()query will return null or an array with 1 or more Intro instances.
You can not create the form with the result of findAll() query.
You'll need to provide an id to find a specific Intro from database or loop over the array findAll() gave you and make an new IntroType instance for each results.


text:
Q: Arraylist extract values and update I have 2 arraylists. I am using one arraylist as a key to store values.
In nutshell, my code is as below.
    for(int i=0;i<transactionid.size(); i++)
    {
        if(transactionid.get(i).equals(transactionnumber))
        {
            transactionvalue.set(i, transactionvalues);
        }
    }

In the above program snippet, transactionid is used to store my key values. If there is a match in the key value, I am updating the arraylist transactionvalue.
So far so good. But now, I want to update another arraylist diskitemvalues based on the above two arraylist values.  The update is something like below.
for(int i=0;i<transactionid.size(); i++)
{
    if(transactionid.get(i).equals(transactionnumber))
    {
    try
    {
        /* Open file to read contents*/
        while ((strLine = br.readLine()) != null)
        {
           /* Get the values of transactionvalue arraylist and update them. */
           /* The transactionvalue arraylist contains values like {X Y}     */
           /* So my update in the diskitemvalues arraylist
              should be X = so & so Y = so & so based on file               */

I have to navigate to the particular value in the transactionid arraylist and for that particular key, I have to find out the corresponding values in the transactionvalue arraylist and update the diskitemvalues arraylist for all values present in the transactionvalue arraylist.
Example:
Transactionid transactionvalue
 1                 X Y
2                 M N
For transactionid = 2, my diskitemvalues [2] should have M = so & so and N = so & so from the input file. If it is transactionid = 1, my diskitemvalues[1] should have X = so & so and Y = so & so from the input file.


text:
Q: Unable to get result from two sets because of `Unable to cast object of type to type 'System.Data.Entity.Infrastructure.IObjectContextAdapter`` I'm pursuing a way to get result from 2 sets in .NET using Entity framework. From what I've seen on the internet, most of the approaches are similar to this one right here. I did the same thing but I get the error

Unable to cast object of type Domain.Models.AppContext to type 'System.Data.Entity.Infrastructure.IObjectContextAdapter'

Now the code that I use is pretty straight-forward. This is my AppContext.
public partial class AppContext: DbContext {
    public AppContext() {}

    public AppContext(DbContextOptions < AppContext > options): base(options) {
      Database.EnsureCreated();
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder) {

      base.OnModelCreating(modelBuilder);
    }

    public virtual DbSet < Class1 > Class1 {
      get;
      set;
    }
    public virtual DbSet < Class2 > Class2 {
      get;
      set;
    }

After that, I go to my class where the function is located and do public ParametarRepository(AppContext context) : base(context) where base(context) is
public class Repository < T >: IRepository < T > where T: BaseEntity {
    protected AppContext _context;
    private DbSet < T > entities;
    public Repository(AppContext context) {
      _context = context;
      entities = _context.Set < T > ();
    }
}

When I execute the code from the example in the link, namely
public MultiResultDomain GetMultipleResultSetFromSP() {
  MultiResultDomain domainEntity = new MultiResultDomain();
  var connection = _context.Database.GetDbConnection();
  var command = connection.CreateCommand();
  command.CommandText = "dbo.TestResultSets";
  command.CommandType = CommandType.StoredProcedure;
  try {
    connection.Open();
    var reader = command.ExecuteReader();
    List < Class1 > links = ((IObjectContextAdapter) _context).ObjectContext.Translate < Class1 > (reader).ToList();
    reader.NextResult();
    List < Class2 > data = ((IObjectContextAdapter) _context).ObjectContext.Translate < Class2 > (reader).ToList();

    domainEntity.Links = links;
    domainEntity.Data = data;

    return domainEntity;
  } finally {
    connection.Close();
  }
}

I get the error that I mentioned earlier. Interesting thing is that if I debug this and check the value of reader, it does have values for Class 1 and after NextResult(), it has the values for Class 2 as well but sadly I can't access them as the code fails in the part where I should cast them to an object. EF version I have is 3.1.3 and .NET 3.1 version

A: This is not supported in EF Core, the tracking issue is here.
You can interop with ADO.NET directly, or with Dapper which will handle multiple results and materialize the objects for you.  See: QueryMultiple.


text:
Q: Input type="file" changes file name while i am try to upload (.url) file at that time it changes file name as well as file path. it will takes path from Internet Temporary File address.
i want to get original file name and original file path.
please Help me.

A: You can't get the original file name or path from a file input. They are obscured to protect the user's privacy and security (the structure of their file system is not the business of websites they interact with).
The purpose of a file input is to allow the content of a file to be submitted, not meta data about the file.


text:
Q: how to create a form to generate url i have a form on my site to generate url and it works well but the user should wait until the whole page is loaded to be able to use it properly , i think that happens because i use window.onload and i should use $(document).ready instead of it , but i couldnt replace it i need someone to help me with it

<form   id="searchform" name="filterform">
   <select class="chosen" name="department" id="searchfield" >
      <option value="http://www.mysite.com/">choise 1</option>
      <option value="http://www.mysite.com/">choise 1</option>
   </select>

   <select class="chosen" name="country" id="choose">
      <option value="?qatar=show&action=Filter">qatar</option>
      <option value="?ksa=show&action=Filter">ksa</option>
   </select>

   <button  class="submit" onclick="filterLoad()"  /></button>

</form>

A: I'd get rid of all the extra javascript to assign the function and just use:
<form   id="searchform" name="filterform" onsubmit="filterLoad">

A: You have the right idea, I would just call that function though when the form is submitted, and remove the on click event from the submit button.
Try this :

<form id="searchform" name="filterform" onSubmit="return filterLoad();" >
   <select class="chosen" name="department" id="searchfield" >
      <option value="http://www.mysite.com/">choise 1</option>
      <option value="http://www.mysite.com/">choise 1</option>
   </select>

   <select class="chosen" name="country" id="choose">
      <option value="?qatar=show&action=Filter">qatar</option>
      <option value="?ksa=show&action=Filter">ksa</option>
   </select>
   <button  class="submit" /></button>
</form>


text:
Q: End recording once silence is detected I've been using something like this up to now: End sox recording once silence is detected
But now I'd like for the audio source and recording mechanism to be separate.
I can get the source as an .m3u stream. It's a two-ray radio stream, and so there will be periods of inactivity.
I've been reading the documentation for sox and don't see something for using a stream as a audio device.
Is there a better tool for this?


text:
Q: DiscordAPIError: Unknown Message when trying to automatically delete messages I am trying to create a system that automatically deletes messages in a specific channel if the message does not start with the command prefix AND the user does not have a specific role.
Everything works, but as soon as it deletes one message, it throws the error DiscordAPIError: Unknown Message
The following is the code snippet where this error is coming from:
client.on("messageCreate", (message) => {
    function deleteTalk(delay) {
        setInterval(() => {
            if (message.channel.id === "786356926216536102") {
                if (
                    !message.content.startsWith(prefix) &&
                    !message.member.roles.cache.has("791024545091420190")
                ) {
                    if (!message) return;
                    const user = message.author;
                    message.delete();
                    user.send("Please don't talk in report channels.");
                    return;
                }
            }
        }, delay);
    }

    deleteTalk(100);

//Other Code...
});

I've looked through questions where people have gotten the same error, but the solutions to those instances haven't worked for me. I've tried to add in code snippets that should prevent the function from firing again if there is no message to delete, but I assume what I had written was incorrect as I am still getting the error.

A: You put a setInterval so for the first execution your message is deleted but then you try again to delete it 100ms later but the message no longer exists.
For your situation I don't see what the setInterval is for

client.on('messageCreate', (message) => {
    if (
        message.channel.id === '786356926216536102' &&
        !message.content.startsWith(prefix) &&
        !message.member.roles.cache.has('791024545091420190')
    ) {
        const user = message.author;
        message.delete();
        user.send("Please don't talk in report channels.");
        return;
    }
});


text:
Q: Arduino to Arduino Modbus RTU in RS-485 I'm trying Arduino to Arduino (master-slave) communication using Modbus RTU protocol in RS-485. I am using an Arduino Mega 2560 for the project and using this library Modbus RTU. As of now, the master simply reads data slave and prints in the Serial monitor.
I tried the following code:
Slave
#include <ModbusRtu.h>
#define ID   3

Modbus slave(ID, 0, 0);
boolean led;
int8_t state = 0;
unsigned long tempus;
// data array for modbus network sharing
uint16_t au16data[9];

void setup() {
  // define i/o
  pinMode(2, INPUT);
  pinMode(3, INPUT);
  pinMode(4, INPUT);
  pinMode(5, INPUT);

  // start communication
  slave.begin(19200);
  tempus = millis() + 100;
  digitalWrite(13, HIGH);
}

void loop() {
  // poll messages
  // blink led pin on each valid message
  state = slave.poll( au16data, 9 );
  if (state > 4) {
    tempus = millis() + 50;
    digitalWrite(13, HIGH);
  }
  if (millis() > tempus) digitalWrite(13, LOW );
  // get digital inputs -> au16data[0]
  bitWrite( au16data[0], 0, digitalRead( 2 ));
  bitWrite( au16data[0], 1, digitalRead( 3 ));
  bitWrite( au16data[0], 2, digitalRead( 4 ));
  bitWrite( au16data[0], 3, digitalRead( 5 ));

  // diagnose communication
  au16data[6] = slave.getInCnt();
  au16data[7] = slave.getOutCnt();
  au16data[8] = slave.getErrCnt();
}

Master
#include <ModbusRtu.h>

// data array for modbus network sharing
uint16_t au16data[16];
uint8_t u8state;

/**
 *  Modbus object declaration
 *  u8id : node id = 0 for master, = 1..247 for slave
 *  u8serno : serial port (use 0 for Serial)
 *  u8txenpin : 0 for RS-232 and USB-FTDI
 *               or any pin number > 1 for RS-485
 */
Modbus master(0,1,1); // this is master and RS-485

/**
 * This is an structe which contains a query to an slave device
 */
modbus_t telegram;

unsigned long u32wait;

void setup() {
  master.begin(19200); // baud-rate at 19200
  master.setTimeOut(2000); // if there is no answer in 2000 ms, roll over
  u32wait = millis() + 1000;
  u8state = 0;
  Serial.begin(9600);
}

void loop() {
  Serial.print(u8state);
  switch(u8state) {
  case 0:
    if (millis() > u32wait) u8state++; // wait state
    break;
  case 1:
    telegram.u8id = 1; // slave address
    telegram.u8fct = 3; // function code (this one is registers read)
    telegram.u16RegAdd = 1; // start address in slave
    telegram.u16CoilsNo = 4; // number of elements (coils or registers) to read
    telegram.au16reg = au16data; // pointer to a memory array in the Arduino
    master.query(telegram); // send query (only once)
    u8state++;
    break;
  case 2:
    master.poll(); // check incoming messages
    if (master.getState() == COM_IDLE) {
      u8state = 0;
      u32wait = millis() + 100;
    }
    break;
  }
  Serial.println(au16data[0])
}

The output in the serial monitor is not changed when the input at Pin 2 is high in slave.
20
00

Could someone please tell me the possible cause and solution? If I've missed out anything, over- or under-emphasized a specific point, let me know in the comments.


text:
Q: Caused by: java.security.PrivilegedActionException: GSSException: Defective token detected (Mechanism level: GSSHeader did not find the right tag) TO acheive SSO, we just need to  modify Jboss Spring security files and placed kerberos setup configuration.
but we are unable to figure it out why GSS exceptions are occuring.
Kerberos and jboss are running in different machines. Please see the code of spring files, are we did any mistakes in it?
krb5.conf File
[libdefaults]
    default_realm = LAB.LOCAL
    dns_lookup_kdc = false
    dns_lookup_realm = false
    permitted_enctypes = RC4-HMAC aes128-cts aes256-cts arcfour-hmac-md5
    default_tgs_enctypes = RC4-HMAC aes128-cts aes256-cts arcfour-hmac-md5
    default_tkt_enctypes = RC4-HMAC aes128-cts aes256-cts arcfour-hmac-md5
[domain_realm]
.lab.local= LAB.LOCAL
lab.local= LAB.LOCAL
[realms]
  LAB.LOCAL = {
    kdc = 172.18.0.64:88
    default_domain = LAB.LOCAL
  }

Spring-security-07-portal.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:util="http://www.springframework.org/schema/util"
  xmlns:sec="http://www.springframework.org/schema/security"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
    http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">

  <!-- Configure security for the web interface. -->
 <sec:http pattern="/**" use-expressions="false" entry-point-ref="spnegoEntryPoint" >
    <!-- This is needed for CSRF protection and must not be removed -->
    <sec:custom-filter ref="csrfChannelProcessingFilter" before="FILTER_SECURITY_INTERCEPTOR" />
<!-- Added a filter for spnego -->
    <sec:custom-filter ref="spnegoAuthenticationProcessingFilter" position="PRE_AUTH_FILTER" />
    <sec:intercept-url pattern="/**" access="IS_AUTHENTICATED_FULLY" />

    <sec:request-cache ref="appianRequestCache"/>

    <sec:anonymous enabled="false"/>

   <!-- <sec:form-login login-page="#{pageUrls.login}" login-processing-url="/auth"
      username-parameter="un" password-parameter="pw"
      authentication-success-handler-ref="appianAuthenticationSuccessHandler"
      authentication-failure-handler-ref="appianAuthenticationFailureHandler"
      authentication-details-source-ref="portalAuthenticationDetailsSource"/> -->

    <sec:session-management session-authentication-strategy-ref="portalSessionAuthenticationStrategy"/>

    <sec:logout logout-url="#{pageUrls.logout}" invalidate-session="true" success-handler-ref="logoutSuccessHandler"/>

   <sec:remember-me services-ref="appianRememberMeServices"/>
  </sec:http>

    <bean id="spnegoEntryPoint"
            class="org.springframework.security.extensions.kerberos.web.SpnegoEntryPoint" />

  <bean id="logoutSuccessHandler" class="org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler">
    <property name="defaultTargetUrl" value="/"/>
    <property name="alwaysUseDefaultTargetUrl" value="true"/>
  </bean>

  <bean id="appianRequestCache" class="com.appiancorp.security.auth.AppianHttpSessionRequestCache" />

  <!-- These configurations are not yet available through the security namespace,
  so we use a BeanPostProcessor to apply settings required by the Portal environment. -->
  <bean id="appianSpringSecurityBeanPostProcessor" class="com.appiancorp.security.auth.BeanPostProcessorForPortalAuth">
    <property name="allowPostOnlyForAuthentication" value="false"/>
    <property name="useForwardForLoginPage" value="true"/>
  </bean>

    <!--These lines have been added to handle SSO with Kerberos -->
    <bean id="spnegoAuthenticationProcessingFilter" class="org.springframework.security.extensions.kerberos.web.SpnegoAuthenticationProcessingFilter">
        <property name="failureHandler" ref="failureHandler"/>
        <property name="authenticationManager" ref="authenticationManager" />
    </bean>

    <bean id="failureHandler" class="org.springframework.security.web.authentication.ExceptionMappingAuthenticationFailureHandler">
        <property name="defaultFailureUrl" value="/portal/loginPage.none?" />
    </bean>

</beans>

Spring security-03-auth-mgr.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:util="http://www.springframework.org/schema/util"
  xmlns:sec="http://www.springframework.org/schema/security"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
    http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">

    <!-- Spengo authentication entry point -->

 <bean id="spnegoEntryPoint" class="org.springframework.security.extensions.kerberos.web.SpnegoEntryPoint" />
 <bean id="spnegoAuthenticationProcessingFilter"
        class="org.springframework.security.extensions.kerberos.web.SpnegoAuthenticationProcessingFilter">
        <property name="authenticationManager" ref="authenticationManager" />
 </bean>

    <!-- Authentication manager configuration, specifying the class(es) responsible for performing the authentication. -->
  <sec:authentication-manager alias="authenticationManager" erase-credentials="true">
  <sec:authentication-provider ref="kerberosServiceAuthenticationProviderWrapped"/>
  </sec:authentication-manager>

<!-- Need to wrap the Authentication Provider using the Authentication Provider Wrapper class. See Appian Forum for details -->
  <bean id="kerberosServiceAuthenticationProviderWrapped" class="com.appiancorp.suiteapi.security.auth.AuthenticationProviderWrapper">
        <constructor-arg ref="kerberosServiceAuthenticationProvider"/>
     </bean>

  <!--Kerberos Authentication Provider -->
                 <bean id="kerberosServiceAuthenticationProvider" class="org.springframework.security.extensions.kerberos.KerberosServiceAuthenticationProvider">
                                <property name="ticketValidator" ref="kerberosTicketValidator"/>
                                <property name="userDetailsService" ref="appianUserDetailsServiceNoPwMgmt" />
                </bean>

                <bean id="kerberosTicketValidator" class="org.springframework.security.extensions.kerberos.SunJaasKerberosTicketValidator">
                                <property name="servicePrincipal" value="HTTP/user01@lab.local" />
                                <property name="keyTabLocation" value="file:///usr/local/appian/ear/suite.ear/web.war/WEB-INF/conf/appianrdserver.keytab" />
                                <property name="debug" value="true" />
                </bean>
                <bean class="org.springframework.security.extensions.kerberos.GlobalSunJaasKerberosConfig" >
                                <property name="debug" value="true" />
                                <property name="krbConfLocation" value="file:///etc/krb5.conf"/>
                </bean>
  <bean id="appianAuthenticationProvider" class="com.appiancorp.suiteapi.security.auth.AuthenticationProviderWrapper">
    <constructor-arg ref="appianAuthenticationProviderInternal"/>
    <constructor-arg ref="scsKeyChangeHandlerNoOp"/>
  </bean>

  <bean id="appianAuthenticationProviderInternal" class="com.appiancorp.security.auth.AppianAuthenticationProvider">
    <constructor-arg ref="appianUserDetailsService"/>
  </bean>

  <bean id="appianUserDetailsService" class="com.appiancorp.suiteapi.security.auth.AppianUserDetailsService"/>
  <bean id="appianUserDetailsServiceForRememberMe" class="com.appiancorp.suiteapi.security.auth.AppianUserDetailsService">
    <constructor-arg value="false"/>
  </bean>

  <bean id="rememberMeConfiguration" class="com.appiancorp.security.auth.rememberme.RememberMeConfiguration">
    <constructor-arg name="enabled" value="false"/>
    <constructor-arg name="tokenValiditySec" value="1209600"/>
  </bean>

  <bean id="rememberMeScsHandler" class="com.appiancorp.security.auth.rememberme.RememberMeScsHandler">
    <constructor-arg ref="rememberMeConfiguration" />
  </bean>

  <bean id="appianRememberMeServices" class="com.appiancorp.security.auth.rememberme.AppianPersistentTokenBasedRememberMeServices">
    <constructor-arg ref="rememberMeConfiguration"/>
    <constructor-arg ref="rememberMeTokenService"/>
    <constructor-arg ref="appianUserDetailsServiceForRememberMe"/>
    <constructor-arg ref="rememberMeTokenRepository"/>
    <constructor-arg ref="rememberMeScsHandler" />
    <constructor-arg ref="portalAuthenticationDetailsSource"/>
    <property name="seriesLength" value="32"/>
    <property name="tokenLength" value="32"/>
  </bean>

  <bean id="beanPostProcessorForAuthMgr" class="com.appiancorp.security.auth.BeanPostProcessorForAuthMgr">
    <property name="authenticationEventPublisher" ref="appianAuthenticationEventPublisher"/>
    <property name="rememberMeConfiguration" ref="rememberMeConfiguration"/>
  </bean>

  <bean id="appianAuthenticationEventPublisher" class="com.appiancorp.security.auth.AppianAuthenticationEventPublisher"/>

    <bean id="appianUserDetailsContextMapper" class="com.appiancorp.suiteapi.common.spring.security.BasicUserDetailsContextMapper">
       <constructor-arg ref="appianUserDetailsServiceNoPwMgmt"/>
     </bean>

       <bean id="appianUserDetailsServiceNoPwMgmt" class="com.appiancorp.suiteapi.security.auth.AppianUserDetailsService">
    <constructor-arg value="false"/>
  </bean>

</beans>

Server log

18:03:43,879 INFO  [stdout] (http-/0.0.0.0:8080-1) 2015-01-06 18:03:43,879 [http-/0.0.0.0:8080-1] DEBUG org.springframework.security.web.access.ExceptionTranslationFilter - Calling Authentication entry point.
18:03:43,879 INFO  [stdout] (http-/0.0.0.0:8080-1) 2015-01-06 18:03:43,879 [http-/0.0.0.0:8080-1] DEBUG org.springframework.security.extensions.kerberos.web.SpnegoEntryPoint - Sending back Negotiate Header for request: http://172.18.0.78:8080/suite/designer

18:03:43,912 INFO  [stdout] (http-/0.0.0.0:8080-1) 2015-01-06 18:03:43,912 [http-/0.0.0.0:8080-1] DEBUG org.springframework.security.web.FilterChainProxy - /designer at position 3 of 10 in additional filter chain; firing Filter: 'SpnegoAuthenticationProcessingFilter'
18:03:43,913 INFO  [stdout] (http-/0.0.0.0:8080-1) 2015-01-06 18:03:43,913 [http-/0.0.0.0:8080-1] DEBUG org.springframework.security.extensions.kerberos.web.SpnegoAuthenticationProcessingFilter - Received Negotiate Header for request http://172.18.0.78:8080/suite/designer: Negotiate TlRMTVNTUAABAAAAl4II4gAAAAAAAAAAAAAAAAAAAAAGAHIXAAAADw==
18:03:43,917 INFO  [stdout] (http-/0.0.0.0:8080-1) 2015-01-06 18:03:43,917 [http-/0.0.0.0:8080-1] DEBUG org.springframework.security.authentication.ProviderManager - Authentication attempt using com.appiancorp.suiteapi.security.auth.AuthenticationProviderWrapper
18:03:43,918 INFO  [stdout] (http-/0.0.0.0:8080-1) 2015-01-06 18:03:43,917 [http-/0.0.0.0:8080-1] DEBUG org.springframework.security.extensions.kerberos.KerberosServiceAuthenticationProvider - Try to validate Kerberos Token
18:03:43,952 INFO  [stdout] (http-/0.0.0.0:8080-1) 2015-01-06 18:03:43,951 [http-/0.0.0.0:8080-1] WARN  com.appiancorp.security.auth.AuthenticationEventLoggerListener - Cannot retrieve authentication details. Please update your Spring Security XML configuration, so that com.appiancorp.security.auth.AppianAuthenticationDetailsSource is used as the authenticationDetailsSource. (Expected an instance of com.appiancorp.security.auth.AuthenticationDetails, but got null.)
18:03:43,963 INFO  [stdout] (http-/0.0.0.0:8080-1) 2015-01-06 18:03:43,961 [http-/0.0.0.0:8080-1] WARN  org.springframework.security.extensions.kerberos.web.SpnegoAuthenticationProcessingFilter - Negotiate Header was invalid: Negotiate TlRMTVNTUAABAAAAl4II4gAAAAAAAAAAAAAAAAAAAAAGAHIXAAAADw==
18:03:43,964 INFO  [stdout] (http-/0.0.0.0:8080-1) org.springframework.security.authentication.BadCredentialsException: Kerberos validation not succesfull
18:03:43,964 INFO  [stdout] (http-/0.0.0.0:8080-1)  at org.springframework.security.extensions.kerberos.SunJaasKerberosTicketValidator.validateTicket(SunJaasKerberosTicketValidator.java:69)
18:03:43,964 INFO  [stdout] (http-/0.0.0.0:8080-1)  at org.springframework.security.extensions.kerberos.KerberosServiceAuthenticationProvider.authenticate(KerberosServiceAuthenticationProvider.java:86)
18:03:43,965 INFO  [stdout] (http-/0.0.0.0:8080-1)  at com.appiancorp.suiteapi.security.auth.AuthenticationProviderWrapper.authenticate(AuthenticationProviderWrapper.java:86)
18:03:43,965 INFO  [stdout] (http-/0.0.0.0:8080-1)  at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:156)
18:03:43,965 INFO  [stdout] (http-/0.0.0.0:8080-1)  at org.springframework.security.extensions.kerberos.web.SpnegoAuthenticationProcessingFilter.doFilter(SpnegoAuthenticationProcessingFilter.java:147)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:653)
18:03:43,973 INFO  [stdout] (http-/0.0.0.0:8080-1)  at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:926)
18:03:43,974 INFO  [stdout] (http-/0.0.0.0:8080-1)  at java.lang.Thread.run(Thread.java:745)
18:03:43,974 INFO  [stdout] (http-/0.0.0.0:8080-1) Caused by: java.security.PrivilegedActionException: GSSException: Defective token detected (Mechanism level: GSSHeader did not find the right tag)
18:03:43,974 INFO  [stdout] (http-/0.0.0.0:8080-1)  at java.security.AccessController.doPrivileged(Native Method)
18:03:43,974 INFO  [stdout] (http-/0.0.0.0:8080-1)  at javax.security.auth.Subject.doAs(Subject.java:415)
18:03:43,974 INFO  [stdout] (http-/0.0.0.0:8080-1)  at org.springframework.security.extensions.kerberos.SunJaasKerberosTicketValidator.validateTicket(SunJaasKerberosTicketValidator.java:67)
18:03:43,974 INFO  [stdout] (http-/0.0.0.0:8080-1)  ... 45 more
18:03:43,975 INFO  [stdout] (http-/0.0.0.0:8080-1) Caused by: GSSException: Defective token detected (Mechanism level: GSSHeader did not find the right tag)
18:03:43,975 INFO  [stdout] (http-/0.0.0.0:8080-1)  at sun.security.jgss.GSSHeader.<init>(GSSHeader.java:97)
18:03:43,975 INFO  [stdout] (http-/0.0.0.0:8080-1)  at sun.security.jgss.GSSContextImpl.acceptSecContext(GSSContextImpl.java:306)
18:03:43,975 INFO  [stdout] (http-/0.0.0.0:8080-1)  at sun.security.jgss.GSSContextImpl.acceptSecContext(GSSContextImpl.java:285)
18:03:43,975 INFO  [stdout] (http-/0.0.0.0:8080-1)  at org.springframework.security.extensions.kerberos.SunJaasKerberosTicketValidator$KerberosValidateAction.run(SunJaasKerberosTicketValidator.java:146)
18:03:43,975 INFO  [stdout] (http-/0.0.0.0:8080-1)  at org.springframework.security.extensions.kerberos.SunJaasKerberosTicketValidator$KerberosValidateAction.run(SunJaasKerberosTicketValidator.java:136)
18:03:43,975 INFO  [stdout] (http-/0.0.0.0:8080-1)  ... 48 more
18:03:43,976 INFO  [stdout] (http-/0.0.0.0:8080-1) 2015-01-06 18:03:43,976 [http-/0.0.0.0:8080-1] DEBUG org.springframework.security.web.authentication.ExceptionMappingAuthenticationFailureHandler - Redirecting to /portal/loginPage.none?
18:03:43,977 INFO  [stdout] (http-/0.0.0.0:8080-1) 2015-01-06 18:03:43,977 [http-/0.0.0.0:8080-1] DEBUG org.springframework.security.web.DefaultRedirectStrategy - Redirecting to '/suite/portal/loginPage.none?appian_environment=designer&'


text:
Q: Cannot add a Kivy Scatter widget into a Carousel I am trying to create a carousel where each image is added to a Scatter or ScatterLayout before adding to the carousel.  I want to resize the image with touch gestures.  The app is for an android phone.
However, I get an error that I Cannot add the scatter widget since it already has a parent.
Cannot add <kivy.uix.scatter.ScatterLayout object at 0x7fb9b903def0>,
it already    has a parent kivy.uix.relativelayout.RelativeLayout
object at 0x7fb9b8e21530>.

I can  add one image to a scatter widget and it stretches.  But with more than one image, when I try to insert the scatter or the scatterlayout between the carousel and the image, the error results.
the user needs to stretch the image (zoom in) on each carousel page if necessary.
import kivy
kivy.require('1.8.0')

from kivy.app import App
from kivy.uix.carousel import Carousel
from kivy.uix.scatter import Scatter
from kivy.uix.scatterlayout import ScatterLayout
from kivy.uix.scatter import ScatterPlane
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.image import Image
from kivy.uix.image import AsyncImage
from kivy.uix.anchorlayout import AnchorLayout

one_image = False
scatter = ScatterLayout(do_rotation=False)
carousel = Carousel(direction='right', loop=True)
data_dir_receipt = 'data/receipts'
prefix = '02_february_2015_receipts-all-*'
    if one_image is True:
        prefix = '02_february_2015_receipts-all-1.png'
        filename = join(data_dir_receipt, prefix)
        image = AsyncImage(source=filename, allow_stretch=True)
        scatter.add_widget(image)
        return scatter
    else:
        for filename in glob(join(data_dir_receipt, prefix)):
            image = AsyncImage(source=filename, allow_stretch=True)
            scatter.add_widget(image)
            carousel.add_widget(scatter)
        return carousel


text:
Q: gdb and debugging problems with an STL list I recently asked a question here, and didn't get an answer I could use, unfortunately:
C++ STL list functions segfaulting with empty list
I've been trying to use gdb to debug the issue, and I have a question about what something means:
I declare a list as a member of a class like so:
std::list<Thing*> inventory;

...and then instantiate the class it's in (an object called 'pc').  In gdb, I presume this shows that I have some memory allocated to it?
(gdb) p &pc.inventory
$7 = (std::list<Thing*, std::allocator<Thing*> > *) 0xbffff22c

Further in, one line before the problem line of the code (in essence, calling 'inventory.size()' causes a segfault), this still holds:
(gdb) p &inventory
$8 = (std::list<Thing*, std::allocator<Thing*> > *) 0xbffff22c

...however I still get the segfault:
(gdb) n
558   if (inventory.size() == 52) {
(gdb) n

Program received signal SIGSEGV, Segmentation fault.
0x0804e3fe in std::_List_const_iterator<Thing*>::operator++ (this=0xbfff94e0)
at /usr/include/c++/4.4/bits/stl_list.h:223
223     _M_node = _M_node->_M_next;

My question is essentialy this:  Surely, if I have an address for the member list, the list exists, and I should be able to use size() on it??  If not, why not?  And how could I further debug?
Thanks all!

A: To debug memory errors i suggest you run the program in valgrind

valgrind --tool=memcheck program_name

and fix all the errors pointed by valgrind


text:
Q: Return file from request framework7 I am trying to create a script for downloading files through a web app, for now I am concentrating on the script server then I will switch to cordova for phones.
Code i tried:
Javascript:
$f7.request({
  method: 'POST',
  url: urlofwebsite + 'api/getFile.php',
  crossDomain: true,
  data: {
    fakeid: idoffile,
    iduser: iduser, // check for security reason
    time: timeoflogin // check for security reason
  },
  success: function(data, status, xhr) {
    var blob = new Blob([data], {
      type: 'application/pdf'
    });
    var url = window.URL.createObjectURL(blob);
    var fileName = 'test.pdf';
    var urllink = url;
    var link = document.createElement('a');
    link.href = urllink;
    link.download = fileName;
    link.click();
  }
});

PHP:
$file = $_SERVER['DOCUMENT_ROOT'].$res['url'];
readfile($file);

By manually specifying the extension and file type (just for test it), the file from the blob is downloaded but completely blank.

A: thanks to @ADyson for help, i can provide a community wiki answer:
Besides the various basic problems such as header etc. in my question, there was a fundamental trick which is adding this command to the request:
xhrFields: { responseType: 'blob' }

In the php file instead just use:
$file = PATHTOFILE; readfile($file);


text:
Q: Returning different types of variables Sorry if my title is a bit misleading, not sure how to summarize the issue Im having at this point.
Basically my assignment is to use Inheritances.
But my issue at the moment is that Im not sure how to return int and strings in the same function to be displayed in another function.
Below is the example, hope it makes more sense.
I've tried using references, but clearly Im doing it wrong as Im unable to get it to work.
Main.cpp:
#include <iostream>
#include "Text.h"

int main(){

    Text text1;
    text1.SetText("Arial", 12, "Black", "This is a sample text"); //String, int, string, string
    text1.PrintText();

    return 0;
}

Text.h:
#ifndef TEXT_H
#define TEXT_H

class Text{

    public:
        Text();
        void SetText(std::string font, int size,  std::string color, std::string data);
        void GetParameters(); /*This is the problem area. I have setText that will set it, but how do I return these values to use in PrintText if it has different variable types?*/
        void PrintText();

    private:
        std::string font;
        int size;
        std::string color;
        std::string data;
};

#endif // TEXT_H

Text.cpp:
#include <iostream>
#include "Text.h"

Text::Text(){
}

void Text::SetText(std::string font, int size,  std::string color, std::string data){
    font = font;
    size = size;
    color = color;
    data = data;
}

void Text::GetParameters (){//Any pointers in this would be much appreciated.
}

void Text::PrintText(){
    cout <<"Text parameters are: "  <<GetParameters() <<endl;//this is where Im trying to simply display the font, size, color and data values.
}

Im sorry if its a bit lengthy, I wasnt sure how much to include to properly illustrate the issue Im having.
The result Im trying to achieve is something very basic:
Text parameters are:
Font = Arial
Size = 12
Color = Black
Data = This is a sample text

Worth mentioning that I cant use structs in this assignment.

A: It looks like you only need to return a string as the output from the function GetParameters. Note that currently your return type is void (returns nothing).
Example code:
std::string Text::GetParameters() {
    std::string stringToReturn = "";
    stringToReturn += "Font = " + font + "\n";
    stringToReturn += "Size = " + std::to_string(size) + "\n";
    // leave it to you to figure out the rest of the function
    return stringToReturn;
}

A: Just print out the data members:
void Text::PrintText()
{
    cout << "font: " << font << ", size: " << size << ", color: " << color
         << ", data: " << data << "\n";
}

If you want to access these members from non-member functions, then add public getter member functions:
class Text {
public:
    // ...

    const std::string& getFont() const { return font; }
    int getSize() const { return size; }
    const std::string& getColor() const { return color; }
    const std::string& getData() const { return data; }
};

I recommend renaming the private member variables to clearly distinguish them from public members. A popular way is to just append an underscore to their name:
class Text {
    // ...

private:
    std::string font_;
    int size_;
    std::string color_;
    std::string data_;
};

A: The std::string Text::GetParameters() function is already covered by the other answers, but I'd like to point out a bug with your void Text::SetText implementation:
void Text::SetText(std::string font, int size,  std::string color, std::string data){
    font = font;
    size = size;
    color = color;
    data = data;
}

This doesn't do anything because font = font; just sets the font parameter to what it already is, and likewise for the other parameters. Instead, try this:
void Text::SetText(std::string font, int size, std::string color, std::string data) {
    this->font = font;
    this->size = size;
    this->color = color;
    this->data = data;
}

By saying this->font you are telling it that you don't mean the font parameter, but the font field of the object. Now it's correctly setting the fields to the respective parameters.


text:
Q: TFS mapping gone in solution explorer, but listed correct at Team Explorer I have a team project that I was working on, but today I opened Visual Studio 2013 (update 2) and my solution, just to see that TFS options (check in, get latest menu options, along with the lock and + signs next to files) are gone. The solution is just like a local solution. I haven't done anything. When I go to team options, I can see that it is mapped to the correct path and I'm on the correct workspace. I've removed the mapping, deleted the solution locally (I didn't have any pending changes) and remapped the solution from TFS. Got the latest version but still no mapping in solution explorer. Restarted Visual Studio many times (obviously), but no avail. I can get the latest from team explorer though. What could be the cause and how can I solve this problem?

A: You need to open "File | Source Control | Change Bindings". If the files are in the correct folder you should see a bunch of red squiggles under the mappings.

*

*Unbind all of the projects and the solution

*Rebind all of the projects and the solution

That should solve the issue.

A: You might have lost the solution bindings
 Try to re bind to source control. Also check you are in the correct workspace in both places and that you are correctly mapped.

A: Your top source location is mapped into your local folder, check that and remove if that is mapped to the local folder.
Right Click -> Advanced -> Remove Mapping

A: I ended up going to Control Panel -> User Accounts -> Credential Manager and removing several references to a service account that some how became associated with my work space over the weekend. No idea why that happened but removing those associations and restarting visual studio resolved the issue.
The issues I experienced because of this issue are:

*

*"Out of memory" alert when launching an existing solution that has always worked just fine.

*When "getting latest" on a solution, I would receive an error about our service account not having sufficient permissions to perform the action on my own work space.


text:
Q: Having compatibility issues on Google Play with some devices I've recently just launched my app, and it's going really well! I am having issues with some users, though. Users on older devices such as the Nexus 5X, Huawei P10 Lite, and Meizu M2 Note are saying they are unable to download the app on Google Play because it says it is incompatible with their device. I've already checked the Developer Console and it says the app should support these devices (except the Meizu that one doesn't even show up in the catalog). I've also already run emulators mimicking the devices and everything works fine. All of them are running Android 8.0 which I know for sure is supported by my app.
I've been looking all over google for a way to solve this, but honestly I have no idea what to do anymore. This is my first real app and I can't help but get the feeling that I'm missing some crucial step for widespread release.

Here's my Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.balanstudios.einar.workouttimer">

    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-feature android:name="android.hardware.vibrate" android:required="false"></uses-feature>

    <application
        android:name=".BaseApp"
        android:allowBackup="true"
        android:icon="@mipmap/ic_work_icon_small"
        android:label="Robota"
        android:roundIcon="@mipmap/ic_work_icon_small_round"
        android:supportsRtl="true"
        android:theme="@style/WorkoutTimerLight">
        <activity
            android:name=".MainActivity"
            android:screenOrientation="portrait"
            android:theme="@style/WorkoutTimerLight"
            android:windowSoftInputMode="adjustPan">

        </activity>

        <meta-data
            android:name="preloaded_fonts"
            android:resource="@array/preloaded_fonts" />

        <activity android:name=".SplashScreen"
            android:screenOrientation="portrait"
            android:theme="@style/WorkoutTimerLight"
            android:windowSoftInputMode="adjustPan">

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER"></category>
            </intent-filter>

        </activity>
    </application>

</manifest>

Here's my gradle:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.balanstudios.einar.workouttimer"
        minSdkVersion 23
        targetSdkVersion 28
        versionCode 7
        versionName "1.0.2"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
    sourceSets { main { assets.srcDirs = ['src/main/assets', 'src/main/assets/'] } }
    lintOptions {
        abortOnError false
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:28.0.0-alpha3'
    implementation 'com.android.support:support-media-compat:28.0.0-alpha3'
    implementation 'com.android.support:design:28.0.0-alpha3'
    implementation 'com.android.support.constraint:constraint-layout:1.1.2'
    implementation 'com.android.support:support-v4:28.0.0-alpha3'
    implementation 'com.google.code.gson:gson:2.8.2'
    implementation 'com.anjlab.android.iab.v3:library:1.0.44'

    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

Does anyone have any ideas? I would really appreciate any help!
Play Store Link

A: Your app has min Sdk = 23 (this gradle line)
 minSdkVersion 23

The complaints are probably from users on older versions of Android.


text:
Q: Creating Non-Object Specific Methods Is it possible to make a method that uses an object as a parameter, but doesn't specify exactly what type of object will be passed? The method would try to use the compareTo method that most objects have.
Also, is it possible to check if an object has a compareTo method, and throw an exception if it doesn't?

A: The only thing you need your objects to do is to implement the Comparable interface.  Java will ensure that anything you're passing in would be type-safe at compile time, meaning you don't have to throw any kind of runtime exception.
From there, you may leverage any of the standard sort methods from Java:

*

*Collections#sort

*Arrays.sort
(Note that with Arrays.sort, it expects an Object[], but will throw an exception if the contract of Comparable is violated.)

A: From your description, it sounds to me like what you're asking for is to use casting:
/**
 * @param  lhs
 * @param  rhs
 * @return the result of comparing lhs to rhs via compareTo
 * @throws NullPointerException
 *         if lhs or rhs is null
 * @throws ClassCastException
 *         if lhs or rhs does not implement Comparable or
 *         if lhs and rhs are not mutually comparable
 * @see    Comparable#compareTo(Object)
 */
@SuppressWarnings({"rawtypes", "unchecked"})
private static int compareByCasting(Object lhs, Object rhs) {
    Comparable compL = (Comparable) lhs;
    Comparable compR = (Comparable) rhs;
    return compL.compareTo(compR);
}

This is how methods like Arrays.sort work behind the scenes.
That said, it's very rarely necessary to write code like that, unless you're writing very low-level API like in the case of Arrays.sort. Java has static typing, so in general the goal is to program towards pushing type checks to compile-time so we don't have to run the program to verify that it's correct. That's why we use tools like interfaces and generics.

A: a generic custom method with a constraint like below should enable you to compare objects that implement the generic Comparable interface, therefore, removing the need to take a parameter of type Object and then ensuring it has a compareTo method somehow.
public <T extends Comparable<T>> int comparer(T thiss, T that){
       // do logic
}

A:
sorting method [...] an array of objects

If all of these objects are the same type and implement comparable, you can use generics
Note that if they are not similarly typed, you'll need to write a custom method to compare(ie Integer and String comparison)
private <A extends Comparable<A>> void bigger(A a, A b)
{
    if(a.compareTo(b) > 0)
        System.out.println("a bigger");
    else
        System.out.println("b bigger");
}

Do note that this will only work for same typed objects
//works
String a = "5";
String b = "6";
bigger(a, b);

//compile error
Integer c = 5;
String d = "6";
bigger(c, d);

This works for things that implement Comparable
On custom objects, it's normally straightforward to implement
class Duck implements Comparable<Duck>
{
    private int height;
    [...]
    public int compareTo(Duck other)
    {
        return height - other.height;
    }
}

The cool thing about this, is most of the sorting bits of the Java API are built to handle Comparable

If you do not know that they are Comparables and stuck keeping everything as Objects, then you are most likely stuck using Reflection
int compare(Object a, Object b) throws NoSuchMethodException, IllegalAccessException, java.lang.reflect.InvocationTargetException
{
    return (Integer)a.getClass().getMethod("compareTo", b.getClass()).invoke(a, b);
}


text:
Q: WPF clickable area around controls in grid I have an issue with making a custom title bar for a form. It would contain a search textbox aswell as a few sliders, as seen on this image:

Now, imagine that as the title bar - everything that is not a part of the controls themselves (the textbox which is surrounded by a border element, and the slider) needs to be mousedownable for dragging purposes.
I've tried this:
<Grid MouseDown="TitleGridMouseDown">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="135"/>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="200"/>
        </Grid.ColumnDefinitions>
        <Slider Grid.Column="1" Margin="5 15 5 0" Width="100"  MouseDown="TitleGridMouseDown"/>
        <Slider Grid.Column="2" Margin="5 15 5 0"/>
        <Border Grid.Column="3" CornerRadius="10" BorderThickness="1" BorderBrush="White" Width="180" Height="20" Background="White">
            <TextBox Background="Transparent" BorderThickness="0" Height="20"/>
        </Border>

    </Grid>

However it's of no avail. There's a small part between the two sliders, like a few pixel area, which actually works (DragMove(); in the event itself). I don't have an awful lot of experience this type of things in WPF, but it feels to me like the area shrinks to the control. For instance, nothing changes if I place the border object into a button and try to bind the event to the button.
How should I approach this?

A: Your problem here is that you want to capture the MouseDown event on the grid element. Since your grid has no Background set, its defaulted to null. The MouseDown event does not get raised. Think of it like it is going through the grid without actually hitting it. A Background=Transparent on your top grid should solve the problem.


text:
Q: How to get Exact number of workbooks(excel files) How i can get total number of excel files.I am opening my files using  below code
try
   {
      var excelApp = new Excel.Application();
      excelApp.Visible = true;
      Excel.Workbooks book = excelApp.Workbooks;
      Excel.Workbook sheets = book.Open(schemes.ProcessExefilePath);
    }
 catch (Exception ex)
        {
        }

and then when i'm getting total number of files . it always return me zero count
  Microsoft.Office.Interop.Excel.Application excelApp = null;

    try
     {
        excelApp = (Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
      }
    catch
        {

         }
    if (excelApp == null)
       {
        excelApp = new Microsoft.Office.Interop.Excel.Application();
        }

         for (int i = 0; i < excelApp.Windows.Count; i++)
          {
                       //my work.......
           }

what is wrong in this code .. or is there any thing else i have to do..

A: In your code you don't open any files in the declared excelApp, so Windows.count gives you a value of 0
Try:
Microsoft.Office.Interop.Excel.Application excelApp = null;

try
 {
    excelApp = (Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
  }
catch
    {

     }
if (excelApp == null)
   {
    excelApp = new Microsoft.Office.Interop.Excel.Application();
    }
    ' **HERE** - Open workbooks with excelApp.Workbooks.Open(...)
     for (int i = 0; i < excelApp.Windows.Count; i++)
      {
                   //my work.......
       }


text:
Q: Proper snowball analyzer configuration when using Grails Searchable Plugin To improve stemming we want to switch from the default analyzer to snowball, however, having a lot of difficulty with the proper settings and would appreciate any help.  In
Environment:
- Sun's Java 1.6.16
- Grails 1.2.2
- Searchable Plug-In 0.5.5
Config.groovy:
  Have tried both settings:
compassSettings = ['compass.engine.analyzer.stemmed.type': 'snowball',
                     'compass.engine.analyzer.stemmed.name': 'English']

compassSettings = ['compass.engine.analyzer.snowball.type': 'snowball',
                     'compass.engine.analyzer.snowball.name': 'English',
                     'compass.engine.analyzer.search.type': 'snowball',
                     'compass.engine.analyzer.search.name': 'English']

Search.groovy - The Invocation:
def searchResult = searchableService.search(params.q, withHighlighter: {
highlighter, index, sr

  if (!sr.highlights) {
    sr.highlights = []
  }
  try {
         sr.highlights[index] = highlighter.fragments("content")[0..2].join(" ")
      } catch (IndexOutOfBoundsException ex) {
          sr.highlights[index] = highlighter.fragment("content")
      }
  })

  def suggestion = searchableService.suggestQuery(params.q)
  if (suggestion != params.q) {
      searchResult.suggestedQuery = suggestion
  }

A: Have you tried putting these settings in Searchable.groovy instead of Config.grovy?
In Searchable.groovy, I have:
    compassSettings = [
    'compass.engine.analyzer.default.type': 'snowball',
    'compass.engine.analyzer.default.name': 'English',
    'compass.engine.analyzer.search.type': 'snowball',
    'compass.engine.analyzer.search.name': 'English',
]

And that seems to work fine for me.


text:
Q: attaching unit test data to unit tests in visual studio I heavily make use of unit tests for my developer needs (POCs, unit tests, etc). For one particular test method there was a line that went...
var file = @"D:\data\file.eml";

So I am referencing some file on my file system.
Now in a team when other people are trying to run my "personal" tests (POCs or whatever) they don't have a reference to that file in that path...hence the tests fails. How we'd have to normally make this work is to provide the test data, and allow the user to modify the test code so that it runs on his computer.
Any visual studio way to manage this particular problem?
Whats the benefit in this? Well, people can review the test data (email in my case) as well as the method I wrote for testing, and can raise defects in TFS (the source control system) relating to it if need be.

A: One way I often handle data files for unit test projects are to set the data files as Resources. (* Note that this link is for vs2010 but I have used this approach through vs2015RC).
In the project with the data file:  Project -> Properties -> Resources and choose to add a resource file if you the project doesn't already have one.  Select Files in the resource pane and click Add Resource or just drag and drop your data files onto the resource manager.  By default resources are marked internal, so to access the resources from another project you have several ways:

*

*In the assembly with the data files, add the following to your AssemblyInfo.cs file and this will allow only specified assemblies to access the internal resources

[assembly: InternalsVisibleTo("NameSpace.Of.Other.Assembly.To.Access.Resources")]

*Create a simple provider class to abstract away the entire Resource mechanism, such as:

public static class DataProvider
{
    public static string GetDataFile(int dataScenarioId)
    {
        return Properties.Resources.ResourceManager.GetString(
            string.Format("resource_file_name_{0}", id));
    }
}

*Change the resource management to public (not an approach I have used)You can then access the data file (now a resource) from a unit test such as:

[TestCase(1)]
public void X_Does_Y(int id)
{
    //Arrange
    var dataAsAString = Assembly_With_DataFile.DataProvider.GetScenario(id);

    //Act
    var result = classUnderTest.X(dataAsAString);

    //Assert
    Assert.NotNull(result);
}

Note that using data files as resources, the ResourceManager handles the file I/O and returns strings of the file contents.
Update:  The test method in the example above is from an NUnit project and is not meant to imply process, but a mechanism by which a data file can be accessed from another project.

A: What you'd normally do is add the file to your project and check it into TFS. Then make sure the item's settings are:

*

*Build action: Content

*Copy to output: If newer

Then put an attribute on your Test method or Test class:
[DeploymentItem("file.eml")]

You can optionally specify an output dircetory:
[DeploymentItem("file.eml", "Directory to place the item")]

If you put the files in subdirectories of your test project, then adjust the attribute accordingly:
[DeploymentItem(@"testdata\file.eml")]

The file will be copied to the working directory of your test project and that makes it easy to access from your test code. Either load the file directly, or pass the path to any method that needs it.
If you tests expect the files in a specific location you can use a simple System.IO.File.Copy() or System.IO.File.Move() to put the item in the place you need it to be.
The process is explained here on MSDN.

A: I suppose the most straight forward way is to simply add whatever to the project, and set the correct value for Copy To Output Directory. In other words, say your data is in a text file.

*

*Add text file to your test project

*Right-click to access properties window

*Set copy to output directory field as Always or Copy if newer.

Now if you build the test project, the file gets copied to your output directly. This enables to write unit test code of the fashion:
var dataFile = File.OpenRead("data.txt");


text:
Q: How can make I fields mandatory during Formio editing? I'm building a form editing page using the Formio editor and renderer.
I'd like to make specific form fields mandatory in the form editor. [different than making the field entry mandatory during submission]
There are two roles in the application -
Editor - Modifies the formio definition.
User - Submits the form data.
I'm specifically interested in making several 'meta-data' fields mandatory for the Editor. The Editor should not be able to remove certain fields from the formio component list.
A couple options I'm considering for implementation -

*

*When the form is saved, inspect the form components and ensure the mandatory fields exist, and if they dont, create them.

*Set a flag in the UI for specific components so they are 'disabled' and cannot be removed in the formio editor.

Has anyone implemented this?

A: You seem to be going in the right direction.
You can definitely do (as you suggested):

*

*When the form is saved, inspect the form components and ensure the mandatory fields exist, and if they dont, create them or throw an error

Along with this, you can also extend the form builder and remove the "remove" icon that appears in the builder next to these mandatory components.
To do this,

*

*Add a custom property to all the components, something like "customIsMandatory"

*Modify the options.templates of the WebformBuilder to show a different template (one with "remove" icon removed) if the "customIsMandatory" is true for this component.

*You can pre-populate these mandatory components in the builder and make sure that this property is set to true for them.


text:
Q: Align button to bottom of div I need to align a button to the bottom of my div:

Title

Description

                View

Here is what it looks like at the moment:
http://pasteboard.co/bpTSsTC01.png

A: Use margin-top property according to your requirement.
example: margin-top:100%;
Alternatively, you can use position property
example: position:absolute; bottom:0;


text:
Q: Tangent Spaces (Algebraic Geometry) I'm in my algebraic geometry class and I have the definition of the space tangent to some variety $W=V(F_1,F_2,...)$ as the degree-1 components of $F_1,F_2,...$ . We then introduce the differential at a point $p$, which sends $g$ to $\sum_i \frac{dg}{dx_i}(p)(x_i-p_i)$. We then show that this is independent of generators of $I$, and want to prove the theorem that $T_pV=V(dpF_1...dpF_n)$.
This is where I get confused: isn't this the exact same as the degree-1 components? So haven't we already proven this?
We then show that $dp$ sends $k[x_1...x_n]$ to the set of linear functionals on the tangent space. But then there is some move where we restrict to $m_p=(x_1-p_1,...,x_n-p_n)$ and want to quotient this out, so we consider some $g$ in the kernel of $dp$, and expand it to find that $g$ must have degree greater than 2.
I guess I'm confused as to exactly what we are proving and what the significance of these results are.

A: You want to show that the subspace $(dF) \mid_a=0$ for all $F \in I(W)$ can actually be reduced to the calculation $(dF) \mid_a=0$ for $F= F_1, \dots ,F_n$ which are a set of generators for $I(W)$.
This amounts to showing that $(dF_1) \mid_a, \dots, (dF_n) \mid_a$ generate $\{(dF) \mid_a =0 \mid F \in I(W)\}$ as a vector space.
To do this, you really just need the product rule. If $G= \sum H_i F_i$, then apply the product rule to obtain that
$(dG)_a= \sum_i H_i(a) \cdot (dF_i) \mid_a$


text:
Q: SyntaxError: Unexpected token < in JSON at position 0 - React app in Rails API I'm working on a Rails 5.0.6 as an API. I am also running a React application for the front end running on a node server version v9.8.0. On the React app which is running on localhost:3000 I get the following error:
The rails is used as an API so in the controllers I return @drinks in json format.
drinks_controller.rb
class DrinksController < ApiController
  # GET /drinks
  def index
    @drinks = Drink.select("id,title").all

    render json: @drinks.to_json
  end

  # GET /drinks/1
  def show
    @drink = Drink.find(params[:id])
    render json: @drink.to_json(:include => { :ingredients => { :only => [:id, :description] }})
  end
end

I run both servers locally using Procfile in Profile.dev
web: cd client && PORT=3000 npm start
api: PORT=3001 && bundle exec rails s

When I go to the rails server which is running on localhost:3001/api/drinks I get the following:
[{"id":1,"title":"Sparkling Negroni"},{"id":2,"title":"Pineapple-Jalapeño Margarita"}]

which is in json format, On the app.js im fetching from that endpoint
class App extends Component {
  componentDidMount() {
    window.fetch('api/drinks')
      .then(response => response.json())
      .then(json => console.log(json))
      .catch(error => console.log(error))
  }

Is it the proxy not working?
{
  "name": "package-json",
  "version": "4.0.1",
  "description": "Get metadata of a package from the npm registry",
  "license": "MIT",
  "repository": "sindresorhus/package-json",
  "proxy": "http://localhost:3001",
  "author": {
    "name": "Sindre Sorhus",
    "email": "sindresorhus@gmail.com",
    "url": "sindresorhus.com"
  }

I can't understand what the issue is?

A: I suspect your rails app is returning html when fetch is expecting JSON... The < character is indicative that an HTML string is being delivered, (the JSON parser is choking on HTML).
Try dumping the response "as is" to see what you're receiving.
class App extends Component {
  componentDidMount() {
    window.fetch('api/drinks')
      .then(response => {
         console.log(response.status);
         console.log(response.body);
         return response.json();
      })
      .then(json => console.log(json))
      .catch(error => console.log(error))
}


text:
Q: Im very unfamiliar with python 2.7. Im not sure how to convert a specific piece of code from 2.7 to 3+ I have no idea how python 2.7 works. Is there a way for me to convert it to python 3?
recipients = ['email@email.com', 'email2@email.com']
sent = 1
print 'Email sent to: %s (%s)' % (", ".join(recipients), sent)

Specifically, i'm unsure about the print statement.

A: In Python 3, print is a function. So, you can make this work by changing it to:
recipients = ['email@email.com', 'email2@email.com']
sent = 1
print('Email sent to: %s (%s)' % (", ".join(recipients), sent))

But you can format using f-strings by changing your print statement like this:
print(f'Email sent to: {", ".join(recipients)}')

You can read more about f-strings here.
That's the only difference in this piece of code.
You can read more about the changes here.


text:
Q: AngularJS: how can I get $location.path to template I need current path from url in template (content of $location.path). But not via controller, because I have a lot of controllers (and I do not want to duplicate declaration of $scope.currentUrl = $location.path;). Thanks for the advice.

A: AngularJS template can only see what is available in a scope so you will need somehow to put $location service in a scope. There is one scope that is always available in AngularJS application called $rootScope so it could be use for your use-case.
What you could do is to use run() method of a module to expose $location in the $rootScope:
var myApp = angular.module('myApp', []).run(function($rootScope, $location) {
    $rootScope.location = $location;
});

this would make 'location' available in all templates so later on you could do in your template:
Current path: {{location.path()}}

A: An alternative is to use the more semantic and versatile ui-router, then in the controller, retrieve the current state, and store it on the $scope:
app.controller('MyCtrl', ['$scope', '$state', function MyCtrl($scope, $state) {
  $scope.state = $state.current.name;
  ...
}


text:
Q: Custom error redirect on 404 code for non-aspx files I added to my web.config:
<customErrors mode="RemoteOnly" defaultRedirect="~/Pages/Error/Error.aspx">
    <error statusCode="404" redirect="~/Pages/Error/Error404.aspx"/>
</customErrors>

and it works fine for .aspx pages.
When I try to type: http://domainname.com/notExist, I get the default 404.
I tried the suggestions from:
404 Redirecting for non aspx pages
but nothing works for me.
Any ideas why?
I use .net 3.5, application pool pipeline mode is Integrated.
After adding <httpErrors> I get:

A: Try This, it will provide separate status. Then you can execute as per your requirement.
<system.web>
    <customErrors mode="RemoteOnly" defaultRedirect="~/Pages/Error/Error.aspx">
        <error statusCode="404" redirect="~/Pages/Error/Error404.aspx"/>
    </customErrors>
</system.web>
<system.webserver>
<asp scriptErrorSentToBrowser="true"/>
    <httpErrors errorMode="Detailed">
          <error statusCode="401" path="/Pages/Error/Error.aspx" responseMode="Redirect" />
          <error statusCode="403" path="/Pages/Error/Error.aspx" responseMode="ExecuteURL" />
          <error statusCode="404" path="/Pages/Error/Error404.aspx" responseMode="ExecuteURL" />
          <error statusCode="500" path="/Pages/Error/Error.aspx" responseMode="ExecuteURL" />
    </httpErrors>
</system.webserver>

A: You need to separate setting for other pages.
Try something like this.
 <system.webserver>
      <httpErrors errorMode="Custom" >
            <remove statusCode="404" subStatusCode="-1" />
             <error statusCode="404" path="~/Pages/Error/Error404.aspx" />
      </httpErrors>
 </system.webserver>


text:
Q: PHP Replace multiple string within foreach loop I'm grabbing the source of a page with a lot of PDF links (files) listed in a column like so. simple_php_dom.php
TALB20170826D-$A$$-RA11.pdf
TAP$20170826D-$A$$-RA11.pdf
TASD20170826D-$A$$-RA11.pdf
TAUA20170826D-$A$$-RA11.pdf
TAUB20170826D-$A$$-RA11.pdf
TAUC20170826D-$A$$-RA11.pdf
TAUD20170826D-$A$$-RA11.pdf
TBTP20170826D-$A$$-RA11.pdf
TCBY20170826D-$A$$-RA11.pdf

I need to rename them within the foreach loop
foreach($html->find('a') as $element)
echo $element->href;

For instance TALB is an abbreviation for ALBANY, TAP is an abbreviation for Asia Pacific and so on.
I have a list of the names that correspond with the abbreviations but unsure how to rename them within the loop? Any help would be greatly appreciated!

A: You can put the list of replacements in arrays:
<?php
/*
$list = [];
$list[] = "TALB20170826D-\$A$$-RA11.pdf";
$list[] = "TAP$20170826D-\$A$$-RA11.pdf";
$list[] = "TASD20170826D-\$A$$-RA11.pdf";
$list[] = "TAUA20170826D-\$A$$-RA11.pdf";
$list[] = "TAUB20170826D-\$A$$-RA11.pdf";
$list[] = "TAUC20170826D-\$A$$-RA11.pdf";
$list[] = "TAUD20170826D-\$A$$-RA11.pdf";
$list[] = "TBTP20170826D-\$A$$-RA11.pdf";
$list[] = "TCBY20170826D-\$A$$-RA11.pdf";
*/
$list = $html->find('a');
$abbr = [
    "TALB",
    "TAP",
    // ...
];
$replacements = [
    "ALBANY",
    "Asia Pacific",
    // ...
];
foreach ($list as &$el) {
    $el->href = str_replace($abbr, $replacements, $el->href);
}

Demo
Or, to keep them all in one associative array (order doesn't matter and missing items just won't be replaced, no errors):
<?php
/*$list = [];
$list[] = "TALB20170826D-\$A$$-RA11.pdf";
$list[] = "TAP$20170826D-\$A$$-RA11.pdf";
$list[] = "TASD20170826D-\$A$$-RA11.pdf";
$list[] = "TAUA20170826D-\$A$$-RA11.pdf";
$list[] = "TAUB20170826D-\$A$$-RA11.pdf";
$list[] = "TAUC20170826D-\$A$$-RA11.pdf";
$list[] = "TAUD20170826D-\$A$$-RA11.pdf";
$list[] = "TBTP20170826D-\$A$$-RA11.pdf";
$list[] = "TCBY20170826D-\$A$$-RA11.pdf";*/
$list = $html->find('a');
$abbr = [
    "TALB" => "ALBANY",
    "TAP" => "Asia Pacific",
];
foreach ($list as &$el) {
    $el->href = strtr($el->href, $abbr);
}

Demo
Or use array_map(), maybe you'll find it a bit cleaner:
$list = array_map(function($el) use($abbr) {
    return strtr($el, $abbr);
}, $list);


text:
Q: Not able to parse multiline array in powershell My aws cli returns multiline array with nested hash, I am not able to parse output to get appropriate values from it
>Write-Host $a
[
  [
     [
         {
             "VolumeID": "vol-fxxxxxx"
         }
     ]
   ]
]

If I do $a[0], it returns first line i.e. "[" same with incremental indexs.
How I can parse this array and get the volumeID from it ?
Thanks
Additional details :
Thanks for your valuable answers. Here is the class name of the above object :
> $a.getType()
IsPublic IsSerial Name                                     BaseType
 -------- -------- ----                                     --------
True     True     Object[]                               System.Array

> $a | Where-Object ($_ -like "*Volume*")

> $a | ConvertFrom-Json
 ConvertFrom-Json : Invalid JSON primitive:
 Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData.
 At line:1 char:6

 + $a | ConvertFrom-Json
 +      ~~~~~~~~~~~~~~~~
 + CategoryInfo          : NotSpecified: (:) [ConvertFrom-Json], ArgumentException
 + FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.Commands.ConvertFromJsonCommand

Hi Martin Brandl, TessellatingHeckler I have updated with your question, could you please help me out on the same.
Thanks

A:
same with incremental indexs

I can't make sense of incremental indexes doing the same, and returning the first line, but it looks like it's either:
A multiline string ($a.gettype() has Name: String):
$b = $a | ConvertFrom-Json
$b[0][0][0].VolumeID

or, an array of string ($a.gettype() Name is Object[] or String[]), do this first, then convert from JSON:
$a = -join $a

A: You could use the where-object cmdlet.
$a | where-object {$_ -like "*Volume*"}

More information on the where-object cmdlet can be found here: https://technet.microsoft.com/en-us/library/ee177028.aspx
Thanks, Tim.


text:
Q: Show history of changes to files based on a wildcard e.g. *.vcxproj Somewhere, changes to a project file or similar is causing build issues but there have been a lot of changes from various branches and it's not immediately obvious where or when
Is there a way I can get git to simply list in reverse order, each time a file matching a wildcard has been modified, e.g. *.sln, *.vcxproj, so I can troubleshoot each commit more easily?

A: Yes.
Just filter your log with -- <path> [<other/path>] to restrict the commits output to the ones which modify (in any way, modification, creation, deletion...) said path(s). Wildcards are allowed. (see doc)
git log -- *.sln *.vcxproj

And of course you can then throw in here any comfort options you want (here --oneline for example, but adapt to your needs), including --reverse. You'll also probably want to use --all to search on every branch, not only on the currently checked out one.
Just be sure to have only paths after the --, any option has to be given before it.
git log --reverse --oneline --all -- *.sln *.vcxproj

(Note: double-quote your paths when they happen to contain whitespace)
(In some shells, even without whitespace, you'll also have to double-quote to avoid premature expansion of the wildcard)


text:
Q: How to efficiently have 1 html layout page for many products that'll call mysql database for product info and insert where I designate it? Ok so eventually I will have let's say 100 products in mysql database. The product page pulls all info from database (such as partnumber, material, color, etc...) and inputs it into the areas of the page that I designate it, all this using php. The previous page will show all 100 products and when user click's on one product it'll go to that product page. Just like all websites right...
I don't believe I need to make 100 individual html pages for each product right? Can I make just 1 main html page that is the templet for the 100 different products? Basically when user clicks the image tag of the product(1st example of code) it'll open the main html templet but somehow call to the database on open and load that specific info? Then other products will have the same process but for they're specific data from database. The 1st sample code is one product on the page that'll display all 100 products with the href containing the image that'll get clicked to show user actual product page retrieved dynamically without page reload, into a predestined section. I'm sure there is a name for what I'm looking to do but all the research I've done I haven't found what I'm looking for. Is there a better way then what I'm explaining? Also I hope this makes sense, Thank you for any input.

MANUFACTURER

Lowes

$104.99

   <button class="add-button">ADD</button>

MATERIAL

Aluminum 7075-t6 Forged

PLATFORM

Large

AMERICAN MADE

YES

Actual product page where php gets info from database example
<?php
$sql = "SELECT * FROM Parts;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);

if($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {

?>

Descrption

    <?php
     echo $row['Description'];
    ?>

<?php
}
}
?>

Editor Note: I edited the question to reflect what he want based on thread on my answer below.

A: Add an unique Id to your products in your mysql database, using the Auto Increment option (A_I checkbox in phpmyadmin). Then you can pass that id into a link to the product page ```href="individualProduct.php?id=" while rendering all the products on the all products page.
Then in individualProduct.php you can get that id and retrieve the data
$sql = SELECT * FROM Parts WHERE id =?";
$stmt = mysqli_prepare($sql);
$stmt->bind_param($_GET["id"]);
$stmt->execute();
$result = $stmt->get_result();
// Do stuff with $result as it is the individual product corresponding to that id

A: In this scenario you would need to pass in a unique identifier i.e product-id and create a query to fetch from the database product info by product-id
$product-id= $_GET['id'];
$strSQL = "SELECT * FROM AR15Parts WHERE id='$product-id'";
$rs = mysql_query($strSQL);
if (!$rs) {
    echo 'Could not run query: ' . mysql_error();
    exit;
}

$row = mysql_fetch_assoc($rs);

//display your data

if($row){
  echo $row['field'];
}

A: Optimally, you'll need 2 files:

*

*index/list of products

*detail information of the selected product

index files (maybe call it index.php)
Here, you need to select products and make it a list:
$stmt = $pdo->query("SELECT * FROM Parts");
while ($row = $stmt->fetch()) {
    echo '' . $row['name']."
\n";
}

Since you want the detail to be shown to the index/list page, let's add a container area:

Add a little javascript code to handle AJAX request:

detail page (let's call it detail.php)
In this screen, we fetch details for only one part, specified by HTTP GET id parameter. The one that's being supplied from index.php (the ?id= part).
$stmt = $pdo->query("SELECT * FROM Parts WHERE id = '" . $_GET['id'] . "'");

$part = $stmt->fetch();

echo "Name: " . $part['name'] . "
\n";
echo "Manufacturer: " . $part['manufacturer'] . "
\n";
echo "Price: " . $part['price'] . "
\n";

That's it, you should get it working with a few adjustments based on the table and template you have.
A little note is that I used PDO mechanism to do the query. This is because mysql_* function has been deprecated for so long that it is now removed from PHP 7.0. Also, the current PHP version has been PHP 8. So, be prepared, a lot of web hosting might gonna remove older PHP versions, moving forward.