text:
Q: @ModelAttribute is not working with spring security I'm trying to redirect the entered username on the login page when login fails but in my controller the username of the user retrieved from "@ModelAttribute("user")" is null. When i'm not using spring security this works.
I'm assuming form actually posts to spring security first and then it is redirected to the controller so the information entered is lost between spring security.
How can i retrieve the user without sending it to link parameters?
PS: I tried to create a controller for "/loginFailed" and send it to there if login fails and use method = RequestMethod.POST on that controller.
LoginController
@RequestMapping(value = "/login", method = RequestMethod.GET)
    public String listPersons(@ModelAttribute("user") User u, @RequestParam(required = false) String authfailed, String logout,
            String denied, Model model) {
        model.addAttribute("user", u);
        String message = "";
        if (authfailed != null) {
            message = "Invalid username or password, try again !";
        } else if (logout != null) {
            message = "Logged Out successfully, login again to continue !";
        } else if (denied != null) {
            message = "Access denied for this user !";
        }
        model.addAttribute("error", message);
        return "login";
    }

login.jsp
<c:url var="trylogin" value="/j_spring_security_check" ></c:url>
<c:url var="register" value="/register" ></c:url>

    <form:form action="" modelAttribute="user" method="POST">

                 <form:label path="username"> <spring:message text="Username: "/> </form:label>
                 <form:input path="username" />

                 <form:label path="password"> <spring:message text="Password: "/> </form:label>
                 <form:password path="password" />

                 <input type="submit" value="<spring:message text="Login"/>"
                                    onclick="document.getElementById('user').setAttribute('action', '${trylogin}')"/>
                 <input type="submit" value="<spring:message text="Register"/>"
                                    onclick="document.getElementById('user').setAttribute('action', '${register}')"/>

    </form:form>
    <c:if test="${not empty error}">

${error}

    </c:if>

EDIT (Solution):
Thank you @James creating a failureHandler was the way to go but your solution did not quite work properly because it seems like you need "p:defaultFailureUrl" in the failureHandler bean even though i had "authentication-failure-url="/login?authfailed"" inside the form-login
<bean id="failureHandler" class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler"
    p:useForward="true"
    p:defaultFailureUrl="/login"/>

And after that i had to add another function for /login with method post because p:defaultFailureUrl="/login?authFailed" would just sent it as /login and the link at the browser stayed as "/j_spring_security_check" i couldn't understand why.
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String loginFail(@ModelAttribute("user") User u, @RequestParam(required = false) String authfailed, RedirectAttributes redirectAttrs) {
    redirectAttrs.addFlashAttribute("user", u);
    redirectAttrs.addFlashAttribute("error", "Invalid username or password, try again !");
    return "redirect:/login";
}

A: You should use an AuthenticationFailureHandler.  For your purposes it should be enough to declare a bean of the Spring SimpleUrlAuthenticationFailureHandler class and specify fowarding the request to the destination URL instead of the default redirect behavior in your configuration.  This way your login controller will have access to the original request including the username.
Documentation: http://docs.spring.io/autorepo/docs/spring-security/3.2.1.RELEASE/apidocs/org/springframework/security/web/authentication/SimpleUrlAuthenticationFailureHandler.html
Source: https://github.com/spring-projects/spring-security/blob/master/web/src/main/java/org/springframework/security/web/authentication/SimpleUrlAuthenticationFailureHandler.java
<bean id="failureHandler" class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler"
    p:useForward="true"
/>

And then in your form-login specification:
<security:form-login
    ...
    authentication-failure-handler-ref="failureHandler"
    ...
/>

A: It's a wrong way. Controller for login page use only for view this page. For check credential you need to create service, for example:
@Service("adminDetailsServiceImpl")
public class AdminDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private SepAdminDao adminDao;

    @Override
    public UserDetails loadUserByUsername(String login) {
        SepAdmin admin;

        if (StringUtils.isBlank(login))
            throw new UsernameNotFoundException("Admin not found!");
        admin = adminDao.findByEmail(login);
        return new org.springframework.security.core.userdetails.User(
                admin.getEmail(),
                admin.getPassword(),
                getGrantedAuthorities(admin.getRole().getPermissionNames()));
    }

    private static List<GrantedAuthority> getGrantedAuthorities(String[] roles) {
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (String role : roles)
            authorities.add(new SimpleGrantedAuthority(role));
        return authorities;
    }
}

Assign this service with spring (as example i view you my simple configuration for security):
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
             xmlns:beans="http://www.springframework.org/schema/beans"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security.xsd">
    <beans:bean id="roleHierarchy" class="org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl">
        <beans:property name="hierarchy">
            <beans:value>

                PERM_ROOT > PERM_CREATE_ADMINS
                PERM_CREATE_ADMINS > PERM_DELETE_ADMINS
                PERM_DELETE_ADMINS > PERM_EDIT_ADMINS
                PERM_EDIT_ADMINS > PERM_VIEW_ADMINS

                PERM_ROOT > PERM_CREATE_ROLES
                PERM_CREATE_ROLES > PERM_DELETE_ROLES
                PERM_DELETE_ROLES > PERM_EDIT_ROLES
                PERM_EDIT_ROLES > PERM_VIEW_ROLES
            </beans:value>
        </beans:property>
    </beans:bean>
    <beans:bean id="expressionHandler"
                class="org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler">
        <beans:property name="roleHierarchy" ref="roleHierarchy"/>
    </beans:bean>
    <beans:bean id="accessDecisionManager" class="org.springframework.security.access.vote.AffirmativeBased">
        <beans:property name="decisionVoters">
            <beans:list>
                <beans:bean class="org.springframework.security.web.access.expression.WebExpressionVoter">
                    <beans:property name="expressionHandler" ref="expressionHandler"/>
                </beans:bean>
            </beans:list>
        </beans:property>
    </beans:bean>
    <beans:bean id="roleVoter" class="org.springframework.security.access.vote.RoleHierarchyVoter">
        <beans:constructor-arg ref="roleHierarchy"/>
    </beans:bean>
    <beans:bean id="passwordEncoder"
                class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
        <beans:constructor-arg value="10"/>
    </beans:bean>
    <http pattern="/resources/js/vendor/language" security="none"/>
    <http pattern="/favicon.ico" security="none"/>
    <http auto-config="true" use-expressions="true" access-denied-page="/403"
          access-decision-manager-ref="accessDecisionManager">
        <intercept-url pattern="/login" access="permitAll"/>

        <intercept-url pattern="/dashboard" access="hasRole('PERM_ROOT')"/>
        <intercept-url pattern="/admin/create_admin" access="hasRole('PERM_CREATE_ADMINS')"/>
        <intercept-url pattern="/admin/users/*/edit_admin" access="hasRole('PERM_EDIT_ADMINS')"/>
        <intercept-url pattern="/admin/users/*/view_admin" access="hasRole('PERM_VIEW_ADMINS')"/>
        <intercept-url pattern="/admin/users/*/delete_admin" access="hasRole('PERM_DELETE_ADMINS')"/>

        <intercept-url pattern="/role/create_role" access="hasRole('PERM_CREATE_ROLES')"/>
        <intercept-url pattern="/role/*/edit_role" access="hasRole('PERM_EDIT_ROLES')"/>
        <intercept-url pattern="/role/*/view_role" access="hasRole('PERM_VIEW_ROLES')"/>
        <intercept-url pattern="/role/*/delete_role" access="hasRole('PERM_DELETE_ROLES')"/>

        <form-login username-parameter="email"
                    password-parameter="password"
                    login-page="/login" default-target-url="/" authentication-failure-url="/login?failed"/>
        <logout logout-url="/logout" logout-success-url="/login"/>
    </http>
    <authentication-manager alias="authManager">
        <authentication-provider user-service-ref="adminDetailsServiceImpl">
            <password-encoder ref="passwordEncoder"/>
        </authentication-provider>
    </authentication-manager>
</beans:beans>

And then when user submit login form, we redirect to /j_spring_security_check where used our service and if we have an login exception we can check it at login jsp page:

<c:if test="${not empty SPRING_SECURITY_LAST_EXCEPTION}">

        <spring:message code="Error.Msg.Login"/>

</c:if>

If it's success, we redirected to default target url, in my case - to root.
 <form-login username-parameter="email"
         password-parameter="password"
         login-page="/login" default-target-url="/" authentication-failure-url="/login?failed"/>

That's why the link at the browser stayed as "/j_spring_security_check".


text:
Q: mvc5 razor send parameter to controller I would like to send back a parameter to a controller based on user selection in the view.
This is what I have in the view:
@model IEnumerable<Users>

@{
    ViewBag.Title = "FieldSaver Users";
}

Users

@foreach(char c in ViewBag.Alphabet)
{
    @Html.ActionLink(c.ToString(), "Home/" + c, new object { }, new { @class = "alphabet", @letter = c })
}

                Username
                First name
                Last name

            @foreach (var user in Model)
            {

                    @user.UserName
                    @user.FirstName
                    @user.LastName

            }

And this is the controller:
   public ActionResult Home(string letter)
            {
                ViewBag.Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
                using (var db = new App.Models.DbContext())
                {
                    List<Users> users = (from p in db.Users
                        select p).ToList();
                    return View(users);
                }
                return View();
            }

So, when someone will click on a letter in the alphabet links, I want to send back the value to the controller, currently the postback is happening but the letter parameter is null.
What am I doing wrong?

A: What you're currently using as new object { } is where you provide the route data. You're adding it as an HTML attribute.
In your case, it should be like this:
@Html.ActionLink(c.ToString(),
    "Home",
    new { letter = c },
    new { @class = "alphabet" })

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to change the text 'More' on the standard UITabBarItem I have a TabBarController with several UITabBarItems, the last of those items is the standard 'More'  UITabBarItem provided by iOS. I want the title to be 'Meer' (More in my language), but when I try to set the title programmatically it doesn't work. I've tried this:
UITabBar *tabBar = self.tabBar;
UITabBarItem *chauffeurItem = [tabBar.items objectAtIndex:0];
UITabBarItem *voertuigItem = [tabBar.items objectAtIndex:1];
UITabBarItem *moreItem = [tabBar.items objectAtIndex:2];

chauffeurItem.title = @"Chauffeurs";
voertuigItem.title = @"Voertuigen";
moreItem.title = @"Meer";

This is in my TabBarController. The first two items do change.

A: The More button's text should be consistent with your app's language, and your app's language will be set to system's language, if it is supported by your app (this is handled by iOS). For example, if the user's system language is Dutch, and your app supports Dutch, More should automatically be displayed as Meer (again, this is handled by iOS since the button is a system button).
Anyway, you should't be bothering localizing the More text at this point. If you decide to support multiple languages, you should internationalize then localize your app as a whole. This Apple guide will help you through the process.

A: Go to your Info.plist file, and change the "Localization native development region" key to your language. The "more" button title changes automatically. This also auto-changes some other system button titles.


