text:
Q: Calculated column value based on rows above SQL I have this stupid table in our program db. Program is not ours so there is no way to change table contents. The table stores SQL like expressions in unreadable codes. I am translating those values back to SQL expressions to run these expressions. So far, the translating part goes very well. Result so far is a table like the following:
+--------+--------+---------+----------------+-----------------+
| CODE   | SEQNUM | LOGICAL | EXPRESSION     | EXPRESSIONVALUE |
+--------+--------+---------+----------------+-----------------+
| A23000 | 1      | NULL    | OTHERCODE LIKE | 'A522%'         |
+--------+--------+---------+----------------+-----------------+
| A23000 | 2      | OR      | OTHERCODE =    | 'A62342'        |
+--------+--------+---------+----------------+-----------------+
| A23000 | 3      | OR      | OTHERCODE =    | 'A62343'        |
+--------+--------+---------+----------------+-----------------+
| B43000 | 1      | NULL    | OTHERCODE IN   | 'B34324'        |
+--------+--------+---------+----------------+-----------------+
| B43000 | 2      | NULL    | NULL           | 'B92338'        |
+--------+--------+---------+----------------+-----------------+
| B43000 | 3      | NULL    | NULL           | 'B92342'        |
+--------+--------+---------+----------------+-----------------+
| B43000 | 4      | NULL    | NULL           | 'B02349'        |
+--------+--------+---------+----------------+-----------------+
| B43000 | 5      | OR      | OTHERCODE =    | 'B32443'        |
+--------+--------+---------+----------------+-----------------+

Or order for me to have valid SQL statements, I need to have commas behind the rows where there is an 'in-expression'. I my opinion this needs to be based on earlier rows. I need to have a table like:
+--------+--------+---------+----------------+-----------------+------------+
| CODE   | SEQNUM | LOGICAL | EXPRESSION     | EXPRESSIONVALUE | CALCULETED |
+--------+--------+---------+----------------+-----------------+------------+
| A23000 | 1      | NULL    | OTHERCODE LIKE | 'A522%'         | NULL       |
+--------+--------+---------+----------------+-----------------+------------+
| A23000 | 2      | OR      | OTHERCODE =    | 'A62342'        | NULL       |
+--------+--------+---------+----------------+-----------------+------------+
| A23000 | 3      | OR      | OTHERCODE =    | 'A62343'        | NULL       |
+--------+--------+---------+----------------+-----------------+------------+
| B43000 | 1      | NULL    | OTHERCODE IN   | 'B34324'        | ','        |
+--------+--------+---------+----------------+-----------------+------------+
| B43000 | 2      | NULL    | NULL           | 'B92338'        | ','        |
+--------+--------+---------+----------------+-----------------+------------+
| B43000 | 3      | NULL    | NULL           | 'B92342'        | ','        |
+--------+--------+---------+----------------+-----------------+------------+
| B43000 | 4      | NULL    | NULL           | 'B02349'        | NULL       |
+--------+--------+---------+----------------+-----------------+------------+
| B43000 | 5      | OR      | OTHERCODE =    | 'B32443'        | NULL       |
+--------+--------+---------+----------------+-----------------+------------+

Is this possible to do with SQL?

A: Would this help?
SQL> with test (code, seqnum, logical, expression, value) as
  2    (select 'a23', 1, null, 'othercode like', 'a522%'  from dual union all
  3     select 'a23', 2, 'or', 'othercode ='   , 'a62342' from dual union all
  4     select 'a23', 3, 'or', 'othercode ='   , 'a62343' from dual union all
  5     --
  6     select 'b43', 1, null, 'othercode in'  , 'b34324' from dual union all
  7     select 'b43', 2, null, 'null'          , 'b92342' from dual union all
  8     select 'b43', 3, null, 'null'          , 'b02349' from dual union all
  9     select 'b43', 4, 'or', 'othercode ='   , 'b34243' from dual
 10    ),
 11  poc as
 12    -- SEQNUM where "IN" begins
 13   (select code, min(seqnum) minseq
 14    from test
 15    where expression = 'othercode in'
 16    group by code
 17    ),
 18  zav as
 19    -- SEQNUM where "IN" part ends
 20    (select t.code, max(t.seqnum) maxseq
 21     from test t join poc p on p.code = t.code
 22     where t.seqnum > p.minseq
 23       and t.expression <> 'null'
 24     group by t.code
 25    )
 26  select t.code, t.seqnum, t.logical, t.expression, t.value,
 27    case when t.seqnum >= p.minseq and t.seqnum < z.maxseq then ','
 28         else null
 29    end calc
 30  from test t left join poc p on p.code = t.code
 31              left join zav z on z.code = t.code
 32  order by code, seqnum;

COD     SEQNUM LO EXPRESSION     VALUE   C
--- ---------- -- -------------- ------- -
a23          1    othercode like a522%
a23          2 or othercode =    a62342
a23          3 or othercode =    a62343
b43          1    othercode in   b34324  ,
b43          2    null           b92342  ,
b43          3    null           b02349  ,
b43          4 or othercode =    b342443

7 rows selected.

SQL>

A: You can do this logic with analytic functions:
select t.*,
       (case when coalesce(expression, lag(expression ignore nulls) over (partition by code order by seqnum)) like '% in' and
                  ((lead(logical) over (partition by code order by seqnum) is null and
                    lead(seqnum) over (partition by code order by seqnum) is not null
                   ) or
                   lead(seqnum) over (partition by code order by seqnum) is not null
                  )
             then ','
        end) as calculated
from test t;

The logic implemented identifies the rows associated with in logic -- that is the lag(ignore nulls).
All of these rows get a comma, except for the last one.  This is tricky, because the last row might be the end of the expression (the last row seqnum for the code).  Or, a new boolean expression might follow.
I have added more test cases to show that this works:

*

*No expression after the in.

*Only one value in the in list.

*Another expression before the in.

Here is the db<>fiddle.


text:
Q: List & Label: Getting ErrorCode -105 with Delphi VCL components I have a problem using the List & Label components with the Delphi VCL. When I'm accessing the Design method of the TL20_ object, I get the following error code:

error code -105 (license error)

procedure TForm3.Button1Click(Sender: TObject);
var
  llDriver: TL20_;
  res: Integer;
begin
  llDriver := TL20_.Create(Self);
  try
    llDriver.Language := ltDefaultLang;
    llDriver.LicensingInfo := 'xxxxxx';
    res := llDriver.Design(0, WindowHandle, '123', LL_PROJECT_LABEL, '123', False, True);
    ShowMessage(llDriver.LlGetErrortext(res));
  finally
    FreeAndNil(llDriver);
  end;
end;

Using the same license key with a Python application on the same PC works fine.
Any suggestions?

A: You need to set the LicensingInfo property of the VCL component to the value that can be found in the personal license information file that comes with the installation.

redpajama_set_name: RedPajamaStackExchange


text:
Q: build failed when trying to run flutter app on a emulator (vscode) I've tried to run a flutter application on an installed android emulator on vscode and the build error occurred
(https://i.stack.imgur.com/l2mgF.png)

A: As stated in the error one of your package require a higher Android SDK version.
Go to the file
android/app/build.gradle
Search for
compileSdkVersion
And change its value to
compileSdkVersion 33
This might solve the problem


text:
Q: What standards does your team enforce for a major-version code deployment? I'm curious as to what sort of standards other teams make sure is in place before code ships (or deploys) out the door in major releases.
I'm not looking for specific answers to each, but here's an idea of what I'm trying to get an idea of.

*

*For server-based apps, do you ensure monitoring is in place? To what degree...just that it responds to ping, that it can hit all of its dependencies at any given moment, that the logic that the app actually services is sound (e.g., a service that calculates 2+2 actually returns "4")

*Do you require automated build scripts before code is released? Meaning, any dev can walk onto a new box, yank something from source control, and start developing? Given things like an OS and IDE, of course.

*How about automated deployment scripts, for server-based apps?

*What level of documentation do you require for a project to be "done?"

*Do you make dang sure you have a full-fledged backup plan for all of the major components of the system, if it's server-based?

*Do you enforce code quality standards? Think StyleCop for .NET or cyclomatic complexity evaluations.

*Unit testing? Integration tests? Performance load testing?

*Do you have standards for how your application's error logging is handled? How about error notification?

Again, not looking for a line-by-line punchlist of answers to anything above, necessarily. In short, what non-coding items must a code release have completed before it's officially considered "done" for your team?

A: The minimun:

*

*unit tests work

*integration tests work

*deploy on test stage ok

*manual short check on test stage

Better:

*

*unit tests work

*checkstyle ok

*integration tests work

*metrics like jmeter and test coverage passed

*deploy on test stage ok

*some manual tests on test stage

finally deploy on production stage
All unit and integration tests work automatically, best on a continuous integration server like CruiseControl done by ant or maven. When developing webservices, testing with soapui works fine.
If a database used, automatic upgrade is done (with liquibase for example) before deployment. When external services are used, addidional configuration tests are needed, to ensure URLs are ok (head request from application, database connect, wsdl get, ...).
When developing webpps, a HTML validation on some pages will be usefull. A manual check of the layout (use browsershots for example) would be usefull.
(All example links for Java development)
And last (but not least): are all acceptance tests still passing? Is the product what the owner wants? Make a live review with him on the test system before going further!

A: I mostly do web development, so my items may be different from yours.  Just off the top of my head...

*

*Ensure all web services are up-to-date

*Ensure all database scripts/changes/migrations are already deployed to the production server

*Min all js and css files.

*Make sure all unit/functional/integration/Selenium tests are passing (We aim for 95%+ test coverage while we're developing, so these are usually pretty accurate in determining a problem)

There's more, I know there is, but I can't think of any right now.

A: Each and every project is different, however as a rule of thumb here are the core things that I try to have done prior to letting code go out to the wild.
In no particular order:
1) A version identification in place where it can be found by a user later, this must be unique to this release. (very typically a "version number" associated on the distributable, the libraries and executable, or user visible from an "about" dialog.  Could be a number at a well known register or offset in firmware)
2) A snapshot of the exact code used to produce the release. (a label or a branch of the release in the SCM system is good for this)
3) All the tools necessary to recreate the source must be noted and archived (source from step 2 becomes of limited use without this)
4) An archive of the actual release (a copy of the exact installer released, who knows in 7 years your tools may not be able to build it, but now at least you have the source code and an installable at your side for investigation purposes).
5) A set of documented changes between this release version and the previous one aka Release Notes  (I like to use the style of appending to the list so that all release changes are available in one place for a user).
6) Candidate release test cycle complete.  Using the distributable created load and test using full/vetted test plan to be sure core functionality is operational, all new features are present and operating as intended.
7) Defect tracking shows all outstanding items are flagged as a) fixed b) not a defect c) deferred.
You can sprinkle in many other steps depending upon domain or development style, but I would state that most software "should be" performing the above steps each and every release. YMMV.
Have fun storming the castle.

