text:
Q: tree implementation in buffer of fixed size Which open source implementations of a tree (with arbitrary number of children per node; nodes containing a small data type like int or a pointer (additional to the implementation-specific indexing data, of course)) in a (linear) buffer do exist? (Obviously, the maximum number of tree nodes is bounded by the buffer size)
(Graph instead of tree would also be okay).

A: You can take any implementation of a tree that allows a stateful allocator, and implement a custom allocator on top of your fixed size buffer.
Though the C++ standard doesn't guarantee support for stateful allocators, they work "with most STL implementations most of the time". Allocator state is usually only a problem when moving nodes between containers.
If you can live with one instance, the buffer can also be a template parameter.


text:
Q: How to solve this kind of recurrence relation in closed form? $F(n) = aF(n-1) + bF(n-2) + cF(n-3) + dF(n-4)$ How to solve this   recurrence relation in closed form? $$F(n) = aF(n-1) + bF(n-2) + cF(n-3) + dF(n-4)$$
I know how to solve recurrence relations for less than four calls by solving the characteristic polynomial. But are there other ways so that i don't have to solve the 4 degree characteristic polynomial to solve this recurrence relation?

A: One of the ways of solving such recurrences is backward iteration. Fix the value of $n\ge 1$. Note that the solution will be a sum of product of quantities $a$, $b$, $c$ and $d$ followed by $F_\xi$ where $\xi=0,\cdots,3$. Note that each $a$ diminishes the time index $n$ by unity, each $b$ diminishes it by a two, each $c$ by three and finally each $d$ by a four. Let us denote the number of $b$'s , $c$'s and $d$'s in a sequence as $P$, $q$ and $r$ respectively and let the time index run backwards from the left to the right. Luckily the coefficients do not depend on the time index so all what we need to count the number of strictly ordered sequences of length $P+q+r-1$ (note that the last $d$ quantity in the sequence is replaced by $F_{\xi+1}$) bounded from the below by unity and from the above by $n-\xi-P-2 q-3 r-1$. Therefore we have:
\begin{equation}
F_{n+2} = \sum\limits_{r=0}^n \sum\limits_{q=0}^n \sum\limits_{P=0}^n 1_{n-\xi \ge 2P + 3 q+ 4 r}\frac{(P+q+r)!}{P! q! r!} \binom{n-\xi-P-2 q-3r-1}{P+q+r-1} a^{n-\xi-2 P-3 q-4 r} b^P c^q d^r \cdot F_{\xi+1}
\end{equation}
for $\xi=1$ only. In this way we have obtained one ''mode'',i.e. one solution. The other three linearly independent solutions can be obtained using similar reasoning except that certain boundary conditions have to be taken into account. We will complete this later on.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Regex: Match list of words without reusing previously matched words I am trying to write a regex pattern that will match any string containing the words '28', 'bonus', and 'day'.
At the moment I have come up with this:
(bonus|(days|day)|(28th|28)|twenty[ \-\t]*(eighth|eight))[ \ta-z]*(bonus|days|day|(28th|28)|twenty[ \-\t]*(eighth|eight))[ \ta-z]*(bonus|days|day|(28th|28)|twenty[ \-\t]*(eighth|eight))

You can view the results here: https://regex101.com/r/oOcGqk/8
The trouble I am having is that any word can be used multiple times, and still be matched. For example: 'day day bonus', 'bonus bonus bonus'. How can I exclude strings that use any of these words ('28', 'bonus', 'day') more than once?

A: I think this regex expresion is solution:
(?=.*bonus)(?=.*day)(?=.*28|twenty\s*-?\s*eight).*

A: With a decent regex engine, you could make use of a nice trick:
^     # Start of string
(?=(?:(?!bonus).)*bonus()(?:(?!bonus).)*$)
# Explanation: This lookahead assertion makes sure that "bonus" occurs exactly once
# in the string. It doesn't actually match any text, it just "looks ahead" to see if
# that condition is met. However, it contains an empty capturing group "()" that only
# participates in the match if the lookahead assertion succeeds. We can check this later.
(?=(?:(?!days?).)*days?()(?:(?!days?).)*$)
(?=(?:(?!28(?:th)?|twenty-eighth?).)*(?:28(?:th)?|twenty-eighth?)()(?:(?!28(?:th)?|twenty-eighth?).)*$)
[\w\s]*  # Match a string that only contains alnum character or whitespace
\1\2\3   # Assert that all three words participated in the match
$        # End of string.

You can test this here
In JavaScript, you'll have to spell out all possible permutations. Unfortunately, JS doesn't even allow verbose regexes, so it's going to be monstrous.
Just as a starting point: The following regex will match strings that contain bonus, days and 28 exactly once, but it only allows them in the order "bonus, days and 28"  or  "days,bonus and 28". You'd need to add the other four permutations to get a complete regex (and a complete mess). Do this programmatically, not with a regex.
^(?:(?:(?!bonus|days?|28(?:th)?|twenty-eighth?).)*bonus(?:(?!bonus|days?|28(?:th)?|twenty-eighth?).)*days?(?:(?!bonus|days?|28(?:th)?|twenty-eighth?).)*(?:28(?:th)?|twenty-eighth?)(?:(?!bonus|days?|28(?:th)?|twenty-eighth?).)*|(?:(?!bonus|days?|28(?:th)?|twenty-eighth?).)*days?(?:(?!bonus|days?|28(?:th)?|twenty-eighth?).)*bonus(?:(?!bonus|days?|28(?:th)?|twenty-eighth?).)*(?:28(?:th)?|twenty-eighth?)(?:(?!bonus|days?|28(?:th)?|twenty-eighth?).)*)$

Test it here. You have been warned.


text:
Q: How can I insert Html tags into incoming dynamic text I have some incoming text from a database that's generated dynamically and it is being placed into a div, I'll call it:

 ${dataBase.text}

What I want to do is dynamically place p tags inside of the database.text based on the number of complete sentences. So for example before the first line in database.text we have a starting p tag, then after the 8th completed
sentence we have an ending p tag. Then repeat for every 8 sentences.
This is the expression I'm using to count the number of occurring sentences:
/\w[.?!](\s|$)/g
Ultimately here is the simplified code I have so far within an ajax request:
/* The reg expression for counting sentences */

 let re;
 re = /\w[.?!](\s|$)/g

const dataBase = JSON.parse(this.responseText);

/* Pull the text out the database object for counting sentences */
const dataBaseString = dataBase.text;

/* Count the number of senteces */
let count = (dataBaseString.match(re) || []).length;

const output = `

      ${dataBase.text }

`;

document.getElementById('dynamicText').innerHTML = output;

I have no problems counting the sentences, the roadblock I'm running into is putting the p tags into the incoming text. I tried using insertAdjacentHTML() but I get an Uncaught TypeError: Cannot read property 'insertAdjacentHTML' of null error.
Any ideas on how this can be done, or if this can be done?

A: Voila!
Based on responses from:
Split string into sentences in javascript
and
Split array into chunks
I have created a solution that I believe is a viable one. I am splitting the whole string ( database.text ) into and array of phrazes, than I create the chunks of 8 of phrazes, and in the end I append them to the wrapper.
const wrapper = document.querySelector('.wrapper')

const text = `... your stringified content`

const array = text.replace(/([.?!])\s*(?=[A-Z])/g, "$1|").split("|")

function chunker(array, chunkSize) {
  console.log(array)
  return [].concat.apply([],
    array.map(function(el, i) {
      return i % chunkSize ? [] : [array.slice(i, i + chunkSize)];
    })
  );
}

const paragraphs = chunker(array, 8)

paragraphs.forEach((el) => {
    const p = document.createElement('p')
  p.innerText = el
  wrapper.append(p)
})

here is a JSfiddle I have prepared for you: https://jsfiddle.net/mkbctrlll/d5r38whL/35/


text:
Q: Why URL is distorted? Please help solve the problem.
I use rails 5. I create simple site, whitch have follow navigation:
kalinin@kalinin ~/rails/test5 $ rails routes
         Prefix Verb URI Pattern                Controller#Action
     pages_home GET  /pages/home(.:format)      pages#home
    pages_about GET  /pages/about(.:format)     pages#about
pages_portfolio GET  /pages/portfolio(.:format) pages#portfolio
     pages_blog GET  /pages/blog(.:format)      pages#blog
  pages_contact GET  /pages/contact(.:format)   pages#contact
           root GET  /                          pages#home

home page have 2 paths:
http://localhost:3000/pages/home
http://localhost:3000/

home page have js-slider. initialization code:
function clearText(field)
{
    if (field.defaultValue == field.value) field.value = '';
    else if (field.value == '') field.value = field.defaultValue;
}

var flashvars = {};
flashvars.xml_file = "photo_list.xml";
var params = {};
params.wmode = "transparent";
var attributes = {};
attributes.id = "slider";
swfobject.embedSWF("flash_slider.swf", "flash_grid_slider", "960", "350", "9.0.0", false, flashvars, params, attributes);

ddsmoothmenu.init({
  mainmenuid: "templatemo_menu", //menu DIV id
  orientation: 'h', //Horizontal or vertical menu: Set to "h" or "v"
  classname: 'ddsmoothmenu', //class added to menu's outer DIV
  //customtheme: ["#1c5a80", "#18374a"],
  contentsource: "markup" //"markup" or ["container_id", "path_to_menu_file"]
})

Problem:
on path http://localhost:3000/pages/home
this slider is not displays. console output follow error message:

GET http://localhost:3000/pages/photo_list.xml 404 (Not Found)

But on path http://localhost:3000/
slider is displays without problems.
ps:
path pages/photo_list.xml is NOT exist. but path public/photo_list.xml is exist.
PageController:
class PagesController < ApplicationController
  def home
    render layout: "home"
  end

  def about
  end

  def portfolio
    render layout: "portfolio"
  end

  def blog
  end

  def contact
  end
end

A: It's because of this line:
flashvars.xml_file = "photo_list.xml";
That is going to be relative to the page you are on. So when you are on http://localhost:3000/pages/home it will try and load http://localhost:3000/pages/photo_list.xml. When you are on the homepage it will load the right file.
Change that line to this:
flashvars.xml_file = "/photo_list.xml";


text:
Q: How to create a Rule on Drupal that creates activity streams of followed users? I'm using Flags, Commons follow, Message and Rules modules to create the ability for users to follow each other.
I use commons auto generated commons_follow_user flag to create a follow button. I generate that button through views on each node. If user A presses the button on the node submitted by user B, user A starts following user B. By default commons follow user module shows user B name on user A account page. What I also need is for user A to see activity stream of the user B, more specifically to see when user B adds new node. I understand that I have to use rules and messages modules. I have created a rule that triggers Message entity creation on new node creation but how do I make this stream only visible to users following the user that creates those nodes? Is there a way with rule conditions? Or should I look in the other direction to achieve this?

A: It looks like you're trying to create some sort of social network.
A module I'm pretty fond of us the Statuses module
If you're just looking for something that will post activity, there's also the heartbeat module
I hope that helps.