text:
Q: Is it possible to label the area between grid lines rather than the grid lines Below is my bar graph.
What I am trying to achieve is positioning the xLabels between the grid lines. Not aligned to the X grid line LEFT\CENTER\RIGHT.
e.g. the label Mon needs to be placed in the middle of the 1st bar (bar with the value 20)
Is this possible using achart??
Would really appreciate the help.
This is its code:
public class AChartEngingFragment extends Fragment {
    private GraphicalView chartView;

    private String[] weekDays = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat","Sun"};

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View v = inflater.inflate(R.layout.fragment_achart_engine, container, false);
        final Resources resources = getResources();
        LinearLayout linearLayout = (LinearLayout) v.findViewById(R.id.chart);

        chartView = createIntent();

        linearLayout.addView(chartView, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

        return v;
    }

    public GraphicalView createIntent() {
        String[] titles = new String[]{"Benchmark line"};
        //List<double []> values = new ArrayList<double []>(); //as y1
        //values.add(new double[] {20.0, 10.0, 30.0, 25.0, 40.0});
        double[] y1 = new double[]{20.0, 10.0, 30.0, 25.0, 40.0, 15.0, 19.2};
        List<double[]> x = new ArrayList<double[]>();
        for (int i = 0; i < titles.length; i++) {
            x.add(new double[]{0, 1, 2, 3, 4, 5, 6});
        }
        /*****************************************/
        List<double[]> lineValues = new ArrayList<double[]>(); //as values
        lineValues.add(new double[]{10, 10, 10, 10, 10, 10, 10, 10, 10});

        int[] colors = new int[]{Color.parseColor("#ea2e49")}; //pink

        XYMultipleSeriesRenderer mRenderer = buildBarRenderer(colors);
        mRenderer.setPointSize(0);
        int length = mRenderer.getSeriesRendererCount();
        for (int i = 0; i < length; i++) {
            XYSeriesRenderer seriesRenderer = (XYSeriesRenderer) mRenderer.getSeriesRendererAt(i);
            seriesRenderer.setDisplayChartValues(false);
            seriesRenderer.setLineWidth(2);
            seriesRenderer.setFillPoints(true);
        }
        mRenderer.setOrientation(XYMultipleSeriesRenderer.Orientation.HORIZONTAL);
        setChartSettings(mRenderer, "Average Customer Waiting Time", "Table Categories", "Minutes", 0, 7.5, 0, 30, Color.BLACK, Color.BLACK);
        mRenderer.setXLabels(0);
        mRenderer.setYLabels(10);
        mRenderer.setShowGrid(true);
        mRenderer.addXTextLabel(1, weekDays[0]);
        mRenderer.addXTextLabel(2, weekDays[1]);
        mRenderer.addXTextLabel(3, weekDays[2]);
        mRenderer.addXTextLabel(4, weekDays[3]);
        mRenderer.addXTextLabel(5, weekDays[4]);
        mRenderer.addXTextLabel(6, weekDays[5]);
        mRenderer.addXTextLabel(7, weekDays[6]);
        mRenderer.setXLabelsPadding(20f);

        mRenderer.setXLabelsAlign(Paint.Align.RIGHT);
        mRenderer.setYLabelsAlign(Paint.Align.RIGHT);

        XYSeries ySeries = new XYSeries("Average Customer Waiting Time");
        ySeries.add(0.5, y1[0]);
        ySeries.add(1.5, y1[1]);
        ySeries.add(2.5, y1[2]);
        ySeries.add(3.5, y1[3]);
        ySeries.add(4.5, y1[4]);
        ySeries.add(5.5, y1[5]);
        ySeries.add(6.5, y1[6]);
        mRenderer.setBarSpacing(0.5);

        XYSeriesRenderer yRenderer = new XYSeriesRenderer();
        yRenderer.setColor(Color.parseColor("#77c4d3")); //light blue

        XYMultipleSeriesDataset dataset = buildBarDataset(titles, x, lineValues);
        dataset.addSeries(0, ySeries);
        mRenderer.addSeriesRenderer(0, yRenderer);
        yRenderer.setDisplayChartValues(true);
        yRenderer.setChartValuesTextSize(20); //text size on each bar

        String[] types = new String[]{BarChart.TYPE, LineChart.TYPE};
        final GraphicalView grfv = ChartFactory.getCombinedXYChartView(getActivity(), dataset, mRenderer, types);
        return grfv;
    }

    protected XYMultipleSeriesRenderer buildBarRenderer(int[] colors) {
        XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer();
        PointStyle[] styles = new PointStyle[]{PointStyle.CIRCLE};
        mRenderer.setAxisTitleTextSize(17);
        mRenderer.setChartTitleTextSize(25);
        mRenderer.setLabelsTextSize(15);
        mRenderer.setLegendTextSize(15);
        mRenderer.setBarSpacing(-0.5);
        mRenderer.setPointSize(1f);
        mRenderer.setMarginsColor(Color.parseColor("#EEEDED"));
        mRenderer.setXLabelsColor(Color.BLACK);
        mRenderer.setYLabelsColor(0, Color.BLACK);
        mRenderer.setApplyBackgroundColor(true);

        mRenderer.setBackgroundColor(Color.parseColor("#FBFBFC"));
        int length = colors.length;
        for (int i = 0; i < length; i++) { //build benchmark line
            XYSeriesRenderer r = new XYSeriesRenderer(); //change
            r.setColor(colors[i]);
            r.setPointStyle(styles[i]);
            mRenderer.addSeriesRenderer(r);
        }
        return mRenderer;
    }

    protected void setChartSettings(XYMultipleSeriesRenderer mRenderer, String title, String xTitle, String yTitle, double xMin, double xMax, double yMin, double yMax, int axesColor, int labelsColor) {
        mRenderer.setChartTitle(title);
        mRenderer.setYLabelsAlign(Paint.Align.RIGHT);
        mRenderer.setXTitle(xTitle);
        mRenderer.setYTitle(yTitle);
        mRenderer.setXAxisMin(xMin);
        mRenderer.setXAxisMax(xMax);
        mRenderer.setYAxisMin(yMin);
        mRenderer.setYAxisMax(yMax);
        mRenderer.setMargins(new int[]{10, 65, 10, 15});
        mRenderer.setAxesColor(axesColor);
        mRenderer.setLabelsColor(labelsColor);
        mRenderer.setXLabelsAlign(Paint.Align.RIGHT);
        //mRenderer.setZoomEnabled(false);
        mRenderer.setPanEnabled(false, false);
        mRenderer.setZoomEnabled(false, false);
    }

    protected XYMultipleSeriesDataset buildBarDataset(String[] titles, List<double[]> xValues, List<double[]> yValues) {
        XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
        int length = titles.length;
        for (int i = 0; i < length; i++) {
            XYSeries series = new XYSeries(titles[i], 0);
            double[] xV = xValues.get(i);
            double[] yV = yValues.get(i);
            int seriesLength = xV.length;
            for (int k = 0; k < seriesLength; k++) {
                series.add(xV[k], yV[k]);
            }
            dataset.addSeries(series);
        }
        return dataset;
    }
}

A: You need to update values at
    ySeries.add(1, y1[0]);
    ySeries.add(2, y1[1]);
    ySeries.add(3, y1[2]);
    ySeries.add(4, y1[3]);
    ySeries.add(5, y1[4]);
    ySeries.add(6, y1[5]);
    ySeries.add(7, y1[6]);

Change
    mRenderer.setXLabelsAlign(Paint.Align.CENTER);

And you'll get next result


text:
Q: Is there a program that tracks the running times of certain processes? I think I spend way too much time on computer games and would like to know exactly how much time I spend on them, in hopes that this will help me refrain myself from playing...
Is there a program that can give me a detailed report on how long certain processes run per day?

A:
Is there a program that can give me a detailed report on how long certain processes run per day?

ProcrastiTracker gives a detailed report, including per-process graphs of how long and exact times it was running.

A: What about XFire or Raptr or Steam? Every 3 of them can track TONS of games, AND custom games too. Check them out which fits your need. They are made for this. XFire just got a huge money 'investment' from Intel, so it'll become much better too.


text:
Q: IOS builds fine but gives error when run on device Hello I have a problem when I compile and build a swift project.
it compiles fine but when it was supposed to run on my test Device the device screen blinks with a white startup screen and shortly after Xcode reports this:

process launch failed: Unspecified

and after that first run any run will report

process launch failed: Disabled

instead.
I've tried so many things.
including:
cleaning the derived files making a clean before build.
clean the MacBook and the phone after a reboot try to compile again.
I've tried to change signing identities and provisioning profile.
only resulted in a lot of mess with signing identities that I would be fearful for entering again.
I do not know what to do please help ?
EDIT
I have also tried to create a new project and just copy the content of the files in to it no changes to the project files except those Really needed that I know it worked with before. same results.
I had som signing problems and have changed the Signing Identity a few times as well as the provisioning profile. I'm not sure if this could cause problems but I don't get an error from the signing anymore.
EDIT2
I have now made a factory reset of the phone just to eliminate that as the cause. As expected the problem still persist.
I'm considering to make a backup of my Mac from a earlier point to make sure that it is not the cause either simply making sure that the project files or something in the compilation are the problem. ?
I'm striking my head against a wall here any help or suggestions are appreciated.

A: Uncheck the "Launch due to a background fetch event" box in the Edit Scheme menu
Here are steps for the same

*

*In Xcode, click the button that includes your app's name that is to the immediate right of the Stop button

*Click "Edit Scheme..." in the dropdown menu

*Make sure "Run" is selected on the left and "Options" is selected at the top

*The Background Fetch box will be in the middle of the view

A: Well I've finally solved my problem. I still do not know what caused it. But it must have been a setting in the project or a framework that was not removed entirely.
My solution was to create a new branch of a earlier working branch, and just write in all the files and changes that was between them without touching the project files or import any frameworks. I avoided copy pasting as last time I created an entire new project I copy pasted most of the files and I think something went wrong in that as the result was the same problem.
Hopefully this answer will be elaborated on by someone who knows more than me about this but currently this was the only way I could make it work.


text:
Q: How Do I Replace/Change The Heading Text Inside , Using Javascript? How do I change/replace the text: "Hello" using javascript to say "Goodbye" instead?

            Hello

A: document.getElementsByClassName("pagetitle")[0].innerHTML = "Goodbye";

Here is a working fiddle.

A: document.getElementById('title').getElementsByTagName('span')[0].innerHTML = 'Goodbye';

A: If you're happy to give legacy browsers the finger (preferable):
document.querySelector('#title .pagetitle').innerHTML = 'Goodbye';

Support:
Chrome  Firefox (Gecko)  Internet Explorer  Opera  Safari (WebKit)
1       3.5 (1.9.1)      8                  10     3.2 (525.3)
        bug 416317                                 WebKit bug 16587

See also: document.querySelectorAll

A: document.getElementsByClassName("pagetitle")[0].textContent = "Goodbye";

or
document.getElementsByClassName("pagetitle")[0].innerHTML = "Goodbye";

or
document.getElementById('title').getElementsByTagName('span')[0].textContent = 'Goodbye';

or
document.getElementById('title').getElementsByTagName('span')[0].innerHTML = 'Goodbye';

or
document.getElementById('title').getElementsByClassName("pagetitle")[0].textContent = "Goodbye";

