text:
Q: How to show partial view I have a page with information, i want to add there a list (in a form of table) within a partial view. User has to have an ability to sort it by switching radio box.
My problem: the code works fine (i have tried in a separate view), but when i try to switch radio button (they submit page on change and activate 2nd method, which create new model according to radio button) i get html code only from my partial view.
In other words:
i want to : HTML from view1 + HTML from myPartial
i get: only HTML from myPartial
I suppose problem is here (calling my myPartial):
@Html.Action("_ShowEmployeeProjects", "Employee")

But when i try to use this:
@Html.Partial("Partial/_ShowEmployeeProjects")

I get this:

The model item passed into the dictionary is of type
  'BTGHRM.Models.EmployeeJobDataViewModel', but this dictionary requires
  a model item of type
  'System.Collections.Generic.List`1[BTGHRM.Models.EmployeeProjectHistoryModel]'.

My controllers code:
    public PartialViewResult _ShowEmployeeProjects()
    {
        int EmpId = HRMSession.SelectedEmployeeId;

        using (var db = new HRMEntities())
        {
            List<EmployeeProjectHistoryModel> list = (from t1 in db.ProjectWorkers
                                                      join t2 in db.Projects
                                                      on t1.ProjectId equals t2.ProjectId
                                                      where (t1.WorkerId == EmpId && t1.IsActive == true)
                                                      select new EmployeeProjectHistoryModel()
                                                      {
                                                          ProjectName = t2.ProjectName,
                                                          Activity = t1.Activity,
                                                          StartDate = t1.StartDate,
                                                          EndDate = t1.EndDate
                                                      }).ToList();
            return PartialView("Partial/_ShowEmployeeProjects",list);
        }
    }
    [HttpPost]
    public PartialViewResult _ShowEmployeeProjects(string ActiveOnlySelect)
    {
        int EmpId = HRMSession.SelectedEmployeeId;
        List<EmployeeProjectHistoryModel> list;
        using (var db = new HRMEntities())
        {
            if (ActiveOnlySelect.Equals("both"))
            {
                list = (from t1 in db.ProjectWorkers
                        join t2 in db.Projects
                        on t1.ProjectId equals t2.ProjectId
                        where (t1.WorkerId == EmpId)
                        select new EmployeeProjectHistoryModel()
                        {
                            ProjectName = t2.ProjectName,
                            Activity = t1.Activity,
                            StartDate = t1.StartDate,
                            EndDate = t1.EndDate
                        }).ToList();
                list.OrderBy(x => x.StartDate);
            }
            else
            {
                list = (from t1 in db.ProjectWorkers
                        join t2 in db.Projects
                        on t1.ProjectId equals t2.ProjectId
                        where (t1.WorkerId == EmpId && t1.IsActive == true)
                        select new EmployeeProjectHistoryModel()
                        {
                            ProjectName = t2.ProjectName,
                            Activity = t1.Activity,
                            StartDate = t1.StartDate,
                            EndDate = t1.EndDate
                        }).ToList();
                list.OrderBy(x => x.StartDate);
            }
        }
        return PartialView("Partial/_ShowEmployeeProjects", list);
    }

My partial:
@model    List<BTGHRM.Models.EmployeeProjectHistoryModel>
@using (Html.BeginForm("_ShowEmployeeProjects", "Employee", FormMethod.Post, new { type = "main" }))
{

            @Html.RadioButton("ActiveOnlySelect", "activeonly", true, new { id = "ActiveOnlySelect0", onchange = "this.form.submit();" })
            @Resources.Localization.show_only_actual

            @Html.RadioButton("ActiveOnlySelect", "both", new { id = "ActiveOnlySelect1", onchange = "this.form.submit();" })
            @Resources.Localization.show_all_data

}
@{
    WebGrid grid = new WebGrid(Model, canSort: false, rowsPerPage: 15);
if (Model.Any())
{

    @grid.GetHtml(
    tableStyle: "table",
    headerStyle: "table_HeaderStyle",
    footerStyle: "table_PagerStyle",
    rowStyle: "table_RowStyle",
    alternatingRowStyle: "table_AlternatingRowStyle",
    selectedRowStyle: "table_SelectedRowStyle",
    columns: grid.Columns(
        grid.Column("ProjectName", Resources.Localization.project, style: "p30"),
        grid.Column("Activity", Resources.Localization.activity, style: "p30"),
        grid.Column("StartDate", Resources.Localization.start_date, format: @<text>
            @if (item.StartDate != null)
            {
                @item.StartDate.ToShortDateString()
                @Html.Hidden("Model.StartDate", (object)item.StartDate.ToShortDateString())
            }
            else
            {

            }</text>, style: "p10"),
        grid.Column("EndDate", Resources.Localization.end_date, format: @<text>
            @if (item.EndDate != null)
            {
                @item.EndDate.ToShortDateString()
                @Html.Hidden("Model.EndDate", (object)item.EndDate.ToShortDateString())
            }
            else
            {

            }</text>, style: "p10")
    )
    )
}

}

A: It looks like you are passing a wrong model to your partial. The structure will be:
In your principal Layout:
@model System.Collections.Generic.List[BTGHRM.Models.your_model]

@Html.Partial("Partial/_ShowEmployeeProjects", Model.projects)

In your Partial, remember to get the model which you are passing from your main layout:
@model System.Collections.Generic.List[BTGHRM.Models.your_model.projects]

Then, in your controller, you must return return:
[HttpPost]
    public PartialViewResult _ShowEmployeeProjects(string ActiveOnlySelect)
    {
        // DO YOUR MAGIC
        // model should be a List[BTGHRM.Models.your_model]
        PartialView("Partial/_ShowEmployeeProjects", model);
    }

Model:
public class your_model
{
   List<Employee> employees;
   List<Project> projects;
.....
}


text:
Q: Swipe in Recycler when applied in ViewPager I have a viewpager that includes one recycler view.
Every item of the recycler view can be dismissed by swipe.
When i apply the recycler view in the view pager, the view pager does not allow the swipe-to-dismiss and overlay the control with the page swapping.
When i detect the swipe in the recycler, i disable the viewpager onInterceptTouchEvent, but the swipe movement initiated previously is restarted.
Anyone has a solution ?

A: Using a swipe action on a recyclerview item works against the swiping action of a viewpager. Essentially, you're telling the user to do the same action on the same screen to do two entirely different actions. This is bad design. Ask yourself if it is necessary to use both of these things. I had the same predicament and removed the viewpager entirely.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Google Cloud ML Engine + Tensorflow perform preprocessing/tokenization in input_fn() I want to perform basic preprocessing and tokenization within my input function. My data is contained in csv's in a google cloud storage bucket location (gs://) that I cannot modify. Further, I to perform any modifications on input text within  my ml-engine package so that the behavior can be replicated at serving time.
my input function follows the basic structure below:
filename_queue = tf.train.string_input_producer(filenames)
reader = tf.TextLineReader()
_, rows = reader.read_up_to(filename_queue, num_records=batch_size)
text, label = tf.decode_csv(rows, record_defaults = [[""],[""]])

# add logic to filter special characters
# add logic to make all words lowercase
words = tf.string_split(text) # splits based on white space

Are there any options that avoid performing this preprocessing on the entire data set in advance?  This post suggests that tf.py_func() can be used to make these transformations, however they suggest that "The drawback is that as it is not saved in the graph, I cannot restore my saved model" so I am not convinced that this will be useful at serving time.  If I am defining my own tf.py_func() to do preprocessing and it is defined in the trainer package that I am uploading to the cloud will I run into any issues? Are there any alternative options that I am not considering?

A: Best practice is to write a function that you call from both the training/eval input_fn and from your serving input_fn.
For example:
def add_engineered(features):
  text = features['text']
  features['words'] = tf.string_split(text)
  return features

Then, in your input_fn, wrap the features you return with a call to add_engineered:
def input_fn():
  features = ...
  label = ...
  return add_engineered(features), label

and in your serving_input fn, make sure to similarly wrap the returned features (NOT the feature_placeholders) with a call to add_engineered:
def serving_input_fn():
    feature_placeholders = ...
    features = ...
    return tflearn.utils.input_fn_utils.InputFnOps(
      add_engineered(features),
      None,
      feature_placeholders
    )

Your model would use 'words'.  However, your JSON input at prediction time would only need to contain 'text' i.e. the raw values.
Here's a complete working example:
https://github.com/GoogleCloudPlatform/training-data-analyst/blob/master/courses/machine_learning/feateng/taxifare/trainer/model.py#L107


text:
Q: NULL Pointer at InputStreamReader ClassPath Hi sadly i just dont get why i receive a nullpointer:
My ResourceLoader class
public static String loadResource(String path){
       StringBuilder result = new StringBuilder();
       try {
           InputStreamReader isr = new InputStreamReader(Class.class.getResourceAsStream(path)) ;
           BufferedReader reader = new BufferedReader(isr);
           String line = "";
           while((line = reader.readLine()) != null){
                result.append(line).append("\n");
           }
       }catch (IOException e){
           System.out.println("File nicht gefunden:  " + e);
       }
    return result.toString();
    }

This is where i use it
shaderProgram.createVertexShader(ResourceLoader.loadResource("shaders/mainVertex.glsl"));
shaderProgram.createFragmentShader(ResourceLoader.loadResource("shaders/mainFragment.glsl"));

This is the Exeption i receive
java.lang.NullPointerException
    at java.base/java.io.Reader.<init>(Reader.java:167)
    at java.base/java.io.InputStreamReader.<init>(InputStreamReader.java:72)
    at utils.ResourceLoader.loadResource(ResourceLoader.java:13)
    at graphics.Renderer.init(Renderer.java:32)
    at GameEngine.init(GameEngine.java:43)
    at GameEngine.run(GameEngine.java:33)
    at Main.main(Main.java:9)

Process finished with exit code 0

Thank your for looking at it!

A: As NomadMaker pointed out, the issue lies with the call
new InputStreamReader(Class.class.getResourceAsStream(path))
returning a null value (you would have seen this as part of the error message).
This should work for you:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Objects;

public class Main {

    public static void main(String[] args) {
        String filepath = "test.txt";
        System.out.println(loadResource(filepath));
    }

    public static String loadResource(String path) {
        InputStream is = Main.class.getClassLoader().getResourceAsStream(path);
        StringBuilder result = new StringBuilder();
        try (InputStreamReader isr = new InputStreamReader(Objects.requireNonNull(is));
             BufferedReader reader = new BufferedReader(isr)) {
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line).append("\n");
            }
        } catch (IOException | NullPointerException e) {
            System.out.println("File nicht gefunden:  " + e);
        }
        return result.toString();
    }
}

Issues to keep in mind:

*

*You need to close the InputStreamReader and BufferedReader when you are done with these. I used a try-with-resources here (refer to the official documentation if this is new to you).

*This code assumes that you stored the file you are reading from inside the resources folder. If the file can't be found, a NPE error will be thrown, which I am including in the catch. You may choose to deal with the exception in a different way.

*This code also assumes that you are working within a static context. If not, use this.class.getClass()getClassLoader().getResourceAsStream(path) instead.


text:
Q: Does exist ORM / Framework that converts data automatically when I want to change column datatype in table? Assume that I have existing database with existing data.
Is there any framework / ORM that generates data conversion SQL scripts when I need change column datatype?
Of course there is problem with conversions like

*

*float to int

