text:
Q: Problema al Cambiar el Estado de un atributo de una base de datos en java Tengo un checkbox en la primera columna de mi jtable para seleccionar las filas de los registros que quiero cambiar de estado osea de true a false y viceversa  pero al momento de hacer click en un checkbox y después volver a quitar la bandera azul del check para quitar el seleccionado el método igual me lo toma entonces cree este método pero igual no me funciona
private void datalistadoMousePressed(java.awt.event.MouseEvent evt) {

         int fila =datalistado.getSelectedRow();
         TableModel model = datalistado.getModel();
            if (fila != y){
              y = fila;
              rep=0;
              rep++;
            }else{
              rep++;
            }
            if(rep%2==0){
                  listaRIF.removeLast();
                  listaEstado.removeLast();
            }else{
                  listaRIF.add((String)datalistado.getValueAt(fila,1));
                  listaEstado.add((Boolean)datalistado.getValueAt(fila,9));
           }
    }             `


text:
Q: Is it okay to have a password in a cookie or session? I'm making a PHP CMS and I was wondering if it was okay to have, a small password encrypted in a cookie so certain users can access the admin zone who know the password. It will be encrypted, and the encryption key will be the password itself... Is this safe or not? What are the dangers of this? Would it be better in a session?
Sorry, I don't know two much about this.

A: You store password in the cookie to log in to some service, right? So, if I obtain the encrypted password (just by looking in the cookies, its not that hard), the only thing i have to do to access this account is to create cookie with this password? I would say it's not the best idea ;)
Yes - creating session id stored in cookie, that is temporary and destroyed on logout / after predefined time - is better practise.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to check if an element name contains a specific string in XSLT and then rename those elements? I have an XML file that contains several elements named FileName1, FileName2, FileName3, and so on. I need to check the document for these element names and then rename them "FileName".
Here's the XML:
<?xml version="1.0" encoding="UTF-8"?>
<ProcessData>
  <Transformed>
    <ConnectionZone>Internal</ConnectionZone>
    <Directory>/Test/Inbox</Directory>
    <FTPProfileID>XYZ</FTPProfileID>
    <FileName1>Test1.txt</FileName1>
    <FileName2>Test2.txt</FileName2>
    <MoveDirectory>/Test/MovedFiles</MoveDirectory>
    <Operation>MV</Operation>
    <RenameExt>.csv</RenameExt>
  </Transformed>
</ProcessData>

Here's what I have in the XSLT so far:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes" />
<xsl:strip-space elements="*"/>

<xsl:template match="/">
    <table>
        <xsl:if test="//*[contains(name(), 'FileName']">
            <xsl:element name="FileName">
        </xsl:if>
    </table>
</xsl:template>
</xsl:stylesheet>

Nothing I try has proven successful so far. I can't seem to get any matches in my xsl:if statement.
Please let me know if you can think of a better way to perform this! I just need to remove the last character (digit) of each element name that contains "FileName".
Thanks!

A: You only need to write a template for those elements with
<xsl:template match="*[starts-with(local-name(), 'FileName')]">
  <FileName>
    <xsl:apply-templates/>
  </FileName>
</xsl:template>

and of course include the identity transformation template
<xsl:template match="@* | node()">
  <xsl:copy>
    <xsl:apply-templates select="@* | node()"/>
  </xsl:template>
</xsl:template>

as the main tool to keep processing the rest.

A: Just to expand on Martin's answer, you have a classic transformation pattern where you want to copy everything unchanged except for a few things that you want to change. The solution to such problems is always: write an identity template rule that matches everything and copies it unchanged (Martin's second rule), and then write specific template rules that match the things you want to change, which in this case is any element whose name starts with "FileName".
By default the transformation will simply work its way down the tree matching elements and firing off template rules as it goes. So long as each template rule invokes xsl:apply-templates to process the children of the current element, every element in the document will be matched and will be processed as directed in the best matching template rule for that element.


text:
Q: Google Analytics pageTracker function doesn't work when loaded via AJAX I posted on this a while ago, and have since done more research and advanced the problem, but I still don't have a solution...
I have a site (www.seatgeek.com) where a lot of links are loaded via AJAX.  When a user clicks on one of these links I want to count it as a goal, so I've tried attaching pageTracker._trackPageview() to the links' onClick attribute.  But GA isn't recording these clicks, and I have no idea why.  Here's the code for one of these links:
<a href="<?php echo $tickets[$x][3] ?>" target = "_blank" class="buyTicketsLink" onClick="pageTracker._trackPageview('/outgoing/event4.php');">BUY TICKETS

I've tried the above code in situations where the link is not loaded via AJAX and it works fine, so it's definitely a problem specific to AJAX.  Also, in my attempts to solve this problem I've also tried adding the onclick events programmatically, e.g.:

This doesn't work either.  But when I add a test alert box to the record_goal() function, it's clear that the function is getting run.  For example, if I change the function to this:
function record_goal() {
alert('Hello');
pageTracker._trackPageview('/event/outgoing');
}

Then the 'Hello' alert box displays when a link is clicked.  But the pageview to '/event/outgoing' still is not recorded.
I'm completely baffled by what might be causing this.  Any advice would be greatly appreciated.

A: Are you using a JavaScript library such as Prototype? document.getElementsByClassName is not a standard JavaScript DOM method.
Do you get any JavaScript errors? E.g. open up Firebug or the Firefox Error Console.
In Firebug, if you type pageTracker; in the console, does it tell you that pageTracker is definitely a function and not undefined?

A: Try adding "return false" after your trackPageView() call, so...
onClick="pageTracker._trackPageview('/outgoing/event4.php'); return false">

Our Analytics rep recommended this to me and it worked like a charm. "return false" usually says, "hey don't pay attention to the href" (I thought, anyway), but my implementation is working just fine.
Hope this helps!

A: If you're still using the asynchronous method of loading Google Analytics, the following snippet will accomplish the same task:

_gaq.push(['_trackPageview', '/anything']);

or (@Lauren code)

onClick="_gaq.push(['_trackPageview', '/outgoing/event4.php']); return false">


text:
Q: BeautifulSoup get_text() not returning all text I'm trying to scrape from a forum site that is littered with random silly html gems, and am unable to get everything I need from it. Most of the content scrapes just fine (when the html isn't too ugly) but for the problematic posts, I'm only getting the text from the first  tag. Can you help me figure out how to get all the text from the entire post? Thank you!
The HTML for the post looks something like this:
This is all contained in a  tag from a

Mike,

    "lorem ipsum, lorem ipsum"

    "lorem ipsum, lorem ipsum"

Most of the posts make use of the  tag, but every once in a while, this gem pops up instead. When it does, the only part that gets scraped by BS is the first div, and the string "Mike," is the only part that gets scraped, however I am also needing to scrape the "lorem ipsum" content.
I'm using beautifulsoup and requests as follows (this is inside a loop that is reading content and writing rows to file, so I'm trying to extract the relevant pieces of code here):
import requests
import re as regex
from bs4 import BeautifulSoup

url = "http://www.example.com/community/default.aspx?f=35&m=5555555&p=3"
r = requests.get(url)
soup = BeautifulSoup(r.text)
posts = soup.find_all('table', class_='PostBox')
if not posts:
    break
for k in posts:
    tds = k.find_all('td')
    userField = tds[0].get_text()
    temp1 = regex.split(userField)
    userName = temp1[0]
    joinDate, postCount = temp1[-1].split("Total Posts : ")
    post = str(tds[3].find('div', class_='PostMessageBody'))
    postMessage, postSig = tds[3].find('div', class_='PostMessageBody').get_text(), ""
    postMessage = postMessage.encode('ascii','ignore')
    postSig = postSig.encode('ascii','ignore')
    writer.writerow([site, userName, joinDate, postCount, postMessage, postSig])

Thanks for the help!


text:
Q: NET 5 DLL is present but does not load This question is about why an assembly cannot find a library that resides in the same folder. As far as I can tell, the bitness of the caller (x64) agrees with the unfindable NuGet package (AnyCPU).
Even when I recompile everything to AnyCPU, the error message remains:
Could not load file or assembly 'ChoETL.Core, Version=1.2.1.28, etc.' The system cannot find the file specified.

My published NET 5 exe (x64) file calls a published NET 5 library that calls the Nuget package ChoETL.Core in the error message (exe->lib->ChoETL.Core).
Here is the command line that I used to build the program exe and intermediate library .csproj files. I do not use Visual Studio and do not use the solution .sln file. All files build without errors or warnings.
msbuild -t:restore;publish /p:Platform=x64 /p:PlatformTarget=x64 /p:Configuration=Debug /p:TargetFramework=net5.0-windows7.0 /p:RuntimeIdentifier=win-x64  /p:PublishDir=c:\dev\holding\core.plt xxx.csproj

Here is the reference in the .csproj file of the library that references the ChoETL.Core package. Keep in mind that the msbuild command line properties override the AnyCPU values in the csproj file below.
   <PropertyGroup>
      <UseWindowsForms>true</UseWindowsForms>
      <Platforms>AnyCPU</Platforms>
      <PlatformTarget>AnyCPU</PlatformTarget>
      <TargetFramework>net5.0-windows7.0</TargetFramework>
   </PropertyGroup>

   <ItemGroup>
      <PackageReference Include="ChoETL" Version="1.2.1.28" />
   </ItemGroup>

I thought maybe the CorFlags values might be the issue, so I checked them. There were as follows (32bitreq/prefs were zero):
Program.exe: PE32+, flags 0x9, ILONLY 1, Signed 1
Library.dll: PE32+, flags 0x9, ILONLY 1, Signed 1
ChoETL.Core: PE32, flags 0x1, ILONLY 1, Signed 0

PE32+ means x64, and PE32 means AnyCPU (if the assembly is loaded into a 64 process, it runs as a 64-bit assembly). So, they should be compatible (and besides, I cannot compile the NuGet package).
I looked at this SO question, but it did not help.
Could not load file or assembly, system could not find the file specified
Does anyone have any idea why the library cannot find the ChoETL.Core.dll library when all three assemblies are side by side in the same folder?
I've spent days on the problem without progress or success. Thank you.

A: After yet another day of debugging, I have things working, but I don't know exactly why. I started with a simple console program, then exe + lib, then exe + lib (that called ChoETL), and finally made a test case with part of my real system. By the time I got to experiments with part of the real system, things were working okay. But fragile, I imagine.
Here are some theories that might help the next person.
One key issue (in the real system that was failing) was that the ChoETL package was not being published by the msbuild ... -t:clean;restore;publish operation. I think this was a major part of the problem. Yet, as I built up my test experiments using the same msbuild command lines, ChoETL was always being published correctly beside the executables and libraries that consumed the package.
At that time, I recognized that my experiments always completely deleted the bin and obj folders before starting a new build, whereas my real system build files did not take that drastic action (thinking that msbuild clean/restore would be sufficient for a clean build). But, not so. Msbuild is not that smart. I modified my real-system build files to completely delete all obj/bin folders in the 70-project build sequence at the start of the build, and ChoETL was correctly published beside the assemblies that consumed it.
And at last, the original problem was solved (but not really understood). The system could find ChoETL and load it. All I know is that completely deleting the obj and bin folders at the start enabled a successful build. I do not have a clear idea of what file(s) or data elements in the obj/bin folders might have prevented a successful publish operation. Maybe it was the project.assets.json file, or maybe it was one of the other json files.
I do know that msbuild does not easily regenerate the json files when csproj files and msbuild command line properties are changed. I have developed the habit of completely deleting the obj/bin folders in the months since starting to work with NET 5 because of such problems.
I thought msbuild would do dependency and timestamp analysis like make does, and regenerate the json files if they were "out of date" (whatever that might mean in this context; I don't know). But it does not. Thus I have started to develop the habit of completely deleting the obj/bin folders before a build. Obviously, this experience (a development delay of weeks) shows that I still have much further to go with developing that into a rigid habit. I hope this answer might help someone else.


text:
Q: Cakephp3 strato installation i want to write a little Cakephp3 application for a friend. Now i developed a part of the application locally and i want to install this on his server. He got a managed server at strato.de. I have no access to a shell or something like this to configure everything by myself.
What i did already to solve the problem:

*

*I googled around and found several things about some definitions in the htaccess-files: .htaccess for cakephp but it didn't solve my problem.

*I also read the installation-guide of cakephp.

The problem:
I can't access the application. If i try to open the url i only get a complete white page. So what do i have to do to access the application?
Thanks for help!

A: Put this lines in you root index.php file to show all errors
error_reporting(E_ALL);
ini_set("display_errors", "on");

(overhead this line)
require 'webroot' . DIRECTORY_SEPARATOR . 'index.php';

But I imagine a message like this...

Fatal error: You must enable the intl extension to use CakePHP in ... cakephp/config/bootstrap.php on line 38

I talked with Strato about it, but they didn't give me any solution for shared hostings...
If it's any info, I checked hostings strato and its support laravel5


text:
Q: Displaying Current Sub-Category name on Magento Product page I currently working on a magento store where i need to display the name and url of current subcategory of the product in the product page. Till now i have come up with the following code.
<?php $categories = $_product->getCategoryIds(); ?>

                <?php

                foreach($categories as $k => $_category_id):

                $_category = Mage::getModel('catalog/category')->load($_category_id)

                ?>

                <a href="<?php echo $_category->getUrl() ?>"><?php echo $_category->getName() ?>

                <?php endforeach; ?>

But the problem is this displays all the categories the product is assigned to. All i need is the only subcategory's name in which the product is assigned to. Thanks.

A: There are lot of ways. Quickest and easiest may to use thr Magentk Registry. So try code below:
$category = Mage::registry('current_category')

Or
$categoryIds = Mage::registry('current_product')->getCategoryIds();


text:
Q: delete item from custom listview i'm trying to delete custom listview's item on button click , delete function is working correctly, but prblem is when i click on button then item donot delete on the spot, when i reload
@Override
public View getView(final int paramInt, View paramView, ViewGroup paramViewGroup) {
    // TODO Auto-generated method stub

    LayoutInflater inflator = activity.getLayoutInflater();
    if (paramView == null) {
        view = new ViewHolder();
        paramView = inflator.inflate(R.layout.listview_row, null);

        view.header = (TextView) paramView.findViewById(R.id.tvHeader);
        view.from = (TextView) paramView.findViewById(R.id.tvfrom);
        view.to = (TextView) paramView.findViewById(R.id.tvto);
        view.value = (EditText) paramView.findViewById(R.id.etValue);
        view.imgViewFlag = (ImageView) paramView.findViewById(R.id.ibclose);
        view.result = (TextView) paramView.findViewById(R.id.tvResult);

        paramView.setTag(view);

    } else {
        view = (ViewHolder) paramView.getTag();
    }

    view.header.setText(Header.get(paramInt));
    view.from.setText(From.get(paramInt));
    view.to.setText(To.get(paramInt));
    view.value.setText(Value.get(paramInt));
    view.imgViewFlag.setImageResource(close.get(paramInt));
    view.value.setFocusableInTouchMode(false);
    view.value.setFocusable(false);
    view.imgViewFlag.setFocusableInTouchMode(false);
    view.imgViewFlag.setFocusable(false);
    view.imgViewFlag.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            int i=paramInt+1;
            File f1 = new File("/data/data/com.example.converter/shared_prefs/"+i+".xml");

            if(f1.exists()){
                f1.delete();
                 Header.remove(paramInt);
                 From.remove(paramInt);
                 close.remove(paramInt);
                 To.remove(paramInt);
                 Value.remove(paramInt);
            }
            else{
                for(int l = i;i<6;){
                    File f2 = new File("/data/data/com.example.converter/shared_prefs/"+l+".xml");
                    if(f2.exists()){
                        f2.delete();
                         Header.remove(paramInt);
                         From.remove(paramInt);
                         close.remove(paramInt);
                         To.remove(paramInt);
                         Value.remove(paramInt);
                        break;
                    }
                    else{
                        l++;
                    }
                }

            }

        }
    });

    return paramView;

please help me ,I'm very confused how i do it, i want to delete that item when i click on button and it does not delete when i click on button that does not delete on that time........

A: I am posting code for deleting item from listview which is working correctly in my code.
You forgot to call notifysetchanged thats it.
    @Override
public View getView(int position, View convertView, ViewGroup parent)
{
    View row = null;
    LayoutInflater inflater = getLayoutInflater();

    row = inflater.inflate(R.layout.one_result_details_row, parent, false);

    // inflate other items here :
    Button deleteButton = (Button) row.findViewById(R.id.Details_Button01);
     deleteButton.setTag(position);

    deleteButton.setOnClickListener(
        new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
                Integer index = (Integer) view.getTag();
                items.remove(index.intValue());
                notifyDataSetChanged();
            }
        }
    );

plz have a look at the following answers
1) Remove ListView items in Android
2) Remove selected item from ListView
Let me know if you are still facing any issue...
Thanks


text:
Q: Randomly get index of one of the maximum values in a PyTorch tensor I need to perform something similar to the built-in torch.argmax() function on a one-dimensional tensor, but instead of picking the index of the first of the maximum values, I want to be able to pick a random index of one of the maximum values. For example:
my_tensor = torch.tensor([0.1, 0.2, 0.2, 0.1, 0.1, 0.2, 0.1])
index_1 = random_max_val_index_fn(my_tensor)
index_2 = random_max_val_index_fn(my_tensor)

print(f"{index_1}, {index_2}")
> 5, 1

A: You can get the indexes of all the maximums first and then choose randomly from them:
def rand_argmax(tens):
    max_inds, = torch.where(tens == tens.max())
    return np.random.choice(max_inds)

sample runs:
>>> my_tensor = torch.tensor([0.1, 0.2, 0.2, 0.1, 0.1, 0.2, 0.1])
>>> rand_argmax(my_tensor)
2
>>> rand_argmax(my_tensor)
5
>>> rand_argmax(my_tensor)
2
>>> rand_argmax(my_tensor)
1

A: I think this should work:
import numpy as np
import torch

your_tensor = torch.tensor([0.1, 0.2, 0.2, 0.1, 0.1, 0.2, 0.1])
argmaxes = np.argwhere(your_tensor==torch.max(your_tensor)).flatten()
rand_argmax = np.random.choice(argmaxes)
print(rand_argmax)

make sure you adjust for np.random.choice to account for replacement


text:
Q: Generic classes taking Object parameters - Java
Possible Duplicate:
What are the reasons why Map.get(Object key) is not (fully) generic

I have a question about the Generic java collections, specifically Map. I notice that the get, contains and similar methods that require a parameter (usually the key) take an Object as the parameter, while I would have expected them to take something of class K, e.g. rather than get(Object key) I would expect get(K key). Can anyone explain the reason for this?

A: As it says here, it is because the object you pass to get does not have to be equal to the type of the key you are trying to retrieve.
The only condition is that their equals method return true.
EDIT: As Peter Lawrey pointed out, the hashcode should be the same.

A: The main problem is backward compatibility.
It was always possible to attempt to do the following, even if you "know" its not going to work
Map map = new HashMap();
map.put("hello", "world");

Object o = map.get(1); // null
boolean b = map.contain(2); // false
boolean b2 = map.remove(3); // false

As a result these methods still need to be able to take any type even though the generics implies that it will always return null or false.

Also its possible to construct a TreeMap where the keys don't need to be the same type, equals true, have the same hashCode or even compareTo() == 0
Map map = new TreeMap(new Comparator() {
    @Override
    public int compare(Object o1, Object o2) {
        return String.valueOf(o1).compareTo(o2.toString());
    }
});
map.put("1", "one");
map.put(2, "two");
map.put(3L, "three");
map.put('4', "four");

for(Object o: new Object[] { 1L, '2', 3, "4"}) {
    System.out.println(o.getClass().getSimpleName()+" "+o+" => "+map.get(o));
}

prints
Long 1 => one
Character 2 => two
Integer 3 => three
String 4 => four


text:
Q: Finder in Snow Leopard Does Not Show All Files in Directory I have 1189 mp3 files in a single directory (Finder says I have 1189 files and Terminal reports 1189 files). The terminal command: "ls -1" (el es space dash one) shows the long list of files; they have numeric/alpha names that always sorts properly.  The problem is in the Finder listing; When I scroll through this very large directory (regardless of display mode - list, column, or cover flow) there are gaps in the files displayed (remember they are sequential and finder SHOULD sort them the same as terminal)  Though my research it appears that the finder listing is limited to about 1024 entries. I don't know if this also applies to any previous OS X releases.  Is there a way to tell Finder to display more (all) files?

A: Finder does not sort files the same as the terminal.
The terminal (or more correctly, ls), sorts using simple ASCII ordering. The Finder uses the Unicode Collation Algorithm - see this Apple Support article
BTW, I managed to create a folder with > 100,000 files and Finder displayed all files.


text:
Q: How to NHibernate Map Multiple Classes to the Same Table Is it possible to map 2 classes to the same table?
class Foo {}
class Bar : Foo {}
class Zap : Bar {}

Foo and Bar are Fluent Nhibernate auto mapped in one session factory.
All 3 classes are mapped with Fluent mappings in a different session factory:
class FooMap :  Class<Foo> {}

class BarMap :  Subclass<Bar> {}

class ZapMap :  Subclass<Zap> {
    public ZapMap() {
          Table("Bar");
    }
}

I want Zap to get mapped to the Bar table and not create a new one. Is this possible?

A: If you change BarMap to:
class BarMap : Class<Bar> { }

and you have a "type" column on your Bar table (of type string for it to discriminate between Bar's and Zap's), then it should work
Take a look at http://fluentnhibernate.wikia.com/wiki/Fluent_mapping near the bottom of the page about Subclasses (you want  table-per-class-hierarchy)


text:
Q: Facebook session problem I am trying to connect to a facebook API, but found some issues.
The user has to log in by the javascript FB.login function. Then a cookie is stored and the PHP class will try to connect with this cookie.
When I test on my local machine, everything works fine. When I upload my code to the webserver and try out my code, the connection is done with javascript. It places the cookie with the right data on my computer. When I parse the cookie, the access_token is set, but there is no way of connecting to facebook. I receive the error:
Fatal error: Uncaught OAuthException: An active access token must be used to query information about the current user
I tried to delete my cookies, so a new session is created, but I still get the same error. THe api key and secret are correct, so that cannot be the problem. I can post the code here, but it is the basic API code.
Does somebody know how I can solve this problem?
Thanks in advance!

A: Wow... The javascript attaches some / and " chars at the beginning and the ending of the cookie. Looked over it. Was looking on this issue for about 3 hours :D
trim($cookie, '/"');
resolved my problem.


text:
Q: application id changed but firebase is still working I tried to upload my application in playStore then an error came, which wanted me to change the package name from example to any other name. After that, I changed the package name and application id using an answer on StackOverflow.
After that when I installed my application, my authentication, firestore and database is still working with the new application id. People say that the application id is the only thing by which firebase knows the app. Of course a new apk was installed when I installed the app in my phone after renaming id.
So why this is happening that firebase is working with an app with different application id from the id that has been saved in the project in firebase.

A: Mistake - It was ok after one hour. Firebase took its time. My application got an error of mismatch of id in the studio.
So my concepts of application id are correct and working properly. I decided to put this question here so that anyone having this problem can know this solution.


text:
Q: Spring Cloud: Microservice authentication works through Eureka Discovery, but not through Zuul I'm kind of new to Spring Cloud. I'm trying to build a few microservices by using Spring Cloud Eureka Discovery and Zuul Gateway.
I can access the microservices and perform actions through Zuul Gateway, but only when there is no security involved. If my microservice is secured, then I cannot do anything through Zuul as it doesn't return back a JWT token. If I do it through Eureka discovery client it works like a charm.
Maybe there is something wrong with my Zuul configuration? Or maybe I have chosen an invalid way to secure the services? Thanks in advance!
Here is my Zuul Gateway configuration:
Application.class
@SpringBootApplication
@EnableZuulProxy
@EnableDiscoveryClient
public class GatewayServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(GatewayServiceApplication.class, args);
    }

    @Bean
    public Filter shallowEtagHeaderFilter() {
        return new ShallowEtagHeaderFilter();
    }
}

application.properties
eureka.client.service-url.defaultZone=http://localhost:8010/eureka/
server.port=8011
zuul.prefix=/services

bootstrap.properties
spring.application.name=gateway-service
# specify where config server is up
spring.cloud.config.uri=http://localhost:8001

Here is my microservice JWT & security configuration:
WebSecurityConfig.class
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure (HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests()
                .antMatchers(HttpMethod.POST, "/login").permitAll()
                .anyRequest().authenticated()
                .and()
                // We filter the api/login requests
                .addFilterBefore(new JWTLoginFilter("/login", authenticationManager()), UsernamePasswordAuthenticationFilter.class)
                // And filter other requests to check the presence of JWT in header
                .addFilterBefore(new JWTAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    }

    @Override
    protected void configure (AuthenticationManagerBuilder auth) throws Exception {
        // Create a default account
        auth.inMemoryAuthentication()
                .withUser("**")
                .password("**")
                .roles("**");
    }
}

TokenAuthenticationService.class
public class TokenAuthenticationService {
    static final long EXPIRATIONTIME = 864_000_000; // 10 days
    static final String SECRET = "*";
    static final String TOKEN_PREFIX = "Bearer";
    static final String HEADER_STRING = "Authorization";

    static void addAuthentication (HttpServletResponse res, String username) {
        String JWT = Jwts.builder()
                .setSubject(username)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATIONTIME))
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();
        res.addHeader(HEADER_STRING, TOKEN_PREFIX + " " + JWT);
    }

    static Authentication getAuthentication (HttpServletRequest request) {
        String token = request.getHeader(HEADER_STRING);
        if (token != null) {
            // parse the token.
            String user = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
                    .getBody()
                    .getSubject();

            return user != null ?
                    new UsernamePasswordAuthenticationToken(user, null, Collections.emptyList()) :
                    null;
        }
        return null;
    }
}

JWTLoginFilter.class
public class JWTLoginFilter extends AbstractAuthenticationProcessingFilter {

    public JWTLoginFilter (String url, AuthenticationManager authManager) {
        super(new AntPathRequestMatcher(url));
        setAuthenticationManager(authManager);
    }

    @Override
    public Authentication attemptAuthentication (HttpServletRequest req, HttpServletResponse res)
            throws AuthenticationException, IOException, ServletException {

        AccountCredentials creds = new ObjectMapper().readValue(req.getInputStream(), AccountCredentials.class);
        return getAuthenticationManager().authenticate(
                new UsernamePasswordAuthenticationToken(
                        creds.getUsername(),
                        creds.getPassword(),
                        Collections.emptyList()
                )
        );

    }

    @Override
    protected void successfulAuthentication (HttpServletRequest req,
                                             HttpServletResponse res,
                                             FilterChain chain,
                                             Authentication auth)
            throws IOException, ServletException {
        TokenAuthenticationService.addAuthentication(res, auth.getName());
    }
}

JWTAuthenticationFilter.class
public class JWTAuthenticationFilter extends GenericFilterBean {
    @Override
    public void doFilter (ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        Authentication authentication = TokenAuthenticationService.getAuthentication((HttpServletRequest) servletRequest);

        SecurityContextHolder.getContext().setAuthentication(authentication);
        filterChain.doFilter(servletRequest, servletResponse);
    }
}

A: try to define the below.
zuul.sensitiveHeaders=Cookie,Set-Cookie

In zuul, Cookie, Set-Cookie and Authroization headers are default sensitive headers. If you want to Authroization header in your api server, you need to redefine it without Authroization header like above.
Also you can define it for each route.
Please refer to the doc : http://cloud.spring.io/spring-cloud-netflix/spring-cloud-netflix.html [Cookies and Sensitive Headers]


text:
Q: How can I get the 'size' attribute to work in Mobile-Chrome? My Question is related to this one, except that it pertains to Mobile Chome.

Consider the following jsFiddle.
<select size="2">
    <option value="0" selected="selected">Default</option>
    <option value="1">select 1</option>
    <option value="2">select 2</option>
    <option value="3">select 3</option>
</select>

*

*On Desktop Chrome, it correctly displays two options in the dropdown.

*But on Mobile Chrome, it shows only one.

My Question:

*

*How can I get the 'size' attribute to work in Mobile-Chrome?


text:
Q: Curl not working on wordpress     <?php
$userid = "USER_ID";
$accessToken = "EXAMPLE_TOKEN";
$url = "https://api.instagram.com/v1/users/{$userid}/media/recent/?access_token={$accessToken}";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$result = curl_exec($ch);
curl_close($ch);
$result = json_decode($result);

 foreach ($result->data as $post)
 {
  echo '
  images->standard_resolution->url.'" data-fancybox-group="gallery" title="'.$post->caption->text.'">images->thumbnail->url.'" alt="SOME TEXT HERE">
';
 }
     ?>

id like to use this working code so i can populate a div but its not working on wordpress.

A: Since you are calling a HTTPs URL , you need to enable this parameter..
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

By setting this paramater to FALSE prevents cURL from verifying the peer's certificate


text:
Q: RoR: undefined method error in "create" action I get an undefined method error here and I don't know why. It works until I try submit the new form.
Any ideas?
class TweetsController < ApplicationController
  before_action :set_tweet, only: [:show, :update, :destroy]
  before_action :authenticate_user!, only: [:new, :index, :show, :create]

  def new
    @tweet = current_user.tweets.build
  end

  def index
    @tweets = Tweet.all
  end

  def show
    @tweet = Tweet.find(params[:id])
  end

  def create
    @tweet = current_user.tweets.build(tweet_params)
    respond_to do |format|
      if @tweet.save
        format.html { render notice: 'Tweet was successfully created.' }
        format.json { render :show, status: :created, location: @tweet }
      else
        format.html { render :new }
        format.json { render json: @tweet.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @tweet = Tweet.find(params[:id])
    @tweet.destroy
    respond_to do |format|
      if @tweet.destroy
        format.html { render notice: 'Tweet was successfully removed.' }
        format.json { render :index, status: :destroyed, location: @tweet }
      end
    end
end

  private

  def set_tweet
      @tweet = Tweet.find(params[:id])
  end

  def tweet_params
    params.require(:tweet).permit(:user_id, :content)
  end

end

My form
<%= simple_form_for @tweet do |f| %>
    <%= f.label :content %>
    <%= f.text_field :content %>

  <%= f.submit %>
<% end %>

When I try to submit form I get
undefined method `tweet' for #<Tweet:0x00007f64b90ad988>