or
document.getElementById('title').getElementsByClassName("pagetitle")[0].innerHTML = "Goodbye";

A: Here is JSBin
Change by using getElementsByTagName('span')
document.getElementsByTagName('span')[0].innerHTML = 'Goodbye';

A: Using innerHTML is not recommended according to XSS vulnerability, textContent is not supported by older version of browsers (ex. IE8). So will be better to create a TextNode
element = document.getElementByClassName("pagetitle");
txt = document.createTextNode("GoodBye");
element.appendChild(txt);


text:
Q: How do I reset the cached data of my singleton class? In my iOS application I am creating a singleton classs like follow, and the same class has some properties, so when I set some values to the properties all the data will be cached to memory, now how do I reset the singleton object ?
how do I do some thing like this [Model sharedInstance] = nil ?
Model.m

    + (instancetype)sharedInstance
    {
        static Model *objModel = nil;
        static dispatch_once_t predicate;
        dispatch_once(&predicate, ^{
            objModel = [[Model alloc]init];
        });
        return objModel;
    }

A: You cannot. its simply what a singleton is. An entity that is initialised once. If you want to "re-instantiate" then its not a singleton pattern anymore. Probably you are more inclined in using global variables?
However, you can clear the properties of a singleton something like this: [Object instance].myMutableProperty = nil;
quoting here: In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.


text:
Q: JavaScript Web API: Handle long TouchEvent while retaining default behavior in browser? In addition to MouseEvents I'd like to use a "long" TouchEvent of a single finger/digit/input for my application (change mode, e.g. to start drawing or select elements to manipulate), while retaining all default actions like clicking/tapping, scrolling/swiping and hold-for-context-menu or hold-to-select.
In other words:

*

*a short touch (tap) should be analogous to a normal mouse click (usually emulated by browser)

*(short) touch and move (swipe) should cause normal scrolling

*a "longer" touch should be analogous to a mouse click-and-hold

*consequent move events should not cause scrolling but are handled by the application

*a long touch without move should cause normal secondary function (select, context-menu)

*pinch and other multi-touch gestures should use default handlers (for now)

There is no "hold-to-select" or similar event to my knowledge, so I am attempting to implement this myself.
Detecting a "long" touch before drag is quite simple (setTimeout(), e.g. How to detect a long touch pressure with javascript for android and iphone?), however, the initial touchstart already seems to trigger default event handlers, causing

*

*no scrolling (intended)

*

*Chrome on Windows

*Chrome on Android

*scrolling

*

*Safari on iOS (iPhone)

*Firefox on Windows and Android

*secondary functions

*

*select (not intended if move occurs)

*

*Safari on iOS (iPhone)

*magnifier (not intended if move occurs)

*

*Safari on iOS (iPhone)

*context-menu (intended, when no move occurs)

*Chrome on Windows: as intended (very long touch, no move)

*Firefox on Windows: as intended (very long touch, no move)

*Chrome on Android: none

*Firefox on Android: none

on actual devices, despite preventDefault() and stopPropagation() calls from touchmove.

*

*is there a "better" way already (an event I don't know about)?

*is it possible to retroactively affect these envents/handlers (revert/undo events?)?

*is there a way to determine the default actions (select, context menu) and the respective timeout (browser / OS implementation dependant)?

or

*

*will I have to re-implement the very low-level handlers myself and then create and emit the necessary events (keeping different browser implementations in mind)?

Here's a preliminary snippet for testing (feel free to improve/extend):

let t = document.getElementById("t");
t.innerHTML += navigator.userAgent + '
';

// timer
var timerid;
var touchduration = 500;
var longtouch = false;
function lt(e){
  timerid = undefined;
  longtouch = true;
  e.preventDefault();
  e.stopPropagation();
  ls("LONG");
}
function ct(){if (timerid)window.clearTimeout(timer); timerid = undefined;}

function ls(s){
  t.innerHTML += i + ' ' + s + '
';
  t.scrollTop = t.scrollHeight;
}

// log event
let i = 0;
let o;
function le(e){
  if (e.type!=o){
    ls( e.type + (longtouch?' LONG':'') );
    o = e.type;
    }
  i++;
}

// mouse
t.addEventListener("mouseenter",  e=>{le(e);});
t.addEventListener("mousedown",   e=>{le(e);});
t.addEventListener("mouseup",     e=>{le(e);});
t.addEventListener("mousemove",   e=>{le(e);});
t.addEventListener("mouseout",    e=>{le(e);});
t.addEventListener("mouseleave",  e=>{le(e);});

t.addEventListener("click",     e=>{le(e);});
t.addEventListener("dblclick",   e=>{le(e);});
t.addEventListener("auxclick",   e=>{le(e);});

// wheel
t.addEventListener("wheel",       e=>{le(e);});

// touch
t.addEventListener("touchstart",  e=>{le(e);
  timerid = window.setTimeout(lt, 500, e);
  });
t.addEventListener("touchend",    e=>{le(e);
  ct();
  longtouch = false;
  });
t.addEventListener("touchmove",   e=>{le(e);
  ct();
  if (longtouch) {
    e.preventDefault();
    e.stopPropagation();
    //e.stopImmediatePropagation();
    }
  });
t.addEventListener("touchcancel", e=>{le(e);});

t.addEventListener("drag",        e=>{le(e);});

t.addEventListener("scroll",      e=>{le(e);});

t.addEventListener("contextmenu", e=>{le(e);});
t.addEventListener("select",      e=>{le(e);});


text:
Q: How to change the bibliographystyle .bst file (TexStudio) I would like to change the bibliographystyle manually in my .tex file.
I use TexStudio.

I have already found out that the changes have to be made in the .bst file and wanted to save it in the appropriate folder of MikTex, but I was denied that, even the assignment of another folder in MiKTex was not possible, then came always the message it is not TDS compatible.

Can you help me?


text:
Q: TypeORM migrations cannot detect changes Have trouble with TypeOrm migrations. I add column to User entity, run command for generate migration and it shows - No changes in database schema were found - cannot generate a migration. To create a new empty migration use "typeorm migration:create" command. But there isn't such column in db. When I delete whole User table in db and generate migration after that it works as expectable. So it generates migration correctly when I create new entity but when I add some column to exist entity or change some column it doesn't work.
ormconfig.json
{
  "type": "postgres",
  "host": "localhost",
  "port": 5432,
  "database": "figrea",
  "username": "postgres",
  "password": "postgres",
  "entities": [
    "D:\\work\\figrea\\figrea-api\\src\\entities\\**\\**.entity{.ts,.js}"
  ],
  "synchronize": false,
  "schema": "public",
  "logging": false,
  "subscribers": [],
  "migrationsTableName": "migrations",
  "connectTimeoutMS": 180000,
  "migrations": [
    "migration/development/*.ts"
  ],
  "cli": {
    "migrationsDir": "migration/development"
  }
}


text:
Q: How to limit textbox maxlength by byte in winrt? For TextBox, has a attribute "MaxLength",but it count all ascii and unicode as 1 character。
But in database, we set the field varchar(n) . It treats the ascii 1 and the unicode 2。
How can I limit the textbox input by the byte?
Because no notify before text changed, workaround like this.
public class TextBoxEx : TextBox
    {
    private bool bIsChanging;

    public TextBoxEx()
    {
        TextChanged += TextBoxEx_TextChanged;
    }

    public int MaxByteLength { private get; set; }

    private void TextBoxEx_TextChanged(object sender, TextChangedEventArgs e)
    {
        if (bIsChanging || MaxByteLength == 0 || Text.Length*2 <= MaxByteLength)
            return;
        bIsChanging = true;
        int start = SelectionStart;
        Text = TruncateString(Text, MaxByteLength);
        SetLimit();
        SelectionStart = start;
        bIsChanging = false;
    }

    private void SetLimit()
    {
        MaxLength = MaxByteLength - Encoding.UTF8.GetBytes(Text).Length + Text.Length;
    }

    private static string TruncateString(string text, int max)
    {
        if (max == 0) return text;
        byte[] bytes = Encoding.UTF8.GetBytes(text);
        if (bytes.Length <= max) return text;
        char[] c = text.ToCharArray();
        var sb = new StringBuilder();
        int count = 0;
        foreach (char t in c)
        {
            count += Encoding.UTF8.GetByteCount(t.ToString());
            if (max >= count)
            {
                sb.Append(t);
            }
            else
            {
                break;
            }
        }
        return sb.ToString();
    }
}

A: ascii code is hexadecimal as well, which means one character stands for 2 bytes of information
EX: "A" is 41(Hx) 0100 0001 which is 2 bytes and so on

A: I think you should refer this answer
It suggests to handle this your self (In this case, it limits 12 bytes length):
private void textBox1_TextChanged(object sender, EventArgs e)
{
    var textBytes = Encoding.UTF8.GetBytes(textBox1.Text);
    var textByteCount = Encoding.UTF8.GetByteCount(textBox1.Text);
    var textCharCount = Encoding.UTF8.GetCharCount(textBytes);

    if (textCharCount != textByteCount && textByteCount >= 12)
    {
        textBox1.Text = Encoding.UTF32.GetString(Encoding.UTF32.GetBytes(textBox1.Text), 0, 12);
    }
    else if (textBox1.Text.Length >= 6)
    {
        textBox1.Text = textBox1.Text.Substring(0, 6);
    }
}

A: I'd simply use MaxLength of half the n in varchar(n).


text:
Q: Typo3 extbase validating custom or manual objects I have created extbase extension, there for some reason I need to create object manually in create action.
My create action looks like this,
/**
* action create
*
* @return void
*/
public function createAction() {
$newObj = new \TYPO3\Myext\Domain\Model\Modelname();
$newObj->setMyval('value');
$this->myrepository->add($newObj);
}

Here the problem is its not validating for require field, captcha etc even if I mention @validate NotEmpty in model.
So how to make the validation of manually created object ?
It should throw error to form like out-of-the-box features.
Thank you.

A: Out of the box validation is only triggered on constructing model objects from GET/POST parameters according to your controller actions signature.

A: It should look something like this:
   /**
    * action create
    * @param \TYPO3\Myext\Domain\Model\Modelname $newObject
    * @return void
    */
    public function createAction(\TYPO3\Myext\Domain\Model\Modelname $newObject) {
        $this->myrepository->add($newObj);
    }

Take a look at the extension_builder, create a model and let the new/create action be generated for you. That will give you a good example on the create action as well as on the new action where the form is being rendered.


text:
Q: undefined method `authenticate_user! Api::PostsController in Devise / Rails 4 There is the following routes in my project:
  root 'home#index'

  namespace :api, defaults: { format: :json } do
    devise_for :users, controllers: { sessions: "api/sessions" }
    resources :posts
  end

User model:
class User < ActiveRecord::Base
    has_many :posts,        dependent: :destroy
    has_many :comments, dependent: :destroy

    validates :name, presence: true

    devise :database_authenticatable, :rememberable
end

Session controller:
class Api::SessionsController < Devise::SessionsController
  def create
    @user = User.find_for_database_authentication(email: params[:user][:email])
    if @user && @user.valid_password?(params[:user][:password])
        sign_in(@user)
    else
        warden.custom_failure!
      @errors = [ 'Invalid email or password' ]
        render 'api/shared/errors', status: :unauthorized
    end
    end
end

Application controller:
class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  #protect_from_forgery with: :exception
end

At last my Post controller:
class Api::PostsController < ApplicationController
    before_action :authenticate_user!, only: [ :create ]

    def create
      current_user.posts.create!(post_params)
    end

    private

        def post_params
            params.require(:post).permit(:title, :content)
        end
end

But when I try to create a new Post I get the following error: "undefined method `authenticate_user! Api::PostsController". If I delete it, I get the error about 'current_user' method. What's the trouble? How can I fix it? Thanks in advance!!!

A: I had a similar problem using devise.
The issue was that i named my db with a different name rather than user ( i named xuser).
In my case all i had to do was rename the vars in my controller.
Something like this
before_action :authenticate_xuser!, only: [ :create ]

def create
    current_xuser.posts.create!(post_params)
end

private

def post_params
       params.require(:post).permit(:title, :content)
end

Hope it helps!

A: You get that error because of nesting devise within the :api namespace in your routes.rb file. Therefore, you should authenticate users in the following way:
class Api::PostsController < ApplicationController
    before_action :authenticate_api_user!, only: [ :create ]
end


text:
Q: WPF XAML listbox selected item border color I have implemented some listbox which contains border and a grid in this border.
<Style x:Key="SelectedHiglightStyle"
       TargetType="{x:Type ListBoxItem}"
       BasedOn="{StaticResource MaterialDesignListBoxItem}">
    <Style.Resources>
        <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
                         Color="Transparent" />
        <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}"
                         Color="Transparent" />
    </Style.Resources>
    <Style.Triggers>
        <Trigger Property="IsSelected"
                 Value="True">
            <Setter Property="Background"
                    Value="#316308" />
            <Setter Property="Opacity"
                    Value="0.8" />
        </Trigger>
    </Style.Triggers>
