Q: Unable to change the link of a button using Javascript Hello I am a total newbie (I don't code) and I made a wordpress website in two different languages (french and english) using the Polylang plugin.
But I am facing the following problem :  in my website, there is a button linking to a Facebook page in english and when the website is switched to french, I would like the button to link to another Facebook page (that will be in french).
From what I searched so far, I understand that this would be possible using javascript.
And I tried many variations of the following code with no result :
<script>
    jQuery(document).ready(function(){
        $('html[lang=|fr] .fa-facebook').attr('href', 'https://myfacebookpage.com');
   });
</script>

"fa-facebook" is the css class of the social media button.
What am I doing wrong and how can I fix that please ?
Thank you !
Edit : here is the html code of the french version : jsfiddle.net/yup5zxng

A: I also tried with not result :
  <script>
jQuery(document).ready(function(){
    $('html:lang(fr-FR) .fa-facebook').attr('href', 'https://myfacebookpage.com'); }); </script>

A: Basically what you should do is check the language of the <html> tag on document ready and after loop through all the facebook links and update their href. Something like this:
$(document).ready(function() {

  const documentLanguage = $("html").attr("lang");
  const facebookLinks = $(".fa-facebook");

  facebookLinks.each(function(index, link) {
    if (documentLanguage === "fr-FR") {
      $(link).parent().attr("href", "https://facebook.com/my-french-site/");
    } else if (documentLanguage === "en-EN") {
      $(link).parent().attr("href", "https://facebook.com/my-english-site/");
    }
  });
});

Here is a live sample: https://jsfiddle.net/rhernando/kwndv609/3

EDIT
I forgot about the tree structure of your DOM the class element is an <i> tag so you have to point to it's parent element. The updated code should work.

A: you have a typo in the attribute selector:
| should be before =, not after:
$('html[lang|=fr] .fa-facebook')

More about attribute selectors here: https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors


Q: Use of M2M Table and relationship to get specific data in sqlalchemy I have Table
# File : MyRelations.py
ACC_ADD_TABLE = Table('acc_add_rel', METADATA,
    Column('acc_id', ForeignKey('acc.id'),
            nullable=False),
    Column('add_id', ForeignKey('address.id'),
            nullable=False),
    PrimaryKeyConstraint('add_id', 'acc_id'),
    )

# File : Address.py
class Address(Base):
    id = Column(Integer, primary_key=True,)
    type = Column(String(length=10), nullable=False)

# File : Account.py
class Account(Base):
    id = Column(Integer, primary_key=True,)
    addresses = relationship('Address',
                            secondary=ACC_ADD_TABLE
                            )
#   default_address = relationship('Address',
#                           secondary=ACC_ADD_TABLE,
#                           primaryjoin=and_("ACC_ADD_TABLE.add_id==Address.id",
#                                            "ACC_ADD_TABLE.acc_id==Account.id",
#                                            "Address.type='default'")
#                           )

As per the example I want to access the all default addresses in account. I can use declared_attr or can write the function but is there any way to combine Table and Class attribute in single and_ operation?
Note: Address.py and Account.py both are different files and due to cycle dependency I cant import any model in other model
Thx for you help.

A: This works without requiring an import:
default_address = relationship('Address',
                       secondary=ACC_ADD_TABLE,
                       primaryjoin="acc.c.id==acc_add_rel.c.acc_id",
                       secondaryjoin="and_(address.c.id==acc_add_rel.c.add_id, address.c.type=='default')",
                       #uselist = True,
                       )

If you are certain that there is only one default address, you might use uselist=True for convenience.
Sometimes I prefer the other structure for such situations though: add a column to the Account table: default_address_id and build 1-[0..1] relationship based on this column, still checking that the referenced Address is also part of Account.addresses M-N relationship.

On the side note, a typo: in your (commented) code you should use == instead of = in "Address.type='default'". This does not solve the problem though.


Q: Is there some difference between mv and {cp + rm the old file} on Unix?
*

*mv a b

*cp a b;rm a
These are two sets of statements. Is there some difference between what they do?

A: Yes, mv has a chance of being atomic on the same disk, whereas the combination of cp and rm never has.
This is assuming that mv is implemented using rename(), which is the call that has the guarantee. See, for instance, this newsgroup post, which quotes POSIX:

This rename() function is equivalent
  for regular files to that defined
      by the ISO C standard. Its inclusion here expands that definition
  to
      include actions on directories and specifies behavior when the new
      parameter names a file that already exists. That specification
      requires that the action of the function be atomic.

A: On the same file system mv changes the directory reference, pointing to the same inode (file data and metadata) thus:

*

*is an atomic operation (it cannot be interrupted by another process file operation)

*takes only a trivial amount of additional disk space (the additional name in the directory)

*preserves file permissions and ownership

*can be much faster, depending on amount of data

Copy and remove

*

*is not atomic (another process could interfere between the cp and rm commands)

*requires storing the file data twice on disk for a short period (between the cp and rm commands)

*changes file permissions and ownership to defaults

*can be much slower or even fail, depending on amount of data

A: When the source and the destination are on the same physical volume, then the first approach is simply a rename and is very fast (even if the file(s) are very big).
cp & rm will always have to load/store all the data, even if it weren't necessary.

A: mv is in essence a "rename" operation. This means the file itself is left in the same spot on disk. No actual file operation is performed.

A: The difference is that mv conserves file-attributes while cp by default doesn't, for example setting creation-date to the current date.
To override this default, use "cp -p" to preserve the last data modification, the time of the last access, the user ID and group ID (only if it has permissions to do this),
file permission bits and the SUID and SGID bits.

A: Assuming the files involved are on the same file system, then mv simply changes pointers in the file system, whereas cp copies the entire contents of the file, and rm once again changes pointers. So mv is far more efficient.

A: Yes.
mv simply changes the filesystem metadata on the file relating to it's name and location, whereas cp creates a seperate copy of the file, which takes much
longer as it must fully read the first file and then write it's contents to another file

A: cp and rm is a much heavier on the disk usage, and may fail for disk space reasons.


Q: Прибавление дней k дней к дате Подскажите пожалуйста, как добавить k дней (допустим 180, может быть и больше года) к дате формата:
  t_date = record
    day: 1..31;
    month: 1..12;
    year: 2000..3000;
  end;

Вообще идей ни каких, так как нужно учитывать много факторов одновременно, типа начала нового года, високосный ли год и сколько дней в месяце, помогите пожалуйста. Функциями для работы с датой пользоваться нельзя, так бы я и сам бы всё сделал.

A: Ну, костяк процедуры AddDays, например, такой ( не факт, что оптимизировано). Мог ошибиться, т.к. писал не в IDE.
const
   daysinmonth:array[1..12] of integer = (31, 28, 31,...); // количество дней в месяцах
   daysinmonth_v:array[1..12] of integer = (31, 29, 31,...); // количество дней в месяцах для високосного года

function Visokosny(d:integer):boolean;
begin
  Result:=true если d- високосный год, иначе false; // Думаю, сами напишете
end;

procedure AddDays(k:days; var td:t_date);
var
  y, m, d:integer;
begin
   y:=td.year;
   m:=td.month;
   d:=td.day;
   while k >= 365 do
      begin
         if Visokosny(y) then
            begin
               if k=365 then break // разумеется, здесь можно сразу всё прибавить и закончить процедуру - тут вам решать
              else dec(k,366);
            end
         else dec(k, 365);
         inc(y);
      end; // целые годы прибавили
   if k > 0 then
       begin
          repeat
            if Visokosny(y) then
              begin
                 if (d+k) > daysinmonth_v[m] then
                   begin
                      dec(k,daysinmonth_v[m]);
                      inc(m);
                      if m > 12 then
                        begin
                          m:=1;
                          inc(y);
                        end;
                   end
                 else break;
              end
           else
              begin
                 if (d+k) > daysinmonth[m] then
                   begin
                      dec(k,daysinmonth[m]);
                      inc(m);
                      if m > 12 then
                        begin
                          m:=1;
                          inc(y);
                        end;
                   end
                 else break;
              end
          until false; // пробежали по месяцам
          inc(d,k);
       end;
   td.year:=y;
   td.month:=m;
   td.day:=d;

end;


Q: Responsive WYSIWYG editor in jquerymobile website and mobile app I'm struggling but i couldn't find a single rich text editor which is compatible with jquerymobile and Cordova.
I Have a container div now i want to put editor in it and the width and height of editor should change if container div width and height change i Have tried many editors like TinyMCE but they are not responsive and i don't want to use bootstrap library. Please help?

A: This question was old, but not answered very well and I ran across this same problem earlier today. jHtmlArea can be used on a responsive page with a couple of small modifications to its source code.
The original documentation for jHtmlArea can be found here:
https://pietschsoft.com/post/2009/07/22/jhtmlarea-the-all-new-html-wysiwyg-editor-for-jquery
The original source code has migrated to GitHub: https://github.com/crpietschmann/jHtmlArea
To make jHtmlArea responsive, simply replace the init function code in jHtmlArea-0.8.js with the code below:
init: function (elem, options) {
    if (elem.nodeName.toLowerCase() === "textarea") {
        var opts = $.extend({}, jHtmlArea.defaultOptions, options);
        elem.jhtmlareaObject = this;

        var textarea = this.textarea = $(elem);
        var container = this.container = $("<div/>").addClass("jHtmlArea").insertAfter(textarea);

        var toolbar = this.toolbar = $("<div/>").addClass("ToolBar").appendTo(container);
        priv.initToolBar.call(this, opts);

        var iframe = this.iframe = $("<iframe/>").height(textarea.height());
        iframe.width('inherit');

        var htmlarea = this.htmlarea = $("<div/>").width('100%').append(iframe);

        container.append(htmlarea).append(textarea.hide());

        priv.initEditor.call(this, opts);
        priv.attachEditorEvents.call(this);

        // Fix total height to match TextArea
        iframe.height(iframe.height() - toolbar.height());
        // toolbar.width(textarea.width());

        if (opts.loaded) { opts.loaded.call(this); }
    }
},

Hopefully this will save someone else some time.

A: jHtmlArea is a nice WYSIWYG editor
is very simple to use
// Turn all <textarea/> tags into WYSIWYG editors
$(function() {
    $("textarea").htmlarea();
});

You can download the library from here
http://pietschsoft.com/demo/jHtmlArea/


Q: found button but unable to click on it I have a methods which fills facebook sign up for and should to press "Create an account" button. It seams that it founds button, but due to unclear reason unable to click on it
code of button is:
<button type="submit" class="_6j mvm _6wk _6wl _58mi _3ma _6o _6v" name="websubmit" id="u_0_s">Create Account</button>

and my method is:
def submit_new_account_form(self, **credentials):

    firstname = self.driver.find_element_by_css_selector(self.__first_name_field_css)
    lastname = self.driver.find_element_by_css_selector(self.__last_name_field_css)
    number_or_email = self.driver.find_element_by_css_selector(self.__mobile_number_or_email_field_css)
    newpass = self.driver.find_element_by_id(self.__new_password_field_id)
    maleradio = self.driver.find_element_by_css_selector(self.__male_radio_css)
    femaleradio = self.driver.find_element_by_css_selector(self.__female_radio_css)
    submit_button = self.driver.find_element_by_id(self.__create_account_button_id)

    if submit_button:
        print ("submit button found")

    if maleradio:
        print("maleradio found")
    if femaleradio:
        print ("femaleradio found")
    #firstname.clear()
    if credentials['first_name']:
        firstname.send_keys(credentials['first_name'])

    #lastname.clear()
    if credentials['last_name']:
        lastname.send_keys(credentials['last_name'])

    #number_or_email.clear()
    if credentials['phone_or_email']:
        number_or_email.send_keys(credentials['phone_or_email'])
        re_enter_email_field = WebDriverWait(self.driver, 10).until(
            expected_conditions.presence_of_element_located((By.CSS_SELECTOR,self.__re_enter_new_email_field_css)))
        re_enter_email = self.driver.find_element_by_css_selector(self.__re_enter_new_email_field_css).send_keys(
            credentials['phone_or_email'])

    #newpass.clear()
    if credentials['newpass']:
        newpass.send_keys(credentials['newpass'])

    if credentials['sex'] == 'male':
        maleradio.click()

    if credentials['sex'] == 'female':
        femaleradio.click()

    submit_button.click()

    if submit_button.click():
        print('submit button clicked')

each time I run script submit button clicked doesn't appears and error occurs:
selenium.common.exceptions.ElementNotVisibleException: Message: element not visible

A: <button type="submit" class="_6j mvm _6wk _6wl _58mi _3ma _6o _6v"
name="websubmit" id="u_0_s">Create Account</button>

From above,I could see id for submit button is 'id='u_0_s'.
Can you confirm that you are passing id correctly for submit?If not,please correct it with 'id='u_0_s',try and let me know if it works.
Also,check if the Submit button is visible while your test case is getting executed.You can add code to maximize browser window for this.

A: You can use this xpath: "//button[contains(text(), 'Create an account')]", it will solve your problem

A: I have added implicit wait
WebDriverWait(self.driver,10).until(expected_conditions.visibility_of_element_located((By.ID, self.__create_account_button_id)))

And after that everything works good


Q: apache beam running locally but unable to read data from csv in Python import apache_beam as beam
from apache_beam.options.pipeline_options import PipelineOptions
p = beam.Pipeline(options=PipelineOptions())lines = p | beam.io.ReadFromText('file:///C:/Users/Lenovo/Desktop/dataflow.csv')
Apache beam is running locally but is unable to read data from csv.


Q: Parallel processing data analysis - Is there a benefit to having more splits than processor cores? I am using a naive Bayesian classifier to predict some test data in R. The test data has >1,000,000,000 records, and takes far too long to process with one processor. The computer I am using has (only) four processors in total, three of which I can free-up to run my task (I could use all four, but prefer to keep one for other work I need to do).
Using the foreach and doSNOW packages, and following this tutorial, I have things set up and running. My question is:
I have the dataset split into three parts, one part per processor. Is there a benefit to splitting the dataset into say 6,9, or 12 parts? In other words, what is the trade-off between more splits, vs, just having one big block of records for each processor core to run?
I haven't provided any data here because I think this question is more theoretical. But if data are needed, please let me know.

A: Broadly speaking, the advantage of splitting it up into more parts is that you can optimize your processor use.
If the dataset is split into 3 parts, one per processor, and they take the following time:
Split A - 10 min
Split B - 20 min
Split C - 12 min
You can see immediately that two of your processors are going to be idle for a significant amount of time needed to do the full analysis.
Instead, if you have 12 splits, each one taking between 3 and 6 minutes to run, then processor A can pick up another chunk of the job after it finishes with the first one instead of idling until the longest-running split finishes.


Q: Speed up a Laravel query where a field from relationship matches at least all elements of a given array I'm using the query below to get all results matching at least all elements of an array:
$colors_array = ['red', 'green', 'blue'];

Foo::with('colors')
  ->whereHas(
    'colors',
    function ($query) use ($colors_array) {
      $query->distinct()->whereIn('name', $colors_array);
    },
    '=',
    count($colors_array)
  );

But this query is very slow, is there a better syntax to speed it up ?


Q: CMD.exe consumes all the CPU, blocking other CMD.exe to execute We have some Batch scripts (.bat) in Windows to execute the “backups” and “archive log” for the databases. These scripts are called from Tivoli periodically.
For each executed script, the process creates a sub session in order to load the DB2cmd environment, in order to execute the db2 commands and exit.
daily.bat
call db2cmd hourly.cmd

The content of the script is this:
db2_job_saveddaily.cmd
db2 -fE:\DB2\scripts\tmp\db2_job_savedbhourly.db2 -zE:\DB2\scripts\tmp\db2_job_savedbhourly.log
exit

The content of the db2 file is (however, it is not important because it is executed correctly)
db2_job_saveddaily.db2
archive log for database ICMNLSDB

We are facing a problem with these scripts, and I think it is related with the exit. At one execution, the script freezes, and it starts to consume the whole CPU (see attached image). After this behavior, we cannot execute any other DB2 command from the CLP.
We kill all the CMD.exe and db2bp.exe processes, but the error persists.
There is nothing in the db2diag.log file, and the only solution is to restart the machine.
Probably, the CMD.exe process losses the communication with the db2bp.exe, and the exit cannot be executed. I would like to understand the origin of this problem and learn how to execute db2 processes in Windows.

A: Our friend @AngocA seems to check into SO often but hasn't been checking this dangling question even though he did something to close it. Let's at least put his answer in here so folk know it's CLOSED by user. :)  Courtesy of tonight's Point Pimp. :-D

"The problem was in another db2cmd session where there was an
  infinitive loop. This created a scenario when new db2cmd session
  blocked because the first session used the whole CPU. – AngocA"


Q: Determinant of a matrix without actually expanding it. Given a Matrix $$A =  \begin{vmatrix}
a^2 & (s-a)^2 & (s-a)^2\\
(s-b)^2 & b^2 & (s-b)^2 \\
(s-c)^2 & (s-c)^2 & c^2\\
\end{vmatrix}$$
and $$a+b+c = 2s$$ , how can I find its determinant without expanding?
I've tried finding all factors which make two columns (/rows) similar or proportional. Only with s=0 all the rows and columns becomes 1 (after taking out the common value). With s=a $$\left|\matrix{
a^2 & 0 & 0\\
(a-b)^2=c^2 & b^2 & (a-b)^2=c^2 \\
(a-c)^2=b^2 & (a-c)^2=b^2 & c^2\\
}\right|=0$$
Here is a list of trivial factors
(s-a), (s-b), (s-c), (s-0). I'm given a hint that the determinant is a degree 6 polynomial, which I don't understand cause max degree of s is 4, please do explain how degree is 6.
I think det(A) = (s-a)(s-b)(s-c)(s-0).
Are there any more factors? What are they?
Edit: Please also explain how to arrive at the solution.

