SQLite error "database is locked" when publishig on linux azure app service (.net core 3.1). But i am not using SQLite

Question: When the application is published on windows it works perfectly. I am not using SQLite, I´m using SqlServer.
Error log from azure:
<code>2020-11-27T17:36:08.879028391Z Documentation: http://aka.ms/webapp-linux
2020-11-27T17:36:08.879035191Z Dotnet quickstart: https://aka.ms/dotnet-qs
2020-11-27T17:36:08.879041791Z ASP .NETCore Version: 3.1.8
2020-11-27T17:36:08.879048191Z Note: Any data outside '/home' is not persisted
2020-11-27T17:36:09.077744493Z Running oryx create-script -appPath /home/site/wwwroot -output /opt/startup/startup.sh -defaultAppFilePath /defaulthome/hostingstart/hostingstart.dll     -bindPort 8080 -userStartupCommand ''
2020-11-27T17:36:09.582281718Z Cound not find build manifest file at '/home/site/wwwroot/oryx-manifest.toml'
2020-11-27T17:36:09.583285560Z Could not find operation ID in manifest. Generating an operation id...
2020-11-27T17:36:09.583308261Z Build Operation ID: cf1c55c9-70a7-4bd1-bfa2-e3a2350cf36c
2020-11-27T17:36:10.816104146Z Writing output script to '/opt/startup/startup.sh'
2020-11-27T17:36:11.085709074Z Trying to find the startup DLL name...
2020-11-27T17:36:11.086560810Z Found the startup D name: Digibyte.API.dll
2020-11-27T17:36:11.088017070Z Running the command: dotnet "Digibyte.API.dll"
2020-11-27T17:36:47.812986572Z [41m[30mfail[39m[22m[49m: Microsoft.EntityFrameworkCore.Database.Command[20102]
2020-11-27T17:36:47.813053275Z       Failed executing DbCommand (30,042ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
2020-11-27T17:36:47.813066676Z       PRAGMA journal_mode = 'wal';
2020-11-27T17:36:47.944070916Z Unhandled exception. System.AggregateException: One or more errors occurred. (SQLite Error 5: 'database is locked'.)
**2020-11-27T17:36:47.944105917Z  ---> Microsoft.Data.Sqlite.SqliteException (0x80004005): SQLite Error 5: 'database is locked'.**
2020-11-27T17:36:47.944116518Z    at Microsoft.Data.Sqlite.SqliteException.ThrowExceptionForRC(Int32 rc, sqlite3 db)
2020-11-27T17:36:47.944124918Z    at Microsoft.Data.Sqlite.SqliteDataReader.NextResult()
2020-11-27T17:36:47.944132618Z    at Microsoft.Data.Sqlite.SqliteCommand.ExecuteReader(CommandBehavior behavior)
2020-11-27T17:36:47.944140519Z    at Microsoft.Data.Sqlite.SqliteCommand.ExecuteReader()
2020-11-27T17:36:47.944148119Z    at Microsoft.Data.Sqlite.SqliteCommand.ExecuteNonQuery()
2020-11-27T17:36:47.944155719Z    at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQuery(RelationalCommandParameterObject parameterObject)
2020-11-27T17:36:47.944187521Z    at Microsoft.EntityFrameworkCore.Sqlite.Storage.Internal.SqliteDatabaseCreator.Create()
2020-11-27T17:36:47.944197721Z    at Microsoft.EntityFrameworkCore.Storage.RelationalDatabaseCreator.CreateAsync(CancellationToken cancellationToken)
2020-11-27T17:36:47.944205421Z    at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.MigrateAsync(String targetMigration, CancellationToken cancellationToken)
2020-11-27T17:36:47.944213022Z    at Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.CreateDatabase(IServiceProvider serviceProvider)
2020-11-27T17:36:47.944220422Z    --- End of inner exception stack trace ---
2020-11-27T17:36:47.944229022Z    at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
2020-11-27T17:36:47.944236223Z    at System.Threading.Tasks.Task.Wait()
2020-11-27T17:36:47.944243123Z    at Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.AddHealthChecksUI(IServiceCollection services, String databaseName, Action`1 setupSettings)
2020-11-27T17:36:47.944250523Z    at Digibyte.API.Startup.ConfigureServices(IServiceCollection services) in /home/vsts/work/1/s/Digibyte.API/Startup.cs:line 177
</code>
Comment: Can you show us the code near line `177` or all the code in your `Startup.cs` file?
Comment: `2020-11-27T17:36:47.944250523Z    at Digibyte.API.Startup.ConfigureServices(IServiceCollection services) in /home/vsts/work/1/s/Digibyte.API/Startup.cs:line 177`, This sentence should point out the problem, we need to confirm it before we know the specific reason. Under normal circumstances, your error message will not happen.
Answer: With the tip posted by @jason-pan I´ve found that the error was caused by HealthChecks package.
https://github.com/Xabaril/AspNetCore.Diagnostics.HealthChecks/issues/455
Related to: ASP.NET Core on Azure WebApp crashes because of SQLite


Como retirar bug de linhas de antialising gerado no Firefox e IE?

Question: Estou a criar um rebordo no meu site, com background image. Funciona tudo perfeitamente no Chrome, mas no Firefox e IE aparecem umas linhas indesejadas. Já percebi que estão presentes na propriedade CSS3 de transform:scaleX(-1); na Div efeito do qual eu necessito, também noutros elementos do site para que o padrão comece a a partir do centro da página da direita para a esquerda. Não percebo como as poderei eliminar.
Firefox

IE

O meu código HTML é:

Copyright

O meu CSS é:
.ft_copyright { height: 33px; margin-top: -20px;}
.rebordo_copyright {background: url('assets/images/rebordo.png') 0px -20px repeat-x;}
.back_ft_cr {height: 76px; background: #848484; text-align: center; }
/*rebordos*/
.rebordo {height: 20px; margin-top: 0px; }
.rebordo_l { width: 50%; height: 20px; float: left; background-size: 68px 20px;   background-repeat: repeat-x; outline: 0; /* flip background vertically */ -webkit-transform:scaleX(-1); -moz-transform:scaleX(-1); -ms-transform:scaleX(-1); -o-transform:scaleX(-1); transform:scaleX(-1); filter: FlipH; -ms-filter: "FlipH"; }
.rebordo_r {width: 50%; height: 20px; float: right;  background-size: 68px 20px; background-repeat: repeat-x; outline: 0; }

Comment: Cara você verificou se não são problemas na imagem mesmo.
Mas se não for, pode ser uma simples questão de alinhamento ou sua ou do próprio navegador.
Comment: Isso ocorre porque neles é aplicado [antialiasing](http://en.wikipedia.org/wiki/Anti-aliasing) enquanto o Chrome não aplica.
Comment: Não são problemas na imagem, nem de alinhamento. Em provável que sejam de antialising. Como resolvo isso?
Comment: Teria como fazer um exemplo no [jsfiddle.net](http://jsfiddle.net/)?
Comment: mude o .ft_copyright pra 34 de altura e diga o que acontece.
Answer: Como não foi disponibilizado um exemplo do código não posso garantir que irá funcionar, mas esse código abaixo desativa o antialiasing que deve ser a causa do problema: (fonte)
.rebordo {
    image-rendering: optimizeSpeed;
    image-rendering: -moz-crisp-edges;
    image-rendering: -o-crisp-edges;
    image-rendering: -webkit-optimize-contrast;
    image-rendering: optimize-contrast;
    -ms-interpolation-mode: nearest-neighbor
}

Outra coisa que pode ser feita é ajustar a propriedade background-size evitando que ela altere o tamanho da imagem na direção que está o problema, algo que gera antialiasing.
Ainda outro motivo para que esses navegadores apliquem o antialiasing são as transformações CSS: você pode desativá-las e substituir a imagem no .rebordo_l.
Já que está usando CSS3 há uma propriedade interessante para esse caso: border-image. Com ela é possível especificar uma imagem para as bordas. Há uma demostração interativa para webkit além dos exemplos da MDN.
Comment: não resultou o código que desactiva o antializing, obrigado
Comment: Como eu disse não posso garantir que irá funcionar. Editei procurando abranger todos os casos que geram antialiasing, assim como alternativas.
Comment: tenho aquele efeito css3 no rebordo de modo a que este comece a aparecer da direita para esquerda, a haja bico  no centro do ecrã
Comment: Obrigado pela ajuda.
Answer: Se bem entendi, seu problema está ao centralizar a borda. A maneira mais limpa de fazer essa borda é a seguinte:
HTML

Copyright

CSS
.ft_copyright {
    height: 76px;
    margin-top: 20px;
    text-align: center;
    position:relative;
    background: #848484;
}
.ft_copyright:before {
    display: block;
    content: "";
    height: 20px;
    background: url('assets/images/rebordo.png') center 0px repeat-x;
    background-size: 68px 20px;
    outline: 0;
    position:absolute;
    top: -20px;
    left: 0;
    right: 0
}
.ft_copyright p {
    color: #fff
}

Simplificando o seu código desta maneira não precisaria aplicar filtros, diminuindo seu CSS, aumentaria a velocidade de renderização da página, e tornaria seu código HTML mais semântico e menos poluído.
Comment: O padrão não fica centrado. No meu projecto isso é crucial pois a partir da repetição do padrão nasce o logo da marga que tem que ficar centrado. Obrigado pela ajuda.
Comment: Afinal fica centrado, só que perde-se a opção de uso da imagem em sprite. Obrigado


Where are Drupal (6) custom colour picker values stored?

Question: I am using a Drupal theme which makes use of the colour picker.  When I select a new colour scheme, a directory gets creates in MyDrupalSite/sites/default/files/color/ThemeName-RandomNumer.  Using Opera's developer console, I can see that these files (the generated images and CSS) are used to render the website (if CSS caching is switched off, of course).  However, I have no idea where Drupal is told to look in that directory for the CSS: it doesn't seem to be in a config file and I have no idea where something like that might be stored in the DB.  I would also like to know where the colours for a "custom" configuration are stored: I spent a large chunk of last night trying to figure that out, but to no avail.  Are they somehow encoded into the "RandomNumber"?  So, if someone could enlighten me, I would be much obliged.
Answer: You'll find that the color form on your theme saves the locations of the files as variables at the end of its save operation:
http://api.drupal.org/api/function/color_scheme_form_submit/6
  // Maintain list of files.
  variable_set('color_'. $theme .'_stylesheets', $css);
  variable_set('color_'. $theme .'_files', $paths['files']);

These values are then picked up by your color-aware theme. For instance, the Drupal 6 default theme (Garland) has the following in it's phptemplate_preprocess_page():
  // Hook into color.module
  if (module_exists('color')) {
    _color_page_alter($vars);
  }

This will add the CSS files to the header.


Setting Bootstrap's Custom File Input Cursor to Pointer

Question: I am using the Bootstrap 4 Custom File Chooser and I modified it to make the Browse "button" appears on the left. This is the code:
HTML:

    <input id="application-resume" class="custom-file-input" type="file">

        Choose file (pdf, docx, doc, odt)

CSS:
/* Disabling the default Browse pseudo element */
.custom-file-label::after {
    content: none;
}

.custom-file-input:lang(en) ~ .custom-file-label::after {
    content: none;
}

/* Overriding Bootstrap's Custom File classes */
.custom-file {
    cursor: pointer !important;
}

.custom-file-input {
    cursor: inherit !important;
}

.custom-file-label {
    cursor: inherit !important;
    padding-top: 0;
    padding-left: 0;
    padding-right: 0.75rem;
    padding-bottom: 0.75rem;
}

.custom-file-label::before {
    content: "Browse";
    display: inline-block;
    height: 2.25rem;
    padding: 0.375rem 0.75rem;
    margin-right: 0.25rem;
    line-height: 1.5;
    color: #495057;
    background-color: #e9ecef;
    border-right: 1px solid #ced4da;
    border-radius: 0.25rem 0 0 0.25rem;
}

:lang(en) .custom-file-input ~ .custom-file-label::before {
    content: "Browse";
}

.custom-file-input:focus ~ .custom-file-label::before {
    border-color: #80bdff;
}

.input-group > .custom-file:not(:last-child) .custom-file-label::before {
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
}

.was-validated .custom-file-input:valid ~ .custom-file-label::before, .custom-file-input.is-valid ~ .custom-file-label::before {
    border-color: inherit;
}

.was-validated .custom-file-input:invalid ~ .custom-file-label::before, .custom-file-input.is-invalid ~ .custom-file-label::before {
    border-color: inherit;
}

So everything looks perfect, except that the cursor: pointer; works as expected on Firefox (cursor appears as a pointer on whole custom-file component), but not on both Chrome and Opera the cursor appears as default on the 1/4 of the component and as a pointer on the rest:
this is the image
I don't understand why this is happening since I have all the elements of the custom file component (parent div, input and label) having cursor: pointer; in CSS (cursor: inherited; for child elements).
Thanks for your replies.
Comment: first to do: check through inspect element (on Chrome at least) whether browser respect your css or just throwing in some default.. though [MDN says chrome support](https://developer.mozilla.org/en-US/docs/Web/CSS/cursor) it, i'm afraid they had some browser-specific styling.
Answer: Try text-indent: -999px; for the input[type="file"], it will solve the problem.
Comment: Thank you Mohammed it works perfectly on all my browser, 3-point shot made ;)
Comment: Woho, glad that it worsk ;)
Answer: I too faced the same issue and i fixed with the below code
.custom-file-input {
  z-index: -1;
}

.custom-file-label {
  z-index: 1;
  cursor: pointer;
}


Approaches for quickly gaining some guitar chops

Question: I'm extremely musical; I've listened very deeply and practiced very deeply (with my mind and my voice and whatever instruments I happen to pick up) to pretty much every style and mode of music, including the 'difficult' ones.
I also write profound meaningful poetry off the top of my head as easy as pie. So it's occurred to me that I might as well learn the electric guitar and sing my poetry. So far I've found that all kinds of familiar guitar rhythms are easy/effortless to play but the chords are impossibly awkward and infuriating. And since I have tiny hands, it's easy for me to give myself an excuse and give up on progressing. Still, I know that getting 2 or 3 chord progressions down so I can play them in my sleep will be enough to let me sing a lot of songs before I run out.
Of course I've seen dozens of "how to learn guitar" pages on the web, but most of them seem to be way more technical/systematic than I'm interested in.
So my question is about "philosophies" for learning guitar -- the more metaphoric, spiritual, and poetic the better!
What are your own ways of understanding how to quickly gain a few useful chord progressions when you're an (albeit musically-comfortable) total noob to the electric guitar? What are the top "boring exercises" I devote my time to so as to "mold my brain"?  What are the main opportunities for "reinforcing bad habits"? Again, this is all with a preference toward practical orientations/approaches to quickly gain some chops and move beyond the "that sounded kind of interesting in an experimental textural kind of way" phase.
Answer: Playing guitar is physically demanding. It requires a lot of coordination and dexterity. An ordered, systematic approach, as with most other subjects, is the best approach to the technical side of playing.
As for the artistic side: creating actual music, it is often a product of the technical/mechanical side.
e.g. The more songs and chord progressions you have learnt and analysed the more knowledge and experience you have to draw from when creating your own progressions.
This concept applies to all aspects of the artistic side: the more melodies, chord voicings, techniques, timbres, rhythms, lyrics etc etc you have in your repertoire the more sources you have to draw on to create the music you want without being restricted by a lack of knowledge.
Stand on the shoulders of giants.
To become great at something you must learn from the greats who came before you.
In other words, learn and analyse as much music from as many sources as possible.


Regex how to match an optional character with condition

Question: I need a regex to let a String matches if it's empty or has a length between 8,16
I tried this one " (.?|(\w){8,16})$ " but it doesn't work.
Thank you
Comment: What you mean exactly by *empty*? and what would be the format of your string?
Comment: "It doesn't work" is about the worst way to describe an issue.
Comment: Regex: `^(.{8,16})?$`.
Comment: @Phylogenesis you need to put that inside a group.
Comment: @AvinashRaj Yeah. realised it would use `?` as a less-greedy operator instead of the conditional one.
Comment: The string has to match only when it has a length equals zero o between 8 and 16. the format is not important, it could be numbers or chars or mixed.
Comment: I get it : ^(?:\w{8,16})?$ thank you.
@I'L'I  you're right but thanks
Answer: Seems like you want something like this,
^(?:.{8,16})?$

or
^(?:\w{8,16})?$

Comment: Accept an answer which helps you a lot.
Answer: This will do the job: ^(|.{8,16})$
Demo: https://regex101.com/r/cU9mK7/1
Answer: Try this:
    ((.){8,16})|(.{0})
Let me know if it helped.
Comment: ^(?:.{8,16})?$ i used this one for my job. thank you for your response
Answer: Your regex (.?|(\w){8,16})$ "doesn't work" because of how regexes work in general, there are multiple flaws. Between alternations the most-left one is tested first. .? means 0 or 1 times of any character (which also means that string with length of 1 is incorrectly matched as well). So, a 8 character string will match its last character because of .? and your second alternation isn't even checked.
Another thing is the usage of $ and no ^, this means that you will simply check the last 8-16 characters (if there are any). ^ is the start of the string and is needed to use here (to check whole string from start to finish).
^(|\w{8,16})$ should work and means "empty"(^$ is an empty string, nothing between the start and end of it) OR 8-16 word symbols between the start and end of string.


What is the difference in sound quality between high and low impedance 'headphones'?

Question: I want to record and mix music and I have been looking at some equipment, one of which is the DT 770 PRO headphones. However, this headphone is available in varying levels of impedance, namely 32 ohms, 80 ohms and 250 ohms. I could not find the answer to the question on whether high impedance equals to better quality of sound. The only answer I came across after hours of researching is, how with low impedance can be connected to virtually anything while high impedance requires an audio interface.
What are the differences between low and high impedance headphones in terms of quality of sound? Why should you choose one over the other? (Other than the fact that one requires a dedicated audio interface and the other does not).
I feel incredibly lost and an answer shedding light on this matter would be most sincerely appreciated, looking forward.
Comment: no @DavidW that question is regarding microphones, this question is concerning headphones.
Comment: There isn't.  Just match impedance with your source,  and of course buy headphones that are made well.
Comment: @ShahzadRahim Fair point. I didn't read carefully enough
Comment: Does this answer your question? [What is the difference between high impedance and low impedance microphones?](https://music.stackexchange.com/questions/111275/what-is-the-difference-between-high-impedance-and-low-impedance-microphones)
Answer: I don't think there is any difference in sound quality, or at least if there is, it's so minimal that it's overshadowed by all the other design elements of the headphones.
The reason why different impedances are available is to work better with different devices. If you buy the highest impedance set and plug it into your smart phone, you may find that even with the volume all the way up on your phone, it's still not very loud.
Conversely, if you buy the lowest impedance set and plug it into a professional mixing console, you might find you have to have the headphone level pot turned almost all the way down to keep it from being too loud.
In a way, that last example does relate to a sound quality difference, but not because of the headphones themselves. A stereo analog pot (knob) works best in the middle of its range. If you turn a pot almost all the way down, the stereo balance might be off a little bit and the quality of the signal through that pot might suffer. Obviously higher quality pots are more stable throughout their range, but there are inherent limitations in all gear, and the lowest level settings can often bring them out.
So that's the one interaction between headphone impedance and final sound quality that I can think of. If you'd like to invest in one set of headphones to use for both consumer devices like phones and professional devices like audio interfaces and mixing consoles, then get the middle impedance level. Either way it might help to buy from a good retailer with a reasonable return policy so you can send back a set that seems to be too loud or too quiet for a different impedance.
Comment: What would be the issue with turning an analog pot almost all the way up?
Comment: @Edward I've never done it before on a headphone output pot because it would be painfully loud for me. Because of the physical properties of a typical analog pot I expect the high end of the range to have similar characteristics as the low end.
Comment: Because of what physical properties exactly?  It's pretty well known that pots have less accuracy at low levels (hence the stereo unbalancing) but I've never heard of volume pot being inaccurate at too high of a level.  That needs a citation or justification.
Comment: @Edward Ok... maybe I'll just edit it out. Whatever
Comment: So then which one do I get? I plan on buying the scarlet solo for the headphones, should I get 32 ohms? 80 ohms? 250 ohms? I plan on using it for mixing acoustic guitar arrangements. So impedance is merely something to suit different devices? A higher impedance headphone with an interface is not superior in terms of clarity to lower impedance headphones without it?
Comment: @ShahzadRahim It is correct that one is not clearly better than the other. I think for the Scarlett and similar home studio device Beyerdynamic recommends the 80 Ohm version. I'll add a reference for that to the question.
Answer: If the source runs on a 3v power rail (a couple of AA batteries) or a 5v one (USB) you'll need low impedance cans in order to get any volume.  With 12v, 24v or more to play with, higher impedance is appropriate.  Neither is good or bad as such.  Pick the ones that suit your equipment.
It may be that high impedance cans are perceived as inferior by analogy with high impedance microphones.   In this sphere, high impedance models are typically wired unbalanced and are associated with cheaper systems.  Low impedance ones are wired balanced and are 'professional'.
Comment: I am sorry but my question is referring to headphones not microphones.
Comment: I know.  I discussed headphones ('cans') then mentioned a comparison with microphones.


Showing a subset of sequences is not closed

Question: Let $E$  be the set of sequences of real numbers $x = (x_n)_{n\in \mathbb N}$ such that the series
$\displaystyle \sum_{n=1}^{\infty}\dfrac{|x_n|}{n^2}$  converges. $E$ is a normed space with $||x||=\displaystyle \sum_{n=1}^{\infty}\dfrac{|x_n|}{n^2}$.
Let $F$ be the set of sequences of real numbers $y = (y_n)_{n\in \mathbb N}$ such that
$\displaystyle ||y||_∞ = \sup_{n\ge 1}|y_n|$ is finite. Clearly $F \subset E$, and I want to show  that $F$ is not closed in $E$ for $|| · ||$.
My idea is to come up with a sequence of sequences in $F$ such that this sequence of sequences  converge to a sequence in $E$ but this limiting sequence is not in $F$. But I could not find one that makes this true.
Comment: A good first idea in that kind of situation is to take a sequence in $E \,\backslash\, F$, let's call it $u$, and look at the sequences $u^{(k)}$ that are the "truncatures" of $u$: $u^{(k)}_n = u_n$ if $n \leq k$, and $= 0$ if $n > k$. There'll then only be the problem of checking that there's convergence for $(u^{(k)})_k$ to $u$ for $||.\!||$.
Answer: For a natural number $n$, denote by $g^n$ the sequence $g_i^n=\sqrt{n}$ if $i<n$ and $0$ else. We note that $||g^n||_{\infty}<\infty$ and that $g^n$ converges to $(\sqrt{n})_{n}$ in the norm of $E$, yet $(\sqrt{n})_{n}$ does not lie in $F$
Comment: Yes that is what I mean.
Comment: by $(\sqrt{n})_n$ do you mean the sequence of real numbers $v_n=\sqrt {n}$  for all $n\in \mathbb N$ ?


Getting access to internal register of PCIe device

Question: I've found few topics about it here, but none of them explained the issue I have.
I'm simply trying to get access to internal status register of PCIe device, by mapping it to user memory space in linux.
Here is my system configuration:
# uname -a
Linux localhost.localdomain 4.18.13-200.fc28.x86_64 #1 SMP Wed Oct 10 17:29:59 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux

# lspci -tv
-[0000:00]-+-00.0  Intel Corporation Device 1980
       +-04.0  Intel Corporation Device 19a1
       <...>
       +-1f.2  Intel Corporation Device 19de

# cat /proc/iomem
df570000-df573fff : 0000:00:1f.2

# lspci -s 00:1f.2 -x
00:1f.2 Memory controller: Intel Corporation Device 19de (rev 11)
00: 86 80 de 19 00 00 00 00 11 00 80 05 00 00 80 00
10: 00 00 57 df 00 00 00 00 00 00 00 00 00 00 00 00
20: 00 00 00 00 00 00 00 00 00 00 00 00 d9 15 69 09
30: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

So, the device is sitting on 00:1f.2 and visible for the system. I try to get access to internal "ERRCORSTS" register with offset 0x110 of memory controller, which shows the error status of individual correctable error sources on a PCI Express device page1673 (here is the manual for my SoC ). The output that I get from my program is:

data = ffffffff
PCI BAR0 0x0000 = 0xffff

It seems that I'm missing something in understanding of linux memory mapping or may be they just changed something in 4.18 kernel, so it's not so easy as it was before.
Could anybody help me out with it, please?
Here is my code:
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define BASE_ADDR 0xdf570000
#define DATA_OFFSET 0x110
extern int errno;
int main()
{
    int i;
    int fd = open("/dev/mem",O_RDWR|O_SYNC);
    if(fd < 0) {
            printf("Can't open /dev/mem\n");
            return 1;
    }

    u_int32_t* mapped_base = (u_int32_t *) mmap(0, 4096UL, PROT_READ|PROT_WRITE, MAP_SHARED, fd, BASE_ADDR);

    // Trying to get access to device memory
    if(mapped_base == NULL) {
            printf("Can't mmap\n");
            return 1;
    } else {
            unsigned int status_register0 = *(int *)(mapped_base + DATA_OFFSET  );
            printf("data = %lx \n",status_register0);
    }

    // Trying to get access to DevID
    int fb = open("/sys/devices/pci0000:00/0000:00:1f.2/resource0", O_RDWR | O_SYNC);
    u_int32_t* ptr = mmap(0, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fb, 0);
    printf("PCI BAR0 0x0000 = 0x%4x\n",  *((unsigned short *) ptr) );

    return 0;
}

Answer: This performs pointer arithmetic.
mapped_base + DATA_OFFSET

The offset is automatically multiplied by the element size, which is probably 4 based on
u_int32_t* mapped_base

However, your documentation appears to specify offsets in bytes.
Thus, you need to read 0xdf570110 but are actually reading 0xdf570440
Comment: Good point! I've changed DATA_OFFSET from 0x110 to 0x44, but still get the same result only '1's. As I read in bunch of articles, it should be fairly easy to map device memory space to user memory space by mmap() and work with it like with regular memory. And it's also strange, that /resource0 doesn't work either. But lspci -xxxx can actually read data from BAR0.
Is there some kind of protection in Fedora 28 Linux ?
Answer: It seems that I messed up the memory, when I experimented with it. So everything works after I reboot the machine.


how to add permissions with samba

Question: i have a samba file server on ubuntu server for my windows pc and when i try to write on the shared drive it says that i need permission to do that. i have done this:
sudo chown nobody:nogroup /var/www/html

and my smb.conf is:
[webpage]
    comment = Ubuntu File Server Share
    path = /var/www/html
    browsable = yes
    guest ok = yes
    read only = no
    create mask = 0755

i have another shared folder and that one is working fine with the same .conf
please can somebody tell me how to give myself permissions. thanks
Answer: Your connection probably doesn't run as the user you think it does.

You can try to find out as with user samba runs that connection. Run
chmod 1777 /var/www/html

Then you should be able to create a file in that directory. It will have the user and group of the Samba process for this connection.
Change the permissions back after that.
You can change the user and group of the Samba process with these lines in smb.conf
force user = nobody
force group = nogroup

how to add permissions with samba


Unwrap XPCNativeWrapper object in Firefox  versions < 3.6.2

Question: Is there a way to unwrap an XPCNativeWrapper object in early versions of Firefox (before version 3.6.2)?
Answer: Accessing the wrapper's wrappedJSObject property is functionally equivalent whenever the object passed to XPCNativeWrapper.unwrap is an XPCNativeWrapper. For example, assuming you know your window is a wrapped object, then the following is "true":
XPCNativeWrapper.unwrap(window) === window.wrappedJSObject // => true

XPCNativeWrapper.unwrap is safer when you don't know for sure that you're dealing with a wrapped object. For example, the following is "true":
var test = [1, 2, 3];
XPCNativeWrapper.unwrap(test) === test // => true

...but this is "false" (when using the same array):
XPCNativeWrapper.unwrap(test) === test.wrappedJSObject // false


MKMapView Not Loading When Called on an NSThread?

Question: I am creating a MKMapView in a method named "generateMap". From inside viewDidLoad, this works:
[self generateMap];

but this causes the map to quickly load and then disappear, leaving only the blank grey grid:
[NSThread detachNewThreadSelector:@selector(generateMap) toTarget:self withObject:nil];

Any ideas why this might be happening when I call the method through a thread?

I ended up doing this:
-(void)viewDidLoad {
[NSThread detachNewThreadSelector:@selector(spinTheSpinner) toTarget:self withObject:nil];
[self performSelectorOnMainThread:@selector(generateMap) withObject:nil waitUntilDone:NO];
[super viewDidLoad];
}

This allows me to have a spinner (UIActivityIndicator) and load the MKMapView as I want. I set "waitUntilDone:No]" so that the screen switches the MapView before it is done with generateMap. Otherwise, we would not see the spinner and would only see a blank screen until generateMap was done.
Answer: First off, can I see the generateMap method?  Second, a more sufficient way to perform a selector is by saying

[self performSelector:@selector(generateMap)];

Comment: Or, simply, `[self generateMap];`
Answer: I don't think it is advisable to try to update the UI through anything but the main thread.
What happens when you try to run -generateMap on the main thread with -performSelectorOnMainThread:withObject:waitUntilDone:?
For example:
[self performSelectorOnMainThread:@selector(generateMap) withObject:nil waitUntilDone:YES];

Comment: I set ...waitUntilDone:NO]; so the screen does not sit there blank.


Detect multiple images load event

Question: I'm wondering if there is a way to detect load event of multiple images (particularly, a function should execute when the last image in a given set has completed loading).
For instance, an user clicks on a link and lighbox appears with 10 images. When all images have loaded, loading bar should disappear.
jQuery(".lightbox-image").each(function(){
    var image = jQuery(this);
    jQuery('').attr('src', image.attr('src')).load(function(){
        hideLoadingBar();
    });
});

This unfortunately triggers hideLoadingBar(); too early (after one image has completed loading).
P.S.
I also need my function to work after images have been cached so: jQuery('#img1, #img2').load(); won't work.
Comment: see this  http://stackoverflow.com/a/9624426/235710
Comment: @MohammadAdil This is precisely what doesn't work when images are already cached. And I can't `trigger('load')` manually because that will execute `hideLoadingBar()` too early.
Comment: if i'm not wrong load is always an ajax req, did you try progress callback?
Answer: Check out this jQuery imagesLoaded plugin, it should suit your needs I think.
Answer: Well, it seems that no one has better idea, so below is my solution/workaround. The other answer to this question is probably what you want to use because it's a library created specifically for that but here's the solution that I'm going to use because it's shorter and simple:
var allImages = jQuery(".lightbox-image").length;
var counter = 0;
jQuery(".lightbox-image").each(function(){
    var image = jQuery(this).find('.myimage');
    jQuery('').attr('src', image.attr('src')).load(function(){
        counter++;
        if(counter >= allImages){
            hideLoadingBar();
        }
    });
});

Works for cached images and not cached images.
Comment: What happens with this solution if you have, say, 10 or so rather large images that are currently loading when this function executes. Then you'll start another 10 downloads of the same images, isn't that right? Perhaps that performance slowdown is acceptable to you.
Comment: Also check the browser quirks [documented on the plugin page](https://github.com/desandro/imagesloaded/wiki/Browser-quirks).
Comment: @HannesJohansson I'm not sure how it does this but I hope that it doesn't load them twice. Especially if they are already cached. In my case images won't be large so it should be acceptable.
Comment: @HannesJohansson I checked this in Apache's access log and even if I create 100 instances of this image, in different ways, at different points, there is only 1 request per page refresh from Chrome 27 (cache disabled).
Comment: @Paul Ok, I don't know how all the browsers work exactly. Just saying one needs to be careful because browsers handle images and caching differently, so if cross-browser compatability is important to you I'd advice to be careful. The people who wrote the plugin thought hard about this and it's not that big a plugin, only a kilobyte minified.

Detect multiple images load event


Should coin flips be modeled as Bernoulli or binomial draws in RJags?

Question: What is the best way to model coin flips as a hierarchical model? Do you say coin draws are a series of draws from Bernoulli trials or as one draw from a binomial distribution?
That is something like this:
model {
  p ~ dunif( 0, 1 )
  for( i in 1 : n) {
    h[i] ~ dbern( p )
  }
}

or, this:
model {
  p ~ dunif( 0, 1 )
  numberOfHead ~ dbinom (totalTrials, p)
}

Answer: One draw from binomial distribution generally is enough. But it depends of the data you have. If you have the data of how many heads in the individual coin flips have been seen in total, then binomial distribution is enough, no need for detailed model with N bernoulli flips. However, if you have data on results of individual coin flips and you need to distinguish them (e.g. because of covariates for individual coin flips), you will need more detailed model with bernoulli distribution.
Answer: Both models will give the exact same results.  Why? The Likelihood principle.  RJags is an R package that uses the software JAGS to conduct Bayesian inference, and any fully Bayesian procedure, one where inference proceeds from the posterior distribution, will satisfy the Likelihood principle.  Essentially, the Likelihood principle states that if two likelihood functions are proportional to each other, then the same inference about the parameters should be obtained from the two likelihood functions.
In your example we are inferring the probability of a coin landing heads up, $p$,  from $n$ independent tosses, $X_1,...,X_n$, of that coin.  Prior to tossing the coin, you assume that any value of $p$ in the interval $[0,1]$ is equally likely.  Thus the prior distribution for the parameter $p$ is $\pi (p)=1$. Suppose we observe $k$ coin tosses where the coin lands heads up, where $0\leq k\leq n$. In the case of the model using the binomial distribution, the likelihood function is
$$
l(p|X_1,...,X_n)= {n \choose k}p^k (1-p)^{n-k}
$$
For the Bernoulli model, the likelihood function is
$$
l_\star (p|X_1,...,X_n)=p^k(1-p)^{n-k}
$$
We have observed the data, so both $n$ and $k$ are fixed values and therefore ${n \choose k}$ is just a constant, and $l(p|X_1,...,X_n) \propto l_\star(p|X_1,...,X_n)$, bearing in mind $l$ and $l_\star$ are functions of $p$. Once we have our samples from the posterior distribution from RJags, we will make the same conclusion, aside from any error due to having a finite sample from a Markov Chain that has hopefully converged.
Also, if you are familiar with sufficient statistics, you could note that $k=\sum_{i=1}^n{X_i}$ is a sufficient statistic for $p$ in both models (assuming $n$ fixed).


Pentaho Role Intersection

Question: I am working with roles in mondrian schema and i would like to know if possible to make intersection of two declared roles.
I created these roles:
For product manager that has restriction on specific types of products
<Role name="product_manager">
    <SchemaGrant access="none">
      <CubeGrant cube="product" access="all">
          <HierarchyGrant hierarchy="product_group" rollupPolicy="partial" access="custom">
           <MemberGrant member="[product_group].[Wardrobes]" access="all">
           </MemberGrant>
          </HierarchyGrant>
        </CubeGrant>
    </SchemaGrant>
  </Role>

And financial manager that has restriction on specific country
<Role name="financial_manager">
        <SchemaGrant access="none">
          <CubeGrant cube="country" access="all">
              <HierarchyGrant hierarchy="country" rollupPolicy="partial" access="custom">
               <MemberGrant member="[country].[Germany]" access="all">
               </MemberGrant>
              </HierarchyGrant>
            </CubeGrant>
        </SchemaGrant>
      </Role>

My required result should be intersection of these two roles, i found that exist element UNION, but i found that it returns sum of both so the user can see all from both, it isn't my required solution.
<Role name="product_and_financial_manager_for_wardrobes_and_germany_resort">
    <Union>
        <RoleUsage roleName="product_manager" />
        <RoleUsage roleName="financial_manager" />
    </Union>
  </Role>

Something like this:
 <Role name="product_and_financial_manager_for_wardrobes_and_germany_resort">
        <Intersection>
            <RoleUsage roleName="product_manager" />
            <RoleUsage roleName="financial_manager" />
        </Intersection>
      </Role>

This is example on data:
fact_product
---------------------------------------------------------------------------
|  id_fact_product   |  price    | id_dim_product_group  | id_dim_country
---------------------------------------------------------------------------
| 1                  |   100     |   1                   |    1
---------------------------------------------------------------------------
| 2                  |    150    |   1                   |    2
---------------------------------------------------------------------------
| 3                  |    120    |   2                   |    2
---------------------------------------------------------------------------
| 4                  |    230    |   1                   |    2
---------------------------------------------------------------------------

dim_product_group
----------------------------------------------
| id_dim_product_group  |  section
----------------------------------------------
|  1                    |  Wardrobes
----------------------------------------------
|  2                    |  Tables
----------------------------------------------

dim_country
----------------------------------------------
| id_dim_country        |  country
----------------------------------------------
|  1                    |  Italy
----------------------------------------------
|  2                    |  Germany
----------------------------------------------

The result for Role product_and_financial_manager_for_wardrobes_and_germany_resort should be see data only in this range
 -----------------------------------------------------------------------------
    |  id_fact_product   |  price    | id_dim_product_group  | id_dim_country
    ---------------------------------------------------------------------------
    | 2                  |    150    |   1                   |    2
    ---------------------------------------------------------------------------
    | 4                  |    230    |   1                   |    2
    ---------------------------------------------------------------------------
----------------------------------------
    |  section           |  country  |
    -----------------------------------
    |  Wardrobes         |  Germany  |
    -----------------------------------
    | Wardrobes          |  Germany  |
    -----------------------------------

Thanks for you help
Answer: There is no such feature in Mondrian. I suggest creating a ticket in the Jira tracker.
Alternatively, you could implement the Role interface and pass it to your connection.

Pentaho Role Intersection


Sobrescrever action POST de ViewSet para salvar e atualizar dados no Django Rest Framework

Question: Estou criando uma aplicação para controle de estoque e estou tendo a seguinte dificuldade. Quando insiro uma [entrada de produto] a quantidade de entrada deve ser somada com a quantidade em estoque de [produto]. Existe a possibilidade de fazer um update em [Produto] no método create de [entrada de produto]?
serializer de [produto]:
from rest_framework.serializers import ModelSerializer
from produto.models import Produto

class ProdutoSerializer(ModelSerializer):
    class Meta:
        model = Produto
        fields = ('id', 'nome', 'descricao', 'categoria', 'quantidade_estoque', 'imagem')

serializer de [entrada de produto]:
from rest_framework.serializers import ModelSerializer
from estoque_entrada.models import EstoqueEntrada
class EstoqueEntradaSerializer(ModelSerializer):
    class Meta:
        model = EstoqueEntrada
        fields = ('id', 'produto', 'data', 'quantidade_entrada', 'valor_pago', 'usuario')

viewset de [entrada de produto] com o que eu tentei fazer:
from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response
from rest_framework import status
from estoque_entrada.models import EstoqueEntrada
from produto.models import Produto
from produto.api.serializers import ProdutoSerializer
from .serializers import EstoqueEntradaSerializer

class EstoqueEntradaViewSet(ModelViewSet):
    queryset = EstoqueEntrada.objects.all()
    serializer_class = EstoqueEntradaSerializer

    def create(self, request, *args, **kwargs):

        produto_queryset = Produto.objects.filter(id=request.data['produto'])
        quantidade_entrada = int(request.data['quantidade_entrada'])
        quantidade_produto = produto_queryset[0].quantidade_estoque
        quantidade_produto = quantidade_produto + quantidade_entrada
        produto_serializer = ProdutoSerializer(produto_queryset, many=True)
        produto_data = produto_serializer.data
        produto_data[0]['quantidade_estoque'] = quantidade_produto
        # produto_serializer.is_valid(produto_data)
        # produto_serializer.update(produto_data)

        entrada_serializer = self.get_serializer(data=request.data)
        entrada_serializer.is_valid(raise_exception=True)
        self.perform_create(entrada_serializer)
        headers = self.get_success_headers(entrada_serializer.data)
        return Response(entrada_serializer.data, status=status.HTTP_201_CREATED, headers=headers)

Comment: Parece-me que o problema é que você está somente serializando, não [atualizando](https://www.django-rest-framework.org/api-guide/serializers/#saving-instances) a instância de `Produto` que você filtrou.
Answer: Foi importada a classe Produto de models, obtidos e alterados seus objetos e depois utilizado o produto.save() para alteração no banco de dados.
from estoque_entrada.models import EstoqueEntrada
from produto.api.serializers import ProdutoSerializer
from produto.api.viewsets import ProdutoViewSet
from produto.models import Produto
from rest_framework import status
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from .serializers import EstoqueEntradaSerializer

class EstoqueEntradaViewSet(ModelViewSet):
    queryset = EstoqueEntrada.objects.all()
    serializer_class = EstoqueEntradaSerializer

    def create(self, request, *args, **kwargs):

        produto_queryset = Produto.objects.filter(id=request.data['produto'])
        quantidade_entrada = int(request.data['quantidade_entrada'])
        quantidade_produto = produto_queryset[0].quantidade_estoque
        quantidade_produto = quantidade_produto + quantidade_entrada
        produto_serializer = ProdutoSerializer(produto_queryset, many=True)
        produto_data = produto_serializer.data
        produto_data[0]['quantidade_estoque'] = quantidade_produto
        produto = Produto.objects.get(id=request.data['produto'])
        produto.quantidade_estoque = produto_data[0]['quantidade_estoque']
        produto.save()

        entrada_serializer = self.get_serializer(data=request.data)
        entrada_serializer.is_valid(raise_exception=True)
        self.perform_create(entrada_serializer)
        headers = self.get_success_headers(entrada_serializer.data)
        return Response(entrada_serializer.data, status=status.HTTP_201_CREATED, headers=headers)


Trying to migrate Date values using migrate module.

Question: I'm trying to migrate some data from a csv to a field_collection in a user profile. Everythings works fine but not for a field of Date (with range) type.
I'm on Drupal 7.22 and I'm using Migration and Migration Extra modules
I do not receive any error message, but the data is not entered, please help me
My code in the migration class:
[...]
$source_file = drupal_get_path('module', 'module_name') . '/data/user_employments_info.csv';

$columns = array(
  [...]
  array('employment_period_start', 'employment_period_start'),
  array('employment_period_end', 'employment_period_end'),
  [...]
);

$this->destination = new MigrateDestinationFieldCollection(
  'field_usr_bkg_emplo',
  array('host_entity_type' => 'user')
);

[...]

$this->addFieldMapping('host_entity_id', 'user')->sourceMigration('User');

[...]

$this->addFieldMapping('field_usr_bkg_emplo_time', 'employment_period_start');
$this->addFieldMapping('field_usr_bkg_emplo_time:to', 'employment_period_end');

Comment: Probably a format issue? Have you checked what the format looks like before it gets passed to the fieldMapping? Probably you need to format it in a prepareRow() function?
Comment: I thought about it in fact I saved data with the simple form and I used the same format (YYYY-MM-DD 00:00:00): a common datetime without tracking hours, minutes and seconds.
I used the format also literally in the code but I get the same result: nothing.

If I'm omitting something I'm sorry but I'm not an expert in Drupal
Comment: Probably this helps you? http://drupal.stackexchange.com/questions/56762/what-format-should-date-iso-date-be-when-using-migrate-module
Answer: At the base there was a problem: the module dates was patched.
The final code that have worked:
my.info
dependencies[] = migrate
dependencies[] = migrate_extras
dependencies[] = date
dependencies[] = date_migrate

my.make
projects[migrate][subdir] = "contrib"
projects[migrate][version] = "2.6-rc1"
projects[migrate_extras][subdir] = "contrib"
projects[migrate_extras][version] = "2.5"
projects[date][subdir] = "contrib"
projects[date][version] = "2.6"
projects[date][patch][] = "https://drupal.org/files/date-consolidated_migrate-1.patch"

my_migration.inc
$this->addFieldMapping('field_date', 'date_from');
$this->addFieldMapping('field_date:to', 'date_to');
$this->addFieldMapping('field_date:timezone', 'UTC');


Matlab Reading the coordinates from txt file and store them in a matrix

Question: I generate 4 multivariate normal samples from given mu and sigma and store them in a txt file. The file consists of the x1-x2 pairs as following.
1 2
3 4
5 6
7 8
So, what I try to do is read them from txt file and store them in 4x2 matrix. Can you give me a solution to accomplish this problem?
Answer: Use dlmread.
A = dlmread('vals.txt')

Answer: Matlab has several functions for this, two of which are textread and textscan.


Spicing C with classes

Question: Disclaimer: I am a complete newbie with C, but I've been playing with it trying to mimic some features of classes. Ok, I know that if I want to go that way I should learn C++, but consider the following a little experiment.
Schreiner, in the book Object-oriented programming with ANSI-C suggests a way to use pointers to get object orientation features in C. I must admit I have only skimmed through the book, but I don't like his approach too much. Basically, he uses pointers to functions in order to arrange that
func(foo);

actually results in calling
foo.methods->func();

where foo.methods is a struct containing pointers to functions. The thing I do not like in this approach is that one has to have the global function foo anyway; that is, methods are not namespaced by the class they live in. My feeling is that this will soon lead to clutter: think two objects foo and bar, both having a method func but with a different number of parameters.
So I have tried to get something more fit to my taste. A first attempt is the following (I omit the declarations for sake of brevity)
#include <stdio.h>

//Instances of this struct will be my objects
struct foo {
    //Properties
    int bar;

    //Methods
    void (* print)(struct foo self);
    void (* printSum)(struct foo self, int delta);
};

//Here is the actual implementation of the methods
static void printFoo(struct foo self) {
    printf("This is bar: %d\n", self.bar);
}

static void printSumFoo(struct foo self, int delta) {
    printf("This is bar plus delta: %d\n", self.bar + delta);
}

//This is a sort of constructor
struct foo Foo(int bar) {
    struct foo foo = {
        .bar = bar,
        .print = &printFoo,
        .printSum = &printSumFoo
    };
    return foo;
}

//Finally, this is how one calls the methods
void
main(void) {
    struct foo foo = Foo(14);
    foo.print(foo); // This is bar: 14
    foo.printSum(foo, 2); // This is bar plus delta: 16
}

This is unconvenient but sort of works. What I do not like, though, is that you have to explicitly add the object itself as the first argument. With some preprocessor work I can do a little better:
#include <stdio.h>
#define __(stuff)     stuff.method(* stuff.object)

//Instances of this struct will be my objects
struct foo {
    //Properties
    int bar;

    //Methods
    //Note: these are now struct themselves
    //and they contain a pointer the object...
    struct {
        void (* method)(struct foo self);
        struct foo * object;
    } print;
};

//Here is the actual implementation of the methods
static void printFoo(struct foo self) {
    printf("This is bar: %d\n", self.bar);
}

//This is a sort of constructor
struct foo Foo(int bar) {
    struct foo foo = {
        .bar = bar,
        //...hence initialization is a little bit different
        .print = {
            .method = &printFoo,
            .object = &foo
        }
    };
    return foo;
}

//Finally, this is how one calls the methods
void
main(void) {
    struct foo foo = Foo(14);
    //This is long and unconvenient...
    foo.print.method(* foo.print.object); // This is bar: 14
    //...but it can be shortened by the preprocessor
    __(foo.print); // This is bar: 14
}

This is as far as I can get. The problem here is that it will not work for methods with arguments, as preprocessor macros cannot take a variable number of arguments. Of course one can define macros _0, _1 and so on according to the number of arguments (until one gets tired), but this is hardly a good approach.

Is there any way to improve on this and let C use a more object-oriented syntax?

I should add that actually Schreiner does much more than what I said in his book, but I think the basic construction does not change.
Comment: Preprocessor macros can take a variable number of arguments, as of 12 years ago.
Comment: I would use a vtable approach for functions, which is similar to your second approach, except `print` would be a pointer.
Comment: "both having a method func"... func is the name of a pointer-to-function field in a struct: there's no reason the global function it points to must be called simply "func".  Prefix/postfix it with something class-specific and you've solved that problem.
Comment: C99 allows variadic macro. I agree with R..
Comment: @Tony: Ok, I agree that one can do manual namespacing, like fooFunc, but it is still less than ideal.
Comment: @R. D'oh! This is my second question in C, and the second time I get caught by something which has been changed in C99. This comes from studying from and old book about C89... :-( I will document better next time!
Comment: @R. About putting some effort in the actual design: yes, this is what I am trying to do. I do not want to copy any other language, but it feels weird that method do not belong to the object itself. I'm not claiming that the syntax I presented here is ideal. It is just an experiment to work out which possibility one actually has for the syntax.
Answer: Various frameworks already exists.  See for instance http://ldeniau.web.cern.ch/ldeniau/html/oopc.html
Comment: Thank you, this looks very interesting. I will have a look at the source to see how this works.
Comment: 500 - Internal server error

There was an error loading the page you requested: http://ldeniau.web.cern.ch/ldeniau/html/oopc.html — There is a problem with the resource you are looking for, and it cannot be displayed.
Comment: @LaszloPapp, Laurent had papers (you can find one or two by looking for its name) and several frameworks linked from his home page.  It looks like one of his frameworks is available at http://sourceforge.net/projects/cos/ (there is also a githup project which seems inactive).
Comment: Yes, I found those. I meant to indicate that you should perhaps update your reply.
Answer: A book (in PDF form) that explains how to do it, is object oriented programming in ANSI C
It's old (1993) but still contains some valid ideas and tips, IMHO.
Comment: Indeed this is the book I refer to, but I don't like its approach too much. See the question.
Comment: OK, I did not see the reference at first!
Answer: Did you have a look at Google's Go? It's basically a modernized C where things are done somewhat in the way you suggested. It has parameter polymorphisms. So you don't have to do this:
static void printFoo(struct foo self) {
    printf("This is bar: %d\n", self.bar);
}

In Go it can be done this way:
static void print(Foo self) {
    printf("This is foo: %d\n", self.foo);
}

static void print(Bar self) {
    printf("This is bar: %d\n", self.bar);
}

In Go Foo and Bar would also be structs. So you are basically on the samet track as the Go language designers.
For an overview of Go see http://golang.org/doc/effective_go.html This is the Go main language description: http://golang.org/doc/effective_go.html

Spicing C with classes


Gx X Ev3, Desenvolvimento Genexus Java Environment

Question:
Nota: Em Genexus, que é um "criador" de pacotes de código para desenvolvimento ágil, não se necessita codificar em linguagem comum como o Java. Apenas criando a transação especificando os seus atributos já é o suficiente para que se crie o "objeto" e até com uma pré-interface com um CRUD básico.

Estou desenvolvendo uma aplicação com Genexus e utilizando Java/MySQL como Environment. Criei apenas uma transação como teste. Está tudo ok, mas ao mandar executar o programa e a geração do Build e Developer Menu nada acontece, nem sequer uma janela aparece.
O que pode ser?
Estou programando para Java Win/Web.
Comment: Fica complicado te ajudar se você não nos ajudar a entender qual é o problema. Por que não [edita](http://pt.stackoverflow.com/posts/56680/edit) a pergunta fornecendo mais informações e trechos de código? Bem vindo ao StackOverflow.
Comment: @renan Aparentemente ele não escreveu nenhum código. Uma "transação" complexa pode ser feita em Genexus sem escrever nenhuma linha de código.
Comment: Exatamente @Caffé]
Comment: Em Genexus, que é um "criador" de pacotes de código para desenvolvimento ágil, não se necessita codificar em linguagem comum como o Java. Apenas criando a transação especificando os seus atributos já é o suficiente para que se crie o "objeto" e até com uma pré-interface com um CRUD básico.
Answer: Talvez você tem a janela de Output fechada e mensagens de saída (erro) estão lá. Você pode abrir a janela com a opção View/Other Tool windows/Output.
Comment: Não estou com a janela de Output fechada. Foi uma das primeiras coisas que eu fui verificar. Como eu disse no tópico. Está tudo "certo", mas não tenho qualquer resposta. Fui até atrás de atualizar todos os arquivos para ver se foi falta de algum complemento, mas nada. Não sei mais o que fazer.


mysql, select with no duplicates with count, based on maximum value of different column

Question: I have fallowing table structure
|id|product_id|date|buyer_id|seler_id|

as a result of a query i need to have
not duplicated, product_id with maximum date and corresponding to it buyer_id and also quantity of buyers for this product_id
Answer: select t.*
from your_table t
inner join
(
   select product_id, max(date) as mdate
   from your_table
   group by product_id
) x on x.product_id = t.product_id and x.mdate = t.date

Answer: The subquery gets the latest date for every product_id. To get the other columns, you need to join the subquery on the table itself on two conditions, that it matches the product_id and the date.
SELECT  a.*
FROM    tableName a
        INNER JOIN
        (
            SELECT  product_id, MAX(date) date
            FROM    tableName
            GROUP   BY product_id
        ) b ON a.product_id = b.product_id AND
                a.date = b.date

This can also be done using correlated subquery,
SELECT  a.*
FROM    tableName a
WHERE   a.date =
        (
            SELECT  MAX(date) date
            FROM    tableName b
            WHERE   a.product_id = b.product_id
        )

The Rows Holding the Group-wise Maximum of a Certain Column
Comment: thank you for your quick response, but i already figure it out how to get distinct product_id with last buyer, the problem is that i also need to know how many buyers bought this product


Matplotlib table cell colors are not rendering

Question: I am trying to create a table in matplotlib with varied row colors. The colors I provide to ax.table() are not being applied to the cell. I cannot find anything in the documentation that would indicate why. Is this a bug or am I doing something incorrectly?
fig, ax = plt.subplots(dpi=300)

ax.axis('off')
ax.axis('tight')

even_color='#9CDEF6'
odd_color='#6549DA'

cell_text = [[0.2] * 3, [0.1] * 3, [0.3] * 3]

labels=['Linear Regression', 'Bayesian Ridge', 'MARS']
columns = ['$R^2$', 'MAE', 'RMSE']

cell_colors = [[even_color] * len(columns) if i % 2 == 0 else [odd_color] * len(columns) for i in range(len(cell_text))]

table = ax.table(cellText=cell_text,
                      rowLabels=labels,
                      cellColours = cell_colors,
                      colLabels=columns,
                      loc='best', edges='open', cellLoc='center')

Answer: If it is okey for you, try to use closed edges.
table = ax.table(cellText = cell_text,
                 rowLabels = labels,
                 cellColours = cell_colors,
                 colLabels = columns,
                 loc = 'best', edges = 'closed', cellLoc = 'center')

I hope it will be useful.
Answer: Either you use closed edges as Polina suggested or you modify the underlying artist to set the edge line width to zero:
table = ax.table(cellText=cell_text,
                      rowLabels=labels,
                      cellColours = cell_colors,
                      colLabels=columns,
                      loc='best', edges='closed', cellLoc='center')
for c in table.properties()['celld'].values():
    c.set(linewidth=0)

And you get a table without cell borders


Proving Lebesgue integrability of a bounded function

Question:
Let $u:\mathbb{R}\to\mathbb{R}$ be a simple function such that \begin{equation} |u(x)|\le\frac{x^2}{1+|x|^3}\end{equation} for all $x\in\mathbb{R}$. Prove that $u$ is Lebesgue integrable.

My attempt: Note that $f(x):=\frac{x^2}{1+|x|^3}$ is measurable as the ratio of two measurable functions. Moreover, $|u(x)|\le f(x)$ and by the dominance principle $u(x)$ is integrable as it is simple and bounded above so its integral will be finite. This is sufficient for integrability. Is this correct?
Comment: Though bounded (and even tending to $0$), $f$ is not integrable at $\pm\infty.$
Comment: @AnneBauval but $u$ is simple so can only take finitely many values; does this resolve that issue?
Comment: Yes it does, since the support of $u$ will then be bounded. I think your title should rather be: "Proving Lebesgue integrability of a simple function which tends to $0$ at infinity".
Comment: Can we use dominance principle in addition to the fact there are only finitely many values? or can we just not use dominance at all here
Comment: if $\phi$ is a nonnegative Lebesgue integrable function and $f$ a measurable function such that $|f(x)|\le \phi(x)$ for almost all $x$ then $f$ is Lebesgue integrable
Comment: You cannot apply this to $f=u$
 and $\phi(x)=\frac{x^2}{1+|x|^3}$
 because (as pointed in my first comment where it was named $f$ like in your post) the latter is not integrable. I think your title should rather be: "Proving that if a simple function tends to $0$
 at infinity then its support is bounded".
Answer: Suppose $u=\sum\limits_{j=1}^{n}c_j\chi_{E_j}$ with $c _j \neq 0$ and $E_j$'s disjoint. Each $E_j$ is a bounded set: Otherwise,  $0< |c_j|\leq \frac {x_i^{2}}{1+|x_i|^{3}} \to 0$  along a sequence $(x_i)$ in $E_j$ tending to $\pm \infty$, a contradiction. Hence,  $u$ is integrable.
Answer: More generally, let $u$ be a measurable function such that
$$\lim_{\pm\infty}u=0\quad\text{and}\quad m{\bf1}_E\le|u|\le M{\bf1}_E$$
for some measurable set $E$ and positive constants $m,M.$
Since $\lim_{\pm\infty}|u|=0<m,$ there exists a constant $A$ such that for all $x\in\Bbb R,$
$$|x|>A\implies|u(x)|<m.$$
For such an $A$, we have $E\subseteq[-A,A]$ and
$$\int|u|\,d\lambda\le M\,\lambda(E)\le2AM<\infty$$
hence $u$ is integrable.


When importing a dependency script acts as it is in a different directory

Question: I have the following directory:
project
|
├──folder1
│  └── text_to_use.txt
│  └── file.py
|
├──folder2
|  └──file_to_import.py
|
└──more_files.py
file.py is using text_to_use.txt and usually works fine.
When importing file_to_import.py, file.py starts acting as if inside project instead of folder1.
file.py code:
from folder2.file_to_import import some_class
open("text_to_use.txt", 'r')

Error:
FileNotFoundError: [Errno 2] No such file or directory: 'text_to_use.txt'

note:
I'm using PyCharm. this also happens when I import the same dependency with other files in folder1.
I'm looking for an elegant solution, not something like:
import sys
sys.path.append('folder2.file_to_import')

Comment: If you do that, then presumably some code in `file_to_import` will break, because it had a reason for changing the directory...
Comment: That `open()` call uses a plain filename with no path, so it will always look in the current directory.  As a debugging step, you can print the result of `os.getcwd()` to see the current directory.  (Does `file_to_import.py` change the current directory?)
Comment: @JohnGordon you are correct. I tried calling ```os.getcwd()``` with and without ```file_to_import.py``` and I saw that the directory has changed.
What does it mean? Can you help me solve my problem with this information?
Comment: So it sounds like `file_to_import.py` has an `os.chdir()` call at the top level.
Comment: dosn't happen to me
Comment: Does it mean I need to call ```os.chdir()``` in my ```file.py``` to change the working directory again?
Comment: Then how can I fix my problem? What do you suggest?
Comment: It would be best if you don't change the current directory at all, and just use full paths to open any necessary files, instead of depending on those files being in the current directory.
Answer: file.py
from pathlib import Path

pa_to_use = Path(__file__).parent.parent / "folder2" / "text_to_use.txt"

with pa_to_use.open() as f_use:
  stuff = f_use.read()


Is it correct voice leading to move the same right hand chord shape down in contrary motion to the bass?

Question:
Here is a progression I wrote where you can see the right hand just moves down playing the same chord shape in CM to the bass. Is this good voice leading or is using 2 chords in the right hand with the same intervals a bad thing?
Answer: This is okay. As long as you're avoiding parallel fifths, moving chords like this is not only permitted, but it's fairly routine.
What is odd about the progression is not the movement, but the second chord. A more expected progression would have D in the bass.


Can jQuery deferreds be cancelled?

Question: I have a situation where I want to cancel a deferred. The deferred is associated with an ajax call.
Why I am using deferreds
I don't use the normal xhr objects returned by $.ajax. I'm using jsonp, which means I can't use HTTP status codes for error handling and have to embed them in the responses. The codes are then examined and an associated deferred object is marked as resolved or rejected accordingly. I have a custom api function that does this for me.
function api(options) {
  var url = settings('api') + options.url;
  var deferred = $.Deferred(function(){
    this.done(options.success);
    this.fail(options.error);
  });
  $.ajax({
    'url': url,
    'dataType':'jsonp',
    'data': (options.noAuth == true) ? options.data : $.extend(true, getAPICredentials(), options.data)
  }).success(function(jsonReturn){
    // Success
    if(hasStatus(jsonReturn, 'code', 200)) {
      deferred.resolveWith(this, [jsonReturn]);
    }
    // Failure
    else {
      deferred.rejectWith(this, [jsonReturn]);
    }
  });

  return deferred;
}

Why I want to cancel the deferred
There is an input field that serves as a filter for a list and will automatically update the list half a second after typing ends. Because it is possible for two ajax calls to be outstanding at a time, I need to cancel the previous call to make sure that it doesn't return after the second and show old data.
Solutions I don't like

I don't want to reject the deferred because that will fire handlers attached with .fail().
I can't ignore it because it will automatically be marked as resolved or rejected when the ajax returns.
Deleting the deferred will cause an error when the ajax call returns and tries to mark the deferred as resolved or rejected.

What should I do?
Is there a way to cancel the deferred or remove any attached handlers?
Advice on how to fix my design is welcome, but preference will be given to finding a way to remove handlers or prevent them from firing.
Comment: Your `.fail(jqXHR, textStatus, errorThrown)` handlers could just check whether `textStatus` is "abort".
Comment: Can you elaborate more? From what you said it looks like a bad design
Comment: A deferred either passes or fails. You can't cancel it or remove the handlers. Maybe there is a better way to do what you are trying to do.
Answer: Looking in the jQuery doc and code, I don't see any way to cancel a jQuery deferred.
Instead, you probably need a way in your resolveWith handler to know that a subsequent ajax call has already been fired and this ajax call should ignore its result.  You could do that with a globally incrementing counter.  At the start of your ajax call, you increment the counter and then you grab the value into a local variable or put it as a property on the ajax object.  In your resolveWith handler, you check to see if the counter still has the same value as when your ajax call started.  If not, you ignore the result. If it does, no new ajax calls have been fired so you can process the result.
Alternately, you could refuse to fire a new ajax call while one is in flight already so you never had more than one in flight at a time.  When the one finishes, you could either just use that result or fire the next one if desired.
Comment: I'd better go with `rejectWith`, but +1 for the idea
Comment: @zerkms - it depends upon where you want to do the duplicate detection. If that happens at the point where the code is deciding whether to reject or resolve, then perhaps rejectWith is a good idea with an argument indicating it's rejected because of a subsequent call.  If the dup detection happens in the resolved handler, then it's already been resolved so rejecting it isn't feasible.
Comment: And as another proposal: instead of counter I'd just pass `{ manuallyAborted: true }` 2 argument to `rejectWith`, since counter may cause race conditions in true multi-threading environments, which is not applicable to browsers and JS, at least yet ;-)
Comment: @zerkms - the counter is used to detect multiple ajax calls in flight when a result comes in.  If you get rid of the counter, how would you detect that?
Comment: well, I assumed that OP wants to perform `xhr.abort()` to cancel unnecessary request. From this point of view I see more logical place to put that logic - is `fail` handlers
Comment: I would just check if `{ manuallyAborted: true }` passed to the `fail` handler
Comment: @zerkms - OK, you made different assumptions than I did.  The OP didn't say anything about doing an `abort()`.
Comment: "I need to cancel the previous call to make sure that it doesn't return after the second and show old data".
Comment: @zerkms - My proposal cancelled it's effect by ignoring the result - different interpretation.  The OP can choose which way they want to go.
Comment: @zerkms request aborted with xhr.abort() may be out of sight in jQuery, but nevertheless the server will process till the end - design of http protocol!
Comment: @benzkji: "design of http protocol" --- could you please prove it with any reference to HTTP RFC that requires a server to finish process even if the connection was terminated? I haven't seen such a statement there ever.
Comment: @benzkji - it's not the design of the http protocol.  It is totally up to the server process for whether it does anything differently if the connection drops or if the main action on the server is ever even informed.  An http server could abort its process when the connection was dropped, but it is more likely that once the command is received from the client, that command is processed and only when it goes to send the response back does it realize that the connection has droppped.  It doesn't have to be that way, but that is the simplest server-side behavior.
Comment: as Erv Walter states in his comment on the accepted answer: http://stackoverflow.com/questions/446594/abort-ajax-requests-using-jquery (my "explanation" was a bit vague, I agree). to elaborate a bit: I think that jquery will not tell the server to terminate the connection, but just stop listening to it's response, at least this is my experience. no RFC, sorry.
Comment: @benzkji - I just stepped through the `xhr.abort()` method that jQuery provides for aborting an ajax call that is in progress.  It does follow through and call the `XMLHttpRequest.abort()` method which is supposed to terminate the connection.  As the `XMLHttpRequeset` object is only now getting a draft standard, I can't say what individual browsers are actually doing in that regard.  The Chrome network trace shows that the ajax call is actually cancelled.  As I think everyone now understands, cancelling the request doesn't force the server to do anything - it may still process the request.
Comment: @jfriend00 thx for that research - as you say, it's a draft. as for myself, thinking that "canceling" the request could avoid load on a server, this is, almost always today, not true...so I think it's important to keep that "detail" in mind.
Comment: @benzkji - the draft spec for the XMLHttpRequest object has absolutely nothing to do with the server behavior.  Once the server receives the request and starts processing it, it is unlikely to even know the socket has been closed until it starts sending back the response.  That would be the normal server process flow.  While a server could implement more advanced flow and somehow abort processing if the socket is closed while the processing is happening, that would require special design in the server process and would rarely (perhaps never) be the default behavior.
Answer: While you can't "cancel" a deferred like you want, you could create a simple closure to keep track of the last ajax call through $.ajax returning an jqXHR object. By doing this you can simply abort() the call when a new jqXHR comes in to play if the last one wasn't finished. In your code's case it will reject the jqXHR and leave the deferred open to be deleted as you initially wanted.
var api = (function() {
    var jqXHR = null;

    return function(options) {
        var url = options.url;

        if (jqXHR && jqXHR.state() === 'pending') {
            //Calls any error / fail callbacks of jqXHR
            jqXHR.abort();
        }

        var deferred = $.Deferred(function() {
            this.done(options.success);
            this.fail(options.error);
        });

        jqXHR = $.ajax({
             url: url,
             data: options.toSend,
             dataType: 'jsonp'
        });

        jqXHR.done(function(data, textStatus, jqXHR) {
            if (data.f && data.f !== "false") {
                deferred.resolve();
            } else {
                deferred.reject();
            }
        });

        //http://api.jquery.com/deferred.promise/
        //keeps deferred's state from being changed outside this scope
        return deferred.promise();
    };
})();

I've posted this on jsfiddle. If you wish to test it out. Set timeout is used in combination with jsfiddles delayer to simulate a call being interupted. You'll need a console enabled browser to see the logs.
On a side note switch any .success(), .error(), and complete() methods over to deferred methods done(), fail(), and always(). Via jquery/ajax

Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks will be deprecated in jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead as newer
Comment: Thanks for the heads up Artur. It would be helpful to mention why it won't work for the OP to edit or make a suggestion for the change.
Comment: I believe `jqXHR.abort()` triggers the `fail` function with `xhr.status === 0`, so you may want to also `reject()` your deferred inside of the `fail` / `error` function.
Answer: JustinY: seems like you're really close already to what you want. You're already using two deferreds (inner- > the ajax and outer -> $.Deferred()).  You're then using the inner deferred to decide how to resolve the outer deferred based on some conditions.
Well, so just don't resolve the outer deferred at all when you don't want to (maybe you have a boolean variable that serves as a toggle gate for allowing the inner dfd to resolve/reject at all).  Nothing bad will happen: whatever handlers you have attached to this entire function won't fire. Example in your inner success function:
if(gateOpen){
  gateOpen = false;
  if(hasStatus(jsonReturn, 'code', 200)) {
    deferred.resolveWith(this, [jsonReturn]);
  }
  else {
    deferred.rejectWith(this, [jsonReturn]);
  }
}

Some other logic in the application will decide when the gateOpen gets set back to true (some sort of _.throttle() or _.debounce() timeout, user interaction, whatever you want).If you wanted to track or cancel other requests in the else of that function, you could do that too. But the basic thing is that you don't have to resolve OR reject that outer deferred.  And that's the same as canceling it, even if you don't cancel/abort the inner one.
Answer: I've created a shim that seamlessly adds the ability to cancel deferred objects and ajax requests.
In short, once a deferred object has been canceled, resolutions/rejections are completely ignored, and the state becomes "canceled".
According to jQuery.com, "Once the object has entered the resolved or rejected state, it stays in that state." Therefore, attempts to cancel are ignored once a deferred object is resolved or rejected.
(function () {
    originals = {
        deferred: $.Deferred,
        ajax: $.ajax
    };

    $.Deferred = function () {

        var dfr = originals.deferred(),
            cancel_dfr = originals.deferred();

        dfr.canceled = false;

        return {
            cancel: function () {
                if (dfr.state() == 'pending') {
                    dfr.canceled = true;
                    cancel_dfr.resolve.apply(this, arguments);
                }
                return this;
            },

            canceled: cancel_dfr.done,

            resolve: function () {
                if ( ! dfr.canceled) {
                    dfr.resolve.apply(dfr, arguments);
                    return this;
                }
            },

            resolveWith: function () {
                if ( ! dfr.canceled) {
                    dfr.resolveWith.apply(dfr, arguments);
                    return this;
                }
            },

            reject: function () {
                if ( ! dfr.canceled) {
                    dfr.reject.apply(dfr, arguments);
                    return this;
                }
            },

            rejectWith: function () {
                if ( ! dfr.canceled) {
                    dfr.rejectWith.apply(dfr, arguments);
                    return this;
                }
            },

            notify: function () {
                if ( ! dfr.canceled) {
                    dfr.notify.apply(dfr, arguments);
                    return this;
                }
            },

            notifyWith: function () {
                if ( ! dfr.canceled) {
                    dfr.notifyWith.apply(dfr, arguments);
                    return this;
                }
            },

            state: function () {
                if (dfr.canceled) {
                    return "canceled";
                } else {
                    return dfr.state();
                }
            },

            always   : dfr.always,
            then     : dfr.then,
            promise  : dfr.promise,
            pipe     : dfr.pipe,
            done     : dfr.done,
            fail     : dfr.fail,
            progress : dfr.progress
        };
    };

    $.ajax = function () {

        var dfr = $.Deferred(),
            ajax_call = originals.ajax.apply(this, arguments)
                .done(dfr.resolve)
                .fail(dfr.reject),

            newAjax = {},

            ajax_keys = [
                "getResponseHeader",
                "getAllResponseHeaders",
                "setRequestHeader",
                "overrideMimeType",
                "statusCode",
                "abort"
            ],

            dfr_keys = [
                "always",
                "pipe",
                "progress",
                "then",
                "cancel",
                "state",
                "fail",
                "promise",
                "done",
                "canceled"
            ];

        _.forEach(ajax_keys, function (key) {
            newAjax[key] = ajax_call[key];
        });

        _.forEach(dfr_keys, function (key) {
            newAjax[key] = dfr[key];
        });

        newAjax.success = dfr.done;
        newAjax.error = dfr.fail;
        newAjax.complete = dfr.always;

        Object.defineProperty(newAjax, 'readyState', {
            enumerable: true,
            get: function () {
                return ajax_call.readyState;
            },
            set: function (val) {
                ajax_call.readyState = val;
            }
        });

        Object.defineProperty(newAjax, 'status', {
            enumerable: true,
            get: function () {
                return ajax_call.status;
            },
            set: function (val) {
                ajax_call.status = val;
            }
        });

        Object.defineProperty(newAjax, 'statusText', {
            enumerable: true,
            get: function () {
                return ajax_call.statusText;
            },
            set: function (val) {
                ajax_call.statusText = val;
            }
        });

        // canceling an ajax request should also abort the call
        newAjax.canceled(ajax_call.abort);

        return newAjax;
    };
});

Once added, you may cancel an ajax call:
var a = $.ajax({
        url: '//example.com/service/'
    });

a.cancel('the request was canceled');

// Now, any resolutions or rejections are ignored, and the network request is dropped.

..or a simple deferred object:
var dfr = $.Deferred();

dfr
    .done(function () {
        console.log('Done!');
    })
    .fail(function () {
        console.log('Nope!');
    });

dfr.cancel(); // Now, the lines below are ignored. No console logs will appear.

dfr.resolve();
dfr.reject();

Can jQuery deferreds be cancelled?


Como coletar tweets e followers pela API?

Question: Bem galera estou aqui de novo pesquisando sobre as api's em redes sociais, estou iniciando o twitter agora e estou tendo algumas dificuldades, preciso coletar perfis (id/nome) e junto com o perfil tenho que coletar os tweets e os followers, até onde eu sei a linguagem que da pra fazer isso é em php, não conheço muito, mas acho que é uma linguagem mais comum. Alguém conhece algum tutorial claro que possa ajudar? ou algum trecho de código que possa ajudar?
Grato.
Comment: Faltou o mais importante. Em que linguagem? Aproveita coloca um contexto do que quer fazer. Leia o [tour] e o [ask].
Comment: Desculpa cara, acho que agora está mais claro.
Comment: Amigão da uma olhada nesse cara https://storm.apache.org/ estou usando ele no meu tcc .. é bem legal!
Answer: Olá, sou o Luís, desenvolvedor evangelista do Twitter aqui no Brasil. O Twitter possui vários endpoints na API que permitem acessar o que você precisa. Não ficou claro a linguagem que você quer utilizar, mas vou dar o exemplo em PHP, já que você mencionou. Para conectar na API você precisa:

Criar uma app em apps.twitter.com
Obter as 4 chaves de acesso: consumer_key, consumer_secret, access_token_key, access_token_secret (na sua app em apps.twitter.com)
Configurar essas chaves na biblioteca que você vai utilizar:

A biblioteca mais recomendada para PHP é a tmhOAuth, veja um exemplo de como buscar tweets, disponível em https://github.com/themattharris/tmhOAuthExamples/blob/master/cli/search.php:
<code><?php
require __DIR__.DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'tmhOAuthExample.php';
$tmhOAuth = new tmhOAuthExample();
$code = $tmhOAuth->apponly_request(array(
  'method' => 'GET',
  'url' => $tmhOAuth->url('1.1/search/tweets'),
  'params' => array(
    'q' => 'tmhoauth'
  )
));
$tmhOAuth->render_response();
</code>
Você também pode obter o grafo de um usuário, como mostra o exemplo do mesmo repositório: https://github.com/themattharris/tmhOAuthExamples/blob/master/cli/followings.php
Sugiro dar uma olhada nas seguintes referências:

http://dev.twitter.com
http://t.co/libs
http://t.co/rest
https://dev.twitter.com/rest/reference/get/followers/list
https://dev.twitter.com/rest/reference/get/search/tweets
Comment: Luiz Boa Noite, eu estou tentando entender como trabalhar nessa questão mas ainda não estou entendendo como fazer a requisição pelo php, eu sei que precisa das keys e tokens, mas eu ainda não consegui coletar alguma coisa.


C# encrypt one set of credentials used on multiple devices

Question: I have an application that uses a specific user account which is logged on using LogonUser WINAPI.
What I now need is store the credentials in a secure way (not source code (in exe)) and get it on computers.
Users cannot get to the password - I can't have them input it. Actions done by this account are sensitive and launched in the background.
I was thinking about first hashing the password with a derived key from something installer specific and replacing a few bytes of the key with a generated salt used for hashing it to obfuscate it a bit further. This initial hash would be contained in the installer which would run a helper application that would get to the password and hash it using something computer specific resulting into a different hash on each device which is not related to the initial hash.
My question is, since all of these actions are basically hard coded (using byte arrays, not strings), how safe would it be? How to really approach this?
Comment: _"how safe would it be?"_ - not at all. _"How to really approach this?"_ - hide the actual action (and user) behind a service running on a server, and issue a call to said service as the current user.
Comment: If you need the actual password how the hash should help? Hash != encryption
Comment: `How safe would it be` really depends on what you are trying to achive and what you are trying to protoect.
Safety always needs to be prooprtional to the thing you want to protect, you dont put down a mine-field around your company if a fence is sufficient.
Haveing no idea what you want to protect id say everyone with a reasonable amount of time and an insentive to get in your system will be able to crack it. If your audience is mainly 5 year olds or there is not really an insentive to bypass the password this level of protection is probably fine.
Comment: The actions need to run on the local computer. It launches a third party application that cannot run under the system account and needs to display progress to the user as there are some reboots in between - a complicated set commands involving LogonUser, SetDACL on winsta and desktop objects etc. is needed and I do not see how these would be done remotely from the server. Securing the password is crucial as that would expose the account which is a local admin on all of the systems - tens of thousands.
Comment: Sounds like you need group policies, not an application that contains your local admin password.
Answer: I would use windows CredentialManager for this.
Login in with that user, open the CredentialManager and set the user/password pair, then access these values like here:
http://www.pinvoke.net/default.aspx/advapi32/CredRead%20.html
or with a wrapper like here:
https://www.nuget.org/packages/CredentialManagement
The credential manager encrypts internaly the values with DPAPI (key based on your account key).


Error in directive dragula update hook: "TypeError: Cannot read property 'drake' of undefined"

Question: I used vue-dragula in my project for the drag & drop list requirement.
It's worked perfect. But I have the below error at that hold element remove time.

Error in directive dragula update hook: "TypeError: Cannot read
property 'drake' of undefined"

My code sample below
(template HTML code)

{{drDatas.name}}

(Script code)
import 'vue-dragula/styles/dragula.css';

created () {
  Vue.vueDragula.options('action-bag', {
    invalid: function (el, handle) {
      return // CONDITION BASED
    }
  });
},

mounted () {
  const self = this;
  Vue.vueDragula.eventBus.$on('drop', async function ([bag, curElmt, allElmts]) {
    // drop event based functionalities
  })
}

Answer: I believe that it will be much easier for you to use the vanilla Dragula library instead of the Vue-Dragula wrapper. This will save you from a lot of headaches and will also reduce the bundle size.
I am using it like this:
import dragula from 'dragula'

data()
{
  return {
    stages: { // we have 5 lists - items can be dragged between any 2 of them
      LEAD_IN: [],
      HOMEOWNER_ADDED: [],
      PROPOSAL_GENERATED: [],
      WON: [],
      LOST: [],
    },
    drake: null,
  }
},
mounted()
{
    // IMPORTANT !!! prevent default image dragging for IE which interferes badly with Dragula
    document.ondragstart = function () {
      return false
    }
    this.drake = dragula({
      isContainer: this.dragContainer,
      moves: this.dragMoves,
      accepts: this.dragAccept,
      mirrorContainer: document.getElementById('app'), //eslint-disable-line
    })
    this.drake.on('drop', this.drakeDrop)
    this.drake.on('drag', this.drakeStart)
    this.drake.on('over', this.drakeOver)
    this.drake.on('out', this.drakeStop)
    this.drake.on('cancel', this.drakeStop)
},
methods:
{
    dragContainer(el) {
      // defines containers for draggable items
      return 'kind' in el.dataset
    },
    dragMoves(el, source, handle, sibling) {
      // allows dragging only by using the HANDLE
      return 'move' in handle.dataset
    },
    dragAccept(el, target, source, sibling) {
      // only containers can accept draggable items
      return 'kind' in target.dataset
    },
    drakeStart(el, source) {
      // indicate which container's item we have started dragging
      source.classList.add('drag_src')
    },
    drakeOver(el, container, source) {
      source.classList.add('drag_src')
      container.classList.add('drag_dst')
    },
    drakeStop(el, container, source) {
      source.classList.remove('drag_src')
      container.classList.remove('drag_dst')
    },
    drakeDrop(el, target, source, sibling) {
      // EL was dropped into TARGET before SIBLING and originally came from SOURCE
      this.drake.cancel(true) // !!! very important - we do not want Dragula to mess with the DOM as it will confuse Vue
      if (source !== target) {
        // update arrays
        const task = this.stages[source.dataset.kind].splice(el.dataset.index, 1)[0]
        const dst = this.stages[target.dataset.kind]
        dst.splice(sibling ? sibling.dataset.index : dst.length, 0, task)
        this.updateTask(task, target.dataset.kind)
      }
    },
    updateTask(task, newStage) {
      this.loading = true
      this.$axios
        .post('/houses/stages', {
          lead_id: task.lead.id,
          kind: newStage,
        })
        .then(() => {
          this.loading = false
        })
        .catch((error) => {
          this.loading = false
          events.$emit(TOAST_ERROR, error.message || error)
        })
    },
}

Template for each of the lists is

this is the drag HANDLER

      <button>some action, eventually</button>

The kind prop should match (in my particular case) with the properties of the this.stages object.
And some handy styles
.task_item {
  cursor: grabbing;
}
.task_list .task_item {
  cursor: default;
}
.task_list .task_item .content_move {
  cursor: move;
}
.task_list.drag_dst {
  border: 1px solid green;
}
.task_list.drag_src.drag_dst {
  border: 1px solid red;
}

Answer: I fixed this issue with hide and show the parent component.


Error when performing autoregressive GEE in Python

Question: Although this question is a programming question and would, therefore, be more suitable for StackOverflow, I would like to address the question over here given that it is the result of a rather unknown method for non-statisticians, and I was hoping other people may have encountered the same issue.
I am testing the GEE with a small dataset in Python. When I use the independent or exchangeable covariance matrix, it works perfectly fine. However, when I attempt to use the autoregressive covariance matrix, I get a # ValueError: Not a bracketing interval. What may be the reason for that error?
The dataset consists of several different variables, but has only five samples. In the GEE, I use one group, and the time variable is the cumulative sum of dur_int_sec:
    eda_t_filt         SDNN  dur_int_sec
0    -0.181794   126.970082    65.691406
1     0.130116   130.083402    98.619141
2    -0.106355   113.451393   129.865234
3     0.005535    90.197269   343.261719
4     0.013384   112.712131   241.161132

# The code
ar = sm.cov_struct.Autoregressive()
gee_by_task_ar = sm.GEE.from_formula("SDNN ~ eda_t_filt", \
    groups=np.ones(5), data=by_task, time=np.cumsum(by_task.dur_int_sec), cov_struct=ar)
gee_by_task_ar_res = gee_by_task_ar.fit() # ValueError: Not a bracketing interval.

The complete error:
Traceback (most recent call last):
  File "<pyshell#50>", line 1, in <module>
    gee_by_task__ar_res = gee_by_task_ar.fit() # ValueError: Not a bracketing interval.
  File "D:\Python27\lib\site-packages\statsmodels\genmod\generalized_estimating_equations.py", line 1113, in fit
    self._update_assoc(mean_params)
  File "D:\Python27\lib\site-packages\statsmodels\genmod\generalized_estimating_equations.py", line 1261, in _update_assoc
    self.cov_struct.update(params)
  File "D:\Python27\lib\site-packages\statsmodels\genmod\cov_struct.py", line 768, in update
    self.dep_params = brent(fitfunc, brack=[b_lft, b_ctr, b_rgt])
  File "D:\Python27\lib\site-packages\scipy\optimize\optimize.py", line 2003, in brent
    res = _minimize_scalar_brent(func, brack, args, **options)
  File "D:\Python27\lib\site-packages\scipy\optimize\optimize.py", line 2035, in _minimize_scalar_brent
    brent.optimize()
  File "D:\Python27\lib\site-packages\scipy\optimize\optimize.py", line 1841, in optimize
    xa, xb, xc, fa, fb, fc, funcalls = self.get_bracket_info()
  File "D:\Python27\lib\site-packages\scipy\optimize\optimize.py", line 1829, in get_bracket_info
    raise ValueError("Not a bracketing interval.")
ValueError: Not a bracketing interval.

Answer: The variables in your model formula do not exist in the data you provided, so I'm not sure what you are trying to do here.
But in general, I have seen this AR covariance structure fail when the data are  a poor fit to the AR model.  The error message could be improved, but I suspect that is what is going on here.
Comment: Selected the wrong columns excuse me. But you think the problem could be that there is too little data?


What decides if a faceoff is Won or Lost?

Question:
How is a Faceoff decided as a won faceoff, or a lost faceoff? Is it all which center get the puck where he wants, or is it decided by another factor?
Answer: It is not determined until possession is determined.
While it is possible that a center will win the faceoff by succeeding to draw the puck back to one of his teammates, if his team cannot maintain possession through the ensuing play, then the other team is awarded the faceoff won.


Given function π, prove that seg(x) is a well ordered set

Question: (ZF) Let $\langle A,\le \rangle$ be a linear ordered set. Let the function $π : \mathscr{P}(A) \to \mathscr{P}(A)$ be defined by:
$$π(X) = \{y ∈ A : \mathrm{seg}(y) \subseteq X\}$$
Prove that $π$ is monotonic and if that $A^*$ is the smallest fixed point of  $π$, then for each $x ∈ A$ the following equivalence holds:
$$x \in A^* \iff \langle \mathrm{seg}(x), {\le} \cap(\mathrm{seg}(x)×\mathrm{seg}(x))\rangle \text{ is a well ordered set}$$
What I have in mind is the following:
To use Tarsky's theorem about fixed points which states that: if π is a monotonic function, defined in P(A),  there exists a point x in P(A) for which π(x)=x.
I will name this point A.
Then if I consider π to be a linear operator, I think that I will have to prove that π preserves the order, namely: π(x)<π(y) for x<y. So in this way I will get π to be an increasing function with lower bound π(A)=A.
Is it correct, can you please help me to solve this problem?
Thank you in advance!
Answer:
To use Tarsky's theorem about fixed points which states that: if π is a monotonic function, defined in P(A), there exists a point x in P(A) for which π(x)=x. I will name this point A.

The problem already gives you $A^*$. It is unclear why you want to introduce another fixed point "A".

Then if I consider π to be a linear operator,

What is a linear operator (in this context)? I usually encounter this when there is a vector space.

I think that I will have to prove that π preserves the order, namely: π(x)<π(y) for x<y. So in this way I will get π to be an increasing function with lower bound π(A)=A.

Let me break down your task for this assignment.

Prove $\pi$ is order-preserving/monotonic i.e. for all $S,T\in\mathscr{P}(A)$, if $S\subseteq T$, then $\pi(S)\subseteq \pi(T)$.
Prove the equivalence "$\iff$" statement assuming $A^*$ is already given. From (1.) and by Tarski's theorem, one already knows $A^*$ exists.

$$x \in A^* \iff \langle \mathrm{seg}(x), {\le} \cap(\mathrm{seg}(x)×\mathrm{seg}(x))\rangle \text{ is a well ordered set}$$
Hints:

$\pi(S)=\{y\in A:\mathrm{seg}(y)\subseteq S\}$ and $\pi(T)=\{y\in A:\mathrm{seg}(y)\subseteq T\}$
$x\in A^*\Leftrightarrow x\in \pi(A^*)$.
For the forward implication, it is enough to show that the sublinear ordered set $\langle A^*, \le... \rangle$ is well ordered. Suppose it is not; by contradiction take a nonempty subset $S$ without a least element. Without loss of generality suppose $S$ is upward closed i.e. if $s\in S$ and $s\le x$ then $x\in S$. Consider the complement $A^*\setminus S$. It can be shown that this complement is a $\pi$-fixed-point resulting in a contradiction to the fact that $A^*$ is the least fixed point.
For the reverse implication, it is enough to show $\mathrm{seg}(x)\subseteq A^*$.
This is straight-forward. Suppose by contradiction it is not true. Then there exists $s<x$ such that $s\notin A^*$. If you take the smallest such $s$, then the contradiction is within reach if you recall $\pi(A^*)=A^*$.
Comment: Thank you so much! I was using Tarski's Th for point A*, I just wrote A by an accident. Also, I have assumed that pi is an linear operator in order to make use of its properties, even though there are of no importance in this problem.