*string to int

, but I would like to have such default functionality that automatically converts data from

*

*int to float

*int to string.

Do I have always to write data SQL data conversion scripts in both cases?

A: In the .Net world I've had very good experience with LLBLGen Pro. It supports the generation of DDL scripts to migrate the underlying database to the updated entity definitions. Here is quick start guide that shows the overview of how this works, and here is documentation section for Model-First design process
You can either use it with its own runtime framework, or simply as a design tool for Entity Framework, NHibernate, or Linq to SQL.

A: SauceDB is written in .NET and is capable of doing automatic schema modifications when you change the data type on an access object.
http://sauce.codeplex.com
Disclamer: I wrote it

A: There is EntityFramework.Migrations for example.

A: And another competitor: Propel Migrations

A: What about Doctrine Migrations

A: I would recommend DataObjects.Net.
Automatic upgrade works when we add new classes and properties to the model, but sometimes necessary to perform some specific schema modifications, for example rename of properties or classes, in this case you can write an upgrade handler(RenameFieldHint, RemoveFieldHint etc)


text:
Q: Почему перевод абзаца останавливается на первой точке в конце первого предложения? У меня есть этот код перевода Google. Со своей задачей справляется хорошо, но есть небольшой баг. Не знаю почему, но перевод останавливается на DOT (точка в конце первого предложения). Итак, каждое предложение переводится до первой точки, но дальше не идет.
import sys
import requests

url = "https://translate.google.com/translate_a/single"
headers = {
    "Host": "translate.google.com",
    "Accept": "*/*",
    "Cookie": "",
    "User-Agent": "GoogleTranslate/5.9.59004 (iPhone; iOS 10.2; ja; iPhone9,1)",
    "Accept-Language": "en",
    "Accept-Encoding": "gzip, deflate",
    "Connection": "keep-alive",
    }
sentence = "A glint of joy had appeared in my eyes, discreet but effective, just as the reddish sun lit up the horizon for the last time. After all, the most telling proof of understanding art, sensing fidelity to nature is to observe a phenomenon."
params = {
    "client": "it",
    "dt": ["t", "rmt", "bd", "rms", "qca", "ss", "md", "ld", "ex"],
    "otf": "2",
    "dj": "1",
    "q": sentence,
    "hl": "ja",
    "ie": "UTF-8",
    "oe": "UTF-8",
    "sl": "en",
    "tl": "ru",
    }

res = requests.get(
    url=url,
    headers=headers,
    params=params,
    )
print(res.status_code)
res = res.json()
print(res["sentences"][0]["trans"])

P.S. Я обнаружил странную вещь об этом коде. Может кто подскажет, почему код "ест" из предложений? То есть он переводит одно предложение, потом не переводит другое. Потом идет дальше, переводит два предложения, но не переводит третье. И так далее.

A: Просто переберите все предложения:
for sentence in res["sentences"]:
    if 'trans' in sentence:
        print(sentence["trans"])

Вывод:
200
В моих глазах появился огонек радости, сдержанный, но действенный, когда красноватое солнце в последний раз осветило горизонт.
Ведь самое красноречивое доказательство понимания искусства, ощущения верности природе — это наблюдение явления.

А вообще в таких случаях нужно просто красиво печатать данные и всё становится понятно:
import pprint

pprint.pprint(res)

Вывод:
{'confidence': 0.9784949,
 'ld_result': {'extended_srclangs': ['en'],
               'srclangs': ['en'],
               'srclangs_confidences': [0.9784949]},
 'sentences': [{'backend': 3,
                'model_specification': [{}],
                'orig': 'A glint of joy had appeared in my eyes, discreet but '
                        'effective, just as the reddish sun lit up the horizon '
                        'for the last time.',
                'trans': 'В моих глазах появился огонек радости, сдержанный, '
                         'но действенный, когда красноватое солнце в последний '
                         'раз осветило горизонт. ',
                'translation_engine_debug_info': [{'model_tracking': {'checkpoint_md5': 'c5f104380d2f4c4bf0c587f790a21817',
                                                                      'launch_doc': 'en_ru_2021q4.md'}}]},
               {'backend': 3,
                'model_specification': [{}],
                'orig': 'After all, the most telling proof of understanding '
                        'art, sensing fidelity to nature is to observe a '
                        'phenomenon.',
                'trans': 'Ведь самое красноречивое доказательство понимания '
                         'искусства, ощущения верности природе — это '
                         'наблюдение явления.',
                'translation_engine_debug_info': [{'model_tracking': {'checkpoint_md5': 'c5f104380d2f4c4bf0c587f790a21817',
                                                                      'launch_doc': 'en_ru_2021q4.md'}}]},
               {'translit': 'V moikh glazakh poyavilsya ogonek radosti, '
                            'sderzhannyy, no deystvennyy, kogda krasnovatoye '
                            "solntse v posledniy raz osvetilo gorizont. Ved' "
                            "samoye krasnorechivoye dokazatel'stvo ponimaniya "
                            'iskusstva, oshchushcheniya vernosti prirode — eto '
                            'nablyudeniye yavleniya.'}],
 'spell': {},
 'src': 'en'}

Тут сразу видно, что в словаре res есть список словарей 'sentences', из которого нам нужно взять элементы по ключам 'trans'. Причём, этот ключ присутствует не в каждом словаре списка, его присутствие нужно дополнительно проверять.

A: посмотри это. Я изменил код. Теперь он работает нормально, переводит все предложения, а не только некоторые из них.
import sys
import requests

def translate(contents, source_language, target_language):
    url = "https://translate.google.com/translate_a/single"
    headers = {
        "Host": "translate.google.com",
        "Accept": "*/*",
        "Cookie": "",
        "User-Agent": "GoogleTranslate/5.9.59004 (iPhone; iOS 10.2; ja; iPhone9,1)",
        "Accept-Language": "fr",
        "Accept-Encoding": "gzip, deflate",
        "Connection": "keep-alive",
    }

    params = {
        "client": "it",
        "dt": ["t", "rmt", "bd", "rms", "qca", "ss", "md", "ld", "ex"],
        "otf": "2",
        "dj": "1",
        "q": requests.utils.quote(contents),
        "hl": "ja",
        "ie": "UTF-8",
        "oe": "UTF-8",
        "sl": source_language,
        "tl": target_language,
    }

    res = requests.get(
        url=url,
        headers=headers,
        params=params,
    )

    if res.status_code != 200:
        raise Exception('Could not translate phrase')

    res = res.json()
    for sentence in res["sentences"]:
        if 'trans' in sentence:
            return requests.utils.unquote(sentence["trans"])

    raise Exception('Could not find translation')

if __name__ == "__main__":
    print(translate("piersici & caise; mere | visine = rodii. struguri, pere", "ro", "en"))


text:
Q: When solving inequalities that involve logarithms, exponentials and the quadratic formula, which way does the sign turn? I always get confused when solving inequalities that involve logarithms, exponentials and quadratics that require the quadratic formula because I don't know where the sign is supposed to turn.
See the examples below:
On logarithms and exponents
$$1 \ge \log_2(x) \Leftrightarrow 2 \text{ ?? } x$$
Or the other way around:
$$1 \ge \log_2(x) \Leftrightarrow x \text{ ?? } 2$$
or
$$2^x \le 256 \Leftrightarrow x \text{ ?? } 8$$
On the quadratic formula
$$0 \ge x^2+3x+2 \Leftrightarrow x \text{ ?? }\frac{-3\pm \sqrt{3^2+4(1\cdot2)}}{2(1)}$$
Basically I have two questions:

*

*How do I know which way the sign turns in the above situations?

*What happens exactly between $2^x = 256$ and $x = \log_2(8)$? Are any operations omitted or is the exponent "swapped" with a logarithm because that's the logical thing to do?

A: Let $a\geq b$. Then if $f$ is an increasing function, then applying the function on the inequality retains its direction, i.e.
$$f(a)\geq f(b). $$
On the other hand, if $g$ is a decreasing function, then applying the function reverses the inequality, i.e.
$$g(a)\leq g(b).$$

Consider the function defined by $f(x) = 2^x$ which is an increasing function. Hence
$$1 \geq \log_2 (x) \implies f(1) \geq f(\log_2(x)) \implies 2\geq x.$$
For the quadratic it's slightly more complicated as more steps are used. Consider the quadratic function
$$q(x) = ax^2+bx+c,\quad a\neq 0. $$
Then let $x_1, x_2$ (let $x_1$ be the smaller of the two) be roots of $q(x) = 0$. The real line is divided into $3$ intervals, namely
$$I_1 = (-\infty,x_1],\quad I_2 = [x_1,x_2],\quad I_3 = [x_2,\infty).$$
Consider the inequality
$$0 \leq q(x).$$
If $a>0$, then the inequality is solved for $x\in I_1 \cup I_3$, i.e. if $x\leq x_1$ or $x \geq x_2$.
If $a < 0$, then the inequality is solved for $x\in I_2$, i.e. if $x_1\leq x \leq x_2$.
For the inequality in the other direction, namely
$$0\geq q(x)$$
the two solutions above are interchanged.

A: One way I remember it is that for bases $b > 1$ applying exponents or logarithms is strictly increasing, so the inequality doesn't change directions. So, if I know $u < v$ then I also know $b^u < b^v$ if exponentiation is appropriate, and $\log_b(u) < \log_b(v)$ if taking logarithms is appropriate.
For instance, say you know $1 \geqslant \log_2(x)$. To get rid of the logarithm, you should exponentiate using the base $b=2$, right? It follows that $2 = 2^1 \geqslant 2^{\log_2(x)} = x$. Notice that the inequality did not change directions.
Similarly, suppose you know $2^x \leqslant 256$. In this case, you would apply $\log_2$ to both sides, and find $x = \log_2(2^x) \leqslant \log_2(256) = 8$. Again, the inequality did not change directions.
Be wary, though - if your base $b <1$ then applying exponents or logorithms is strictly DECREASING, and the inequality DOES change directions. For instance, $\left(\frac{1}{2}\right)^x \leqslant 1/256$ implies $x = \log_{\frac{1}{2}}\left(\left(\frac{1}{2}\right)^x\right) \geqslant \log_{\frac{1}{2}}(1/256) = 8$
As for use of the quadratic formula, it mostly depends on the sign of the leading coefficient - picture upward facing and downward facing parabolas.


text:
Q: Does using LIMIT improve the performance and is it noticeable? I want to understand the following.
Assume that I have a complicated query with let's say a join of 5 tables a group by summations and order by.
Letting aside any optimizations to the query itself e.g. indexes etc.
Is there any significant performance benefit using LIMIT? I assume that all the query (and results) must be processed before LIMIT is applied, so using a LIMIT to retrieve a subset of the results, does this offer any significant/noticable improvement?

A: When a query is executed it first gets translated into a plan that is made up of several operators. There are two basic types of operators: Blocking and Non-Blocking.
 A Non-Blocking Operator retrieves a row (or a few rows) from its child or children for each row requested from it. A Blocking Operator on the other hand has to read in and process the entire row set of all its children before it can produce any output.
Sort is a typical Blocking Operator. So a select with order by does not benefit much from a limit. However, there are RDBMSs that can utilize a sorting algorithm that needs less memory and is faster when a limit clause is provided. It is in this case enough to just store the currently first n rows and move them out of memory as earlier rows come along. That can be a significant performance gain. However, I am not 100% sure that MySQL has that ability.
Either way, even a limit-sort still needs to process the entire input row set before it can produce the first output row. While this algorithm, if implemented, can speed up the sort, if the rest of the query is the most expensive part, the total execution time will not significantly improve because of a provided limit.