A: The equation $a+b+c=2s$ has a geometric interpretation: $s$ is the semiperimeter of a triangle of sides $a,\,b,\,c$. If this triangle is degenerate, say with $a=b+c$, then $s=a$ and$$A=\left|\begin{array}{ccc}
\left(b+c\right)^{2} & 0 & 0\\
c^{2} & b^{2} & c^{2}\\
b^{2} & b^{2} & c^{2}
\end{array}\right|=0,$$so $(s-a)(s-b)(s-c)|A$. A similar treatment of $-a=b+c\implies s=0$ can prove $s|A$. Since $A$ is of dimension $6$ and is homogeneous when all sides are rescaled, the symmetries require a result proportional to $s^3(s-a)(s-b)(s-c)$. An equilateral triangle with $a=b=c=2,\,s=3,\,A=54$ proves the coefficient is $2$, as in @JanEerland's answer.

A:
Not a 'real' answer, but it was too big for a comment.

I wrote and ran some Mathematica-code:
In[1]:=Clear["Global`*"];
FullSimplify[
 Det[{{a^2, (s - a)^2, (s - a)^2}, {(s - b)^2,
    b^2, (s - b)^2}, {(s - c)^2, (s - c)^2, c^2}}],
 Assumptions -> a + b + c == 2 s]

Running the code gives:
Out[1]=-2 (b - s) (b + c - s) s^3 (-c + s)

If you're not only looking for the solution, it is not very hard to show that this is correct.


Q: How to Group Documents by a Field and Calculate Count in mongodb using java How to write the below aggregation query in java.Can anyone please help me out regarding this ...
My documents in mongodb:
{ "_id" : ObjectId("56d6b5849d6e45832c36482a"), "name" : "abc", "count" : 100 }
{ "_id" : ObjectId("56d6b5899d6e45832c36482b"), "name" : "abc", "count" : 200 }
{ "_id" : ObjectId("56d6b5949d6e45832c36482c"), "name" : "xyz", "count" : 50 }

My query:
db.orders.aggregate([
{$group:{_id:"$name",total:{$sum:"$count"}}}
])

o/p:
{ "_id" : "abc", "total" : 300 }
{ "_id" : "xyz", "total" : 50 }

A: db.getCollection("orders").aggregate(Arrays.asList(new Document("$group", new Document("_id", "$name").append("total", new Document("$sum", "$count")))));
Hopes this will help.


Q: Stored procedure select VS select from external connection I am trying to find the pros and cons of using stored procedures instead of SQL queries from an external connection, but I am unable to find any direct comparison.

*

*What is the benefit of using stored procedures instead of SQL queries from an external connection?

*Is there any execution speed differences between them for small volume and big volume outputs?

*Is there any benefits for the database management as well?

A:
What is the benefit of using stored procedures instead of SQL queries from an external connection?

*

*Stored Procedures can be complex. Very complex. They can do things
that a single SQL query cannot do. (Execute Block aside.)

*They have their own set of grants so they can do things that current user
cannot do at all.

*Firebird optimizer is not that bad but obviously complex queries require more time for optimization and the result still may be suboptimal. Using imperative language the programmer can split complex query to set of simpler ones making Data Access Paths more predictable.

Is there any execution speed differences between them for small volume
and big volume outputs?

No.

Is there any benefits for the database management as well?

It depends on what you call "database management" and what benefits you have on mind. Most likely - no.

A:
What is the benefit of using stored procedures instead of SQL queries from an external connection?

One benefit, in terms of execution, is stored procedures store their query plan whereas dynamic sql query plans will not be stored and must be calculated each time the query is executed.

Is there any execution speed differences between them for small volume and big volume outputs?

Once the query plan is calculated, no, there is no speed difference.