A: *

*Codestyle (automated)

*Automated Tests (Unit- & Integrationtests)

*Manual Tests (including test and beta stages)

*Whitebox penetration testing tool (automated)

*Blackbox penetration testing tool (automated)

*Manual Exception/Logging monitoring on test/beta stages before rollout

*ability to revert to previous version at any time

*code review & 'illegal checkins'

A: For web / internal apps one thing in addition to the other suggestions.
Make sure to involve the ops/deployment team so you don't deliver software which requires more servers then they have (don't assume the people pushing the requirements already have).

A: *

*Review the checklist: check that all the new features, change requests and bug fixes planned for the version  have been finished.

*Build (in build machine) compiles without any warning nor error in Release mode.

*All the automated Unit Tests run without error.

*All the messages and images have been approved by the product team.

*Performance checks are not worst than former version.

*The full (manual) test plan has been checked by the test team without errors.

*

*The application is tested in many possible scenarios (different OS, database engines, configurations and third party applications).

*All the features of the application are tested: many times happened to us that a change in a feature broke another one thought unrelated, shit happens, so we have to minimize it.

*The setup or deployment works in all the scenarios too

*The setup is able to upgrade former versions

A: We did a major release recently, so this is still pretty fresh in my mind. We make a Windows application with a GUI for which we release a binary executable, so my list is necessarily going to be substantially different from that for a web-only release.

*

*Release candidates go out to the testing team. They need at least a few days to play with it. If they find any bugs that we consider show-stoppers, release is aborted. This presumes you have a testing team. We only clear a release candidate if at least one week has passed since its build date.

*All automated testing has to work and pass. Automated testing is considered a supplement to the live testers.

*Any bugs marked as "blockers" must be resolved for the final build.

*Publicity material has to be ready (in our case, a web-page update and an email newsletter). Resellers are alerted that a release is coming several weeks in advance, so that they can prepare their material as well. This mostly isn't a programmer concern, but we do check marketing claims for accuracy.

*Licensing has to be updated to reflect whatever copy-protection we're using. Our beta versions and the release versions use different licensing models, and this change requires programming effort.

*The installer and license agreement have to be updated. Since the beta versions have an installer, this is usually just a text change, but it still falls to the programmers to actually update the install script.

*Any references to the beta version need to be removed from the application itself. We missed a few of these, embarrassingly.

*Help files and manuals had to be brought completely up-to-date and proofread, since they were part of the release package.

*If there were bugs that couldn't be fixed in time, we would at least try to mitigate the damage -- for example, detect that such-and-such bug was occurring, and abort the operation with an apologetic error message. This contributes enormously to perceived product stability.
Far and away, the difficulties of a major release were not programming problems, they were administrative/marketing problems. Many of these things required programmer attention -- helping with installers, proof-reading the feature list to make sure none of it was nonsense, proof-reading technical sections of the manual, updating licensing, etc. The main technical difference was the shift from bug-fixing to bug-mitigating.

A: *

*no visible bugs? ok

*unit test work? ok (some ignored) ha well ok

*setup ya sure. ok

*error logging ? off course ! :-) we need this ! to fix the bugs!

*all on cruisecontrol.net nice.


text:
Q: How to use WebShare Api for multiple Post in the blogger PostSnippet I'm trying to create a Share button using WebShare API for every post in the postsnippet on the homepage of a blogger website.
When I'm clicking on the first post button it works fine, but for other it doesn't.
What should I do to make it work on every post?
See what I created:
Demo
As we know, for post snippet in blogger we have to create only one div and id, like this:

                        <svg class='line' viewBox='0 0 24 24'>
                            <path d='M92.30583,264.72053a3.42745,3.42745,0,0,1-.37,1.57,3.51,3.51,0,1,1,0-3.13995A3.42751,3.42751,0,0,1,92.30583,264.72053Z' transform='translate(-83.28571 -252.73452)'/>
                            <circle cx='18.48892' cy='5.49436' r='3.51099'/>
                            <circle cx='18.48892' cy='18.50564' r='3.51099'/>
                            <line class='cls-3' x1='12.53012' x2='8.65012' y1='8.476' y2='10.416'/>
                            <line class='cls-3' x1='12.53012' x2='8.65012' y1='15.496' y2='13.556'/>
                        </svg>

                        <data:post.title/>

<data:post.title/>

                                <data:blog.metaDescription/>

                                <data:post.body/>


text:
Q: Makefile executes only the first target I have files that look like this
1_0_fa.bam  1_1_fa.bam  1_2_fa.bam  1_3_fa.bam  1_4_fa.bam  1_5_fa.bam
1_6_fa.bam  1_7_fa.bam  1_8_fa.bam  1_9_fa.bam  1_0_mo.bam  1_1_mo.bam
1_2_mo.bam  1_3_mo.bam  1_4_mo.bam  1_5_mo.bam  1_6_mo.bam  1_7_mo.bam
1_8_mo.bam  1_9_mo.bam  1_0_p1.bam  1_1_p1.bam  1_2_p1.bam  1_3_p1.bam
1_4_p1.bam  1_5_p1.bam  1_6_p1.bam  1_7_p1.bam  1_8_p1.bam  1_9_p1.bam

I'd like to combine them by bin, which is the second number in the name. Here is my Makefile (GNU make 3.81)
SHELL = /bin/sh
bins = 0 1 2 3 4 5 6 7 8 9
$(info $(bins))
code = 1

define buildVCF

$(info $(1))
$(eval targ = $(code)_$(1)_bin.vcf)
$(info $(targ))
targs += $(targ)
$(eval deps = $(wildcard $(code)_$(1)_*.bam))
$(info $(deps))

$(targ): $(deps)
    cat $$^ > $$@

endef

$(foreach bin,$(bins),$(eval $(call buildVCF,$(bin))))

all: $(targs)

If i do make -n, it produces
0 1 2 3 4 5 6 7 8 9
0
1_0_bin.vcf
1_0_p1.bam 1_0_mo.bam 1_0_fa.bam
1
1_1_bin.vcf
1_1_fa.bam 1_1_p1.bam 1_1_mo.bam
2
1_2_bin.vcf
1_2_mo.bam 1_2_p1.bam 1_2_fa.bam
3
1_3_bin.vcf
1_3_fa.bam 1_3_mo.bam 1_3_p1.bam
4
1_4_bin.vcf
1_4_mo.bam 1_4_fa.bam 1_4_p1.bam
5
1_5_bin.vcf
1_5_fa.bam 1_5_mo.bam 1_5_p1.bam
6
1_6_bin.vcf
1_6_p1.bam 1_6_fa.bam 1_6_mo.bam
7
1_7_bin.vcf
1_7_fa.bam 1_7_p1.bam 1_7_mo.bam
8
1_8_bin.vcf
1_8_fa.bam 1_8_mo.bam 1_8_p1.bam
9
1_9_bin.vcf
1_9_mo.bam 1_9_p1.bam 1_9_fa.bam
cat 1_0_p1.bam 1_0_mo.bam 1_0_fa.bam > 1_0_bin.vcf

Why is not building the rest of the targets?

A: Because the all target isn't the first in the Makefile. When you call make without a target, the first rule in the Makefile is built, which in this case is the one for 1_0_bin.vcf (because it is generated first). If you call make -n all, it'll work as you expect.
To make it work without an explicit rule, just moving the all target to the top won't work because targs doesn't have the correct value at that point, but you can make it work using a level of indirection:
all: dummy

define buildVCF
...
endef

$(foreach bin,$(bins),$(eval $(call buildVCF,$(bin))))

dummy: $(targs)

However, this does seem like a rather roundabout way of doing things. If I were you, I'd attempt to solve the problem with a static pattern rule, such as
targs = $(foreach bin,$(bins),$(code)_$(bin)_bin.vcf)

all: $(targs)

$(targs) : $(code)_%_bin.vcf : $(foreach i,fa mo p1,$(code)_%_$(i).bam)
    cat $^ > $@