</Style>

<ListBox IsSynchronizedWithCurrentItem="True"
         HorizontalAlignment="Stretch"
         VerticalAlignment="Stretch"
         Grid.Row="3"
         ScrollViewer.CanContentScroll="False"
         Style="{StaticResource MaterialDesignListBox}"
         ItemsSource="{Binding Devices}"
         SelectedItem="{Binding SelectedDevice, Mode=TwoWay,
         UpdateSourceTrigger=PropertyChanged}"
         ItemContainerStyle="{StaticResource SelectedHiglightStyle}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Border>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition />
                        <ColumnDefinition />
                    </Grid.ColumnDefinitions>

                    <Grid Grid.Column="0">
                        <Rectangle Width="35"
                                   Height="35"
                                   Margin="5"
                                   HorizontalAlignment="Left"
                                   OpacityMask="{DynamicResource DashboardDeviceLogo}">
                                <Rectangle.Fill>
                    ................
                        <Grid Grid.Column="1">
                            <StackPanel>
                                <TextBlock Text="{lex:Loc DeviceName}"
                                           Margin="0,4,0,2" />
                                <TextBlock x:Name="tbDeviceName"
                                           Text="{Binding Device.Name}"
                                           FontSize="10" />
                    ................

How I can change color of selected item border? Each item has his own view-model. Is there a easier way than broadcast message via Messanger (I'm using MVVM Light) , capture it in all DeviceViewModel's, compare id of device and then bind the color from view-model?

A: You could define a Style with a DataTrigger that binds to the IsSelected property of the parent ListBoxItem container:
<ListBox.ItemTemplate>
    <DataTemplate>
        <Border>
            <Border.Style>
                <Style TargetType="Border">
                    <Setter Property="BorderThickness" Value="2" />
                    <Setter Property="BorderBrush" Value="Black" />
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding IsSelected, RelativeSource={RelativeSource AncestorType=ListBoxItem}}"
                                                 Value="True">
                            <Setter Property="BorderBrush" Value="Red" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Border.Style>
            <Grid>
                ...
            </Grid>
        </Border>
    </DataTemplate>
</ListBox.ItemTemplate>

The Style is applied to the Border element in your ItemTemplate.

A: The easiest way to do this is here.
If you need just to change selection border you write this in listboxitem's style triggers section
 <Trigger Property="IsSelected" Value="True">
        <!--your code...-->
        <Setter Property="BorderBrush"
                Value="Red"/>
        <Setter Property="BorderThickness" Value="1"/>
 </Trigger>

And edit your datatemplate, binding your border to setters of borderbrush and borderthickness in style
 <ListBox.ItemTemplate>
    <DataTemplate>
        <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}">...

I've edited my answer cause first time I read this question, I thought you need different borderbrush for each type of data. But your case is much easier


text:
Q: Single statement consuming ~1000 ms to execute - Is it obvious? rerouted from here
The concat.=$concat .= $ref_wrapper->$er_field_mac_id->nid->value(); line is consuming more time to execute. Is it obvious or is there some thing else that might cause this behaviour.
What am I doing?
1.Iterate field collection item as it is a multi value field
2.Iterate though field inside field_collection item to get field whose machine name ends with _list_er (this is a entity reference field)
3.Once machine name found break and do not enter second loop again
4 Continue with outer loop and set the $concat variable
Why loop to get machine name?
I do not want it hardcoded like field_item_list_er, because same snippet should be applied to different fields that ends tith _list_er. Ex. field_tv_list_er, field_favteam_list_er.
timer_start('get_loop_time');
foreach ($wrapper->$list_mac_id->getIterator() as $delta => $ref_wrapper) {
    if (!isset($er_field_mac_id)) {
        foreach ($ref_wrapper->getIterator() as $in_fci) {
            $in_fci = $in_fci->info();
            if (is_array($in_fci)) {
                if (is_array($in_fci) && isset($in_fci['type']) && $in_fci['type'] == 'node' && preg_match(
                        "/_list_er\z/i",
                        $in_fci['name']
                    )
                ) {
                    $er_field_mac_id = $in_fci['name'];
                    break 1;
                }
            }
        }
    }
    //following statement consuming from ~600ms to ~750ms for each iteration(currently only 2)
    timer_start('get_single_time');
    $concat .= $ref_wrapper->$er_field_mac_id->nid->value();
    dpm(timer_read('get_single_time'));
}
//so then total is from ~1200ms to ~1400 ms  (includes for loop)
dpm(timer_read('get_loop_time'));