Is there any benefits for the database management as well?

This is very subjective! In the past I worked at a place where ALL database access went through stored procedures so that they could lock down access to just the SPs. Other places I've worked didn't use stored procs at all because they are generally outside source control and problematic for developers who aren't SQL gurus. Also, business logic spread across multiple systems can become a real problem.


Q: Hibernate gives a strange ClassCast exception (using Transformers) This code:
@Override
public List<FactCodeDto> getAllFactsWithoutParentsAsFactDto() {
    String completeQuery = FactCodeQueries.SELECT_DTO_FROM_FACT_WITH_NO_PARENTS;
    Query query = createHibernateQueryForUnmappedTypeFactDto(completeQuery);

    List<FactCodeDto> factDtoList = query.list(); //line 133
    return factDtoList;
}

calling this method:
private Query createHibernateQueryForUnmappedTypeFactDto(String sqlQuery) throws HibernateException {
    return FactCodeQueries.addScalars(createSQLQuery(sqlQuery)).setResultTransformer(Transformers.aliasToBean(FactCodeDto.class));
}

gives me a ClassCastException -> part of the trace:
Caused by: java.lang.ClassCastException: org.bamboomy.cjr.dto.FactCodeDto cannot be cast to java.util.Map
    at org.hibernate.property.access.internal.PropertyAccessMapImpl$SetterImpl.set(PropertyAccessMapImpl.java:102)
    at org.hibernate.transform.AliasToBeanResultTransformer.transformTuple(AliasToBeanResultTransformer.java:78)
    at org.hibernate.hql.internal.HolderInstantiator.instantiate(HolderInstantiator.java:75)
    at org.hibernate.loader.custom.CustomLoader.getResultList(CustomLoader.java:435)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2423)
    at org.hibernate.loader.Loader.list(Loader.java:2418)
    at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:336)
    at org.hibernate.internal.SessionImpl.listCustomQuery(SessionImpl.java:1898)
    at org.hibernate.internal.AbstractSessionImpl.list(AbstractSessionImpl.java:318)
    at org.hibernate.internal.SQLQueryImpl.list(SQLQueryImpl.java:125)
    at org.bamboomy.cjr.dao.factcode.FactCodeDAOImpl.getAllFactsWithoutParentsAsFactDto(FactCodeDAOImpl.java:133)

Which is pretty strange because, indeed, if you look up the source code of Hibernate it tries to do this:
@Override
@SuppressWarnings("unchecked")
public void set(Object target, Object value, SessionFactoryImplementor factory) {
    ( (Map) target ).put( propertyName, value ); //line 102
}

Which doesn't make any sense...
target is of type Class and this code tries to cast it to Map,
why does it try to do that???
any pointers are more than welcome...
I'm using Hibernate 5 (and am upgrading from 3)...
edit: I also use Spring (4.2.1.RELEASE; also upgrading) which calls these methods upon deploy, any debugging pointers are most welcome as well...
edit 2: (the whole FactCodeDto class, as requested)
package org.bamboomy.cjr.dto;

import org.bamboomy.cjr.model.FactCode;
import org.bamboomy.cjr.model.FactCodeType;
import org.bamboomy.cjr.utility.FullDateUtil;
import org.bamboomy.cjr.utility.Locales;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.util.Assert;

import java.util.*;

@Getter
@Setter
@ToString
public class FactCodeDto extends TreeNodeValue {

    private String cdFact;
    private String cdFactSuffix;
    private Boolean isSupplementCode;
    private Boolean isTitleCode;
    private Boolean mustBeFollowed;

    private Date activeFrom;
    private Date activeTo;
    private Boolean isCode;
    private Long idFact;
    private Long idParent;
    private String type;
    Map<Locale, String> description = new HashMap<Locale, String>(3);

    public FactCodeDto() {
    }

    public FactCodeDto(String prefix, String suffix) {
        super();
        this.cdFact = prefix;
        this.cdFactSuffix = suffix;
    }

    public FactCodeDto(String cdFact, String cdFactSuffix, Boolean isSupplementCode,  Boolean mustBeFollowed) {
        super();
        this.cdFact = cdFact;
        this.cdFactSuffix = cdFactSuffix;
        this.isSupplementCode = isSupplementCode;
        this.mustBeFollowed = mustBeFollowed;

    }

    public FactCodeDto(String cdFact, String cdFactSuffix, Boolean isSupplementCode,  Boolean mustBeFollowed, Long idFact, Long idParent, Boolean isCode, Boolean isTitleCode, Date from, Date to, Map<Locale, String> descriptions,String type) {
        super();
        this.cdFact = cdFact;
        this.cdFactSuffix = cdFactSuffix;
        this.isSupplementCode = isSupplementCode;
        this.mustBeFollowed = mustBeFollowed;
        this.idFact = idFact;
        this.idParent = idParent;
        this.isCode = isCode;
        this.isTitleCode = isTitleCode;
        this.activeFrom = from;
        this.activeTo = to;
        if (descriptions != null) {
            this.description = descriptions;
        }

        this.type = type;

    }

    public FactCodeDto(FactCode fc) {
        this(fc.getPrefix(), fc.getSuffix(), fc.isSupplementCode(), fc.isHasMandatorySupplCodes(), fc.getId(), fc.getParent(), fc.isActualCode(), fc.isTitleCode(), fc.getActiveFrom(), fc.getActiveTo(), fc.getAllDesc(),fc.getType().getCode());
    }

    public String formatCode() {
        return FactCode.formatCode(cdFact, cdFactSuffix);
    }

    public boolean isActive() {
        Date now = new Date(System.currentTimeMillis());
        return FullDateUtil.isBetweenDates(now, this.activeFrom, this.activeTo);

    }

    public void setDescFr(String s) {
        description.put(Locales.FRENCH, s);
    }

    public void setDescNl(String s) {
        description.put(Locales.DUTCH, s);
    }

    public void setDescDe(String s) {
        description.put(Locales.GERMAN, s);
    }

    /**
     * public String toString() {
     * StringBuilder sb = new StringBuilder();
     * sb.append(getIdFact() + ": ")
     * .append(getIdParent() + ": ")
     * .append(" " + cdFact + cdFactSuffix + ": " + (isSupplementCode ? "NO Principal " : "   Principal "))
     * .append((mustBeFollowed ? "    Must Be Followed " : "NOT Must Be Followed "));
     * return sb.toString();
     * }
     */

    public Map<Locale, String> getDescription() {
        return description;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        String fullCode = formatCode();
        result = prime * result + ((fullCode == null) ? 0 : fullCode.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        FactCodeDto other = (FactCodeDto) obj;

        return formatCode().equals(other.formatCode());
    }

    @Override
    public boolean isChildOf(TreeNodeValue value) {
        Assert.notNull(value);
        boolean isChild = false;
        if (value instanceof FactCodeDto) {
            if (this.getIdParent() != null) {
                isChild = this.getIdParent().equals(((FactCodeDto) value).getIdFact());
            }

        }
        return isChild;
    }

    @Override
    public boolean isBrotherOf(TreeNodeValue value) {
        Assert.notNull(value);
        boolean isBrother = false;
        if (value instanceof FactCodeDto) {
            if (this.getIdParent() != null) {
                isBrother = this.getIdParent().equals(((FactCodeDto) value).getIdParent());
            }

        }
        return isBrother;
    }

    @Override
    public boolean isParentOf(TreeNodeValue value) {
        Assert.notNull(value);
        boolean isParent = false;
        if (value instanceof FactCodeDto) {
            isParent = this.getIdFact().equals(((FactCodeDto) value).getIdParent());
        }
        return isParent;
    }

    @Override
    public int compareTo(TreeNodeValue to) {
        if (to instanceof FactCodeDto) {
            return formatCode().compareTo(((FactCodeDto) to).formatCode());
        } else return 1;

    }

    public String getCode() {
        return formatCode();
    }

}

A: I found that AliasToBean has changed in Hibernate 5. For me adding getter for my field fixed the problem.

A: This exception occurs when the setters and getters are not mapped correctly to the column names.
Make sure you have the correct getters and setters for the query(Correct names and correct datatypes).
Read more about it here:
http://javahonk.com/java-lang-classcastexception-com-wfs-otc-datamodels-imagineexpirymodel-cannot-cast-java-util-map/

A: I do some investigation on this question. The problem is that Hibernate converts aliases for column names to upper case — cdFact becomesCDFACT.
Read for a more deeply explanation and workaround here:
mapping Hibernate query results to custom class?

A: In the end it wasn't so hard to find a solution,
I just created my own (custom) ResultTransformer and specified that in the setResultTransformer method:
private Query createHibernateQueryForUnmappedTypeFactDto(String sqlQuery) throws HibernateException {
    return FactCodeQueries.addScalars(createSQLQuery(sqlQuery)).setResultTransformer(new FactCodeDtoResultTransformer());
    //return FactCodeQueries.addScalars(createSQLQuery(sqlQuery)).setResultTransformer(Transformers.aliasToBean(FactCodeDto.class));
}

the code of the custom result transformer:
package org.bamboomy.cjr.dao.factcode;

import org.bamboomy.cjr.dto.FactCodeDto;

import java.util.Date;
import java.util.List;

/**
 * Created by a162299 on 3-11-2015.
 */
public class FactCodeDtoResultTransformer implements org.hibernate.transform.ResultTransformer {

    @Override
    public Object transformTuple(Object[] objects, String[] strings) {

        FactCodeDto result = new FactCodeDto();

        for (int i = 0; i < objects.length; i++) {
            setField(result, strings[i], objects[i]);
        }

        return result;
    }

    private void setField(FactCodeDto result, String string, Object object) {

        if (string.equalsIgnoreCase("cdFact")) {
            result.setCdFact((String) object);
        } else if (string.equalsIgnoreCase("cdFactSuffix")) {
            result.setCdFactSuffix((String) object);
        } else if (string.equalsIgnoreCase("isSupplementCode")) {
            result.setIsSupplementCode((Boolean) object);
        } else if (string.equalsIgnoreCase("isTitleCode")) {
            result.setIsTitleCode((Boolean) object);
        } else if (string.equalsIgnoreCase("mustBeFollowed")) {
            result.setMustBeFollowed((Boolean) object);
        } else if (string.equalsIgnoreCase("activeFrom")) {
            result.setActiveFrom((Date) object);
        } else if (string.equalsIgnoreCase("activeTo")) {
            result.setActiveTo((Date) object);
        } else if (string.equalsIgnoreCase("descFr")) {
            result.setDescFr((String) object);
        } else if (string.equalsIgnoreCase("descNl")) {
            result.setDescNl((String) object);
        } else if (string.equalsIgnoreCase("descDe")) {
            result.setDescDe((String) object);
        } else if (string.equalsIgnoreCase("type")) {
            result.setType((String) object);
        } else if (string.equalsIgnoreCase("idFact")) {
            result.setIdFact((Long) object);
        } else if (string.equalsIgnoreCase("idParent")) {
            result.setIdParent((Long) object);
        } else if (string.equalsIgnoreCase("isCode")) {
            result.setIsCode((Boolean) object);
        } else {
            throw new RuntimeException("unknown field");
        }

    }