A: When no target is specified on the command line make builds the default goal.
The default goal is

the first target (not targets whose names start with '.')

In your makefile the first target is the first target created by the buildVCF define.
As Wintermute points out you can't simply move the all: $(targs) line above the loop as targs doesn't have the correct value yet.
That being said you can either put all: above the loop to "reserve" the default target (in which case all: $(targs) appends prerequisites to the reserved target) or you can manually set the default goal with .DEFAULT_GOAL := all anywhere in the makefile.
On a different not I haven't fully understood the setup you have but I would imagine you could do this with a simpler set of general pattern (or static pattern) rules.


text:
Q: how to calculate 1000 digit number divided by 13 N = 111...111 which consists of 1000 digits of ones.
What is the remainder of N upon division by 13?
N = 111...111=111...08+3
N = 4k+3 but I can not go further.

A: Note that your number $N=11 \ldots 1$, with $1000$ digits, is equal to $(10^{1000}-1)/9$, and since gcd$(10,13)=1$, we have by Fermat's little theorem that $10^{12} \equiv 1 \pmod{13} \Rightarrow (10^{12})^{83} \equiv 1 \pmod{13}$ and so $10^{1000} = 10^{12\times 83 +4} \equiv 10^4 \equiv 3 \pmod{13}$, then, finally, $10^{1000}-1\equiv 2 \pmod{13}$, which gives us that $9N \equiv 2 \pmod{13}$. Multiplying both sides by $3$, we get  $N \equiv 3\times9 N \equiv 6 \pmod{13}$. So, $N \equiv 6 \pmod{13}$.

A: $1001$ is divisible by $13$,
$111,111$ is divisible by $1001.$
if you have a number that is all 1's and the number of 1's is divisibe by 6, then the number will be divisible by 111111, 1001 and 13.

A: Using Doug M's hint and the fact that $1000 \pmod{6} \equiv 4$ we know that
$\tag 1 N \equiv 1111 \pmod{13}$
subtracting $1001$ we can write
$\tag 2 N \equiv 110 \pmod{13}$
ANS: $N \equiv 6 \pmod{13}$


text:
Q: Regex para encontrar um traço não seguido por letras Tenho a seguinte situação:

const a = "          s - al";

console.log(a.match(/^-|(?<![a-zA-Z0-9])-/))

Essa regex atual retorna um match no "-", mas não deveria, pois existe uma letra precedida que é o "s".
Como faço pra pegar somente o primeiro traço que não é precedido por letras, como é este caso:
     - este traco
- este tambem
          - - somente o primeiro traco deve ser pego

A: A sua regex pega o hífen que está no início (^-), ou um hífen que não tem uma letra imediatamente antes. Como no seu código a string tem um espaço imediatamente antes do hífen, a regex encontra um match.
Neste caso você deveria considerar que podem ter espaços entre a letra e o hífen, por exemplo. Mas usando lookbehind você fica um pouco limitado porque as engines de regex costumam ser restritivas quanto a esta construção (muitas não deixam colocar quantificadores, que seria uma opção para os espaços opcionais, por exemplo), além de não funcionar bem em todos os browsers - veja mais sobre isso aqui e aqui.
De qualquer forma, ficaria:
console.log(a.match(/^-|(?<![a-zA-Z0-9]\s*)-/));

Ou seja, depois das letras/números, tenho \s* (zero ou mais espaços). Lembrando que lookbehind não é suportado em todos os browsers, e incluir quantificadores em um lookbehind também não é permitido em muitas engines.
Detalhe: se a string for "s - - al", ela dará match no segundo hífen (que não ficou claro se deve ser encontrado ou não).

Sem usar lookbehind
Se a ideia for pegar o primeiro hífen que não tem nenhuma letra ou número em qualquer posição anterior, aí acho mais fácil fazer assim:

const a = "         s - al";
let pos = a.indexOf('-');
if (pos < 0 || /[a-zA-Z0-9]/.test(a.slice(0, pos))) {
    console.log('não encontrou');
} else {
    console.log(`encontrou na posição ${pos}`);
}

Ou seja, primeiro eu procuro pelo hífen. Se encontrar, eu vejo se em qualquer posição anterior tem uma letra ou número (usando uma regex mais simples, sem lookbehind).
Pode parecer que ficou pior só porque "tem mais linhas", mas acho que fazer uma regex para isso, embora até acredito que seja possível, ficaria complicado demais para valer a pena. Código menor não é necessariamente melhor.
Eu também retorno a posição do hífen porque me parece mais útil do que retornar o próprio hífen. Afinal, eu já sei que estou buscando por um hífen, então retornar este caractere é redundante - e no caso de ter mais de um hífen na string, como eu saberei qual deles deu match? Por isso acho que retornar a posição faz mais sentido nesse caso.
Se a ideia for ver se antes do hífen tem uma letra seguida de zero ou mais espaços, bastaria mudar a regex acima para /[a-zA-Z0-9]\s*$/(não ficou claro o critério, mas parece que pode ter apenas espaços entre a letra e o hífen).

E tem mais uma coisa que não ficou clara. Se a string for por exemplo "x -   - al", o primeiro hífen está precedido por letra, mas e o segundo? Podemos considerar que sim (afinal, tem um "x" em uma posição anterior), ou não, pois só contamos depois do primeiro hífen?
Se for a primeira opção, o código acima já resolve. Mas se for a segunda opção, você teria que ir procurando por hífens até encontrar algum que satisfaça a condição (ou até não ter mais nenhum):

const a = " x -  - al";
let pos = 0;
let posicaoEncontrada = -1;
while (pos < a.length) {
    let anterior = pos;
    // procura a partir da posição do último hífen encontrado
    pos = a.indexOf('-', pos);
    if (pos < 0)
        break;
    if (/[a-zA-Z0-9]/.test(a.slice(anterior, pos))) {
        pos++;
    } else {
        posicaoEncontrada = pos;
        break;
    }
}

// encontra o segundo hífen (posição 6)
if (posicaoEncontrada >= 0) {
    console.log(`encontrou na posição ${pos}`);
} else {
    console.log('não encontrou');
}


text:
Q: Wait till images are loaded inside angularjs factory I've created a small feature alowing users to search for movie titles. This does a JSON requests from tmdb.org which returns things like titles, dates and url's posters.
The controller:
    angular.module('movieSeat')
        .factory('moviesearchFactory', ['$http', '$q', '$rootScope', function ($http, $q, $rootScope) {

            var factory = {};

            function httpPromise(url) {
                var deferred = $q.defer();
                $http({
                    method: 'JSONP',
                    url: url
                })
                    .success(function (data) {
                        deferred.resolve(data.results);
                    })
                    .error(function () {
                        deferred.reject();
                    });
                return deferred.promise;
            }

            factory.getMovies = function (searchquery) {
                return httpPromise('http://api.themoviedb.org/3/' + 'search/movie?api_key=a8f7039633f2065942cd8a28d7cadad4' + '&query=' + encodeURIComponent(searchquery) + '&callback=JSON_CALLBACK')
            }

            return factory;

        }]);

The factory:
    angular.module('movieSeat')
        .controller('moviesearchCtrl', ['$scope', 'moviesearchFactory', function ($scope, moviesearchFactory) {

            $scope.createList = function (searchquery) {
                $scope.loading = true;
                moviesearchFactory.getMovies(searchquery)
                    .then(function (response) {
                        $scope.movies = response;
                    })
                    .finally(function () {
                        $scope.loading = false;
                    });

            }

        }]);

The template:

Loading

        <input ng-model="searchquery" ng-change="createList(searchquery)" ng-model-options="{ debounce: 500 }" />
        {{ search }}

                {{ movie.title }}
                {{ movie.release_date }}

The problem with this feature is that the spinner class only waits for the requested data. But just loading some JSON doesn't take long, it's downloading the images from the api in the browser that takes a while.
This causes 2 things. First of the spinner is removed before the images are rendered in the browser and because the images are all loaded async it causes a waterfall effect.
The easiest way to resolve this problem would to delay the .then call in the controller until the images are downloaded for the user and then go into the .finally call.
But I can't find a way to create something like that. Any tips?

A: Try this and let me know:
The idea is to use a directive to emit a render finished event:
dashboard.directive('onFinishRender', function ($timeout) {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
            if (scope.$last === true) {
                $timeout(function () {
                    scope.$emit(attr.onFinishRender);
                });
            }
        }
    }
});

In the controller keep the event listener that wait for the image load promises:
    $scope.$on('dataLoaded', function(ngRepeatFinishedEvent) {
        // your code to check whether images has loaded
        var promises = [];
        var imageList = $('#my_tenants img');
        for(var i = 0; i < imageList.length; i++) {
            promises.push(imageList[i].on('load', function() {}););
        }
        $q.all(promises).then(function(){
            // all images finished loading now
            $scope.loading = false;
        });
    });

and in the html side:

        // more divs


text:
Q: Header includes in implementation file is causing errors in Qt moc Imagine I have a class foo with a header and an implementation file.
I also have those for bar. However, in bar I have an instance of foo. But I don't include foo in the header of bar but in the implementation file.
Qt's moc does not include the foo header, causing errors for not knowing the existence of the class foo.
Is there a way of keeping the include in the implementation file and having the moc add those includes as well?
foo.cpp
#include "foo.h"

foo.h
#pragma once

class foo {};