update: apologies :( for lack of info,now details are updated.One more thing there are > 10000 node are present to which entityreference field is referenced.
update2:while seaching for the solution I found the link about accessing field_collection_item and further splitted the statement like below
// Load that field collection item
$field_collection_item_value = $ref_wrapper->value();

// Wrap it with Entity API
$collection = entity_metadata_wrapper('field_collection_item', $ref_wrapper);

$val = $collection->{$er_field_mac_id}->value()->nid;

From above code it is found that statement $field_collection_item_value = $ref_wrapper->value(); is consuming more time around 600ms for each iteration, where $ref_wrapper is a field collection item. Is it a problem with the field collection item for taking so much  of time for loading single field value(inside field_collection_item two fields are there one is entityreference and another is textfield)


text:
Q: Express Server to bypass CORS I am trying to solve the problem of CORS on the client side. The server side is working fine without any problem but CORS is not enabled. I built a single Page application using React. I am using node Js and express to write a very simple proxy server that will forward all incoming request with path that begins with '/api' to 'https://api.example.com'. I have used request library to achieve this and everything is working fine as expected when tested with postman. But when i try from React frontend; i got this error: 500 Internal Server error. Please what am i doing wrong? I cant' just wrap my head around this. Your help will be appreciated... Here is the server.js:
const express  = require('express');
const path     = require('path');
const request  = require('request');

//create express app instance
const app = express();

//set the port as env variable
const PORT    = process.env.PORT || 3030;
const API_URL = 'https://api.example.com';

//This will pipe the whole request to the API endpoint
//and pipe the response back to the requester.
app.use('/api', function(req, res) {
  req.pipe(request(`${API_URL}${req.url}`)).pipe(res);
});

if (process.env.NODE_ENV === 'production') {
  // Serve any static files
  app.use(express.static(path.join(__dirname, '../build')));
  // Handle React routing, return all requests to React app
  app.get('*', function(req, res) {
    res.sendFile(path.join(__dirname, '../build', 'index.html'));
  });
}

//The server will now listen on the provided port
app.listen(PORT, () => console.log(`Listening on port ${PORT}...`));

A: Install cors library npm install cors --save and use it like so.
const cors = require('cors');
const app = express();

/**use dependencies*/

app.use(cors());


text:
Q: Change label text based on textfield I'm making a little demo app and I'm having trouble changing.
Heres the thing:
I have a UIButton that every click will add a character in a NSString in a UITextField.
And I put an IBAction(Mudar_Resposta)  on that UITextField(campo) in the part 'Value Changed'.
In that IBAction, I put that:
- (IBAction)MudarResposta:(id)sender {
   campo.text=@"lol";
}

But I can't get it to work. Any ideas?
Thanks.

A: Most likely you didn't connect that action to anything in the XIB file.

A: The proper way to get it to work is to connect an action method to the Touch Up Inside event for your button. Within that method, edit they text for your text field.
- (IBAction)mudarResponsta:(id)sender {    // Connect to Touch Up Inside of your button
    campo.text = [NSString stringWithFormat:%@ %@", campo.text, @"lol"];    // Add string ' lol' every time it's called
}

Connecting to Value Changed will never invoke the method because the value is never being changed—you're connecting the changing method to the change…if that makes any sense.

A:     - (IBAction)Button:(id)sender {
[self.contacts addObject:_txtField.text];
_txtField.text=@"";

}

Here contacts is an Array name which is a Mutable Array. txtField is UITextField.


text:
Q: How can i pause a function till a response comes back and state is set I am running a function that has an API call that brings back a response that I use to set the state and then triggers another function which uses the state that has just been updated. the problem the second function is running before response comes back and updated the state
I have tried .then I thought that should work
import React from "react";
import API from "../../utils/API"
class Content extends React.Component {
    state={
        postID:"",
        statusPost:""
    }

    submitPost = () => {
        API.savePost({
            content: this.state.statusPost,
            post_by: this.props.userInfo.firstname + this.props.userInfo.lastname
        })
        .then(console.log(this.submitPost))
        .then(res => {

            this.setState({ postID:res.data._id })

            console.log(this.state)
        })
            .then(this.addPostID())
            .catch(err => console.log(err));

    }

    addPostID = () => {

    API.postID({
        _id:  this.props.userInfo.user_ID,
        post:this.state.postID
      })

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

    }
}

A: The problem here is that setState is asynchronious by itself. It better used for rendering React component based on state changes but not to transfer data between functions calls. So it better to refactor you code this way
submitPost = () => {
    API.savePost({
        content: this.state.statusPost,
        post_by: this.props.userInfo.firstname + this.props.userInfo.lastname
    })
    .then(console.log(this.submitPost))
    .then(res => {

        this.setState({ postID:res.data._id })

        console.log(this.state)
        this.addPostID(res.data._id); // As state will not be updated on this point
    })
        .catch(err => console.log(err));
}

addPostID = (postID) => {

API.postID({
    _id:  this.props.userInfo.user_ID,
    post:postID // Use argument and not state here
  })

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

}

Alternative approach to this problem can be to use second argument of setState function which is callback that will be called after state update.
For example
this.setState({ postID:res.data._id }, () => this.addPostID()); // Now addPostId will be called after state updated


text:
Q: Display Post image on the Custom Page Template with Pagination I have this code for my page template.
This is what i have right now: http://www.ohright.com/emoticons/
How do I change it so that it can display all my post images at 20 images per-page and with a pagination below?
<?php
/*
Template Name: emoticons-page
*/
get_header(); ?>

<?php query_posts('cat=44'.get_the_title().'&post_status=publish,future');?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

<?php the_content(); ?>
<?php endwhile; else: endif; ?>

<?php get_footer(); ?>

A: <?php
/*
Template Name: emoticons-page
*/
get_header(); ?>

        <?php
        $paged = (get_query_var('page')) ? get_query_var('page') : 1;
        $posts_per_page = 20;
        query_posts('cat=44&post_status=publish&paged=' . $paged . '&posts_per_page=' . $posts_per_page);?>
        <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

<?php the_content(); ?>
        <?php endwhile;
        posts_nav_link();
        wp_reset_query();
        endif; ?>


text:
Q: Como pegar o id do banco de cada TD da table html Boa Noite
Tenho um botão que guarda o id do banco de cada  em uma linha, eu envio esse id para abrir um arquivo em outra aba, e agora acrescentei uma segunda função neste botão para pegar o id na coluna subject que guarda o id e fazer um update via ajax.
Está funcionando corretamente, só que o problema é que o ajax só faz o update com o 1 registro da linha 1 da tabela, e com as outras linhas ele simplesmente não atualiza.
Exemplo: se clico no registro numero 20 ele atualiza o registro com o id 1 da tabela. Preciso saber onde está meu erro, e porque ele não pega o id de cada linha que eu clico para fazer a atualização? já quebrei a cabeça e nada. Alguém poderia me ajudar?
Meu codigo está assim:

          <input type='hidden' name="subject" id="subject" value="<?php echo $dados['id']?>"><?php echo $dados['id']?>

          <a href="visualizar.php?protocolo=<?php echo $dados['id'] ?>" type="submit" onclick="inserir_registo()" class="btn btn-primary" target="_blank">Visualizar

E aqui minha pagina update.php que atualiza os registros:
<?php

 include("conexao.php");
    $id = $_REQUEST['subject'];

    try
    {
        //insere no BD
        $sql = "UPDATE registros SET status=1 WHERE id = '$id'";
        $result = mysqli_query($con, $sql);

        //retorna 1 para no sucesso do ajax saber que foi com inserido sucesso
        echo "1";
    }
    catch (Exception $ex)
    {
        //retorna 0 para no sucesso do ajax saber que foi um erro
        echo "0";
    }
?>

Me desculpem se não deu pra explicar direito, eu sou iniciante, to começando a estudar essas linguagens agora. Quem puder me ajudar agradeço.

A: O problema é que você está repetindo a id id="subject" e passando no data do AJAX. Assim irá sempre pegar o primeiro id="subject" da página. Um id deve ser único, mas você não precisa fazer isso, criar uma coluna com input escondido para pegar um valor via id.
Basta você passar o id vindo do PHP direto no onclick como parâmetro e receber esse valor na função.
Altere o onclick para:
onclick="inserir_registo('<?php echo $dados['id']?>')"

E a abertura da função para:
function inserir_registo(id){

E o valor do 'subject' para:
'subject': id


text:
Q: Algebra and exponents I am solving a 7th grade math text book, and I came across this one:
If $a^x = b^y = c^z$, and $a^3 = b^2 c$, then what is $\displaystyle \frac{3}{x} - \frac{2}{y}$?
I tried:
--> $\displaystyle c = \frac{a^3}{b^2} \Rightarrow a = \sqrt[3]{b^2c} \Rightarrow b = \sqrt{\frac{a^3}{c}}$
But I couldn't arrive at a conclusion, and I also thought there should be a simpler way of solving this.
Please help.

A: Let $$a^x=b^y=c^z=d^{xyz}$$
$$\implies a=d^{yz}\text{ etc.} $$
So, $$(d^{yz})^3=(d^{zx})^2\cdot d^{xy}\implies d^{3yz}=d^{2zx+xy}\implies 3yz=2zx+xy$$
Divide either sides by $xyz$

A: Since $a^3=b^2c$, we have
$$(a^3)^{xyz}=(b^2c)^{xyz}\iff a^{3xyz}=b^{2xyz}c^{xyz}\iff a^{3xyz}=(b^y)^{2xz}(c^z)^{xy}$$$$\iff a^{3xyz}=(a^x)^{2xz}+(a^x)^{xy}\iff a^{3xyz}=a^{2x^2z+x^2y}.$$
Hence, we have
$$3xyz=2x^2z+x^2y.$$
Finally, dividing the both sides by $x^2yz$ will give you
$$\frac 3x=\frac 2y+\frac 1z\iff \frac 3x-\frac 2y=\frac 1z.$$


text:
Q: Contact Form 7, Calculate Quote show price on submit I am using contact form 7 on a website and i want a calculate quote function where the user enters how many meters wide and long the driveway is and the type of finish the concrete is. After they enter the details in the form, they hit calculate quote and the price shows up.
At the moment, as soon as the sizing changes (wide/long) the price shows up.
How do i make it on click to show the price. I've been racking my brains. (relatively new to jquery)
website page is http://x.aiadstaging.com.au/projects/fdmconcreting.com.au/calculate-quote/
contact form 7 form code and jquery is:

// wpcf7_caculate_quote.js
function caculate_quote($form, ev) {
 var $ = jQuery, $quoteTotal = $form.find('.quote-total');
 var $drivewayMeters = $form.find('[name="driveway-meters"]');
 var $footpathMeters = $form.find('[name="footpath-meters"]');

 var $finish = $form.find('[name="finish"]');
 var $totalQuote = $form.find('[name="total-quote"]');
 var total = 0;
 total = parseInt( $drivewayMeters.val() );
 total += parseInt( $footpathMeters.val() ) * parseInt($finish.val().replace(/^\$(\d+) /, '$1'))

 $totalQuote.val( total );
 $quoteTotal.html( '$' + $totalQuote.val() );
 if( total > 0 ) {
  $form.find('.head-title').removeClass('hide');
  $form.find('.your-info').removeClass('hide');

 } else {
  $form.find('.head-title').addClass('hide');
  $form.find('.your-info').addClass('hide');
 }
 return;
}
function hasEmptyValues($elements) {
 var res = false, $ = jQuery;
 $elements.each(function() {
  if( $.trim(this.value) == '') {
   res = true;
   return false;
  }
 });
 return res;
}
jQuery(function($){
 var forms = document.querySelectorAll('form.wpcf7-form');
 for( var i=0; i<forms.length; i++) {
  (function($form) {
   if( $form.find('#contact-me, #email-quote, #caculate-quote').length == 3 ) {
    // caculate_quote.call($form[0], $form);
    var $line1 = $form.find('[name="email-phone"], [name="your-name"], [name="post-code"]');
    var $line2 = $form.find('[name="your-email"], [name="your-name1"], [name="post-code1"]');
    $line1.bind('change.submit', function(ev) {
     if( hasEmptyValues($line1) ) {
      $form.find('.btn-contact-me').attr('disabled', 'disabled');
     } else {
      $form.find('.btn-contact-me').removeAttr('disabled');
     }
    });
    $line1.change();

    $line2.bind('change.submit', function(ev) {
     if( hasEmptyValues($line2) ) {
      $form.find('.btn-email-quote').attr('disabled', 'disabled');
     } else {
      $form.find('.btn-email-quote').removeAttr('disabled');
     }
    });
    $line2.change();

    var j=0, $elements = $form.find('select.change-quote, input.change-quote');
    for(j=0; j < $elements.length; j++) {
     if( $elements[j].type == 'submit' ) {
      continue;
     }
     if( $elements[j].type == 'checkbox' || $elements[j].type == 'radio' ) {
      $($elements[j]).bind('click.caculate', function(ev) {
       return caculate_quote.call(this, $form, ev);
      });
      continue;
     }
     $($elements[j]).bind('change.caculate', function(ev) {
      return caculate_quote.call(this, $form, ev);
     });
    }

    $form.unbind('submit.caculate').bind('submit.caculate', function(ev) {
     // ev.preventDefault();
     // return false;
     return caculate_quote.call(this, $form, ev);
    });
    var data = $._data( forms[i] ), firstClick = false;
    if( data && ('events' in data) && ('submit' in data.events) && (data.events.submit.length > 1) ) {
     if( data.events.submit[1].namespace == 'caculate' ) {
      var bk = data.events.submit[1];
      data.events.submit[1] = data.events.submit[0];
      data.events.submit[0] = bk;
      bk._handler = bk.handler;
      bk.handler = function(ev) {
       var $yourInfo = $form.find('.your-info');
       if( firstClick ) {
        caculate_quote.call($form[0], $form);
        firstClick = true;
       }
       if( $yourInfo.hasClass('.hide') ||
        !$.trim( $yourInfo.find('[name="email-phone"]').val() ) ||
        !$.trim( $yourInfo.find('[name="your-name"]').val() ) ||
        !$.trim( $yourInfo.find('[name="post-code"]').val() ) ||
        !$.trim( $yourInfo.find('[name="your-email"]').val() ) ||
        !$.trim( $yourInfo.find('[name="your-name1"]').val() ) ||
        !$.trim( $yourInfo.find('[name="post-code1"]').val() )
        ) {
        ev.preventDefault();
        return false;
       }
       return bk._handler.call(this, ev);
      }
     }
    }
   }

  })( $(forms[i]) );

 }
});

Quote Total: 0

excludes GST

Would you like us to contact you about this quote?

[text total-quote id:total-quote class:total-quote]

[text* email-phone id:email-phone class:email-phone placeholder "Email or Phone No"][text your-name id:your-name class:your-name placeholder "Your Name"][text post-code id:post-code class:post-code placeholder "Post Code"][submit id:contact-me class:btn-contact-me "Contact Me"]

[email* your-email id:your-email class:your-email placeholder "Email Address"][text your-name1 id:your-name1 class:your-name1 placeholder "Your Name"][text post-code1 id:post-code1 class:post-code1 placeholder "Post Code"][submit id:email-quote class:btn-email-quote "Email Quote"]

Step 1
How wide is your driveway?: [number* driveway-meters min:0 id:driveway-meters class:driveway-meters class:change-quote "10"] meters

Step 2
How far is your garage from the footpath?: [number* footpath-meters min:0 id:footpath-meters class:footpath-meters class:change-quote "20"] meters

Step 3
Choose your concrete finish:  [select* finish  id:finish class:finish class:change-quote "$65 sq/m|Plain" "$80 sq/m|Coloured Concrete" "$120 sq/m|Exposed Aggregate" "$120 sq/m|Stenciled"]

[submit id:caculate-quote class:btn-caculate-quote "Caculate Quote"]


text:
Q: Rotating a mesh along a given axis, then rotate again along a different axis properly I'm working on a block rotation component for my game, and I hit a bit of a snag that I can't figure out. Basically, I want the ability to rotate a mesh component along all three axis. The player will only ever be able to rotate one axis at a time, by 90degrees or -90degrees. I also want the player to always rotate the mesh according to the world's X, Y, and Z axis, not the block's relative axis, which will change as it is rotated. How do I achieve this?
Mesh with no rotation:

Mesh rotated 90 degrees CCW along X axis:

The problem from here, is if I want to rotate the block along the Y axis, instead it will rotate the block along the Z axis, since the block is now rotated. How do I keep new rotations oriented to the world axis, and not the mesh?

A: Found the solution for this. I needed a blueprint node called AddWorldRotation. In C++ from the actor or component you would call AddWorldRotation as well. Then you simply input a rotator for what you wish to add to the component's existing rotation.
In my case, rotating 90 degrees along a specific axis would be FRotator(90, 0, 0), FRotator(0, 90, 0), or FRotator(0, 0, 90).


text:
Q: ag grid : js : How to find which filter is applied I have data displayed in ag grid.
It has 4 columns name,age,sport and has the following data:-
data
now when I filter the data based on "sport" , lets say uncheck "blanks"
I get the following data:-
 filtered data
1)My questions is how to get the which filter is applied on columns ,
like in this case "blanks" is applied on "sport".
2)If I refresh the data using
api.setRowdata(), filter applied to the columns are lost

A:
1.how to get the which filter is applied on columns

You can get it using gridApi.filterManager.allFilters
Check this live example ag-grid: Built-In Filters - log the filters applied.
Apply age and year filters and then click Log Filter button.

age: {column: Column, filterPromise: Promise, scope: null, compiledElement: null, guiPromise: {…}}
  year: {column: Column, filterPromise: Promise, scope: null, compiledElement: null, guiPromise: {…}}
  __proto__: Object

A: Starting from ag-grid@19.0.0 to get or set all applied filters you can take advantage of using:
const savedModel = gridApi.getFilterModel();
gridApi.setFilterModel(savedModel);

A: For the

*if I refresh the data using api.setRowdata(), filter applied to the columns are lost

we can use the following settings for columns in columnDefs object :-
filterParams: {
    newRowsAction: 'keep'
}


text:
Q: FastApi create background task in a custom APIRoute According to this tutorial you can create BackgroundTasks from the route function as follow:
@app.post("/send-notification/{email}")
async def send_notification(email: str, background_tasks: BackgroundTasks):
    background_tasks.add_task(write_notification, email, message="some notification")
    return {"message": "Notification sent in the background"}

but in my case, I have a custom APIRoute that should create a background task after every endpoint-call (this is a simplified example):
# core/users.py
def process(email):
    #processing
    #create a background task here

# router.py
class MyRoute(APIRoute):
    def get_route_handler(self) -> Callable:
        original_route_handler = super().get_route_handler()

        async def custom_route_handler(request: Request) -> Response:
            response: Response = await original_route_handler(request)
            return response

    return custom_route_handler

# app.py
from core import users
@app.post("/send-notification/{email}")
async def send_notification(email: str):
    #processing

A: You can do that, but you should attach the background object to the response. You can check starlette official doc at Background Tasks

# core/users.py
from fastapi import BackgroundTasks

def send_email(email):
    print("sending email to {} as background task!".format(email))

def process(email):
    background_tasks = BackgroundTasks()
    background_tasks.add_task(send_email, email)
    return background_tasks

#app.py
from core import users
from fastapi.responses import JSONResponse

@app.post("/send-notification/{email}")
async def send_notification(email: str):
    background_tasks = users.process(email)
    return JSONResponse("Email sent!", background=background_tasks)

A: Thank you everyone for the ideas; but according to my use case (the background task is created in a custom APIRoute, after the response is created)
I ended up with something like this:
# core/users.py
def process(response: Response):
    background_task: BackgroundTask = BackgroundTask(async_process, MY_ARG1)
    if response.background is None:
        response.background = background_task
    else:
        response.background.add_task(background_task.func, *background_task.args, *background_task.kwargs)

# router.py
class MyRoute(APIRoute):
    def get_route_handler(self) -> Callable:
        original_route_handler = super().get_route_handler()

        async def custom_route_handler(request: Request) -> Response:
            response: Response = await original_route_handler(request)
            users.process(response=response)
            return response

    return custom_route_handler

# app.py
app = APIRouter(route_class=MyRoute)
@app.post("/send-notification/{email}")
async def send_notification(email: str):
    #processing

PS: These code snippets are a simplified version of what I used in creating a "trace-module" for the OpenReplay project.

A: BackgroundTasks is just a helper, you can run it in thread/loop by yourself:
def run_in_background(func, *args):
    if asyncio.iscoroutinefunction(func):
        loop = asyncio.get_event_loop()
        loop.create_task(func("param"))
    else:
        # Starlette uses anyio library here under the hood
        t = threading.Thread(target=func, args=("param",))
        t.start()

A: background task come from Starlette and it is attached to a response.
As fastapi doc said:
"It's still possible to use BackgroundTask alone in FastAPI, but you have to create the object in your code and return a Starlette Response including it."
you may want to take a look at runing your function in a threadpool from tiangolo (creator of fastapi)
from fastapi.concurrency import run_in_threadpool

@api.get('/handler')
async def handler():
    ...
    # Slow async function
    await my_async_function()
    ....
    # Slow running sync function
    await run_in_threadpool(sync_function)


text:
Q: Connection error when trying to connect to Cloud-sql sql-server from cloud-functions I am using firebase functions to connect to cloud-sql (Micorsoft SQL Server). I tried the following to connect to SQL Server via public ip:
/*Tedious Start*/
var TediousConnection = require('tedious').Connection;
var TediousRequest = require('tedious').Request;
var TediousTypes = require('tedious').TYPES;
const config = {
  user: 'admin',
  password: 'password',
  server: '12.345.5.678',
  database: 'mma',
  //host: 'myproject:us-central1:my-db'
};
app.get('/mssql/', async(req, res) => {
  var sql = require('mssql');
  sql
    .connect(config)
    .then(function() {
      //6.
      var request = new sql.Request();
      //7.
      request
        .query('SET NOCOUNT ON;select * from student')
        .then(function(recordset) {
          // send records as a response
          res.send(recordset.recordset);
          sql.close();
        })
        .catch(function(err) {
          //8.
          console.log(err);
          sql.close();
        });
      res.end();
    })
    .catch(function(err) {
      //9.
      console.log(err);
    });
});

I get the following error:
{ ConnectionError: Failed to connect to 12.345.5.678:1433 in 15000ms
    at Connection.tedious.once.err (/srv/node_modules/mssql/lib/tedious/connection-pool.js:68:17)
    at Object.onceWrapper (events.js:315:30)
    at emitOne (events.js:116:13)
    at Connection.emit (events.js:211:7)
    at Connection.connectTimeout (/srv/node_modules/mssql/node_modules/tedious/lib/connection.js:1195:10)
    at Timeout.connectTimer.setTimeout [as _onTimeout] (/srv/node_modules/mssql/node_modules/tedious/lib/connection.js:1157:12)
    at ontimeout (timers.js:498:11)
    at tryOnTimeout (timers.js:323:5)
    at Timer.listOnTimeout (timers.js:290:5)
  code: 'ETIMEOUT',
  originalError:
   { ConnectionError: Failed to connect to 12.345.5.678:1433 in 15000ms
    at ConnectionError (/srv/node_modules/mssql/node_modules/tedious/lib/errors.js:13:12)
    at Connection.connectTimeout (/srv/node_modules/mssql/node_modules/tedious/lib/connection.js:1195:54)
    at Timeout.connectTimer.setTimeout [as _onTimeout] (/srv/node_modules/mssql/node_modules/tedious/lib/connection.js:1157:12)
    at ontimeout (timers.js:498:11)
    at tryOnTimeout (timers.js:323:5)
    at Timer.listOnTimeout (timers.js:290:5)
     message: 'Failed to connect to 12.345.5.678:1433 in 15000ms',
     code: 'ETIMEOUT' },
  name: 'ConnectionError' }

I think the cloudfunction is unable to reach the sql server. I also tried to add the service account to have the cloudsql permissions.
I thought I was doing something wrong with my cloud functions and tried cloudsql-postgresql from cloud funtions. I am able to connect successfully to ClouSQL-postgresql from cloud function.
For e.g in case of cloudsql-postgresql, the host takes a value similar to the following using unix domain socket :
config.host = `/cloudsql/${process.env.CLOUD_SQL_CONNECTION_NAME}`;

In case of Cloudsql-mssql, I am providing the ipaddress for server. I do not know what I am missing. Is there a firewall issue I need to take care of?

A: As per the documentation:

Cloud Functions does not support connecting to Cloud SQL for SQL
  Server over public IP. Use private IP instead

instead you should connect directly using the private IP address and port 1433 for your instance.


text:
Q: How to do PngCrush for my images of iOS app?
Possible Duplicate:
What is PngCrush in iOS?

I'm having a doubts about image optimisation technique of iOS apps Pngcrush
My doubt is,
Is pngcrush built-in to xcode or do we need to explicitly download pngcrush tool and optimise our images?
If we want to do it explicitly how can we achieve this?

A: This question may solve your problem: Skipping the 'CompressResources' build step for XCode iPhone apps
Another thing is there might chances that the PNGs are of type JPG's and the Extentation has been modified with png.


text:
Q: Email from website form submission not being deliverd due to SPF fail I need a little guidance on a spam related email rejection our website is having.  It is a Wordpress site hosted with WPengine.  As far as I'm aware it's using the default PHP mailer.
I've configured an SPF record for our website's domain that allows the WPengine IP's by way of  include:wpengine.com.  This in turn has it's own IP's and includes that add google SPF's, SendGrid SPF's and so on.
There is also a number of other IP's and includes in our record, but despite the fail from http://www.kitterman.com/spf/validate.html, and the warning about too many lookups from MXtoolbox, the SPF is valid.
We're receiving all form submissions from our site (I did add some Exchange message rules to make sure they are delivered into the inboxes rather than junk or clutter), and so are other Exchange email servers our various offices have that use a different email domain.  There is one problem office that has a Kerio mail server that is rejecting form submission emails from our website.
I know this because I've setup a "Mail User" on our Exchange server with an external forward to the Kerio mailbox the form submission is intended for.
Form submission emails are from: postmaster@ourdomain.com.au to MailUser@ourdomain.com.au (forwarded to recipient@theirdomain.com.au).
When I do a message trace on our Exchange, I see the following results:

Is this problem mine entirely?  Or can I simply ask the administrator of this Kerio mail server to create some whitelist entries for our email domain, the WPengine site and the form submission email subject?

A: The answer is in the "too many lookups" warning, which should be an error telling you that your SPF record is invalid for exceeding the 10 lookup limit:

4.6.4.  DNS Lookup Limits
     Some mechanisms and modifiers (collectively, "terms") cause DNS
     queries at the time of evaluation, and some do not.  The following
     terms cause DNS queries: the "include", "a", "mx", "ptr", and
     "exists" mechanisms, and the "redirect" modifier.  SPF
     implementations MUST limit the total number of those terms to 10
     during SPF evaluation, to avoid unreasonable load on the DNS.  If
     this limit is exceeded, the implementation MUST return "permerror".

This site makes some suggestions on how to fix your problem, such as reviewing your SPF record to remove unnecessary includes or restructuring your email domains to separate out emails by source (or just not use SPF).
For example, you could have your form send email from @webform.example.com and then set up a SPF record specific to that name:
webform.example.com.   IN TXT  "v=spf1 include:wpengine.com"

(don't forget an MX if you want people to be able to reply to these emails, and of course setting up your mailserver to recognize the addresses)


text:
Q: How to communicate between joomla components? In my website a registered user navigates through various components, I am thinking of using session variable for all communications between components instead of a POST /GET. Is this a right thing to do?
I have several custom joomla 2.5 components written by me. Things like login welcome page, application1 and so on. Now the welcome page has buttons to these applications and instead of using a post/get I am thinking of using session variables. I am new to web technologies and I want to know pros and cons of this approach.

A: There's no need to use superglobals like $_SESSION when you're using a CMS like Joomla.  Instead, use:
JRequest::setVar("varName");

and
JRequest::getVar("varName");


text:
Q: Column widget isn't contracting I have a container in a stack widget. the container contains a column. I'm trying to align the container to the bottom center of the app. So the pink background color should only take up the space of its child.
For some reason, it's taking up the entire height of the app. What am I doing wrong and how can I fix it?
Widget build(BuildContext context) {
    return Stack(
      alignment: Alignment.bottomCenter,
      children: [
...Other Children
        Container(
          color: Colors.pink,
          child: Column(mainAxisAlignment: MainAxisAlignment.end, children: [Text('hey')]),
        )
      ],
    );
  }

A: Based on your question --and my understanding--, this is what you want to achieve:

The only problem with your code is that you put the color: Colors.pink values inside the parent Container of the Column widget.
To achieve position like the image above, add the color: Colors.pink values inside the children of the Column itself
Stack(
            alignment: Alignment.bottomCenter,
            children: [
              // ...Other Children...
              Container(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    Container(
                      color: Colors.pink,
                      child: Text('hey'),
                    ),
                  ],
                ),
              )
            ],
          ),