    @Override
    public List transformList(List list) {
        return list;
    }
}

in hibernate 3 you could set Aliasses to queries but you can't do that anymore in hibernate 5 (correct me if I'm wrong) hence the aliasToBean is something you only can use when actually using aliasses; which I didn't, hence the exception.

A: Im my case :

 => write sql query and try to map result to Class List
 => Use "Transformers.aliasToBean"
 => get Error "cannot be cast to java.util.Map"

Solution :
      => just put \" before and after query aliases
      ex:
      "select first_name as \"firstName\" from test"

The problem is that Hibernate converts aliases for column names to upper case or lower case

A: I solved it by defining my own custom transformer as given below -
import org.hibernate.transform.BasicTransformerAdapter;

public class FluentHibernateResultTransformer extends BasicTransformerAdapter {

    private static final long serialVersionUID = 6825154815776629666L;

    private final Class<?> resultClass;

    private NestedSetter[] setters;

    public FluentHibernateResultTransformer(Class<?> resultClass) {
        this.resultClass = resultClass;
    }

    @Override
    public Object transformTuple(Object[] tuple, String[] aliases) {
        createCachedSetters(resultClass, aliases);

        Object result = ClassUtils.newInstance(resultClass);

        for (int i = 0; i < aliases.length; i++) {
            setters[i].set(result, tuple[i]);
        }

        return result;
    }

    private void createCachedSetters(Class<?> resultClass, String[] aliases) {
        if (setters == null) {
            setters = createSetters(resultClass, aliases);
        }
    }

    private static NestedSetter[] createSetters(Class<?> resultClass, String[] aliases) {
        NestedSetter[] result = new NestedSetter[aliases.length];

        for (int i = 0; i < aliases.length; i++) {
            result[i] = NestedSetter.create(resultClass, aliases[i]);
        }

        return result;
    }
}

And used this way inside the repository method -
@Override
    public List<WalletVO> getWalletRelatedData(WalletRequest walletRequest,
            Set<String> requiredVariablesSet) throws GenericBusinessException {
        String query = getWalletQuery(requiredVariablesSet);

        try {
            if (query != null && !query.isEmpty()) {
                SQLQuery sqlQuery = mEntityManager.unwrap(Session.class).createSQLQuery(query);
                return sqlQuery.setResultTransformer(new FluentHibernateResultTransformer(WalletVO.class))
                        .list();
            }
        } catch (Exception ex) {
            exceptionThrower.throwDatabaseException(null, false);
        }

        return Collections.emptyList();
    }

It worked perfectly !!!

A: Try putting Column names and field names both in capital letters.

A: This exception occurs when the class that you specified in the AliasToBeanResultTransformer does not have getter for the corresponding columns. Although the exception details from the hibernate are misleading.


Q: RxJava: Observable and default thread I have the following code:
Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(@NonNull final ObservableEmitter<String> s) throws Exception {
                Thread thread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        s.onNext("1");
                        s.onComplete();
                    }
                });
                thread.setName("background-thread-1");
                thread.start();
            }
        }).map(new Function<String, String>() {
            @Override
            public String apply(@NonNull String s) throws Exception {
                String threadName = Thread.currentThread().getName();
                logger.logDebug("map: thread=" + threadName);
                return "map-" + s;
            }
        }).subscribe(new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {}

            @Override
            public void onNext(String s) {
                String threadName = Thread.currentThread().getName();
                logger.logDebug("onNext: thread=" + threadName + ", value=" + s);
            }

            @Override
            public void onError(Throwable e) {}

            @Override
            public void onComplete() {
                String threadName = Thread.currentThread().getName();
                logger.logDebug("onComplete: thread=" + threadName);
            }
        });

And here's the output:
map: thread=background-thread-1
onNext: thread=background-thread-1, value=map-1
onComplete: thread=background-thread-1

Important detail: I'm calling the subscribe method from another thread (main thread in Android).
So looks like Observable class is synchronous and by default and it performs everything (operators like map + notifying subscribers) on the same thread which emits events (s.onNext), right? I wonder... is it intended behaviour or I just misunderstood something? Actually I was expecting that at least onNext and onComplete callbacks will be called on the caller's thread, not on the one emitting events. Do I understand correctly that in this particular case actual caller's thread doesn't matter? At least when events are generated asynchronously.
Another concern - what if I receive some Observable as a parameter from some external source (i.e. I don't generate it on my own)... there is no way for me as its user to check if whether it is synchronous or asynchronous and I just have to explicitly specify where I want to receive callbacks via subscribeOn and observeOn methods, right?
Thanks!

A: RxJava is unopinionated about concurrency. It will produce values on the subscribing thread if you do not use any other mechanisem like observeOn/ subscribeOn. Please don't use low-level constructs like Thread in operators, you could break the contract.
Due to the use of Thread, the onNext will be called from the calling Thread ('background-thread-1'). The subscription happens on the calling (UI-Thread). Every operator down the chain will be called from 'background-thread-1'-calling-Thread. The subscription onNext will also be called from 'background-thread-1'.
If you want to produce values not on the calling thread use: subscribeOn. If you want to switch the thread back to main use observeOn somewhere in the chain. Most likely before subscribing to it.
Example:
Observable.just(1,2,3) // creation of observable happens on Computational-Threads
            .subscribeOn(Schedulers.computation()) // subscribeOn happens only once in chain. Nearest to source wins
            .map(integer -> integer) // map happens on Computational-Threads
            .observeOn(AndroidSchedulers.mainThread()) // Will switch every onNext to Main-Thread
            .subscribe(integer -> {
                // called from mainThread
            });

Here is a good explanitation.
http://tomstechnicalblog.blogspot.de/2016/02/rxjava-understanding-observeon-and.html


Q: How to use a for loop to display an image depending on a position in an index? This is inside a react-native project:
I have a progress bar that has 10 positions, and each position as a possibility of three states - incomplete, active, complete. There is an image that corresponds to each of those states. I was thinking I could use a for loop that would look for the index number of the page, which I'll store in an object, and depending on the relationship between the position in the loop and and the index number, that would determine which image gets displayed. Something like this:
if the position in the loop > index number, display the incomplete image

if the position in the loop = index number, display the active image

if the position in the loop < index number, display the complete image

Beyond this, I'm not even sure on where to start.

A: In your class/component:
  state = {
    indexNum: 4, // arbitrary value
  }

  displayStatus(item) {
    if(item.id > this.state.indexNum){ // Incomplete
      return <View style={styles.progressPoint}><Text>I</Text></View>;
    }
    else if(item.id == this.state.indexNum){ // Active
      return <View style={styles.progressPoint}><Text>A</Text></View>;
    }
    else if(item.id < this.state.indexNum){ // Complete : you can use only 'else' here
      return <View style={styles.progressPoint}><Text>C</Text></View>;
    }

  }

In render() of your class/component:
    // Positions/Pages - these will serve as basis for .map - you can add more than 'id'
    const positions  = [{"id": 1},{"id": 2},{"id": 3},{"id": 4},{"id": 5},
                       {"id": 6},{"id": 7},{"id": 8},{"id": 9},{"id": 10}];
    return (
       <View style={styles.container}>
          {positions.map((item) => (
             this.displayStatus(item)
          ))}
       </View>
    );

Here's an Expo Snack of the above (based on the scope of your question) to get you started.
You can store the index number of the page in state and update this state at completion of each progress position. Note: if you are not using redux, you may need to pass/handle state (index number) on each page individually (depending on your navigation or components structure).


Q: CORS Configuration Flask, Angular and NGINX I'm trying to upload an angular application to a digital ocean droplet using nginx. This app consumes an API in flask. In local everything works pretty well, but on the VPS is not working. It says something about Cross-origin request blocked: Same origin policy does not allow reading of remote resources at http://127.0.0.1:5001/api/talk/
Here's my nginx configuration:
server {
    server_name x.domain.com;
    location / {
            proxy_pass http://127.0.0.1:4200;
            proxy_set_header Host x.domain.com;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Protocol $scheme;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_set_header Origin "";
            add_header "Access-Control-Allow-Origin"  "*";
            add_header "Access-Control-Allow-Methods" "GET, POST, OPTIONS, HEAD";
            add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept";
    }
 }
 server {

    location / {
            proxy_pass http://127.0.0.1:5001;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Protocol $scheme;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_set_header Origin "";
            add_header "Access-Control-Allow-Origin"  "*";
            add_header "Access-Control-Allow-Methods" "GET, POST, OPTIONS, HEAD";
            add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept";
    }

    location /api/talk/ {
            proxy_pass http://127.0.0.1:5001;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Protocol $scheme;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_set_header Origin "";
    }

    location /api/response/ {
            proxy_pass http://127.0.0.1:5001;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Protocol $scheme;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_set_header Origin "";
    }
 }

Here's my flask configuration:
app = Flask(__name__)
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})

chat = Chat()

@app.route('/api/talk/', methods=['POST'])
@cross_origin(origin='localhost')
def index():
  print(request.data.decode("utf-8"))
  chat.send_message(request.data)
  return request.data

@app.route('/api/response/', methods=['GET'])
@cross_origin(origin='localhost')
def get():
  response = chat.response
  return response

def options(self):
  return {'Allow': 'POST'}, 200, \
    {'Access-Control-Allow-Origin': '*',
     'Access-Control-Allow-Methods': 'POST,GET'}

if __name__ == '__main__':
  app.run(host='127.0.0.1', port=5001, debug=True)

And angular consumes the flask API here:
export class Message {
  constructor(public content: string, public sentBy: string){ }
}

@Injectable({
  providedIn: "root",
})
export class MessageService {
  conversation = new BehaviorSubject<Message[]>([]);
  readonly SERVER_URL = "http://127.0.0.1:5001";
  public httpClient = axios.create();

  constructor(){}

  update(msg: Message) {
    this.conversation.next([msg]);
  }

  converse(msg: string) {
    const userMessage = new Message(msg, 'user');
    this.update(userMessage);
    this.sendMessage(userMessage.content)
  }

  sendMessage(msg: string) {
    console.log(msg)
    const config = {
    headers: {
      'Content-Type': 'text/plain',
      'Access-Control-Allow-Headers': 'Content-Type',
      'Access-Control-Allow-Methods': 'GET POST',
      'Access-Control-Allow-Origin': '*'
    },
  };
  this.httpClient.post(this.SERVER_URL+'/api/talk/', btoa(msg), config)
    .then(function (response) {
  })
  .catch(function (error) {
     console.log(error);
   });
 }

