Fix Expected Singleton Error on Odoo14/Flectra

Question: I have a problem where I have a lot of data records, and when I try to download more than 1 data record an error always appears which basically looks like this
File "c:\\users\\it uw\\odoo14\\mspcustomaddons\\l10n_id_efaktur\\models\\account_move.py ", line 136, in download_efaktur
self.\_generate_efaktur(',')
File "c:\\users\\it uw\\odoo14\\mspcustomaddons\\l10n_id_efaktur\\models\\account_move.py", line 296, in \_generate_efaktur
output_head = self.\_generate_efaktur_invoice(delimiter)
File "c:\\users\\it uw\\odoo14\\mspcustomaddons\\l10n_id_efaktur\\models\\account_move.py", line 144, in \_generate_efaktur_invoice
company_id = self. company_id
File "C:\\Users\\IT UW\\odoo14\\flectra\\flectra\\fields.py", line 947, in __get__
record. ensure_one()
File "C:\\Users\\IT UW\\odoo14\\flectra\\flectra\\models.py", line 4437, in ensure_one
raise ValueError("Expected singleton: %s" % self)
ValueError: \<class 'ValueError'\>: "Expected singleton: account. invoice(35590, 35589, 35588, 35587)" while evaluating
'action = records.download_effect()'

And here is the code
@api.multi
def download_efaktur(self):
    """Collect the data and execute function _generate_efaktur."""
    for record in self:
        if record.state == 'draft':
            raise ValidationError(_('Could not download E-faktur in draft state'))
        if record.partner_id.l10n_id_pkp and not record.l10n_id_tax_number:
            raise ValidationError(_('Connect %(move_number)s with E-faktur to download this report',
                                  move_number=record.name))

    self._generate_efaktur(',')
    return self.download_csv()

@api.multi
def _generate_efaktur(self, delimiter):
    if self.filtered(lambda x: not x.l10n_id_kode_transaksi):
        raise UserError(_('Some documents don\'t have a transaction code'))
    if self.filtered(lambda x: x.type != 'out_invoice'):
        raise UserError(_('Some documents are not Customer Invoices'))

    output_head = self._generate_efaktur_invoice(delimiter)
    my_utf8 = output_head.encode("utf-8")
    out = base64.b64encode(my_utf8)

    attachment = self.env['ir.attachment'].create({
        'datas': out,
        'name': 'efaktur_%s.csv' % (fields.Datetime.to_string(fields.Datetime.now())
                                                   .replace(" ", "_")),
        'type': 'binary',
        })

    for record in self:
        record.message_post(attachment_ids=[attachment.id])
    self.l10n_id_attachment_id = attachment.id
    return {
            'type': 'ir.actions.client',
            'tag': 'reload',
        }

I have tried to change the looping logic in the download_efaktur() method and also the generate_efaktur() method
but the error still appears.
Answer: The error seems to be in this line
File "c:\users\it uw\odoo14\mspcustomaddons\l10n_id_efaktur\models\account_move.py", line 144, in _generate_efaktur_invoice
company_id = self.company_id
You haven't showed the code of the method _generate_efaktur_invoice
But when you make the call to:
output_head = self._generate_efaktur_invoice(delimiter)

Seems that self it's a recordset of more than one record so the code self.company_id will raise an error because it will call to self.ensure_one() as part of the ORM operations to retrieve the value of the company_id field that expect to be from only one record
Comment: @api.multi
    def _generate_efaktur_invoice(self, delimiter):
        """Generate E-Faktur for customer invoice."""
        # Invoice of Customer
        for invoice in self:
            company_id = self.company_id
            dp_product_id = self.env['ir.config_parameter'].sudo().get_param('sale.default_deposit_product_id')

 output_head = '%s%s%s' % (
                _csv_row(FK_HEAD_LIST, delimiter),
                _csv_row(LT_HEAD_LIST, delimiter),
                _csv_row(OF_HEAD_LIST, delimiter),
            )

is in that code?
Comment: yes, check it there


Why do people look directly at the keyboard when playing piano in videos?