A: If you want to take advantage of LIMIT to improve performance, you need

*

*understand the data you are retrieving

*proper indexing the correct sequence of columns

*take responsibility for refactoring the query

*using LIMIT before JOIN
These principles can go a long way if you can orchestrate them.
I learned these concepts by watching this YouTube Video (listen carefully through the French accent)
I used those concepts to answer a very tough StackOverflow question about getting the top 40 articles from some tables : May 12, 2011 : Fetching a Single Row from Join Table.
In my answer to that question (May 16, 2011), I wrote the following query and tested it thoroughly:
SELECT
  AAA.author_id,
  AAA.date_created,
  IFNULL(BBB.title,'<NO_TITLE>') title,
  IFNULL(CCC.filename,'<NO-IMAGE>') filename,
  IFNULL(CCC.date_added,'<NO-IMAGE-DATE>') image_date
FROM
(
  SELECT
    AA.id,
    AA.date_added,
    BB.author_id,
    BB.date_created
  FROM
  (
    SELECT
      A.id,IFNULL(MAX(B.date_added),'1900-01-01 00:00:00') date_added
      FROM (SELECT id FROM articles ORDER BY date_created DESC LIMIT 40) A
      LEFT JOIN article_images B ON A.id = B.article_id
      GROUP BY A.id
  ) AA
  INNER JOIN articles BB USING (id)
) AAA
LEFT JOIN article_contents BBB ON AAA.id=BBB.article_id
LEFT JOIN article_images CCC
ON (AAA.id=CCC.article_id AND AAA.date_added=CCC.date_added)
ORDER BY AAA.date_created DESC;

Please notice the line in the query with the LIMIT
      FROM (SELECT id FROM articles ORDER BY date_created DESC LIMIT 40) A

This subquery is buried three levels deep. This allowed me to get the last 40 articles using LIMIT. Then, I performed the necessary JOINs afterwards.
LESSONS LEARNED

*

*Doing LIMIT inside subqueries may not always be the answer because of the cardinality of indexes, the data content, and the result set size from the LIMIT. If you have all your "ducks in a row" (Have the four principles in mind for your query), you can get surprisingly good results.

*Make your queries as simplistic as possible when doing LIMIT by gathering keys only.

A: In my case, I can say Yes, even if I (still) don't understand why.
SELECT g0_.id AS id_0, COUNT(a1_.id_tarifs) AS sclr_1
FROM groupe_jardinerie g0_
INNER JOIN articles_tarifs a1_
  ON (a1_.groupe_jardinerie_id = g0_.id)
WHERE g0_.centrale_id = 511
  AND a1_.date_fin_tarif >= '2018-01-29 10:46:35'
GROUP BY g0_.id;

(result set)

8 rows in set (**18.14 sec**)

Note the time : 18 seconds. Same request with a big LIMIT :
SELECT g0_.id AS id_0, COUNT(a1_.id_tarifs) AS sclr_1
FROM groupe_jardinerie g0_
INNER JOIN articles_tarifs a1_
  ON (a1_.groupe_jardinerie_id = g0_.id)
WHERE g0_.centrale_id = 511
  AND a1_.date_fin_tarif >= '2018-01-29 10:46:35'
GROUP BY g0_.id
LIMIT 100000000000;

(exact same result set)

8 rows in set (**1.32 sec**)

More than ten times faster !!!
EXPLAIN give the same result for both requests.
+----+-------------+-------+------------+--------+---------------------------------------------------+---------+---------+------------------------------+--------+----------+----------------------------------------------+
| id | select_type | table | partitions | type   | possible_keys                                     | key     | key_len | ref                          | rows   | filtered | Extra                                        |
+----+-------------+-------+------------+--------+---------------------------------------------------+---------+---------+------------------------------+--------+----------+----------------------------------------------+
|  1 | SIMPLE      | a1_   | NULL       | ALL    | IDX_438010BBC10784EF                              | NULL    | NULL    | NULL                         | 795135 |    33.33 | Using where; Using temporary; Using filesort |
|  1 | SIMPLE      | g0_   | NULL       | eq_ref | PRIMARY,IDX_9CA5CF6758A1D71F,IDX_9CA5CF67670C757F | PRIMARY | 4       | phs.a1_.groupe_jardinerie_id |      1 |    50.00 | Using where                                  |
+----+-------------+-------+------------+--------+---------------------------------------------------+---------+---------+------------------------------+--------+----------+----------------------------------------------+

LIMIT should interfer only to limit the result set (i.e., if I do a LIMIT 4, I got only the first 4 rows of the above result set).


text:
Q: LWJGL - Text's color changes background's color I have a serious problem with my LWJGL program.
If I set one of my text's colour, the background's color changes, too.
I think I know why, I just put all of the drawing things in an infinite loop, and maybe that's the reason.Can you help me with this? Am I correct with the reason of the problem? If yes, how can I solve that? If not, what do you think, what is the problem?
Here's my code:
The main class:
<!-- language: lang-java -->
public class DoomMain {
public static final int WIDTH = 640;
public static final int HEIGHT = 480;
public static final int SCALE = 1;

private static State state;

public DoomMain() {
    try {
        Display.setDisplayMode(new DisplayMode(WIDTH*SCALE,HEIGHT*SCALE));
        Display.setTitle("Tomco - Doom");
        Display.create();
    } catch(LWJGLException e) {
        e.printStackTrace();
    }

    while(!Display.isCloseRequested()) {
        state = State.MENU;

        switch(state) {
            case INTRO:
                new Intro();
                break;
            case MENU:
                new MainMenu();
                break;
            case CREDITS:
                break;
            case GAME:
                break;
            default:
                break;
        }

        Display.update();
        Display.sync(60);
    }

    Display.destroy();
}

public static void main(String[] args) {
    new DoomMain();
}
}

The MainMenu class:
<!-- language: lang-java -->
public class MainMenu {

private Texture background;
private TrueTypeFont doomfont;

private boolean ana = false;

public MainMenu()  {
    glClear(GL_COLOR_BUFFER_BIT);
    glEnable(GL_TEXTURE_2D);
    glClearColor(0.0f,0.0f,0.0f,0.0f);
    glEnable(GL11.GL_BLEND);
    glBlendFunc(GL11.GL_SRC_ALPHA,GL11.GL_ONE_MINUS_SRC_ALPHA);
    glViewport(0,0,DoomMain.WIDTH,DoomMain.HEIGHT);
    glMatrixMode(GL11.GL_MODELVIEW);
    glMatrixMode(GL11.GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0,DoomMain.WIDTH,DoomMain.HEIGHT,0,1,-1);
    glMatrixMode(GL11.GL_MODELVIEW);
    glShadeModel(GL_SMOOTH);

    drawBackground();
    drawText();
    glDisable(GL_TEXTURE_2D);
}

private void drawBackground() {
    try {
        background = TextureLoader.getTexture("PNG",new FileInputStream(new File("res/textures/mainmenu/doom_00340461.png")));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        Display.destroy();
    } catch (IOException e) {
        e.printStackTrace();
        Display.destroy();
    }

    glBegin(GL_QUADS);
    {
        glTexCoord2f(0,0);
        glVertex2f(0,0);
        glTexCoord2f(1,0);
        glVertex2f(background.getTextureWidth(),0);
        glTexCoord2f(1,1);
        glVertex2f(background.getTextureWidth(),background.getTextureHeight());
        glTexCoord2f(0,1);
        glVertex2f(0,background.getTextureHeight());
    }
    glEnd();
}

private void drawText() {
    Color.white.bind();
    try {
        InputStream inputStream = ResourceLoader.getResourceAsStream("res/fonts/DooM.ttf");
        Font awtFont = Font.createFont(Font.TRUETYPE_FONT,inputStream);
        awtFont = awtFont.deriveFont(24f);
        doomfont = new TrueTypeFont(awtFont,ana);
    } catch(Exception e) {
        e.printStackTrace();
    }

    doomfont.drawString(200,100,"Start new game",Color.red);
}
}

A: By default, the texture will be multiplied by the current color. As a state machine, the "current color" is whenever you set it last. In your case, when you draw text; when you enter the loop again, that same color is used for the texture.
To simplify the problem, you can reduce the whole drawText routine to just setting the color:
LOOP:
    a) draw background
    b) set color

results in: ... set color; draw background ...
The glClear function clears the buffers of what is already drawn, but not the color to be used next.
As a solution, you can explicitly change the color just before you draw the texture. glColor3f(1.0f, 1.0f, 1.0f) will produce the texture as is, and any other value will work as a color filter (just as it is now).
Another solution is to change the texture drawing behavior with glTexEnv. Assuming the texture is GL_RGBA, then calling glTexEnv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE) works. The linked page contains a table with different settings and their effects.

A: First if all : The Color.white.bind() call in your drawText() function is probably what is affecting the background.
Here is a quick and dirty example of how to only load the data once. I've moved data loading to the loadData() function. The DoomMain class is created once after the screen is opened, loadData() is called before the main loop and you call your drawing using menu.draw().
Ideally you would load all the resources you need in one place first, then pass the objects to DoomMain at initialization. You might want to use that texture and font in other places as well.. and you don't want to load it multiple times.
public DoomMain()
{
    // Open screen here since we need a context to make textures etc
    ...
    // Make objects for your different parts
    MainMenu menu = MainMenu();
    menu.loadData(); // <- Loads the texture and font

    while(!Display.isCloseRequested())
    {
        state = State.MENU;
        switch(state) {
            ...
            case MENU:
                menu.draw();
                break;
            ...
        }
        Display.update();
        Display.sync(60);
    }
    Display.destroy();
}

MainMenu
public class MainMenu
{
    private Texture background;
    private TrueTypeFont doomfont;
    private boolean ana = false;

    public MainMenu() { }