 async getResponse() {
  await this.delay(900);
  let msg = ''
  return this.httpClient.get(this.SERVER_URL+'/api/response/')
  .then(response => {
     msg = response.data
     const botMessage = new Message(msg, 'chucho');
     this.update(botMessage);
     return msg
  })
  .catch(function (error) {
    console.log(error);
  });
}

 delay(ms: number) {
   return new Promise( resolve => setTimeout(resolve, ms) );
 }
}

My angular App runs on the 4200 port and the Flask API is on the 5001 port.
Hope you can help me.

A: Try enabling CORS like this -
but first install latest flask-cors by running -

pip install -U flask-cors

from flask import Flask
from flask_cors import CORS, cross_origin
app = Flask(__name__)
cors = CORS(app) # This will enable CORS for all routes

@app.route("/")
@cross_origin()
def helloWorld():
  return "Helloworld!"


Q: Finding the share of Marbles through Simple Arithmatic Fraction My 5th grader is practicing simple arithmatic fractions. He stumbled upon a question and now its troubling me too. I can't seem to solve the question without the help of Algebra which I can not explain to my kid without a proper introduction. Will appreciate if someone can give a hint on solving it without involving Algebraic expressions. Question goes as follows:
Peter, John and Mary share 78 marbles. Peter takes $\dfrac{1}{3}$ of the marbles and John takes thrice as many as Mary. Find the number of marbles John takes.
Edit: Apparently the question has been marked-down due to the absence of my attempt. So here it goes:
$\dfrac{1}{3}$ of 78 is 26. So Peter took 26 away from 78. 52 remains to distributed among John and Mary. From the given info John (J) keeps 3 times of the Mary's(M) share so J=3M. We know J + M = 52. We can substitute J in the equation that will become 3M + M = 52, therefore M = $52 \div 4$ $\implies$ M = 13. As J=3M, therefore J = $3\times 13$ which is 39. But this involves Algebra which I want to avoid explaining my kid at this moment.

A: To a 5th grader who cannot make algebraic equation, you can explain in steps -

*

*Remove $\frac{1}{3}$ of 78 marbles first and give to Peter

*Then make four equal parts with the remaining as one of them is taking three parts and the other is taking one part.

*Once we have made four parts, give one part to Mary and three parts to John.

There is a nice one you can try to explain to a 5th grader without algebraic equations:
There are total of 45 soldiers and horses. If there are 120 legs in total, how many soldiers and horses?


Q: QGIS - OTB - Object based classification - Segmentation - Does not work properly I'm using the OTB Toolbox to perform an object based classification on a raster (clipped ESRI satellite raster).
This raster result from an aggregation of several satellite imageries, which induces differences in the quality of the raster.
In some areas, the Segmentation tool isn't able to distinguish "green" and "blue" entities.
Here are the parameters I am using:

*

*Segmentation algorithm: meanshift

*Spatial radius: 2

*Range radius: 4

*Max/min iterations: 100

*ulco

*8 neighbor connectivity

*Minimum object size: 1

Here is the result:

In red, the segmentation isn't done properly.
I add a link to download the raster I am using, maybe it can help.
Raster Zone 8
In my situation, I'm trying to distinguish the mangrove dark green from other entities for a surface calculation.
If you know a better way to do so, I'm also interested.

A: I would use some pixel-wise machine learning approach for this task.

*

*traditional machine learning approach: build pixel features (Haralick indices, radiometric indices, etc.). You can use that with native OTB applications (HaralickTextureIndices + RadiometricIndices or BandMath + ConcatenateImages to compute your features image, then use the OTB image classification framework on it). You can directly use traditional OTB applications.

*deep learning: let the classifier find what's the best features. Use the otbtf remote module (see here for a short insight, dive in this book for more complete land cover mapping use cases with semantic segmentation and other fully convolutional approaches). You should have better results if you have enough terrain truth (say hundreds of labeled pixels will work well enough with a small deep net). You will have to use docker since otbtf is shipped in docker images.


Q: Difference between SomeValue {get;} = true; vs SomeValue => true; in Properties In C# you could declare a property in two ways that seem very similar:
public string SomeProperty => "SomeValue";

vs
public string SomeProperty { get; } = "SomeValue";

Is there a difference between these two? (Ignoring the fact that "SomeValue" is not a very interesting value, it could be the result of a method call or whatever else would express a difference between the two forms).

A: In your example there is no functional difference because you're always returning a constant value.  However if the value could change, e.g.
public string SomeProperty => DateTime.Now.ToString();

vs
public string SomeProperty { get; } = DateTime.Now.ToString();

The first would execute the expression each time the property was called.  The second would return the same value every time the property was accessed since the value is set at initialization.
In pre-C#6 syntax the equivalent code for each would be
public string SomeProperty
{
    get { return DateTime.Now.ToString();}
}

vs
private string _SomeProperty = DateTime.Now.ToString();
public string SomeProperty
{
    get {return _SomeProperty;}
}


Q: OrientDB: Select unique vertices but retain the edges I am trying to do the following weird thing. I have a group of edges that point towards a group of vertices, but there is some repetition - multiple edges point to the same vertices.
Given a SELECT command that gives me the list of edges, I want to:

*

*SELECT the unique vertices from all of the 'out' vertices

*Return, along with the @rid of the unique vertices, a list of all the edges that pointed towards them.

E.g. the result should be a list of vertices with (vertex rid, [edge 1, edge 2, edge 3]).
Another way to think about this is I want to GROUP BY outgoing vertex but somehow retain in a field the @rid's of all the edges I grouped.
Thanks!

A: You can try this:
in this you get for every vertex the outgoing edges
select $a.@rid, $a.outE() from 'your class'
let $a = (select from 'your class' where $parent.current.@rid = @rid)

if you want the ingoing vertices you have to change $a.outE() with inE(), like below:
select $a.@rid, $a.inE() from 'your class'
let $a = (select from 'your class' where $parent.current.@rid = @rid)

Hope it helps.
Regards.


Q: Use if/else statement without else branch I don't know how to use if else in this case. When score > 10, stop insert. Else continue insert as normally. But what is the syntax to do that?
CREATE TRIGGER invalidScore ON dbo.dbo_score
AFTER INSERT
AS
DECLARE @score DECIMAL;
SET @score = (SELECT s.score FROM Inserted s);
IF(@score > 10)
BEGIN
  RETURN 'score must be less than 10'
  ROLLBACK TRAN
END
ELSE
BEGIN
END

A: First, creating these types of sql objects should use begin.. end blocks. Second is,you can ignore the else statement.
CREATE TRIGGER invalidScore ON dbo.dbo_score
AFTER INSERT
AS
BEGIN
    DECLARE @score DECIMAL;
    SET @score = (SELECT s.score FROM Inserted s);
    IF(@score > 10)
        BEGIN
            RETURN 'score must be less than 10'
            ROLLBACK TRAN
        END
END

A: There are 3 things you need to change for this trigger to work:

*

*Remove the else section - its optional.

*Handle the fact that Inserted may have multiple rows.

*Throw the error rather than using the return statement so you can handle it in the client. And throw it after rolling back the transaction in progress.

Corrected trigger follows:
create trigger invalidScore on dbo.dbo_score
after insert
as
begin
  if exists (select 1 from Inserted S where S.Score > 10) begin
    rollback tran;
    throw 51000, 'score must be less than 10', 1;
  end
end

A: 'Else' is an option section you can remove this and use it,but i may like you to consider using check constraints for scenarios like this rather than adding a trigger check on score column
e.g.
CREATE TABLE dbo.dbo_score(
Score int CHECK (score < 10)

);
A CHECK constraint is faster, simpler, more portable, needs less code and is less error prone


Q: Getting Warning on Play Store for using WRITE_CALL_LOG permission in android app I'm working on a project based on cloud backup which saves and restore user's call log. It was working fine for the previous version but now getting following warning. I added a description before taking permission from the user but still getting the warning.

Your app is requesting the following permission which is used by less
  than 1% of functionally similar apps: WRITE_CALL_LOG
Users prefer apps that request fewer permissions and requesting
  unnecessary permissions can affect your app's visibility on the Play
  Store. If these permissions aren't necessary, you may be able to use
  alternative methods in your app and request fewer permissions. If they
  are, we recommend providing an explanation to users of why you need
  the permissions. Learn more
Note: This guidance is based on a comparison with functionally similar
  apps, which change over time as new apps get published and existing
  apps change behavior. Therefore the warning may change even if you
  don't change your permission usage.

A: Its a warning.  If you need that permission (and it seems your app does), then you're fine.  If you didn't really need it, you should remove it.  Google isn't going to scan your description to see if you explain it, that level of AI isn't really possible yet.  So you'll continue to get the warning.


Q: Why could the Oracle not see past/understand her choice? Inspired by this Q&A: What is the choice the Oracle couldn't see beyond?
The accepted answer there states that the choice the Oracle is referring to in the question's quote is, in fact, her own choice to help Neo rather than just guide the One back to the Source like normal.
My question is, why can't she see past her choice? I mean, the answer to that is that she doesn't understand it, so I suppose my real question is in fact, is there any evidence (from the films or other canon sources) to explain why she can't understand her own choice to help Neo?

A: After re-watching the trilogy and reading this blog (specifically the "Love, Actually" part), I believe the answer is:
The Oracle could not understand her choice to help the humans end the war because it was an irrational choice based on becoming emotionally attached to them, counter to her original purpose
In the third film specifically, there is emphasis placed on machines effectively having "human emotions", most notably demonstrated by Neo's conversion with Rama-Kandra in Mobil Avenue:

Rama-Kandra: No. I don’t mind. The answer is simple. I love my daughter very much. I find her to be the most beautiful thing I’ve ever seen. But where we are from, that is not enough. Every program that is created must have a purpose; if it does not, it is deleted. I went to the Frenchman to save my daughter. You do not understand.
Neo: I just have never…
Rama-Kandra: …heard a program speak of love?
Neo: It’s a… human emotion.
Rama-Kandra: No, it is a word. What matters is the connection the word implies. I see that you are in love. Can you tell me what you would give to hold on to that connection?
Neo: Anything.
Rama-Kandra: Then perhaps the reason you’re here is not so different from the reason I’m here.
The Matrix Revolutions transcript

This shows that machines/programs are capable of forming "connections" that are akin to human emotions such as "love", despite being irrational. Sati was created without purpose, out of love, after all.
From the blog I link above:

These programs are experiencing a profound connection to each other, one that they're using the word 'love' to describe, since it's as good a word as any, and it shares a reasonably close meaning with Neo's understanding of the word.

If these programs are capable of "irrational" connections that are comparable to "love", then it makes sense that the Oracle has developed a profound connection with the humans race, especially since she's been studying them (that's why she was originally created, after all):

Architect: ... Thus the answer was stumbled upon by another – an intuitive program, initially created to investigate certain aspects of the human psyche. If I am the father of the matrix, she would undoubtedly be its mother.
Neo: The Oracle.
The Matrix Reloaded transcript