A: set mainAxisSize: MainAxisSize.min, property of Column, so your column contracts to the total size of its children


text:
Q: What happens when an FPGA is "programmed"? From what I understand, the process of programming an FPGA comes in two parts:

*

*Encode the hardware description into bits that the FPGA can understand (i.e. write some HDL and compile it)

*Load the compiled HDL onto the FPGA.

My question is: "What does the FPGA do with the compiled HDL?". At the moment, I think of FPGAs as "mouldable hardware", where wires and logic gates can be moulded to whatever you want. One of the nice things is that the mouldability is permanent: FPGAs can be reprogrammed.
How do FPGAs interpret compiled HDL? How is permanent mouldability achieved?

A: Compiling the HDL results in a bit pattern which indicates which connections inside the FPGA should be activated. The FPGA doesn't have to interpret the HDL anymore. The bit pattern is programmed into a serial loader Flash/EEPROM, and upon booting this pattern is shifted into the FPGA, making the necessary connections.

A: The result of the compilation is a bitstream (literally a stream of bits) which is loaded in after power up.  This shifts through the FPGA being stored in some memory cells (latches).  These cells are connected to various logic entities, multiplexers, look-up tables, RAM blocks, routing matrices and constitute what is called the "configuration".  Once the bitstream is loaded, the FPGA begins to operate - the bits in the configuration-latches "tell" each little piece of FPGA how to operate.
EDIT April 24, 2012: The flip-flops I mentioned aren't for the look-up tables or the configuration of them. As @ajs410 said those are in RAM which is even fewer transistors. THe flip-flops are for the storeage of the data out of the LUT, if that storage is enabled.