    public void loadData()
    {
        // Load the background texture
        try {
            background = TextureLoader.getTexture("PNG",new FileInputStream(new File("res/textures/mainmenu/doom_00340461.png")));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Display.destroy();
        } catch (IOException e) {
            e.printStackTrace();
            Display.destroy();
        }
        // Load and initialize the font here
        try {
            InputStream inputStream = ResourceLoader.getResourceAsStream("res/fonts/DooM.ttf");
            Font awtFont = Font.createFont(Font.TRUETYPE_FONT,inputStream);
            awtFont = awtFont.deriveFont(24f);
            doomfont = new TrueTypeFont(awtFont,ana);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public void draw()
    {
        glClear(GL_COLOR_BUFFER_BIT);
        glEnable(GL_TEXTURE_2D);
        glClearColor(0.0f,0.0f,0.0f,0.0f);
        glEnable(GL11.GL_BLEND);
        glBlendFunc(GL11.GL_SRC_ALPHA,GL11.GL_ONE_MINUS_SRC_ALPHA);
        glViewport(0,0,DoomMain.WIDTH,DoomMain.HEIGHT);
        glMatrixMode(GL11.GL_MODELVIEW);
        glMatrixMode(GL11.GL_PROJECTION);
        glLoadIdentity();
        glOrtho(0,DoomMain.WIDTH,DoomMain.HEIGHT,0,1,-1);
        glMatrixMode(GL11.GL_MODELVIEW);
        glShadeModel(GL_SMOOTH);

        drawBackground();
        drawText();
        glDisable(GL_TEXTURE_2D);
    }

    private void drawBackground()
    {
        ... bind background texture
        ... draw your quad
    }

    private void drawText()
    {
        doomfont.drawString(....);
    }
}


text:
Q: styling form based on other server added to my site by JS i'm trying so much to styling this form based in this page :
http://student.ly/form/
first of all this form added to my site by javascript code only and it's linked to another website..
i mean i can't access the actual code for the form, i want to styling it
i try doing this :
.page-id-1418 .inq

and this
.page-id-1418 .entry_content input.inq

and a lot of other codes no one works to me
and in the other hand
this code works fine
    .page-id-1418 .post-content iframe{
height:700px !important;
}

i want to styling the inputs , any help please?

A: Try
CSS
input.inq {
width:200px;
...
...
}


text:
Q: SELinux keeps blocking my Apache instance I am using CentOS 7 and have set up a duplicate Apache instance using the systemd structure there.
I can get both Apaches to run if I use setenforce 0. However, when I setenforce 1, the new Apache won't start.
I did my best to go through all the files I created and I have copied the SELinux type across using "ls -Z" and then chcon to the same as httpd.
The failure message I am getting is:
[Thu Jun 23 23:51:24.123185 2016] [core:notice] [pid 24944] SELinux policy enabled; httpd running as context system_u:system_r:httpd_t:s0
[Thu Jun 23 23:51:24.124434 2016] [suexec:notice] [pid 24944] AH01232: suEXEC mechanism enabled (wrapper: /usr/sbin/suexec)
[Thu Jun 23 23:51:24.146830 2016] [auth_digest:notice] [pid 24944] AH01757: generating secret for digest authentication ...
[Thu Jun 23 23:51:24.147901 2016] [lbmethod_heartbeat:notice] [pid 24944] AH02282: No slotmem from mod_heartmonitor
[Thu Jun 23 23:51:24.147983 2016] [core:error] [pid 24944] (13)Permission denied: AH00099: could not create /etc/httpd-bobby/httpd-bobby.pid
[Thu Jun 23 23:51:24.148000 2016] [core:error] [pid 24944] AH00100: httpd-bobby: could not log pid to file /etc/httpd-bobby/httpd-bobby.pid

But the location has the httpd context:
[root~]# ls -Z /etc | grep httpd
drwxr-xr-x. root root system_u:object_r:httpd_config_t:s0 httpd
drwxr-xr-x. root root unconfined_u:object_r:httpd_config_t:s0 httpd-bobby

I know it is SELinux because it works with setenforce 0. What am I doing wrong?

A: There are multiple httpd contexts and this isn't the right one.
The directory in which the pid file goes should have the context httpd_var_run_t .
I'd recommend against putting it in /etc and create one in /var/run.
To set the correct context permanently for example for /var/run/httpd-bobby:
semanage fcontext -a -t httpd_var_run_t "/var/run/httpd-bobby(/.*)?" &&
restorecon /var/run/httpd-bobby


text:
Q: Water main pressure speed In a long fire service water main under pressure, say 10 Km long,  for street hydrants, if the farthest one of street hydrants open, what is the time lag  the pressure drop can be detected by the pressure sensor installed in the fire water pumping station. My question is will any time delay due to long distance between the pressure sensor in the pumping station and the farthest end of water main.

A: Your question is not very clear to me, but I think the speed you are seeking is equal to speed of sound in water.


text:
Q: Magento 1.X put label after System > Configuration element I'm making a System > Configuration extension where as a developer you can specify a file where all requests will be logged. It's just a textfield where you can fill in any name you want.
What I would like to add is '.log' just after the textfield so users don't write that down instead of having to display (don't add .log).
My question is simple:
Is this possible? And if so, how?
Here's the code I use inside my system.xml
  <requestfile translate="label">
        Resuest log filename (don't add .log)
        <frontend_type>text</frontend_type>
        <sort_order>1</sort_order>
        <show_in_default>1</show_in_default>
  </requestfile>

A: If you want to achieve something like following

Try following
<requestfile translate="label">
    Resuest log filename (don't add .log)
     <comment><![CDATA[Your comment text comes here]]></comment>
    <frontend_type>text</frontend_type>
    <sort_order>1</sort_order>
    <show_in_default>1</show_in_default>
</requestfile>

Notice the <comment></comment> tag in  the code given above.You should write your message or comment there.

A: Soo...
Magento can't do it apparently.
What I could do, and did by accident, is add

<validate>validate-code</validate>

to the system.xml
This ensures that the user can only input a-z, 0-9 or _
So no . so no .log
As easy as that.


text:
Q: How to manage loading incase of multiple AJAX call in HTML page in Google Chrome? I have loading div as following:
CSS:
.loader {
    border: 8px solid #f3f3f3;
    border-radius: 50%;
    border-top: 8px solid gray;
    width: 60px;
    height: 60px;
    -webkit-animation: spin 2s linear infinite;
    animation: spin 2s linear infinite;
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    margin: auto;
}

@-webkit-keyframes spin {
    0% {
        -webkit-transform: rotate(0deg);
    }

    100% {
        -webkit-transform: rotate(360deg);
    }
}

@keyframes spin {
    0% {
        transform: rotate(0deg);
    }

    100% {
        transform: rotate(360deg);
    }
}

HTML:

    <button onclick="generateOrder();">Create Order</button>

Javascript:
function generateOrder() {
     $('.loader').css('display', 'block');
     $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            datatype: "json",
            url: oDataUri,
            data: jsonPO,
            async: false,
            beforeSend: function (XMLHttpRequest) {
                XMLHttpRequest.setRequestHeader("Accept", "application/json");
            },
            success: function (data, textStatus, XmlHttpRequest) {
                for (var i = 0; i < data.results.length; i++) {
                    AddProducts(data.results[i].ProductID, data.results[i].ProductName)
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            }
        });
        reloadGridData();   //it will call ajax and reload all data.
        $('.loader').css('display', 'none');
}

function AddProducts(productID, productName) {
     //$('.loader').css('display', 'block');
     $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            datatype: "json",
            url: oDataUri,
            data: jsonPO,
            async: false,
            beforeSend: function (XMLHttpRequest) {
                XMLHttpRequest.setRequestHeader("Accept", "application/json");
            },
            success: function (data, textStatus, XmlHttpRequest) {
                for (var i = 0; i < data.results.length; i++) {
                    //more AJAX call with async: false
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            }
        });
        //$('.loader').css('display', 'none');
}

In Above case, loading is working fine in Mozila Firefox but when I am trying to use in Google Chrome, it doesn't work.
I can't set Async to True. Also I have multiple Ajax call.
Please suggest me solution of it.

A: Why note use the jQuery ajaxStart() and ajaxStop() methods to run your code.
ajaxStart Document

*

*This is a global event handler which gets fired when ever an ajax call is occurred. The same principle goes to ajaxStop as well. You could search ajaxStop in google to get the documentation. Pretty easy to use.

A: Is just a dirty quick suggestion, not a pretty solution at all (and no tested):

*

*Declare a global var to store the total ajax calls count (without async), and initiate the loader and the first ajax call
ajax_count = 1;
$ajax({
  // ...
});

*Increase the ajax call count on  success:
ajax_count = data.results.length;

2.1. and decrease ajax_count and check if is the less or equal to 0:
ajax_count--;
if (ajax_count <= 0) {
  $('.loader').css("display":"none");
}

*Increase the ajax_count in the second ajax success callback calls level:
ajax_count += data.results.length;

3.1. and decrease ajax_count and check if is the less or equal to 0:
ajax_count--;
if (ajax_count <= 0) {
  $('.loader').css("display":"none");
}

*On the ajax third level success callback decrease and compare ajax_count too

*Refactor the code as you want (encapsulate check, handle possible error - decrease and check on error callback too, or use the complete callback, ...)

A: the only 2 way i can think of are:

*

*find which ajax calls finishes in the end. and in the success block of it call $('.loader').css("display":"none");.

*register an even when the data that you must have before showing the page is available. and create an event listener to listen to it. when the data is available the event will be fired. the listener will listen and call $('.loader').css("display":"none"); and deregister the event.
that's all folks!


text:
Q: Filling in the list of the required format in the python loop I am trying to create a list structure in a loop:
[children:[{text: "Title 1", id: '1', expanded: true,children: [{text: "title2", leaf: true ,},{text: "title3", leaf: true}]},{text: "Title4", id: '4', expanded: true, children: [{text: "title5", leaf: true,} ]}]]

The source data looks like this:
mylist =[{'id': '1', 'name': 'Title1', 'id_parent': '0'}, {'id': '2', 'name': 'title2', 'id_parent': '1'}, {'id': '3', 'name': 'title3', 'id_parent': '1'}, {'id': '4', 'name': 'Title4', 'id_parent': '0'}, {'id': '5', 'name': 'title5', 'id_parent': '4'}]

Using recursion, I go through the data and get parental and childish records:
def get_parent(id_parent):
    c = []
    for x in mylist:
        if not x["id"] == id_parent and x["id_parent"] == id_parent:
            if x["id_parent"] == id_parent:
                x['expanded'] = True
            else:
                x['leaf'] = True
            c.append(x)
    return(c)
def get_tree(t):
    lst = []
    main_data = []
    for x in get_parent(t):
        all_stor = {}
        all_stor["text"] = x['name']
        all_stor["id"] = x['id']
        if x.get('expanded'):
            all_stor["expanded"] = x['expanded']
        else:
            all_stor["leaf"] = x['leaf']