bar.cpp
#include "foo.h"
#include "bar.h"

bar.h
#pragma once

#include <QtCore>

class bar : public QObject
{
    Q_OBJECT

public:
    foo instanceOfFoo;
};

The moc will not include foo.h.
Which in turn generates errors telling me moc_bar.cpp is unaware of a class named foo.

A: The short answer is: No, you can't.
The reason is that bar has a foo member. In order to generate the definition of bar, the compiler must know what a foo is. Otherwise the memory layout of bar would be impossible to determine.
So you have to #include "foo.h" in bar.h.
You could circumvent it by using a pointer to foo and a forward declaration but it sounds wrong to me.
Also:

"The principle of keeping includes out of header files [...]"

There is no issue to have #include directives in header files. You only need to include what's necessary for your class to be completely defined (e.g. You need a std::string member ? Just #include <string>).


text:
Q: What is the correct way of parsing this json? Using ArduinoJson I can't get the correct way to parse this JSON using ArduinoJson library
Here is the resulting json I need to parse.
{
"Error": false,
"Message": "Success",
"Sensor": [
    {
        "id": 10,
        "mac_address": "aabbccddeeff",
        "status": "ON"
    }
  ]
}

May target value to get is the value of "status"
I tried to get some value and println it, but I got nothing?
Codes I tried so far.
  StaticJsonBuffer<100> jsonBuffer;
  HTTPClient http;
  http.begin(path);
  int httpCode = http.GET();
  String payload = http.getString();
  JsonObject& root = jsonBuffer.parseObject(payload);
  String state = root["Sensor"];
  Serial.println(payload);
  Serial.println(state);    //Print request response payload

A: Upon searching, I found that the author create an assistant to convert your defined json string.
You can find it here
https://bblanchon.github.io/ArduinoJson/assistant/index.html

A: Sensor is a list with a single object that has your desired property status.
String state = root["Sensor"][0]["status"];


text:
Q: How can I solve the Ramanujan problem by using Wolfram language? The problem like this:
find all integers n, 1 ≤ n ≤ 10, 000 such that n is the sum of two cubes of positive integers in two different ways.
I want to solve the problem as a procedure in mathematica.

A: Clear["Global`*"]

eqns = {n == a^3 + b^3, n == c^3 + d^3, 1 <= n <= 10000, a >= b > 0,
   a > c >= d > 0};

sol = Solve[eqns, {n, a, b, c, d}, Integers]

(* {{n -> 1729, a -> 12, b -> 1, c -> 10, d -> 9}, {n -> 4104, a -> 16,
  b -> 2, c -> 15, d -> 9}} *)

And @@ Flatten[eqns /. sol]

(* True *)

A: You could use IntegerPartitions to find integers representable as the sum of two cubes.
Table[
   {n, IntegerPartitions[n, {2}, Range[n]^3]},
   {n, 1, 100}]

Also, PowersRepresentations is designed for problems like this; however, it uses non-negative integers, allowing 0 as one of the cubes.
Table[
   {n, PowersRepresentations[n, 2, 3]},
   {n, 1, 100}]