text:
Q: aura:id is coming to be undefined for the first row in table first error is -> Action failed: c:xyz_Cmp$controller$onKeyUp [Cannot read property 'get' of undefined] Failing descriptor: {c:xyz$controller$onKeyUp}
second error is -> Action failed: c:xyz_Cmp$controller$onKeyUp [Cannot read property 'match' of undefined] Failing descriptor: {c:xyz_Cmp$controller$onKeyUp}
following is the code :
Sorry, new to stackexchange , following is the component markup

                        <aura:iteration items="{!v.cont}" var="item" indexVar="ind">

                                        <lightning:input type="text" variant="label-hidden" disabled="true" value="{!item.x__c}"  placeholder="" pattern="\d{5}-\d{3}-\d{2}" maxlength="12" messageWhenBadInput=Invalid" messageWhenPatternMismatch="Invalid"/>

                                        <lightning:input type="text" aura:id="fieldId" variant="label-hidden" required="true" name="input2"  value="{!item.y__c}" pattern="^[1-9]\d{4}$" maxlength="5" messageWhenBadInput="Invalid" messageWhenPatternMismatch="Invalid" placeholder=""/>

                                        <ui:inputText aura:id="searchInput"
                                                      keyup="{!c.onKeyUp}" value= "{!item.z__c}" class="slds-input"
                                                      updateOn="keyup" />
                                        {!v.errormessage}

                        </aura:iteration>

js controller :

onKeyUp: function(component, event, helper)
                                        {
                                            let PList = component.get("v.cont");

                                             for(var i=0;i<PList.length;i++)
                                             {

                                                 var searchInput = component.find('searchInput');

                                                 var nvalue = searchInput[i].get("v.value");

                                                var patt = /^(\d{5}-\d{3}-\d{2})$|^(\d{4}-\d{4}-\d{2})$|^(\d{5}-\d{4}-\d{1})$|^(\d{5}-\d{4}-\d{2})$/;

                                                 if(nvalue.match(patt))
                                                 {
                                                     component.set("v.errorcheck",false);
                                                     component.set("v.errormessage",'');
                                                     document.getElementById("ValidationError"+i).style.display = 'none';
                                                 }
                                                 else if(!ndcvalue.match(patt))
                                                 {
                                                     component.set("v.errorcheck",true);
component.set("v.errormessage",'Invalid, Please Enter Valid Format.');               document.getElementById("ValidationError"+i).style.display = 'block';

                                                 }
                                             }
                                        }