Question: Ok so lately I have been wanting to play music from some of my favorite shows. When I play something that isn't mainstream it can be kinda hard to find sheet music on a website so I find a video that links it. I tend to look/listen at people actually playing the song to get a real-world piano sound to help me get a sense of what it should sound like, I know that sounds weird.
One thing that I have noticed, in the videos where people show their hands when playing and face, is that the player looks directly at their hands whilst playing the song (or piece depending on if it's an intro or not).
I think they may have either memorized the sheet music or played by ear, but still, I am being taught to try not to look at my hands. Am I being taught wrong or am I just confused? If so, can you explain what I am missing?
Comment: Regardless of whether or not it's "bad" to look at your hands while playing, it can be very helpful to practice playing without looking at your hands at all, either by closing your eyes or making yourself look at something up above the piano.
Comment: I do it by turning the lights off.First task: find the piano.
Comment: I think it's worth keeping in mind that not all videos on Youtube show good technique, and not all sheet music found on a website is well transcribed.
Comment: Does this answer your question? [Is it bad practice to look at hands when practicing piano? How to break the habit?](https://music.stackexchange.com/questions/83151/is-it-bad-practice-to-look-at-hands-when-practicing-piano-how-to-break-the-habi)
Comment: If you want to improve your ability to play without looking, practice scales and arpeggios.
Comment: I'm maybe not enough of a musician to make this claim myself, but isn't it a bit contradictory that you yourself prefer getting an actual look at someone playing the song, yet judge those people based on them looking at themselves playing the song?
Comment: @Flater No, I don't judge them negatively. I just try to get my technique correct (beginner things) and it just confused me since I am being taught not to do so. I was wondering if I'm doing it wrong, I just asked for clarification. Also, I don't really see those videos much so I don't witch hunt them or something. I don't know why you thought that, maybe you didn't read my whole description of the situation.
Comment: @ojs I am now aware of the technique part, but thank you. And for the sheet music, it's really hard to find sheet music for certain songs I like in a store or online since they are covers of a certain song or they are from a non-American show. And even a lot of non-classical music is really hard to find in my area. So I gotta work with what I've got ya feel me?
Comment: I understand. It's just that Youtube has even less quality control than any traditional publisher. So, if something looks or sounds wrong, it might be wrong. If it looks right, it might still be wrong. And finally, if something looks wrong, it might be right or just work really well for them. Here's someone looking at their hands in incredibly slouched posture: https://www.youtube.com/watch?v=ySq76KD1gZA
Comment: I see, what I do if sheet music on there sounds wrong is that I try to change it in a way. Like if the sheet music for a song has a note that is off then I try to change it to make it sound right to me. And I have been told not to go off of everyone I see after I messaged my teacher thing (she doesn't exactly teach me since it's not her job.) So I understand your point, thank you.
Answer: The way I was taught was also to avoid looking at my hands; however, in some cases, it makes sense to look at my hands instead of somewhere else. In my opinion, at least from the teachers I've had, the point is to avoid reliance on looking at your keyboard. Relying on manually positioning based on sight slows you down compared to having the muscle memory for certain things like common scales, chords, etc. It's similar to typing on a computer keyboard.
It is also impossible to sight-read or even play music you haven't memorized if you are reliant on looking at your keys, since you obviously can't look at the score and the keyboard simultaneously, and jumping between the two means you're more likely to miss something on the score or miss a note, possibly both.
I personally think striking your own balance is really the most important part. As long as you are able to play most things off of your muscle memory and you can find intervals, chords, and steps without needing to check your keyboard, I'd say you're doing fine. I usually don't need to look at my keyboard, but some of the songs I play have a lot of pretty decent jumps (couple of octaves) and so I'll often look at my keyboard to make sure I'm hitting them right.
TL;DR: there's no objectively "right" way to do it; I think it's pretty reasonable to assert that you have to be able to play without relying on your sight always, which is probably what most teachers are encouraging, but I don't think it's productive to subscribe to the idea that you should never at all look at your hands.
Comment: It's similar to touch typing, but far more complex. With touch typing, the two hands don't need to move laterally, although the fingers occasionally need to.Playing piano, they all need to move considerably more.
Answer: Depends what you're doing! When sight-reading, looking at hands/fingers/keyboard is usually not a good idea, as there's a tendency to lose one's place on the sheet.
When one knows a piece fairly well, particularly when it's, for example, a jumpy bass pattern, it makes sense to look at what's happening on the keys, at least until some form of 'muscle memory' kicks in.
When performing to an audience, it's good to be able to look at that audience at least from time to time or even the conductor - by then, there should be no need to check the dots, or keep looking at the keyboard.
If your teacher is adamant that one path is followed - do ask the question why, and expect a reasoned answer.
Comment: The answer to that lies in the first paragraph.
Comment: My teacher and some friends and family with experience in music said that it's good to not keep your eyes glued to the keyboard because for some things I won't be able to pay attention to the keyboard because I will be reading music or I will be looking at someone. They said that you can glance at the keyboard just using your eyes just don't keep your eyes stuck to the keyboard. Did they give me a good reason?
Comment: oh I see, I apologize for my ignorance in this.
Answer: Firstly, is it necessary to look at your hands?
Well, not if these blind pianists are anything to go by.  5 Famous Blind Piano Players You Should Know
Ray Charles, Stevie Wonder, Art Tatum, George Shearing, Nobuyuki Tsujii.
Here is a video of Nobuyuki Tsujii playing Chopin - Etude Op. 10 No. 12 'Revolutionary'
Secondly, do highly skilled pianists look at their hands?
Yes. Can they play without looking? Here is Sophie Druml trying to play blindfold. She makes quite a few mistakes but remarkably the fast passage seems to be more accurate - at least initially. Chopin: Etude Op. 25 No. 11 Blindfold It's easy to imagine that, with practice, she could play blindfold perfectly.

So who does play without looking?
Very often, it's singers. They know the importance of looking at the audience or into the camera in order to get the words across. Here's Elton John looking into the camera while playing. Sorry seems to be the hardest word
And here's Billy Joel My Life (Official Video)

Answer
Is it wrong to look at your hands? No.
Is it useful to be able to play without looking? Yes.
When should you play without looking? When singing for an audience or when sight-reading (although even then it's okay to look down for the difficult bits.)
If you want to have fun, try asking your teacher to play something difficult with a blindfold!!! Props to them if they can do it.
Comment: To a certain extend, you need to play large parts of sufficiently difficult pieces without looking, even when you are looking: Stuff is happening so fast right and left that it's impossible to have your eyes on both hands. It definitely helps when you have at least one hand trained to play what it needs to play without any visual control.
Answer: Look at your hands to aim during a leap.  Otherwise, prefer feel to eyesight.  The spacing of the black keys tells your fingers how to refine their aim.  If you're staying within four or five octaves and not playing something designed to show off your virtuosity, you should rarely need to glance at your hands.
Historically, the piano's keyboard grew higher and lower, unlike other keyboard instruments.  In the classical tradition, organists play from sheet music.  But unlike organists (and oboists and ophicleidists), pianists are expected to play from memory, because especially in the late Romantic repertoire their hands are so mobile that their eyes are needed for aiming.
The composers of that period knew this.  Leaps are common, but a set of simultaneous leaps in both hands is surpassingly rare, fiendish to learn, and devastatingly effective when mastered.
Organists are also encouraged to not look at their feet, to play by feel.  But because they don't play barefoot, their sense of touch is diminished.  Videos of even top organists betray the occasional glance downward.  But just a glance, not a stare.

The videos you've seen may "cheat," particularly for a pianist who's also singing.  For dramatic effect the video track might temporarily switch to something that was video-recorded afterwards to match the final audio recording, like "lip sync."  Suspect that, especially if the view changes to one that emphasizes the face and hides detailed finger movement.
Answer: Some teachers emphasize not looking at your hands as a way of reinforcing playing sheet music at sight. However, this varies amongst teachers: some encourage hand-looking, some are neutral, some are against.
However, outside of learning to sight-read, one plays however it works best for that individual. I look at my hands and the keyboard a great deal, because the visual cues are helpful to me in "seeing" chords or other patterns, or in gauging distances.
Sometimes I look at the music, sometimes my hands, sometimes off into space, and sometimes close my eyes altogether.
Comment: 'However it works best for that individual' is rather hard to judge, especially when you are at a beginner or intermediate level. Many players (myself included) are not aware of what it is about their technique that is holding them back.
Answer: I'm self taught on piano, so I'm just using experience and intuition here, but I would say it's good to look at your hands so long as you've very intentional about it.
If you're learning a tricky section, learning with each hand independently, you obviously can't rely on sight for both hands. So making decisions bar by bar about where your eyes should be, based on your strengths and weaknesses is part of the practise.
Answer: Depends also a bit on why and how the video is made.
In any professionally made video, you simply do whatever the director tells you. You get shot in various different ways, from various different angles, looking in various different direction with different expression etc. And in the end they just cut it together, in whatever the director feels looks best.
Answer: You need to learn both: looking and not looking. "Looking" comes naturally, so your teacher is focusing on the latter.
In real life you will use a mixture of both, and for challenging pieces you might have to develop a strategy, like: "I need to look at my right hand in this bar, then take a glimpse at the left one in that bar".
Generally:

for bigger jumps and when both hands change position - looking works
well,
for quick runs that relay on finger position - you play by the
feel,
for stride, hand is quicker than the eye... but sometimes I need to look at one "side" (just the bass note or just the chord)
for improvisation and cantilena pieces (I mean like Chopin's nocturnes)- looking at the hand playing the melody helps me focus.


Problemas em executar Buildozer kivy

Question: Poderiam me ajudar? Eu estou a vários dias tentando executar o buildozer na maquina virtual configurada pelo próprio kivy, contudo todas as soluções que achei na net e implementei, me retorna o mesmo erro como escrito no código abaixo. Eu aceito até mesmo um programa que seja uma alternativa ao buildozer tbm.
<code>[INFO]:    STDOUT (last 20 lines of 213):
    jnius/jnius.c:331:82: note: expanded from macro '__Pyx_PyCode_New'
  ...PyCode_New(a, 0, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)
     ~~~~~~~~~~                                                             ^~~~
/home/kivy/Desktop/nova/.buildozer/android/platform/build-armeabi-v7a/build/other_builds/python3/armeabi-v7a__ndk_target_21/python3/Include/code.h:122:12: note:
      'PyCode_New' declared here
PyAPI_FUNC(PyCodeObject *) PyCode_New(
           ^
jnius/jnius.c:57497:9: error: too many arguments to function call, expected 15,
      have 16
        __pyx_empty_bytes  /*PyObject *lnotab*/
        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
jnius/jnius.c:331:82: note: expanded from macro '__Pyx_PyCode_New'
  ...PyCode_New(a, 0, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)
     ~~~~~~~~~~                                                             ^~~~
/home/kivy/Desktop/nova/.buildozer/android/platform/build-armeabi-v7a/build/other_builds/python3/armeabi-v7a__ndk_target_21/python3/Include/code.h:122:12: note:
      'PyCode_New' declared here
PyAPI_FUNC(PyCodeObject *) PyCode_New(
           ^
6 warnings and 16 errors generated.
error: command '/home/kivy/.buildozer/android/platform/android-ndk-r19c/toolchains/llvm/prebuilt/linux-x86_64/bin/clang' failed with exit status 1
[INFO]:    STDERR:

[INFO]:    COMMAND:
cd /home/kivy/Desktop/nova/.buildozer/android/platform/build-armeabi-v7a/build/other_builds/pyjnius-sdl2/armeabi-v7a__ndk_target_21/pyjnius && /home/kivy/Desktop/nova/.buildozer/android/platform/build-armeabi-v7a/build/other_builds/hostpython3/desktop/hostpython3/native-build/python3 setup.py build_ext -v

[WARNING]: ERROR: /home/kivy/Desktop/nova/.buildozer/android/platform/build-armeabi-v7a/build/other_builds/hostpython3/desktop/hostpython3/native-build/python3 failed!
# Command failed: /usr/bin/python3 -m pythonforandroid.toolchain create --dist_name=myapp --bootstrap=sdl2 --requirements=python3,kivy --arch armeabi-v7a --copy-libs --color=always --storage-dir="/home/kivy/Desktop/nova/.buildozer/android/platform/build-armeabi-v7a" --ndk-api=21
# ENVIRONMENT:
#     LS_COLORS = 'rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=00:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.zst=01;31:*.tzst=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.wim=01;31:*.swm=01;31:*.dwm=01;31:*.esd=01;31:*.jpg=01;35:*.jpeg=01;35:*.mjpg=01;35:*.mjpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.m4a=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.oga=00;36:*.opus=00;36:*.spx=00;36:*.xspf=00;36:'
#     LESSCLOSE = '/usr/bin/lesspipe %s %s'
#     XDG_MENU_PREFIX = 'xfce-'
#     LANG = 'en_ZA.UTF-8'
#     GDM_LANG = 'en_US'
#     DISPLAY = ':0.0'
#     GTK_OVERLAY_SCROLLING = '0'
#     COLORTERM = 'truecolor'
#     JAVA_HOME = '/usr/lib/jvm/java-8-openjdk-amd64'
#     XDG_VTNR = '7'
#     SSH_AUTH_SOCK = '/run/user/1000/keyring/ssh'
#     MANDATORY_PATH = '/usr/share/gconf/xubuntu.mandatory.path'
#     GLADE_CATALOG_PATH = ':'
#     XDG_SESSION_ID = 'c1'
#     XDG_GREETER_DATA_DIR = '/var/lib/lightdm-data/kivy'
#     USER = 'kivy'
#     GLADE_MODULE_PATH = ':'
#     DESKTOP_SESSION = 'xubuntu'
#     DEFAULTS_PATH = '/usr/share/gconf/xubuntu.default.path'
#     QT_QPA_PLATFORMTHEME = 'gtk2'
#     PWD = '/home/kivy/Desktop/nova'
#     HOME = '/home/kivy'
#     SSH_AGENT_PID = '1389'
#     QT_ACCESSIBILITY = '1'
#     XDG_SESSION_TYPE = 'x11'
#     XDG_DATA_DIRS = '/usr/share/xubuntu:/usr/share/xfce4:/usr/local/share:/usr/share:/var/lib/snapd/desktop:/var/lib/snapd/desktop:/usr/share'
#     XDG_SESSION_DESKTOP = 'xubuntu'
#     GLADE_PIXMAP_PATH = ':'
#     CLUTTER_BACKEND = 'x11'
#     SHELL = '/bin/bash'
#     VTE_VERSION = '5202'
#     TERM = 'xterm-256color'
#     XDG_SEAT_PATH = '/org/freedesktop/DisplayManager/Seat0'
#     XDG_CURRENT_DESKTOP = 'XFCE'
#     GPG_AGENT_INFO = '/run/user/1000/gnupg/S.gpg-agent:0:1'
#     XDG_SEAT = 'seat0'
#     SHLVL = '1'
#     LANGUAGE = 'en_ZA:en'
#     WINDOWID = '58723411'
#     GDMSESSION = 'xubuntu'
#     LOGNAME = 'kivy'
#     DBUS_SESSION_BUS_ADDRESS = 'unix:path=/run/user/1000/bus'
#     XDG_RUNTIME_DIR = '/run/user/1000'
#     XAUTHORITY = '/home/kivy/.Xauthority'
#     XDG_SESSION_PATH = '/org/freedesktop/DisplayManager/Session0'
#     XDG_CONFIG_DIRS = '/etc/xdg/xdg-xubuntu:/etc/xdg:/etc/xdg'
#     PATH = '/home/kivy/.buildozer/android/platform/apache-ant-1.9.4/bin:/bin:/home/kivy/bin:/home/kivy/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin'
#     SESSION_MANAGER = 'local/kivy-complete:@/tmp/.ICE-unix/1407,unix/kivy-complete:/tmp/.ICE-unix/1407'
#     LESSOPEN = '| /usr/bin/lesspipe %s'
#     _ = '/usr/local/bin/buildozer'
#     PACKAGES_PATH = '/home/kivy/.buildozer/android/packages'
#     ANDROIDSDK = '/home/kivy/.buildozer/android/platform/android-sdk'
#     ANDROIDNDK = '/home/kivy/.buildozer/android/platform/android-ndk-r19c'
#     ANDROIDAPI = '27'
#     ANDROIDMINAPI = '21'
#
# Buildozer failed to execute the last command
# The error might be hidden in the log above this error
# Please read the full log, and search for it before
# raising an issue with buildozer itself.
# In case of a bug report, please add a full log with log_level = 2
</code>
Comment: uma função esta recebendo 16 argumentos, mas era para ser 15. parece que o erro esta num arquivo .c, vc pode fazer oq indica na ultima linha e ativar o log completo e reportar um bug
Answer: Eu resolvi meu problema depois de abandonar a maquina virtual que baixamos no site do Kivy, acabei baixando uma imgem de Lubunto limpa e instalando o buildozer e suas dependencias.... após isso deu tudo certo

Problemas em executar Buildozer kivy


For a finite structure $\mathfrak A$ in an *infinite* language, is $Th \mathfrak A$ decidable?

Question: In Enderton's logic, Theorems 26C and 26D, the assumption is that the first order language is finite.
Theorem 26C: For a finite structure $\mathfrak A$ in a finite language, $Th \mathfrak A$ is decidable.
Theorem 26D: For a finite language, $\{\sigma | \sigma \text{ has a finite model} \}$ is effectively enumerable.
Is a finite language a necessary assumption in these two theorems? So long as the universe of some structure is finite, one could build a tree from the finite sentence $\sigma$ and evaluate all the leaves with the values from the universe.
If a sentence of the form $\forall c \phi(c)$, where c referred to constants is allowed, then a finite language would be a necessary assumption. But I believe that $\forall$ can only range over variables.
Comment: I think it is important that you clarify whether $\sigma$ is a single sentence or a (possibly infinite) set of sentences. 26D is false on the latter reading.
Comment: @RobArthan 26D is *meaningless* on the latter meaning; what does it mean to say that a collection of possibly infinite sets is c.e.? This doesn't need clarification.
Comment: @NoahSchweber:  I just read "$\sigma$ has a finite model" with no constraint on whether $\sigma$ is a single sentence or a set of sentences.  The idea of collection of sets whose characteristic functions are encoded by an r.e. set of encodings of recursive functions sounds like a reasonable thing to me. I thought the question would be improved by a minor clarification.
Answer: Note that in order to make sense of computability-flavored questions around infinite languages, we need to think of symbols as being represented by natural numbers in some reasonable way. This is something we can ignore when the language is finite, but with infinite languages it's important.

Theorem $26D$ makes no real use of the finiteness of the language. This is because every sentence can only use finitely many symbols. Really the only way complexity can enter the picture is if the language we're looking at is itself of high complexity, in which case the set of sentences in that language itself (not even thinking about the set of sentences in that language with finite models, yet) will be of high complexity. But this has nothing to do with the finite model property. A bit more precisely, as long as $\Sigma$ is a computable language, the set of $\Sigma$-sentences which have finite models is c.e. - given a computable language $\Sigma$ and a $\Sigma$-sentence $\sigma$, let $\Sigma_0$ be the finite fragment of $\Sigma$ which actually appears in $\sigma$ and search through the finite $\Sigma_0$-structures for one satisfying $\sigma$.

Theorem $26C$, by contrast, absolutely does rely on a finite language. Take for example a language with a unary relation symbol $U_i$ for each $i\in\mathbb{N}$ (note that this language is computable!). For each set $X\subseteq\mathbb{N}$, let $\mathfrak{M}_X$ be the structure whose universe consists of a single element, such that $U_i$ holds on that element iff $i\in X$. Then $Th(\mathfrak{M}_X)$ computes $X$ since we have $$i\in X\iff\mathfrak{M}_X\models\exists xU_i(x).$$ So now just pick some really complicated $X$.
Informally speaking, the infinite language lets us "access" each of the bits of $X$ (using one symbol per bit), and so code the entire complexity of $X$ into the theory of the resulting structure. If we tried to do this with only finitely many $U_i$s, we'd only get finitely much information about $X$, which - regardless of how complicated $X$ is - would be computable. And the fact that every finite structure in a finite language has a computable theory demonstrates that there's no clever way around this.
Comment: In other words, decidability is *not* a constructive statement, but merely an existential one.
Comment: @Travis08 That doesn't work because your "algorithm" needs to work *for all $k$*. This means that while each *instance of* the algorithm only needs finitely much information to be "baked in," the *algorithm as a whole* uses the full complexity of $X$. This is exactly what I was getting at re: **uniformity** above, and tomasz is absolutely right. Since this has nothing to do with the original model theory question, and this comment thread is getting long, I suggest asking a separate question about this if you're still confused.
Comment: Is X the universe for the structure M? Is X not computable? But if the universe is not computable, then even in a finite language, Th(M_x) is not decidable.
Comment: @Travis08 No, the universe for $M$ just has a single element - say, its universe is $\{17\}$, if you care specifically (as I say, "the structure with a single element"). The universe is **very** computable! The point is that all the complexity of $X$ gets folded into how the $U_i$s are interpreted; the fact that $\mathfrak{M}_X$ has only one element doesn't limit this. In a finite language this sort of coding wouldn't be possible, but once we have an infinite language we can do things like this.
Comment: So the universe for M is computable. But X is not computable, correct? Suppose I have a structure M and the universe has a single element 0. The structure uses a finite language with one unary relation symbol U.  U is defined in the following way: $0 \in U$ iff $0 \in X$. Since X is not computable (there's no way to compute whether 0 is in X or not), a sentence involving U is not decidable.
Comment: @Travis08 No, that's not right - any finite amount of information is computable. Regardless of how complicated $X$ is, the answer to the question "Is $0\in X$?" - and so any structure depending entirely on the answer to this question, in the way you've described! - will be very simple. We need a unary relation for *each* "bit" of $X$, which is why the language has to be infinite.
Comment: @Travis08 I've edited to clarify this.
Comment: "Any finite amount of information is computable." Based on your answer to my previous question, I assume that $0 \in U$ iff $0 \in X$ is decidable. Am I correct? If so, then $U_1(x)$ is decidable, $U_2(x)$ is decidable, etc. In an infinite language, any sentence $\sigma$ from the language is going to include only a finite number of $U_i$. Each of the $U_i$ in $\sigma$ is decidable. Thus the entire sentence $\sigma$ is decidable.
Comment: @Travis08 I'm not sure what you mean by "$0\in U$ iff $0\in X$" - there is *no* "$U$" at all. There is a separate $U_i$ for each $i\in\mathbb{N}$. I also don't know what you mean by "the entire sentence $\sigma$ is decidable" - it doesn't really make sense to talk about a *single* sentence being decidable or undecidable in this context, for the same reason. What is true is that for each $n$ the theory of $\mathfrak{M}_X$ restricted to formulas using only the symbols $U_k$ for $k<n$ is computable - but this isn't **uniform in $n$** so this doesn't give the computability of $Th(\mathfrak{M}_X)$.
Comment: I was wrong to speak about a sentence $\sigma$ as decidable. I meant it is possible to decide for any single sentence $\sigma$ whether $\sigma$ is a member of Th(M_x). Because it seems that you are saying that for every fixed $U_i$, it is possible to decide whether $i \in X$. What does it mean to say, "isn't uniform in n"? Do you have an example of an X? Something concrete might help me understand. (I couldn't move this conversation to chat. If this conversation has grown too tedious for you, that's fine. My understanding this answer may be outside of my current knowledge base.)
Comment: @Travis08: I think you should go back to the definition of decidability of the theory. It basically means that there is a*fixed*  procedure which, given an *arbitrary* sentence, tells you whether that sentence follows from the theory or not (in finitely many steps). Since you can code any set as the set of true sentences in a theory of a singleton structure (in an infinite language), including sets which are not recursive, singleton structures are not decidable.
Comment: @tomasz My difficulty is understanding "Any finite amount of information is computable." Suppose $X \subseteq \mathbb N$ is the range of the Busy Beaver function. Suppose there is a structure $\mathfrak M_x$ with a finite number of $U_i$ (from 1 to $10^{{10}^{10}})$, where each $U_i$ is satisfied by the single element 0 from the universe iff $i$ is a member of the range of the Busy Beaver function. $Th(\mathfrak M_x)$ is decidable according to the theorem. What does "decidable" in this context mean, since we can't prove using ZFC what the BB number is for 748 states?
Comment: @Travis08: It doesn't matter whether or not we know or can know what the number is. It is enough that we know that the number exists (otherwise, the structure would not be well defined). So (for simplicity, only for formulas $(\exists x)U_i(x)$), to define the procedure, take $X_0=X\cap [0, 10^{10^{10}}]$. Then, the procedure is as follows: if $i\in X_0$, return True, else return False. Since $X_0$ is finite, all is fine --- the decision procedure exists. Not knowing $X_0$, we don't know what it is, we *can't* know what it is, but we *know* it exists --- so we have decidability.
Comment: @tomasz Here's my 'decision procedure' that uses your example as a template to determine whether a sentence $\sigma$ is satisfied by a structure $\mathfrak M_x$ with an infinite language. The structure uses the Busy Beaver function to determine whether the unary predicates are satisfied or not (as above).
Comment: Let $X$ be the range of BB. Let $\sigma$ be a sentence from the language. $\sigma$ is finite and has a finite number of prime formulas. For simplicity, let's assume they are all of the form $\exists(x)U_i(x)$. Let k = Maximum $i$ of the $U_i$ in $\sigma$ -- since the number of $U_i$ in $\sigma$ is finite, that is possible. Let $X_0 = X \cap [0, k]$. Then the decision procedure is as follows: if $i \in X_0$ return True, else return False. Since $X_0$ is finite, all is fine --- the decision procedure exists.
Comment: @Travis08: Noah already explained this nicely, but putting it differently: what you have described (well, approximately) is a procedure to decide whether or not a *fixed* $\sigma$ is satisfied in the structure. There is no place for input (which was $i$ in my example). So the procedure can be even simpler than what you describe: if $\sigma$ is satisfied, return True, else return False. But this only works for this one $\sigma$, so that tells you nothing about decidability.


mongoose | find query with timeout

Question: I'm trying to run a find query with timeout, but the timeout doesn't seems to have any impact.
myModel.find(query, select, {maxTimeMS: 1000, skip:0, limit: 1000}).lean().exec(function(){...}

I've using mongoose version 5.0.12
What am I missing?
Duplicate attempt:
myModel.find(query, select, {skip:0, limit: 1000}).maxTime(1000).lean().exec(function(){...}

Comment: Thanks, your code works fine for me when I try it, giving an ExceededTimeLimit error if I set the maxTime value low enough.
Comment: the answer in the duplicated question doesn't work
Comment: It still works fine when I try it with Mongoose 5.1.1. Can you update your question to show how you're trying to use the answer in the linked dupe?
Comment: Hi, i've added the new attempt to the original question
Comment: Well, it should be `lean()`, but what else isn't working about it?
Comment: it's lean() - just forgot to add the `()` in the question.
i'm not receiving a timeout for a request that takes about 5 seconds
Comment: strange... i'm not getting timeout.
Answer: You can use https://github.com/aheckmann/mquery#maxtime
myModel.find(query, select).maxTime(1000).exec(function(err, doc) { ... });

Also you can test it inside console.
https://docs.mongodb.com/manual/reference/method/cursor.maxTimeMS/
Comment: i actually have more flags under OPTIONS. i've updated my question

mongoose | find query with timeout


How can I formally show that a root n consistent estimator is weakly consistent?

Question: How can I formally show that a root n consistent estimator is weakly consistent?
Heuristically its clear that if $\sqrt{n}(\theta_n-\theta_0)$ is bounded in probability then since $\sqrt{n} \to \infty$ as $n \to  \infty$ clearly $\theta_n-\theta_0 \in o_p(1)$ that is it goes to zero in probability but every time I try to write it formally I get stuck. Could someone help me out?
Comment: @gung I was reading some notes and although it seemed obvious, surprisingly I could not prove it , so I sought some help. A hint would be appreciated too
Comment: Is this a question from a course or textbook? If so, please add the `[self-study]`
tag & read its [wiki](http://stats.stackexchange.com/tags/self-study/info).
Answer: I'm going to write your estimator with a hat on it: $\hat{\theta}_n$. The tricks involve playing around with subsets. If $A \subset B$, then $P(A) \le P(B)$. Observe that
\begin{align*}
P(|\hat{\theta}_n - \theta_0| > \epsilon) &= P(|\hat{\theta}_n - \theta_0| > \epsilon , \sqrt{n}|\hat{\theta}_n - \theta_0| \le M) + P(|\hat{\theta}_n - \theta_0| > \epsilon , \sqrt{n}|\hat{\theta}_n - \theta_0| > M) \\
&\le  P(|\hat{\theta}_n - \theta_0| > \epsilon , \sqrt{n}|\hat{\theta}_n - \theta_0| \le M) + P(\sqrt{n}|\hat{\theta}_n - \theta_0| > M) \\
&\le  P(M/\sqrt{n} > \epsilon , \sqrt{n}|\hat{\theta}_n - \theta_0| \le M) + P(\sqrt{n}|\hat{\theta}_n - \theta_0| > M) \\
&\le  P(M/\sqrt{n} > \epsilon ) + P(\sqrt{n}|\hat{\theta}_n - \theta_0| > M).
\end{align*}
So, more formally, pick $\epsilon,\delta >0$. Then pick $M$ such that
$$
P(\sqrt{n}|\hat{\theta}_n - \theta_0| > M) \le \delta,
$$
if $n > N_1$, which you can do because it's bounded in probability. Then if $n > \text{max}(N_1, M^2/\epsilon^2)$, you have your result:
$$
P(|\hat{\theta}_n - \theta_0| > \epsilon) \le \delta.
$$
Note that I am not showing how $\sqrt{n}$- consistency implies boundedness in probability, so I hope that this counts as a hint.
Comment: @user3503589 yes, that's right. Sorry, I didn't see this message because you never tagged me.
Comment: I have a stupid question .  On rereading your proof I am wondering what is random in the set $\{M/\sqrt{n}> \epsilon\}$. Its clear that the set is either empty or the whole set depending on the value of $n$ and we choose n large enough so that its empty(since we have already fixed $M$ and $\epsilon$). The probability of this set can either be $1$ or $0$ and we chose $n$ in such a way so that its $0$. Am I correct?


Add suffix to generated string resource

Question: I have a gradle config as setup below. To allow for side by side installs of different builds/flavors
buildTypes {
    release {
    }
    debug {
        applicationIdSuffix ".debug"
        // Somehow add debug suffix to app ID?
    }
}
productFlavors {
    ci {
        applicationId "com.myapp.ci"
        ext.betaDistributionGroupAliases = "mobileworkforce.ci"
        resValue "string", "app_name", "AppName.CI"
    }

    staging {
        applicationId "com.myapp.staging"
        resValue "string", "app_name", "AppName.Staging"
    }

    production {
        applicationId "com.myapp"
        resValue "string", "app_name", "AppName"
    }

The issue is that I cannot figure out how to update the app_name string resource to have the suffix "Debug" to the app_name string resource (used as the label for the application)
Answer: I was able to create a viable solution using manifestPlaceholders instead of generating string resources. It is not ideal because the result is AppName.Debug.CI instead of AppName.CI.Debug but it works.
buildTypes {
    release {
         manifestPlaceholders = [ activityLabel:"AppName"]
    }
    debug {
        applicationIdSuffix ".debug"
                     manifestPlaceholders = [ activityLabel:"AppName.Debug"]
    }
}
productFlavors {
    def addActivityLabelSuffix = { placeholders, suffix ->
        def appName = placeholders.get("activityLabel")
        placeholders.put("activityLabel", appName + suffix);
    }
    ci {
        applicationId "com.myapp.ci"
        ext.betaDistributionGroupAliases = "mobileworkforce.ci"
        addActivityLabelSuffix getManifestPlaceholders(), ".CI"
    }

    staging {
        applicationId "com.myapp.staging"
        addActivityLabelSuffix getManifestPlaceholders(), ".Staging"
    }

    production {
        applicationId "com.myapp"
        resValue "string", "app_name", "AppName"
    }
}

Answer: Using getManifestPlaceholders().get("...") I always get null, so I was looking for another solution... and maybe is better because I can get correct order in app name...
// build.gradle
def appNameBase = "My App"
buildTypes {
    release {
        manifestPlaceholders = [ appNameBase: appNameBase, appNameSuffix: "" ]
    }
    debug {
        manifestPlaceholders = [ appNameBase: appNameBase, appNameSuffix: " Debug" ]
        applicationIdSuffix ".debug"
    }
}
productFlavors {
    one {
        manifestPlaceholders = [ appNameFlavor: "One" ]
    }
    two {
        manifestPlaceholders = [ appNameFlavor: "Two" ]
    }
}

// AndroidManifest.xml
<application android:label="${appNameBase} ${appNameFlavor}${appNameSuffix}" ...>

In my case I wanted for prod just "My App One" and "My App Two" ad for debug "My App One Debug" and "My App Two Debug" and code above works great.

Add suffix to generated string resource


How to fix 'Double data loading' from firebase realtime database

Question: I am using firebase realtime database for a small project.We have a list of students from single department.The purpose is to lend money to some other student and we keep the record.
I have user authenticated user firebase Authentication.The issue i am facing is once a user adds more entries , instead of loading the actual list , it creates copies.

Here is my code to load data in recycler view.
    private void loadtorecyclerview() {
    databaseReference  = FirebaseDatabase.getInstance().getReference("Transaction");

    databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
                readTransaction = snapshot.getValue(Transaction.class);
                if (readTransaction.getSponsor_id().contentEquals(user.getUserId().toString())) {
                  read_data.add(readTransaction);
                  Log.e("log" , readTransaction.toString());
                }
            }

               transactionAdapter.notifyDataSetChanged();

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

}

I am calling this method in OnCreateView of my fragment.
Here is code to add new data to firebase.
button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String amount = editText.getText().toString();

                setValue(amount);

                //value published firebase
                Log.e("amount" , amount);
                DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Transaction");
                String key = databaseReference.push().getKey();
                databaseReference.child(key).setValue(transaction_submitted);

            //    loadtorecyclerview();

                popupWindow.dismiss();
            }
        });

Here is code for Transaction Adapter.
public class TransactionAdapter extends RecyclerView.Adapter<TransactionAdapter.ViewHolder>{
    Context context;
    ArrayList<Transaction> data;

    public TransactionAdapter(Context context, ArrayList<Transaction> data) {
        this.context = context;
        this.data = data;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = (View) LayoutInflater.from(context).inflate(R.layout.single_item_sponsor_rv  , parent ,false);
        ViewHolder viewHolder = new ViewHolder(v);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.amount.setText(data.get(position).getAmount());
        holder.department.setText(data.get(position).getDepartment());
        holder.collector.setText(data.get(position).getCollector_name());
        holder.published.setText(data.get(position).getPublished_at());
    }

    @Override
    public int getItemCount() {

        return data.size();

    }

    class ViewHolder extends RecyclerView.ViewHolder {
        TextView published;
        TextView department;
        TextView amount;
        TextView collector;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            published = itemView.findViewById(R.id.timestamp);
            department = itemView.findViewById(R.id.department);
            amount = itemView.findViewById(R.id.amount);
            collector = itemView.findViewById(R.id.collector);
        }
    }
}

You can see in image there are three entries in Transaction , but when loaded , it duplicates them and show many.
Comment: Seems a problem with the adapter. Please attach the code of the `TransactionAdapter` class.
Comment: @salmanwahed please check the updated code.
Comment: Please check the answer and let me know if it solves the issue.
Comment: @salmanwahed i used this:

                read_data.clear();
transaction_adapter.notifydatasetchanged() and it works
Answer: It's an issue with the adapter setting. You are adding values to the data-set without removing the old ones. Please reinitialize/clear the read_data object before adding new items to it.
databaseReference  = FirebaseDatabase.getInstance().getReference("Transaction");

read_data.clear();

databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
                readTransaction = snapshot.getValue(Transaction.class);
                if (readTransaction.getSponsor_id().contentEquals(user.getUserId().toString())) {
                  read_data.add(readTransaction);
                  Log.e("log" , readTransaction.toString());
                }
            }

               transactionAdapter.notifyDataSetChanged();

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

}


How to integrate $\int_{0}^{\infty}\left(\frac{\tanh x}{x^2}-\frac{\mathrm{sech}^2x}{x}\right)\frac{1}{\sinh x}dx$

Question: I am trying to integrate
$$\int_{0}^{\infty}\left(\frac{\tanh(x)}{x^2}-\frac{\mathrm{sech}^2(x)}{x}\right)\cdot \frac{\mathrm dx}{\sinh(x)}\tag1$$
and to simplify a little bit,
$$\int_{0}^{\infty}\frac{\tanh(x)}{x^2}\cdot \frac{\mathrm dx}{\sinh(x)}-\int_{0}^{\infty}\frac{\mathrm{sech}(x)}{x}\cdot \frac{\mathrm dx}{\sinh(x)}$$
$$\int_{0}^{\infty}\frac{1}{x^2\cosh(x)} \mathrm dx-\int_{0}^{\infty}\frac{2}{x}\cdot \frac{\mathrm dx}{\cosh(x)\sinh(2x)}$$
I don't think I can use series here to help me.
Can anyone help to evaluate $(1)?$
Comment: I don't think splitting the original integral into two integrals like that will be useful since the last two integrals don't seem to converge.
Comment: The answer seems to be $\ln 2$ according to [WA](https://www.wolframalpha.com/input/?i=integrate+%28%28tanh+x%29%2Fx%5E2+-+%28sech%5E2+x%29%2Fx%29%2F%28sinh+x%29+from+0+to+infinity).
Comment: Agree with @AlexMacedo ... writing a convergent integral as the difference of two divergent integrals is not helpful.
Answer: Write
$$ I \equiv \int \limits_0^\infty \left[\frac{\tanh(x)}{x^2} - \frac{1}{x \cosh^2 (x)}\right] \, \frac{\mathrm{d} x}{\sinh(x)} = \int \limits_0^\infty \left[\frac{1}{x^2 \cosh(x)} - \frac{1}{x \sinh(x)} + \frac{\sinh(x)}{x \cosh^2 (x)}\right] \, \mathrm{d} x $$
and integrate by parts to find
\begin{align}
I &= \left[\frac{1}{x} \left(1 - \frac{1}{\cosh(x)}\right)\right]_{x=0}^{x=\infty} + \int \limits_0^\infty \left[\frac{1}{x^2 \cosh(x)} - \frac{1}{x \sinh(x)} + \frac{1}{x^2}\left(1 - \frac{1}{\cosh(x)}\right)\right] \, \mathrm{d} x \\
&= \int \limits_0^\infty \left[\frac{1}{x^2} - \frac{1}{x \sinh(x)} \right] \, \mathrm{d} x \, .
\end{align}
The remaining integral has already been evaluated here and in a comment to this question (using Frullani integrals or the pole expansion of $\operatorname{csch}$) and we obtain $I = \ln(2)$.


disable @Nonnull annotation on "implement methods"

Question: IntelliJ is adding @Nonnull annotations on code generated via the implement methods feature. How to prevent IntelliJ from annotating signatures with that annotation?
IntelliJ 2019.1
Thanks
Comment: Do you have the interface signature annotated with `@NotNull`? Why do you want the implementation to omit the annotation?
Comment: @CrazyCoder - you are right! the method signatures on the interface are annotated with `@Nonnull`. I did not notice that before.
Answer: IntelliJ IDEA copies the annotations from the interface declaration, there is no way to disable this behavior.


For what measurable set $A \subset \Bbb R^2$ and Lipschitz function $f$ is $f(A) \subset \Bbb R$ not measurable?

Question:
Find a Lebesgue measurable set $A \subset \Bbb R^2$ and a Lipschitz function
  $f: \Bbb R^2 \to \Bbb R$ s.t.
  $f(A)$ is not Lebesgue measurable.

I want to find an $A$ and an $f$ such that $f(A)$ is a Vitali set.
If we let $x \sim y : \iff x-y \in \Bbb Q$ and $E_x:=\{y \in \Bbb R: x \sim y\}$
then for $g:\{E_x:x\in \Bbb R\} \to \Bbb R \; ; g(E_x)=x$ we have that the image of $g$ is not not measurable.
But how can I find the set $A$ and the function $f$?
Answer: Take $f(x,y)=x$ where $A$ is the product of a nonmeasurable subset of the line say $V$, and a singleton. Check that $A$ is measurable and then note $f(A)=V$.


Determine whether the following expression is a tautology, a contingency, or a contradiction by using the logical equivalences

Question: As a practice problem, I'm asked to determine whether the following proposition is a tautology, contradiction, or contingency through the use of logical equivalences.
I get how to determine what truth value the proposition is and I understand most of the logic rules, but I'm stumped on what the first step would be on solving this one. I can't use distribution on ( (  ∨  ) ∧ ( ¬  ∨  ) ) because of the negation symbol on p. If I use de morgan's by moving that outer negation inside, I don't see how it would make a difference because all it'd do is just flip the signs. If I used association and moved the bracket to ( (  ∨  ) ∨ (  ∨  )) I still can't use distribution because all the symbols are a ∨.
¬ ( (  ∨  ) ∨ ( (  ∨  ) ∧ ( ¬  ∨  ) ) )
Any help or push in the right direction would be appreciated.
Comment: Have you covered the consensus theorem in your class?  (You may have called it "resolution.")
Comment: No, we haven't covered that.
Comment: Ignore the outside negation until the end.  Apply distributivity to $(p \vee q) \wedge (\neg p \vee r)$, and then apply "$a \vee (a \wedge b)$ simplifies to $a$ twice.
Comment: But distributivity is (A ∨ (B ∧ C)) ≡ (A ∨ B) ∧ (A ∨ C) right? I thought I could only do it if there wasn't a negation on the 2nd p.
Comment: Distributivity in Boolean algebras is also $(A \wedge (B \vee C)) \equiv (A \wedge B) \vee (A \wedge C)$.  It feels wrong because it doesn't work for the real numbers, but Boolean algebras enjoy duality of $\wedge$ and $\vee$.
Answer: I will in the following show the reduction of $\neg ((q \lor r) \lor ((p \lor q) \land (\neg p \lor r)))$:
By De Morgan's laws:
$\equiv \neg (q \lor r) \land \neg ((p \lor q) \land (\neg p \lor r))$
By De Morgan's laws:
$\equiv \neg (q \lor r) \land \neg (p \lor q) \lor \neg (\neg p \lor r)$
By De Morgan's laws:
$\equiv (\neg q \land \neg r) \land (\neg p \land \neg q) \lor (p \land \neg r)$
$\equiv (\neg q \land \neg r \land \neg p) \lor (p \land \neg r)$
$\equiv (\neg q \lor p) \land (\neg r \lor p) \land (\neg p \lor p) \land (\neg q \lor \neg r) \land (\neg r \lor \neg r) \land (\neg p \lor \neg r)$
$\equiv (\neg q \lor p) \land (\neg r \lor p) \land T \land (\neg q \lor \neg r) \land T \land (\neg p \lor \neg r)$
$\equiv (\neg q \lor p) \land (\neg r \lor p) \land (\neg q \lor \neg r) \land (\neg p \lor \neg r)$
$\equiv (\neg q \lor p) \land (\neg q \lor \neg r) \land (\neg r \lor (p \land \neg q))$
$\equiv (\neg q \lor (p \land \neg r)) \land (\neg r \lor (p \land \neg q))$
As you can see, I have used De Morgan's laws or the first 3 steps. Even though it doesn't seem like it will make any difference swapping the negation sign and inverting the boolean operator, it might actually give a surprising result since some parentheses may be eliminated because they contain a tautology or contradiction. This is exactly what I have done after the first 3 steps.
Comment: Your final result is incorrect.  Careful with parentheses and with the application of distributivity.
Comment: What happened to the brackets for ¬(q∨r)∧¬(p∨q)∨¬(¬p∨r)?
Comment: I will fix it a bit later.
@GilmoreGirling I used De Morgan's law to apply the negation to the inner value in the parentheses. By doing this, the boolean operator must be swapped to its opposite.


SQL Server Need To Run Same Query Multiple Times To Get Desired Results

Question: I have a stored procedure that I had working perfectly on Wednesday but is no longer working properly. I haven't changed any of the code and for some reason it's just not acting the same way.
Here's the code snippet that isn't working:
WITH Minimum AS (SELECT DataTable.PortID, [Rating Max],
    CASE When [Rating Max] <= [Sector Max] And [Rating Max] <= [ConcAfterUnwritten] And [Rating Max] <= [NatAfterUnwritten] And [Rating Max] <= [CashMaxAfterUnwritten] And [Rating Max] <= MatAfterUnwritten And [Rating Max] <= MatAfterInitialConcentration  Then [Rating Max]
         When [Sector Max] <= [ConcAfterUnwritten] And [Sector Max] <= [NatAfterUnwritten] And [Sector Max] <= CashMaxAfterUnwritten And [Sector Max] <= MatAfterUnwritten And [Sector Max] <= MatAfterInitialConcentration Then [Sector Max]
         When ConcAfterUnwritten <= NatAfterUnwritten And ConcAfterUnwritten <= CashMaxAfterUnwritten And ConcAfterUnwritten <= MatAfterUnwritten And ConcAfterUnwritten <= MatAfterInitialConcentration Then ConcAfterUnwritten
         When NatAfterUnwritten <= CashMaxAfterUnwritten And NatAfterUnwritten <= MatAfterUnwritten And NatAfterUnwritten <= MatAfterInitialConcentration Then NatAfterUnwritten
         When CashMaxAfterUnwritten <= MatAfterUnwritten And CashMaxAfterUnwritten <= MatAfterInitialConcentration Then CashMaxAfterUnwritten
         When MatAfterUnwritten <= MatAfterInitialConcentration Then MatAfterUnwritten
         Else MatAfterInitialConcentration
         End As [Min Of 5 Restrictions]
FROM DataTable)
UPDATE DataTable
Set
    DataTable.MinOf5Restrictions = Minimum.[Min Of 5 Restrictions],
    DataTable.MktValueAllocation = IIF(Minimum.[Min Of 5 Restrictions] < DataTable.MatAfterInitialConcentration, 0, DataTable.MatAfterInitialConcentration),
    DataTable.ModelParAmount = IIf([MktValueAllocation]=0,0,Round([MktValueAllocation]/([$Px+Acc]*10)/5,0,1)*5),
    DataTable.AllocatedPar = IIF(DataTable.ModelParAmount = 0, 0, ParLots.AllocatedPar),
    DataTable.[Check Cash And Concentration] = IIf(DataTable.[AllocatedPar]*[$Px+Acc]*10>[MinOf5Restrictions],[ModelParAmount],DataTable.[AllocatedPar]),
    DataTable.[Final After State Switch] =  IIf([StateOnly]='TRUE',IIf([RestrictionType]='Specific',[Check Cash And Concentration],0),[Check Cash And Concentration])
FROM
    ((DataTable INNER JOIN Minimum ON DataTable.PortID = Minimum.PortID) LEFT JOIN ParLots ON DataTable.ModelParAmount = ParLots.ModelPar) INNER JOIN TestSet ON DataTable.PortID = TestSet.PortID, Main;

My current problem is that I have to run the query 6 times in order to get the result that I want. Basically the UPDATE statement only seems to be updating one of the columns every time that I execute it instead of all 6 at once. The first time it's executed the MinOf5Restrictions is populated but the other columns aren't, the second time MktValueAllocation is populated but the last 4 are still empty, etc.
Any idea why this might be? I suppose I could separate it into 6 different UPDATE statements but I'd rather not if I don't have to, especially since I had it working before.
Thanks
Comment: You can add an `OUTPUT` clause to the `UPDATE` statement and see what is being updated in each pass. For testing you can wrap it in `BEGIN TRANSACTION`/`ROLLBACK TRANSACTION`. That will allow you to rerun the query without actually updating the table.
Comment: I would recommend you to debug your query, part by part, specially all these inline ifs and the select case to be sure that they're returning the desired value.
Answer: The query you have there is very complicated and without knowing schema of tables and values in tables it is hard to diagnose your issue. However that being said the way I typically debug issues with updates is modifying it to a select and seeing if the values returned are what you expect and what you would want to be updating. So I would update the query to something like this (couldn't verify that this works since I don't have schema but should give you an idea if it doesn't).
WITH Minimum AS
(
    SELECT
        DataTable.PortID
       ,[Rating Max]
       ,CASE
            When [Rating Max] <= [Sector Max] And [Rating Max] <= [ConcAfterUnwritten] And [Rating Max] <= [NatAfterUnwritten] And [Rating Max] <= [CashMaxAfterUnwritten] And [Rating Max] <= MatAfterUnwritten And [Rating Max] <= MatAfterInitialConcentration  Then [Rating Max]
            When [Sector Max] <= [ConcAfterUnwritten] And [Sector Max] <= [NatAfterUnwritten] And [Sector Max] <= CashMaxAfterUnwritten And [Sector Max] <= MatAfterUnwritten And [Sector Max] <= MatAfterInitialConcentration Then [Sector Max]
            When ConcAfterUnwritten <= NatAfterUnwritten And ConcAfterUnwritten <= CashMaxAfterUnwritten And ConcAfterUnwritten <= MatAfterUnwritten And ConcAfterUnwritten <= MatAfterInitialConcentration Then ConcAfterUnwritten
            When NatAfterUnwritten <= CashMaxAfterUnwritten And NatAfterUnwritten <= MatAfterUnwritten And NatAfterUnwritten <= MatAfterInitialConcentration Then NatAfterUnwritten
            When CashMaxAfterUnwritten <= MatAfterUnwritten And CashMaxAfterUnwritten <= MatAfterInitialConcentration Then CashMaxAfterUnwritten
            When MatAfterUnwritten <= MatAfterInitialConcentration Then MatAfterUnwritten
            Else MatAfterInitialConcentration
         End As [Min Of 5 Restrictions]
    FROM DataTable
)
SELECT
    Minimum.[Min Of 5 Restrictions] [MinOf5Restrictions],
    IIF(Minimum.[Min Of 5 Restrictions] < DataTable.MatAfterInitialConcentration, 0, DataTable.MatAfterInitialConcentration) [MktValueAllocation],
    IIf([MktValueAllocation]=0,0,Round([MktValueAllocation]/([$Px+Acc]*10)/5,0,1)*5) [ModelParAmount],
    IIF(DataTable.ModelParAmount = 0, 0, ParLots.AllocatedPar) [AllocatedPar],
    IIf(DataTable.[AllocatedPar]*[$Px+Acc]*10>[MinOf5Restrictions],[ModelParAmount],DataTable.[AllocatedPar]) [Check Cash And Concentration],
    IIf([StateOnly]='TRUE',IIf([RestrictionType]='Specific',[Check Cash And Concentration],0),[Check Cash And Concentration]) [Final After State Switch]
FROM
    ((DataTable
    INNER JOIN Minimum ON
        DataTable.PortID = Minimum.PortID)
    LEFT JOIN ParLots ON
        DataTable.ModelParAmount = ParLots.ModelPar)
    INNER JOIN TestSet ON DataTable.PortID = TestSet.PortID

If you want any more help it would be helpful if you could simplify your query (and doing this might also help you find the issue).
Comment: Thanks for the help Warren. Though I haven't really found the problem as to why it wasn't working, your tip will definitely help me in the future.

Oddly enough, if I split it into 6 separate UPDATE statements, it works how I want it to. I'm probably going to just keep it with the 6 update statements since the minimal performance hit of the multiple update statements is not worth the time or headache to try and fix.
I believe the problem is that the third column, ModelParAmount, is reading every column of MktValueAllocation in as 0, so it seems to be executing that statement before the other


Reading a log file which is locked by another application

Question: I want to access a log file that is locked by a third party Java application. The file is locked for the whole day and will be released the next day. However, my objective is to read it now using RandomAccessFile (must use this class because I need to start/store the last position while reading) without waiting until tomorrow.
Currently, I can read the log only if I unlock it with a file Unlocker software. Can anyone suggest any jar/utilities that I can use in my Java program to meet my objective?
Comment: A little similar to your problem? http://stackoverflow.com/questions/1555883/locking-and-unlocking-files-using-the-java-api
Though the solution provided isn't very elegant, it will work for the time being.
Comment: Also, can you identify what application is locking your log file? Is it an external 3rd party app? Or some other piece of your own code? If it is your own code somewhere, this might be of some help: http://www.javaspecialists.eu/archive/Issue190.html
Comment: Another similar problem: http://stackoverflow.com/questions/5680588/in-java-is-there-a-way-to-read-a-file-when-that-file-is-locked-by-other-thread
Comment: It is 3rd party apps who blocks the file. I have to use Unblocker Assistant Software to kill the block then i can access the file at the same time the 3rd party software still running as usual. So is there any libs/software that can integrate with my apps to unblock it?
Comment: Just out of curiosity. Doesn't it work to open the file i read only mode?  Like new RandomAccessFile(file, "r") Then you can store the position when reading. You can open it later in "rw" if you need to write once the lock has been released.
Comment: Of cause it is working if it realize the lock. The problem is, it will be unlock on the next day(daily pattern file). What i want is immediately.
Answer: Assuming you're using a Microsoft operating system:
The software Shadow Copy is using using Microsoft's volume-shadow-service (VSS) to copy locked files.
You could use the software from within the Java Runtime Environment or perhaps make use of the VSS-API yourself via Java Native Interface.
My approach would be to shadow-copy the file and then access the content through it's copy. The downside is that you're possibly reading outdated information if the file has been updated since your copy operation.
However, this is just a guess as I'm not familiar with this topic.
Comment: I agreed with you this can solve my objective only if the file is small. However to copy a huge file is not a good idea within every 3 seconds. That why i am using RandamAccessFile just to access the specific location in the file.
Comment: @JoeIjam: The VSS uses copy-on-write, so it only writes a bit of header information. The file's contents aren't copied until one of the files is written to, and then only the changed areas are copied. Even so, using shadow copies for this is complete overkill. It's better to just break the original process' lock, unpleasant though that is.
Answer: You can lock/unlock files and folders in Java but only by application that locked them (you programmed). However there is no Java method/class which can unlock file used by other process.
You should bundle your application with another (native) software. For example you could create shell script for Linux systems and execute it. In Java application detect in which OS it is running so you can execute proper script/software.
When application requires RW lock, system must ensure that no one else have rights to modify it, thats why you need to kill process that is using it.
If you have access to source code of that 3rd party Java application (that is actually locking file you need), then you could implement server side which will listen requests for unlocking file and approval for locking it back again.
By my opinion better approach would be to transfer file by that application to yours, then do what you want and 3rd party app can run without interruption (shouldn't be noticeable). If you need to modify it, then 3rd should wait, your modifies and send back an updated version, 3rd continue to work.
Answer: I don't see any reliable tool to do such job, my first mind is to try to avoid the lock while exposing the file as a service through any servlet or any other mechanism. The servlet reads the file once then deliver its contents as plain text (or stream)... No more lock contention
HTH
Jerome


Remove git files/directories older than x days via GitHub Action

Question: We use a gh-pages branch in our repository to host a static website and frequently commit new information to this branch. Those files often get stale, as we push to a subdirectory per feature branch in the same repository.
The directory structure in my gh-pages branch is similar to the following:
.
|-- README.md
|-- JIRA-1234-feature
|   `-- graph
|-- JIRA-4567-bugfix
|   `-- graph
|-- JIRA-7890-branch-name
|   `-- testing

I want to remove directories via a GitHub actions for which the last update was more than 5 days ago.
I naively tried to remove them via find /path/to/files* -mtime +5 -exec rm {} ;, but the operating system obviously uses the clone date as the last modified time.
I also found
git ls-tree -r --name-only HEAD | while read filename; do
  echo "$(git log -1 --format="%ad" --date="short" -- $filename) $filename"
done

which prints the last git update and the file name like this:
2023-01-12 JIRA-1234-test/index.html
2023-01-12 JIRA-1234-test/static/test.css

I don't know how to trigger file removal commands from this list, though.
How would I have to modify the following action to remove the old files?
name: Prune GH Pages branch

on:
  workflow_dispatch:

jobs:
  upload:
    runs-on: ubuntu-latest
    timeout-minutes: 15
    steps:
      - name: Checkout
        uses: actions/checkout@v3
        with:
          ref: gh-pages
      - name: Cleanup
        run: |
          # TODO: REMOVE FILES HERE
          git ls-tree -r --name-only HEAD | while read filename; do
            echo "$(git log -1 --format="%ad" --date="short" -- $filename) $filename"
          done
      - name: Commit & Push
        run: |
          if [ $(git status --porcelain | wc -l) -eq "0" ]; then
            echo "git repo is clean."
          else
            git add -A
            git commit -m "branch cleanup"
            git push
          fi

Answer: Unfortunately, I didn't find a way to make a nice one-liner for the requirement. We need the following bash script. I have commented all the important steps.
#!/bin/bash

# Validate if $1 is a positive number days
[[ $1 != +([[:digit:]]) ]] &&
   echo "$1: The script has to be run with positive number argument" && exit 1

# Get the X days ago timestamp
X_DAYS_AGO_TIMESTAMP=$(date -d "$1 days ago" +%s)

# Iterate over all files in the repository
for file in $(git ls-files); do
  echo -n "."
  # Get the timestamp of the last commit that modified this file
  LAST_MODIFIED_TIMESTAMP=$(git log -1 --format="%at" -- "$file")
  # If the file hasn't been modified within the last $1 days
  if [ "$LAST_MODIFIED_TIMESTAMP" -lt "$X_DAYS_AGO_TIMESTAMP" ]; then
    # Remove the file from the repository
    echo -e "\nRemoving $file last modified at $(date -d "@$LAST_MODIFIED_TIMESTAMP")"
    git rm --quiet "$file"
  fi
done

# Commit the changes (if any)
if ! git diff --exit-code --quiet --staged; then
  git commit -m "Remove files not modified within the last $1 days"
else
  echo "No files removed"
fi

I can elaborate if something is not clear enough.


How can I create multiple cropped Media images without re-uploading them?

Question: Solutions that I've found allow to crop Media, type Image when I've uploaded an image, but the media entity is not yet created (on the "Add media" page).
I need to upload a large full image once (and use it in full format on some nodes), and then crop it differently when I select it in different content types (to display small "zoomed" parts of the full image). So I need a manual crop to appear when I select a Media of type Image from a Media library. It can appear in Entity browser or on the node page.
Other solution is that I can create cropped images in advance being in my media library (/admin/content/media) or when adding a media (/media/add/image). The idea is that I do not want to reupload the image and add new title and alt.
Is this possible?
Comment: What cropping modules are you using? With crop and image_widget_crop, you can set up multiple crop types, configure different image styles that each uses the desired crop type and then you can basically do as many crop configurations as you want
Comment: Are you familiar with
[Image Styles](https://www.drupal.org/docs/user_guide/en/structure-image-style-create.html)
and [image_style_warmer contrib module](https://www.drupal.org/project/image_style_warmer)?
Comment: I used image_widget_crop, but the problem is that I needed to upload a new image to have it's cropped version, I could not use an existing one. And also the manual crop area appeared everywhere, even there where I did not need crop.

I use Image Styles, sure. The problem of it and image_style_warmer contrib module is that they can create styles where crop is the same for all images. I need to crop manually sometimes in the center, sometimes in some corner etc.
Answer: Solution:

Install Crop API and Image Widget Crop modules
Configure Image Widget Crop as explained in the tutorial, for Image field situated in Structure > Media types > Image. The image style for this Image field should contain no effects.
There where you want to use cropped image, select the style for it (in content type, for example) that contain "Manual crop" effect and, if you need, "Crop and Scale effect" (to display square thumbnails in listings, for example).
There where you want to use full umage, select the style for it that contain no "Manual crop" effect.

How to use images:

Upload a large full image, crop manually the interesting part
Use the same image there where you need it cropped and there where you need it full. It will be displayed differently on front.

Note: if you try to clone the Image entity (for example with Entity Clone module), it will not help because the clone Image entity and the original Image entity will apply the same crop.


how to avoid onCreateView() when swiping in tabs

Question: I have an application with an activity and 3 swipable tabs(fragments). I have some heavily created UI elements inside tabs which take some time to be created and it's ok for the first run, but the views are recreated every time I swipe them.
When I select a tab, the other tab calls onStop() and when I select the previous tab again,onCreateView() is called again and view is repopulated which slows down and blocks UI thread.
What is the correct way to create fragments inside tabs ONCE and avoid recreating their view when swiping between other tabs?
Comment: Are you using ViewPager?
Comment: im using FragmentPagerAdapter, ABS, holoevrywhere and sherlock`s actionbartabs
Answer: To add to what CommnosWare stated, if you are using a view pager, you can simply call mViewPager.setOffscreenPageLimit(3); to keep all three in memory. But if your UI is too heavy, you may notice some jank. So try revising your UI setup code.
Comment: I am using 3 constant tabs and after doing what u proposed, my tabs are very really smooth.I already use worker threads to modify ui.
Answer:
I have some heavily created UI elements inside tabs which take some time to be created

If "some time" is more than ~5 milliseconds, your app is broken and needs to be fixed. Use Traceview to determine precisely where you are spending your time, then repair matters so that it takes less time on the main application thread.

What is the correct way to create fragments inside tabs ONCE and avoid recreating their view when swipping between other tabs?

AFAIK, FragmentPagerAdapter should not have the effect that you are describing (though FragmentStatePagerAdapter will). But, again, if you fix your onCreateView() performance issue, even FragmentStatePagerAdapter will not post a problem.
Comment: @afterburner: "but everytime the fragment is selected socialize calls to its servers again and again and shows a progressbar after delaying morethan 5 secs on the UI" -- sounds like either their API is broken, or you missed some instructions for doing work in the background. "delaying morethan 5 secs on UI" is ghastly and puts you on the edge of an ANR. Also, it's entirely possible that the "socialize actionbar" may not be recreated via `onCreateView()`, but instead is responding to some other `View` lifecycle method that is triggered as the fragment is restored to the screen.
Comment: its always an honor to get a response from you sir.im using FragmentPagerAdapter  and in my third fragment i use socialize actionbar in bottom of my page to add sharing capabilities to my app but everytime the fragment is selected socialize calls to its servers again and again and shows a progressbar after delaying morethan 5 secs on the UI. Should i not deploy socialize actionbar in fragments onCreateView()?
Comment: i had a similar problem and i was using FragmentPagerAdapter but everytime onCreateView() was call the above answer helped. i don't think just using FragmentPagerAdapter solves this issue
Answer: Just add the following code inside main Fragment/Activity class where TabAdapter declared.
viewPager.setOffscreenPageLimit(tabLayout.getTabCount());

The tabLayout and viewPager as follows
TabLayout tabLayout = (TabLayout) root.findViewById(R.id.tab_layout);
ViewPager viewPager = (ViewPager) root.findViewById(R.id.pager);


Python function on AWS Lambda

Question: I need run the following function below on the lambda AWS:
def subset_sum(numbers, target, partial=[]):
    s = sum(partial)

# check if the partial sum is equals to target
if s == target:
    print("sum(%s)=%s" % (partial, target))
if s >= target:
    return  # if we reach the number why bother to continue

for i in range(len(numbers)):
    n = numbers[i]
    remaining = numbers[i + 1:]
    subset_sum(remaining, target, partial + [n])

if __name__ == "__main__":
    subset_sum([1,2,3], 5)

However the following error appears and I can't resolve:
{
  "errorMessage": "'>=' not supported between instances of 'int' and 'LambdaContext'",
  "errorType": "TypeError",
  "stackTrace": [
    [
      "/var/task/lambda_function.py",
      7,
      "subset_sum",
      "if s >= target:"
    ]
  ]
}

The original function has more values that take a long time because of this I'm running on Lambda.
On the computer using py subset_sum.py it works normally.
Comment: Is `subset_sum` your handler function?
Comment: Please read http://docs.aws.amazon.com/lambda/latest/dg/python-programming-model-handler-types.html.
Comment: Please show your entire Lambda function. If that *is* your entire Lambda function, then you should be coding your function to receive calls via a Handler. See: [Lambda Function Handler (Python)](http://docs.aws.amazon.com/lambda/latest/dg/python-programming-model-handler-types.html).
Answer: The handler function has 2 params event and context
def handler_name(event, context):
...
         return some_value

http://docs.aws.amazon.com/lambda/latest/dg/python-programming-model-handler-types.html

Python function on AWS Lambda


Grunt Sass: change one folder name on destination path

Question: How to generate CSS files in a folder other than that of the SCSS source, but keeping a part of the tree of it?
Let me explain, I have different folders with several .scss sources:
resources/client-1/scss/app.scss
resources/client-2/scss/app.scss

I would like the CSS generated this place in the css folder and not scss. So:
resources/client-1/css/app.scss
resources/client-2/css/app.scss

But I would especially like to have a dynamic configuration, because the number of client-x folder will increase with time.
Any idea?
Thank.

EDIT:
My configuration using grunt-sass is currently as follows:
module.exports = {
  options: {
    outputStyle: 'nested',
    precision: 3,
    sourceMap: true
  },
  main: {
    files: {
      'resources/clients-1/css/style.css': ['resources/clients-1/scss/style.scss' ],
      'resources/clients-2/css/style.css': [ 'resources/clients-2/scss/style.scss' ]
    }
  }
};

Comment: Which compiler are you using? Can you show us your `Gruntfile.js`?
Answer: You can build the files object dynamically (instead of using the Files Object Format, which is what you're currently using), and utilize the rename property to create the new destination path for each resultant .css files.
Replace your files property with the following instead:
files: [{
  expand: true,
  cwd: 'resources',
  src: ['**/*.scss'],
  dest: 'resources/', // <-- Value must match `cwd` value and
                      //     include trailing forward slash.
  ext: '.css',
  rename: function(dest, src) {
    var parts = src.split('/');
    parts.splice(1, 1, 'css');

    return dest + parts.join('/');
  }
}]

Explanation:

In the body of the rename function we firstly split the src path into an Array via the line which reads:
var parts = src.split('/');

Given your example source path of 'resources/clients-1/scss/style.scss', this will result in an Array assigned to the parts variable like this:
['clients-1', 'scss', 'style.scss']

We then use splice() in the line reading:
parts.splice(1, 1, 'css');

This replaces the value at index 1 (i.e. 'scss') with the given value of 'css'. The parts Array now results in this:
['clients-1', 'css', 'style.scss']

Finally, via the line which reads:
return dest + parts.join('/');

We return from the function a new String for the dest path. Given the previous example the dest path will be this:
'resources/clients-1/css/style.css'

Because the ext property has a value of .css, grunt replaces the original .scss extension name with .css.

Note:
If your resources folder has sub-folder(s) containing .scss files that you don't want to generate a .css file for you'll need to negate them using a globbing pattern. For example lets say your resources directory looks like this:
.
├── resources
│   ├── clients-1
│   │   └── scss
│   │      └── style.scss
│   ├── clients-2
│   │   └── scss
│   │      └── style.scss
│   ├── foo
│   │   └── scss
│   │      └── style.scss
│   └── quux
│       └── scss
│          └── style.scss
└── ...

And let's say you don't want .css files generated for the .scss files which exist in folders foo and quux, (i.e. you only want to process folders clients-1 and clients-2).
Given such a situation you would need to change your src property in the code example provided above to:
src: ['{,!(foo|quux)/**/}*.scss'],


Rails 4 JS production issues on heroku / asset compiling

Question: Uncaught ReferenceError: Chart is not defined
For all the places where JS is not working properly, I receive similar errors based on which JS file it is trying to read from.
In development, all my JS is reading and executing properly.  In production, some of the JS is not. Here is my application.js file with comments about which are working and which aren't.
application.js
//= require jquery # working
//= require bootstrap.min # working
//= require jquery_ujs # working
//= require turbolinks # working
//= require jquery.ui.all # working
//= require jquery.sidr.min # working
//= require jquery_timepicker_addon # working
//= require infobox # working
//= require buttons # not working
//= require tooltip # not working
//= require deliveries # not working
//= require Chart# not working
//= require jquery-addressPicker # working
//= require_tree .

I run RAILS_ENV=production bundle exec rake assets:precompile
and I've recently read a blog post suggesting running rake assets:clean assets:precompile but that did not solve the issues
production.rb
config.cache_classes = true
config.eager_load = true
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
config.serve_static_assets = false
config.assets.js_compressor = :uglifier
config.assets.digest = true
config.assets.version = '1.0'
config.i18n.fallbacks = true
config.active_support.deprecation = :notify
config.assets.compile = false

Any help on how to debug this issue would be greatly appreciated!
deliveries.js.coffee is the only file I've written myself. The others are all from external libraries.
jQuery ->
  mixes = $('#order_mix_id').html()
  $('#order_job_id').change ->
    job = $('#order_job_id :selected').text()
    escaped_job = job.replace(/([ #;&,.+*~\':"!^$[\]()=>|\/@])/g, '\\$1')
    options = $(mixes).filter("optgroup[label='#{escaped_job}']").html()
    if options
      $('#order_mix_id').html(options)
    else
      $('#order_mix_id').empty()

Answer: A syntax error in the infobox.js file caused files beyond it to not properly define certain variables I called in my code leading to uncaught reference errors.  I'm still not sure why there was 1 file after this file that continued to work properly.
application.js
//= require jquery
//= require bootstrap.min
//= require jquery_ujs
//= require turbolinks
//= require jquery.ui.all
//= require jquery.sidr.min
//= require jquery_timepicker_addon
//= require buttons
//= require tooltip
//= require deliveries
//= require Chart
//= require jquery-addressPicker
//= require_tree .

Comment: RAILS_ENV=production rake assets:clean assets:precompile is helpful to ensure assets are being cleanly rewritten each time you precompile


Cannot redeclare libraries_drush_command()

Question: After issuing the following command in the base drupal folder (/var/www/html)
<code>$ drush status
</code>
I get the following response.
<code>PHP Fatal error:  Cannot redeclare libraries_drush_command() (previously declared in /var/www/html/profiles/commons/modules/contrib/libraries/libraries.drush.inc:13) in /var/www/html/sites/all/modules/libraries/libraries.drush.inc on line 25
Drush command terminated abnormally due to an unrecoverable error.                                                                 [error]
Error: Cannot redeclare libraries_drush_command() (previously declared in
/var/www/html/profiles/commons/modules/contrib/libraries/libraries.drush.inc:13) in
/var/www/html/sites/all/modules/libraries/libraries.drush.inc, line 25
</code>
This is a new server install using RHEL 6.4 (Santiago) and drush 6.0 installed through pear.
Where I might begin to fix this?
Comment: You've got two copies of the libraries module, one in profiles/common and one in sites/all - interestingly both are being included in the page load which suggests they're both installed somehow. Is this just a stock install of Drupal Commons?
Comment: This is version commons 3.3. I may have to let them know...
Answer: Removing /var/www/html/sites/all/modules/libraries/libraries.drush.inc cleared things up. I bungled things up somewhere. IRC #drupal-commons confirmed Clive's note above.
Comment: Make sure to mark your answer as complete. :)
Comment: I intend to mark it; however, there is a 2 day waiting period that must pass before I can.
Comment: I ran into the same issue, after redeclaring libraries module, it had some problem with features module as well, I assume this issue happens if you are using drupal profiles and there's duplication of modules in /profiles/PROFILENAME/modules/contrib/MODULENAME and also in /sites/all/modules/MODULENAME
Answer: Drush seems to load duplicate command files as reported in https://github.com/drush-ops/drush/issues/280
and looks like the they fixed the same https://drupal.org/node/644126


How to get an item from an array of objects stored in Vuex by ID field?

Question: I have an array of objects in a Vuex store. Like this:
[
  {
    id: 1,
    value: 'some value'
  },
  {
    id: 2,
    value: 'other value'
  },
  ...
]

Is there a way to create a getter to get a certain item of the array by id?
Something like
getArrItem(state, id) {
  return state.find(item => item.id === id);
}

Answer: You could use method-style-access as follows :
getArrItem: (state) => (id) => {
  return state.items.find(item => item.id === id);
}


Spearman correlation and splitting 1 variable

Question:        Year.Sales.Advertise.Employees
1               1985 1.05 162 32
2               1986 1.26 285 47
3               1987 1.47 540 23
4               1988 2.16 261 68
5               1989 1.95 360 32
6                1990 2.4 690 17
7               1991 2.37 495 58
8               1992 3.15 948 75
9               1993 3.57 720 98
10             1994 4.41 1.14 43
11             1995 4.5 1.395 76
12             1996 5.61 1.56 89
13            1997 5.19 1.38 108
14             1998 5.67 1.26 76
15             1999 5.16 1.71 65
16              2000 6.84 1.86 93

I want to find the Spearman correlation between Sales and Advertise and ive been stuck for 3 hours please help. I think I have to separate the 1 variable into 5 variables but Im struggling.
Comment: What do you mean by "separate the 1 variable into 5 variables"?
Comment: What happened that your data is in this format? Are you trying to read a tab-delimited file or something but doing it wrong? If this is how you're getting your data, might be better to start debugging upstream of getting correlations
Answer: We can use strsplit to split our data, i.e.
new_df <- setNames(data.frame(do.call(rbind, strsplit(df2$Year.Sales.Advertise.Employees, ' '))),
                   strsplit(names(df2), '.', fixed = TRUE)[[1]])

which gives,

   Year Sales Advertise Employees
1  1985  1.05       162        32
2  1986  1.26       285        47
3  1987  1.47       540        23
4  1988  2.16       261        68
5  1989  1.95       360        32
6  1990   2.4       690        17
7  1991  2.37       495        58
8  1992  3.15       948        75
9  1993  3.57       720        98
10 1994  4.41      1.14        43
11 1995   4.5     1.395        76
12 1996  5.61      1.56        89
13 1997  5.19      1.38       108
14 1998  5.67      1.26        76
15 1999  5.16      1.71        65
16 2000  6.84      1.86        93

You can then use cor (i.e. cor(new_df$Advertise, new_df$Employees)) to find correlations between any columns you want.
NOTE1: Make sure that your initial column is a character (not factor)
NOTE2: By default, cor function calculates the pearson correlation. For spearman, add the argument cor(..., method = "spearman"), as mentioned by @Base_R_Best_R.
DATA
dput(df2)
structure(list(Year.Sales.Advertise.Employees = c("1985 1.05 162 32",
"1986 1.26 285 47", "1987 1.47 540 23", "1988 2.16 261 68", "1989 1.95 360 32",
"1990 2.4 690 17", "1991 2.37 495 58", "1992 3.15 948 75", "1993 3.57 720 98",
"1994 4.41 1.14 43", "1995 4.5 1.395 76", "1996 5.61 1.56 89",
"1997 5.19 1.38 108", "1998 5.67 1.26 76", "1999 5.16 1.71 65",
"2000 6.84 1.86 93")), class = "data.frame", row.names = c(NA,
-16L))

Answer: Not sure if you are looking for something like below or other things
# split strings into separate columns
df <- `names<-`(data.frame(t(apply(df, 1, function(x) as.numeric(unlist(strsplit(x,split = " ")))))),
          unlist(strsplit(names(df),split = "\\.")))

# calculate correction coefficient
r <- cor(df$Sales,df$Advertise)

such that
> r
[1] -0.5624524

DATA
df <- structure(list(Year.Sales.Advertise.Employees = c("1985 1.05 162 32",
"1986 1.26 285 47", "1987 1.47 540 23", "1988 2.16 261 68", "1989 1.95 360 32",
"1990 2.4 690 17", "1991 2.37 495 58", "1992 3.15 948 75", "1993 3.57 720 98",
"1994 4.41 1.14 43", "1995 4.5 1.395 76", "1996 5.61 1.56 89",
"1997 5.19 1.38 108", "1998 5.67 1.26 76", "1999 5.16 1.71 65",
"2000 6.84 1.86 93")), class = "data.frame", row.names = c(NA,
-16L))

> df
   Year.Sales.Advertise.Employees
1                1985 1.05 162 32
2                1986 1.26 285 47
3                1987 1.47 540 23
4                1988 2.16 261 68
5                1989 1.95 360 32
6                 1990 2.4 690 17
7                1991 2.37 495 58
8                1992 3.15 948 75
9                1993 3.57 720 98
10              1994 4.41 1.14 43
11              1995 4.5 1.395 76
12              1996 5.61 1.56 89
13             1997 5.19 1.38 108
14              1998 5.67 1.26 76
15              1999 5.16 1.71 65
16              2000 6.84 1.86 93

Comment: Thanks, works perfectly but with my data it shows an error: supply both 'x' and 'y' or a matrix-like 'x'. I think it's because year sales etc. are all in 1 variable and need to be split and I don't know how to :(
Answer: If you're asking for the data to be split into 4 discrete columns, this should do it.
Your data in the question needed some cleaning.  It probably needs more (manual) cleaning, as advertise falls from 720 to 1.14 between 1993 and 1994.  That's likely from hundreds of thousands to millions.
x <- c("1985 1.05 162 32",
  "1986 1.26 285 47",
  "1987 1.47 540 23",
  "1988 2.16 261 68",
  "1989 1.95 360 32",
  "1990 2.4 690 17",
  "1991 2.37 495 58",
  "1992 3.15 948 75",
  "1993 3.57 720 98",
  "1994 4.41 1.14 43",
  "1995 4.5 1.395 76",
  "1996 5.61 1.56 89",
  "1997 5.19 1.38 108",
  "1998 5.67 1.26 76",
  "1999 5.16 1.71 65",
  "2000 6.84 1.86 93")

library(tidyverse)
clean_df <- x %>%
  as.data.frame() %>%
  separate('.',
           into = c('year','sales', 'advertise', 'empl'),
           sep = ' ') %>%
  as_tibble() %>%
  mutate_all(as.numeric)

cor(clean_df$sales, clean_df$advertise, method = 'spearman')


Matplotlib - Pie Chart from dataframe

Question: I saw a sample from the internet to build a simple pie chart from Matplotlib but not sure how to embed it with my dataset (https://gist.github.com/datomnurdin/33961755b306bc67e4121052ae87cfbc).
from pandas import DataFrame
import matplotlib.pyplot as plt
import pandas as pd

df = pd.read_csv('data.csv')

my_labels = 'Positive','Neutral','Negative'
my_colors = ['lightblue','lightsteelblue','silver']
plt.pie(df, labels=my_labels, autopct='%1.1f%%', startangle=15, shadow = True, colors=my_colors)
plt.title('Sentiment Overview')
plt.axis('equal')
plt.show()

P.S: The dataset didn't contain any labels, only values.
Answer: I would do something like this:
my_labels = {1:'Positive',0:'Neutral',-1:'Negative'}
my_colors = ['lightblue','lightsteelblue','silver']

# count the values to plot pie chart
s = df.sentiment.map(my_labels).value_counts()

plt.pie(s, labels=s.index, autopct='%1.1f%%', colors=my_colors)
# also
# s.plot.pie(autopct='%1.1f%%', colors=my_colors)

plt.show()

Output:

Matplotlib - Pie Chart from dataframe


jQuery + jQuery Mobile + Chrome 20

Question: We are experiencing a strange problem after updating Google Chrome to the latest version, can someone help us? we are getting out of ideas.
We have several .aspx pages in wich we include jquery core (1.7.1) and jquery mobile (1.1.0) and some jqm plugins. everything worked perfectly until we updated google chrome... we started getting totaly random errors like:

"Uncaught TypeError: Cannot call method 'apply' of undefined"
  "Uncaught TypeError: Cannot call method 'jqmData' of undefined"

In Firefox, IE9/10 and Safari everything works properly.
The exception is beeing thrown by jquery mobile in the initializePage function.
we created a basic page (structure and some basic elements)... still no luck.
We found this similar problem but is from 2010.
http://productforums.google.com/forum/#!msg/chrome/JDKZxXsQZiE/sdW9-g1rxYs
Any ideas/sugestions?
Answer: could it be about that v8 bug : http://code.google.com/p/chromium/issues/detail?id=125148 ?
if so, see the workaround there : Chrome sometimes calls incorrect constructor
Comment: tks :D
we are going to give it a try!

jQuery + jQuery Mobile + Chrome 20