A: Judging by your other question, you're a Xilinx guy.  So I highly suggest getting the data sheet for your Xilinx chip and going to the Functional Description chapter.  For the Spartan 3 chip that I use, it's 42 pages of fun reading.  It details exactly what components are inside an FPGA - the IOBs, CLBs, slices, LUTs, Block RAM, Multipliers, Digital Clock Manager, Clock Network, Interconnect, and some very basic configuration information.  You need to understand this information if you want to know what a "compiled HDL" looks like.
Once you're familiar with your FPGA's architecture, then you can understand this process.  First, your HDL design is run through the synthesis engine, which turns your HDL into basically RTL.  Then the Mapper processes the results from Synthesis, "mapping" them onto the available pieces of FPGA architecture.  Then the Router does Place And Route (PAR), which figures out where those pieces go and how to connect them.  Finally, the results from PAR are turned into a BIT file.  Typically this BIT file is then transformed in some way so that it can be loaded into a Flash chip, so that the FPGA can be programmed automatically when it powers up.
This bit file describes the entire FPGA program.  For instance, the CLBs in a Spartan 3 are composed of slices, which are composed of LUTs, which are just 16-address 1-bit SRAMs.  So one thing the BIT file will contain is exactly what data goes into each address of the SRAM.  Another thing the BIT file contains is how each input of the LUT is wired to the connection matrix.  The BIT file will also contain the initial values that go inside the block RAM.  It will describe what is connected to the set and reset pins of each flip flop in each slice.  It will describe how the carry chain is connected.  It will describe the logic interface for each IOB (LVTTL, LVCMOS, LVDS, etc).  It will describe any integrated pull-up or pull-down resistors.  Basically, everything.
For Xilinx, the FPGA's memory is cleared when configuration is initiated (i.e. PROG_B is asserted).  Once memory is clear, INIT_B goes high to indicate that phase is complete.  The BIT file is then loaded, either through JTAG or the Flash chip interface.  Once the program is loaded, the Global Set/Reset (GSR) is pulsed, resetting all flip flops to their initial state.  The DONE pin then goes high, to indicate configuration is complete.  Exactly one clock cycle later, the Global Three-State signal (GTS) is released, allowing outputs to be driven.  Exactly one clock cycle later, the Global Write Enable (GWE) is released, allowing the flip flops to begin changing state in response to their inputs.  Note that even this final configuration process can be slightly reordered depending on flags that are set in the BIT file.
EDIT:
I should also add that the reason the FPGA program is not permanent is because the logic fabric is composed of volatile memory (e.g. SRAM).  So when the FPGA loses power, the program is forgotten.  That's why they need e.g. Flash chips as non-volatile storage for the FPGA program, so that it can be loaded whenever the device is powered on.

A: The standard term is "configuration" and not "programming" for an FPGA. The FPGA is usually an SRAM based device. An SRAM stores bits which indicate which connections are formed and broken inside the "logic fabric" of the device. When configuration occurs, a stream of bits is sent into the FPGA which writes into this SRAM. When the SRAM based FPGA is switched, off the SRAM data is erased and when the FPGA is turned on, it shall need to be configured again.
Now know this, they are various methods to "configure" and FPGA and thus different formats of files exist containing this "bit stream". At the end of the day, the structure of these files and details of how precisely the FPGA is configured are proprietary for the manufacture and this information is never shared. But the general principle remains the same across FPGAs.


text:
Q: Error on matching the type signature on function for a list of pairs I am trying to write a function that takes a list of pairs, ex. [(1,2),(1,4),(2,5),(3,4),(1,8)] and it returns the list of the sum of the second values of each pair, for each of first value in a sorted manner. ex.[14,5,4].
To do this I made a comprehension list to fold the second values from a list of pairs, and a comprehension list where the list of pairs is filtered by the first value.
addSec :: (Num a, Num b) => [(a,b)] -> b
addSec a = foldr (+) 0 (map snd a)

listf ::(Num a,Enum a,Eq a,Fractional a,RealFrac a)=> a ->[a]
listf g =  [ a | x <- [0..g], a <- addSec(filter ((== x ).fst) z ) ]
                        where
                        z=[ (x,y) | x <-reverse [1..553],
                                  let s = x * (fromIntegral (ceiling(504 / x))) - 504,
                                   y <- [s..g] ]

I have tried the functions
foldr (+) 0 (map snd a)

filter ((== x ).fst) z

separately on Prelude> and they work as intended but I get this sort of error in a program:

try.hs:20:36: error:
    * Occurs check: cannot construct the infinite type: a ~ [a]
    * In the expression: addSec (filter ((== x) . fst) z)
      In a stmt of a list comprehension:
        a <- addSec (filter ((== x) . fst) z)
      In the expression:
        [a | x <- [0 .. g], a <- addSec (filter ((== x) . fst) z)]
    * Relevant bindings include
        x :: a (bound at try.hs:20:18)
        z :: [(a, a)] (bound at try.hs:22:25)
        g :: a (bound at try.hs:20:7)
        listf :: a -> [a] (bound at try.hs:20:1)
   |
20 | listf g =  [ a | x <- [0..g], a <- addSec(filter ((== x ).fst) z ) ]
   |                                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Failed, no modules loaded.

I get similar errors even when the type signature is:
addSec :: [(a,b)] -> a

So I am not sure what to change. Thank you very much, I appreciate any help.


text:
Q: IdentityServer4 - RefreshToken Expiration Is there a way to achieve following flow using IdentityServer4
If a client is not active for a specified amount of time - he should not be able to refresh his token.
As I understand this should be achievable via RefreshTokenExpiration settings, but I don't understand what specific combination of settings should allow this behavior.
https://identityserver4.readthedocs.io/en/latest/topics/refresh_tokens.html - This is the official documentation, but none of the combination I tried helped me achieve my goal

A: Here is settings required:
RefreshTokenExpiration = TokenExpiration.Absolute,
AbsoluteRefreshTokenLifetime = 10000,

Here is when update token happens on code


text:
Q: Store device tokens for push notification in ejabberd I will send push notification via gcm in ejabberd.If user is offline I will write a module for offline message hook and I will send push notification to receiver.But I need device token for send request to gcm servers.I don't know how to store device token in ejabberd ? I need help.How can I store device tokens for each user in ejabberd ?

A: Your question is "how do I store data in Erlang?"
There are many answers. Probably, you want to read about Mnesia. Or use a relational database. Or use basically any other data store (Redis, MongoDB, DynamoDB, etc, etc, etc) depending on your needs and situation.