`````````````````````````

code is not working, not sure how to resolve it. searchInput is coming to be undefined

A: I didn't see any specific use of using aura:id's here. Since updateOn on ui:inputText attribute itself does that.
You can use the keyup event & add whatever you're trying to do because you already have the updated value in the list.
    onKeyUp : function(c, e , h){
       let contactList = c.get('v.cont');
       var patt = /^(\d{5}-\d{3}-\d{2})$|^(\d{4}-\d{4}-\d{2})$|^(\d{5}-\d{4}-\d{1})$|^(\d{5}-\d{4}-\d{2})$/;
       contactList.forEach((contact) =>{
       if(contact.z__c !== undefined){
          if(contact.z__c.match(patt)){
             //put your validation code inside here
           }
        }
        else{
         //this was a newly added row .. add validation for it here
        }
       });
    }


text:
Q: Complexity Analysis of Nested Loops with Sigma Notation There are two nested for loops. I'm not sure but I think that it's geometric series, but I cannot get well solution for it. What I tried is below up to now,
$$ \sum _{i=0}^{log\left(n-1\right)}\:\sum _{j=0}^{i-1}\:1 $$
$$ \sum _{i=0}^n\:\sum _{j=0}^n\:\left(\frac{1}{2}\right)^j $$
At first, I thought it's $O(nlogn)$ but instead as far as I research the right result is  $O(n)$.
int try(int n) {
    int sum = 0;
    for (int i = n; i > 0; i /= 2) {
        for (int j = 0; j < i; j++) {
          sum += 1;
          }
    }
    return sum;
}

Could you show its sigma notation with its complexity? I want to comprehend it.

A: The complexity is basically how many times the "sum+=1;" line is executed, since it is the line that is executed most often. How many times then?
$$n+\lfloor\frac{n}{2}\rfloor+\lfloor\frac{n}{2^2}\rfloor+\cdots\leq n+\frac{n}{2}+\frac{n}{2^2}+\cdots=2n.$$
So the time complexity is $\mathcal{O}(n)$, as the run time of the code is bounded by a constant times $n$.


text:
Q: Grails dependency injection from service to controller is not working As per the grails 3.1.13 guide I am trying to add service dependency to my controller, but somehow it is not working for me. It is throwing NullPointerException for Cannot get property 'serviceMethod' on null object. Below I am mentioning the steps to reproduce.
Execute following commands
grails create-app DepInjectionTest
grails create-controller com.abc.project.KpiReport
grails create-service com.abc.project.KpiReport

Above creates below directory structure

KpiReportService
@Transactional
class KpiReportService {

    def serviceMethod() {
        return "Hello from KpiReportService"
    }
}

KpiReportController
class KpiReportController {
    def index() {
        def kpiReportService
        render kpiReportService.serviceMethod
        //render "Hello from KpiReportController"
    }
}

Exception
Grails application running at http://localhost:8080 in environment: development
ERROR org.grails.web.errors.GrailsExceptionResolver - NullPointerException occurred when processing request: [POST] /KpiReport/index
Cannot get property 'serviceMethod' on null object. Stacktrace follows:
java.lang.reflect.InvocationTargetException: null
        at org.grails.core.DefaultGrailsControllerClass$ReflectionInvoker.invoke(DefaultGrailsControllerClass.java:210)
        at org.grails.core.DefaultGrailsControllerClass.invoke(DefaultGrailsControllerClass.java:187)
        at org.grails.web.mapping.mvc.UrlMappingsInfoHandlerAdapter.handle(UrlMappingsInfoHandlerAdapter.groovy:90)
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:961)
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:895)
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
        at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869)
        at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
        at org.grails.web.servlet.mvc.GrailsWebRequestFilter.doFilterInternal(GrailsWebRequestFilter.java:77)
        at org.grails.web.filters.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:67)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException: Cannot get property 'serviceMethod' on null object
        at com.abc.project.KpiReportController.index(KpiReportController.groovy:7)
        ... 13 common frames omitted

Using postman for request

I am new to grails, please help me figure out what is going wrong, may be I am missing something.

A: The error message indicates you are referring to a property that does not exist.  Instead of render kpiReportService.serviceMethod you want render kpiReportService.serviceMethod().

A: Services are injected as class variables
class KpiReportController {
    def kpiReportService

    def index() {
        render kpiReportService.serviceMethod()
        //render "Hello from KpiReportController"
    }
}


text:
Q: How can i store images in an array and with a for loop print them? PHP I try to print images with a for loop but the images dont load.
<?php
$imagenes = array('1.png', '2.jpg', '3.png', '4.jpg','IMG_0105.JPG');
 ?>

        <?php
              for ($i=0; $i < 4; $i++) {
              echo '';
              }
         ?>

The images are in the same folder as the .php file

A: Use foreach for this. And for concatinate string with var - use . (dot)
       <?php
             foreach ($imagenes as $image) {
                echo '';
             }
        ?>

A: Edit: Added additional solutions based on answer from @nik
This will never work because variables are not evaluated inside of single quoted strings.
Make sure that your use a string inside double quotes. Or use string concatenation to build the HTML tag. Also, you image tag has a semicolon inside of it that might break the tag.
So you can do this ...
echo "";

or
echo "";

or
<img src="<?= $imagenes[$i]; ?>" width="100px" height="100px">

or
<img src="<?php echo $imagenes[$i]; ?>" width="100px" height="100px">

A: This would make it simplier:

      <?php foreach ($imagenes as $url) { ?>
        <img src="<?php echo $url ?>" width="100px" height="100px">
      <?php } ?>

A: I think its the way you're escaping the characters, you can just use concatenation on $images:

            <?php
            for ($i=0; $i < 4; $i++) {
                echo '';
            }
            ?>


text:
Q: How to change "Return to sellers.email@somemail.com" to "Return to Seller's Business Name" in Woocommerce? I'm using Woocommerce for my current project. Everything is okay. But, when a customer purchases and makes payment through PayPal, PayPal shows messages with Seller's email address. Example:
Before payment:http://i.stack.imgur.com/fk78l.png
After payment http://i.stack.imgur.com/h252d.png
Is there anybody to help?

A: You will need to update your business name inside your paypal account.
Note : Your personal account cannot have a business name. Need to have a Business account.

*

*login to your business account at www.paypal.com

*My Account->My selling tools->My business information.

*Update your business name.


text:
Q: Table values blank in JSF JSF excerpt:
<h:dataTable border="1" cellspacing="10">
 <h:column>
    <f:facet name="header">Order No</f:facet>
    <h:outputText value="FirstEntry" />
 </h:column>

 <h:column>
    <f:facet name="header">Product Name</f:facet>
    #{userBean.firstName}
 </h:column>

 <h:column>
    <f:facet name="header">Email</f:facet>
    #{userBean.email}
 </h:column>
</h:dataTable>

Gives me this in html:

   Order No
   Product Name
   Email

The table always comes as an empty table with headers and nothing in rows. According to JSF tutorials this should work. As you can see i have tried several options of putting values in table( using outputText, using a bean, tried typing some casual text without tags, putting the text in quotes, using value=). Everytime the outcome is same. What am i doing wrong?

A: You don't have a value attribute in your h:datatable
See for example MyFaces JSF implementation: https://myfaces.apache.org/core21/myfaces-impl/tagdoc/h_dataTable.html

Attrivute name: value
  Attribute type: Object
An EL expression that specifies the data model that backs this table.
The value referenced by the EL expression can be of any type.

*

*A value of type DataModel is used directly.

*Array-like parameters of type array-of-Object, java.util.List, java.sql.ResultSet or javax.servlet.jsp.jstl.sql.Result are wrapped in a corresponding DataModel that knows how to iterate over the elements.

*Other values are wrapped in a DataModel as a single row.

  Note in particular that unordered collections, eg Set are not
  supported. Therefore if the value expression references such an object
  then the table will be considered to contain just one element - the
  collection itself.

P.S. If you don't have a collection of elements for your table why do you need h:datatable? You might as well use html.


text:
Q: Rutherford scattering in Quantum Mechanics terms? Rutherford scattering stands as the first evidence of atoms having the positive charge concentrated in a small nucleus.
While the classical description of the phenomenon is satisfactory, it puzzles me that no description from Quantum Mechanics point of view appears to exist.
Is there any? Or could someone elaborate one? At least the starting points maybe, no need for a fully coherent deduction although it would be very welcome.

A: Rutherford scattering is simply elastic scattering in a Coulomb potential. This process can, of course, be treated quantum mechanically, and this is described in any QM text book that covers scattering theory.
There is a strange accident which is that the differential cross section computed classically agrees exactly with the quantum mechanical results. This is ultimately broken by relativistic corrections, higher order QED effects etc, but the leading 1/$\sin(\theta/2)^4$ is the same classically and quantum mechanically.  Of course, Rutherford had no way to know this, so he got a little lucky with his classical formula.

A: Rutherford scattering is electric at energies lower than 28 MeV, the alpha particle total binding energy. The alpha particles are destroyed, freeing the magnetic moments of the nucleons. Therefore the not so anomalous is magnetic as shown below:


text:
Q: GMSMapView display whole world map? I am adding my map view like
mapView_ = [[GMSMapView alloc]initWithFrame:_viewMapContainer.bounds];
mapView_.myLocationEnabled = YES;
mapView_.frame = _viewMapContainer.bounds;
[_viewMapContainer addSubview: mapView_];

In my application this view is only for displaying the whole map of the world and some markers. I am unable to display the whole world in one view.Any help will be appreciable ,I don't want the user interactions on it

A: I have also faced this problem
- (void)focusMapToShowAllMarkers
{
CLLocationCoordinate2D myLocation = ((GMSMarker *)_markers.firstObject).position;
GMSCoordinateBounds *bounds = [[GMSCoordinateBounds alloc] initWithCoordinate:myLocation coordinate:myLocation];

for (GMSMarker *marker in _markers)
    bounds = [bounds includingCoordinate:marker.position];

[_mapView animateWithCameraUpdate:[GMSCameraUpdate fitBounds:bounds withPadding:15.0f]];
}

Please try this and share the response.
happy coding :)


text:
Q: JSF 2 dynamic form and bean validation JSR 303 I generate a dynamic form starting from annotated bean. The same bean is annotated for validation using Hibernate Validator.
The form is correctly rendered but when the form is submitted the validation step it's not executed. If I write the same form with jsf tag the validation works properly.
Any idea?
The form page:

    <ui:composition template="/template/basetheme_one_col.xhtml">
        <ui:define name="title">#{__g4cController.entityClassName}</ui:define>

        <ui:define name="main_area">

#{__g4cController.entityClassName}

                <h:form id="briciole_pane_form"  styleClass="form">
                    <h:commandLink action="home" value="Home" />
                    <h:outputText value=" / " />
                    Modifica #{__g4cController.entityClassName}
                </h:form>

            <h:form id="edit_record"  styleClass="myForm">
                <rich:calendar rendered="false" />

Modifica #{__g4cController.entityClassName}

                <h:messages errorClass="error_msg" layout="list" globalOnly="false" />

               <h:panelGrid binding="#{__g4cController.dynamicForm}" />

                        <h:commandLink action="#{__g4cController.edit}" value="Salva Modifiche">
                            <f:param name="cruddao.objectKey" value="#{g4c:getXmlFromObject(__g4cController.entity.id)}" />
                        </h:commandLink>

                    <h:commandLink action="#{__g4cController.listSetup}" styleClass="link_annulla_rosso"
                                   value="Annulla e torna a lista #{__g4cController.entityClassName}" immediate="true" />

           </h:form>

        </ui:define>
    </ui:composition>

Code that generate the form starting from EntityBean
    public UIComponent getDynamicForm() {
    FacesContext ctx = FacesContext.getCurrentInstance();
    Application app = ctx.getApplication();
    HtmlPanelGrid panel = (HtmlPanelGrid) app.createComponent(HtmlPanelGrid.COMPONENT_TYPE);
    panel.setColumns(2);

    Class currentClass = super.entityClass;
    while(!currentClass.equals(Object.class)) {
        Field fields[] = currentClass.getDeclaredFields();
        for(Field field: fields) {
            Annotation id = field.getAnnotation(Id.class);
            Annotation embeddedId = field.getAnnotation(EmbeddedId.class);
            OneToMany oneToMany = field.getAnnotation(OneToMany.class);
            ManyToMany manyToMany = field.getAnnotation(ManyToMany.class);
            Transient transientTag = field.getAnnotation(Transient.class);
            Temporal temporal = field.getAnnotation(Temporal.class);

            if(id == null && embeddedId == null && oneToMany == null && manyToMany == null && transientTag == null) {
                int modifiers=field.getModifiers();
                if(!Modifier.isStatic(modifiers)) {
                    HtmlOutputLabel label = (HtmlOutputLabel) app.createComponent(HtmlOutputLabel.COMPONENT_TYPE);

                    String name = field.getName();
                    Class clazz = field.getType();

                    panel.getChildren().add(label);
                    label.setFor(name);
                    label.setValue(StringUtil.capitalize(name)+":");

                    String expression = "#{__g4cController.entity."+name+"}";
                    ValueExpression valueExpression = app.getExpressionFactory()
                            .createValueExpression(ctx.getELContext(),
                                    expression,
                                    clazz);

                    ManyToOne manyToOne = field.getAnnotation(ManyToOne.class);
                    if(manyToOne != null) {
                        HtmlSelectOneMenu input = (HtmlSelectOneMenu) app.createComponent(HtmlSelectOneMenu.COMPONENT_TYPE);
                        input.setId(name);
                        input.setValueExpression("value", valueExpression);
                        input.setLabel(name);

                        UISelectItems items = (UISelectItems) app.createComponent(UISelectItems.COMPONENT_TYPE);
                        input.getChildren().add(items);
                        String manyToOneClassName = field.getType().getSimpleName().toLowerCase();
                        String itemsExpression = "#{"+manyToOneClassName+".entityListSelectOne}";
                        ValueExpression itemsValueExpression = app.getExpressionFactory()
                                .createValueExpression(ctx.getELContext(),
                                        itemsExpression,
                                    SelectItem[].class);
                        items.setValueExpression("value", itemsValueExpression);
                        panel.getChildren().add(input);
                    } else {
                        if(temporal != null) {
                            if(temporal.value().equals(TemporalType.DATE)) {
                                UICalendar input = (UICalendar) app.createComponent(UICalendar.COMPONENT_TYPE);
                                input.setId(name);
                                input.setValueExpression("value", valueExpression);
                                input.setDatePattern("dd/MM/yyyy");
                                //input.setConverter(new DateConverter());
                                panel.getChildren().add(input);
                            }
                        } else {
                            HtmlInputText input = (HtmlInputText) app.createComponent(HtmlInputText.COMPONENT_TYPE);
                            input.setId(name);
                            input.setValueExpression("value", valueExpression);
                            input.setLabel(name);
                            input.setSize(50);
                            input.setMaxlength(255);
                            panel.getChildren().add(input);
                        }

                    }
                }
            }
        }
        currentClass = currentClass.getSuperclass();
    }
    return panel;
}

A Entity Bean example:
@Entity

public class Istituto implements Serializable, IBaseEntity {
    private static final long serialVersionUID = 1L;
@Id
@SequenceGenerator(name="IstitutoGenerator", sequenceName="ISTITUTO_SEQ", allocationSize=1)
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="IstitutoGenerator")
@Column(name="ID_ISTITUTO")
private int idIstituto;

@NotNull
private String nome;

@NotNull
private String indirizzo;

@NotNull
private String comune;

@NotNull
@Pattern(regexp="[0-9][0-9][0-9][0-9][0-9]", message="Il CAP deve essere composto da 5 numeri")
private String cap;

@OneToMany(mappedBy="istituto")
private Set<Classe> classes;

public Istituto() {
}

public int getIdIstituto() {
    return this.idIstituto;
}

public void setIdIstituto(int idIstituto) {
    this.idIstituto = idIstituto;
}

public String getCap() {
    return this.cap;
}

public void setCap(String cap) {
    this.cap = cap;
}

public String getComune() {
    return this.comune;
}

public void setComune(String comune) {
    this.comune = comune;
}

public String getIndirizzo() {
    return this.indirizzo;
}

public void setIndirizzo(String indirizzo) {
    this.indirizzo = indirizzo;
}

public String getNome() {
    return this.nome;
}

public void setNome(String nome) {
    this.nome = nome;
}

public Set<Classe> getClasses() {
    return this.classes;
}

public void setClasses(Set<Classe> classes) {
    this.classes = classes;
}

@Override
public Integer getId() {
    return this.getIdIstituto();
}

@Override
public int hashCode() {
    int hash = 0;
    hash += this.getIdIstituto();
    return hash;
}

@Override
public boolean equals(Object object) {
    if (!(object instanceof Istituto)) {
        return false;
    }
    Istituto other = (Istituto) object;
    if  (this.getIdIstituto() != other.getIdIstituto()) {
        return false;
    }

    return true;
}

@Override
public String toString() {
    return this.getNome();
}

}

A: You have to add an instance of javax.faces.validator.BeanValidator to your input components:
input.addValidator(new BeanValidator());

The reason is that default validators (BeanValidator is registered as one) are added during tag execution: http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-635.


text:
Q: Angular routing same path different guard I want to use the same path ticket because I want to redirect when save something (Use same component to Update Ticket ).
But there is a problem with canActivate.  What is the best way to fix it?
const router: Routes = [
  {
    path: '',
    component: HomeLayoutComponent,
    canActivate: [AuthGuard],
    children: [
      {
        path: '',
        component: HomeComponent
      },
      {
        path: 'ticket',
        canActivate: [SupportGuard],
        component: TicketComponent
      },
      {
        path: 'ticket',
        canActivate: [CustomerGuard],
        component: SiteTicketComponent
      },
      ....
    ]
  },
  {
    path: '',
    component: LoginLayoutComponent,
    children: [
      {
        path: 'login',
        component: LoginComponent
      },
      {
        path: 'signup',
        component: SignupComponent
      },
    ]
  },
  {
    path: '**',
    component: Error404Component
  }
]

Thanks in advance.

A: I had a similar issue.
The solution would be to introduce a parent component BaseComponent for the two routes, and inside this component perform a router.navigate meaning:
const router: Routes = [
   {
    path: '',
    component: BaseComponent,
    children: [
      {
       path: '',
       component: HomeLayoutComponent,
       canActivate: [AuthGuard],
       children: [
      ...
       ]
     },
     {
       path: '',
       component: LoginLayoutComponent,
       children: [
      ...
       ]
     },
    ...
   ]}

And inside the BaseComponent:
ngOnInit(): void {
    if (theCondition) {
      this.router.navigate(['./one-path'], { relativeTo: this.route });
    } else {
      this.router.navigate(['./other-path'], { relativeTo: this.route });
    }
}


text:
Q: How to execute sql TRIGGER automatically after every 5 seconds in SQL SERVER? I want to make a stored procedure by which a Triggers will automatically execute after 5 seconds to check/show whether new row is updated or not.
I have a table called 'Inbox' in Database. I made a trigger for this whenever data in inserted in table.
CREATE TRIGGER tr_Inbox_ForInsert
ON Inbox
FOR INSERT
AS
BEGIN
SELECT * FROM inserted
END

I just want this trigger to execute itself after 5 seconds

A: That's not how triggers work... They are run after a transaction is carried out on the object they are attached to.
If you want something to run every X time interval, look into SQL Server Agent Jobs instead


text:
Q: Cardinality constrained portfolio in MATLAB I am working on portfolio optimization. With MATLAB help I have calculated the risk of portfolio given the expected return with quadprog. Now I want to add cardinality constraints in it, which makes it a mixed integer programming.
I have seen the MATLAB help for mixed integer programming and gaoptimset, which says that if we are having integer constraint than we can not specify the equality constraints.
But I have two equality constraints

*

*Summation of weights = 1
w(1) + w(2) + w(3) + .... + w(n) = 1

*Cardinality Constraint
support(w) = K
Can somebody please help me in NONLINEAR MIXED INTEGER PROGRAMMING


text:
Q: Преобразование даты между строковыми представлениями Мне приходят данные в виде 'Март 1, 2010', 'Сен. 1, 2010' и т.п. Меняю им вид вот так:
def date_convertion(datetime):
    res = datetime.split(' ')
    res.reverse()
    return (res[0] + '-' + res[2][:-1] + '-' + res[1][:-1])

datetime получаю вот такой:
['Март 1, 2010']

на выходе функции это уже вот так:
['2010-Март-1']

Вопрос: как "Март" преобразовать в "03"? Создать словарь (он же ассоциативный массив) и искать по ключу значение или можно это сделать иначе?

A: При преобразовании из одного строкового формата в другой, особенно если входной формат нефиксированный и возможны вариации, то полезно использовать промежуточный объект-дату, чтобы убедиться что значения были интерпретированы корректно.
входная строка -> объект-дата -> выходная строка

Например:
datetime.strptime("входная строка", "формат") ->
datetime объект ->
dt.strftime("формат вывода")

setlocale() вариант
Если русская локаль установлена для программы или известно её название на данной платформе, то можно её активировать и попробовать распознать входные строки, используя фиксированный список форматов:
#!/usr/bin/env python3
import locale
from datetime import datetime

locale.setlocale(locale.LC_TIME, 'ru_RU.UTF-8') # the ru locale is installed

date_strings = ['Март 1, 2010', 'Сен. 1, 2010', '2015-Апрель-26']
print(date_strings)
date_formats = '%B %d, %Y',    '%b %d, %Y',    '%Y-%B-%d'

dates = []
for date_str in date_strings:
    date_str = date_str.replace('Сен.', 'Сент.') # fix the abbr.
    for date_fmt in date_formats:
        try:
            dates.append(datetime.strptime(date_str, date_fmt).date())
        except ValueError:
            pass
        else:
            break
    else:
        print('failed to parse %r' % date_str)

output_date_strings = list(map(str, dates))
print(output_date_strings)

Вывод
['Март 1, 2010', 'Сен. 1, 2010', '2015-Апрель-26']
['2010-03-01', '2010-09-01', '2015-04-26']

ICU вариант
Если есть возможность установить PyICU, то можно использовать несколько локалей независимо от наличия соответствующей системной локали и без изменения глобального состояния программы (может быть полезно в многопоточном приложении) [синтакс ICU форматов для времени]:
#!/usr/bin/env python3
from datetime import datetime
import icu # PyICU

date_strings = ['Март 1, 2010', 'Сен. 1, 2010', '2015-Апрель-26']
print(date_strings)

df = icu.SimpleDateFormat('', icu.Locale('ru'))
output_df = icu.SimpleDateFormat('yyyy-MM-dd')

output_date_strings = []
for date_str in date_strings:
    date_str = date_str.replace('Сен.', 'Сент.') # fix the abbr.
    for pattern in 'LLLL d, yyyy', 'yyyy-LLLL-dd':
        df.applyPattern(pattern)
        try:
            output_date_strings.append(output_df.format(df.parse(date_str)))
        except icu.ICUError:
            pass
        else:
            break
    else:
        print('failed to parse %r' % date_str)

print(output_date_strings)

Результат такой же как у первой программы.
str.replace() вариант
Если входные данные более разнообразны, то можно ещё добавить предварительный шаг, который сделает их более регулярными, например, как date_str.replace() выше (можно словарь использовать со списком замен). Например, можно избавиться от зависимости на локаль, заменяя все названия соответствующими цифрами:
for old, new in [('Март', '3'), ('Сен.', '9'), ('Апрель', '4')]:
    date_str = date_str.replace(old, new)

После этого можно использовать datetime.strptime() c '%m %d, %Y', '%Y-%m-%d' форматами без setlocale() вызова.

A: Кратко
Многое в решении вашей проблемы зависит от формата строки.
Если названия месяцев соответствуют русской локали и записаны либо полностью, либо сокращённо до трёх букв, то можете воспользоваться стандартной библиотекой datetime. В противном случае, если единого формата нет, можете задать словарь замен. Например (для двух месяцев):
month = {'Март': '03', 'Апр.': '04'}

Использовать его в вашем случае легко: month[res[2][:-1]].
Небольшое замечание. Решение с использованием reverse и split, конечно, работоспособно, но не очень хорошо читается. Я бы использовал на вашем месте регулярные выражения. Тогда при замене формата строки изменения в программе будут минимальными.
Замена с помощью datetime
Для начала задайте локаль (достаточно один раз в начале программы). Если у вас система уже настроена на русский язык, то достаточно выполнить следующие команды:
import locale
locale.setlocale(locale.LC_ALL, '')

Если язык системы другой, то вместо пустых кавычек укажите требуемую локаль.
При помощи метода strptime вы можете проанализировать строку на соответствие некоторому формату.
Пример:
from datetime import datetime
d = datetime.strptime("Апр. 6, 2015", "%b. %d, %Y")
print(d)

2015-04-06 00:00:00

Здесь %b — краткое название месяца в текущей локали, %d — номер дня, %Y — номер года (4 цифры).
В переменной d будет находиться экземпляр класса datetime, который можно привести к любому другому виду.
В вашем случае:
print(d.strftime('%Y-%m-%d'))

2015-04-06

Перечисленный операции можно объединить в одну функцию и использовать её для добавления элементов в список:
def date_convert(s):
    return datetime.strptime(s, "%b. %d, %Y").strftime('%Y-%m-%d')

[date_convert(d) for d in dates]

Здесь dates — список строк, хранящих даты в указанном вами формате.
Если требуется одновременно использовать две локали, то действия с датами можно выполнять, например, внутри with написав контекстный процессор.
Библиотека datetime

A: Добавление элемента в список или в ассоциативный массив
Добавление элемента в список производится с помощью функции append:
my_list.append( new_element )

Другой способ:
my_list += [ new_element ]

Добавление в ассоциативный массив выполняется так:
my_dict.update({ new_key : new_element })

или ещё проще:
my_dict[ new_key ] = new_element

Это если говорить в общем. У вас же вопрос немного туманный и не совсем понятно, что вы пытаетесь сделать.
Преобразование даты между форматами
Преобразование даты осуществляется обычно с помощью функции strptime, которая из вашей строки сделает объект даты, с которым можно выполнять дальнейшие манипуляции, в том числе форматирование в другой формат.
Это будет выглядеть так:
  d = datetime.datetime.strptime(d_string, fmt)
  d_string2 = d.strfime(fmt2)

В данном случае я преобразовал исходную строку d_string из формата fmt в формат fmt2, результат записан в d_string2.
(правда это к спискам не имеет никакого отношения).

A: import functools, datetime, icu

_Replace = [('фев', 'февр'), ('ноя', 'нояб'), ('май', 'мая'), ('сен', 'сент'), ]
MonthReplace = (_Replace + [(s.capitalize(), r) for (s, r) in _Replace])  # для автозамены + capitalize
AllLocales = (En, Ru,) = list(map(icu.Locale, ['en', 'ru', ]))
TZ = icu.ICUtzinfo.getDefault()  # time zone, ~ в 2012г была другая, эти даты парсит на час назад
s_rus = 'авдимнопсфчя'  # первые буквы имен месяцев и недель
S_Rus = set(s_rus + s_rus.upper())
IcuDateMasks = ['dd/MMM/yy HH:mm:ss', 'dd/MMM/yy HH:mm', 'EEE, dd MMM y HH:mm:ss', 'EEE, dd MMM y HH:mm', 'EEE, dd MMM y', 'EEE MMM dd HH:mm:ss y', ]  # http://userguide.icu-project.org/formatparse/datetime
DateMaskForIcu = {(mask, lcl): icu.SimpleDateFormat(mask, lcl) for mask in IcuDateMasks for lcl in AllLocales}

@functools.lru_cache()
def str_to_datetime(datetime_str: str) -> 'datetime.datetime':
    (dtime_str, lcl) = _find_locale(datetime_str.split('+', 1)[0].strip())
    for mask in IcuDateMasks:  # выбрать правильный формат маски
        try: return datetime.datetime.fromtimestamp(icu.DateFormat.parse(DateMaskForIcu[mask, lcl], dtime_str), TZ, ).replace(tzinfo=None)
        except icu.ICUError: continue
    raise UserWarning(f'"{dtime_str}" не распознана в локали "{lcl}", ни по одной из масок "{IcuDateMasks}" !!!')

def _find_locale(datetime_str: str) -> (str, 'icu.Locale'):
    if any((s in datetime_str) for s in S_Rus):  # рус locale
        for (s, r) in MonthReplace:
            if s in datetime_str:
                datetime_str = datetime_str.replace(s, r, 1)  # 'правильные' имена месяцев
                break
        return datetime_str, Ru
    else: return datetime_str, En

if __name__ == '__main__':
    print(str_to_datetime('04/июн/12 11:56'))  # 2012-06-04 11:56:00
    print(str_to_datetime('15/Jan/19 2:49'))  # 2019-01-15 02:49:00
    print(str_to_datetime('15/Фев/19 20:42:01'))  # 2019-02-15 20:42:01
    print(str_to_datetime('Пт, 02 ноя 2018 14:26:00'))  # 2018-11-02 14:26:00


text:
Q: how to get fabricJS to work with touch events? I have an application developped with phonegap and I am testing the touch support for fabricJS but somehow it doesn't work for me.
I tried creating a custom version here but it doesn't work with it.
I have this jsfiddle where I used another version called fabric_events.js but it doesn't seems to work too. (BTW how do you upload your own version to jsfiddle?)
so I tried the FabricJS touch events demo and it DOES work!!
since the demo worked I tried to download it's own version from http://fabricjs.com/lib/fabric_with_gestures.js but still no luck.
this is my code:
    <!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="initial-scale=1, width=device-width, user-scalable=true" />

    <title></title>

    <canvas id="c" width="200" height="200" style='z-index:-1'></canvas>

A: Sorry for the late answer. I am working with Fabric.js at the moment and I do not have any problems with gestures. I have tried your code, it is generally working if you care for three things:
1.) Very important: Please remove style='z-index:-1' from the canvas itself. The z-index property specifies the stack order of an element and a negative number will not allow you to interact with the canvas in your example. More information: CSS z-index Property.
2.) Are you sure that you had created a Custom Build with "Interaction" and "Gestures"? "Gestures" is dependent on "Interaction". If you are unsure, create a Custom Build with all modules except "Node" (unless you want to use Node.js later).
3.) Fabric.js and jQuery must be in the subfolder 'js' regarding to your code. But I would think that it was like that already.
Then it should work for you, too.


text:
Q: A Better way of doing Fade Out with PHP I amc creating A Login script with php and javascript.
What I want to do is log the user in without the page refresh which I have archived so far, With some help from Stack Flow users, I am fairly good with PHP but new to the Javascript client side.
Anyway, When the user enters the correct data and the session gets started how do I get it to call the fade out function?
Heres the PHP Side
<?php
    require "../core/database.php";

    //lets create some veriables to use, This way is shorter
    $username = strip_tags(trim($_POST['user_login']));
    $password = strip_tags(trim($_POST['pass_login']));
    $md5_pass = md5($_POST['pass_login']);

    $user_login = mysql_real_escape_string($username);
    $pass_login = mysql_real_escape_string($md5_pass);

    if (($user_login) && ($password)) {
    //Connect to the database to fetch the users username and password
    $select_user = mysql_query("SELECT username,password FROM users WHERE username='$user_login' AND password='$pass_login'");
    $user_rows = mysql_fetch_array($select_user);
    $username_row = $user_rows['username'];
    $password_row = $user_rows['password'];

        if(($username_row==$user_login)  && ($md5_pass==$password_row)) {
        //All user information is correct, Now start the session

        //I HAVE CALLED IT HERE HOPING THERE,S A BETTER WAY OF DOING THIS. IT WILL CAL
        echo "
        Yes, Now we can start the session right here, when your ready.

        ";

        } else {

        echo "The username or password you entered is incorrect";
        }

    } else {
    echo "Blank Fields

    You must enter A Username/Password Combination";
    }

?>

Incase yous need it, there is the client side aswill (modified by some users to make the functionality better)
$(document).ready(function() {
    // Make a function that returns the data, then call it whenever you
    // need the current values
    function getData() {
        return {
            user_login: $('#user_login').val(),
            pass_login: $('#pass_login').val()

        }
    }

        function loading(e) {
        $('#content').html('Loading Data');
    }

    function check(e) {
        e.preventDefault();
        $.ajax({

            url: 'ajax/check.php',
            type: 'post',
            data: getData(), // get current values
            success: function (data) {
                $('#content').html(data);
            }
        });
    }

    // Don't repeat so much; use the same function for both handlers
    $('#field').keyup(function(e) {
        if (e.keyCode == 13) {
    var username = $('#user_login').val();

        loading(e);
        check(e);

        }
    });

    $('#submit').click(function(e) {
        if (e.keyCode != 13) {
        loading(e);
        check(e);
        }

    });

});

Since PHP is Server Side and Java Script controls the Client side, Probably the best way to do or call it is this way, But its worth A ask anyway.

Besides this everything is working out well.
If you want you can help change the way loading data is coded/works, But the functionality is working perfectly so theres not much need.

A: The ajax success method needs to check the response from the server to see if login was successful and then take the appropriate action:
// php
if(($username_row==$user_login)  && ($md5_pass==$password_row)) {
            //All user information is correct, Now start the session

            echo 'correct';

            } else {

            echo 'The username or password you entered is incorrect';
            }

// js
function check(e) {
        e.preventDefault();
        $.ajax({
            url: 'ajax/check.php',
            type: 'post',
            data: getData(), // get current values
            success: function (data) {
                if (data === 'correct') {
                  $('#field').fadeOut();
                } else {
                  $('#content').html(data);
                }
            }
        });
    }

A: Returning JSON instead of raw HTML is much more flexible. Quick example:
PHP Side
<?php
require "../core/database.php";

$json = array('success' => false, 'error' => null);

$username = strip_tags(trim($_POST['user_login']));
$password = strip_tags(trim($_POST['pass_login']));
$md5_pass = md5($_POST['pass_login']);

$user_login = mysql_real_escape_string($username);
$pass_login = mysql_real_escape_string($md5_pass);

if (($user_login) && ($password)) {

    $select_user = mysql_query("SELECT username,password FROM users WHERE username='$user_login' AND password='$pass_login'");
    $user_rows = mysql_fetch_array($select_user);
    $username_row = $user_rows['username'];
    $password_row = $user_rows['password'];

    if(($username_row==$user_login)  && ($md5_pass==$password_row)) {
        $json['success'] = true;
    }
    else {
        $json['error'] = "The username or password you entered is incorrect";
    }

} else {
    $json['error'] = "Blank Fields
You must enter A Username/Password Combination";
}

echo json_encode($json);

Your AJAX function:
function check(e) {
    e.preventDefault();
    $.ajax({

        url: 'ajax/check.php',
        type: 'post',
        data: getData(), // get current values
        success: function (data) {
            var loginResult = JSON.parse(data);
            if(loginResult.success){

                //Login successful - fade out whatever form or fields
                //that you want to
                $('#field').fadeOut();

            } else{
                //Add error message to an error div or whatever
                $('#error').html(loginResult.error);
            }
        }
    });
}

A: I'll start by saying that your PHP should be using the newer mysqli_* functions or the PDO object for all of your database queries. Further, you should be using prepared statements which will safeguard you against SQL injection attacks.
Another thing to note is that in a PHP file that is not going to output anything to the browser, or in other words, is just going to run some code, you don't need a closing tag. In fact, you don't want a closing tag. That is because anything after the closing tag will get sent to the browser, which will get included in the response of your AJAX success function. That includes things like spaces and new lines.
Now, on to your PHP. You are going to want to output some JSON so that you can check for success or failure in your AJAX.
PHP
<?php
    require "../core/database.php";

    //lets create some veriables to use, This way is shorter
    $username = strip_tags(trim($_POST['user_login']));
    $password = strip_tags(trim($_POST['pass_login']));
    $md5_pass = md5($_POST['pass_login']);

    $user_login = mysql_real_escape_string($username);
    $pass_login = mysql_real_escape_string($md5_pass);

    //Create an array to represent our JSON data.
    $json = array(
        "successCode" => 0
    );

    if (($user_login) && ($password)) {
        //Connect to the database to fetch the users username and password
        $select_user = mysql_query("SELECT username,password FROM users WHERE username='$user_login' AND password='$pass_login'");
        $user_rows = mysql_fetch_array($select_user);
        $username_row = $user_rows['username'];
        $password_row = $user_rows['password'];

        if(($username_row==$user_login)  && ($md5_pass==$password_row)) {
            //All user information is correct, Now start the session
            //echo "Yes, Now we can start the session right here, when your ready."
            $json['successCode'] = 0;
        } else {
            //echo "The username or password you entered is incorrect";
            $json['successCode'] = 1;
        }

    } else {
        //echo "Blank Fields

        //You must enter A Username/Password Combination";
        $json['successCode'] = 2;
    }

    //Set that our content type is JSON
    header("Content-type: application/json");
    echo json_encode($json); //Convert the PHP array to JSON and echo it as the response.

In our PHP, we have created a $json array which will story the successCode that we will be responding to the client. This will tell the client if the login was a success or failure, and even what type of failure occurred. It will then be up to the client to decide how to display that success or failure to the user. This allows multiple applications to use the same server side source, but display the errors differently if desired.
At the end of the PHP, we have set the header Content-type to specify that we are sending back application/json to the client. Then, we encode the PHP array as JSON, and output it to the response.
jQuery/Javascript
//Let's define different messages depending on what status code we get on the client.
var errorMessages = [
    "Yes, Now we can start the session right here, when your ready.",
    "The username or password you entered is incorrect",
    "Blank Fields
You must enter A Username/Password Combination"
];

function check(e) {
    e.preventDefault();
    $.ajax({
        url: 'ajax/check.php',
        type: 'post',
        data: getData(), // get current values
        success: function (data) {
            //First, make sure that data and data.successCode are defined.
            if (data && data.successCode) {
                //Here, you are getting back the JSON data from the login call.
                $('#content').html(errorMessages[data.successCode]);

                //If the successCode is 0, which means it was successful, then we want to fade out the #field div.
                if (data.successCode == 0) {
                    $('#field').fadeOut();
                }
            } else {
                //There must've been a server error. You'd handle that here.
            }
        }
    });
}

Why put the error messages on the client instead of the server? Because it allows you to easily change how the error messages are displayed, without having to touch the server side code. The server just outputs an error code, and the client decides how to handle that code.
The Javascript array, errorMessages, defines the error messages corresponding to their index in the array. The error message at index 0 would correspond to successCode = 0, and so on. If you weren't going to use sequential successCodes, you could use a javascript object to specify keys corresponding to each error code.


text:
Q: Zero velocity field inside an ellipse I'm investigating the velocity field induced by a continuous distribution of 2D vortex points distributed along an ellipse $\{a\cos\theta,b\sin\theta\}$. I'm interested in the field inside the ellipse, and I need some help to prove whether this field is zero or not.
The intensity of each vortex point is proportional to $d\theta$ and not to the length along the ellipse. A vortex point located at a point $\boldsymbol{x'}$ induces a velocity field $\boldsymbol{u}(\boldsymbol{x})=\frac{d\theta}{2\pi |\boldsymbol{x}-\boldsymbol{x'}|} \boldsymbol{e}_\perp$ where ${e}_\perp$ is the unitary vector orthogonal to $(\boldsymbol{x}-\boldsymbol{x'})$ which is in 2D: $\boldsymbol{e}_z\times(\boldsymbol{x}-\boldsymbol{x'})/|\boldsymbol{x}-\boldsymbol{x'}|$.
The total velocity field at a point $(x,y)$ inside the ellipse is obtained by integration over $\theta$. Numerical experiments seem to show that the field is zero inside the ellipse, but I cannot prove it. Dropping the factor $2\pi$, the field is in cartesian coordinates:
$$\boldsymbol{u}=\int_0^{2\pi} \left\{\frac{-y + b \sin\theta}{(x - a \cos\theta)^2 + (y -
     b \sin\theta)^2}, \frac{x - a \cos\theta}{(x - a \cos\theta)^2 + (y -
     b \sin\theta)^2}\right\} d\theta \stackrel{?}{=}\{0,0\}$$
Is the field really zero?
Maybe there is no need for the integrals to prove it. Maybe complex analysis is of help?
I should mention that the following property is true in this problem: For any closed contour inside the ellipse the circulation is zero:
$$\oint \boldsymbol{u}\cdot\boldsymbol{dl} =0$$
Since we are in a simply connected region, the velocity is the gradient of a potential which is single valued. But then is this potential constant?...
I'm able to prove that the velocity is zero on both the $x$ and the $y$ axis. Also $u_x$ is an even function of $x$ and an odd function of $y$. The opposite applies for $u_y$. I'm able to prove the result for a circle $a=b$.
Can somebody help me for the ellipse? Any idea?

A: The answer was given by another user on another forum:
https://physics.stackexchange.com/questions/81300/velocity-field-induced-by-vortex-points-along-ellipse
The velocity field is zero inside the ellipse.


text:
Q: Casting Tab - Fullscreen Video While casting a tab, fullscreen videos will be resize to fit the current window. Is it possible to achieve this with a chrome extension?
What changes in the tab if you cast it? Is there some open-source code of the casting API?
Reproduce:

*

*Chromecast a tab with video inside.

*Fullscreen video.

*Video will be resize to fit window.


text:
Q: Load svg file from url on ImageView I have a URL of this type for the Jira REST API with no SVG extension or file name at the end of the URL.
When opened in a browser, it shows an image.
I want to show the image in an ImageView, but this is not appearing to be a file path from server.
I have studied about showing an SVG into ImageView from drawables here, but nothing about loading from these type of URLs.
I am using Volley (if that matters).
When I inspect the element in Chrome and see Network > Response tab, I can see Content-Type:image/svg+xml;charset=UTF-8.
How can I achieve showing image using this type of URL in an ImageView?

A: ImageView only accepts Bitmaps or VectorDrawables.
An SVG is neither of the two, even if VectorDrawable descends from it.
If you don't want to use an external library to transform the SVG into a Bitmap, then I can suggest you to use a WebView to display it

Alternatively, you might want to convert the SVG to a VectorDrawable by using a free online tool.

A: kotlin + Coil
add dependency:
//Coil (https://github.com/coil-kt/coil)
implementation("io.coil-kt:coil:1.2.0")
implementation("io.coil-kt:coil-svg:1.2.0")

add this function to your code:
fun ImageView.loadSvg(url: String) {

val imageLoader = ImageLoader.Builder(this.context)
    .componentRegistry { add(SvgDecoder(this@loadSvg.context)) }
    .build()

val request = ImageRequest.Builder(this.context)
    .crossfade(true)
    .crossfade(500)
    .placeholder(R.drawable.placeholder)
    .error(R.drawable.error)
    .data(url)
    .target(this)
    .build()

imageLoader.enqueue(request)
}

Then call this method in your activity or fragment:
imageView.loadSvg("your_file_name.svg")
// OR imageView.loadSvg(url)


text:
Q: Link Types for Plugins I'm new to Banno so I apologize if this is common knowledge but I couldn't find anything in the Banno knowledge base. I've looked at link types (https://knowledge.banno.com/apps/partnerintegrations/linktypes) that you over for plugins but couldn't find the one I was looking for. There are blue links above the Banno cards in the dashboard and I'm wondering if I have access to these links. I would like to create a link there for my application. Below is a screenshot of the links I'm talking about.

From what I understand, I have the ability to add my link there but only in the account details page. I would like to add my link to the dashboard page above the section containing the Banno Plugin Cards. Is this possible?

A: Not 100% certain about that specific location (on the Dashboard above the area where cards, both built-in and plugins, reside). Will check with Product & Engineering teams for clarity. Thank you very much for linking our doc...that helps narrow things down for us!


text:
Q: How to write for loop so that y_pr>=1 assign label 1 and y_pr<=-1 assign label -1? Given weights w=[8, 10] (1 by 2 vector) and b=-5 for a hyperplane w^Tx+b=0 and I want to use this hyperplane to classify the testing dataset X_te (51 by 2). For a data point x_i, the classification is based on if w^Tx_i+b >= 1 then assigns the label y=1 and if w^Tx_i+b <= -1 then assign the label y=-1.
I try the following code:
def cla(X,w,b):
    pre_te=np.zeros(len(X))
    length=X.shape[0]

    for i in range(length):
        y_pred=np.dot(np.array(X[i]),w.T)+b
        if y_pred>=1:
            pre_te[i]=1
        else:
            pre_te[i]=-1
    return pre_te

I can assign +1 to y_pred if y_pred>=1. How to add -1 to y_pred if y_pred<=-1 in the above for loop?
I do not think that write else: pre_te[i]=-1 work... There will be 0 in the output...

A: I think you need elif
for i in range(length):
        y_pred=np.dot(np.array(X[i]),w.T)+b
        if y_pred>=1:
            pre_te[i]=1
        elif y_pred<=-1:
            pre_te[i]=-1
    return pre_te


text:
Q: How can I make default a checkmark in the line "Don't create a Start Menu folder" -Inno Setup- I use Inno Setup as extractor for my Portable software (Windows). I want in the line "Do not create a Start Menu folder" to be checked by default, so that if the user wants a folder in the start menu he must uncheck the check box.
Thanks for your time and help,
Alexei

A: Programatically check the respective checkbox component (WizardForm.NoIconsCheck).
You should do it on fresh installs only. For upgrades/reinstalls, you should keep the previous user selection (more so, now that Inno Setup does not even show the Select Start Menu Folder wizard page for reinstalls).
procedure InitializeWizard();
begin
  if not IsUpgrade then
    WizardForm.NoIconsCheck.Checked := True;
end;

For the IsUpgrade function, see my answer to
Can Inno Setup respond differently to a new install and an update?


text:
Q: Reading > 1GB GZipped CSV files from external FTP server In a scheduled task of my Laravel application I'm reading several large gzipped CSV files, ranging from 80mb to 4gb on an external FTP server, containing products which I store in my database based on a product attribute.
I loop through a list of product feeds that I want to import but each time a fatal error is returned: 'Allowed memory size of 536870912 bytes exhausted'. I can bump up the length parameter of the fgetcsv function from 1000 to 100000 which solves the problem for the smaller files (< 500mb) but for the larger files it will return the fatal error.
Is there a solution that allows me to either download or unzip the .csv.gz files, reading the lines (by batch or one by one) and inserting the products into my database without running out of memory?
$feeds = [
    "feed_baby-mother-child.csv.gz",
    "feed_computer-games.csv.gz",
    "feed_general-books.csv.gz",
    "feed_toys.csv.gz",
];

foreach ($feeds as $feed) {
    $importedProducts = array();
    $importedFeedProducts = 0;

    $csvfile = 'compress.zlib://ftp://' . config('app.ftp_username') . ':' . config('app.ftp_password') . '@' . config('app.ftp_host') . '/' . $feed;

    if (($handle = fopen($csvfile, "r")) !== FALSE) {
        $row = 1;
        $header = fgetcsv($handle, 1, "|");

        while (($data = fgetcsv($handle, 1000, "|")) !== FALSE) {
            if($row == 1 || array(null) !== $data){ $row++; continue; }

            $product = array_combine($header, $data);
            $importedProducts[] = $product;
        }

        fclose($handle);
    } else {
        echo 'Failed to open: ' . $feed . PHP_EOL;
        continue;
    }

    // start inserting products into the database below here
}

A: The problem is probably not the gzip file itself,
Of course you can download it, on process it then, this will keep the same issues.
Because you are loading all products in a single array (Memory)
$importedProducts[] = $product;

You could comment this line out, and see it if this prevent's hitting your memory limit.
Usually i would create a method like this addProduct($product) to handle it memory safe.
You can then from there decide a max number of products before doing a bulk insert. to achieve optimal speed.. i usually use something between 1000 en 5000 rows.
For example
class ProductBatchInserter
{
    private $maxRecords = 1000;
    private $records = [];

    function addProduct($record) {
        $this->records[] = $record;
        if (count($this->records) >= $this->maxRecords) {
           EloquentModel::insert($this->records);
           $this->records = [];
        }
    }
}

However i usualy don't implement it as a single class, but in my projects i used to integrate them as a BulkInsertable trait that could be used on any eloquent model.
But this should give you an direction, how you can avoid memory limits.
Or, the easier , but significantly slower, just insert the row where you now assign it to array.
But that will put a ridiculous load on your database and will be really very slow.
If the GZIP stream is the bottleneck
As i expect this is not the issue, but if it would, then you could use gzopen()
https://www.php.net/manual/en/function.gzopen.php
and nest the gzopen handle as handle for fgetcsv.
But i expect the streamhandler you are using, is doing this already the same way for you..
If not, i mean like this:
$input = gzopen('input.csv.gz', 'r');

while (($row = fgetcsv($input)) !== false) {
 // do something memory safe, like suggested above
}

If you need to download it anyway there are many ways to do it, but make sure you use something memory safe, like fopen / fgets , or a guzzle stream and don't try to use something like file_get_contents() that loads it into memory


text:
Q: Caractere inválido em arquivo .bat Senhores !
Tenho um arquivo .bat que utilizo para iniciar o Apache Tomcat da minha aplicação em modo de debug. Porém ao executar este arquivo no CMD, a primeiro coisa exibida é a seguinte mensagem:
'´╗┐' não é reconhecido como um comando interno
ou externo, um programa operável ou um arquivo em lotes.
Ressalto que após isto, o script funciona normalmente, porém gostaria de saber se alguém já passou por algo semelhante ou conhece alguma solução. Eu havia tentado refazer o mesmo, porém o erro persiste.
Segue abaixo o conteúdo do arquivo:
@echo off

echo.

rd /s /q C:\tomcat\work\
rd /s /q C:\tomcat\conf\Catalina\
del /s /q C:\tomcat\logs\*
del /s /q C:\tomcat\temp\*
del /s /q C:\tomcat\webapps\sa\WEB-INF\web.xml.template
del /s /q C:\tomcat\webapps\sa\META-INF\context.xml.template

echo.

set CATALINA_HOME=C:\tomcat
set CATALINA_BASE=C:\tomcat
set JAVA_HOME=C:\java\jdk7
set INSTANCE=C:\instance

set CATALINA_OPTS=-Xms256m -Xmx512m -XX:MaxPermSize=256m

set CATALINA_OPTS=%CATALINA_OPTS% -Dfile.encoding=UTF-8
set CATALINA_OPTS=%CATALINA_OPTS% -Djava.awt.headless=false
set CATALINA_OPTS=%CATALINA_OPTS% -Dcom.sun.management.jmxremote
set CATALINA_OPTS=%CATALINA_OPTS% -Dcom.sun.management.jmxremote.port=9014
set CATALINA_OPTS=%CATALINA_OPTS% -Dcom.sun.management.jmxremote.ssl=false
set CATALINA_OPTS=%CATALINA_OPTS% -Dcom.sun.management.jmxremote.authenticate=false
set CATALINA_OPTS=%CATALINA_OPTS% -Dorg.apache.catalina.loader.WebappClassLoader.ENABLE_CLEAR_REFERENCES=false
set CATALINA_OPTS=%CATALINA_OPTS% -Duser.timezone=America/Sao_Paulo
set CATALINA_OPTS=%CATALINA_OPTS% -Duser.language=pt
set CATALINA_OPTS=%CATALINA_OPTS% -Duser.region=BR
set CATALINA_OPTS=%CATALINA_OPTS% -Dsun.java2d.noddraw=true
set CATALINA_OPTS=%CATALINA_OPTS% -Dsun.java2d.d3d=false
set CATALINA_OPTS=%CATALINA_OPTS% -Xdebug
set CATALINA_OPTS=%CATALINA_OPTS% -Xrunjdwp:transport=dt_socket,address=8990,server=y,suspend=n

%CATALINA_HOME%\bin\startup.bat

A: O seu arquivo possivelmente foi salvo com UTF-8 COM BOM (BOM sendo a abreviação de BYTE ORDER MARK) no bloco de notas, ou seja no topo do documento .bat ou qualquer tipo de documento, quando é salvo com UTF-8 BOM é adicionado um caractere chamado byte-order mark, que já foi citado em algumas perguntas aqui no site, mais detalhes sobre o BOM em utf-8 e outros como utf-32 em:

*

*https://pt.wikipedia.org/wiki/Marca_de_ordem_de_byte
Basicamente o seu .bat pensa que esse caractere chamado byte-order mark é um comando, no caso o caractere unicode U+FEFF é imprimido como ´╗┐, o .bat procura então um programa com tal nome, o que provavelmente não existe, ocasionando assim o erro de comando ou programa não reconhecido.
Criei um exemplo salvando em UTF-8 via Bloco de Notas do Windows:
@echo off

echo Oi

pause

No caso deixei uma linha antes do @echo off e logo ao executar ocorreu o mesmo erro:

Veja que é o mesmo caractere ´╗┐

Se deseja usar UTF-8 você deve salvar com UTF-8 sem BOM ou usar ANSI (ou qualquer formato compatível), vai depender da necessidade.
Se desejar ainda sim usar UTF-8 você deverá fazer uso de um programa mais avançado, como notepad++ que pode ser baixado em:

*

*https://notepad-plus-plus.org
Abra o seu .bat nele e salve assim:

Se utf-8 não for necessário para ti no proprio bloco de notas do windows selecione Salvar como... e selecione ANSI:

A: Possivelmente seu problema não esteja no batch, mas na página de caractere usada no sistema na pela interface do prompt/cli, sugiro dar uma verificada nas configurações das chaves:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Nls\CodePage
OEMCP="850"

Verifique se figura algo diferente de 850 ou 1252, caso esteja outro valor, é só mudar 850, ou 1252
Para verificar na linha de comando, use:
reg query "HKLM\SYSTEM\CurrentControlSet\Control\Nls\CodePage" | findstr "OEMCP"

rem :: o comando retorna a saída assim :: OEMCP    REG_SZ    850

Para alterar usando a linha de comando você pode usar o comando abaixo, observando que necessário executar como administrado:
reg add "HKLM\SYSTEM\CurrentControlSet\Control\Nls\CodePage" /v OEMCP /t reg_sz /d 850 /f

Já tive problemas quando precisava da exibição de um caractere que figurava no chcp 65001, após eu mudar o valor na chave, retornando para o padrão chcp 850, meus batchs pararam de exibir essa mesma mensagem com estes caracteres..
tem post que me ajudaram:
esse foi 1
esse foi outro


text:
Q: Prevent previous window from opening in Sublime Anyone know how to prevent Sublime from opening the previous window / session when using the command line?  This happens in both OSX and Windows.  If I open a folder by passing the path to the app, a session with the folder opens, but so does the previous window / session / folder...

A: Go to preferences -> Settings - User
Add:
{
  "hot_exit": false,
  "remember_open_files": false
}


text:
Q: Disable a Custom Checkout Step I have a custom checkout step that i want to try and disable if i have no products in my crosssell however i cant figure out how to disable the step in below code:
define(
[
    'ko',
    'uiComponent',
    'underscore',
    'Magento_Checkout/js/model/step-navigator'
],
function (
    ko,
    Component,
    _,
    stepNavigator
) {
    'use strict';
    /**
    *
    * mystep - is the name of the component's .html template,
    * <Vendor>_<Module>  - is the name of the your module directory.
    *
    */
    return Component.extend({
        defaults: {
            template: 'Harrigo_CrosssellCheckout/crosssellstep'
        },

        //add here your logic to display step,
        isVisible: ko.observable(true),

        /**
        *
        * @returns {*}
        */
        initialize: function () {
            this._super();
            // register your step
            stepNavigator.registerStep(
                //step code will be used as step content id in the component template
                'crosssell_step',
                //step alias
                null,
                //step title value
                'Interested in?',
                //observable property with logic when display step or hide step
                this.isVisible,

                _.bind(this.navigate, this),

                /**
                * sort order value
                * 'sort order value' < 10: step displays before shipping step;
                * 10 < 'sort order value' < 20 : step displays between shipping and payment step
                * 'sort order value' > 20 : step displays after payment step
                */
                5
            );

            return this;
        },

        /**
        * The navigate() method is responsible for navigation between checkout step
        * during checkout. You can add custom logic, for example some conditions
        * for switching to your custom step
        */
        navigate: function () {

        },

        /**
        * @returns void
        */
        navigateToNextStep: function () {
            stepNavigator.next();
        }
    });
}
);

There are sections for logic to display step but simply setting this to false does not seem to work.

A: You should stop register your custom step on stepNavigator.registerStep() if your conditions are not met
if(!YourCondition){
    stepNavigator.registerStep(
        //step code will be used as step content id in the component template
        'crosssell_step',
        //step alias
        null,
        //step title value
        'Interested in?',
        //observable property with logic when display step or hide step
        this.isVisible,

        _.bind(this.navigate, this),

        /**
        * sort order value
        * 'sort order value' < 10: step displays before shipping step;
        * 10 < 'sort order value' < 20 : step displays between shipping and payment step
        * 'sort order value' > 20 : step displays after payment step
        */
        5
    );
}


text: Q: Error while saving theme configuration I am trying to update Welcome text in theme configuration, but when i am saving changes it giving me "An error occurred while saving the configuration. Area is already set". I am using meigeeteam's universal theme.


text:
Q: Will be TRIM enabled by default? I heard that Ubuntu 14.04 will feature TRIM by default on SSDs. What I would like to know is that if in the current daily builds it is already activated.
Also, it would be appreciated a way to verify if it is indeed working.

A: TRIM will be run by a cronjob by default as announced by Martin Pitt. This will be done weekly (as can be seen in the patch) and will be perfectly configurable. Automatic TRIMimg will be enabled.


text:
Q: Spring AMQP, CorrelationId and GZipPostProcessor: UnsupportedEncodingException I have a Project with Spring AMQP (1.7.12.RELEASE).
If I put a value for the correlationId field (etMessageProperties (). SetCorrelationId) and I use GZipPostProcessor, the following error always occurs:
"org.springframework.amqp.AmqpUnsupportedEncodingException: java.io.UnsupportedEncodingException: gzip"

To solve it, it seems that it works using the following code:
DefaultMessagePropertiesConverter messageConverter = new DefaultMessagePropertiesConverter();
    messageConverter.setCorrelationIdAsString(DefaultMessagePropertiesConverter.CorrelationIdPolicy.STRING);
template.setMessagePropertiesConverter(messageConverter);

but I do not know what implications it will have to use it in real with clients that do not use Spring AMQP (I establish this field if the message that has reached me has it).
I enclose a complete example of code:
@Configuration
public class SimpleProducerGZIP
{
    static final String queueName = "spring-boot";

    @Bean
    public CachingConnectionFactory connectionFactory() {
        com.rabbitmq.client.ConnectionFactory factory = new com.rabbitmq.client.ConnectionFactory();
        factory.setHost("localhost");
        factory.setAutomaticRecoveryEnabled(false);
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory(factory);
        return connectionFactory;
    }

    @Bean
    public AmqpAdmin amqpAdmin() {
        RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory());
        rabbitAdmin.setAutoStartup(true);
        return rabbitAdmin ;
    }

    @Bean
    Queue queue() {
        Queue qr = new Queue(queueName, false);
        qr.setAdminsThatShouldDeclare(amqpAdmin());
        return qr;
    }

    @Bean
    public RabbitTemplate rabbitTemplate()
    {
        RabbitTemplate template = new RabbitTemplate(connectionFactory());
        template.setEncoding("gzip");
        template.setBeforePublishPostProcessors(new GZipPostProcessor());

         // TODO :
        DefaultMessagePropertiesConverter messageConverter = new DefaultMessagePropertiesConverter();
        messageConverter.setCorrelationIdAsString(DefaultMessagePropertiesConverter.CorrelationIdPolicy.STRING);
        template.setMessagePropertiesConverter(messageConverter);

        return template;
    }

    public static void main(String[] args)
    {
        @SuppressWarnings("resource")
        ApplicationContext context = new AnnotationConfigApplicationContext(SimpleProducerGZIP.class);
        RabbitTemplate _rabbitTemplate = context.getBean(RabbitTemplate.class);
        int contador = 0;
        try {
            while(true)
            {
                contador = contador + 1;
                int _nContador = contador;
                System.out.println("\nInicio envio : " + _nContador);
                Object _o = new String(("New Message : " + contador));
                try
                {
                    _rabbitTemplate.convertAndSend(queueName, _o,
                            new MessagePostProcessor() {
                                @SuppressWarnings("deprecation")
                                @Override
                                public Message postProcessMessage(Message msg) throws AmqpException {
                                    if(_nContador%2 == 0) {
                                        System.out.println("\t--- msg.getMessageProperties().setCorrelationId ");
                                        msg.getMessageProperties().setCorrelationId("NewCorrelation".getBytes(StandardCharsets.UTF_8));
                                    }
                                    return msg;
                                }
                            }
                    );
                    System.out.println("\tOK");
                }catch (Exception e) {
                    System.err.println("\t\tError en envio : " + contador + " - " + e.getMessage());
                }

                System.out.println("Fin envio : " + contador);
                Thread.sleep(500);
            }
        }catch (Exception e) {
            System.err.println("Exception : " + e.getMessage());
        }
    }
}

The question is, if I change the configuration of the rabbitTemplate so that the error does not happen, can it have implications for clients that use Spring AMQP or other alternatives?
--- EDIT (28/03/2019)
This is the complete stack trace with the code:
org.springframework.amqp.AmqpUnsupportedEncodingException: java.io.UnsupportedEncodingException: gzip
    at org.springframework.amqp.rabbit.support.DefaultMessagePropertiesConverter.fromMessageProperties(DefaultMessagePropertiesConverter.java:211)
    at org.springframework.amqp.rabbit.core.RabbitTemplate.doSend(RabbitTemplate.java:1531)
    at org.springframework.amqp.rabbit.core.RabbitTemplate$3.doInRabbit(RabbitTemplate.java:716)
    at org.springframework.amqp.rabbit.core.RabbitTemplate.doExecute(RabbitTemplate.java:1455)
    at org.springframework.amqp.rabbit.core.RabbitTemplate.execute(RabbitTemplate.java:1411)
    at org.springframework.amqp.rabbit.core.RabbitTemplate.send(RabbitTemplate.java:712)
    at org.springframework.amqp.rabbit.core.RabbitTemplate.convertAndSend(RabbitTemplate.java:813)
    at org.springframework.amqp.rabbit.core.RabbitTemplate.convertAndSend(RabbitTemplate.java:791)
    at es.jab.example.SimpleProducerGZIP.main(SimpleProducerGZIP.java:79)
Caused by: java.io.UnsupportedEncodingException: gzip
    at java.lang.StringCoding.decode(Unknown Source)
    at java.lang.String.<init>(Unknown Source)
    at java.lang.String.<init>(Unknown Source)
    at org.springframework.amqp.rabbit.support.DefaultMessagePropertiesConverter.fromMessageProperties(DefaultMessagePropertiesConverter.java:208)
    ... 8 more

A: I'd be interested to see the complete stack trace for more information about the problem.
This code was part of a transition from a byte[] correlation Id to a String. This was needed to avoid a byte[]/String/byte[] conversion.
When the policy is String, you should use the correlationIdString property instead of correlationId. Otherwise, the correlationId won't be mapped in outbound messages (we don't look at correlationId in that case). For inbound messages it controls which property is populated.
In 2.0 and later, correlationId is now a String instead of a byte[] so this setting is no longer needed.
EDIT
Now I see the stack trace, this...
template.setEncoding("gzip");

...is wrong.
/**
 * The encoding to use when inter-converting between byte arrays and Strings in message properties.
 *
 * @param encoding the encoding to set
 */
public void setEncoding(String encoding) {
    this.encoding = encoding;
}

There is no such Charset as gzip. This property has nothing to do with the message content, it is simply used when converting byte[] to/from String. It is UTF-8 by default.


text:
Q: How to retrieve text from url using regex in Android I have a url and I am trying to extract the text before the third slash. I am quite new to the concept in Android. I believe the Pattern class is used to achieve this. My problem is how to.
Take for instance: http://name.mywebsite.com/images.... I only require everything before images. Could anyone point me in the right direction?

A: You can use the uri method getHost in java.This example will help you,
URI uri = new URI("http://name.mywebsite.com/images");

String host = uri.getHost();
/* It returns name.mywebsite.com/*/


text:
Q: Aurora:Find diff between two tables based on primary key I have TABLE1 like below
|001000900|aaaaa BELLOWS CORPORATION||N|
|001000905|ddddd DEPARTMENT OF LABOR AND EMPLOYMENT SECURITY|BUREAU OF COMPLIANCE|N|
|001001049|gggg RAVIOLI MFG CO INC|SPINELLI BKY RAVIOLI PASTRY SP|N|
|001001130|dddd ANGELES UNIFIED SCHOOL DISTRICT|TRANSPORTATION BRANCH|N|
|001001143|ffff MUSIC PARTIES, INC||N|
|001001155|BOSTON BRASS AND IRON CO||N|
|001001171|HANCOCK MARINE, INC.||N|
|001001184|TRILLION CORPORATION||N|
|001001192|HAWAII STATE CHIROPRACTIC ASSOCIATION INC||N|
|001001379|THE FRUIT SQUARE PEOPLE INC|L & M BAKERY|N|
|001001416|J & S MARKET||N|

And Table2 like this
|001000145|PARADISE TAN||N|
|001000306|SHRUT & ASCH LEATHER COMPANY, INC.||N|
|001000355|HARRISON SPECIALTY CO., INC.||N|
|001000363|LOUIS M. GERSON CO., INC.||N|
|001000467|SAVE THE SEA TURTLES INTERNATIONAL|ADOPT THE BEACH HI|N|
|001000504|DIRIGO SPICE CORPORATION|CUNNINGHAM SPICE|N|
|001000744|FREEDMAN THREAD COMPANY|COLONIAL THREAD CO|N|
|001000756|AFFORDABLE AIR CONDITIONING|P R ENTERPRISE|N|
|001000900|CLIFLEX BELLOWS CORPORATION||N|
|001000905|FLORIDA DEPARTMENT OF LABOR AND EMPLOYMENT SECURITY|BUREAU OF COMPLIANCE|N|
|001001049|SPINELLI RAVIOLI MFG CO INC|SPINELLI BKY RAVIOLI PASTRY SP|N|
|001001130|LOS ANGELES UNIFIED SCHOOL DISTRICT|TRANSPORTATION BRANCH|N|
|001001143|TOSCO MUSIC PARTIES, INC||N|
|001001155|BOSTON BRASS AND IRON CO||N|

My requirement is to find the rows which is present in both tables (Matching rows)  based on primary key which is first column only if their others columns are changed.
For example if primary key is same and their other columns are different at least one then that will come in output .
How can i do this .
Plain except will give me result ?

A: Are you looking for a join with a where condition?
select t1.*, t2.*
from table1 t1 join
     table2 t2
     on t1.pk = t2.pk
where not (t1.col2 <=> t2.col2) or
      not (t1.col3 <=> t2.col3) or
      not (t1.col4 <=> t2.col4) ;


text:
Q: How to track email is opened or not, email is delivered or not, email bounced or not? I am trying to build an email marketing tools. where i can track my customers actions, whether they opened the email or not and email delivered or not.
I will send some HTML template in the email.
So i want to know the concept of this how i can develop this type of protocol ?
I am using backend as NodeJs, Nodemailer and for frontend i am using react js.
I am trying to develop a prototype like mailchimp.
So can anyone suggest me how i can achieve this ?

A: Nodemailer already tells you if an error occurred during sending an email.
transporter.sendMail({
    from: 'sender@example.com',
    to: 'recipient@example.com',
    subject: 'Message',
    text: 'I hope this message gets delivered!'
}, (err, info) => {
    // check for errors here
    console.error(err);
    console.log(info);
});

For tracking if email is opened or not:
You can possibly add a small hidden image to the HTML body and when that image is loaded from your server, you can know at least if customers are opening their emails.


text:
Q: ValueError: Operands could not be broadcast together with shapes (54, 54, 128) (54, 54, 64) I wrote a ResNet block with three convolutional layers:
def res_net_block(input_data, filters, kernel_size):
kernel_middle = kernel_size + 2
filters_last_layer = filters * 2

x = Conv2D(filters, kernel_size, activation = 'relu', padding = 'same')(input_data)   #64, 1x1
x = BatchNormalization()(x)

x = Conv2D(filters, kernel_middle, activation = 'relu', padding = 'same')(x)          #64, 3x3
x = BatchNormalization()(x)

x = Conv2D(filters_last_layer, kernel_size, activation = None, padding = 'same')(x)   #128, 1x1
x = BatchNormalization()(x)

x = Add()([x, input_data])

x = Activation('relu')(x)
return x

When I add it to my model, I receive this error: ValueError: Operands could not be broadcast together with shapes (54, 54, 128) (54, 54, 64)
Here is my model so far:
inputs = Input(shape = (224, 224, 3))
model = Conv2D(filters = 64, kernel_size = 7, strides = 2, activation = 'relu')(inputs)
model = BatchNormalization()(model)
model = MaxPool2D(pool_size = 3, strides = 2)(model)
for i in range(num_res_net_blocks):
    model = res_net_block(model, 64, 1)

I believe the problem comes from this line in the ResNet block:
x = Add()([x, input_data])

The input data is with different dimensions from the x. But I don't know how to fix this issue.
I would really appreciate some help here.

A: The error is due to adding two tensors with different dimensions - (54, 54, 128) & (54, 54, 64). In order to perform tensor addition, the input dimensions must be the same along all axes. Here's the same note from Keras Add() doc:
Quote: "keras.layers.Add() ... It takes as input a list of tensors, all of the same shape, and returns a single tensor (also of the same shape)"
In order to perform residual addition, you need to ensure the two tensors - one along the identity path and one on the residual path, have the same dimensions. As a simple solution to debug the error, in the final Conv2D replace filters_last_layer with filters to get both residual (x) and identity tensor (input_data) to have the same shape (54, 54, 64).
Hope this helps! :)


text:
Q: Why getting Could not establish trust relationship for the SSL/TLS secure channel with authority? I've developed a windows service with C#.NET and calling a Java web service from my windows service. The web service is certificate protected so my client has provided me with the certificate. I've installed the certificate using MMC.EXE to Root, Personal and Trusted People section but getting the following error while trying to communicate with their API.

Could not establish trust relationship for the SSL/TLS secure channel with authority 'pmtest.xxxxxx.ua:9192'.
  inner exception : The remote certificate is invalid according to the validation procedure.

Here is my code for calling the method in their web service.
  try
   {
      System.Net.ServicePointManager.ServerCertificateValidationCallback += delegate { return true; };
     resp = (EBMType)wsClient.InvokeMember(this.remoteMethodName, BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public, null, this.privatMoney, new object[] { this.requestObject }); //Here I'm getting error
    }
  catch (System.Reflection.TargetInvocationException e)
    {
              System.ServiceModel.FaultException<FaultType> ex = (System.ServiceModel.FaultException<FaultType>)e.InnerException;
                    throw new ApplicationException(string.Format("PrivatMoney error occurred. Message: {0}, Code: {1}", ex.Detail.FaultNotification.FaultMessage.Text, ex.Detail.FaultNotification.FaultMessage.Code));
     }

May I please know what to do in this situation as I'm quite new in this field. Thanks in advance.


text:
Q: Our developer created our Facebook App and is no longer with the company. How do we change the admin? How do you change the admin for a Facebook App when the admin developer left the company and didn't delegate access?

A: Only the administrator of the app can add another admin.
So, only your developer has the power to delegate the rights to you and no one.
If there are not many users in your app, I would suggest you to a create new app and change the app credentials in the code. But of-course, the authentication step will be repeated for the existing users.

A: The first step that I would take is check developers.facebook.com and see if he did in face delegate access.
When you go their go to apps (upper menu on the screen), and then check to see if your app shows in that list. If it does click on it and then go to roles thats on the sub-menu on the left hand side. If you are a administrator then you can remove him.
If the namespace of your app isn't important, such you are accessing the api from a website then you can create a new app and just use that one. The down side here is that all your users's access tokens would be invalid. They also might wonder why they see two simular looking apps that they have granted permission to.
Another thought is that you could ask your question in this group, as I don't have a ton of experience, but I really doubt that their will be anything you can do as he is the administrator. (basically he owns it)


text:
Q: Observable's subscribe is never triggered I'm facing an strange behavior while subscribing to my Observable.
For some reason the console.log(item) is never called and also there are no errors on the console.
this.store$
.pipe(
  select(getRecentNotes),
  mergeAll(),
  groupBy(item => item.status.code),
  mergeMap(group => group.pipe(toArray())),
  toArray()
)
.subscribe((items)=> console.log('Grouped Items', items));

BTW, If I pipe only select(getRecentNotes) then it works and I'm getting something like this:
[
  {id: 1, note: "ABC", status: {code: 1, name: 'active'}},
  {id: 2, note: "DEF", status: {code: 1, name: 'active'}},
  {id: 3, note: "HIJ", status: {code: 2, name: 'hidden'}}
]

more interesting is that the following will work:
// This will work
this.store$
.pipe(
  select(getRecentNotes),
  mergeAll()
)
.subscribe((items)=> console.log('Bunch of Items', items));

But if I add another operator, like toArray() then it stops working.
// This will not work
this.store$
.pipe(
  select(getRecentNotes),
  mergeAll(),
  toArray()
)
.subscribe((items)=> console.log('All items', items));

Is there any hidden rule that I'm missing out?
I've tried to recreate the problem at StackBlitz using just a simple Observable.from([]) but everything seems to works.
Update 1:
I added some other operators to the pipe, they do stuff (like printing to the console). But the code in the .subscribe is not called
this.store$
.pipe(
  select(getRecentNotes),
  mergeAll(),
  tap((item)=> {console.log(item)}),   // <--- This is printed to the console
  reduce((acc, item)=> {
  console.log(acc);                    // <-- This is printed to the console
  console.log(item);
  return acc.push(item);
  },[])
)
.subscribe((items)=> console.log('All items', items));

A: As @AnjilDhamala mentioned in his comment, operators like toArray don't execute until the stream completes.  Your store$ observable stays open for changes so that toArray operator will never emit a result.
It seems like your goal is to return an array of arrays chunked by a code?
The simple solution would be to add take(1) after your select operator call.  That should result in the last toArray returning an array of arrays.
But if my assumption is correct, then all of this may be unnecessary.  It might seem that using all those rxjs operators is clean, but the intention of what you're trying to accomplish is far from clear.  After the select you can just call map with a function that will chunk your array up with plain old JavaScript.
this.store$
.pipe(
  select(getRecentNotes),
  map(x => chunkBy(x, x => x.status.code))
).subscribe((items)=> console.log('All items', items));

function chunkBy<T>(ary: T[], chunkKeySelector: (item: T) => any) {
  const result: T[][] = [];
  const indexMap = new Map<any, number>();

  for (let value of ary) {
    const key = chunkKeySelector(value);
    (indexMap.has(key))
      ? result[indexMap.get(key)].push(value)
      : indexMap.set(key, result.push([value]) - 1);
  }
  return result;
}


text: Q: Transfering Hyper-V VM os to boot Server directly from SAN through iSCSI I have Hyper-V VMs (main application server 2008 R2 on IBM and MSSQL on DELL), both virtualized in Hyper-V 2012. I have discovered some performance offset when using virtualized OS (Terminal server) and I would love to use the physical servers full power. SO after some reading, I wanted to compare the performance of virtualized local machine, to machine with OS booted from SAN directly. I believe when booting from SAN, after some hardware tweaks and adding some redundant hardware, I could get solid and expandable system. However I have a OS on VHDX from hyper V, which has plenty of informations, settings, tweaks, and I would love to transfer / migrate this OS as it is to a LUN on SAN, and boot server directly from that. I managed to connect targets, initiators, server BIOS can connect and boot from SAN, but I guess simly pointing iSCSI Target to my Hyper-V VHDX is not the way how it should be done (there must be some MBR, or iSCSI drivers missing, as I get a blue screen when windows try to boot) I could not find any information about this migration or process anywhere(some sort of easy one). If anybody can help to accomplish this would be great. Maybe my solution I am trying to reach is not the best from somebody point of view, but I would still love to test and compare the difference in performance I can get out of the hardware physical/virtualized hardware. (I am thinking of booting OS from SAN, as later I want to add second fail over Server X3850 X5, and connect them with QPI, and use as one powerfull machine, plus to centrally manage snapshots of whole OS, data etc...thanks for any comments and help.


text:
Q: store array data in mysql using codeigniter-3 I want to store array data in database(mysql) using codeigniter
$data['product_data'] = $this->Products_database_fe->get_by_id($id);

$data contains data which i have fetch from database.
Now $data which contain an array, and i want to store that array data in phpmyamin using codeigniter-3


text:
Q: Assume $a_1 > 1$. Find the limit of $a_{n+1} = 2 - ( \frac{1}{a_n} + a_n )$. Attempt:
$$L = 2 - \frac{1}{L} $$
By solving this, I can get that $L=1$. However, in trying to prove the limit existence, I want to do this by proving the recursive sequence is bounded and monotonic. Unfortunately, I don't know how to do this for a recursive sequence. What is the best approach for this?

A: *

*convergency is not true in general. For $a_{1}=2$, $a_{3}$ is infinity. Generally, nontrivial precondition $\forall_{n}a_{n}\neq1$ is necessary

*Correct equation is $2L=2-\frac{1}{L}
 $, without real roots

A: The sequence is diverge. Because $a_{2n}\leq 0$ and $a_{2n+1}\geq 4$ for all $n\geq 1.$

A: Hints: if $a_n>1$ then $a_{n+1}<0$:
$$
a_{n+1}=-\left(\frac{1}{\sqrt{a_n}}-\sqrt{a_n}\right)^2<0.
$$
And if $a_{n}<0$ then $a_{n+1}>1$:
$$
a_{n+1}-1=1-\left(a_n+\frac{1}{a_n}\right)>1>0.
$$
From these, what can you say about $a_1,a_3,a_5,\ldots$ and $a_2,a_4,a_6,\ldots$?