She even makes the same choice again, according to this line, despite the fact that she cannot understand her choice:

Oracle: I made a choice, and that choice cost me more than I wanted it to.
Morpheus: What choice?
Oracle: To help you to guide Neo. Now, since the real test for any choice is having to make the same choice again, knowing full well what it might cost – I guess I feel pretty good about that choice, ’cause here I am, at it again.
The Matrix Revolutions transcript

"I guess I feel pretty good about that choice" doesn't sound like she understands it, but the fact that she's describing it as "feeling good" makes it sound more like an irrational "emotional" choice rather than the sort of logical decision we'd expect from a machine/program.
Generally speaking, it seems that the Oracle has come to value emotional connections such as "love", as we see her "teaching" to Sati:

(Oracle’s kitchen)
Oracle: That’s it. That’s the secret. You’ve got to use your hands.
Sati: Why?
Oracle: Cookies need love like everything does.
The Matrix Revolutions transcript

The "like everything does" part shows us that perhaps her understanding of purpose is evolving past that of some machines/programs (certainly the Architect), likely as a result of her studying humans and their emotional connections. Simply playing out one's purpose as many machines/programs isn't as important as connections such as "love".
I conclude that she must have somehow come to "love" or otherwise care about the human race, and then decided to help them, despite the fact that she did not understand why, since that wasn't part of her original purpose (which was merely to study them). Although she isn't an exile, she does essentially go against her purpose, against the system, but in secret, hoping that the outcome would be as she predicted, despite not being able to see past her own choice.

Seraph: Did you always know?
Oracle: Oh no. No, I didn’t. But I believed. I believed.
The Matrix Revolutions transcript


Q: macro para eliminar filas duplicadas quiero hacer una macro para eliminar filas duplicadas por ID. El rango no debe seleccionar filas fijas, ya que el fichero se va alimentando con nuevas filas. las columnas siempre permanecen las mismas y en el mismo orden. ¿Alguien me puede ayudar? Gracias!

A: Para eliminar las filas duplicadas en documentos de Excel puedes hacer uso de una Macro, en tu ventana de Visual Basic vas a agregar el siguiente código:
Sub nombremacro()
Dim fila As Long
  With Application
         For fila = Cells(Rows.Count, 1).End(xlUp).Row To 1 Step -1
          If .WorksheetFunction.CountIf(Range(«A:A»), _
              Cells(fila, 1)) > 1 Then Cells(fila, 1).EntireRow.Delete
      Next fila
       End With
End Sub

Después de guardar tu Macro ya las próximas veces que quieras ejecutarla debes hacerlo desde Herramientas/Macro y seleccionar la Macro según el nombre que le asignaste, en el ejemplo le asigne el nombre de nombremacro


Q: Conditional redirection with logout I've been asked to implement a custom redirection in WordPress. It seemed quite simple at first but I have no idea how to get it right. So much that I can't even get started with it.
This is how it should go:

*

*The user logs in, and the database gets queried using the wp_login hook

*If a certain condition is met, the user gets logged out using wp_logout() from the wp_login hook

*This is where the problem comes in, the user should get redirected to a page dedicated to them, without breaking the normal logout function

So if the user logs out normally, they get redirected to the default page, however if the condition is met they get redirected to another page and still get logged out.
I've tried the wp_logout and wp_clear_auth_cookie hooks, but to no avail.
I can't really show you any code, as I did not manage to come up with anything concrete.
edit:
 ....
 //in the login hook
 if($condition)
    wp_logout();
 ...
 add_action("wp_login","login_hook",10,2);

 //below the login hook
 function logout(){
    if($condition){
      wp_redirect(home_url("/redirectTo"));
      exit;
     }
  }
 add_action("wp_logout","logout");

A: The action to hook off is on line 603 of pluggable.php according to the codex link.
add_action( $hook, $function_to_add, $priority, $accepted_args ); is the format you should use so it would probably look something like:
 add_action( 'wp_logout' , 'logout_page' );

 function logout_page() {
   // Work out your conditions

     if($condition1) {
       $page = *page*; // whatever page
     } else if ($condition2) {
       $page = *page*; // whatever page
     }

   header("Location: /$page");
  }

I haven't done much with the logout hook but unless the function has already output something (which it would seem unlikely at that stage) the header should take you to the right page.

A: The wp_logout() function is pluggable. You should be able to write your own version and "overload" the Core function:
function wp_logout() {

  $lid = get_current_user_id();

  wp_destroy_current_session();
  wp_clear_auth_cookie();

  do_action( 'wp_logout' );
  /**
    * Fires after a user is logged-out.
    *
    * @since 1.5.0
    */
  if (2 == $lid) {
    wp_redirect(home_url("/redirectTo"));
    exit;
  }

}


Q: panels expanded in viewport in my west region panel there is smth. like the task panel here:
http://dev.sencha.com/deploy/dev/examples/tasks/tasks.html
the data is loaded from 2 different 's containing only  with links
the first "task" group is always expanded to all the height of the document, though there are much less data there.
here is the code:
new Ext.Panel({
            region: 'west',
            title: 'דוחות',
            id: 'w',
            header: false,
            width: 190,
            split: true,
            layout: 'fit',
            collapseMode: 'mini',
            //minWidth: 100,
            baseCls:'x-plain',
            margins: '0 1 0 0',
            items: [ new Ext.Panel({
                    id:'wp',
                    frame:true,
                    title: 'דוחות לעובדים',
                    collapsible:true,
                    contentEl: 'workerRep',
                    //titleCollapse: true
                    }),
                    new Ext.Panel({
                    frame:true,
                    id:'mp'
                    title: 'דוחות למכונות',
                    collapsible:true,
                    contentEl:'machRep',
                    layout: 'fit',
                    //titleCollapse: true
                    })
                     ]

What could be the problem?

A: Ext.layout.FitLayout ( which is what layout: 'fit' stands for) is for situations when you anly have one item in a container, because it tries to 'fit' this one component to the full size of the container.
From manual:

This is a base class for layouts that contain a single item that automatically expands to fill the layout's container.

If you have more than one item in container use different layout like Ext.layout.ContainerLayout (default one), Ext.layout.VBoxLayout or perhaps Ext.layout.TableLayout.

A: found the answer, the problem was here:
baseCls:'x-plain',


Q: How to append to array in for loop? How can I append my results in this array so I can use it later ?
 var animalQuestion = [(orderlist: Int, questionid:String, question: String, description: String)]()

This is my array which I declared in my class above.
let stmt = try db.prepare("SELECT * FROM allquestion_other where allquestion_other.name= 'animalChoice' and allquestion_other.id NOT IN (select answerresult.questionId FROM answerresult where answerresult.friendUserId='\(friendUserId)')")
        for row in stmt {

            let orderlist = row[4]
            let questionid = row[0]
            let question = row[6]
            let description = row[7]

        animalQuestion.append(orderlist: orderlist, questionid: questionid, question: question, description: description)

            }

When i'm running this code , i'm getting the error "Cannot call value of non-function type '[(orderlist: Int, questionid: String, question: String, description: String)]'"
row[4] row [0]row [6]row [7] is returning some values which I need to append in my array

A: Try to use:
animalQuestion.append((orderlist: orderlist, questionid: questionid, question: question, description: description))

And do not forgot:
let orderlist = row[4] as Int

Your code incorrect because of:
1) For appending new objects to array you must to use array-method
animalQuestion.append(<Array object>)
2) In your case Array object is a tuple. So first you need to create a tuple, something like:
let orderTuple = (orderlist, questionid, question, description)

and after that appaned orderTuple to animalQuestion array like:
animalQuestion.append(orderTuple)


Q: Sl4A Selecting running application from notification window I have a SL4A program I have written.  I have one issue before i'm ready to publish it.
For some reason when the app is running,  if I home screen out of the app,  I see it running in the notification area,  but when I select it nothing happens.  However if I click my icon from apps area it will bring the app back up.
Any suggestions?

A: Notifications created by SL4A do nothing; they have no callback and can only alert users. Unfortunately there isn't really any way around this: BeanShell, JRuby and Rhino can make Java API calls (eg., to add the 'open my app when clicked' part) but can't use Contexts (which notifications require), and you could make your own version of the API facade, but then users would be required to install your specific version of x (eg., Python) for Android.
Otherwise all I could think of would be to get tricky with Intents or something and include an activity in the /src of your app to show the notification, though that would likely require learning Java / Android programming meaning you may as well follow through and write the entire app natively.
Sorry, but there really isn't an easy way to do this

A: You stated you wanted to publish it so I am assuming you were implying that in the long run you will be compiling it into a standalone apk?
If so, which package are/will you be using? py4a's method, python27, kivy? From my experiences when you compile to an apk with python27, there is no notification window at the top at all but if you were to compile it using py4a's method it should create a workable notification item for you. Please see the following link for further information: http://code.google.com/p/android-scripting/wiki/SharingScripts
Otherwise ProfSmiles answer is correct but it appears to be a much more complex solution then using the py4a method.
You can also see the python27 project if you would like a more embedded approach, although as mentioned previously it does not have a notification setup by default like py4a.
Kivy's implementation also looks promising but I am unfamiliar with it, it might also be worth looking at further: https://github.com/kivy/python-for-android

A: Well It seems that you can see the notifications started by SL4A "como.googlecode.android_scripting" package with the following command:
This is more like a hack.
dumpsys statusbar | grep "pkg=com.googlecode.android_scripting"

Every notification initiated by SL4A will have an "id". For example the "id=1" is the notification started by SL4A when the server is running. The one you click to stop the server.
With this in mind you can can actually list every notification started by your package and block until the id of your notification disappear.
If so then your next notifications should have an id with 2 or above. Note that this can change if SL4A is stopped or crash. The next time you may get the "id=2" for the (RPC) server notification and then "id=3" and over for your app notifications until you restart your device and so the RPC server notification goes back to "id=1". Knowing this means that you need to keep searchig for new notifications within a loop.
For example in bash and using adb:
while read Info; do echo "$Info" | grep 'pkg=com.googlecode.android_scripting'; done < <(adb shell dumpsys statusbar)

You'll get something like this:
1: StatusBarNotification(pkg=com.googlecode.android_scripting id=2 tag=null score=0 notn=Notification(pri=0 contentView=com.googlecode.android_scripting/0x109008f vibrate=null sound=null defaults=0x0 flags=0x62 kind=[null]) user=UserHandle{0}) # SL4A RPC Notification
7: StatusBarNotification(pkg=com.googlecode.android_scripting id=3 tag=null score=0 notn=Notification(pri=0 contentView=com.googlecode.android_scripting/0x109008f vibrate=null sound=null defaults=0x0 flags=0x10 kind=[null]) user=UserHandle{0}) # My Notification
Let's play with this!
Running:
while read Info; do echo "$Info" | grep "pkg=com.googlecode.android_scripting" | awk '{print $3}' | cut -s -d '=' -f2 ; done < <(adb shell dumpsys statusbar)