on line two of create action @tweet.save
Started POST "/tweets" for ::1 at 2020-03-19 12:33:19 +0000
Processing by TweetsController#create as HTML
  Parameters: {"authenticity_token"=>"qHs3m6KUuUb2nA3w+o4T7C7xTm+6f8iPHEv6ur4UvLs+fu+OAMgxCSVkGM0tBxjfzS/36HoTpEil9R+SQW/sfA==", "tweet"=>{"content"=>"cdzcdzc"}, "commit"=>"Create Tweet"}
  User Load (1.8ms)  SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?  [["id", 2], ["LIMIT", 1]]
Completed 500 Internal Server Error in 16ms (ActiveRecord: 1.8ms | Allocations: 5089)

NoMethodError (undefined method `tweet' for #<Tweet:0x00007f1d189b2490>):

app/controllers/tweets_controller.rb:23:in `block in create'
app/controllers/tweets_controller.rb:22:in `create'
Started POST "/__web_console/repl_sessions/29c1187effa0e72e597bf7e21a7d198b/trace" for ::1 at 2020-03-19 12:40:57 +0000
Started POST "/__web_console/repl_sessions/29c1187effa0e72e597bf7e21a7d198b/trace" for ::1 at 2020-03-19 12:40:59 +0000

Anyone know what i'm doing wrong? Everything else works until I try submit new form.
Added error from command line.

A: You accept tweet param:
params.require(:tweet).permit(:user_id, :content, :tweet)

yet you don't have (and apparently don't need) such column in DB. Remove it:
params.require(:tweet).permit(:user_id, :content)

and modify your form in order to prevent passing this param to the controller.


text:
Q: passing dynamic jQuery post to PHP Hi I need help with the following code. I have searched a number of posts and other sites but to no avail.
This is a stripped down version from a site I'm building which has admin pages with numerous divs that are editable using CKeditor, so serialize is not an option for me(I don't think). I can pass the array to PHP when I hard code the $.post indexes and use variables for the content.
This is ok for one page, but I have many. And so when I try to construct the array string as a variable and pass this as a second argument to $.post, it fails. Firebug shows json being passed, although the values are in red(the hard coded version is not being identified as json! Just Index Value). I believe this is probaly just a syntax issue but I've hit a wall. Can anybody show me the light.
The PHP handler tries various methods of reading the POST.
The dynamic HTML with the js :

<title>jQuery POST Test</title>

    <button onClick="getDivs();">Get Divs dynamically</button>
    <button onClick="grabText();">Grab Text to hard coded index</button>

This is Block 1 content

This is Block 2 content

This is Block 3 content

This is the PHP test handler:
<?php
$data = json_decode($_POST, true);
$decode = json_decode($_POST,true);
$decodeNstrip = json_decode(stripslashes($_POST),true);

echo "Post 0: ".$_POST[0]."\n\r";

echo "\n\rPost block1: ".$_POST['block1']."\n\r";

echo "\n\rPost loop\n\r";
foreach($_POST as $key => $value){
    echo $key.': ' .$value."\n\r";
}

echo "\n\rPost decode: ";
print_r($decode)."\n\r";

echo "\n\rPost decode and strip: ";
print_r($decodeNstrip)."\n\r";

echo "\n\rPost Array: ";
print_r($_POST)."\n\r";

?>

A: The data passing to .post only accepts String and Object
String as in query string, e.g. year=2000&month=11
or
Object in key-value/paired, e.g. {"year":2000,"month":11}

A: In grabText you pass an array/object but in getDivs you're trying to send text.  The text could be formatted as a query string, but I prefer this method.
function getDivs(){
var divArry = getElementsByClass('editable')
var postElmnts = '';
var msg = {}
    for(i=0; i<divArry.length; i++){
        pageName = divArry[i].id;
        pageContent = document.getElementById(pageName).innerHTML;
        msg[pageName] = pageContent
    };
    $.post("handle.php",msg, function(data){alert(data);});
}

Here's the jQuery way of doing it.  I still prefer the more traditional method (plus it's a bit faster).
function getDivs(){
    var msg = {}
    $('.editable').each(function(e){
            msg[$(this).attr('id')] = $(this).html();
    });

    $.post("handle.php",msg, function(data){alert(data);});
}


text:
Q: convex polygon and $P$ a point inside it Let $C$ be a convex polygon and $P$ a point inside it. Let $N$ be number of
vertices, such that an interval connecting $P$ to the vertex divides the
angle of $C$ into two acute angles. Denote $ n $ number of sides of $C$, such
that the foot of perpendicular from $P$ to that side is strictly inside
that side.
Proof that $N=n$.

A: Let p be the number of sides.  Notice that the condition of the foot perpendicular to a side $(v_0,v_1)$ being strictly within the side is equivalent to the condition that the angles $P,v0,v1$ and $P,v1,v0$ are both acute, and when the condition fails, exactly one of the two angles is non-acute (i.e. obtuse or right).  Consider the $2p$ angles consisting of all $P,v_0,v_1$ and $P,v_1,v_0$  where $v_0,v_1$ are adjacent vertices; notice that, among those, there's exactly one non-acute angle whenever a vertex did not contribute to N, and also there's exactly one non-acute angle whenever a side did not contribute to n.  Therefore p-N = (number of non-acute angles out of these $2p$) = p-n, so N = n.


text:
Q: com.sun.faces.renderkit.html_basic.MenuRenderer createCollection: Unable to create new Collection instance for type java.util.Arrays$ArrayList I'm trying to use JSF / SelectManyCheckBox tag with an enum :
Here is my xhtml code :
            <h:form id="searchForm">
                <h:panelGrid columns="2">
                    <h:outputText value="Searched queues" />
                    <h:panelGroup>
                        <h:selectManyCheckbox layout="pageDirection" value="#{jmsErrorController.errorSearchCriteria.searchedQueues}" converter="queueConverter">
                            <f:selectItems value="#{jmsErrorController.completeQueueList}" />
                        </h:selectManyCheckbox>
                    </h:panelGroup>
                </h:panelGrid>
                <h:commandButton action="#{jmsErrorController.search}"
                    value="Search !" />
            </h:form>

I've add a converter as stated in an other post.
It seems to work fine but I see this stack trace on the console :
28-Jun-2013 09:07:46 com.sun.faces.renderkit.html_basic.MenuRenderer createCollection
SEVERE: Unable to create new Collection instance for type java.util.Arrays$ArrayList
java.lang.InstantiationException: java.util.Arrays$ArrayList
at java.lang.Class.newInstance0(Class.java:340)
at java.lang.Class.newInstance(Class.java:308)
at com.sun.faces.renderkit.html_basic.MenuRenderer.createCollection(MenuRenderer.java:907)
at com.sun.faces.renderkit.html_basic.MenuRenderer.convertSelectManyValuesForModel(MenuRenderer.java:367)
at com.sun.faces.renderkit.html_basic.MenuRenderer.convertSelectManyValue(MenuRenderer.java:129)
at com.sun.faces.renderkit.html_basic.MenuRenderer.getConvertedValue(MenuRenderer.java:315)
at javax.faces.component.UIInput.getConvertedValue(UIInput.java:1030)
at javax.faces.component.UIInput.validate(UIInput.java:960)
at javax.faces.component.UIInput.executeValidate(UIInput.java:1233)
at javax.faces.component.UIInput.processValidators(UIInput.java:698)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1214)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1214)
at javax.faces.component.UIForm.processValidators(UIForm.java:253)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1214)
at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1172)
at com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:76)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227)
at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:300)
at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:26)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
at weblogic.servlet.internal.RequestEventsFilter.doFilter(RequestEventsFilter.java:27)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.doIt(WebAppServletContext.java:3684)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3650)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:121)
at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2268)
at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2174)
at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1446)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:201)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:173)

After this stacktrace, the application seems to work fine but I wonder why is there such a stacktrace..
Can someone help me?
Thanks.
Stéphane.

A: This will happen when the UISelectMany component's value being provided is created using Arrays#asList() method instead of new ArrayList().
If a model value is already prepopulated, JSF will try to use exactly the same type to put submitted values in and set the new model value. However, the java.util.Arrays$ArrayList type as returned by Arrays#asList() is internal to java.util.Arrays class and not individually instantiable as in new Arrays$ArrayList(). Hence this exception.
To fix this, make sure that the value is created using new ArrayList().
Alternatively, explicitly specify the collection type via collectionType attribute as instructed in this closely related answer: org.hibernate.LazyInitializationException at com.sun.faces.renderkit.html_basic.MenuRenderer.convertSelectManyValuesForModel.
<h:selectManyCheckbox ... collectionType="java.util.ArrayList">


text:
Q: MongoDB - AND request on array with GeoJSON element I've looked at other issues without finding a suitable answer for my problem, so I hope you may help me.
SITUATION
I am currently working on a localisation app with MongoDB. For the moment I test my queries in the MongoDB shell.
I have a collection of Point documents with locations. I use GeoJSON objects for the coordinates of my point.
Here is what a Point document looks like :
{
    _id: "Roma_DellArte",
    localisations: [
        { location_type_id: 1, location: { type: "Point", coordinates: [ 41.9097306,12.2558141 ] } }
    ]
}

My location_type_id refers to another collection, juste for you to know.
I already made a query which gets me all the points near a precise location :
db.point.createIndex({ 'localisations.location': "2dsphere" })

db.point.find({
    'localisations.location': {
        $near: {
            $geometry: { type: "Point",  coordinates: [ 48.8588377, 2.2770207 ] },
            $minDistance: 0,
            $maxDistance: 100000
        }
    }
})

Now I would like to query all the points which are near a precise location AND those with a specific location_type_id.
TRIES AND FAILS
I tried many queries in the MongoDB shell but none of them produced a satisfying result.
Query 1
I think it doesn't return anything because location: isn't an exact field.
db.point.createIndex({ location: "2dsphere" })

db.point.find({
    'localisations': {
        location_type_id: 1,
        location: {
            $near: {
                $geometry: { type: "Point", coordinates: [ 48.8588377, 2.2770207 ] },
                $minDistance: 0,
                $maxDistance: 100000
            }
        }
    }
})

Query 2
The main problem here is it gets me a point document if in the localisations field there is an object with a correct location_type_id and an object with the correct location. It is not necessarily the same object, which I want it to be.
see: https://docs.mongodb.com/manual/tutorial/query-array-of-documents/#combination-of-elements-satisfies-the-criteria - second paragraph at the end.
db.point.createIndex({ 'localisations.location': "2dsphere" })

db.point.find({
    'localisations.location_type_id': 1,
    'localisations.location': {
        $near: {
            $geometry: { type: "Point", coordinates: [ 48.8588377, 2.2770207 ] },
            $minDistance: 0,
            $maxDistance: 100000
        }
    }
})

Query 3
I wanted to try this method : https://docs.mongodb.com/manual/tutorial/query-arrays/#query-for-an-array-element-that-meets-multiple-criteria
db.point.createIndex({ location: "2dsphere" })

db.point.find({
    localisations: {
        $elemMatch: {
            location_type_id: 1,
            location: {
                $near: {
                    $geometry: { type: "Point", coordinates: [ 48.8588377, 2.2770207 ] },
                $minDistance: 0,
                $maxDistance: 100000
                }
            }
        }
    }
})

Unfortunately, I get this error:
Error: error: {
    "ok" : 0,
    "errmsg" : "geoNear must be top-level expr",
    "code" : 2,
    "codeName" : "BadValue"
}

Now you know everything, I hope you can help me.


text:
Q: How to validate open source R packages; i.e, eliminate malicious packages Open source R packages are available at sites such as https://cran.r-project.org. Anyone can develop any package that might be useful to use.
I am exploring to find out if there is any way to validate if a package is safe to use or can be considered malicious or questionable.
I am new to R programming. However, R has been available for a while now and I am curious to know how other programmers and companies have solved this question.


text:
Q: Problema com CORS em aplicação Angular 7 e WebAPI Galera, bom dia.
Estou criando minha primeira aplicação Angular 7 com .NET Core WebAPI.
Após toda estrutura do front montada, fui realizar a comunicação de um get numa api que criei e consegui usando uma extensão para o Chrome que habilita o CORS, de acordo com o método abaixo.
getAgenda() {
    return this.http.get(apiUrl)
      .subscribe(d=> console.log(d));
  }

** Essa minha variável apiUrl é o meu webapi rodando em localhost.
Com o método acima, consegui obter valores.

Porém, quando chamo um outro método referente a outro component, usando o POST, eu tenho erro. Observe a tela abaixo:
Método no service:
AddTipoPerfil(tipoperfil) {
    this.http.post(apiUrl, tipoperfil)
      .subscribe(res => console.log(res));
  }

Método do meu component:
addTipoPerfil(ret){
    const obj = {
      Nome: ret.value.Nome,
      id: 0
    }

    this.apiService.AddTipoPerfil(obj);
  }

** Onde ret é o meu formgroup.
Entidade no meu backend:
[Table("TipoPerfil")]
    public class TipoPerfil : Implementation.EntityBase
    {
        [Column("Nome")]
        public string Nome { get; set; }
    }

Recebo este erro:

Quem puder ajudar, agradeço <3 !


text:
Q: Purpose of RemoveAll() I am new to Linq. From my understanding LINQ should be used only to query but not for modification of a collection or db etc.
If that is the case why did Microsoft provide RemoveAll() extension?
As far as my understanding goes RemoveAll() modifies the collection.
Is it not against the purpose of Linq?
Can some please explain the reason for providing RemoveAll()?

A: RemoveAll() is part of the List<T> class from .Net 2.0.
It has nothing to do with LINQ; it predates LINQ by a couple of years.
List<T> has a number of methods that do the same thing as LINQ methods, including ConvertAll, Exists, Find, FindAll, FindLast, and TrueForAll.
It also has the ForEach method, which is not LINQ.


text:
Q: Is there a way to get outlook push notification, only when a specific field of calendar item is updated? I followed the Outlook push notification documentation to subscribe for calendar notifications. And I am able to receive push notification whenever calendar item is changed or deleted. Now I want to receive push notification only when specific properties(example: To, Start time and End time properties) of calendar item are updated or calendar item itself is deleted.
Is there any API available to implement above scenario?

A: This isn't supported, the hooks are scoped at the object level (event, user, etc). You cannot subscribe to an individual property.


text:
Q: Open a accordion FAQ content with outside link I have an issue with trying to open a specific block of content from our home page to the specific question the user would click.  I would like it to automatically open the question they click on our home page that opens up to the FAQ page.  I have tried using anchors and it just moves it down to the specific question but doesn't show the content.  Any help would be appreciated.

Section 1 FAQs

    <input id="so-tab-1" type="checkbox" name="tabs">
    What is the best trail camera that sends pictures to your phone?

The Browning Defender Pro Scout cameras are our number one-rated cellular trail camera at the moment. You can choose between the Browning Pro Scout AT&T Cellular Trail Camera, or the Browning Pro Scout Verizon Cellular Game Trail Camera. These cellular game trail cameras take excellent photos and get great battery life.

    <input id="so-tab-2" type="checkbox" name="tabs">
    What is the the best motion activated trail camera?

The Browning Patriot Trail Camera has our top-rated score at this time. This trail game camera takes excellent photos, videos, and gets great battery life. If you are looking for the best motion activated trail camera purchase it with Trailcampro today.

    <input id="so-tab-3" type="checkbox" name="tabs">
    Are wireless trail cameras worth it?

Wireless trail cameras give you the ability to receive photos or videos directly to your phone. Getting real time photos of deer and other wildlife to your phone is invaluable. You can also use wireless trail cameras for security applications.

    <input id="so-tab-4" type="checkbox" name="tabs">
    What is the best cellular trail camera for the money?

The best cellular trail camera for the money is the Browning Pro Scout Verizon or the Browning Pro Scour AT&T cellular trail game camera. These cellular cameras are $199.95 and take great photos, get great battery life, and are easy to use.

    <input id="so-tab-5" type="checkbox" name="tabs">
    What is the difference between a game camera and a trail camera?

Wildlife cameras are called by a few different names. Some users call them game cameras, trail cameras, scouting cameras, and wildlife cameras. There is really no difference between a game camera and a trail camera. There are many different models of both and they can be called both a game camera, or a trail camera. Read our trail camera and game camera reviews here at Trailcampro to find the best game or trail camera to fit your needs.

    <input id="so-tab-6" type="checkbox" name="tabs">
    How high off the ground should a trail camera be?

There are many different scenarios for setting up trail cameras. There is not one particular way that it has to be done. However, as a rule of thumb we recommend mounting trail cameras about waist high. This usually works for most settings like placing a game camera on a trail, or maybe watching a feeder.

    <input id="so-tab-7" type="checkbox" name="tabs">
    What is the best trail camera for home security?

There are many different trail cameras you can use for security. Some of them will have the ability to send photos to your phone using a cellular connection through Verizon or AT&T. On of our top picks for a cellular security camera is going to be the Ridgetec Lookout. If you are looking for a cellular trail camera for home security one of our top-picks is going to be the here. If you don't have a cellular signal where you are wanting to place the security trail camera. The Reconyx Hyperfire 2 Security may be a good option for you.

    <input id="so-tab-8" type="checkbox" name="tabs">
    How much does a cellular trail camera plan cost?

When choosing a cellular trail camera the cost of the plans can be important. Spypoint seems to offer the best monthly and yearly plans especially if you are wanting an unlimited plan. Most cameras are going to start around $10 a month and that is going to get you a set number of photos per month or a specific amount of data per month. To check out all the cellular cameras and their plans click here and choose which cellular game camera you want to look at.

    <input id="so-tab-9" type="checkbox" name="tabs">
    How do I view my trail camera pictures on my phone?

Almost everyone has a smart phone these days and you can use them to view your trail camera photos. Typically when you have a iPhone the best thing to purchase is going to be an iPhone SD card reader. You would want to purchase one made by Apple as we have seen issues with other brands. If you have an Android device you could use the Stealth Cam 4-IN-1 reader. It seems to work well with Android phones but has issues with iPhones.

A: If you are okay with using JavaScript for this, you can make use of <HTMLElement>.click().
If you have a query parameter passed whenever you click on the FAQ bit (such as ?faqclick=specificquestion), you can use .click(). If you need information on getting the query parameter from the client side, use this post: How to get parameters on client side passsed by HTTP GET request?
An example of .click() would be document.querySelector("#myUniqueQuestion").click()


text:
Q: Which server should I put my message queue on: my worker server or my application server? I have two EC2 servers.  One is the application server (serving HTTP/S requests) and one is a "worker" server processing jobs.
I am wanting to move to use Huey (a task queue) which uses Redis as a backend.
I don't want to spin up another server just to run Redis, but I'm not sure what the best practice is - should I run Redis on my application server or my worker server, and why?

A: As long as you have only two servers it doesn't really matter.
I'd usually put the queue on a separate set of servers or on the application servers if there are budget constraints. Since workers should be the most easy part to scale up and down it would be silly to take down the queue when reducing the number of workers.


text:
Q: Very large php class being loaded on every page of site. Need advice for refactoring I've inherited a project that is using one file DBOperations for all interactions with out database. It's a huge mess of static function calls for read/writes. It's about 24,000 lines and maybe 1000 functions.
This file is then loaded using require_once in most pages. Just by including the file it adds about 300ms of load time. I need to sort this out and I'm looking for advice on how to approach it.
We don't have the resources to re-write everything so I want to re-organise everything.
I currently plan on splitting my big DBOperations file out into many smaller ones. Each database table will have it's own DBOps file e.g. my 'users' table will have a corresponding UsersDBOps.php file that will extend a class that will have some generic CRUD functions. I'll move all functions for the users table in DBOperations into UserDBOps. To prevent breaking any code I'll replace the code in DBOperations with a call to the function in UserDBOps. Finally I'll introduce autoloading.
So in summary my current plan is:

*

*Split DBOperations into DBOps files for each database table.

*Move all functions for a table to it's DBOps file. Update DBOperations functions to point to the new DBOps functions (prevent breaking my existing code)

*Slowly refactor all calls to DBOperations to the new DBOps files. Eventually I'll be able to get rid of DBOperations altogether.

*Introduce autoloading.

Would you make any changes to my plan?


text:
Q: Twitter OAuth 1.0 authentication with signature in perl I'm getting this problem with my app in perl for oauth authentication:
401 Unauthorized Failed to validate oauth signature and token
Here is my code:
sub Twitter {

my $IN = new CGI;

  my $qs = build_query({
    oauth_callback => $callback_url,
    oauth_consumer_key => $consumer_key,
    oauth_nonce => time,
    oauth_signature_method => "HMAC-SHA1",
    oauth_timestamp => time,
    oauth_version => "1.0"
  });

# Create Signature

  my $signing_key = $IN->escape($consumer_secret)."&";

  my $base_signature = "POST&".$IN->escape($request_token_url)."&".$qs;

  use Digest::HMAC_SHA1;

  my $hmac = Digest::HMAC_SHA1->new($signing_key);
  $hmac->add($base_signature);

  $qs .= "&oauth_signature=".$IN->escape($hmac->b64digest);

# Fetch the page

  use LWP;
  my $ua = LWP::UserAgent->new;
  my $req = HTTP::Request->new(POST => $request_token_url);
  $req->content_type('application/x-www-form-urlencoded');
  $req->content($qs);

  my $res = $ua->request($req);

# Check the outcome of the response
  unless ($res->is_success) {
    print $IN->header.$res->status_line, "\n";
    print $res->content;
    exit;
  }
  print $IN->header.$res->content;
}
sub build_query {
  my $input = shift;
  use URI;
  my $uri = URI->new;
  $uri->query_form($input);
  return $uri->query;
}

I have obviously deleted my callback url and key information.

A: I figured it out.  I was encoding the signature wrong, I had to sort my query strings, and the call back URL is not needed in this instance.  Here is my working code:
sub Twitter {

  my $IN = new CGI;

  my $params = {
    oauth_consumer_key => $consumer_key,
    oauth_nonce => time,
    oauth_signature_method => "HMAC-SHA1",
    oauth_timestamp => time,
    oauth_version => "1.0"
  };
  my $qs = build_sorted_query($params);

  my $signing_key = $IN->escape($consumer_secret)."&";

  my $signature_base = "POST&".$IN->escape($request_token_url)."&".$IN->escape($qs);

  use Digest::HMAC_SHA1;
  use MIME::Base64;

  my $hmac = Digest::HMAC_SHA1->new($signing_key);
  $hmac->add($signature_base);

  $params->{oauth_signature} = $IN->escape(encode_base64($hmac->digest));

  $qs = build_sorted_query($params);

  use LWP;
  my $ua = LWP::UserAgent->new;
  my $req = HTTP::Request->new(POST => $request_token_url);
  $req->content_type('application/x-www-form-urlencoded');
  $req->content($qs);

  my $res = $ua->request($req);

# Check the outcome of the response
  unless ($res->is_success) {
    print $IN->header.$res->status_line, "\n";
    print $res->content;
    exit;
  }
  print $IN->header.$res->content;
  return;
}
sub build_sorted_query {
  my $input = shift;
  my $qs;
  foreach (sort keys %$input) {
      $qs .= $_."=".$input->{$_}."&";
  }
  return substr ($qs, 0, -1);
}

Thanks for looking!


text:
Q: Heatmap dc.js - provide the color range manually I'm not sure how to do this. I'm developing a heatmap dc.js. I want to set a range of colors manually. For example,

var chart = dc.heatMap('#heatmapID');

chart
    .width(690)  //850
    .height(400)
    .margins({top: 10, right: 0, bottom: 50, left: 70})
    .dimension(dimension)
    .group(group)
    .keyAccessor(function(d) { return d.key[0]; })
    .valueAccessor(function(d) { return d.key[1]; })
    .colorAccessor(function(d) {return d.value.rate;});
chart.data(grouphelper.dataAccessor(dimension));
chart.colors(['#30d074', '#f3cb2c', '#ffa85c', '#ff604e'])
    .calculateColorDomain();

The code above works but its automatically setting the colors base on the min and the max data (I'm assuming). For the chart.colors(....) i want to set a range manually but when I tried to apply a return function, for example,
 //Outside of the chart function
 var colors = ['#30d074', '#f3cb2c', '#ffa85c', '#ff604e'];
 function colorHeatMap() {
  return d3.scale.threshold().domain([0.02,0.06,0.23]).range(colors);   }

 //now apply colorHeatMap function into the .color function.
 chart.colors(colorHeatMap()) .calculateColorDomain();

I received a _colors.domain is not a function error. When I remove the .calculateColorDomain(), the heatmap display all black boxes. My goal is to set the range manually for the 4 colors.  Please help. This approach works well with dc row charts but I cannot figure out how to do that for the heatmap.

A: You cannot pass an array colors to the chart.colors() function; you must pass a d3 color scale object. That's why your heatmap shows all black boxes when you remove calculateColorDomain().
I've run into a similar issue, and my solution was to create a colorDomain array and use it to access the colors. If you know which values you want to assign to each color, it's simple: just put the values in an array in that order.
var colorsDomain = [0.02, 0.06, 0.23];
var colors = ['#30d074', '#f3cb2c', '#ffa85c', '#ff604e'];

chart.colors(d3.scaleQuantize().domain([0, colors.length - 1]).range(colors))
       .colorAccessor(d => colorsDomain.indexOf(d.value.rate))

It looks like you might be using d3 v3 or lower, in which case you would want to use d3.scale.quanitze() instead of d3.scaleQuantize() in the colors function. Hope this helps!


text:
Q: Finding the API using reflection from the server & using it like NancyFx From what I understand NancyFX uses Reflection to find classes that extend NancyModule, and then it can use those classes and make the http calls through them.
I've managed to get the class I'm looking for from the server class using reflection:
public static void Register(string ass1, string ass2)
{
    Assembly assembly1 = Assembly.Load(ass1);
    Assembly assembly2 = Assembly.Load(ass2);
    Assembly[] assemblies = { assembly1, assembly2 };

    foreach (var assembly in assemblies)
    {
        var types = assembly.GetExportedTypes();

        if (!(assembly.GetExportedTypes().Length > 10))
        {
            foreach (var type in types)
            {
                if (type.BaseType != null)
                {
                    var a = type.BaseType.Name;
                    if (type.BaseType.Name == "ApiController")
                    {
                        Console.WriteLine("YES");
                    }
                }
            }
        }
    }
}

I am still not sure what to return in this method, the Type, the name, I'll deal with that later, for now I want to understand what is next? What is the next step?


text:
Q: How to convert from String to IQ object in Smack I'm making IQ requests for saving some data. In order to be synced with ejabberd server, I save IQ data to SQLite database in case of failure. So I convert IQ object to String by iqObject.toXML().toString(). But I'm stuck When I read from database and convert into IQ class.
My question is: How to convert following String to IQ class?
<iq type='set' id='1001'>
<query xmlns='urn:xmpp:contacts' clean="false" domain='localhost'>
<add>
Mesut
Umit
Unknown
</add>
<delete>

</delete>
</query>
</iq>

Any helps would be very appreciated.
Best regards...
Update1

*

*My smack version is: 4.5.0-alpha1

The problem is not related with neighter ejabberd nor openfire. It is exactly related with Smack

Atention please, the problem is not sending or receiving IQ packets. I make these works successfully. My question is how to send the String above over Smack as IQ stanza packet, so that receive appropriate IQ response.

A: You approach is true to convert that IQ object into XML, then String.
First you need to go through with the official document of ejabberd server website: https://www.ejabberd.im/IQ%20handlers/index.html
Now, you have to understand how IQ object raw packet are receiving in this thread:  https://discourse.igniterealtime.org/t/how-can-i-create-send-and-receive-raw-iq-packet/71540


text:
Q: Advanced Segments returning unexpected results in Google Mobile App Analytics I'm having a problem with Advanced segments in Google Mobile App Analytics.
A condition has been setup to include all screens that match regex "/01-12-2013/" - but it's also showing me screens which does not contain this string. For example I'm getting a screen name containing "/11-11-2013/" which I would have expected to be filtered out.
The segment seems to return different results based on which tab I'm in in Google Mobile App Analytics. If that helps at all.
In "Audience Overview" I's returning 48.02% of all Screen Views. In "Behavior Overview" it's returning 71.51% of all screen views.
Here are some screenshots to illustrate the problem.

A: This is going to sound a bit ridiculous but, when creating advanced segments, after you've created them, I'd give them an hour or two before relying on the data they provide.  I still have yet to find a solid answer as to why this is, but across a wide range of sites over the past year or two I've found similar issues.  I've noticed that when I create an advanced segment to filter specific pages, invariably the initial results still show irrelevant pages I specifically filtered out.  The only thing I've been able to attribute this to is some sort of "lag", on Google's side, in updating the Analytics data/property/view/segment.  In almost every case, I've simply waited an hour or two after creating an advanced segment, and the data that was filtered usually displays correctly by then.
An interesting thing I've also seen was that a third party reporting platform I use, that has a Google Analytics integration, actually displayed the correct advanced segmented data BEFORE it showed up properly in Analytics.  Strange.


text:
Q: Angular pass checkbox value to custom pipe I'm looping through the values and displaying checkboxes which I'm showing, now in addition there is an search box filter on the top of list of checkboxes basically to filter out checkbox list.
HTML
 <input [(ngModel)]="searchText" class="lmn-input lmn-select-input-inner mt-input" placeholder="Search by key word" id="mngd-seg"/>

                  <input class="lmn-control-input" type="checkbox" [formControlName]="i">

                Data Concept
                {{ checkBoxValueList[i].scopeSets }}

Therefore I've created an custom pipe 'searchFilter' and using this pipe above in *ngFor
PIPE
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'searchFilter',
})
export class FilterPipe implements PipeTransform {
  transform(items: any, searchText: string): any {
    if (!items) return [];
    if (!searchText) return items;

    searchText = searchText.toLowerCase();
    return items.filter((it) => {
      return it.name.toLowerCase().includes(searchText);
    });
  }
}

In TS I'm initializing the checkboxes to false (with checkboxes, the Angular form control value is bound to the "checked" state (not the "value" attribute), so it should be either true or false) since it needs to be unchecked initially.
TS
      const formControls = this.checkBoxValueList.map(
        (control) => new FormControl(false)
      );
      const selectAllControl = new FormControl(false);

      this.scopeSetDetails = this.fb.group({
        search_text: this.fb.control(''),
        checkBoxValueList: new FormArray(formControls, this.minSelectedScopeSet(1)),
        selectAll: selectAllControl,
      });

Now issue is in filter pipe I'm getting items as an array of FormControl whose value property is 'false'. I need the checkbox text somehow and initially all checkboxes should be unchecked. how can I achieve this?


text:
Q: Simplify infinitely recursive function $f(a,b) = a+b\sin( a + b\sin( \cdots ( a + b\sin(a) ) \cdots ) )$ Is there a mathematical method to simplify this infinitely recursive function?
I have tried to approximate it, but for work with the ranges I am considering, precision becomes an important factor.
the recursion is as follows
$f_i = a + b \ \sin( f_{i-1} )$       with $f_0 = a$
For example, 3 stage recursion:
$a + b \ \sin( a + b \ \sin( a + b \ \sin( a ) ) )$
Variable ranges if it helps for an approximation
$a \in [-2\pi , 2\pi]$ and $b \in [0,1]$
P.s. I apologize for the poor formatting. This is my first time in StackExchange.

A: If your goal is to solve for $E$ Kepler's equation
$$E-e\sin(E)=M$$ there should not be any problem using high-order iterative methods. The only problem is to have a reasonable starting guess.
The solution being bounded $M < E <M+e$, expand as a series around $E=M$ and use series reversion to get
$$E_0=M+\frac{e \sin (M)}{1-e \cos (M)}-\frac{e^3 \sin ^3(M)}{2 (1-e \cos (M))^3 }+\cdots$$ Now, to find the zero of function
$$f(E)=E-e\sin(E)-M$$ use Newton, Halley or Householder method with this guess $E_0$.
In fact; if I properly remember, there are explicit solutions in terms of Lambert hyperfunction writing the equation in the exponential form
$$E \exp\Bigg[\log \left(1-e\frac{ \sin (E)}{E}\right)\Bigg]=M$$


text:
Q: "this" isn't working as I expected using string concatenation in Javascript

const user1 = {
    name: 'Sherlock Holmes',
    address:{
        street:'Baker street',
        number:"221B",
    },
    sayMyAddress:function (){
        console.log(`My address is ${this.address}`)
        console.log(this.address)
    }

}

user1.sayMyAddress()

The result:
My address is [object Object]
{ street: 'Baker street', number: '221B' }
Why the this keyword shows the address value in the second case and doesn't in the first? the scope in this case isn't in the object user?

A: The result of the conversion of the address to a string is '[object Object]' as we'd expect. For example, if you do
console.log({}.toString())

you'll get an output of:
[object Object]

A small change in the code will give the desired result:

const user1 = {
  name: 'Sherlock Holmes',
  address: {
    street: 'Baker street',
    number: "221B",
  },
  sayMyAddress: function() {
    console.log(`My address is ${this.address.number} ${this.address.street}`)
  }

}

user1.sayMyAddress()
.as-console-wrapper { max-height: 100% !important; }

You could also add a toString() function on the address object:

const user1 = {
  name: 'Sherlock Holmes',
  address: {
    street: 'Baker street',
    number: "221B",
    toString() { return `${this.number} ${this.street}` }
  },
  sayMyAddress: function() {
    console.log(`My address is ${this.address}`)
  }

}

user1.sayMyAddress()
.as-console-wrapper { max-height: 100% !important; }

A: this.address is an object, so even if the console.log is sympatic enough to output the full object with values if you pass it the object directly, if you use it in a string you'll get [object Object].
Just try it like this
console.log(`My address is ${this.address.street} ${this.address.number}`)

A: You are trying to log the object itself. So the output result is pretty much expected.
Change the log line from:
console.log(`My address is ${this.address}`)

to:
console.log(`My address is ${this.address.street} ${this.address.number}`)


text:
Q: Neo4j how to create/delete relationships from a set of nodes ids I have a User nodes and Intersets node. I want to be able given an array of interests to create/delete/change the relationship between the User and the Interests I also want in the same query to update some properties on the user node.
So far this is what i have menage to do:
MATCH (user:User {id: id})
OPTIONAL MATCH (user)-[oldRel:InterestedIn]->(:Interest)
DETACH DELETE oldRel
WITH user
UNWIND {interestsIds} as id
MATCH (interest:Interest {id: id})
MERGE (user)-[rel: InterestedIn]->(interest)
SET user.name = {user}.name, ..(more sets)
RETURN user, collect(interest) as interests

I think this one is working tho some time is looks like the interests are returned duplicated..
As well this query looks like a bit of an overkill. Any idea how to do that query with a better way?

A: Does this seem about right?
MATCH (user:User {id: id})
OPTIONAL MATCH (interest:Interest)
WHERE interest.id IN {interestsIds}
MERGE (user)-[:InterestedIn]->(interest)

WITH DISTINCT user
MATCH (user)-[rel:InterestedIn]->(interest:Interest)
WHERE NOT(interest.id IN {interestsIds})
DELETE rel

WITH DISTINCT user
MATCH (user)-[:InterestedIn]->(interest:Interest)
RETURN user, collect(interest)


text:
Q: Is it true that any two of the graphs of cubic functions are similar? It is evident that any two lines are congruent. In addition, any two parabolas are similar. I wonder whether every graph defined by a cubic function $y=ax^3+bx^2+cx+d$ can be rewritten as $Y=X^3$ via a similarity transformation.
It can be easily demonstrated that a graph defined by a cubic function can be rewritten as $y=x^3+Ax$ via a similarity transformation. Therefore, the question boils down to whether the graph of $y=x^3+Ax$ is similar to that of $y=x^3$ for every real number $A$.
It seems counterintuitive to think the graph of $y=x^3-3x$ is similar to that of $y=x^3$ since the former has two "prominent" points. Nonetheless, I cannot prove or disprove the proposition that any two of the graphs of cubic functions are similar. Any helpful advice is cordially appreciated.

A: Consider $y=x^3$ and $y=x^3-x$. For each one:
Let $T$ be the tangent line through the inflection point at the origin.
Let $L$ be the line through the origin rotated $45$ degrees counter clockwise from $T$.
Let $P$ be the point (to the right) where $L$ crosses the cubic again ($(1,1)$ and $(1,0)$ respectively).
Let $X$ be the angle between $L$ and the (tangent line to the) curve at point $P$.
If the curves were geometrically similar, $X$ would be the same angle for both curves, but it's $Arctan(3)-Arctan(1)$ for the first curve and $Arctan(2) - Arctan(0)$ for the second, and those two angles are not the same (check it numerically).
So they are not geometrically similar.

A: A short disclaimer/warning: I haven't studied these types of problems formally, so there may be a standard, simpler way to deal with this.  This is just the method that occurred to me.
Also, in the general proof, I abuse the symbol $y'$ a fair bit to mean the derivative on different curves, even in the same equation.  Hopefully the context gives enough clues to what I mean, but if anyone knows a standard notation for this application, I'd appreciate comments to that effect.

For the moment, let's consider $y=x^3$ and $y=x^3-3x$ as you have done.  Note that the range of the derivative of each function is of the form $[c_0,\infty)$ for different values of $c_0$ ($0$ and $-3$ respectively).  This difference is what we want to capture, but we need to define a quantity that both makes sense and is independent of similarity.
To do this, first we make the interval bounded by applying $\arctan$ so the range of $\arctan(y')$ is of the form $[c_1,\pi/2)$ for different values of $c_1=\arctan(c_0)$.  Then take [Lebesgue] measures, giving $$\lambda(\arctan(y'(\mathbb{R}))) = \frac{\pi}{2} - c_1.$$  This gives us the quantity we want.

More generally, we can consider any smooth curve $C \subset \mathbb{R}^2$ and let $[C]$ denote the equivalence class of all curves which are similar to $C$.  Then I claim that the function $$[C] \mapsto \lambda(\arctan(y'(C)))$$ is well-defined.  To see this, it's enough to see how it behaves under translation, uniform scaling, reflection, and rotation.

*

*Translation and uniform scaling: Note that $y'(C)$ is unchanged under both, so obviously the above value is unchanged.

*The particular reflection $R_y(x,y) = (x,-y)$ satisfies
$$\begin{align*}\lambda(\arctan(y'(R_yC))) &= \lambda(\arctan(-y'(C))) \\ &= \lambda(-\arctan(y'(C))) \\ &= \lambda(\arctan(y'(C)))\end{align*}$$
and any other reflection can be written as $T\rho R_y \rho^{-1}T^{-1}$ where $T$ is a translation and $\rho$ is a rotation

*For $0 \leq \theta < \pi$, any counterclockwise rotation $\rho_{\theta}$ by $\theta$ about some point satisfies, for $(x,y) \in C$, $$\arctan(y'(\rho_\theta(x,y))) = \begin{cases}\arctan(y'(x,y)) + \theta & \text{ if } \arctan(y'(x,y)) + \theta \leq \frac{\pi}{2} \\ \arctan(y'(x,y)) + \theta - \pi & \text{ otherwise}\end{cases}$$ Using this, we may show directly that $\lambda(\arctan(y'(\rho_\theta C))) = \lambda(\arctan(y'(C))).$

*For $\pi \leq \theta < 2\pi$, just note $\rho_\theta =
   (\rho_{\theta/2})^2$ and $0 \leq \theta/2 <\pi$.

Finally, applying the above to $C_A : y=x^3 + Ax,$ we find that $$\lambda(\arctan(y'(C_A))) = \frac{\pi}2 - \arctan(A)$$ so none of these curves are similar to one another.

A: There are four operations we can perform to convert two similar 2D graphs: translation, reflection, rotation, and uniform scaling
It is obvious that the first three of these cannot change the existence of local extreme points.
If we uniformly scale an equation by a factor of $\lambda$, we essentially replace $x$ with $\lambda x$ and $y$ with $\lambda y$.  If we take a cubic with no local extreme points, i.e. one of the form $y-A=C(x-B)^3$ and rescale it, we get $\lambda y-A= C (\lambda x-B)^3$.  If we redefine $A'=\frac{A}{\lambda}, B'=\frac{B}{\lambda}<, C'=C\lambda^2$, this is equivalent to $y-A'=C'(x-B')^3$, which is also a cubic with no local extreme points


text:
Q: What would i need to do display urls in order the way they are displayed on SO? I'm really unsure of how ordered results are displayed on a page like stack overflow questions. I know how to get the data from the DB but do i use a for each loop to display the data. And how can i paginate?
I know all about display logic on the databse end. What i mean is that i have the data ready but i do not know how to put in on the page to be displayed correctly.
Thanx

A: You need to use

*

*ORDER BY for sorting your results

*LIMIT for pagination

GET parameters in your requests should determine the values applied to those statements.

A: To order results, you should add a "ORDER BY" clause to your SQL statement. Specifically, for StackOverflow default view, it shows questions by date (with the most recent most). This implies that each question has the datetime which it is created tagged to it.
As for pagination, here's a general outline of the code

*

*Find total number of records

*Decide how many records per page

*Find out how many pages (record per page/page)

*Check what's the current page number

*Calculate the parameters to add to the LIMIT clause in the SQL statement. The start record should be current page * records per page.


text:
Q: asp gridview css border goes out of scope The below is the css and asp code for the gridview.
The border are spreading out then expected.
I tried setting Width=100% which worked, but I want the border to follow the size of grid instead spreading the grid view to occupy space unnecessarily.
This is an Asp Gridview with css for rounding corners
CSS:
    .rounded-corners {
        border: 1px solid #565656;
        -webkit-border-radius: 8px;
        -moz-border-radius: 8px;
        border-radius: 8px;
        overflow: hidden;
}

    .Grid td, .Grid th {
        border: 1px solid #565656;
        text-align: center;
        padding-top: 3.5px;
        padding-bottom: 3.5px;
        font-size: medium;
        font-family: 'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande',     'Lucida Sans', Arial, sans-serif;
    }

Source Code:

Description
Time
Time

abc
07:30
07:30

def
07:30
07:30

ghi
07:30
07:30

A: I think the grid is rendered like this:

column 1	column 2	column 3

value 1	value 2	value 3

value 1	value 2	value 3

so you could then style it:
.Grid {
    display:inline-block; /* trick to not take 100%. */
    /* alternatively: you could border .Grid>table */
    border-radius:8px;
}

.Grid>table>tbody>tr:first-row {
  /* special stuff for the first row here */
}


text:
Q: golang. reflect makefunc: how to decorate the origin func? I'm making a tools that decorte my origin function to test my program. It can inject some specific method to oringin function. Now I'm using reflect to do that:
I will define a Handle function to decorate the origin func. Like inject error to the origin, inject latency to the origin, etc...
When I call decorate to rewrite my origin func, I need a function to set excute "Handle" before the origin or after the origin. So that It can support inject error before call origin or after call origin.
I write my idea to the following code:
package main

import (
    "fmt"
    "reflect"
)

func main() {
    func1 := OriginFunc
    // todo: need a func can set excute new func after origin or befor origin

    Decorate(&func1)

    val, err := func1(1,2)
    ...
}

func OriginFunc(a, b int) (int,error) {
    return a + b, nil
}

func Decorate(a interface{}) {
    v := reflect.ValueOf(a).Elem()

    m := reflect.MakeFunc(v.Type(), func(args []reflect.Value) (results []reflect.Value) {

        // todo here
        // want to call Handle that support excute it before "OriginFunc" and after "OriginFunc". Just set before or after when I call "Decorate".
        // handle func can be edited by myself
        // example:
        // if I need excute after OriginFunc to inject error message: excute OriginFunc(1,2) and return 3, err
        // If I need excute before OriginFunc to inject error message: excute new func and just return 0, error
        return Handle()

    })
    v.Set(m)

}

func Handle() {
   // inject error or something...
}


text:
Q: Populating a HTML form drop down menu with a PHP array I am trying to populate an HTML form's drop down list with the contents of the current directory. I attempted to use PHP's scandir() function to output these files as an array and then feed them into the option's value tag within the HTML form.
I looked at various solutions available on SO and outside, but none seemed to work for me.
This is how my code looks like right now:
<form action="" >
        <input type="submit" class="Links" value="Select Input">
        <select >
            <?php
                $dir="./inputfiles/";
                $filenames = scandir($dir);
                foreach($filenames as $file){
                    echo '<option value="' . $filenames . '">' . $filenames . '</option>';
                    }
            ?>
        </select>
</form>

For now I'm getting absolutely no options in the drop down menu.
I am very new to PHP and would appreciate your feedback as to how to make this work.

Further Changes:
I tried the solutions given below, and none seemed to work. I changed the code to check whether the PHP script is able to output any variable or not in the html forms list.
<form action="" >
        <input type="submit" class="Links" value="Select Input">
        <select >
            <?php
                  $someval = "Video";
                  echo '<option value="value"> ' . $someval .' </option>';
            ?>
        </select>
</form>

It displays ' . $someval .'  instead of Video in the menu bar

A: You have to use $file in the echo out not $filenames. Like this:
echo '<option value="' . $file . '">' . $file . '</option>';
See PHP foreach for more info.

A: When iterating over the array, you need to use $file for concatenation, not $filenames:
echo '<option value="' . $file . '">' . $file . '</option>';

If inputfiles is present in the same directory, you should use the path: inputfiles/

A: A couple of concerns with your script.
First, you need to output the correct variable within the options:
echo '<option value="' . $file . '">' . $file . '</option>';

Second, you will likely need to add detection for . and .. in your loop, as you will likely not want to output them. You might also want to exclude directories as well.
Third, you should probably make it clear exactly what directory you are trying to scan.  Try using a full file path.  If you need it relative to the currently executing file's directory you can do something like:
$dir= __DIR__ . DIRECTORY_SEPARATOR . 'inputfiles'; // no need for trailing slash

Fourth, you might want to consider working with something like DirectoryIterator to give you some more convenient methods to do what you are looking to do (i.e. verifying it's an actual file before listing it).  So something like this:
$dir= __DIR__ . DIRECTORY_SEPARATOR . 'inputfiles';
$iterator = new DirectoryIterator($dir);
foreach ($iterator as $fileinfo) {
    if($fileinfo->isFile()) {
        echo '<option value="' . $fileinfo->getFilename() . '">' . $fileinfo->getFilename() . '</option>';
    }
}

In this trivial example, it you won't necessarily gain a lot (in terms of saving extra code) by using DirectoryIterator, but I certainly like to point out it's usage when I can, because if you needed to start doing things like showing file size, file permissions, file modification times, etc.  It is much easier to do it using the DirectoryIterator class (or RecursiveDirectoryIterator class if you need to recursive) than using traditional PHP's file system functions.


text:
Q: Php, is password reset token without database secure? I'm working on a password reset procedure for a website. The correct implementation suggests to store a random salted token hash and expiration date in the database.
But I came across a solution that doesn't store tokens in the database :
https://stackoverflow.com/a/3165086/980737
I was thinking about using the above, but replacing sha1() with password_hash() using PASSWORD_BCRYPT.
It looks fine to me but I'm not a security expert. Is the above no database option secure ? If not why ?

A: I would argue the approach linked is "not secure".
The code uses a hand-rolled approach in an attempt to verify the integrity of the URL/token data. The idea is that only the server (which should be the only entity that knows the user password and salt) can generate the given SHA1; on receiving the URL the SHA1 can be regenerated and, if it matches, then the solution proposes that the URL "must" have been server generated and can therefor be trusted.
However, the above assumption might be violated! If the bcrypted/hashed passwords are already known1 then the attacker can generate arbitrary reset URLs and gain access. This is because the attacker has all the required information to forge his own "verifiable" URL.
Applying encryption - after the token generation, to avoid exposing information as Blender pointed out, perhaps - or using an HMAC would increase the knowledge required as an extra "server secret" is used to generate such reset URLs. Encryption and MAC validation is employed in cases where confidentiality and integrity checks of client-stored-and-returned data are performed2.
However, if this additional "server secret" was learned by the attacker, then same issue as mentioned above would still hold and fake reset URLs could be generated at will. (But at this point I suspect that there be other security holes that are more pressing ..)

As far as bcrypt vs. SHA1: there is no point to switch due to the huge input space - the password should already be hashed at this point! - and limited timeout of reset requests. So switching to bcrypt here adds no extra security and using bcrypt does not mitigate the previous issue mentioned. (On the other hand, SHA1 is a poor choice for the actual hashed passwords!)

1 While it would be nice if account/password information is never leaked, the very point of password hashing to begin with is to prevent [mass] exploitation should such a leak occur. Because such leaks are thus taken as a "could happen" scenario (and they do happen), then additional security measures should already assume that such account/password information may not be used as a secure secret.
2 ASP.NET ViewState secuity/validation supports both encryption and integrity verification which shows, that with a solid implementation and security precautions, database/storage-less approaches can work in secure enterprise environments.

A: Random tokens should be truly random. By making the token a function of non-random data, you leak sensitive information.
If you want to implement this yourself, generate a secure random token:
$token = hex(openssl_random_pseudo_bytes(10, true));

And make it expire within 20 minutes or an hour.


text:
Q: I am try to create BottomNavigationView with fragment and I want to use fragment in main layout It can build and run successfully but in virtual device has stopped.
this is the code of my main layout in fragment:
public class BlankFragment14 extends Fragment {

@Override
public View onCreateView( LayoutInflater inflater, ViewGroup container,
                              Bundle savedInstanceState ) {

        return inflater.inflate(R.layout.fragment_blank_fragment14, container, false);

    }

        @Override
        public void onCreate( @Nullable Bundle savedInstanceState ) {
            super.onCreate(savedInstanceState);

            BottomNavigationView bottomNav = getView( ).findViewById(R.id.bottom_navigation);
            BottomNavigationView.OnNavigationItemSelectedListener navListener = null;
            bottomNav.setOnNavigationItemSelectedListener(navListener);

            getFragmentManager( ).beginTransaction( ).replace(R.id.fragment_container1, new ProfileFragment( )).commit( );

            navListener = new BottomNavigationView.OnNavigationItemSelectedListener( ) {
                @Override
                public boolean onNavigationItemSelected( @NonNull MenuItem menuItem ) {
                    Fragment selectedFragment = null;

                    switch (menuItem.getItemId( )) {
                        case R.id.nav_profile1:
                            selectedFragment = new ProfileFragment( );
                            break;
                        case R.id.nav_appointment1:
                            selectedFragment = new AppointmentFragment( );
                            break;
                        case R.id.nav_patientdata1:
                            selectedFragment = new PatientdataFragment( );
                            break;
                    }
                    getFragmentManager( ).beginTransaction( ).replace(R.id.fragment_container1, selectedFragment).commit( );

                    return true;
                }
            };

        }

    }

I don't know that It  can be possible to work ? or I must use activity to be a main layout.

A: Use Navigation component to implement BottomNavigationView. Your MainActivity must have NavHostFragment, that can display other fragment destinations. In MainActivity's onCreate
setup NavController as shown below:
 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar1);
    setSupportActionBar(myToolbar);
    BottomNavigationView navView = findViewById(R.id.nav_view);
    // Passing each menu ID as a set of Ids because each
    // menu should be considered as top level destinations.
    AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
            R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
            .build();
    NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
   //NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
    NavigationUI.setupWithNavController(navView, navController);
}