For "Taxicab Numbers", make a table of representations and select integers with more than one solution. Check that no solution uses 0.
Select[
   Table[
      {n, PowersRepresentations[n, 2, 3]},
      {n, 1, 10000}],
   Length[#[[2]]] >= 2 &]

{{1729, {{1, 12}, {9, 10}}}, {4104, {{2, 16}, {9, 15}}}}


text:
Q: Unexpected venneuler output I'm trying to understand how venneuler works and it outputs a venn diagram I wouldn't expect.  I like to work with simple examples when I'm trying to understand something.  I'm supplying the matrix below which I believe is :

a logical or numeric matrix whose columns represent sets and
  co-occurrence is
      defined by non-zero (rep. TRUE) values in rows (weight for a row being 1 for
      logical matrices or the row sum for numeric matrices). -venneular manual-

I would expect if two things both have 1's or 0's in the same row they'd have overlap in their venn.  So in this matrix w and z have no 1's or 0's in common.  I'd expect their venn's not to overlap but they do (see figure 1 below).  Why?  If I'm supplying wrong information or it needs to be reformatted please explain.  If it's in the calculations of venneular please explain that.
     w x y z
[1,] 1 0 1 0
[2,] 0 0 1 1
[3,] 0 0 1 1
[4,] 1 1 0 0

The code for the above:
library(venneuler)
w <- c(1,0,0,1)
x <- c(0, 0, 0, 1)
y <- c(1, 1, 1,0)
z <- c(0, 1, 1,0)
a <- cbind(w, x, y, z)
v <- venneuler(a)
plot(v)

A: Try these - same as the example of ?venneuler:
library(venneuler)
plot(venneuler(c(A=1, B=1, C=1, "A&B"=0.5, "A&C"=0.5, "B&C"=0.5 ,"A&B&C"=0.5)))

plot(venneuler(c(A=1, B=1, C=1, "A&B"=0.5, "A&C"=0.5, "B&C"=0.5 ,"A&B&C"=0)))

Any significant difference? No. Why? because the second case is impossible! Imagine how any 2 of 3 circles of area = 1 have intersection of area = 0.5, but there is nothing in the intersection of all 3?
Now if you like to have a good representation of your desired matrix, I suggest using VennDiagram package:
library(VennDiagram)
w <- c(1, 0, 0, 1)
x <- c(0, 0, 0, 1)
y <- c(1, 1, 1, 0)
z <- c(0, 1, 1, 0)

venn.diagram(
    x = list(w = which(w==1),x = which(x==1),y = which(y==1),z = which(z==1)),
    height=2000, width=2000, resolution=300, col = "transparent",margin = 0.2,
    fill = c("cornflowerblue", "green", "yellow", "darkorchid1"), alpha = 0.50,
    cex = 1.5,filename="~/Desktop/a.tiff",fontfamily = "serif",fontface = "bold",
    cat.col = c("darkblue", "darkgreen", "orange", "darkorchid4"),cat.cex = 1.5,
    cat.pos = 0,cat.dist = 0.07,cat.fontfamily = "serif",rotation.degree = 270,
    label.col = "white");


text:
Q: Changing text color and style in material-ui version 0.15.4 I am fairly new to CSS and front end web development and having trouble in setting style of the button on my page. I want to change the text color of it and maybe change the primary color of my theme as well (currently it looks cyan, i want to make it blue). I know material-ui has moved to inline styles and i tried passing style as a variable to the "style" field in the button, but wasn't able to make it work. Any help would be appreciated.
var React = require('react'),
mui = require('material-ui'),
LoginDialog = require('./login-dialog.jsx'),
RaisedButton = mui.RaisedButton,
MuiThemeProvider = require('material-ui/styles/MuiThemeProvider'),
darkBaseTheme = require('material-ui/styles/baseThemes/darkBaseTheme');

var Index = React.createClass({
  getChildContext: function() {
    return {
      muiTheme: getMuiTheme(darkBaseTheme),
    };
  },
  childContextTypes: {
    muiTheme: React.PropTypes.object
  },
  render: function() {
    return (
      <div className="mui-app-canvas home-page-background">
        <RaisedButton
          className="login-button"
          label="Login"
          onTouchTap={ this._handleLoginDialog }
          linkButton={ false } />
        <LoginDialog
          ref="loginDialog"
          loginUrl={ this.props.loginUrl } />
      </div>
    )
  },

  _handleLoginDialog: function() {
    this.refs.loginDialog.show();
  }
});

module.exports = Index;

A: Best way to edit the style in material ui is to edit or write your own theme.
Here you can see already implemented themes:
https://github.com/callemall/material-ui/tree/master/src/styles/baseThemes
And here all editable properties:
https://github.com/callemall/material-ui/blob/master/src/styles/getMuiTheme.js
And here how to implement it:
http://www.material-ui.com/#/customization/themes


text:
Q: Built-in base class for controllers in ASP.NET MVC: Controller or ControllerBase? What is the built-in base class for controllers in ASP.NET MVC:
System.Web.Mvc.Controller or System.Web.Mvc.ControllerBase?
It is unclear to me after searching on Google:

*

*On www.ASP.NET: " A controller is a class that derives from the base System.Web.Mvc.Controller class."

*On codeproject: "The abstract ControllerBase class represents the base class for all MVC controllers."

*On MSDN: "The base class for all controllers is the ControllerBase class, which provides general MVC handling. The Controller class inherits from ControllerBase and is the default implement of a controller."

*In the book "Pro ASP.NET MVC 5 Framework" from Adam Freeman: "In ASP.NET MVC, controllers are just C# classes (usually inheriting from System.Web.Mvc.Controller, the framework's built-in controller base class)."
Who is right? What does "Built-in base class" mean exactly in this context?
Is "Controller" the built-in base class and "ControllerBase" the ???? (what would be the right wording?) base class?

A: Controller is the class you should derive from to implement your own MVC controllers. ControllerBase is derived by Controller and, like any abstract class, it doesn't provide implementations to some members that Controller does.
In addition, Controller has many more members than ControllerBase (for example, it lacks View() and many others you may be get used to call in your regular controllers!).
Actually, ControllerBase is an infrastructure class, and it's not suitable to be used directly to implement your own controllers.

A: By Defination
ControllerBase : A base class for an MVC controller without view support.
Controller : A base class for an MVC controller with view support.
Thus if we are not creating views i.e. creating Web API use ControllerBase else use Controller.

A: ASP MVC requires that all controllers implement IController interface. A controller doesn't need to derive from Controller or ControllerBase class.
You can find an example of a custom controller implementing the IController interface in Adam Freeman's book.
ControllerBase class implements IController interface and adds several methods and properties (e.g. ViewBag). It defines an abstract ExecuteCore method that is responsible for locating the action method and executing it. If you choose to derive your controller from ControllerBase, you will have to provide implementation for this method.
Controller class derives from ControllerBase. It provides an implementation for ExecuteCore method and adds several useful methods you can use in your controllers (for example View(), Redirect() etc.).
To summarize - both ControllerBase and Controller are built-in base classes for controllers. Built-in, because they are part of the ASP.NET MVC framework. Base classes for controllers, because if you derive from them, you will create a controller.

A: Controller class is a wrapper over ControllerBase that provides built in functionality for a regular use of the framework especially methods for dealing with HTTP requests.
You can look at the ControllerBase as a class the specifies the minimum requirements that a controller needs to do. It implements the IController interface which has the Execute action. This is the basic functionality that a controller should do from the framework point of view: executing incoming requests.
For normal users the choice is definitely Controller which inherits from ControllerBase and has all the build in support for a regular use.

A: I find myself having trouble posting values a Controller inheriting the ControllerBase class from fetch or axios and having to use APIController instead for the versatile and intuitive functionality that makes me not want to rip my hair out.


text:
Q: Family of curves $x^n+y^n=a^n$ as $n$ goes from $1$ to $\infty$ (integers) and from $1$ down to $0$ Take values of $n$ from 1 to $\infty$ in steps of $1$. Prove that in the limit it will be a square of side $a$.
Take value of $n$ from $1$ to $0$ (fractions). In the limit as $n$ approaches $0$, prove that its a function which has value $a$ at $x=0$ and $0$ elsewhere.
Any idea what happens if $n$ is negative?

A: $x^n+y^n=a^n\iff\left(\frac xa\right)^n+\left(\frac ya\right)^n=1\Longrightarrow$ If n is even, then the function $y(x)=\pm\sqrt[n]{a^n-x^n}$ can only exist for $x\in(-a,+a)$. But if n is odd, such restrictions no longer apply. Nevertheless, if we focus solely on the interval $x\in(0,a)$, then all observations that apply to even powers go for odd ones as well (i.e., the form will ultimately degenerate into a rectangle with its height twice the size of its width as $n\to\infty$).
$n\to\infty\Longrightarrow\left(\frac xa\right)^n\to0\Longrightarrow\left(\frac ya\right)^n\to1\Longrightarrow y\to a\Longrightarrow$ For $x\in(-a,a)$ we have two straight line segments characterized by $y(x)=\pm a$.
$n\to0\Longrightarrow\left(\frac xa\right)^n\to1\Longrightarrow\left(\frac ya\right)^n\to0\Longrightarrow$ y can only be $0$, since otherwise any other number risen to the power $0$ is $1$, whereas $0^0$ is indeterminate, hence $\forall x\in(0,\pm a),\quad y(x)=0$. In $x=0$, however, we have $\underset{n\to0}\lim0^n=0$, hence $y=a$.
As an aside, for $n=1$ we have a square with its four corners in $\pm a$ and $\pm ai$. For $n\to\infty$ we have another square, this time with its four corners in $a\pm ai$ and $-a\pm ai$. For $n=2$ we have the circle centered in the origin with the radius $a$.


text:
Q: CL GL Interop: CL context creation parameters I've been trying to create an OpenCL context bound to an OpenGL context. I've failed to find the appropriate values for the properties parameter needed for the KHRGLSharing.clGetGLContextInfoKHR method to query the devices available. The OpenGL context is created using GLFW and the window I want to work with is the current context (set with glfwMakeContextCurrent)
The following code snipped shows what I've come up with so far:
public static List<Long> queryDevicesForPlatform(long platform) {
        stack.push(); // MemoryStack defined elsewhere
        //Create properties
        //Problematic piece of code
        long[] properties =  switch (Platform.get()) {
            //These parameters let the JVM crash when clGetGLContextInfoKHR is called
            case LINUX -> new long[]{
                    CL_CONTEXT_PLATFORM, platform,
                    CL_GL_CONTEXT_KHR, GLX14.glXGetCurrentContext(),
                    CL_GLX_DISPLAY_KHR, GLX14.glXGetCurrentDisplay(),
                    0
            };
            //Not yet tested
            case MACOSX -> new long[]{
                    CL_CONTEXT_PLATFORM, platform,
                    CL_CGL_SHAREGROUP_KHR, CGL.CGLGetShareGroup(CGL.CGLGetCurrentContext()),
                    0
            };
            //This one works
            case WINDOWS -> new long[]{
                    CL_CONTEXT_PLATFORM, platform,
                    CL_GL_CONTEXT_KHR, glfwGetCurrentContext(),
                    CL_WGL_HDC_KHR, wglGetCurrentDC(),
                    0
            };
        };

        //Copy properties to a buffer
        ByteBuffer byteProp = stack.malloc(properties.length * Long.BYTES);
        byteProp.asLongBuffer().put(properties);
        ByteBuffer bytes = stack.malloc(Long.BYTES);

        //JVM crashes here
        int error = KHRGLSharing.clGetGLContextInfoKHR(PointerBuffer.create(byteProp),
                CL_DEVICES_FOR_GL_CONTEXT_KHR, (ByteBuffer) null, PointerBuffer.create(bytes));
        assert error == CL22.CL_SUCCESS: error;

        ByteBuffer value = stack.malloc((int) bytes.asLongBuffer().get(0));
        error = KHRGLSharing.clGetGLContextInfoKHR(PointerBuffer.create(byteProp), CL_DEVICES_FOR_GL_CONTEXT_KHR, value, null);
        assert error == CL22.CL_SUCCESS: error;
        LongBuffer devices = value.asLongBuffer();

        ArrayList<Long> ret = new ArrayList<>();
        while(devices.hasRemaining()) {
            ret.add(devices.get());
        }

        stack.pop();
        return ret;
    }

Linux: I do not know what values to pass for CL_CONTEXT_PLATFORM, CL_GL_CONTEXT_KHR and CL_GLX_DISPLAY_KHR. The current crash the JVM with a SIGSEGV.
Windows: The code works, but I am not sure whether this is the right way to do it.
Apple: I have no machine to test this on, but I would appreciate it if I'd know the right parameters there too.

A: Intel's Linux drivers do not support CL-GL interop (it lacks the cl_khr_gl_sharing extension).
The code snippet should work on Linux if the driver supports CL-GL interop


text:
Q: Ansible syntax issue running shell command and docker_container module What I have is valid YAML but for some reason it's not valid for Ansible and the documentation on the Ansible site has some great examples of running the modules but there isn't any documentation on how the modules work together or if they can. I'm assuming I can run a shell module and a docker_container module in the same task but it appears to me as if Ansible is disagreeing with me. Here's what I have.
---
- name: Setup Rancher Container
   shell: sudo su_root
   docker_container:
     name: rancherserver
     image: rancher/server
     state: started
     restart_policy: always
     published_ports: 8080:8080

...

ERROR! conflicting action statements

The error appears to have been in '/opt/ansible_scripts/ansible/roles/dockermonitoring
/tasks/main.yml': line 2, column 3, but maybe elsewhere in the file depending on the exact
syntax problem.

The offending line appears to be:

---
- name: Setup Rancher Container
^ here

Because I'm runing this on RHEL 7 I need to be able to run the sudo su_root script to become root before ansible can communicate with the Docker API as docker runs as root.
So if I can't run this script and then run the docker_container I think that's a big problem with ansible.

A:
I'm assuming I can run a shell module and a docker_container module in the same task

Wrong. One task – one module.
There's become parameter to get privileged access, like:
- name: Setup Rancher Container
  become: yes
  docker_container:
    name: rancherserver
    ...


text:
Q: How to check for user role in AWS API gateway authorizer? I am trying to do authentication and authorization with AWS Cognito and AWS API Gateway.
I managed to give the user a JWT token when logged in and when performing a certain get request on my gateway it checks for the Authorization header and verifies it with Cognito (user pools).
The problem that I am facing is that it does not check for any user role. Certain users are in my Cognito admin group, but I can't specify that only users from the Admin group can make such requests. Currently, if any user that has a valid JWT token does that GET request on the API Gateway it executes it.
I thought I could maybe use a custom lambda authorizer in order to check the role. This would not be very secure since you (a potential hacker) could still temper with the JWT token to change this
  "cognito:groups": [
    "User"
  ],
  "iss": "",
  "version": 2,
  "client_id": "6uad7uthfhv3a7p9aihdbjl3tt",
  "token_use": "access",
  "scope": "aws.cognito.signin.user.admin phone openid profile email",
  "auth_time": 1668780261,
  "exp": 1668783861,
  "iat": 1668780262,
  "jti": "",
  "username": "test"
}

To this:
  "cognito:groups": [
    "Admins"
  ],
  "iss": "",
  "version": 2,
  "client_id": "6uad7uthfhv3a7p9aihdbjl3tt",
  "token_use": "access",
  "scope": "aws.cognito.signin.user.admin phone openid profile email",
  "auth_time": 1668780261,
  "exp": 1668783861,
  "iat": 1668780262,
  "jti": "",
  "username": "test"
}