        main_data.append(all_stor)
        lst.append([main_data, get_tree(x["id"])])
    return lst
main = get_tree("0")
print(main)

How to fill the main_data list in a loop in order to get the necessary structure?

A: Your expected output should be a list of children from the root level:
def get_tree(l, parent='0'):
    children = []
    for d in l:
        if d['id_parent'] == parent:
            details = {'text': d['name'], 'id': d['id']}
            grand_children = get_tree(l, d['id'])
            if grand_children:
                details.update({'expanded': True, 'children': grand_children})
            else:
                details['leaf'] = True
            children.append(details)
    return children

so that with your sample input, get_tree(mylist) would return:
[{'text': 'Title1', 'id': '1', 'expanded': True, 'children': [{'text': 'title2', 'id': '2', 'leaf': True}, {'text': 'title3', 'id': '3', 'leaf': True}]}, {'text': 'Title4', 'id': '4', 'expanded': True, 'children': [{'text': 'title5', 'id': '5', 'leaf': True}]}


text:
Q: Multiple Selection Search Narrow I am wanting to create a catering search for my coworkers that allows them to pick things like people attending and food type and then it will narrow down the spreadsheet of catering options to those parameters. I am extremely new to VBA and been trying to search for how to do this but I feel like I don't know the correct terms. How would I go about making this happen if it even is possible?
what I want to be pulled


text:
Q: .NET 4.5.2 is not detected in silent mode by WiX 3.10.2 We have updated our kits to use WiX 3.10.2 and detect .NET Framework 4.5.2 using WIX_IS_NETFRAMEWORK_452_OR_LATER_INSTALLED property - this works, however not in all cases.
When installation is started in silent mode (/qb switch), WIX_IS_NETFRAMEWORK_452_OR_LATER_INSTALLED is not set.
On the other hand property WIXNETFX4RELEASEINSTALLED is set to #379893
I can workaround this issue similar to what was done in Check for .net framework 4.5.2 in registry in wix, but I would rather find the cause of this behavior.

A: My bad,
LaunchConditions action in our kits was scheduled too early - before SetWIX_IS_NETFRAMEWORK_452_OR_LATER_INSTALLED


text:
Q: Using COUNTIF in Excel to count number of "Greater than" values in an array of values So here is my situation. I'm a principal creating a tracker for my teachers to use to track student growth on assessments. In the current tracker it is set up like this:
            % of            67%
            Students Met

**Student Name    Week 1 Goal:         Week 1 Actual:        Goal Met?:**
  Example A       23                    32                    Y
  Example B       45                    44                    N
  Example C       53                    55                    Y

I use a formula for the "Goal Met?" column to put a Y or N depending on if the Actual meets or exceeds the Goal column. Then, I use another formula to determine the % of students Met by doing a COUNTIF of "Y"s in the Goal Met column, dividing it by a COUNTA of that column, and multiplying by 100.
What I'm wondering is... this is very cumbersome to use for teachers, and the more columns and formulas I put, the greater the risk of teachers typing in the wrong place and messing up the formulas... is there any way I can just do a COUNTIF of the Array of the Weekly Goal and Weekly Actual columns, and count only the rows where the Actual is >= the Goal? Like is there a way to do COUNTIF(E5:F17,F>=E) and put some sort of symbol as a variable by the E and F in the criteria so that it goes row by row and compares the values, then counts the ones where the F value is greater than the E value?
Any suggestions would be great because then I can eliminate the "Goal Met" column (which they invariably type in and I have to go back and fix weekly). It gets annoying have to protect every 3rd column on a massive tracker!
Thanks so much for any advice!
Brendan

A: You should always password protect your cells that you do not want changed.
To answer you question you will need to enter an array formula.  Type the following in assuming your column names starts on A3 and then hit Ctrl+Shift+Enter.
=SUM(IF(C4:C6>=B4:B6,1,0))/COUNT(C4:C6)

If you did it correctly curly brackets will appear around the whole formula.
={SUM(IF(C4:C6>=B4:B6,1,0))/COUNT(C4:C6)}

A: My Solution
The following array formula, with cell references adjusted appropriately, should do what you're looking for:
=SUM(1*((OFFSET(C2,0,0,COUNT(C:C),1)-OFFSET(B2,0,0,COUNT(C:C),1))>=0))/COUNT(C:C)

Example:

Set the C2 reference in the first OFFSET to the top cell of the 'Actual' data (F5 in your example), the B2 reference in the second OFFSET to the top cell of the 'Goal' data (E5 in yours), and set all of the C:C references to the column containing one or the other of the 'Actual' or 'Goal' data (E:E or F:F in yours).  Be sure that the only cells with numerical data in the column you choose to replace the C:C references are those cells with 'Actual' or 'Goal' values in them, otherwise the formula will either return an inaccurate result, or will fail entirely.
To enter the formula as an array formula, type it in appropriately and then press Ctrl-Shift-Enter, instead of just Enter.  (See here for more information on array formulas, or just search online for "excel array formula".)  Any time you make a change to the formula, you will always have to enter it with Ctrl-Shift-Enter in order for it to behave properly.
How It Works

*

*Each COUNT retrieves the number of rows of data present.

*The two OFFSET calls retrieve the two arrays of interest, the 'Actual' and 'Goal' scores. In each call:

*

*The first argument marks the top-left cell of the array;

*The second and third arguments are the row and column offsets, respectively (both zero here);

*The fourth argument indicates the number of rows to include in the array; and

*The fifth argument indicates the number of columns to include.

*Since this is an array formula, subtracting the 'Actual' and 'Goal' arrays returns an array of the same size, but containing the element-wise difference between them.

*The >=0 comparison converts the array of differences into an array of TRUE/FALSE values indicating whether or not the goal was met.

*The 1* is there to convert the Boolean TRUE and FALSE values to numerical 1 and 0, to then be counted up by the SUM function.

*

*In Excel, TRUE and FALSE implicitly carry the numerical values of one and zero.

*BUT, if you try to pass a range or array containing TRUE/FALSE values to a function like SUM, it will ignore TRUE values and return zero.

*SO, multiplying the whole TRUE/FALSE array by 1 is a way to trick Excel into interpreting the array in a useful way.

*The SUM divided by the COUNT is then the desired fraction of students meeting the goals set.

EDIT: Per wbeard52's answer, it should be possible in Excel 2010 or later to replace the 1*... hack with an IF structure. In older versions of Excel, IF mishandled array inputs.

A: Another couple of array formula options, so you need to press Ctrl+Shift+Enter to commit them.
To find the number of goals met:
=SUM(--(C4:C6>B4:B6))

To find the percentage of goals met:
=SUM(--(C4:C6>B4:B6))/count(C4:C6)

You can use them independently. Remember to enter them as array formulas by pressing Ctrl+Shift+Enter.

A: Another "array formula" approach is like this:
=AVERAGE(IF(E5:E17<>"",IF(F5:F17>=E5:E17,1,0)))
confirmed with CTRL+SHIFT+ENTER
That gives you an actual % like 0.5 - if you want 50 multiply by 100


text:
Q: Laravel looks for a table that doesnt exist I'm new to PHP. I made a table called tbl_users but for some reasons that i cant understand laravel is trying some other table name called users.
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'raydb.users' doesn't exist
my migration code look like this and its the same in the seeder. the usage of just users is thrown nowhere.
public function up()
{
    Schema::create('tbl_users', function (Blueprint $table) {
        $table->id();
        $table->string('Name');
        $table->string('Email')->unique();
        $table->string('Password');
        $table->timestamps();
    });
}

i made a new controller that is trying to call the table it looks like this
function login(Request $req){
    return User::where(['email'=>$req->email])->first();
}

i cant really find some other place the table or SQL is called...
i see the table tbl_Users in MySQL and everything inside with the proper login name password etc. i dont understand where laravel get the calling of a table called users

A: Laravel uses conventions to make your life easier. One of those conventions is that Laravel assumes that your table names are the plural of your model names. You should read the docs for more information.
You're using a model called User so behind the scenes Laravel is using it's convention and looking for a table called users in your database. If you want to override the name of the table a model is associated with, you need to specify the table name on your model.
class User extends Model
{
  protected $table = 'tbl_users';
}

Ideally though, unless you have a specific reason not to do so it is advisable to stick to the Laravel table naming convention. It will make your life and others lives easier in the long run.


text:
Q: jQuery clone and appendTo duplicating wrong content I am trying to have a form of text inputs. All inputs will in an ordered list OL/LI structure.
There will be a + symbol next to the input that when you click on it, it should create a sub-OL and make a secondary list with another input. If you click it again, it adds another input. The new inputs have + symbols as well and you can do the same thing. I only technically want it to go three deep, but I think I can figure that part out later on, but what I'm really after is how to make this happen.
I have a beginning phase of it, but it's duplicating too much of the LI and I'm not sure what's going on.
This is what I have.
    $('.add_sub_page').live('click',function(e){
    $("
").append($(this).parent().clone()).insertAfter(this);
    e.preventDefault();
});

I brought this up an IRC chat room and I was provided with this solution, but it has the same issue as my first solution, so I'm not sure if it's easier to work with or not, so I will provide it as well.
    $('.add_sub_page').live('click',function(e){
    var ol = $("ol",this), new_ol = ol.length ? false : true;

    ol = new_ol ? $("
") : ol;

    ol.append($(this).parent().clone());

    if (new_ol) {
        ol.insertAfter(this);
    }

    e.preventDefault();
});

And just so you can see what HTML I am working with...
<form id="sitemap" action="" method="post">

Page Name: <input type="text" name="pages[]" value="">+

Page Name: <input type="text" name="pages[]" value="">+

Page Name: <input type="text" name="pages[]" value="">+

Page Name: <input type="text" name="pages[]" value="">+

Page Name: <input type="text" name="pages[]" value="">+

<input type="submit" name="submit_step1" value="Next Step">

</form>

You can preview the issue at http://jsbin.com/everu3 -- click the same Plus (+) sign twice to see the issue.
Thanks for any help you can provide!

A: You just need to remove those child
 elements you added earlier when appending, like this:
$('.add_sub_page').live('click',function(e){
  $("
").append($(this).parent().clone().children('ol').remove().end())
           .insertAfter(this);
  e.preventDefault();
});

You can give it a try here, all we're doing different is when you're cloning it looks for .children() that are
 elements, perform a .remove() on them from the cloned set and use .end() to hop back up the chain to the original cloned element, since that's the one you want to append.

Edit: The original version created an
 per, to get the current numbering, we need one
 beside the  we're clicking.  To do that change it up a bit like this:
$('.add_sub_page').live('click',function(e){
  $(this).parent(':not(:has(ol))').append('

');
  $(this).next().append($(this).parent().clone().children('ol').remove().end());
  e.preventDefault();
});

Give it a try here.  What this does is it goes to the parent, only if it doesn't have a
 and appends an
 (if it already has one the .append() wouldn't run in anything).  Then we're just looking for that
 which should be the .next() element and appending to it.
Also here's a slightly modified version that stops at 3 levels:
$('.add_sub_page').live('click',function(e){
  $(this).parent(':not(:has(ol))').append('

').end()
         .next().append($(this).parent().clone().children('ol').remove().end());
  if($(this).parents('.page-title').length == 2)
     $(this).next().find('.add_sub_page').remove();
  e.preventDefault();
});


text:
Q: Issues with JSVC and Tomcat 7 I'm trying to run tomcat 7 with jsvc, but am receiving an error even though I believe my classpath is correct.
I'm starting it as follows:
# export JAVA_HOME=/opt/java/jdk1.7.0_07
# export CATALINA_HOME=/usr/share/tomcat7
# ./bin/jsvc -cp ./bin/bootstrap.jar:./bin/commons-daemon.jar -outfile logs/catalina.out -errfile /var/tmp/catalina.err org.apache.catalina.startup.Bootstrap

However, I'm receiving the following error:
# cat /var/tmp/catalina.err
Cannot find daemon loader org/apache/commons/daemon/support/DaemonLoader
Service exit with a return value of 1

I'd appreciate any assistance you can offer.
Cheers,
Toki

A: It seems like javavms_conf is not in the correct path, verify where is it.
Usually /usr/local/bin/javavms check for /usr/local/etc/javavms_conf file.


text:
Q: How to make custom light shape in GLSL using distance from fragcoord to light postion I read a 2d light shader in shader toy which can be used to create 2d (point) light.
https://www.shadertoy.com/view/4dfXDn
vec4 drawLight(vec2 p, vec2 pos, vec4 color, float range)
    {
        float ld = length(p - pos);
        if (ld > range) return vec4(0.0);
        float fall = (range - ld)/range;
        fall *= fall;
        return (fall) * color;
    }

void main() {
    vec2 p = gl_FragCoord.xy;
    vec2 c = u_resolution.xy / 2.0;

    vec4 col = vec4(0.0);

    vec2 lightPos = vec2(c);
    vec4 lightCol = vec4(1.000,0.25,0.000,1.000);

    col += drawLight(p, lightPos, lightCol, 400.0);

    gl_FragColor = col;
}

However, I can't figure out how to make another "shape" of light using this?
How can I modify the drawLight function to have another parameter, which modifies the original light, like 1.0 is a full circle light, and 0.25 is a quad-light?

A: in your code the
float ld = length(p - pos);

Is computing your distance from light uniformly in all directions (euclidean distance). If you want different shading change the equation...
For example you can compute minimal perpendicular distance to a polygon shaped light like this:
Vertex:
// Vertex
#version 420 core
layout(location=0) in vec2 pos;     // glVertex2f <-1,+1>
layout(location=8) in vec2 txr;     // glTexCoord2f  Unit0 <0,1>
out smooth vec2 t1;                 // fragment position <0,1>
void main()
    {
    t1=txr;
    gl_Position=vec4(pos,0.0,1.0);
    }

Fragment:
// Fragment
#version 420 core
uniform sampler2D txrmap;   // texture unit
uniform vec2 t0;            // mouse position <0,1>
in smooth vec2 t1;          // fragment position <0,1>
out vec4 col;

// light shape
const int n=3;
const float ldepth=0.25;    // distance to full disipation of light
const vec2 lpolygon[n]=     // vertexes CCW
    {
    vec2(-0.05,-0.05),
    vec2(+0.05,-0.05),
    vec2( 0.00,+0.05),
    };
void main()
    {
    int i;
    float l;
    vec2 p0,p1,p,n01;
    // compute perpendicular distance to edges of polygon
    for (p1=vec2(lpolygon[n-1]),l=0.0,i=0;i<n;i++)
        {
        p0=p1; p1=lpolygon[i];          // p0,p1 = edge of polygon
        p=p1-p0;                        // edge direction
        n01=normalize(vec2(+p.y,-p.x)); // edge normal CCW
//      n01=normalize(vec2(-p.y,+p.x)); // edge normal CW
        l=max(dot(n01,t1-t0-p0),l);
        }
    // convert to light strength
    l = max(ldepth-l,0.0)/ldepth;
    l=l*l*l;
    // render
//  col=l*texture2D(txrmap,t1);
    col = l*vec4(1.0,1.0,1.0,0.0);
    }

I used similar code How to implement 2D raycasting light effect in GLSL as a start point hence the slightly different names of variables.
The idea is to compute perpendicular distance of fragment to all the edges of your light shape and pick the biggest one as the others are facing wrong side.
The lpolygon[n] is the shape of light relative to light position t0 and the t1 is fragment position. It must be in CCW winding otherwise you would need to
 negate the normal computation (mine view is flipped so it might look its CW but its not). I used range <0,1> as you can use that as texture coordinate directly...
Here screenshot:

Here some explanations:

For analytical shape you need to use analytical distance computation ...


text:
Q: Dynamic Image size in Jasper Report I am trying to print a Jasper Report with a image. Image is displayed dynamically using a parameter. Image is printing fine. But I need to output the image size dynamically too. How can I pass the the image size (in inch) as a parameter and get my expected output?
<image>
<reportElement uuid="a4ed8a3a-827e-494c-ba8d-7276007941c7" x="0" y="0" width="555" height="608"/>
<imageExpression><![CDATA[$P{IMAGE_LOCATION}]]></imageExpression>
</image>

A: public JasperDesign dynamicImage() throws JRException {

    JasperDesign jasperDesign = new JasperDesign();
    jasperDesign.setName("NoXmlDesignReport");
    jasperDesign.setPageWidth(595);
    jasperDesign.setPageHeight(842);
    jasperDesign.setColumnWidth(515);
    jasperDesign.setColumnSpacing(0);
    jasperDesign.setLeftMargin(40);
    jasperDesign.setRightMargin(40);
    jasperDesign.setTopMargin(20);
    jasperDesign.setBottomMargin(20);

    JRDesignExpression expression = new JRDesignExpression();

    //Summary

        band = new JRDesignBand();
        band.setHeight(125);
        JRDesignImage jrDesignImage = new JRDesignImage(jasperDesign);
        expression = new JRDesignExpression();
        expression.setText("\"" "/path/to/image\"");
        jrDesignImage.setExpression(expression);
        jrDesignImage.setHorizontalAlignment(HorizontalAlignEnum.LEFT);
        jrDesignImage.setX(400);
        jrDesignImage.setY(0);
        jrDesignImage.setWidth(93);
        jrDesignImage.setHeight(100);
        jrDesignImage.setScaleImage(ScaleImageEnum.RETAIN_SHAPE);
        band.addElement(jrDesignImage);
        jasperDesign.setSummary(band);

    return jasperDesign;
}

You can set width and height dynamically.


text:
Q: Suggestions on on-going development of database schema when it's under replication I'm currently working on a database that comes with a legacy project which uses EntityFramework (updates code based on existing database using Data Model Designer)
Currently I work on the master copy and our developers work locally using SQL Server merge-replications on their local PC.
Issue here is that we recently started doing some change work that modifies the database schema, so when we use schema comparison (visual studio SQL compare feature), there are huge number of replication sp & schema changes that basically if I do update it will corrupt the live database.  So my current solution is remove the dev server replication (so that the schema goes back to what it should look like without replication changes), then do the schema compare & update, and then create a new merge replication again so our developers can continue working on the dev db.
I thought it was just one-off db schema change, but just realized it will be continuous changes at least for the next 3-6 months, so that basically make each release a big headache (if it can be called as a 'release' prep...)
My SQL & EntityFramework knowledge is limited, can anyone shed some light on this for me please?
Thanks in advance!

A: Whats the observed need behind merge replication in the dev environment? I understand the need for devs to have a local copy they can mess with, run tests against etc, but I'm lost on why a full Publisher-Subscriber model is needed to synchronize DB state in a dev/test environment, and it seems to be causing you more problems than it may solve given the schema is going to be malleable for a few months.
If merge replication is not a hard requirement for the dev environment, I would suggest you replace it with an alternate method of distributing changes to the local copies. If the devs are working with a full copy of the DB anyway, I see no reason not to write a script that backs up the master copy on the dev server, then pulls that file down and restores it locally. Then, changes to that schema would be accomplished with change scripts, which can be run and tested locally before being applied to the master DB, then distributed on-demand with another run of the backup/restore script.
It's a slightly more manual process and an older way to work with DBs, but it seems far more palatable to me than breaking and re-establishing replication regularly. It'll require some collaboration to make sure devs aren't trying to make a backup at the same time or making conflicting changes to local copies that will blow up on the master copy; your devs ideally should be talking to each other anyway about this kind of thing, and you might make the script smart enough to look for a recent backup before generating another.
One more thought, don't know how feasible it is given your progress to date; it's not impossible to switch from DB-First to Code-First. The conversion is basically a hybrid process of Database First and Code First; the DB is reverse-engineered as a one-time operation to generate a model similar to DB First, but instead of EDMX files, the model is written out to source code files, and changes to those model files or to mapping conventions on the context can then be aggregated and applied to the schema as migrations in typical Code First style. Assuming you prepare the live DB for migrations as well (and have the live DB in the same state as the master Dev DB prior to the model generation), this even removes the requirement of a SQL compare and update; you just apply the migrations to the live DB, same as you would to any Dev instance. The only potential gotcha is that some migrations can be written destructively, so you have to make sure what you're about to apply isn't going to clear out all the fields in a renamed column.


text:
Q: ASP.NET docker-compose app not coming up on assigned PORT working my way through tutorials on dockerized the API WeatherForecast web template from ASP.NET core:

*

*https://code.visualstudio.com/docs/containers/quickstart-aspnet-core

*https://code.visualstudio.com/docs/containers/docker-compose
I had to start from here, because I wasn't getting a new image to build using the tutorial here: https://docs.docker.com/compose/aspnet-mssql-compose/
"1" works, which is great. However, "2" will not work on the localhost:5000/WeatherForecast  port as advertised, and I'm having some trouble debugging why after many reviews of the available docs.
I should make a note that in creating the templated app from the command line, I did choose the --no-https option.
I then used docker ps  to bring up the PORTS . The web app is using 5000/tcp, 0.0.0.0:32779->80/tcp . When I substitute 5000  for 32779 , I get the API string returned instead!
I know I'm missing something within docker-compose  and could use some extra eyes on it. Thank you!
EDIT: For reference, the files below were generated by my VSCode editor.
1. I ran dotnet new webapi --no-https
2. I then brought up the VSCode "command pallete" and ran Docker: Add Dockerfiles to Workspace and selected 'yes' for the inclusion of docker-compose.yml file and Linux. I also choose to use port 5000. I use Fedora 30.
4. I run dotnet build from the project root in the terminal.
5. If I run from docker commands and make the ports explicit it will work as advertised, but if I run docker-compose -f <yml-file> up -d- --build, it will not.
I just re-read this and find it annoying that I'm stuck within VSCode to fix the issue (according to the docs)

By default Docker will assign a randomly chosen host port to a port exposed by a container (the container port). In this case the exposed (container) port is 5000, but it will be exposed on the host via a random port, such as 32737.
You can use specific port on the host by changing the Docker run options used by docker-run: debug task (defined in .vscode/tasks.json file). For example, if you want to use the same port (5000) to expose the service, the docker-run: debug task definition would look like this:

a. Dockerfile
    # Please refer https://aka.ms/HTTPSinContainer on how to setup an
    https developer certificate for your ASP .NET Core service.
    version: '3.4'

    services:
      aspdotnetdocker2:
        image: aspdotnetdocker2
        build:
          context: .
          dockerfile: Dockerfile
        ports:
          - 5000

b. docker-compose.yml
FROM mcr.microsoft.com/dotnet/core/aspnet:3.1 AS base
WORKDIR /app
EXPOSE 5000

FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build
WORKDIR /src
COPY ["aspdotnet_docker2.csproj", "./"]
RUN dotnet restore "./aspdotnet_docker2.csproj"
COPY . .
WORKDIR "/src/."
RUN dotnet build "aspdotnet_docker2.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "aspdotnet_docker2.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "aspdotnet_docker2.dll"]

A: Have a look at docker-compose docs:

SHORT SYNTAX
Either specify both ports (HOST:CONTAINER), or just the container port (an ephemeral host port is chosen).

So try:
ports:
  - "5000:<port in ASPNETCORE_URLS>"

  # e.g.
  # - "5000:80"
  # - "44388:443"


text:
Q: How do I pick a good representation for a board game tactic for a genetic algorithm? For my bachelor's thesis I want to write a genetic algorithm that learns to play the game of Stratego (if you don't know this game, it's probably safe to assume I said chess). I haven't ever before done actual AI projects, so it's an eye-opener to see how little I actually know of implementing things.
The thing I'm stuck with is coming up with a good representation for an actual strategy. I'm probably making some thinking error, but some problems I encounter:

*

*I don't assume you would have a representation containing a lot of
transitions between board positions, since that would just be
bruteforcing it, right?

*What could branches of a decision tree look
like? Any representation I come up with don't have interchangeable
branches... If I were to use a bit string, which is apparently also
common, what would the bits represent?

*Do I assign scores to the distance between certain pieces? How would I represent that?

I think I ought to know these things after three+ years of study, so I feel pretty stupid - this must look likeI have no clue at all. Still, any help or tips on what to Google would be appreciated!

A: I think, you could define a decision model and then try to optimize the parameters of that model. You can create multi-stage decision models also. I once did something similar for solving a dynamic dial-a-ride problem (paper here) by modeling it as a two stage linear decision problem. To give you an example, you could:

*

*For each of your figures decide which one is to move next. Each figure is characterized by certain features derived from its position on the board, e.g. ability to make a score, danger, protecting x other figures, and so on. Each of these features can be combined (e.g. in a linear model, through a neural network, through a symbolic expression tree, a decision tree, ...) and give you a rank on which figure to act next with.

*Acting with the figure you selected. Again there are a certain number of actions that can be taken, each has certain features. Again you can combine and rank them and one action will have the highest priority. This is the one you choose to perform.
The features you extract can be very simple or insanely complex, it's up to what you think will work best vs what takes how long to compute.
To evaluate and improve the quality of your decision model you can then simulate these decisions in several games against opponents and train the parameters of the model that combines these features to rank the moves (e.g. using a GA). This way you tune the model to win as many games as possible against the specified opponents. You can test the generality of that model by playing against opponents it has not seen before.
As Mathew Hall just said, you can use GP for this (if your model is a complex rule), but this is just one kind of model. In my case a linear combination of the weights did very well.
Btw, if you're interested we've also got a software on heuristic optimization which provides you with GA, GP and that stuff. It's called HeuristicLab. It's GPL and open source, but comes with a GUI (Windows). We've some Howto on how to evaluate the fitness function in an external program (data exchange using protocol buffers), so you can work on your simulation and your decision model and let the algorithms present in HeuristicLab optimize your parameters.

A: Vincent,
First, don't feel stupid.  You've been (I infer) studying basic computer science for three years; now you're applying those basic techniques to something pretty specialized-- a particular application (Stratego) in a narrow field (artificial intelligence.)
Second, make sure your advisor fully understands the rules of Stratego.  Stratego is played on a larger board, with more pieces (and more types of pieces) than chess.  This gives it a vastly larger space of legal positions, and a vastly larger space of legal moves.  It is also a game of hidden information, increasing the difficulty yet again.  Your advisor may want to limit the scope of the project, e.g., concentrate on a variant with full observation.  I don't know why you think this is simpler, except that the moves of the pieces are a little simpler.
Third, I think the right thing to do at first is to take a look at how games in general are handled in the field of AI.  Russell and Norvig, chapters 3 (for general background) and 5 (for two player games) are pretty accessible and well-written.  You'll see two basic ideas:  One, that you're basically performing a huge search in a tree looking for a win, and two, that for any non-trivial game, the trees are too large, so you search to a certain depth and then cop out with a "board evaluation function" and look for one of those.  I think your third bullet point is in this vein.
The board evaluation function is the magic, and probably a good candidate for using either a genetic algorithm, or a genetic program, either of which might be used in conjunction with a neural network.  The basic idea is that you are trying to design (or evolve, actually) a function that takes as input a board position, and outputs a single number.  Large numbers correspond to strong positions, and small numbers to weak positions.  There is a famous paper by Chellapilla and Fogel showing how to do this for a game of Checkers:
http://library.natural-selection.com/Library/1999/Evolving_NN_Checkers.pdf
I think that's a great paper, tying three great strands of AI together:  Adversarial search, genetic algorithms, and neural networks.  It should give you some inspiration about how to represent your board, how to think about board evaluations, etc.
Be warned, though, that what you're trying to do is substantially more complex than Chellapilla and Fogel's work.  That's okay-- it's 13 years later, after all, and you'll be at this for a while.  You're still going to have a problem representing the board, because the AI player has imperfect knowledge of its opponent's state; initially, nothing is known but positions, but eventually as pieces are eliminated in conflict, one can start using First Order Logic or related techniques to start narrowing down individual pieces, and possibly even probabilistic methods to infer information about the whole set.  (Some of these may be beyond the scope of an undergrad project.)

A: The fact you are having problems coming up with a representation for an actual strategy is not that surprising. In fact I would argue that it is the most challenging part of what you are attempting. Unfortunately, I haven't heard of Stratego so being a bit lazy I am going to assume you said chess.
The trouble is that a chess strategy is rather a complex thing. You suggest in your answer containing lots of transitions between board positions in the GA, but a chess board has more possible positions than the number of atoms in the universe this is clearly not going to work very well. What you will likely need to do is encode in the GA a series of weights/parameters that are attached to something that takes in the board position and fires out a move, I believe this is what you are hinting at in your second suggestion.
Probably the simplest suggestion would be to use some sort of generic function approximation like a neural network; Perceptrons or Radial Basis Functions are two possibilities. You can encode weights for the various nodes into the GA, although there are other fairly sound ways to train a neural network, see Backpropagation. You could perhaps encode the network structure instead/as well, this also has the advantage that I am pretty sure a fair amount of research has been done into developing neural networks with a genetic algorithm so you wouldn't be starting completely from scratch.
You still need to come up with how you are going to present the board to the neural network and interpret the result from it. Especially, with chess you would have to take note that a lot of moves will be illegal. It would be very beneficial if you could encode the board and interpret the result such that only legal moves are presented. I would suggest implementing the mechanics of the system and then playing around with different board representations to see what gives good results. A few ideas top of the head ideas to get you started could be, although I am not really convinced any of them are especially great ways to do this:

*

*A bit string with all 64 squares one after another with a number presenting what is present in each square. Most obvious, but probably a rather bad representation as a lot of work will be required to filter out illegal moves.

*A bit string with all 64 squares one after another with a number presenting what can move to each square. This has the advantage of embodying the covering concept of chess where you what to gain as much coverage of the board with your pieces as possible, but still has problems with illegal moves and dealing with friendly/enemy pieces.

*A bit string with all 32 pieces one after another with a number presenting the location of that piece in each square.

In general though I would suggest that chess is rather a complex game to start with, I think it will be rather hard to get something playing to standard which is noticeably better than random. I don't know if Stratego is any simpler, but I would strongly suggest you opt for a fairly simple game. This will let you focus on getting the mechanics of the implementation correct and the representation of the game state.
Anyway hope that is of some help to you.
EDIT: As a quick addition it is worth looking into how standard chess AI's work, I believe most use some sort of Minimax system.

A: When you say "tactic", do you mean you want the GA to give you a general algorithm to play the game (i.e. evolve an AI) or do you want the game to use a GA to search the space of possible moves to generate a move at each turn?
If you want to do the former, then look into using Genetic programming (GP). You could try to use it to produce the best AI you can for a fixed tree size. JGAP already comes with support for GP as well. See the JGAP Robocode example for an instance of this. This approach does mean you need a domain specific language for a Stratego AI, so you'll need to think carefully how you expose the board and pieces to it.
Using GP means your fitness function can just be how well the AI does at a fixed number of pre-programmed games, but that requires a good AI player to start with (or a very patient human).

A: @DonAndre's answer is absolutely correct for movement. In general, problems involving state-based decisions are hard to model with GAs, requiring some form of GP (either explicit or, as @DonAndre suggested, trees that are essentially declarative programs).
A general Stratego player seems to me quite challenging, but if you have a reasonable Stratego playing program, "Setting up your Stratego board" would be an excellent GA problem. The initial positions of your pieces would be the phenotype and the outcome of the external Stratego-playing code would be the fitness. It is intuitively likely that random setups would be disadvantaged versus setups that have a few "good ideas" and that small "good ideas" could be combined into fitter-and-fitter setups.
...
On the general problem of what a decision tree, even trying to come up with a simple example, I kept finding it hard to come up with a small enough example, but maybe in the case where you are evaluation whether to attack a same-ranked piece (which, IIRC destroys both you and the other piece?):
double locationNeed = aVeryComplexDecisionTree();
if(thatRank == thisRank){
   double sacrificeWillingness = SACRIFICE_GENETIC_BASE; //Assume range 0.0 - 1.0
   double sacrificeNeed = anotherComplexTree(); //0.0 - 1.0
   double sacrificeInContext = sacrificeNeed * SACRIFICE_NEED_GENETIC_DISCOUNT; //0.0 - 1.0
   if(sacrificeInContext > sacrificeNeed){
      ...OK, this piece is "willing" to sacrifice itself

One way or the other, the basic idea is that you'd still have a lot of coding of Stratego-play, you'd just be seeking places where you could insert parameters that would change the outcome. Here I had the idea of a "base" disposition to sacrifice itself (presumably higher in common pieces) and a "discount" genetically-determined parameter that would weight whether the piece would "accept or reject" the need for a sacrifice.


text:
Q: ¿Cuándo usar diccionarios y cuando usar tuplas en Swift? Cuando tengo que pasar parámetros a una función normalmente en Objective-C lo hago mediante un diccionario. En Swift esto se puede hacer también con tuplas.
¿Para trabajar con Swift qué es mas aconsejable, usar diccionarios o tuplas? ¿Cuáles son los pros y contras entre usar uno u otro sistema?

A: una tupla es una pareja de 2 variables, da lo mismo de lo que sea cada una y un diccionario es un conjunto de clave-valor. Por ejemplo si quieres tener país y capital y lo tienes en una tupla tendrás un primer elemento de la tupla que sera el país y un segundo que sera la capital. Tendrías algo como esto:
var tupla1: (String, String) = ("España", "Madrid")

En un diccionario tendrás una clave que sera el país y un valor que sera la capital. Si quieres añadir otro país, en la tupla ya no te cabe, tenderas que crear otra tupla y en el diccionario solo añades otro clave valor,
var tupla2: (String, String) = ("Francia", "Paris")

Si haces un array de tuplas, podría simular un diccionario, pero cuando quisieras saber la capital de Francia, con el diccionario accederías muy fácil con Diccionario["Francia"]. Con la tupla no existe esta opción, deberías ir buscando en ese array de tuplas hasta que encuentras una que tenga como primer elemento "Francia", tendrías algo como esto:
var array: [(String, String)] = [("España", "Madrid"), ("Francia", "Paris")]

Espero que te haya servido

A: Las tuplas y los diccionarios son estructuras de datos distintas, cada una con sus características. Si bien en tu caso de "pasar parámetros a una función" puede hacerse con cualquiera de las dos, no son intercambiables.
De hecho, una tupla podría ser más parecido a un struct anónimo (por así decirlo) que a un diccionario.
Con respecto a tu caso de uso (pasar parámetros a un función):

*

*Lo mejor es pasar los valores de a uno, cada uno con su tipo de datos. Agregarlos en una tupla o en un diccionario es innecesario, agrega complejidad al código y afecta el rendimiento en ejecución.

*Dicho esto, si de todas formas no los quieres pasar de a uno, entonces tendría en cuenta que:

*

*si son pocos parámetros y siempre están presentes todos, usaría una tupla

*si son muchos y son todos opcionales, y además la mayoría de las veces voy a pasarle un conjunto reducido de parámetros, entonces usaría un diccionario.


text:
Q: regex for matching an entire line $0 in awk I need some help or advice wrt awk and its use of regular expressions. I have a data input file with an irregular structure. To parse this file correctly I need to recognize a line of the following form:
@ 8/1/17, 10:04 PM

A line with this pattern marks the end of a complete transaction. It's simply a date & time stamp preceded by a space and the @ character.
I've cobbled a regular expression that seems to match in "most" usage:
\W\@\W[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{1,2}\,\W[0-9]{1,2}\:[0-9]{2}\W[AP]M

However, it does not seem to match when used in the following awk statement:
$ awk 'match($0, /\W\@\W[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{1,2}\,\W[0-9]{1,2}\:[0-9]{2}\W[AP]M/) {print $0}' testfile2.txt

My system (macos mojave) has an old version of awk awk version 20070501.
I've also found:

*

*grep -e fails to match this pattern to any line in testfile2.txt, but egrep and grep -E do match the lines I expected them to match.

*awk 'match($0, /\@/) {print $0}' testfile2.txt does match (& print) the expected lines, but I can't rely on a single character!
Here's testfile2.txt:

+13054261988: Forwarding data to primary repository
   @ 1/7/18, 4:21 PM
  +16744774911: Use this URL: https://www.repo-prime.ga/
   @ 1/7/18, 4:22 PM
  +13054261988: Will do. Passwords OK?
   @ 1/7/18, 6:12 PM
  +16744774911: No, use 2FA for all transactions
   @ 1/7/18, 8:56 PM
  +13054261988: Using Google's authenticator?
If so, will need additional information.
   @ 1/7/18, 9:36 PM
  +13054261988: RSVP ASAP, I have transactions that need to be uploaded.
   @ 1/7/18, 9:46 PM

Is my regular expression failing to match in awk usage due to an error I can't see in my awk statement, or is it due to the regex itself, a combination of both, etc?

A: *

*why strictly matching /\W (non-word character) before @ ? as in your text file @ is at start of the line

*no need to escape the chars as \@, \,, : (they are not special chars)

*calling match() is redundant if only need to match a pattern

$ awk '/^@ [0-9]{1,2}\/[0-9]{1,2}\/[0-9]{1,2}, [0-9]{1,2}:[0-9]{2} [AP]M/' file
@ 1/7/18, 4:21 PM
@ 1/7/18, 4:22 PM
@ 1/7/18, 6:12 PM
@ 1/7/18, 8:56 PM
@ 1/7/18, 9:36 PM
@ 1/7/18, 9:46 PM

A: Seems that very old versions of awk had not {…} capability.
This older regex syntax should match in any awk:
awk '/@ [0-9][0-9]?\/[0-9][0-9]?\/[0-9][0-9]?, [1-2]?[0-9]:[0-6][0-9] [AP]M/' file

If your awk could match bracket expressions like [[:blank:]], the regex could be made to be a little more flexible:
awk '/@[[:blank:]][0-9][0-9]?\/[0-9][0-9]?\/[0-9][0-9]?,[[:blank:]][1-2]?[0-9]:[0-6][0-9][[:blank:]][AP]M/' file

If matching one (or more) digits is good enough (I can't see why not), you can use the shorter regex:
awk '/@ [0-9]+\/[0-9]+\/[0-9]+, [1-2]?[0-9]:[0-6][0-9] [AP]M/' file

And you can add start ^ and end $ to make the regex quite more restrictive, if needed.
I am not using match for such a simple matching of a line, but the same regex would work perfectly fine with that function.


text:
Q: SKPhysicsBody contact with the SKSpriteNode I try to make a contact between two nodes and the code is below:
SKTexture *bgTexttureRiverLeft = [SKTexture textureWithImageNamed:@"River_Left_Main"];
bgTexttureRiverLeft.filteringMode = SKTextureFilteringNearest;
SKSpriteNode *spriteRiverLeft = [SKSpriteNode spriteNodeWithTexture:bgTexttureRiverLeft];
spriteRiverLeft.texture.filteringMode = SKTextureFilteringNearest;
spriteRiverLeft.anchorPoint = CGPointZero;
spriteRiverLeft.position = CGPointZero;
spriteRiverLeft.zPosition = -10;
spriteRiverLeft.name = @"River_Left_Main";

spriteRiverLeft.size = CGSizeMake(spriteRiverLeft01.size.width *0.8, _screenSize.height);

spriteRiverLeft.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(spriteRiverLeft.size.width*1.85, spriteRiverLeft.size.height*2)];
spriteRiverLeft.physicsBody.categoryBitMask = river_left_Category;
spriteRiverLeft.physicsBody.collisionBitMask = kajakCategory;
spriteRiverLeft.physicsBody.contactTestBitMask = kajakCategory ;
spriteRiverLeft.physicsBody.dynamic = YES;
spriteRiverLeft.physicsBody.allowsRotation = YES;

[self addChild:spriteRiverLeft];

Because SKTexture River_Left_Main is not a straight line (twisting river), the contact between kayak and the edge of river is perfect some place and not that perfect another places (too late or too early).
My question is how to make the contact more precise? Thank you in advance.

A: CGMutablePathRef path = CGPathCreateMutable();
is the answer. A lot of job but you have to do what you have to do!


text:
Q: C# - Automatic Login to a webpage using WebBrowser - disabled html tag After some research on the WebBrowser DocumentCompleted issue, I've inserted my login attempt into the DocumentCompleted Event Handler.
Here's my code:
public void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        wb.Navigate("fooPage");
        var browser = (WebBrowser)sender;

        HtmlElement email = CookieReader.GetElement("email", browser);
        HtmlElement password = CookieReader.GetElement("pass", browser);
        email.SetAttribute("email", "foo@something.com");
        password.SetAttribute("pass", "foo");
        HtmlElement loginElement = CookieReader.GetElement("fooLog", browser);
        loginElement.InvokeMember("click"); //wb_DocumentCompleted Method Continues...

I didn't manage to login (double checked that I got the login button right). It seems that the problem is with the ReadyState property of the browser object. It's always loading, while the IsBusy property is always False. Also, the page was supposed to finish loading because the DocumentCompleted event fired. Any ideas how this even possible?
Moreover, when debugging, the InvokeMember method changes the html INPUT element and a disabled tag appears (disabled=\"\" - which is HTML5 disabled="disabled" if I'm not mistaken). I don't know why this tag is added (wasn't there before), and if it's related in any way to the permanent Loading ReadyState of the page... insights and/or advises will be much appreciated!

A: I had the same problem. The DocumentCompleted event fires more that once in a single load. I think the first is not the real one. I think you should create a BackgroundWorker and start it when the DocumentCompleted event fires. It should wait a few seconds before do the job. That will definitely work.
You should start the BackgroundWorker only once.


text:
Q: How do I get an element from an HTML table that has an always changing child element number? I am trying to collect the total number of hours that I worked from each pay period that I worked. I can collect the total number of hours from the "Grand Totals" section, however it seems like that section never has a static child element number and shares class names with another row.
Here is an example:
from the first page, if I copy selector in Chrome, I get:
#TableTimeCard > tbody > tr:nth-child(12) > td:nth-child(3)

However, when I go to the next pay period, I get:
#TableTimeCard > tbody > tr:nth-child(14) > td:nth-child(3)

That "tr:nth-child" number ranges between 4 and however many number of entries I had on my time card.
Here is the snippet of code from the site. I am trying to take in 10.37:

I've tried grabbing it by that class name but then it just grabs the first number after "Total Hours" in the image. In this case, 0.00. I believe the reason why is because it has the same class name:

All I need to do is print grand total hours to console. Any ideas?
I am doing print(driver.find_element_by_css_selector("#TableTimeCard > tbody > tr:nth-child(12) > td:nth-child(3)")
Thanks!

A: Well, you can use find_elements  to store all of them, and can iterate like this :-
hours = find_elements(By.CSS_SELECTOR, "#TableTimeCard > tbody > tr > td:nth-child(3)")
print(hours[0].text)

or even you can iterate that list as well :-
for hour in find_elements(By.CSS_SELECTOR, "#TableTimeCard > tbody > tr > td:nth-child(3)"):
    print(hour.text)

Update 1 :
In case if you just want to grab Total hours value, use this xpath :-
//td[text()='Grand Totals']/following-sibling::td[4]

in code :
print(driver.find_element_by_xpath("//td[text()='Grand Totals']/following-sibling::td[4]").text)


text:
Q: Fastest way to create column in pandas based on multiple conditions I'm currently using this function:
def age_groupf(row):
    if row['Age'] <= 19:
        val = '15-19'
    elif row['Age'] <= 24:
        val = '20-24'
    elif row['Age'] <= 29:
        val = '25-29'
    elif row['Age'] <= 34:
        val = '30-34'
    elif row['Age'] <= 39:
        val = '35-39'
    elif row['Age'] <= 44:
        val = '40-44'
    elif row['Age'] <= 49:
        val = '45-49'
    elif row['Age'] <= 54:
        val = '50-54'
    elif row['Age'] <= 59:
        val = '55-59'
    else:
        val = '60 and more'
    return val

to generate AGE-GROUP fields by calling:
DF['AGE-GROUP'] = DF.apply(age_groupf, axis=1)

seems like it's working but it's slow. I have multiple 100MB TXT files and I need this to be faster.

A: Use pandas.cut with defined bins and labels.
For example:
bins = [15, 20, 25, 30, 35, 40, 45, 50, 55, 60, np.inf]
labels = [f'{x}-{y-1}' if y!=np.inf else f'{x} and more' for x, y in zip(bins[::], bins[1::])]

pd.cut(df['Age'], bins=bins, labels=labels)


text:
Q: Biggest neighbourhood of $3$ where $\arctan(z)$ has a convergent taylor series What is the biggest neighbourhood $U$ containing $3$ where $\arctan(z)$ has a convergent taylor series?
So far I have tried to use $\arctan'(z)=\frac{1}{1+z^2}$ to construct a taylor series centered at $3$ with the geometric series. It is easy to obtain a series centered at $0$ but I fail to get one at $3$. Is this even a promising approach? Or can I argue differently and a taylor series doesn't have to be constructed explicitly?

Edit: I quickly want to flesh out my idea mentioned in the comment section: Firstly, a partial fractions decomposition yields $$f'(z)=\frac{1}{1+z^{2}}=\frac{-i/2}{z-i}+\frac{i/2}{z+i}.$$ Then we have

*

*$\frac{1}{z-i}=-\frac{1}{i-3}\cdot\frac{1}{1-\frac{z-3}{i-3}}=\frac{1}{3-i}\cdot\sum_{n=0}^{\infty}\left(\frac{z-3}{i-3}\right)^{n}$ for $z\in D_{\sqrt{10}}(3)$.

*$\frac{1}{z+i}=\frac{1}{i+3}\cdot\frac{1}{1-\frac{z-3}{i+3}}=\frac{1}{3+i}\cdot\sum_{n=0}^{\infty}\left(\frac{z-3}{i+3}\right)^{n}$ for $z\in D_\sqrt{10}(3)$.

In total I get $$f'(z)=\sum_{n=0}^{\infty}\frac{i}{2}\left(\frac{1}{(3+i)^{n+1}}+\frac{1}{(i-3)^{n+1}}\right)(z-3)^{n}$$ and thus $$f(z)=\sum_{n=0}^{\infty}\frac{i}{2(n+1)}\left(\frac{1}{(3+i)^{n+1}}+\frac{1}{(i-3)^{n+1}}\right)(z-3)^{n+1}$$ as my taylor series converging on $D_\sqrt{10}(3)$.

A: If you want the biggest disk centered at $3$ such that $\arctan$ has a convergent Taylor series there, take the disk with radius $\sqrt{10}$. That's so because $\pm i$ are the singularities of $\frac1{1+z^2}$ closest to $3$ and the distance from $3$ to $\pm i$ is $\sqrt{10}$. And integrating term by term the Taylor series of $\frac1{1+z^2}$, you get the Taylor series of $\arctan$.