text:
Q: docker-compose yaml file syntax issues No matter what I try I keep getting syntax errors (mapping not allowed, or can not fine expected ":") on line 67 external: true ( (volumes section at the end). Can someone help me out with the format please? I have tried using quotes, tried messing with indentions and spacing etc, and no matter what I get an error. Thanks!!
# docker-compose.yml
version: '3.7'
services:
  jenkins:
    image: jenkins/jenkins:lts
    restart: always
    privileged: true
    user: root
    ports:
      - 8080:8080
      - 50000:50000
    container_name: jenkins
    volumes:
      - jenkins-data:/var/jenkins_home
      - /var/run/docker.sock:/var/run/docker.sock
  grafana:
    image: grafana/grafana:latest
    restart: always
    privileged: true
    user: root
    ports:
      - 8082:8082
    container_name: grafana
    volumes:
      - grafana-data:/var//lib/grafana
  nexus:
    image: sonatype/nexus3:latest
    restart: always
    privileged: true
    user: root
    ports:
      - 8081:8081
    container_name: nexus
    volumes:
      - nexus-data:/nexus-data
  gitlab:
    image: gitlab/gitlab-ee:latest
    restart: always
    privileged: true
    user: root
    ports:
      - 8083:8083
      - 443:8443
    container_name: gitlab
    volumes:
      - gitlab-data:/var/opt/gitlab
      - gitlab-config:/etc/gitlab
      - gitlab-logs:/var/logs/gitlab
  maven:
    image: maven:latest
    privileged: true
    user: root
    ports:
      - 8085:8085
    container_name: maven
    volumes:
      - maven-data:/root/.m2
  gradle:
    image: gradle:latest
    privileged: true
    user: root
    ports:
      - 8084:8084
    container_name: gradle
volumes:
  ec2-user_jenkins-data
        external: true
  ec2-user_jenkins-docker-certs
        external: true
  gitlab-config
        external: true
  gitlab-data
        external: true
  gitlab-logs
        external: true
  grafana-data
        external: true
  maven-data
        external: true
  sonarqube-data
        external: true
  sonarqube-config
        external: true

A: I think you are just missing the ":" after volumes.
Here is the updated compose file.
# docker-compose.yml
version: '3.7'
services:
  jenkins:
    image: jenkins/jenkins:lts
    restart: always
    privileged: true
    user: root
    ports:
      - 8080:8080
      - 50000:50000
    container_name: jenkins
    volumes:
      - jenkins-data:/var/jenkins_home
      - /var/run/docker.sock:/var/run/docker.sock
  grafana:
    image: grafana/grafana:latest
    restart: always
    privileged: true
    user: root
    ports:
      - 8082:8082
    container_name: grafana
    volumes:
      - grafana-data:/var//lib/grafana
  nexus:
    image: sonatype/nexus3:latest
    restart: always
    privileged: true
    user: root
    ports:
      - 8081:8081
    container_name: nexus
    volumes:
      - nexus-data:/nexus-data
  gitlab:
    image: gitlab/gitlab-ee:latest
    restart: always
    privileged: true
    user: root
    ports:
      - 8083:8083
      - 443:8443
    container_name: gitlab
    volumes:
      - gitlab-data:/var/opt/gitlab
      - gitlab-config:/etc/gitlab
      - gitlab-logs:/var/logs/gitlab
  maven:
    image: maven:latest
    privileged: true
    user: root
    ports:
      - 8085:8085
    container_name: maven
    volumes:
      - maven-data:/root/.m2
  gradle:
    image: gradle:latest
    privileged: true
    user: root
    ports:
      - 8084:8084
    container_name: gradle
volumes:
  ec2-user_jenkins-data:
        external: true
  ec2-user_jenkins-docker-certs:
        external: true
  gitlab-config:
        external: true
  gitlab-data:
        external: true
  gitlab-logs:
       external: true
  grafana-data:
        external: true
  maven-data:
        external: true
  sonarqube-data:
        external: true
  sonarqube-config:
        external: true

Hope this helps :D


text:
Q: Wrapping an ngRepeat inside another directive I'm trying to write a paginator as a directive for my application, but I can't seem to get it to work. Every where I've looked suggests using $compile, but I can't get that to work at all.
This is what I have, and you can view a live demo here
var app = angular.module('myApp', []);

app.controller('MyController', function($scope) {
  $scope.items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
});

app.directive('myPaginator', function() {
  return {
    restrict : 'A',
    priority : 1000,

    scope : {
      items : '=myPaginator'
    },

    controller : function($scope) {
      $scope.amount = 5;
    }
  };
});

app.directive('myPaginatorItem', function($compile) {
  return {
    restrict : 'A',
    require  : '^myPaginator',
    priority : 999,

    compile : function(element) {
      element
        .removeAttr('my-paginator-item')
        .attr('ng-repeat', 'item in items | limitTo:amount');

      return function($scope, element) {
        $compile(element)($scope);
      }
    }
  };
});

As you can probably tell, I'm quite new to angular, and any help will be greatly appreciated.

A: I've managed to make it work by storing the data on the main directive's controller, rather than on the scope, which you can see here.
var app = angular.module('myApp', []);

app.controller('MyController', function($scope) {
  $scope.items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
});

app.directive('myPaginator', function() {
  return {
    restrict : 'A',
    priority : 1000,
    replace  : true,

    scope : {
      items : '=myPaginator'
    },

    controller : function($scope) {
      this.items = $scope.items;
      this.amount = 5;
    }
  };
});

app.directive('myPaginatorItem', function($compile) {
  return {
    restrict : 'A',
    require  : '^myPaginator',
    priority : 999,
    scope    : {},

    compile : function(element) {

      element
        .removeAttr('my-paginator-item')
        .attr('ng-repeat', 'item in paginator.items | limitTo:paginator.amount');

      return function($scope, element, $attrs, paginator) {
        $scope.paginator = paginator;
        $compile(element)($scope);
      }
    }
  };
});

A: You have two major problems here:
First, Your directives doesn't share the same scope:

Second, Inside you directive you refer to an outer scope variable items:
.attr('ng-repeat', 'item in items | limitTo:amount');


text:
Q: Checking the convergence of the sequence: $\left(\frac{7n-3}{6n-5}\right)^n$ I would like to obtain $$\lim_{n \to \infty} \left(\frac{7n-3}{6n-5}\right)^n .$$
I tried solving it but I didn't know how.
Maybe someone can help me ?

A: One may write, for $n\ge1$,
$$
\frac{7n-3}{6n-5}=\frac{7}{6}+\frac{17}{6(6n-5)}>\frac76
$$ giving
$$
\left(\frac{7n-3}{6n-5}\right)^n> \left(\frac{7}{6}\right)^n,\qquad n\ge1,
$$ which yields
$$\lim_{n \to \infty} \left(\frac{7n-3}{6n-5}\right)^n=\infty.$$


text:
Q: How can I hide sensitive photos My problem is I've got heaps of photos that I don't want to be found in finder is their any easy way to stop finder from showing them in places like All Files or quicklook.

A: There are many ways to achieve this.

*

*Exclude such folders in the Spotlight search. Any one else using the Mac can easily find and go through the content.

*Create a new Disk Image (preferably encrypt it) in Disk Utility and it is a separate disk which grows and shrinks based on the contents. You could also use apps like Knox to achieve the same.

*Try apps like Skedaddle to hide from Finder. Skedaddle protects the files with a password and Spotlight cannot find it. It does not encrypt the data.

A: Create a hidden folder and put your private files (not only pictures) there.
They won't show up in spotlight or a finder search (basically both are the same)
To make a hidden folder, open the terminal app and type:
mkdir /.private
This will create a folder named .private in the root of your Hard drive.
Then you can only access this in finder by pressing shiftcommandG and entering /.private.
Of course you can name the folder anything you want and put it anywhere, but it has to start with a dot to be hidden, and you have to remember where you put it.


text:
Q: What it is going to be evaluated in a boolean expression? assuming that I have the following variables
bool b;
int i;
T* ptr;

when I put b, i or ptr, or whatever other variables I have, in a boolean expression like
var1 && var2

What is going to be evaluated to solve this expression ? The C++11 standard says something about what is the part from var1 and var2 that contributes to determine the boolean result ? There are implicit casting ?
It's not clear to me what the standard says about this.

EDIT
I'm interested in how a generic T type is converted into a bool and how a boolean expression is solved according to the standard

A: It's not clear to me what you're asking about. A variable is true in C and C++ if it is non-zero. The && operator only evaluates the right operand if the left operand is true. The truth value of an instance of a class T doesn't exist unless there is a conversion function. This is all in the standard.

A: §5.14/1

The && operator groups left-to-right. The operands are both contextually converted to type bool (Clause 4)... Unlike &, && guarantees left-to-right
  evaluation: the second operand is not evaluated if the first operand is false.

§4/2

[Note: expressions with a given type will be implicitly converted to other types in several contexts:
— When used as operands of operators. The operator's requirements for its operands dictate the destination type (Clause 5).
...

This is about as clear as the standard gets. First var1 will be implicitly converted to bool, and then, if it is true, var2 will be implicitly converted to bool.
Edit: I'll quote also §4.12/1

A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a
  prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false;
  any other value is converted to true. A prvalue of type std::nullptr_t can be converted to a prvalue of
  type bool; the resulting value is false.

Edit 2: For some arbitrary type T, see §4/3,

... Certain language constructs require that an expression be
  converted to a Boolean value. An expression e appearing in such a context is said to be contextually
  converted to bool and is well-formed if and only if the declaration bool t(e); is well-formed, for some
  invented temporary variable t (8.5).

For the meaning of this initialization, see §8.5/16

— Otherwise, if the source type is a (possibly cv-qualified) class type, conversion functions are considered.
  The applicable conversion functions are enumerated (13.3.1.5), and the best one is chosen through
  overload resolution (13.3). The user-defined conversion so selected is called to convert the initializer
  expression into the object being initialized. If the conversion cannot be done or is ambiguous, the
  initialization is ill-formed.

There is even more detail in §13.3.1.5 and §13.3, but you will be reading all night and then some. But the bottom line is that if T is a class type, then there has to be a conversion function. The best practice would be to define explicit operator bool for the class. However you could also do something like operator void*, which is what std::ios and its derived classes define, because void* can then be converted to bool in a standard conversion sequence. (This should be regarded as a deprecated idiom in C++11.)


text:
Q: How do I substring values in two columns to a new column and change the order? I have two columns with varchar data. I need to create a new column with a new ID composed from both columns, the order needs to change and I need to remove the hyphen.
ID1            | ID2       |
---------------+-----------
011216         | 313501-16 |
011280         | 313501-18 |
011283         | 313501-19 |

For example the first record needs to look like:
01121616313501

I've tried adding a new column to my existing table:
alter table Customers add CustID INT;

update Customers
    set CustID = cast(SUBSTRING(ID, 5, 4) as numeric);

A: If you want to keep the leading zeros you should define the column as VARCHAR and not INTEGER.
alter table Customers add CustID varchar(15);

update Customers
set CustID = ID1 + right(ID2, 2) + left(ID2, 6);

See the demo.
Results:
> ID1    | ID2       | CustID
> :----- | :-------- | :-------------
> 011216 | 313501-16 | 01121616313501
> 011280 | 313501-18 | 01128018313501
> 011283 | 313501-19 | 01128319313501

A: Try:
   UPDATE Customers
   SET CustID = CAST(CONCAT(ID1,SUBSTRING(ID2,1,5),SUBSTRING(ID2,8,2)) as numeric)

I think I got the character counts right, but I didn't try this myself yet.
UPDATE:
I just noticed that you are not asking for the numbers after the dash, so the new ID would simply be:
   UPDATE Customers SET CustID = CAST(CONCAT(ID1,SUBSTRING(ID2,1,5)) as numeric)