And encode the token again to make API calls that he should not be able to do.
Another thought I had was to check from the Lambda authorizer directly with Cognito if the user has the correct roles, but I do not know if that is even possible.
Is there a better, more logical way to check with Cognito if the user is inside the user pool AND if it has the correct role?

A: First thing is, we should have a properly implemented JWT validation mechanism in place. With that, tampered tokens can be easily identified.
Please read this article for more details. It says:

JSON Web Tokens are a good way of securely transmitting information
between parties. Because JWTs can be signed—for example, using
public/private key pairs—you can be sure the senders are who they say
they are. Additionally, as the signature is calculated using the
header and the payload, you can also verify that the content hasn't
been tampered with.

So in the Lambda authorizer we can do that JWT validation. Then based on the request path and the assigned roles, it should be able to decide whether to invoke the API or not.


text:
Q: Python Passing Object to Object Good Day,
So I have an object called PointArray and another object called Graph. I am passing the object point to Graph as such
class Graph:
    def __init__(self):
        self.pointArray = PointArray()
    description = "This is a class"
    author      = "Raaj"

    def setPointArray(self,pointArray):
        self.pointArray=pointArray

    def plotFFTGraph(self):
        xArr=[]
        yArr=[]
        for point in self.pointArray.freqArray
            xArr.append(point.X)
            yArr.append(point.Y)

        subplot(2,1,2)
        plot(xArr,yArr)

The problem is, Python doesn't seem to recognize that I can access freqArray!
I get this
for point in self.pointArray.freqArray
                                     ^
SyntaxError: invalid syntax

I have imported everything correctly. What gives this error?

A: You forgot the colon:
for point in self.pointArray.freqArray:
    #                  ---------------^

A: Change it to for point in self.pointArray.freqArray:


text:
Q: boxes won't display inline I tried to put all boxes in same line and i did it but there is one problem,
look at the last box, its not in same line.
Can be done by adding one more text line to the last section but i want just 2 lines.
How to fix that?