Will get you for example:
# Without Using Cut
id=2 # SL4A Notificaion
id=3 # My Notification

Or:
# Using Cut
2 # SL4A Notification
3 # My Notification

Let's get to the action! (An ugly solution)
# Start ADB USB Serial Connection
adb devices

# Activate Wireless ADB (Needs Root) - Not Needed
# adb shell setprop service.adb.tcp.port 5555
# stop adbd
# start adbd

Or:
# Start ADB Wireless
adb connect 192.168.1.3

NotifyCount=0
NotifyList=()

while read Notify; do

   DumpNotify=`echo "$Notify" | grep "pkg=com.googlecode.android_scripting" | awk '{print $3}' | cut -s -d '=' -f2`

   if [ ! -z "$DumpNotify" ] ; then
      NotifyList[$NotifyCount]="$DumpNotify"
      ((NotifyCount++))
   fi

done < <(adb shell dumpsys statusbar)

SL4ARPCNotification="2"
MyScriptNotification="3"

if [[ ${NotifyList[*]} != *"$MyScriptNotification"* ]] ; then
   adb shell am start -a android.intent.action.MUSIC_PLAYER
fi

This should be better in 2 functions with arguments for MyNotification and SL4ARPCNotification variables. That way you can verify from anywhere in the code and divide the job: FunctionX for listing the notifications and FunctionY for comparing the results.
This can easily be done in Pyhon or other interpreters. You need to remember that there's always a notification from SL4A itself. By using Threading in python you can continuously search for new or old notifications without the need to block your program waiting for a change and thus you can continue runninig your script normally.


Q: Values of the synthetic control created by Synth package in R I'm using the Synth package in R. I properly created my dataprep.out and synth(dataprep.out). Following, I created my path.plot and it's very fine.
Now I want to find the values estimated by Synth for my outcome variable for each time period. Where can I find this info, please?
Thanks in advance
I cannot find the values of the outcome variable created by Synth throughout my time periods. The plot created by path.plot shows the trajectory of the synthetic estimator, but not the values estimated.


Q: File Upload Error in Asp.net VB I am trying to add a fileupload control to my aspx page so the user can add pictures, but when I am implementing the code behind on VB the fileuploader controler is not recognized.
I have this on aspx page inside a formview:
<InsertItemTemplate>
    <div id="TaskScreenError">
        Upload a Screenshot of Error:
        <asp:FileUpload ID="ErrorScreen" runat="server"   />
    </div>
<InsertItemTemplate>

And I have the following code on my VB, but it says ErrorScreen is not declared.
Dim filereceived As String = ErrorScreen.PostedFile.FileName
    ' validate the file to ensure it is an image
    Select Case Right(filereceived, 4)
        Case ".jpg", ".tif", ".bmp", ".gif"
        Case Else
            lblErrMsg.Text = "Image is in a format we don't accept, please use jpg, tif, bmp or gif."
            Exit Sub
    End Select
    ...

It might be something really stupid but I cant figure it out what is the problem.
Please help.
Cheers

A: Since your FileUpload control is inside the InsertTemplate, you cannot access the FileUpload control directly. You have to do something like this:
Dim fileUpload As FileUpload = TryCast(YOURFORMVIEWID.FindControl("ErrorScreen"), FileUpload)
If fileUpload Is Nothing Then
    ' Handle if the FileUpload can't be found
Else
    Dim filereceived = fileUpload.PostedFile.FileName
    ' Continue your code here...
End If


Q: image rotation going to wide off of my screen how to keep static or shorten width? Hello guys I was wondering if anyone has a quick fix to my image rotating way to far off my screen and causes my app to have scroll bars and not appealing to the eye maybe have the image just spinning in place to make my formatting issues easier
here is my code
  JS

HTML

A: As markE said set the transform-origin to the center of the image, so something like this:
elem.style.transform-origin = "50% 50%";
elem.style.transform = "rotate("+degrees+"deg)";

You can use -ms- and -webkit- for this in your code too for cross compatability.
Slightly unrelated, I suggest using:
degrees = degrees%360;

instead of your if statement where you wrap from 359 to 1 degrees.
This is because it will work in more general situations, so is less likely to break. For example if you changed the amount of degrees no by +1 but by +10 or -10 it would still wrap correctly between 0 and 360.


Q: Choosing marker size in Matplotlib I am doing a scatter plot with square marker in matplotlib like this one:
.
I want to achieve something like this:

Which means I have to adjust the marker size and the figure size/ratio in such a way that there are no white space between markers. Also there should be a marker per index unit (x and y are both integers) so if y goes from 60 to 100, there should be 40 markers in y direction. At the moment I am tuning it manually. Any idea on what is the best way to achieve this?

A: I found two ways to go about this:
The first is based on this answer. Basically, you determine the number of pixels between the adjacent data-points and use it to set the marker size. The marker size in scatter is given as area.
fig = plt.figure()
ax = fig.add_subplot(111, aspect='equal')

# initialize a plot to determine the distance between the data points in pixel:
x = [1, 2, 3, 4, 2, 3, 3]
y = [0, 0, 0, 0, 1, 1, 2]
s = 0.0
points = ax.scatter(x,y,s=s,marker='s')
ax.axis([min(x)-1., max(x)+1., min(y)-1., max(y)+1.])

# retrieve the pixel information:
xy_pixels = ax.transData.transform(np.vstack([x,y]).T)
xpix, ypix = xy_pixels.T

# In matplotlib, 0,0 is the lower left corner, whereas it's usually the upper
# right for most image software, so we'll flip the y-coords
width, height = fig.canvas.get_width_height()
ypix = height - ypix

# this assumes that your data-points are equally spaced
s1 = xpix[1]-xpix[0]

points = ax.scatter(x,y,s=s1**2.,marker='s',edgecolors='none')
ax.axis([min(x)-1., max(x)+1., min(y)-1., max(y)+1.])

fig.savefig('test.png', dpi=fig.dpi)

The downside of this first approach is, that the symbols overlap. I wasn't able to find the flaw in the approach. I could manually tweak s1 to
s1 = xpix[1]-xpix[0] - 13.

to give better results, but I couldn't determine a logic behind the 13..
Hence, a second approach based on this answer. Here, individual squares are drawn on the plot and sized accordingly. In a way it's a manual scatter plot (a loop is used to construct the figure), so depending on the data-set it could take a while.
This approach uses patchesinstead of scatter, so be sure to include
from matplotlib.patches import Rectangle

Again, with the same data-points:
x = [1, 2, 3, 4, 2, 3, 3]
y = [0, 0, 0, 0, 1, 1, 2]
z = ['b', 'g', 'r', 'c', 'm', 'y', 'k'] # in your case, this is data
dx = [x[1]-x[0]]*len(x)   # assuming equally spaced data-points

# you can use the colormap like this in your case:
# cmap = plt.cm.hot

fig = plt.figure()
ax = fig.add_subplot(111, aspect='equal')
ax.axis([min(x)-1., max(x)+1., min(y)-1., max(y)+1.])

for x, y, c, h in zip(x, y, z, dx):
    ax.add_artist(Rectangle(xy=(x-h/2., y-h/2.),
                  color=c,             # or, in your case: color=cmap(c)
                  width=h, height=h))  # Gives a square of area h*h

fig.savefig('test.png')

One comment on the Rectangle: The coordinates are the lower left corner, hence x-h/2.
This approach gives connected rectangles. If I looked closely at the output here, they still seemed to overlap by one pixel - again, I'm not sure this can be helped.


Q: Is the 'positive question record' a rolling count, and if so how do I work out how many days until it will be positive again? I am '33/30' for the Inquisitive badge, but as I don't have 'positive question record' in the last 30 days, I can't get it yet.

The badge text says:

Asked a well-received question on 30 separate qualifying days, and have a positive question record

Based on the formula in How is a "positive question record" calculated?

(total questions - negative questions - closed - deleted)/total questions ≥ 0.5

And this query I'm not clear how many more days of good questions I need to have.
I'm trying to figure out, assuming the 'total questions' is for the '30 separate qualifying days', that is, it's a rolling score over the 30 separate days, how many more days I need to have a positive (0+ score, not closed, not deleted) question on to bump my 'score' up enough to get the badge?
For instance, say in the last '30 separate qualifying days' I ask 30 questions: the most recent 14 of which are positively received (0+ score, not closed, not deleted) and the first 16 were closed/deleted/negatively scored. My score in theory would be:
score = (total questions - negative questions - closed - deleted)/total questions ≥ 0.5
score = (30 - 0 - 0 - 16)/30
score = 14/30
score = 0.467
0.5 ≥ 0.467

So I would not be considered to have a positive question record for those '30 separate qualifying days'.
Then for the next X days, I ask one positively received (0+ score) question. That would mean on day 30+X, my closed/deleted/negative count is 16-X.
score = (total questions - negative questions - closed - deleted)/total questions ≥ 0.5
score = (30 - 0 - 0 - (16-X))/30
score = 14+X/30
14+X/30 ≥ 0.5
X = 15-14 = 1

So, unless I'm mistaken, that means I'd only need 1 day of positively scored questions, as the non-positively received on day 1 is 'removed' from the rolling total of '30 separate qualifying days'?
However, if all of my non-positively received questions are in the later half of the '30 separate qualifying day' period, I wouldn't end up removing even one from the count until after 16 days of positively (0+) scored questions.
How do I figure out, where in this '30 separate qualifying day' window I am, and when the non-positively received questions age off?


Q: How to join tables without identifiers? For school I have to do this:
Query what salary scale an employee belongs to displaying these columns:
s_schaal.schaal, werknemer.name, werknemer.salaris

But there are no identifiers between the tables. All I have is a bottom line and upper line column (s_schaal.ondergens & s_schaal.bovengrens).
What MySQL query can I use to compare and join this data?

A: I finally figured that joining these tables would not bring a solution. I solved it doing this:
SELECT S.schaal, W.wnr, W.wnaam, W.salaris FROM Werknemer W, S_schaal S
WHERE W.salaris >= S.ondergrens && W.salaris <= S.bovengrens;


Q: How to sort search results by relevance in javascript I'm building a custom search, as of now if I enter "The R" I get the result list with The Fellow ship of the Ring first, because the phrase "the ring" it's in its .text. I want The Return of the King to be first. Is there a way I can give more relevance to the .name field or sort the match array based on the name .field and the input text?
HTML

      <form class="form-inline position-relative">
        <input id="search" class="form-control form-control-search" type="text" placeholder="Search..." aria-label="Search">
      </form>