body {
background: black;
}
.box-container {
  margin-top: 0px;
  text-align: center;
  background: white;
  white-space: nowrap;
}
.box {
  display: inline-block;
  background: green;
  width: 250px;
  height: 300px;
  margin: 35px;
  color: white;
  white-space: normal;
}
.fa.rounded.big {
    font-size: 3.5em;
}
.fa.rounded {
    border-radius: 100%;
    border: 1px solid white;
    height: 150px;
    line-height: 150px;
    width: 150px;
}
.box-container section .fa.rounded {
  margin-bottom: 30px;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">

This page is created with HTML, CSS and jQuery and beacuse of that, it should be fast.

Beacuse of bootstrap, UIkit, Animate.css, WOW.js this page is even more awesome!

There is only 41 lines of code but there will be more things soon!

There are 3 boxes,
make sure you see them all, look at the full page.

A: Add a
vertical-align: top;

CSS attribute to the last box. This should fix it.


text:
Q: How to create shapetext using Java I am trying to create shape texts directly using codes as the number of shapetext i need may vary.
I tried using the code below, and I created the shapes in a collection (with type shapetext). When I use "traceln(text.getX());" it prints 2500 but I do not see the text anywhere on the screen. May I understand what I have done wrongly and how can I make the shapetext be shown? Do I have to add shapetexts into my network/level and initialize it?
Thank you for your help!
    ShapeText text = new ShapeText(SHAPE_DRAW_2D3D, true, (double) 2500, (double) 3000, (double) 0, 0, black, "testing", new Font("SansSerif", Font.BOLD, 100), ALIGNMENT_CENTER );

A: You have successfully created the text, but you need to add it to the presentation to be shown
Simply add
presentation.add(text);

An alternative option if you have an undetermined amount of texts is to rather create a single text object and then replicate it as many times as you want to show it. Once you add a replication to a presentation object a local variable called index is now available for you to use in many of the fields.
Use this in the dynamic text field to get the values you want to display (like in the example below I stored the texts in a collection)
And you also use this index to change the position of the text (See what I have done in the Y coordinates)


text:
Q: Printing 2 pages per sheet results in 4 pages Every now and then, I use the "Layout" option in macOS's print dialog to fit two pages on a sheet, for instance when printing presentation slides. For some reason, this sometimes leads to 4 pages being printed per sheet, rendering the slides hardly readable. Happened twice to me today.

Does anyone know why this is happening and how to prevent it?
Update
In response to Tetsujin's comment:

*

*I'm running the latest macOS Sierra 10.12.4 (16E195) but I've been experiencing this issue with previous versions of macOS (formerly OS X) as well so I don't think it matters.

*I print from Preview and Safari and the problem occurs in both cases.

*I usually print two A5s onto one A4. I'm fairly certain, there's no spilling over.

*The print dialog shows the correct number of pages.

*"Is this happening at the app or at the printer?" - Not sure what is meant.

A: I have the same problem. The only way I manage to print 2 pages is printing it as a two-page layout PDF (which generates the expected two-pages per sheet layout), and then printing this as a one page per sheet. If I print directly, it will print 4 pages per sheet when I specify 2. This happens for the last 3 Mac OS versions, independent of the printer or program (I just checked with a PDF from Safari).
This happens from Sierra up to Movaje (as of now).


text:
Q: MS Word VBA macro to search and replace (Regex) Suppose a word file contains
ab{cdefg{hij{k

And I want { to be moved one place to the right like
abc{defgh{ijk{

I need to make an array with all characters then run a loop with Regex search and replace
search:
({)(array[index])

replace:
$2$1

Plain Regex without loop won't work because I'm dealing with Indic text which have complex characters. I've done this on JavaScript and ExtendScript in inDesign, but I've no clue about VB. Can anyone please help?

A: This can be done using a Word wildcard search-and-replace:
With ActiveDocument.Range.Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .ClearAllFuzzyOptions
    .Text = "(\{)(?)"           ' find opening brace followed by a single character
    .Replacement.Text = "\2\1"  ' swap positions
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchByte = False
    .MatchAllWordForms = False
    .MatchSoundsLike = False
    .MatchFuzzy = False
    .MatchWildcards = True
End With
ActiveDocument.Range.Find.Execute Replace:=wdReplaceAll


text:
Q: Current RecordSet Does not support updating I'm running into the following error, while trying to add data to the database (directly from Excel). I've noticed it's not working for users who have MS Office v1908 - but for example working for these who have v2002

Error number: 3251. Current Recordset Does not support updating.

This may be a limitation of the provide or of the selected locktype. Any idea what might have been causing the issue?
Sub SendData()
  Dim dbpath        As String
  Dim dbtable       As String
  Dim result        As Long
  Dim iCNT          As Long
  Dim CNT           As ADODB.Connection
  Dim dbConnectStr  As String
  Dim rsCNT         As ADODB.Recordset

'------------------------------------------------------------------------------------------------ [DEFINE ERROR SITUATION]
Const sProcName As String = "[SendData]"
On Error GoTo ErrorHandler

'------------------------------------------------------------------------------------------------ [GET ALL VARIABLES]
Call GetAllData
On Error Resume Next
Application.StatusBar = "Running... || " & sProcName
On Error GoTo ErrorHandler
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Application.Cursor = xlWait

  dbpath = "'\\Database location.accdb'"
  dbtable = "[DailyReporting]"
  'AccPassWd = "test"
  dbConnectStr = "Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=" & dbpath '& ";Jet OLEDB:Database Password=" & AccPassWd
  '------------------------------------------------------------------------------------------------ [ CONNECTION ]
  Set CNT = New ADODB.Connection
  Set rsCNT = New ADODB.Recordset
  CNT.Open (dbConnectStr)
  rsCNT.Open dbtable, CNT, adOpenKeyset, adLockOptimistic, adCmdTable
  '------------------------------------------------------------------------------------------------ [ WRITE ]
  'rsCNT.MoveLast
  For iCNT = StartRangeRow To MaxLastRow
    rsCNT.AddNew
    rsCNT.Fields.Item(1).Value = Sheet1.Cells(iCNT, 3)                                      'Company / Location name - Location Code
    rsCNT.Fields.Item(2).Value = Sheet1.Cells(iCNT, 4)                                      'BANK - Currency - Bank account number
    rsCNT.Fields.Item(3).Value = Format(Sheet1.Cells(iCNT, 5), "yyyy-mm-dd;@")              'Statement Date
    rsCNT.Fields.Item(4).Value = Sheet1.Cells(iCNT, 6)                                      'Cash Application Status
    rsCNT.Fields.Item(5).Value = Sheet1.Cells(iCNT, 7)                                      'Bank Reconciliation Status
    rsCNT.Fields.Item(6).Value = Sheet1.Cells(iCNT, 8)                                      'Cash In Items (Total Deposit Items)
    rsCNT.Fields.Item(7).Value = Sheet1.Cells(iCNT, 9)                                      'Cash In Amount (Total Deposit Amount)
    rsCNT.Fields.Item(8).Value = Sheet1.Range("D5")                                         'Team
    rsCNT.Fields.Item(9).Value = Sheet1.Range("D3")                                         'User ID
    rsCNT.Fields.Item(10).Value = Sheet1.Range("D4")                                        'User Name
    rsCNT.Fields.Item(11).Value = Format(Sheet1.Range("D6"), "yyyy-mm-dd hh:mm:ss;@")       'Reporting date (from Excel)
    rsCNT.Fields.Item(12).Value = Format(Now(), "yyyy-mm-dd hh:mm:ss;@")                    'Sending date & time
    'rsCNT.Fields.Item(13).Value = Format(Time, "hh:mm:ss;@")                                'Sending time
    rsCNT.Fields.Item(13).Value = UserNameStart                                             'Sending User ID
    rsCNT.Fields.Item(14).Value = UserFullNameStart                                         'Sending User Name
    rsCNT.Update
  Next iCNT
  rsCNT.Close
  CNT.Close
  '-----------------------------------------------------------------------------------------------  [ MESSAGE BOX ]
  MsgBox "Data has been sent!", vbInformation


text:
Q: Rotation Matrix between two unit direction vectors from different frames I have two fixed frames A and B. I have a mobile point P for which I know the 3D orientation (in terms of unit direction vectors) wrt A and B at each time step.
I need to find the Rotation Matrix from B to A.
I checked other answers (e.g. Expression of rotation matrix from two vectors, Calculate Rotation Matrix to align Vector A to Vector B in 3d?), and I'm able to find a rotation matrix R.
But I don't understand why this matrix R changes when the orientation of point P changes.
Shouldn't it be fixed since A and B are fixed frames, regardless of P orientation?
EDIT:
Example: B is a frame rotated of -$\pi$/4 on the Y (green) axis wrt to A. If I have the following direction vectors:
$v_a = [-1, 0, 0]; v_b = [-0.70, 0, 0.70]$
Using the procedure in Expression of rotation matrix from two vectors I get this rotation matrix:
$R=\begin{bmatrix}0.70&0&-0.7\\0&1&0\\0.70&0&0.70\end{bmatrix} $
But when the rigid body P turns and for example I have the following direction vectors:
$v_a = [-0.866, 0.5, 0]; v_b = [-0.61, 0.5, 0.61]$
I get the following:
$R=\begin{bmatrix}0.83&-0.04&-0.55\\0.22&0.94&0.26\\0.51&0.34&0.79\end{bmatrix} $

A: Thanks to David K and Rollen comments I was able to find a solution:
I only had $v_{Ax}$ and $v_{Bx}$ but I could calculate $v_{Ay}$ and $v_{By}$  using other information about the rigid body (i.e. the positions of two aligned points of the rigid body) I constructed the rotation matrices for the two frames using these two direction vectors and the cross product between them.
$R_A=\begin{bmatrix}v_{Ax}&v_{Ay}&v_{Ax}\times v_{Ay}\end{bmatrix}$;
$R_B=\begin{bmatrix}v_{Bx}&v_{By}&v_{Bx}\times v_{By}\end{bmatrix}$
and then the rotation matrix from A to B is given by:
$R = R_B \cdot R_A^T$
Thank you for your help.


text:
Q: Team Foundation Server - Manage external teams Our company has a small development team in-house but we mostly outsource our customer projects to external consulting firms which we don't manage directly. We only interact with their project manager and maybe a team lead.
I'm implementing TFS 2010 and Scrum for our internal team for Project Management, Version Control and Sharepoint shared documents access.
My problem is how to to manage the external teams.
They won't use our TFS for Version control and I can't forced them to use Scrum and report as such (report on a task level adding remaining hours).
The solution I came with is this:

*

*Use the "MSF for Agile Software Development v5.0"  template in Team Foundation Server.

*Break the project into user stories and then create a task for each.

The tasks have these fields:

*

*Original Estimate
Since we'll track percentage of completion, this will always be 100.

*Remaining
This is the percentage of remaining work.

*Completed
 This is the percentage of competed work.
Their team lead will update the remaining work in percentage for each user story (on the task level).
If progress is reported correctly I can print a "Stories Overview" report periodically and see the percentage complete for each user story,

I'm sure it must be a better way out there and I'll appreciate any help on getting to the right direction.
Thanks

A: We are basically doing the same thing ... I have 10 in-house developers and teams around the world working on their projects. Most of the work we do overlaps between external and external. We are using TFS2010. We break a piece of development into user stories into lots of tasks and eventually bugs. We view the status of the external projects by looking at the breakdown of work on the individual work items.
Part of the development process flow is to get the code into TFS source control; and the control of the logs changes as it comes back into our system.
The external PM's then use the web interface spreadsheet upload  update the data on these logs (Including the time spent / work remaining) so we can see the state of the work. You don't need code upload to set a work item to test / complete.
The process flow we have on the external work is; on a given user story item you can then see the state of development for all those tasks.

*

*List item

*To Spec

*Specified

*Spec Agreed

*Open For Work

*WIP

*Development Complete

*External Test

*Source ADded to TFS

*Delivered to Internal Test

*Internal Test

*Complete


text:
Q: Show Part of Sliding Content with jQuery I have an element that I would like to show a part of by default (say 100px), but then show the rest of it by clicking a link. I found this site that has a solution to it because it does not seem to be possible with jQuery's built-in slideToggle. This solution works (as shown in the code below), but does not work with multiple sliders on the same page. I know I need to somehow switch out '.slider' with the id for the specific slider, but am not sure how to do that. I need to grab the current ID, but using this with the openSlider and closeSlider functions does not work. Can anyone help? I'm sure it is a rather simple issue I just can't seem to figure out.
the HTML

the jQuery
var sliderHeight = "100px";
$('.slider').each(function() {
    var current = $(this);
    current.attr("box_h", current.height());
});

$('.slider').css("height", sliderHeight);
$(".slider_menu").html('Expand');
$(".slider_menu a").click(function() {
    openSlider();
    return false;
});

function openSlider() {
    var open_height = $('.slider').attr("box_h") + "px";
    $('.slider').animate({
        "height": open_height
    }, {
        duration: "slow"
    });
    $(".slider_menu").html('Collapse');
    $(".slider_menu a").click(function() {
        closeSlider();
    });
    return false;
}

function closeSlider() {
    $('.slider').animate({
        "height": sliderHeight
    }, {
        duration: "slow"
    });
    $(".slider_menu").html('Expand');
    $(".slider_menu a").click(function() {
        openSlider();
    });
    return false;
}

A: Script should like this :
var sliderHeight = "100px";
$('.slider').each(function() {
    var current = $(this);
    current.attr("box_h", current.height());
});

$('.slider').css("height", sliderHeight);
$(".slider_menu").html('Expand');
$(".slider_menu a").click(function() {
    openSlider($(this).parent().prev("ul.slider"), $(this).parent());
    return false;
});

function openSlider(obj, slideMenu) {
    var open_height = $(obj).attr("box_h") + "px";
    $(obj).animate({
        "height": open_height
    }, {
        duration: "slow"
    });
    $(slideMenu).html('Collapse');
    $(slideMenu).children("a").click(function() {
        closeSlider(obj, slideMenu);
    });
    return false;
}

function closeSlider(obj, slideMenu) {
    $(obj).animate({
        "height": sliderHeight
    }, {
        duration: "slow"
    });
    $(slideMenu).html('Expand');
    $(slideMenu).children("a").click(function() {
        openSlider(obj, slideMenu);
    });
    return false;
}

Hope this will fix your problem !!


text:
Q: UITableView Stops Scrolling After Returning From A DetailView
I am facing a strange issue. I have a simple iPhone app with a TableViewController with custom TableViewCell that is parsing data using NSXmlParser and displaying it. The image inside the cell is loaded with SDWebImage library. Tapping on a cell will push the detail view controller which uses the link to show the post inside the UIWebView. Simple as that.
PROBLEM: When i tap on the cell and it shows the UIWebView, after that if i come back to the TableViewController, it stops scrolling. It bounces but doesn't go down where it has already loaded more cells.
I don't know where exactly the problem could be otherwise i would have added the code. Let me know if anybody wants some particular piece of code they want to see in order to find the problem. This is how i am pushing to the detail view:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    WebViewController *wvc = [self.storyboard instantiateViewControllerWithIdentifier:@"WebViewController"];
    TheItem *entry = [[channel items] objectAtIndex:[indexPath row]];
    wvc.urlString = entry.link;
    [self.navigationController pushViewController:wvc animated:YES];
}

UPDATE: No matter even i select the last cell in the table view, when i come back from the detail view, the position of the scroll is at the top and stuck there.


text:
Q: AttributeError: 'str' object has no attribute 'dispersion_plot' NLTK I am trying to create a dispersion_plot using NLTK. As far as I can tell, I am following the directions. When I run their example calling the example text that comes with NLTK it works. When I call my own text file, it has the above error.
mine:
>>> text11 = "Text_test.txt"
>>> text11.dispersion_plot(["semiosis", "dialectic", "essentially", "icon", "logo"])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'dispersion_plot'

Their example code:
text4.dispersion_plot(["citizens", "democracy", "freedom", "duties", "America"])

Thankful for any advice/help!

A: Note that you have to make it into an NLTK Text object after tokenizing it. Also, your text11 variable as used in your code is the string "Text_test.txt", not the text inside the file called Text_test.txt.
Assuming that

*

*you have matplotlib and numpy installed, which are necessary for dispersion_plot to work

*your file is at /home/myfile.txt

*your file is simple text like the ones they use
then this should do it
# from Ch. 3
f=open('/home/myfile.txt','rU')    # open the file
raw = f.read()                     # read the text
tokens = nltk.word_tokenize(raw)   # tokenize it
mytext = nltk.Text(tokens)         # turn text into a NLTK Text object

# from Ch. 1
mytext.dispersion_plot(["semiosis", "dialectic", "essentially", "icon", "logo"])


text:
Q: Upload File with Jqgrid and Ajaxfileupload I'm working with a jqgrid and I would like to upload a file (pictures and pdf's). I've seen a lot of examples but nothing... I'd like to do un ajaxfileupload. Here is my code,
 colModel: [
        { name: "id", index:"id", key: true,width: 30,editable: false },

        { name: "name", index:"name", width: 100,editable: true },
        { name: "fileToUpload",
          editoptions: {
              enctype: "multipart/form-data"
            },
            edittype:'file',
            index: 'fileToUpload',
            width: 150,
            align: "left",
            editable: true },
    ],

I've four days trying and looking for informations and tutoriasl!! help me!

A: May be duplicate of :

File upload with jqgrid in PHP

I hope this will works.


text:
Q: Realtime bidirectional communication in Google App Engine I am working on a multi-user system that is already hosted in Google App Engine during development and I need to know a few things about Google Cloud that I don't find in the docs:
Is it possible to implement Realtime bidirectional client server architecture WITHOUT FIREBASE? since this project and scope is too big for firebase in my view, besides, firebase costs would shoot too high in the long run and lock me in when huge data is already involved in spite of insufficient queries. If possible, any hint would be appreciated.
INFO: Server is written in nodejs and Mysql 2nd Generation is the DB used. Main client is Android

A: Outside of Firebase, since the Channel API has been deprecated, your options are really only:

*

*run a full-time server (flexible environment, GCE) with a real-time framework like socket.io

*use a real time service like pubnub or pusher


text:
Q: SED: How to delete from the second match to the end of the file I have the following file
Name            ITEM  Description
fa1(RM01):      1     word1
                2     word2
                3     word3

fa2(RM02):      1     word1
                2     word2
                3     word3

I need to remove from the second match "(RM0", including that line and everything below.
I need to delete this way because there are several files where "fa1 (RM01)" and "fa2 (RM02)" change places.
And I can't delete by number of lines either because the number of items can change.

A: If you have text in blocks separated by a blank line delimiter, you use this simple awk to print the first block:
$ awk -v RS= 'FNR==1' file
Name            ITEM  Description
fa1(RM01):      1     word1
                2     word2
                3     word3

To take your post literally you want to print the first block with RM0 in it. Same method:
$ awk -v RS= '/RM0/ && cnt++<1' file

A: This might work for you (GNU sed):
sed '/RM0/{x;/./Q;x;h}' file

On a match of RM0 set a flag in the hold space. On a subsequent match quit processing.
N.B. The hold space is empty at start of processing and the Q quits without printing the current line.

A:
I need to remove from the second match "(RM0", including that line and everything below

You can do this:
sed ':a; /(RM0/! { n; b a; }; :b; n; /(RM0/ Q; b b' < input

Explanation:

*

*:a - label 'a'

*/(RM0/! { n; b a; } - for a line that does not match the (basic) regular expression (RM0, perform the following group of commands

*

*n - (print the current line and) read the next line

*b a - branch to label 'a'

*:b - label 'b'

*n - (print the current line and) read the next line

*/(RM0/ Q - if the current line matches the (basic) regular expression (RM0 then stop processing input and exit without printing the current line

*b b - branch to label 'b'

That's a bit unusual for a sed script in that it processes the whole input in a single sed cycle.  It reads and output lines until it sees the first instance of the pattern, then it outputs and reads lines until it reaches the second instance of the pattern, at which point it terminates.
The Q is specific to GNU sed.  If you don't want to depend on that then you can use this variation:
sed -n ':a; /(RM0/! { p; n; b a; }; :b; p; n; /(RM0/ q; b b' < input

That's functionally almost the same, but the -n option suppresses auto-printing the current line when the q command is executed.  That also turns off auto-printing by the n command, and that is compensated by adding an explicit p (print) command before each n.

A: If you want to modify the file itself, this is easy with ed:
printf "%s\n" '/(RM0/;//,$ d' w | ed -s file.txt

This first sets the current line to the first one matching the regular expression (RM0, then deletes everything from the next line that matches the same RE to the end of the file, and writes the modified file back to disk.
To print out the first part of the file instead of editing it, if this is just part of a longer pipeline:
printf "%s\n" '/(RM0/;//,$ d' ',p' Q | ed -s file.txt

or
printf "%s\n" "/(RM0/;1,//-2 p" | ed -s input.txt

A: If this was your input:
$ cat file
Name            ITEM  Description
fa1(RM01):      1     word1
                2     word2
                3     word3

fa2(RM02):      1     word1
                2     word2
                3     word3

fa3(RM03):      1     word1
                2     word2
                3     word3

From I need to remove from the second match "(RM0", including that line and everything below. it sounds like you want one or the other of these, but it's not clear which from your question:
$ awk -v RS= -v ORS='\n\n' '!(/\(RM0/ && (++c == 2))' file
Name            ITEM  Description
fa1(RM01):      1     word1
                2     word2
                3     word3

fa3(RM03):      1     word1
                2     word2
                3     word3

$ awk -v RS= -v ORS='\n\n' '!(/\(RM0/ && (++c >= 2))' file
Name            ITEM  Description
fa1(RM01):      1     word1
                2     word2
                3     word3

but it's also possible that all you really need is one or the other of these:
$ awk -v RS= -v ORS='\n\n' 'NR!=2' file
Name            ITEM  Description
fa1(RM01):      1     word1
                2     word2
                3     word3

fa3(RM03):      1     word1
                2     word2
                3     word3

$ awk -v RS= -v ORS='\n\n' 'NR==1' file
Name            ITEM  Description
fa1(RM01):      1     word1
                2     word2
                3     word3

Or something else. Lots of possibilities...


text:
Q: No puedo hacer que en cada repetición de un ciclo while se cambie la suma y por ende el resultado, y así no hacer siempre la misma operación En este código se requiere que en cada repetición se cambie la suma y por ende el resultado, y así no hacer siempre la misma operación.
De momento el código quedó como está pero el problema que es que no se puede hacer que cambie el resultado por cada repetición, es decir: o es la misma suma siempre o se cambia la suma (declarando las variables random de vuelta dentro del while) el resultado que se tiene que poner para pasar es siempre el primero que aparece, repetitivamente siempre el mismo.
let randomone = Math.floor(Math.random() * 100);
let randomtwo = Math.floor(Math.random() * 100);
let captcha = parseInt ( prompt ("Cuanto es" + " " + randomone + " " + "+" + " " + randomtwo));

while ( captcha != (randomone + " " + randomtwo) ){
  alert("respuesta incorrecta")
  captcha = parseInt ( prompt ("Cuanto es" + " " + randomone + " " + "+" + " " + randomtwo));
}

A: Antes que nada te sugiero usar camelCase para declarar tanto las variables como las funciones. Por otro lado, para tener un código más limpio podrías hacer uso de las template literals, lo cual te permite incluir variables dentro del string. Y con respecto a tu problema en particular: estás inicializando las variables fuera del loop, por ende ese método random() se aplica una sola vez. Cuando llamas las variables estás llamando el valor resultante y no la función que lo produjo.
Tené en cuenta además que en la comparación que haces en tu while no estás comparando el captcha con la suma de ambos números, sino con un string (chequealo haciendo un console.log). Cambiando esas cositas y reasignando un valor a las variables dentro del loop, tu código quedaría así:
let randomOne = Math.floor(Math.random() * 100)
let randomTwo = Math.floor(Math.random() * 100)
let captcha = parseInt(prompt(`Cuánto es ${randomOne} + ${randomTwo}`))

while (captcha != randomOne + randomTwo) {
    alert('respuesta incorrecta')
    randomOne = Math.floor(Math.random() * 100)
    randomTwo = Math.floor(Math.random() * 100)
    captcha = parseInt(prompt(`Cuánto es ${randomOne} + ${randomTwo}`))
}

alert('respuesta correcta!')


text:
Q: How to construct an RDD or DataFrame dynamically? I'm doing some pre-processing on a bunch of data. Each line has the following schema
<row Att1="...." Att2="..."  Attn"...." />

However not all the attributes exist in all the rows. That is some rows might have only three attributes while some other have five, etc. Besides, there is no way attribute indicating how many attribute exist within each row.
I would like to form an RDD or DataFrame (prefrable) and run some query on the data. However I can't find a good way of splitting each row. For example, splitting by space not work. I only need a few attributes in my processing. I tried to use pattern matching to extract 4 attributes that exist in all the row as follows but it fails.
val pattern = "Att1=(.*) Att3=(.*) Att10=(.*) Att11=(.*)".r
val rdd1 = sc.textFile("file.xml")

val rdd2 = rdd1.map {line => line match {
    case pattern(att1,att2,att3,att4) => Post(att1,att2,att3,att4)
  }
}

case class Post(Att1: String, Att3: String, Att10: String, Att11: String)

p.s. I'm using scala.

A: This is less of a spark problem than it is a scala problem. Is the data stored across multiple files?
I would recommend parallelizing by file and then parsing row by row.
For the parsing I would:

*

*Create a case class of what you want the rows to look like (This will allow the schema to be inferred using reflection when creating the DF)

*Create a list of name/regex tuples for the parsing like: ("Attribute", regex)

*Map over the list of regex and convert to a map: (Attribute -> Option[Value])

*Create the case class objects

*This should lead to a data structure of List[CaseClass] or RDD[CaseClass] which can be converted to a dataframe. You may need to do additional processing to filter out un-needed rows and to remove the Options.