JAVASCRIPT
const searchIndex = async searchText => {
 const res = await fetch('/data/index.json');
 const index = await res.json();

  matchList.classList.remove("d-none");
 // Get matches to current text input
 let matches = index.filter(index => {
  const regex = new RegExp(`${searchText}`, 'gi');
  return index.name.match(regex) || index.text.match(regex);
 });

 // Clear when input or matches are empty
 if (searchText.length === 0) {
   clearSearch();
 }

 outputHtml(matches);
};

function clearSearch(){
  matches = [];
  matchList.classList.add("d-none");
}

// Show results in HTML
const outputHtml = matches => {
 if (matches.length > 0) {
  const html = matches.map(function(match){
      return `

${match.name}

            ${match.type}

            Found in ${match.product}

            ${match.text}

`
    }
}).join('');
  matchList.innerHTML = html;
 }
};

index.JSON
 [
  {
    "name": "The Fellowship of the Rings",
    "type": "book",
    "text": "Bilbo reveals that he intends to leave the Shire for one last adventure, and he leaves his inheritance, including the Ring, to his nephew Frodo. Gandalf investigates...",
    "url": "books/the-fellowship-of-the-rings",
    "product": "Books"
  },
  {
    "name": "The Two Towers",
    "type": "book",
    "text": "Awakening from a dream of Gandalf fighting the Balrog in Moria, Frodo Baggins and Samwise Gamgee find themselves lost in the Emyn Muil near Mordor and discover they are being tracked by Gollum, a former bearer of the One Ring.",
    "url": "books/the-two-towers",
    "product": "Books"
  },
  {
    "name": "The Return of the King",
    "type": "book",
    "text": "Gandalf flies in with eagles to rescue the Hobbits, who awaken in Minas Tirith and are reunited with the surviving Fellowship.",
    "url": "books/the-return-of-the-king",
    "product": "Books"
  }
]

A: You could map your data to include relevance points:
const index = await res.json();
const searchTextLowercased = searchText.toLowerCase();

const rankedIndex = index.map(entry => {
    let points = 0;

    if (entry.name.toLowerCase().includes(searchTextLowercased)) {
        points += 2;
    }

    if (entry.text.toLowerCase().includes(searchTextLowercased)) {
        points += 1;
    }

    return {...entry, points};
}).sort((a, b) => b.points - a.points);

This way, you have ranked results in rankedIndex const.
Keep in mind that your code probably needs some refactoring, because you're fetching data on each search. I'm assuming your searchIndex() is called with every key press or something like that.


Q: TFTPboot using Uboot : TFTP server on Windows I have a TFTP server running on Windows-10 machine.
I am using MobaXterm it has TFTP server.

I tested client server running on same windows 10, machine, able to communicate.
TFTP -i 192.168.1.7 get test.txt
Transfer successful: 11 bytes in 1 second(s), 11 bytes/s

My TFTP server directory on windows is :--
C:\S32G2_images

My target board, using uboot i am trying to TFTPboot buts connection is not establishing with the TFTP server running on the windows 10 machine.
Please suggest how to resolve this ?
Target Board Uboot setting :--

PC, running windows-10 :--

Ping to TFTP server working from Uboot :--

trying to connect to TFTP server from Linux U-boot failing :--

Windows Firewall setting :--

A: Instead of trying from uboot.
I also tried to run the TFTP client from Linux booted onto my board.
PFE-2 setting on LINUX booted on S32G2 ;--

I added Windows-10 machine to my routing table  :--

I am able to ping from Linux running on my board to windows-10 machine :--

I am able to ping from windows-10 machine to Linux running on my board  :--

TFTP client on my board is part of busybox package.
But still same issue , not able to connect to tftp server on Windows-10 machine :--


Q: ttk Button: relief of the button is not taking effect I have button defined as below:
button_style = ttk.Style()
button_style.configure("button_style.TButton", relief=tk.RAISED,
                       width = 20, padding=6, font=('Helvetica', 12) )
self.button = ttk.Button (self.myContainer1, text="Browse", style='button_style.TButton',
                          command = self.browse_file)
self.button.grid(row = 0,column = 3,padx=5, pady=10, ipadx=5, ipady=5)

For some reason the relief effect of the button is not applied. Could somebody help me please?


Q: RAID-0 2х 256ГБ SSD, или достаточно одного SSD-512ГБ для большей производительности веб-сервера Хочу арендовать выделенный сервер. На нем будет несколько баз данных под веб-приложения (PHP+MySQL).
Допустим в сумме базы данных будут занимать почти все пространство (~500ГБ).
MySQL будет обрабатывать множество запросов к этим БД, причем выборка из БД случайная (т.е. затрагиваться будут записи из разных областей диска).
Как будет лучше с точки зрения производительности: заказать один SSD размером 512ГБ, или заказать два SSD по 256ГБ и объединить их в RAID-0?

A:
Вы имеете ввиду канал связи с "нешним миром"? 100мбит гарантия/1гбит
  shared

Ну вот, теперь смотрим производительность SSD дисков.

60 ГБ SSD-накопитель DEXP S1 [SATA III, чтение - 300 Мбайт/с, запись -
  270 Мбайт/с, Phison S3111-S11, MLC 2D NAND]
60 ГБ SSD-накопитель AFOX AFSN8T3BN60G [SATA III, чтение - 400
  Мбайт/с, запись - 260 Мбайт/с, Silicon Motion SM2258XT, TLC 3D NAND]
120 ГБ SSD-накопитель Smartbuy Splash 3 [SB120GB-SPLH3-25SAT3] [SATA
  III, чтение - 550 Мбайт/с, запись - 450 Мбайт/с, Marvell 88NV1120, TLC
  3D NAND]

Чтение 300 Мбайт/с это грубо говоря 3000 Мбит/с. То есть 3Гбита/с. В три раза больше, чем Вам предлагает провайдер на пике производительности (да еще когда он это Вам выдаст, может и никогда, скажет что "нет технической возможности"). Да и "100мбит гарантия" зачастую на практике означает 50мбит максимум. То есть Вам нет никакого резона ставить  RAID-0, так как производительность и одного диска гораздо больше, чем производительность Вашего канала.
UPD1:

По циклам записи, ожидается около обновлений 2-5 млн записей в день.

Смотря какого размера записи. Но вообще, правило такое:

*

*Если у Вас проект типа библиотеки, когда Вы один раз заливаете на сервер информацию, а потом пользователи ее только читают, то можно ставить SSD диск (при условии, что потоки чтения настолько большие, и канал связи настолько широкий, что тормозит производительность именно диска).

*Если у Вас проект типа youtube или инстаграмма, когда пользователи каждую секунду заливают Вам на сервер 100500 терабайт информации, то ставить SSD диск нет никакого смысла. Вам его запилят очень быстро, так как у SSD диска есть ограничение на количество записей.
UPD2:
А вообще-то выделенный сервер это довольно обязывающая вещь. Гораздо проще арендовать дисковое пространство и не заморачиваться техническими подробностями. А провайдер пусть сам следит и за балансом производительности, и за резервированием и за RAID-ами. Главное, выбрать нормального крупного провайдера с нормальной техподдержкой, а не пионеров из подвала. Впрочем, сейчас уже пионеров не осталось, всех съели.
UPD3:

так пишите, как будто любое телодвижение от диска улетает обратно
  пользователю по сети. Если субд потребуется прочитать всю таблицу на
  полгига размером c диска, и отдать обратно 100 записей, это ведь не
  потребует пропускания всех 500метров по сети, верно? – teran 1 минуту
  назад

Ну это надо смотреть. Если у Вас база данных с поиском (типа продажи авиабилетов), то локальная производительность диска может быть важна. Но все равно, балансы производительности запросов по сети и производительности дисковой подсистемы никто не отменял.


Q: how to change the size of the file from kilobyte into gigabyte using php i have here a code that saves a file the size is kilobyte but i want a size of a file that have a size into gigabyte but i do not know how to change it.
i need a help from you because im a beginner in the php and i don't know how to change the size of the file and i want to save a video in my database.
here is my code:
       <?php
            function output_file($file, $name, $mime_type='') {
        if(!is_readable($file)) die('File not found or inaccessible!');

        $size = filesize($file);
        $name = rawurldecode($name);
        $known_mime_types=array(
        "pdf" => "application/pdf",
        "txt" => "text/plain",
        "html" => "text/html",
        "htm" => "text/html",
        "exe" => "application/octet-stream",
        "zip" => "application/zip",
        "doc" => "application/msword",
        "xls" => "application/vnd.ms-excel",
        "ppt" => "application/vnd.ms-powerpoint",
        "gif" => "image/gif",
        "png" => "image/png",
        "jpeg"=> "image/jpg",
        "jpg" => "image/jpg",
        "php" => "text/plain"
          );
       if($mime_type=='') {
             $file_extension =
            strtolower(substr(strrchr($file,"."),1));

          if(array_key_exists($file_extension, $known_mime_types)) {
            $mime_type=$known_mime_types[$file_extension];
           } else {
                $mime_type="application/force-download";
           };
             };

            @ob_end_clean();

         if(ini_get('zlib.output_compression'))
         ini_set('zlib.output_compression', 'Off');
             header('Content-Type: ' . $mime_type);
         header('Content-Disposition: attachment; filename="'.$name.'"');
         header("Content-Transfer-Encoding: binary");
         header('Accept-Ranges: bytes');
          header("Cache-control: private");
          header('Pragma: private');
         header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
          if(isset($_SERVER['HTTP_RANGE']){
            list($a, $range) = explode("=",$_SERVER['HTTP_RANGE'],2);
          list($range) = explode(",",$range,2);
            list($range, $range_end) = explode("-", $range);
           $range=intval($range);
            if(!$range_end) {
                 $range_end=$size-1;
                       } else {
                       $range_end=intval($range_end);
                }
                    $new_length = $range_end-$range+1;
                         header("HTTP/1.1 206 Partial Content");
                            header("Content-Length: $new_length");
             header("Content-Range: bytes $range-$range_end/$size");
               } else {
                   $new_length=$size;
                        header("Content-Length: ".$size);
                   }
                  $chunksize = 1*(1024*1024);
                    $bytes_send = 0;
                if ($file = fopen($file, 'r') {
                   if(isset($_SERVER['HTTP_RANGE']))
                  fseek($file, $range);

               while(!feof($file) &&
                    (!connection_aborted()) &&
                                 ($bytes_send<$new_length)) {
                   $buffer = fread($file, $chunksize);
                    print($buffer);
                          flush();
                  $bytes_send += strlen($buffer);
                   }
                fclose($file);
                   } else

                  die('Error - can not open file.');
                     die();
                     }
                       set_time_limit(0);
                    $file_path='files/'.$_REQUEST['filename'];
                output_file($file_path, ''.$_REQUEST['filename'].'',
            'text/plain');
             ?>

A: For kilobyte divide it by 1048576. Did you need something more complicated than that?
$sizeInGB = $sizeInKB / 1048576;