Alterar tipo 'None' de um dicionário em python

Question: Preciso alterar o valor de uma chave de um dicionário, cujo valor vem como 'None'.
Exemplo: a = {b: 'qualquer', c: 'qualquer'}, sendo que esse é meu dicionário em python.
Sendo que 'qualquer' se refere a valores aleatórios, sendo que também pode vir valores do tipo None. Não posso fazer a modificação de modo geral, pois não sei quando irá vir valor do tipo None ou não.
Agora eu quero pegar o valor de a['b'] tal que, a['b'] !=  None. Ou sendo mais preciso, quando a['b'] == None fazer virar um string vazia, ou seja, a['b'] == "".
Eu tentei utilizar a função re.sub() , mas sem sucesso:
a['b'] = re.sub(None, "", a['b'])
Comment: Resumindo, você quer que todos os valores que forem `None` no seu dicionário virem uma string vazia?
Comment: @sourcream não todos, mas 1 especifico. Sendo que nesse exemplo é determinado pela chave 'b'.
Comment: Amigo, desculpa, não consigo entender o que tu queres... Tu poderias tentar explicar melhor o problema?
Comment: @LeonardoAlvesMachado quando o valor vir `None` em `a['b']` quero que vire uma string vazia. Assim como deixei claro no enunciado.
Comment: Para isso, basta testar esse campo específico... Um simples `if` faz isso...
Comment: `a["b"] if a["b"] is not None else ""`
Comment: Olha, pensei que não iria funcionar. Pois o valor estava sendo atribuido a um elemento de outro dicionário. Eu sempre utilizo esses testes, mas estava pensando em alguma coisa diferente. Mas no fim, deu certo rsrs. O que eu mais utilizo não estava testando. De qualquer maneira, value demais @LeonardoAlvesMachado.
Comment: Adicione ao campo de respostas, para que assim eu possa escolhe-la.
Answer: Se temos um dicionário do tipo:
a = {b: 'qualquer', c: 'qualuqer'} onde qualquer diz respeito a qualquer entrada aleatório, então para que a['b'] quando for None ser substituido por uma string vazia, do tipo "", basta fazer o seguinte teste com if..
a["b"] if a["b"] is not None else ""
Sendo assim, se a['b'] for None irá ser substituido por "".
Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


How do I use 2 loops, and if it is false, repeat the program indefinetely

Question: Right now I am doing the tutorial "Dragon Realm" from this site http://inventwithpython.com/chapter6.html
I understand what it's all doing slightly but that is not my problem. At the end I'm wanting to add a bit of code that if the player says no, it says, as I currently have it, "too bad *!" and move back up to the beginning of the program. I've gotten it to do that, but once it goes through the second time and i get to the input of whether you want to try again whether or not you type yes or no it just ends the program. I've tried multiple combinations of while, if/else, while True, while False and I am not getting the results I am wanting. I don't understand how you just keep it to keep going? It's probably really simple but I can't figure it out.
this is the code for the program.
import random
import time
def displayIntro():
    print('You are in a land full of dragons. In front of you,')
    print('you see two caves. In one cave, the dragon is friendly')
    print('and will share his treasure with you. The other dragon')
    print('is greedy and hungry, and will eat you on sight.')
    print()
def chooseCave():
    cave = ''
    while cave != '1' and cave != '2':
        print('Which cave will you go into? (1 or 2)')
        cave = input()
    return cave
def checkCave(chosenCave):
    print('You approach the cave...')
    time.sleep(2)
    print('It is dark and spooky...')
    time.sleep(2)
    print('A large dragon jumps out in front of you! He opens his jaws and...')
    print()
    time.sleep(2)
    friendlyCave = random.randint(1, 2)
    if chosenCave == str(friendlyCave):
        print('Gives you his treasure!')
    else:
        print('Gobbles you down in one bite!')
playAgain = 'yes'
while playAgain == 'yes' or playAgain == 'y':
    displayIntro()
    caveNumber = chooseCave()
    checkCave(caveNumber)
    print('Do you want to play again? (yes or no)')
    playAgain = input()

Comment: no need for foul language
Comment: Please reduce the code to the essential part of your problem.
Comment: Excuse me for posting what I had in my code, but noted, although your censorship offends me more.
Comment: Andre the issue has been resolved but, thanks for your interest in helping me!
Answer: You could add simply,
if 'n' in playAgain:
    print "too bad"
    playAgain = 'yes'

At the end (inside your while loop)
By the way, these two lines can be combined:
print('Do you want to play again? (yes or no)')
playAgain = input()

as simply:
playAgain = input('Do you want to play again? (yes or no)')

Because input will display the string argument when asking for input.


How to search an infinite list of words in sorted order for an index corresponding to a word as input

Question: I am confounded by a hard problem I am having with a given stream I am dealing with to do better the linear time O(n)..
Search an infinite list of words in sorted order for an index corresponding to a word as input
given an infinite list ["apple", "banana", "cat", "dog", ...]
we have a class A where A.get(2) # => "cat"
write a function to return the index for the word given as input to the function like so:
A.get_index("cat") # => 2

you can use A.get() but not python the .index() for sequences
Comment: Using a `for` loop with `enumerate` should suffice here.
Comment: search an infinite list of words in sorted order.So while loop?
Comment: and you want none duplicates from A.get_index() I assume?
Comment: You can use a binary search
Comment: Can you show your try in O(N)?
Answer: IIUC, you can do it in O(log n) with a modification of binary search.
import bisect

def find(endless_haystack, needle):

    if endless_haystack[0] == needle:
        return 0

    i = 1
    hay = endless_haystack[i]
    while hay < needle:  # this is O(log n) where n is the index of the element
        i = 2 * i
        hay = endless_haystack[i]

    # from the loop before the element is between i and i // 2
    return bisect.bisect_left(endless_haystack, needle, i // 2, i)

Be aware that the above code is a sketch of an actual solution, you need to check for some edge cases.
Comment: If the infinite list it is not infinite then this is best +1
Comment: I think you meant `i = 0` and `i = 2 * i`?
Comment: @EricSteen Updated the answer
Answer: you can use the built-in function enumerate who is giving you the index and the element:
def get_index(word, my_infinite_list):
    return next(i for i, e in enumerate(my_infinite_list) if e == word)

the built-in function next will make sure to iterate over your list until you find the wanted word
Comment: I am not sure you can use enumerate on an infinit list (or generator)
Comment: yes you can, here are the docs: https://docs.python.org/3/library/functions.html#enumerate
Comment: and the OP was showing a list in the question, maybe a big list, not an infinite list, there is no such thing :)
Comment: Also OP was saying an infinite loop, but if you look at the restriction to not use list.index make sense to show an example in o(n) this is the time complexity for list.index, OP may clarify if he will show his try
Answer: Simply iterate over the list by incrementing a counter until you hit a corresponding value
class A:
   [...]

   def get_index(self, item):
       i = 0
       while self.get(i) != item:
           i += 1
       return i

Note: That this is not very secure code. But because we assume the list is infinite, you don't risk to hit out of index. There is an overflow risk though...


Can I do git-clean with libgit2?

Question: I want to remove untracked files from the working tree. Like here
https://www.kernel.org/pub/software/scm/git/docs/git-clean.html
Answer: libgit2 doesn't implement this itself. It's a porcelain command, which deals with interaction with the user. It also deals primarily with files which are of no interest to the Git repository.
You can run status to see which files are untracked and then remove whichever ones the version of git-clean would have removed through the usual means available in your programming language.
Comment: Is this the reason `REPOSITORY.index.remove()` leaves untracked files lying around in the working directory?

Can I do git-clean with libgit2?


Logged file system access

Question: Assuming the info is there, how I found out who accessed a certain shared folder or a file and made changes (like create a file and delete others) ?
Comment: By reading the log?  I... ugh.
Answer: By default, Windows does not record that type of information. So if you haven't turned on that type of logging and you're looking for something that already happened, you're out of luck.
Answer: A bit of research.
Most likely the user who created a file will also be the file's owner. By switching on file auditing (which was on as I said in my question), it is possible to look at who made changes to the file as well.

Logged file system access


Cannot find the input date into the textbox

Question: How can I search my date into the datagrid view? I have a sample code which I think is correct but why does it not search?

    private void textBox3_TextChanged(object sender, EventArgs e)
    {

        if (string.IsNullOrEmpty(textBox3.Text))
        {
            SqlDataAdapter sda = new SqlDataAdapter("Select * from STUDENT_RESEARCH_PROJECTS WHERE COURSE LIKE '" + comboBox2.Text + "%'", con);
            DataTable data = new DataTable();
            sda.Fill(data);
            dataGridView1.DataSource = data;
        }

        else
        {
            SqlDataAdapter sda = new SqlDataAdapter("SELECT ACCESSION_NO,TITLE_PROJECT,CATEGORY,YEAR,COURSE,DATE,Student_Name1,Student_Name2,Student_Name3,Student_Name4,Student_Name5,RELATED_TITLE1,RELATED_TITLE2,RELATED_TITLE3,RELATED_TITLE4,RELATED_TITLE5 FROM STUDENT_RESEARCH_PROJECTS WHERE DATE LIKE'" + textBox3.Text + "%'", con);
            DataTable data = new DataTable();
            sda.Fill(data);
            dataGridView1.DataSource = data;
        }
    }

Comment: Ever heard of SQL-injection?
Comment: Is the Property of the textbox3 set? What does the debugger say?
What type does the date-column in the database have? Not sure if you can query a date with like. Also you should be aware of sql-injection but I am sure, thats only for the sample :-)
Comment: Have you run your query directly against the database? does it return any records? Take the query along with textbox3.Text and try to run against the database first.
Answer: You cannot use LIKE for date comparison unless your DATE field is a string
Also you need to check how is the date data saved into database
For example in my database I am using datetime which is being saved like 2018-03-20 07:25:58.557
So when you are querying you need to put a format of your date in order to be accepted
Answer: First be aware SQL injection.
you cannot use like operator on Date Column.
Your search TextBox value date format is 03/20/2018(mm/dd/yyyy) and database column contains something different which is usually 2018-03-20 00:00:00.000 to search with the date change the format when querying from database like this.
    private void textBox3_TextChanged(object sender, EventArgs e)
    {

        if (string.IsNullOrEmpty("textBox3.Text"))
        {
            string query = "Select * from STUDENT_RESEARCH_PROJECTS WHERE COURSE LIKE @COURSE";
            SqlCommand cmd = new SqlCommand(query, con);
            cmd.Parameters.AddWithValue("@COURSE", comboBox2.Text);

            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            DataTable data = new DataTable();
            sda.Fill(data);
            dataGridView1.DataSource = data;
        }

        else
        {
            string query = "SELECT ACCESSION_NO,TITLE_PROJECT,CATEGORY,YEAR,COURSE,DATE,Student_Name1,Student_Name2,Student_Name3,Student_Name4,Student_Name5,RELATED_TITLE1,RELATED_TITLE2,RELATED_TITLE3,RELATED_TITLE4,RELATED_TITLE5 FROM STUDENT_RESEARCH_PROJECTS WHERE CONVERT(varchar(10) ,DATE, 101)  = @DATE";
            SqlCommand cmd = new SqlCommand(query, con);
            cmd.Parameters.AddWithValue("@DATE", textBox3.Text);
            SqlDataAdapter sda = new SqlDataAdapter();
            DataTable data = new DataTable();
            sda.Fill(data);
            dataGridView1.DataSource = data;
        }
    }


Automate excel import data from SQL (multiple databases)

Question: I want to get a data dump of SQL server data into excel spreadsheets.
With Excel, importing data from an external data source (from SQL Server Database), I would be able to get data from SQL Server into the spreadsheet.
Would there be a way to automate this process
I need to put into excel files, data from 6 queries (the same 6 queries) , from a 100+ sql database instances.
Only the DB name would keep changing. Looking for advice to help automate the process.
Thanks in advance
Answer: I'd leave this as a comment if I could - this is definitely doable, you could connect to the sqlserver instance with VBA, execute your queries to return Recordset objects, use CopyFromRecordset to paste the result to Excel, and then save the workbook.
If you need to do it for 100+ databases, you can just run the script on a loop, and update the database name in your connection string each time
This has a complete example for connecting to a DB, return a query as a recordset, and pasting it into Excel:
https://www.mrexcel.com/board/threads/vba-to-connect-to-sql-server.617788/
If you haven't done this before , getting the connection string right the first time is usually tricky - and if you don't have experience with VBA you may need help learning to add worksheets/save workbooks, but that's a separate issue


Move Dimension Line to New Layer using ezdxf

Question: I used ezdxf to change the layer name and try to move the entity, but only the dimension line remains on the old layer.
I wrote code to move an entity to a new layer name, but it didn't move.
import ezdxf
import glob
from pathlib import Path
from typing import TYPE_CHECKING, TextIO, Iterable

file_list=glob.glob('./input/*.dxf')
for filename in file_list:
    dwg = ezdxf.readfile(filename,encoding='auto',legacy_mode=False)
    msp = dwg.modelspace()

old_layername1 = 'ABC'
new_layername1 = 'DEF'

try:
    layer = dwg.layers.get(old_layername)
except ValueError:
    print('Layer {} not found.'.format(old_layername))
else:
    layer.dxf.name = new_layername

# move entities in model space to new layer
all_entities_on_old_layer = dwg.modelspace().query('*[layer=="%s"]' % old_layername)
for entity in all_entities_on_old_layer:
    entity.dxf.layer = new_layername  # this assigns the new layer

Only the dimension line remains in the old layer name.
I want to know the solution.
Answer: Renaming layers is not implemented in ezdxf. The usage of layers is not bound to the table entries, this means if you rename a layer table entry, all entities of this layer still have the old layer name stored as DXF attribute, remember ezdxf is an interface to DXF file format not a CAD application. In your special case the DIMENSION entity has also a graphical representation as anonymous BLOCK, all entities of this BLOCK may still refer to the old layer name, also some entities of other BLOCKS and paperspace layouts. This is the code to rename a layer and all entities referring to this layer, tested with beta version v0.10:
import ezdxf

def rename_layer(doc, old, new):
    """
    Works only for layers with an entry in the layer table,
    layers can be used without such an entry.
    """
    if old not in doc.layers:
        raise ValueError('Old layer "{}" does not exist.'.format(old))
    if new in doc.layers:
        raise ValueError('New layer "{}" does already exist.'.format(new))

    def rename_layer_table_entry():
        layer = doc.layers.get(old)
        layer.dxf.name = new
        # this is an internal API call, renaming table entries isn't implemented (yet)
        doc.layers.replace(old, layer)

    def rename_entities_layer_attribute():
        # layer names are case insensitive
        old_lower = old.lower()
        # iterate over all entities of modelspace, paperspace layouts
        # and block definitions
        for e in doc.chain_layouts_and_blocks():
            if e.get_dxf_attrib('layer', '0').lower() == old_lower:
                e.dxf.layer = new

    rename_layer_table_entry()
    rename_entities_layer_attribute()

# TESTING

def add_entities(layout):
    layout.add_text('A', dxfattribs={'layer': 'text'})
    layout.add_line((0, 0), (1, 1), dxfattribs={'layer': 'line'})

doc = ezdxf.new('R2010')
doc.layers.new('text')
doc.layers.new('line')

msp = doc.modelspace()
add_entities(msp)

blk = doc.blocks.new('Test')
add_entities(blk)

rename_layer(doc, 'text', 'text1')
rename_layer(doc, 'line', 'line1')

assert msp[0].dxf.layer == 'text1'
assert msp[1].dxf.layer == 'line1'

assert blk[0].dxf.layer == 'text1'
assert blk[1].dxf.layer == 'line1'

assert 'text1' in doc.layers
assert 'line1' in doc.layers

This function does not care about existing layer filters, which may be broken or frozen layers in viewports and all the things I still don't know. Overall renaming layers is not a good idea and may produce unreadable DXF files.
Update:
Added rename method to Layer, will be released with v0.10b4:
layer = doc.layers.get(old_name)
layer.rename(new_name)

Renames all known layer references, but not for LAYER_INDEX and LAYER_FILTER, both entities are just preserved as a bunch of tags by ezdxf, so be careful - renaming layers with ezdxf may damage DXF files.
Comment: Thank you for answering.
Sorry for replying late.
I tried the code you gave me.
Sometimes it works, but 2D polylines remain in the old layer.
Is there a solution?


nginx and 2 upstreams

Question: I want to do the following:
I have nginx that redirects to tomcat, so the config is something like this:

    upstream miserver.com {
         server localhost:8080;
    }

    server {

        listen      0.0.0.0:80;
        location / {
            proxy_pass http://miserver.com/mywar-web-0.4/convert;
        }
   }

What I want to do is that nignx hits to upstreams, and only takes into account the response of one of them. This is because I want to test a new version of the war, but I still want to continue with the old one (the new one will log the information in a file).
For example, I want to have:

    upstream miserver.com {
         server localhost:8080;
    }

    server {

        listen      0.0.0.0:80;
        location / {
            proxy_pass http://miserver.com/mywar-web-0.4/convert;
            proxy_pass http://miserver.com/mywar_testing-web-0.4/convert;
        }
   }

and when there is a hit on "/", then nginx hits:
- mywar-web-0.4
- mywar_testing-web-0.4
but only the resonpse of mywar-web-0.4 is used.
Comment: You cant have 2 redirects/proxies for the one location..
Answer: Does This work for you?
 upstream miserver.com {
         server localhost:8080;  <- This is Live mywar-web-0.4
         server localhost:8081;  <- This is Testing mywar_testing-web-0.4
    }

    server {
        listen      0.0.0.0:80;
        location / {
            proxy_pass http://miserver.com;
        }
   }

Not sure if you can do this, and still know what backend your using

Hope this helps :D
Comment: In that case, the localhost:8080 will answer and if it is down, then the localhost:8081 will be used. I want that the 2 servers get the request, not just one of them
Comment: That works. But I have to change the location. I want to use the same location for the 2 upstreams.
Comment: You mean so that they overlap??

If you try to do that.. basically, one request will go to live, another request to testing.. ( how will you know) which one your on???
Comment: Is that better?? i updated my answer..
Comment: Noo it will be shared, between requests ( alternating ).. :D
Answer: I load balance 4 tornado servers with this configuration.
upstream frontends {
    server 127.0.0.1:8888;
    server 127.0.0.1:8889;
    server 127.0.0.1:8890;
    server 127.0.0.1:8891;
}
server {
    listen 80;
    location / {
        proxy_pass http://frontends;
    }
}

Requests are distributed among each server in the "frontends" list and if one is down it will be ignored until it reachable.
In your example you could have each of your wars handle part of the traffic at / if they are each listening on a different port.
Check the Upstream module documentation for more information.
Comment: I don't want to distributer the request. I want that all the servers recieve the same requests.
Comment: Neither upstream nor proxy_pass will let you do that. When a client connects it opens 1 socket to nginx, nginx opens a socket with the server it is proxying and funnels the response back through that. There wouldn't be a situation where it opens a second socket to your other server and just discards the response.
Comment: If you are looking for a way to test your new war with the same traffic. Maybe you could use the access logs to replay the traffic against /testing/ or something similar.
Answer: What you basically want is to have a single client request result in nginx making two requests to the backend servers, but only return the result of one of such requests back to the client.  This is very unusual, and it's not something that's generally supported.

You might want to try to play some tricks with error_page.  You would want to make the first request (the reply for which is to be discarded), and then catch its status code as an error, and then use a named location (the one that starts with @ and does not rewrite $uri) to handle the subsequent request, which will be returned to the client.  Not sure if you can specify error_page 200, if not, then you might have to modify your app (the reply of which is to be discarded) to return some actual error code instead.
Alternatively, you may try using some kind of a filter module, like ngx_http_addition_module and add_after_body directive.  Although this is an official module that's already part of the source-code distribution of nginx, it requires recompilation, and it would also result in two replies given back to the user, so you'd have to modify your app anyways.

nginx and 2 upstreams


ImportError: DLL load failed while importing _pydna: The specified module could not be found

Question: Update: I traced the line which is causing the problem.

Error is coming from dna.py file, from line code 15.
This is the code:
<code>    # Import the low-level C/C++ module
if __package__ or '.' in __name__:
    from . import _pydna
else:
    import _pydna
</code>
if is never true. I printed __ Package __ it prints nothing. it is empty. I printed __ Name __ it prints "dna".
from what I can gather. it's not finding my current folder that _pydna is located in. I don't understand the code fully, but I know python swig generated it and this is what Swig uses to import modules.
I don't understand where else statement is supposed to import _pydna from. Am I supposed to pip install it somewhere?

Import Error: DLL load failed while importing _pydna: The specified module could not be found.
This is the error I am getting in Autodesk Maya console.
I want to export my Meta Human from Quixel Bridge, I have exported my Meta Human with UAsset + Source Asset as their documentation suggested. Export is shown to be successful. But nothing appears in Maya. I have checked the console, and this is the error I am getting:
Import Error: DLL load failed while importing _pydna: The specified module could not be found.
I am using Windows 11 and Maya 2024 student version.
Full Console Log:
<code>file -f -new;
// untitled
commandPort -securityWarning -name commandportDefault;
onSetCurrentLayout "General";
# DHI.modules.maya.util : Preparing paths and loading DHI Plugins
# DHI.modules.maya.util : Running on Windows
Importing DHI external libraries
# DHI.modules.maya.util : Running Maya version 2017
# DHI.modules.maya.util : Fetching libraries from folder D:/Quixel Bridge/Megascans Library/support/plugins/maya/7.0/MSLiveLink/DHI/lib/Windows/python2
# DHI.modules.maya.util : Lib folder not on path... Adding
# DHI.modules.maya.util : Running on Windows
# modules.maya.util : Running Maya version 2017
Loading plugin:  D:/Quixel Bridge/Megascans Library/support/plugins/maya/7.0/MSLiveLink/DHI/plugins/Windows/2017/embeddedRL4.mll
Error loading plugin embeddedRL4
Loading plugin:  D:/Quixel Bridge/Megascans Library/support/plugins/maya/7.0/MSLiveLink/DHI/plugins/Windows/2017/MayaUE4RBFPlugin2017.mll
Error loading plugin MayaUE4RBFPlugin2017
Loading plugin:  D:/Quixel Bridge/Megascans Library/support/plugins/maya/7.0/MSLiveLink/DHI/plugins/Windows/2017/MayaUERBFPlugin.mll
Error loading plugin MayaUERBFPlugin
saveShelf MSPlugin "C:/Users/Danish Nazir Arain/Documents/maya/2024/prefs/shelves/shelf_MSPlugin";
// 1
Quixel Bridge Plugin started successfully.
// Bifrost: Pre-loaded mayaUsdPlugin to access proper Maya USD libraries.
// Loading Bifrost version 220.127.116.11-202302170226-ac4d174
// Bifrost: Loading library: Amino, from: Autodesk.
// Bifrost: Loading library: AminoMayaTranslation, from: Autodesk.
// Bifrost: Loading library: bif, from: Autodesk.
// Bifrost: Loading library: bifrostObjectMayaTranslations, from: Autodesk.
// Bifrost: Loading library: geometries, from: Autodesk.
// Bifrost: Loading library: fluids, from: Autodesk.
// Bifrost: Loading library: particles, from: Autodesk.
// Bifrost: Loading library: file, from: Autodesk.
// Bifrost: Loading library: mpm, from: Autodesk.
// Bifrost: Loading library: modeling, from: Autodesk.
// Bifrost: Loading library: nucleus, from: Autodesk.
// Bifrost: Loading library: simulation, from: Autodesk.
// Bifrost: Loading library: riv_types, from: Autodesk.
// Bifrost: Loading library: riv, from: Autodesk.
// Bifrost: Loading library: scatter_pack, from: Autodesk.
// Bifrost: Loading library: graphs, from: Autodesk.
// Bifrost: Loading library: usd_pack, from: Autodesk.
// Bifrost: Loading library: usdMayaTranslations, from: Autodesk.
// Warning: file: C:\Users\Danish Nazir Arain\Documents\maya\2024\prefs\filePathEditorRegistryPrefs.mel line 4: filePathEditor: Attribute 'aiImage.filename' is invalid or is not designated 'usedAsFilename'.
// Warning: file: C:\Users\Danish Nazir Arain\Documents\maya\2024\prefs\filePathEditorRegistryPrefs.mel line 5: filePathEditor: Attribute 'aiPhotometricLight.aiFilename' is invalid or is not designated 'usedAsFilename'.
// Warning: file: C:\Users\Danish Nazir Arain\Documents\maya\2024\prefs\filePathEditorRegistryPrefs.mel line 6: filePathEditor: Attribute 'aiStandIn.dso' is invalid or is not designated 'usedAsFilename'.
// Warning: file: C:\Users\Danish Nazir Arain\Documents\maya\2024\prefs\filePathEditorRegistryPrefs.mel line 7: filePathEditor: Attribute 'aiVolume.filename' is invalid or is not designated 'usedAsFilename'.
// AbcExport v1.0 using Alembic 1.8.3 (built Feb 17 2023 07:53:30)
evalDeferred "shaderBallRendererMenuUpdate";
// Warning: line 1: filePathEditor: Attribute 'aiStandIn.dso' and label 'Standin' have been saved already.
// Warning: line 1: filePathEditor: Attribute 'aiVolume.filename' and label 'VDB' have been saved already.
// Warning: line 1: filePathEditor: Attribute 'aiImage.filename' and label 'Image' have been saved already.
// Warning: line 1: filePathEditor: Attribute 'aiPhotometricLight.aiFilename' and label 'IES' have been saved already.
import arnold
import mtoa
import mtoa.cmds.registerArnoldRenderer;mtoa.cmds.registerArnoldRenderer.registerArnoldRenderer()
updateRenderOverride;
import mtoa.viewport;mtoa.viewport.add_controls()
// AbcImport v1.0 using Alembic 1.8.3 (built Feb 17 2023 07:53:30)
updateRendererUI;
file -f -new;
// untitled
Found import data, importing...
Analytics Sent
Received data with DH Character descriptor. Initializing import!
# Traceback (most recent call last):
#   File "D:\Quixel Bridge\Megascans Library\support\plugins\maya\7.0\MSLiveLink\LiveLink.py", line 124, in InitializeImporter
#     from DHI.DHIImporterSetup import DHIImporterSetup
#   File "D:\Quixel Bridge\Megascans Library\support\plugins\maya\7.0\MSLiveLink\DHI\DHIImporterSetup.py", line 8, in <module>
#     from DHI.modules.dna.scene.builder.sceneBuilder import SceneBuilder, SceneBuilderError
#   File "D:\Quixel Bridge\Megascans Library\support\plugins\maya\7.0\MSLiveLink\DHI\modules\dna\scene\builder\sceneBuilder.py", line 7, in <module>
#     from DHI.modules.dna.dnaprovider import DNAProvider
#   File "D:\Quixel Bridge\Megascans Library\support\plugins\maya\7.0\MSLiveLink\DHI\modules\dna\dnaprovider.py", line 5, in <module>
#     from DHI.modules.dna.dnaholder import DNAHolder
#   File "D:\Quixel Bridge\Megascans Library\support\plugins\maya\7.0\MSLiveLink\DHI\modules\dna\dnaholder.py", line 1, in <module>
#     import dna
#   File "D:\Quixel Bridge/Megascans Library/support/plugins/maya/7.0/MSLiveLink/DHI/lib/Windows/python2\dna.py", line 15, in <module>
#     import _pydna
# ImportError: DLL load failed while importing _pydna: The specified module could not be found.
</code>
Answer: Quixel Bridge for now doesn't support Maya 2024. Quixel FAQs
https://help.quixel.com/hc/en-us/community/posts/11225123454109-Import-Error-DLL-load-failed-while-importing-pydna-The-specified-module-could-not-be-found-From-Quixel-Bridge-to-Maya-Export-


Can the referee stop play for an injury or any other reason?

Question: I know that traditionally if a player is injured someone will kick the ball out of bounds in order to stop play. My question is whether the referee has any discretion to stop play for an injury or other reason, for example, pitch invasions.
If the referee is able to, how does the game restart and who is in possession of the ball when the game restarts?
Answer: If the referee stops play while the ball is still in play (for an injury or a pitch invasion or any other reason), play is restarted with a dropped ball.
FIFA Laws of the Game 2015/16 Law 8: Start and Restart of Play

Definition of dropped ball
  A dropped ball is a method of restarting play when, while the ball is still in play, the referee is required to stop play temporarily for any reason not mentioned elsewhere in the Laws of the Game.
Procedure
  The referee drops the ball at the place where it was located when play was
  stopped, unless play was stopped inside the goal area, in which case the
  referee drops the ball on the goal area line parallel to the goal line at the point nearest to where the ball was located when play was stopped.
  Play restarts when the ball touches the ground.
Infringements and sanctions
The ball is dropped again:
  •    if it is touched by a player before it makes contact with the ground
  •    if the ball leaves the field of play after it makes contact with the ground,without a player touching it
If the ball enters the goal:
  •    if a dropped ball is kicked directly into the opponents' goal, a goal kick is awarded
  •    if a dropped ball is kicked directly into the team's own goal, a corner kick is awarded to the opposing team
Answer: The referee is only permitted to stop play for an injury if it is deemed serious. Head injuries, suspected fractures, loss of consciousness, open wounds and heavy collisions would usually be deemed serious; rolled ankles, cramps and minor knocks would generally not be deemed serious.
From p. 45 - 46 of the 2016/17 FIFA Laws of the Game:

The Referee:
...
Injuries

allows play to continue until the ball is out of play if a player is only slightly injured
stops play if a player is seriously injured and ensures that the player is removed from the field of play.

It goes on further to state that the restart of play is a dropped ball.

if play has not been stopped for another reason, or if an injury suffered by a player is not the result of an infringement of the Laws of the Game, play is restarted with a dropped ball

By playing the ball out when an opponent is only slightly injured, teams are waiving their right to continue playing as an act of respect for their opponents.
Teams will generally play the ball out immediately if one of their teammates is injured, in order to restore their side to full strength. However, they will usually not play the ball out in the middle of a promising attack, since the attack is more important than having a full complement of players.
In previous editions of the Laws, it vaguely stated that the referee could stop, suspend or abandon the match for any outside interference. In the new 2016/17 edition of the Laws, some examples of what may constitute outside interference are provided on p. 47 - 48:

The Referee:
...
Outside interference

stops, suspends or abandons the match for any infringements of the Laws or
because of outside interference e.g. if:

the floodlights are inadequate
an object thrown by a spectator hits a match official, a player or team official, the referee may allow the match to continue, or stop, suspend or abandon it depending on the severity of the incident
a spectator blows a whistle which interferes with play - play is stopped and restarted with a dropped ball
an extra ball, other object or animal enters the field of play during the
match, the referee must:

stop play (and restart with a dropped ball) only if it interferes with play unless the ball is going into the goal and the interference does not prevent a defending player playing the ball, the goal is awarded if the ball enters the goal (even if contact was made with the ball) unless the
ball enters the opponents' goal.
allow play to continue if it does not interfere with play and have it removed at the earliest possible opportunity.

On p. 36, the procedure for handling persons other than players entering the field of play is outlined:

The coach and other officials named on the team list (with the exception of players or substitutes) are team officials. Anyone not named on the team list as a player, substitute or team official is an outside agent.
If a team official, substitute, substituted or sent off player or outside agent enters the field of play the referee must:

only stop play if there is interference with play
have the person removed when play stops
take appropriate disciplinary action

If play is stopped and the interference was by:

a team official, substitute, substituted or sent off player, play restarts with a direct free kick or penalty kick
an outside agent, play restarts with a dropped ball

If a ball is going into the goal and the interference does not prevent a defending player playing the ball, the goal is awarded if the ball enters the goal (even if contact was made with the ball) unless the ball enters the opponents' goal.


Probabilities of one-off events

Question: I am teaching 15 year olds basic probability. I am teaching them "experimental probabilities" (eg the probability that it will rain on a given day in August is 0.15) vs "theoretical probabilities" (eg the probability of throwing 3 Heads in a row is 1/8).
When I asked them for some examples of experimental probabilities, a couple mentioned one-off events, like the probability that their team wins their next match, or that it rains tomorrow.
I can't see that one-off events can have a probability other than 0 or 1. They cannot be re-run and hence their is no basis for determining or assigning a probability.
I would like to correct my students if and when they next make this error, but before doing so I would like to make sure of my facts. Is it legitimate, for example, to talk about a 40% chance of rain tomorrow, and if so, what does it mean?
Comment: It depends on how you think about probability. If you are a frequentist, which is implied by the way you talk about one-off events, then it doesn't really make sense. Or you have to think about them in some very convoluted way. But if you have a Bayesian look on probability, then probability reflects your subjective assessment of the outcome of an event. And in that case, one-off events can be given a probability.
Answer: 40% chance of rain tomorrow usually means (Laplace's definition) that on average, with the same meteorological conditions as you observe today, it will on average rain 40% of the time.
That you cannot repeat tomorrow, does not mean that you cannot repeat the same conditions as the ones in which tomorrow will happen.
Where this does reflect, is in the state of the random variable. If you want the random variable for it raining tomorrow or not, it will be $0$ or $1$ integer, not a real number.
Note this is not true with a baseball game, for example, since it may rain out and some have been known to end in a draw (I remember an All-Star game like that), although the chances for either one should be pretty thin...
Answer: When you assign probabilities to real-world events, you almost always idealize things slightly to obtain some repeatable expirement which you can then assign probabilities too. Sometimes, like if you ask "what's the probability of throwing a three with a fair dice", the idealization is pretty natural - it certainly seems sensible to treat throwing a dice as an repeatable experiment.
If you ask "what's the probability that it will rain tomorrow", the kind of idealization you have in mind isn't immediatly obvious. You could be referring to the date, and effectively be asking "what's the probability of rain on a certain date". Or, you could be asking "what's the probability of rain giving the current state of the earth's atmosphere". Or "what's the probability of rain given that fact that the weather forecast was sunny".
So the question isn't so much whether an event is one-off or not - all real events are, strictly speaking, one-off - but whether there a sensible idealization in which the event is repeatable, and whether that idealization is obvious enough to not require an explanation.
If I was in your place, I'd tell my students that when they say "What's the probability of rain tomorrow" that they have to explain the idealization they're assuming, i.e. instead say maybe "What's the probability of rain tomorrow given that ....".
Answer: Chris Burdzy explored this question in great detail in this book.
He essentially argues that it's fine to assign a probability to a one off event, and if you can't then probability theory is a pretty useless tool. (His argument is obviously more complex than that.)
I'm not sure whether I share his view or not, but it's a bit harsh to judge your students as wrong for agreeing with him.
Answer: Probabilities of one off items are best computed using Dirichlet distributions and other multinomial distributions. The answer for "whether it will rain tomorrow" assuming it is summer is clearly not 0, because there is always a small chance it will. Here is a write up which I think you may find useful.

Probabilities of one-off events


How to upgrade zookeeper from 3.4.5 to 3.4.6 on Ubuntu 14.04.3

Question: I am having trouble with a zookeeper ensamble where one node is not able to join the quorum. Zookeeper will not join the cluster. How to apply patch/upgrade? This seems to be related to a bug which has been fixed in 3.4.6
Now the question is, how to upgrade within Ubuntu 14.04.3? I have already done apt-get update and apt-get upgrade and apt-get dist-upgrade, but the version still is Zookeeper version: 3.4.5--1, built on 06/10/2013 17:26 GMT
This is a production environment and it is important that the service stays live. Right now it is operational with 2 zookeeper nodes.
Answer: The zookeeper service is a java process executing /usr/share/java/zookeeper.jar, which is a symlink to /usr/share/java/zookeeper-3.4.5.jar. I have downloaded the new version of zookeeper, stopped the service, copied the new jar to /usr/share/java/ and pointed the symlink to the new jar, then started the service:
sudo cp zookeeper-3.4.6.jar /usr/share/java/
sudo rm /usr/share/java/zookeeper.jar
sudo ln -s /usr/share/java/zookeeper-3.4.6.jar /usr/share/java/zookeeper.jar

Comment: I have followed your answer. But seeing some problem while upgrading to zookeeper 3.4.13. I have posted the details in https://stackoverflow.com/questions/52090357/how-to-upgrade-zookeeper-from-from-3-8-to-3-13


How to set ssh tunnel properly so you can access site on the server as localhost

Question: I've restricted some part of the sites just to localhost access for security reasons.
In order to access them i would make a ssh tunnel like this
 ssh  -L 8080:localhost:80 firstname.lastname@example.com
and set the local browser at my pc to proxy 127.0.0.1:8080
Well I guess i'm missing something because nothing loads in the local browser
and in the terminal at the server side it says
channel 3: open failed: connect failed: Connection refused
every time i tried to load something at the local pc
firewall was off at the time of trying this
Comment: My feeling is that ought to work; I've just tested it and it does, for me.  That makes me wonder if your server is really set up as you think; can we see the output of `telnet localhost 80` on the server?
Comment: Hang on, did you say you set your local browser to **proxy** `127.0.0.1:8080`?  If so, that'll never work, try unsetting the proxy and pointing the browser at the **page** `http://localhost:8080`.
Comment: Yes but localhost:8080 will load just the server IP and I want to load specific site (one of many) on that server as if I'm on the server.
Comment: Yes but localhost:8080 will load just the server IP and I want to load specific site (one of many) on that server as if I'm on the server.
Comment: Mess with your local `/etc/hosts` file (or OS equivalent) to map the hostnames in question to `127.0.0.1`.
Comment: I guess you've misunderstood my goal since this will just make when i enter the site domain on the local pc to load the server's IP.
Comment: I'm sorry, I can't parse that objection.  I thought you wanted the client to browse to name-virtual-host-based sites hosted on server (but accessible only from server:localhost) via the ssh tunnel?
Comment: Yes, exactly. Then I guess I haven't understood you.
Did you mean me to edit the /etc/hosts on the server side?
Comment: This discussion's got the point where I feel it's too long for comments, so I've summarised in an answer.  I hope that explains things; if it doesn't, **please continue this in comments on the answer**.
Answer: As has been discussed, ssh -L 8080:localhost:80 firstname.lastname@example.com doesn't start a magic proxy server on the client side, it simply forwards client port 8080 to server port 80.  You need to get the client web browser to connect to client port 8080, which as others and myself have said involves pointing your client web browser at http://localhost:8080/.
Your new problem is that the server is running a number of name-based virtual hosts, and you don't get the right host served to you when you don't request it from the server in the URL, which is reasonable enough.
The simplest workround is to tell your client to access the site by name, but to get the OS to lie to the browser about what IP address that host resolves to.  Let us suppose that you want to access hosts vsite1.example.com and vsite2.example.org, which are both being served on port 80 on server, via the SSH tunnel we have already set up.
Edit your client-side /etc/hosts file to tell your OS that those hostnames resolve to 127.0.0.1, with entries such as
127.0.0.1     localhost localhost.localdomain vsite1.example.com vsite2.example.org

I believe there are corresponding hacks for Windows, but I don't know what they are, as I never use it.
Now you can point the client browser at http://vsite1.example.com:8080/, the client OS will tell the browser that's on localhost, the URL will point the browser to localhost port 8080, ssh will conduct the packets sub rosa to server port 80, and client browser will ask server's web server for the right vhost.
Comment: Thank you for the great explanation! It's great and make sense!
I had no idea that the browser will forward correctly the site domain and request it from the server. Thought it would be just the same as typing localhost:8080 in the browser.

However, it now gets to the cloudflare protection page which says the site in question is down, but that is probably something related to cloudflare since the server is not accessing it locally but from itself but seems that it goes through cloudflare.
Anyway, i'll experiment some more. Thank you so much!
Answer: ssh does not create a proxy setup if you do port forwarding.
So either direct the browser directly to http://localhost:8080 or create a hosts entry for "server.com" pointing to localhost.
If you change the browser setting to use a prox on port 8080, then the ssh portforward has to forward a proxy port not a webserver port. Installing squid on server.com will give you a proxy there. Or setup the proxy inside apache. Proxies bring of course a whole lot more security issues so best is to not set one up if you don't absolutely need to.
Comment: Yes but http://localhost:8080 will load just the server IP and I want to load specific site (one of many) on that server as if I'm on the server.
Comment: your sentence does not make sense. I guess you use the wrong terms to describe what you do or what happens. "localhost:8080 loads the server IP" does not make sense. Reformulate differently.


Operations on n-tuples

Question: A novice here, so please go easy on me.
I am struggling with a problem that involves a sequence of numbers. So here is what I am looking for. Let's say x is a 100-tuple (1,2,3...,100) and y is a 50-tuple (2,4,6...,100). I want to define an operator O, such that z = x O y is a 50-tuple with all the elements of x after removing all the elements of y from it.
z = (1,3,5,...,99) or a 50-tuple of odd numbers.
Is such an operation known and studied before? Any direction will be much appreciated.
Answer: This sounds like the set-theoretic difference:  $A \setminus B = \{x \in A \mid x \not \in B\}$.
Edit
OP has clarified that the actual question is not the question asked.  From comments on the other answer (at the time of this writing) "My inquiry comes from trying to solve this problem: One hundred people are sitting in a circle each of who is numbered by their position. First person touches the second and the second walks out, third touches the fourth and fourth walks out and so on. This process is repeated until only one is left. What is the number of that person. The answer is 73. I was trying to solve it for a general case."
Break the operation into "loops": passes around the circle where a person with a lower numbered position dismisses a person with a higher numbered position.  A new loop starts when the person with the highest number has just been dismissed or the person with the highest number has just dismissed the person with the lowest number.
Observe that on each loop, the "gap", the difference between consecutive survivor position numbers, doubles.  It is initially $1$, then on the first pass every alternating person is dismissed leaving gaps of $2$, then on the second pass every alternating person is dismissed leaving gaps of $4$, and so on.
If the total number of survivors at the beginning of a loop is even, the lowest numbered position survives and the highest numbered position is dismissed at the end of the loop.  If the total number of survivors at the beginning of a loop is odd, the highest numbered position survives and the lowest numbered position is dismissed at the end of the loop.
Algorithm:  Let $... b_3 b_2 b_1 b_0$ be the binary representation of the number of people initially in the circle, $N$.  I.e., $N = \sum_k b_k 2^k$.  We construct a table, a sequence of tuples, iteratively according to the following prescription:
(loop, N shifted down by loop bits, gap, first survivor, last survivor)

The first tuple is
(0, N, 1, 1, N)

As long as the second entry is $> 1$, we construct the next tuple as follows:
If the least significant bit of $N$ shifted down by loop is $0$,
    (loop+1, N shifted down by loop+1 bits, 2 gap, first survivor, last survivor - gap)
otherwise
    (loop+1, N shifted down by loop+1 bits, 2 gap, first survivor + 2 gap, last survivor)

For the example of $n = 100 = 1100100_2$, (using "->" to mean "dismisses")
(0, 1100100, 1,  1, 100)
    1 -> 2, 3 -> 4, ..., 99 -> 100
(1, 110010,  2,  1,  99)
    1 -> 3, 5 -> 9, ..., 97 -> 99
(2, 11001,   4,  1,  97)
    1 -> 5, 9 -> 13, ..., 89 -> 93, odd: 97 -> 1
(3, 1100,    8,  9,  97)
    9 -> 17, 25 -> 33, ..., 89 -> 97
(4, 110,    16,  9,  89)
    9 -> 25, 41 -> 57, ..., 73 -> 89
(5, 11,     32,  9,  73)
    9 -> 41, odd: 73 -> 9
(6, 1,      64, 73,  73)

It is, in fact, clearer what's going on if we write the firsts and lasts in binary and keep track of how many of the least significant bits of first and last are being required equal in all the survivors (enforced by the gap, which is always a power of $2$).
(0, 1100100, 1,        1, 1100100)
(1, 110010,  2,        1, 110001 1)
(2, 11001,   4,       01, 11000 01)
(3, 1100,    8,    1 001, 1100 001)
(4, 110,    16,     1001, 101 1001)
(5, 11,     32,    01001, 10 01001)
(6, 1,      64, 1 001001, 1 001001)

Repeating with $N=63$:
(0, 111111,  1,       1, 111111)
    1 -> 2, 3 -> 4, ..., 61 -> 62, odd: 63 -> 1
(1,  11111,  2,     1 1, 11111 1)
    3 -> 5, 7 -> 9, ..., 59 -> 61, odd: 63 -> 3
(2,   1111,  4,    1 11, 1111 11)
    7 -> 11, 15 -> 19, ..., 55 -> 59, odd: 63 -> 7
(3,    111,  8,   1 111, 111 111)
    15 -> 23, 31 -> 39, ..., 47 -> 55, odd: 63 -> 15
(4,     11, 16,  1 1111, 11 1111)
    31 -> 47, odd: 63 -> 31
(5,      1, 32, 1 11111, 1 11111)

But from this it's easy enough to see what the sequence of bits in the firsts is.  It's the sequence of bits in $N$ with the most significant deleted and a trailing $1$ appended.  I.e., $100 = 1100100_2 \rightarrow 1001001_2 = 73$.  This is shown as: Initially, first = 1.  A $0$ bit is prepended to first when the least significant bit of $N$ shifted down by loop bits is $0$.  Alternatively, a $1$ bit is prepended to first when the least significant bit of $N$ shifted down by loop bits is $1$.  Finally, no bit is prepended to first corresponding to the most significant bit of $N$ since the sequence of tuples stops when that is the only surviving bit in the second position of the tuple.  (This is because there is only one survivor in the circle and it is both the first and the last in the final tuple.)
So a table of $N$ and survivors:
N                ->  survivor number
 99 = 1100011_2  ->  1000111_2 = 71
100 = 1100100_2  ->  1001001_2 = 73
101 = 1100101_2  ->  1001011_2 = 75
102 = 1100110_2  ->  1001101_2 = 77
...
127 = 1111111_2  ->  1111111_2 = 127
128 = 10000000_2 ->  00000001_2 = 1
129 = 10000001_2 ->  00000011_2 = 3

If one wants a formula, the shift up by a bit and append $1$ are easy ($2x+1$), but the drop the leading bit is hard.  One way to go is
$$ 2(N - 2^{\lfloor \log_2 N \rfloor})+1 $$
Comment: I was advised by a math student not to call it a set, as sets are by definition not ordered elements. My tuples are formed by the elements of a sequence, so therefore ordered.
Comment: @RaviKulkarni : Are _all_ of your tuples ordered sequences of distinct elements?
Comment: They are always ordered sequences.
Comment: @RaviKulkarni : Do any of your sequences contain a repeated element?
Comment: no repetitions.
Comment: @RaviKulkarni : Then I see no reason not to call them sets.  It is slightly more descriptive to call them "ordered sets", or even "well-ordered sets".  (See https://en.wikipedia.org/wiki/Well-order for more on "well-ordering".)
Comment: excellent. Very clear explanation.
Answer: We have that $x \; \mathrm{O} \; y=z$ for $x=(x_1 , \ldots , x_{100})$ and $y=(y_1 , \ldots , y_{50})$ is such that $z=(z_1 , \ldots , z_{50})$ where $z_i$, $i \in [1,50]$ satisfies the condition that $z_i \neq y_i \, \forall i$.
As Eric Towers mentions, this is analogous to the set difference:
$$A -B = \{x \in A : x \notin B\}$$
However, here we have the property of ordering, as you correctly point out. This matters rather little, though, for we must simply ensure that $x_{n_1}=z_{n_2}$ and $x_{m_1}=z_{m_2}$ is such that $n_2 < m_2$ if and only if $n_1 < m_1$.
So, this operation is well defined. Give me two $n$-tuples, $x$ and $y$ where the number of elements of $x$ is greater than or equal to that of $y$, and I can uniquely determine $x\; \mathrm{O} \;y$.
Whether or not this is particularly interesting is up to you. In my opinion, it is no more interesting than the set-theoretical difference; however, it does help to emphasize that an $n$-tuple is distinct from a set, which is, in general, not even ordered.
I am certain this operation is known, but it is not very noteworthy.
As far as I know, it has not really been studied extensively. I am also not aware of any name for this operation. Might I suggest "$n$-tuple subtraction", or "tuple subtraction" for short?
That may be somewhat confusing, though, as it seems to imply that there are two $n$-tuples involved where you subtract the $j$th element of the first tuple from the $j$th element of the second.
(I'm pretty tired. So, I apologize if I have made a mistake. Please, let me know if that is the case.)
Comment: Thank you Joseph. My inquiry comes from trying to solve this problem:

One hundred people are sitting in a circle each of who is numbered by their position. First person touches the second and the second walks out, third touches the fourth and fourth walks out and so on. This process is repeated until only one is left. What is the number of that person. The answer is 73. I was trying to solve it for a general case.
Comment: @RaviKulkarni : You might have gotten more useful comments if you'd asked about the actual question than the question you asked.  The "right" way to attack your actual question is to write the location of the people in binary and then note that at each step, the survivors all have the same last few bits in their locations.  They're all "...1" after the first loop around, "...01" after the second, but since there are now an odd number of survivors, the highest numbered survivor dismisses $1$ and we continue starting with the survivors' locations ending in "...101", et c.
Comment: @EricTowers, you are probably right. I have already done the analysis you suggested but couldn't come up with a general answer to the problem. I believe I could make headway if I could extend the n-tuple subtraction concept.
Comment: @RaviKulkarni : I've edited my answer to address your dismissal problem.

Operations on n-tuples


TypeORM evokes error in findOne query - QueryFailedError: ER_NO_DEFAULT_FOR_FIELD: Field 'type' doesn't have a default value

Question: I am using MySQL database backed by TypeORM and Nodejs. I have an entity that records holidays. now the insertion works pretty well, but the problem is findOne query does not work.
Here is the entity:
import {
  Column,
  CreateDateColumn,
  Entity,
  PrimaryGeneratedColumn,
  UpdateDateColumn,
  VersionColumn,
} from "typeorm";

@Entity()
export class Holiday {
  @PrimaryGeneratedColumn("uuid")
  id: string;

  @Column()
  type: string;

  @Column({ nullable: true, default: null })
  weekDay?: string;

  @Column({ nullable: true, default: null })
  date?: Date;

  @Column({ default: null })
  remark?: string;

  @CreateDateColumn()
  createdAt: Date;

  @UpdateDateColumn()
  updatedAt: Date;

  @VersionColumn()
  version: number;
}

This is the query I'm executing to findOne record:
const holiday = await getConnection()
        .manager.getRepository(Holiday)
        .findOne(id); //id of the record that needs to find.

The Error I encounter:
QueryFailedError: ER_NO_DEFAULT_FOR_FIELD: Field 'type' doesn't have a default value
code: 'ER_NO_DEFAULT_FOR_FIELD',
errno: 1364,
sqlMessage: "Field 'type' doesn't have a default value",
sqlState: 'HY000',
index: 0,
sql: "INSERT INTO `holiday`(`id`, `type`, `weekDay`, `date`, `remark`, `createdAt`, `updatedAt`, `version`) VALUES ('b8b93d11-2346-4388-bf87-738b61c41118', DEFAULT, DEFAULT, '2021-08-10 06:53:58.213', DEFAULT, DEFAULT, DEFAULT, 1)"

Answer: I think you have issue at following
@Column({ nullable: true, default: null })
date?: Date;

You can not put Date type to null
Try this:
@Column()
date?: Date;

Answer: The error in your case is in the "type" field, which is missing the { nullable: true } option in the entity.
Also, make sure you have run the migration after changes in the entity.


Monit command in shell script

Question: I am issuing monit commands from command line and this works
<code>$ sudo monit reload
</code>
Now I create a shell script monitreload.sh
<code>#!/bin/bash
monit reload
</code>
And then the commands
<code>$ sudo ./monitreload.sh
$ sudo -u ram ./monitreload.sh
</code>
The above ones fail with permission denied error.
Pls note /etc/monit/monitrc file is owned by root and the user 'ram' is a valid sudo user. Most of the questions in SO talk about gid and uid usage in monit config like this one or invoking a shell through monit config like this one
What is going wrong here?
Comment: First of all, I cannot reproduce this on my debian machine. But: Did you try to just put the `sudo` inside your script?
Comment: @boppy No. Sudo was used only while executing the script.
Answer: Based on your sample commands
<code>$ sudo ./monitreload.sh
$ sudo -u ram ./monitreload.sh
</code>
The first one should work, you switch to root.
But the second should not, you switch to user "ram", and the user "ram" can not reload the configuration as long as Monit was stared by "root".
<code>$ sudo -u ram sudo ./monitreload.sh
</code>
If "ram" is authorized to switch to "root", you can add an additional "sudo" in the command to switch from "ram" to "root". Monit will not swich to the "root" user automatically.

Monit command in shell script


NLP, NER --> python extraction of personal informations (like names, surnames, fiscal codes)

Question: i am working on a project to extract personal information from custom documents. In particular, i have a txt file with a lot of names, surnames and information but i would like to extract names and italian fiscal codes.
My actual approach is based on regex but i am not very satisfied because the regex pattern does match always all I need. I was thinking about an NLP approach but i do not know how. I think that actually there are no libraries trained on italian vocabulary. Please, could you kindly help me or give me a few advices?
Thank you very much in advance!!
I have tried an approach based on regex which works well on standard documents, on strongly custom documents it often fails.
Answer: I would try prompting ChatGPT directly in Italian to extract this information for you. They have an API you can access with simple python code, and you can tell it what exactly you want it to extract and in what output format (json for example).
In addition there are traditional NER models you could use, mainly for names, such as spacy which also supports Italian (see: https://spacy.io/usage/models) or Google's which costs money.
I believe that reguarding the fiscal information you will get the best results by using a REGEX.


Definitions and theorems depending on being a regular surface

Question: Consider $S \subset \mathbb{R}^3$ a regular surface. Now, since $S$ is a regular surface, a lot of theorems, propositions and definitions arise, such as
Definition. $\quad$ The quadratic form $I_p$ on $T_p(S)$, defined by $I_p(S) = |w|^2$, is called the first fundamental form of the regular surface $S \subset \mathbb{R}^3$ at $p \in S$
However, why do we need the surface to be regular? In these kind of definitions, what would go wrong if the surface is not regular?
Comment: Your post is confusing. You have inserted the word "curve" twice into this post in what looks to be an inappropriate manner.
Comment: I'll edit it! thanks
Answer: If our patch $\bf{x}$ is regular, then we'll have that ${\bf{x}}_u\times{\bf{x}}_v$ is everywhere non-zero. Indeed,
$${\bf{x}}_u\times{\bf{x}}_v=\begin{vmatrix}U_1 & U_2 & U_3\\ \partial_u x_1 & \partial_u x_2 & \partial_u x_3\\ \partial_v x_1 & \partial_v x_2 & \partial_v x_3 \end{vmatrix},$$ where $\{U_j\}$ represents the standard frame. Notice that the last two rows are the transpose of the Jacobian of $\bf{x}$ at each point. Regularity requires that this be one-to-one, so we know the above quantity is non-zero.
This is important for a few reasons. For one, it tells us that at each point $(u,v)$, the partial velocity curves are linearly independent, giving us a basis for the tangent space. From here, we can define the quantities $E={\bf{x}}_u\cdot {\bf{x}}_u,$ $F={\bf{x}}_u\cdot {\bf{x}}_v,$ and $G={\bf{x}}_v\cdot {\bf{x}}_v,$ which are the components of the first fundamental form. You'll find that $EG-F^2=\left\lVert {\bf{x}}_u\times {\bf{x}}_v\right\rVert^2,$ and requiring that this be non-zero is the same as requiring the matrix associated to the first fundamental form is invertible. We also use this to define the volume form $dS=\sqrt{EG-F^2}dudv$.
Comment: Thanks (once again), however, from what property of the surface being regular can we say that $\mathbf{x}_u \times \mathbf{x}_v$ is everywhere nonzero?
Comment: No problem, and yes, I'll add a clarifying remark.
Comment: Thanks! this clarifies things. I'll accept your answer :)
Comment: Sorry, I misread. It comes from the injectivity of $d{\bf{x}}_p$. I've clarified above.
Comment: I'm glad it helped!


Can you render a custom block in a view without adding it to the admin blocks page?

Question: I made a custom block in my custom module.  I now want to show that block in the "No results" area of a view, but I can't get it to render (I don't see any error message, and I don't see any output).
Here is the block definition:
<code>/**
 * Provides an 'New User' Block.
 *
 * @Block(
 *   id = "newuser_block",
 *   admin_label = @Translation("New user block"),
 *   category = @Translation("MYMODULE"),
 * )
 *
</code>
In my view, in the "No results" section, I added Rendered entity - Block, and set the Block ID to newuser_block.
However, the block does not get rendered.
This is because I did not add the block on the block admin page at <code>/admin/structure/block</code>. When I add the block on the admin page and use the admin page block ID (not the block machine name), the block is rendered correctly.
However, I don't want to add the block to the admin page because I only need this block in a few places on my site, so I was using Layout Builder to inject the block where necessary.
So, is there a way to inject a block by machine name (instead of by the ID used on the block admin page) in Views?
Comment: Add a new region, name it disabled or something like that and never print it anywhere. Add this block to that region. Done.
Answer: The only purpose of a block plugin is to be placed as a block. It's not an entity. The placed block instance can become an entity of its own but also be part of a layout section.
Since the block is your own custom code you don't need any of the workarounds discussed and linked. It would make more sense to refactor the code and expose it as block plugin to be placed on the page and at the same time as area plugin to be placed in a View.
For sharing the custom code between both plugins you can use classic OOP, or the in Drupal very common traits and services. The service has the advantage that it is more flexible and you can not only share code but also data, for example to cache the result if it is expensive to calculate and used in multiple places.
Answer: There is an core issue about this, Problems using 'Rendered entity - Block' in header/footer

the block ID only exists as long a the the block is configured to be
visible in a region

Until fixed, yes, it is possible without having to  add it to a region as long as you solve it via template file. In this case using views-view--[view-name]--[view-display-name].html.twig and using Twig Tweak you can print it with
<code>{{ drupal_form('namespace\\ClassName') }} # except you add an extra `\`
</code>
Ex:
<code>{{ drupal_form('Drupal\\search\\Form\\SearchBlockForm') }}
</code>


What is efficient way to ensure bash script variable is valid permission bits?

Question: I'm inexperienced with bash scripts, mostly cobbling things together from google searches. The following simple script creates file foo and changes its permission bits to whatever the script's $1 is. Can an experienced bash scripter please advise  what would be a proper and/or efficient way to ensure that $1 is valid permission bits, i.e. a valid arg1 to chmod?
#!/bin/sh
#mkfoo.sh

if [ $# -eq 0 ]
then
  return
fi

perm=$1

touch ./foo
chmod "${perm}" ./foo

As part of my inexperience, I'm unclear when/why variables are strings or integers. A string-validation approach feels infeasible because of the number of values the permission bits could be. What comes to mind is that I'd want to validate whether $1 is an integer, and if so, that it's between 0 and 777. But I'm unclear if that's a sufficient/efficient validation: I've got a rudimentary understanding of linux file permissions, and I'm led to believe there are lots of subtleties. Grateful for help.
Comment: This is not easy, because `chmod` allows complicated symbolic permission specifications, like `u+r,o-w`. Why don't you just check whether `chmod` is successful?
Comment: If you only want to allow numeric permissions, you could just check if it matches the pattern `[0-7][0-7][0-7]`
Comment: @StoneThrow, at a guess (wasn't me): this question is fairly simple, and validating an integer in bash (since you appear not to care about other permissions options of `chmod`) has been asked many times and should be findable via google
Comment: why do you need to validate? What do you plan to do in case of an error?
Comment: Permission bits are `4 2 1` for read, write, and execute; ordered as _user_, _group_, and _other_, so 198 is between 0 and 777 but is not valid, so that's not sufficient validation. I was about to also mention the symbolic representation, but Barmar already did.
Comment: @jeremysprofile I'd want to dot do anything; also my concern is about passing bad arguments to `chmod`: will it output error messages (undesirable) or have some other negative impact to file foo?
Comment: @Barmar - do you mean validate the argument using a regex (I'm not sure how to implement the validation you suggested)?
Comment: If this is "create and set permission" you'd better check if the file (or directory) already exists. `touch` will update the date on an already existing file, then `chmod` will set the permissions. You _could_ create the file only if it doesn't already exist, chmod it, and if the chmod fails then delete it -- but that's very dangerous if the file already exists.
Comment: Maybe I shouldn't care about my reputation ding, but why was this question downvoted? I wish there was a way to know why.
Comment: It didn't cross my mind that `chmod` took non-numeric input; glad I came here to ask. For that reason, I think I'll pick @jeremysprofile 's answer, since I didn't intentionally only want to allow numeric input - it's just the alternatives hadn't crossed my mind. Thanks to all (except the downvoter).
Answer: If you only want to allow numeric permissions, you can check them with a pattern check:
case "$perms" in
    [0-7][0-7][0-7])
        touch ./foo
        chmod "${perm}" ./foo
        ;;
    *)
        echo "Invalid permissions $perms"
        ;;
esac

Comment: Valid permissions are actually 4 digits long, counting the set-uid, set-guid, and sticky bits
Comment: Yeah, I assumed that he's only interested in the basic perms.
Answer: From your comments, your goal is to give up on the chmod if the permissions specified are invalid.
chmod "$1" ./foo 2>/dev/null

2 is the file descriptor for stderr. Redirecting to /dev/null will let it fail silently. chmod, as stated in the comments, does its own validation on if the permissions are acceptable.
Comment: @StephenP, yes. I assumed that was the goal. appending `|| rm ./foo` easily solves that problem, however.
Comment: It's an acceptable outcome in my case for a file to be created with the default permission if `$1` is bad input.
Comment: Of course, this will still leave the file that was created, just without the permissions you asked for.
Answer: This script will accept any valid permissions that chmod allows.
It will create the file (if it doesn't already exist) and attempt to set the permissions. If setting the permissions fails the file is removed.
It requires exactly two arguments; the filename to create and the permissions to set.
This allows you to use symbolic or 4-digit permissions, such as create foo u+x,g+rwx (assuming the script is named "create") or create foo 2640
This is pretty simple, as an example. I often include a usage() function which I would call in place of the first echo. You could also include default permissions if the seconds argument was omitted.
#!/bin/sh

if [ $# -ne 2 ]
then
    echo "output a usage message, don't just return"
    exit
fi

if [ -e "${1}" ]
then
    echo "${1} already exists"
    exit
fi

touch ./"${1}"

if chmod "${2}" "${1}" > /dev/null 2>&1
then
    echo "${1} created with permissions ${2}"
else
    rm "${1}"
    echo "${1} not created: invalid permissions: ${2}"
fi

Answer: As others have mentioned, chmod does its own validation so it'd probably be best to just use that, but if you absolutely want to do this in a way similar to the code you provided you can do:
#!/bin/sh
if [ $# -eq 0 ]
then
    echo "Invalid input"
    exit 1
fi

if ! [[ $1 =~ [0-7][0-7][0-7] ]]
then
    echo "Invalid input"
    exit 1
else
    perm=$1
fi

touch ./foo
chmod "${perm}" ./foo

This will ensure that each digit is valid.
Comment: That's a valid point you bring up, that chmod will do its own validation. I was just concerned about error messages it might throw out - but this is addressed by @jeremysprofile 's suggestion to redirect `stderr`'s output to `/dev/null`


Cannot get MariaDB to start

Question: I've been away and one of my databases became a massive size that MariaDB had crashed and I cannot get it to restart. I have tried moving the path /var/lib/ and restart to no avail. I am trying to find messages in /var/log/mysql/ and /var/log but there are no error messages to give me a clue.
Can anyone offer some solutions?
MariaDB: 10.0.12
Debian 7.6.
Thanks.
Comment: Nevermind. Rebooting Debian resolved the issue.
Comment: MariaDB error log is in the data directory. Just read its final lines to find out the problem.
Answer: Check for error messages in the syslog. Mariadb 10.0.* send tehm there if you do not change the /etc/mariadb.conf.d/50-mysqld_safe.cnf and comment the 2 lines: skip_error_log and syslog

Cannot get MariaDB to start


How to delete asp.net profile property values?

Question: I cerated a asp.net user profile with 1 property List<string> Password it contain 24 passwords , now i want to delete 4 passwords from this property values, how can i do this?
Comment: You can use `Password.RemoveRange(index,count);`
Comment: What have you tried so far? Which 4 passwords do you need to delete? Top 4, bottom 4, middle 4 or what is the logic?
Comment: Any 4 from the list, i just want to know how we delete data from the profile properties?
Answer: To remove a range
Password.RemoveRange(index,count);

To remove a known index
Password.RemoveAt(index);

index is always zero based. All list of methods


Load WPF application from the memory

Question: So this is how you invoke Main() in non WPF applications:
var entry = assembly.EntryPoint;

if (assembly.EntryPoint.GetParameters().Length == 0)
    entry.Invoke(null, new object[0]);
else
    entry.Invoke(null, new object[] { args });

but somehow it doesn't work at all for WPF applications, I've tried (MSDN's way):
Assembly asm = Assembly.LoadFrom(file);

Type myType = asm.GetType("WpfApplication1.App");

// Get the method to call.
MethodInfo myMethod = myType.GetMethod("Main");

// Create an instance.
object obj = Activator.CreateInstance(myType);

// Execute the method.
myMethod.Invoke(obj, null);

still no success, Reflector shows Main() as
[DebuggerNonUserCode, STAThread]
public static void Main()
{
    App app = new App();
    app.InitializeComponent();
    app.Run();
}

no matter what I do, I get "System.Reflection.TargetInvocationException" exception.
Any help?
PS. More debugging revealed it can't load "mainwindow.xaml" resource originally located in the assembly that I want to load
{System.IO.IOException: Nie można zlokalizować zasobu "mainwindow.xaml".
   w MS.Internal.AppModel.ResourcePart.GetStreamCore(FileMode mode, FileAccess access)
   w System.IO.Packaging.PackagePart.GetStream(FileMode mode, FileAccess access)
   w System.IO.Packaging.PackagePart.GetStream()
   w System.Windows.Application.LoadComponent(Uri resourceLocator, Boolean bSkipJournaledProperties)
   w System.Windows.Application.DoStartup()
   w System.Windows.Application.<.ctor>b__0(Object unused)
   w System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)
   w System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
   w System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
   w System.Windows.Threading.DispatcherOperation.InvokeImpl()
   w System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
   w System.Threading.ExecutionContext.runTryCode(Object userData)
   w System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
   w System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
   w System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   w System.Windows.Threading.DispatcherOperation.Invoke()
   w System.Windows.Threading.Dispatcher.ProcessQueue()
   w System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   w MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   w MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
   w System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)
   w System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
   w System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
   w System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter)
   w System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg)
   w MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   w MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
   w System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
   w System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
   w System.Windows.Threading.Dispatcher.Run()
   w System.Windows.Application.RunDispatcher(Object ignore)
   w System.Windows.Application.RunInternal(Window window)
   w System.Windows.Application.Run(Window window)
   w System.Windows.Application.Run()
   w WpfApplication1.App.Main()}

so I suspect, the problem is that CLR tries to find .xml within loader application and not within THE ACTUAL wpf application.
Comment: WCF applications must be started via the Service Manager.  You cannot start them on your own.
Comment: I don't think the OP wants to start WCF apps - he's trying to start WPF apps.
Comment: Yes, WPF applications, I've browsed a ton of websites, MSDN and can't get to any working solution, in my desperation I've tried this WCF way of loading (via ServiceHost) but still it doesn't work.
Comment: What type of application are you trying to load it from?  In trying to reproduce it, I keep getting this inner exception "Cannot create more than one System.Windows.Application instance in the same AppDomain."
Answer: I've found a way to do that. You basically have two options.

Load the exe in the separate AppDomain.
Use reflection trickery to change default ResourceAssembly.

Option first, while cleaner, has disadvantage of being slower (WPF needs to load into the new AppDomain too):
//Assembly: WpfLoader.dll
[STAThread]
class Program
{
    public class Loader : MarshalByRefObject
    {
        public void Load()
        {
            var dll = File.ReadAllBytes("WpfTest.exe");
            var assembly = Assembly.Load(dll);
            Application.ResourceAssembly = assembly;
            assembly.EntryPoint.Invoke(null, new object[0]);
        }

    }

    static void Main(string[] args)
    {
        var domain = AppDomain.CreateDomain("test");
        domain.Load("WpfLoader");

        var loader = (Loader)domain.CreateInstanceAndUnwrap("WpfLoader", "WpfLoader.Program+Loader");
        loader.Load();
    }
}

The second solution uses reflection to change ResourceAssembly of current application. You cannot do that with public API's, as the Application.ResourceAssembly is read only once it's set. You have to use reflection to access private members of both Application and ResourceUriHelper classes.
var dll = File.ReadAllBytes("WpfTest.exe");
var assembly = Assembly.Load(dll);

var app = typeof(Application);

var field = app.GetField("_resourceAssembly", BindingFlags.NonPublic | BindingFlags.Static);
field.SetValue(null, assembly);

//fix urihelper
var helper = typeof(BaseUriHelper);
var property = helper.GetProperty("ResourceAssembly", BindingFlags.NonPublic | BindingFlags.Static);
property.SetValue(null, assembly, null);

//load
assembly.EntryPoint.Invoke(null, new object[0]);

There is still a caveat with both solutions: You cannot use more than one Wpf application which uses relative resources in one AppDomain, so should you wish to load more than one app, you need to create multiple AppDomains.
For those examples to work, you need to do two things:

It needs to be called from single appartment state threads, so remember to use [STAThread]
You need to add PresentationCore.dll, PresentationFramework.dll and WindowsBase.dll    references
Comment: Good stuff. Btw AppDomain.ExecuteAssembly() sets ResourceAssembly to the loaded assembly for you. https://learn.microsoft.com/en-us/dotnet/api/system.windows.application.resourceassembly?view=netcore-3.1
Answer: The option 2 from @ghord is very good, but it needs a way to load the *.dll referenced in the WPF.
So you also have to modify the App.xaml.cs of the WPF in the following way
public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
        base.OnStartup(e);
    }
    private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
    {
        string dir = @"C:\your\path\to\WPF\bin\Debug\";
        string fileExtension = "*.dll";
        string needed = args.Name.Split(',')[0];
        if (needed.EndsWith(".resources"))
        {
            return null;
        }
        foreach (String file in Directory.GetFiles(dir, fileExtension, SearchOption.TopDirectoryOnly))
        {
            string name = System.IO.Path.GetFileNameWithoutExtension(file);
            if (args.Name.StartsWith(name))
            {
                byte[] bytes = File.ReadAllBytes(file);
                Assembly assembly = Assembly.Load(bytes);
                return assembly;
            }
        }
        Debug.WriteLine(args.Name);

        return null;
    }
}

The string dir can be set as the path to the Release folder of your WPF app.
Notice that it is important to skip the .resources but for the rest we can assume that all the needed *.dll files are found in the dir folder.
Btw, all this goes very well with an encrypted signature for your assemblies: read for example my article to see how to encrypt a signature for your exe and dll files.
quick win tip
Let's say that your launcher is named launcher.exe and the original WPF is mywfp.exe and you have defined a WPF window TestView under a project folder view. Now you can face an exception like the following:
System.Exception:
"The component 'mywfp.TestView' does not have a resource identified by the URI '/mywfp;component/view/testview.xaml'."

The quick trick here is to:

rename mywfp.exe as mywfp_original.exe (or as you like)
rename the launcher launcher.exe as the original wpf, i.e. mywfp.exe !

In case you want to add a splash screen, include the image with a Resource Build Action in the loader exe: show it ASAP in the STA thread of the loader and close it before invoking the entry point of the in-memory loaded app.
    SplashScreen splashScreen = new SplashScreen("splashscreen.jpg");
    splashScreen.Show(false);

...
    splashScreen.Close(TimeSpan.FromSeconds(1));
    assembly.EntryPoint.Invoke(null, new object[0]);

Load WPF application from the memory


Overloading assignment operator: if we return (*this), which is a value at a pointer/address, what's right syntax for assignment operator?

Question: Using these two previous threads as examples
First thread:
Why does overloaded assignment operator return reference to class?
Second thread:
Why must the copy assignment operator return a reference/const reference?
Is the return type of an overloaded assignment operator a class or a reference to a class?  I have seen both:
Point& Point::operator = (const Point& sourcePoint)
{
// As in the first thread I pasted above
return *this;
}

And
Point Point::operator = (const Point& sourcePoint)
{
// As in the second thread I pasted above
return *this;
}

Which is right?
Similarly, what's the difference between:
int exFunction()
{
     int i = 5;
     int* iPtr = &i;
     return *iPtr;
}

Versus:
int& exFunction2()
{
     int j = 5;
     int* jPtr = &j;
     return *jPtr;
}

Thanks!
Answer: The two thigns are not "similar" at all.
First off, the assignment operators. They should return a reference to the object itself, so that you can use them in a chain:
Foo x, y, z;

x = y = z;   // makes y equal to z and returns a reference to self,
             // which is assigned to x

So it's always:
Foo & operator=(Foo const &) { /* ... */  return this; }  // copy-assignment

Foo & operator=(/* any other signature */) { /* ... */   return this; }

Now, the second question: Your exFunction2 is completely wrong and broken. It has undefined behaviour, because it returns a reference to a local variable, which is out of scope by the time the function returns. (It says essentially return j;; remember that the result of a dereference is an lvalue.) The only sensible way to write that function is like exFunction, which can be shortened to int exFunction() { return 5; }.
Here is a related question on this topic.


Laravel: Sum of foreach

Question: I have this foreach loop:
my $items looks like this:
array:2 [▼
  0 => array:3 [▼
    "variant_id" => "393c6c70-8cb7-11e8-815a-f9c70a1fbe8e"
    "name" => "Medicine 1"
    "quantity" => "1"
  ]
  1 => array:3 [▼
    "variant_id" => "8a80d340-e0c1-11e8-86a4-3b06d2b50e37"
    "name" => "Medicine 2"
    "quantity" => "1"
  ]
]

Now, in my foreach, I compare the variant_id to my database and get the points from that database and multiply it by the quantity of the Medicines.
points for Medicine 1 is = 50
points for Medicine 2 is = 20
so it should be 50(medicine 1 points) multiplied by 1 (quantity of medicine 1) and
20 x 1 (medicine 2) and then the sum of both which should be equal to 70. But when I dd($sum) what I get is 50 which is only for medicine 1.
    $sum = 0;
    foreach ($items as $variants) {
        $id = $variants['variant_id'];
        $quantity = $variants['quantity'];
        $find = Activity::where('variant_id', $id)->first();
        $act_points = $find->points * $quantity;
        $sum += $act_points;
        dd($sum);
    }

What am I missing here?
Comment: `dd($sum);` __after__ `foreach`.
Comment: You have to print the data after completion of your loop. So it will gives you the correct result.
Answer: You can see dd() as a Dump and Die. This will dump the asked data and kills the script. Because this is executed, the script gets terminated before it can finish the loop
You need to use the dd() after the foreach-loop
$sum = 0;
foreach ($items as $variants) {
    $id = $variants['variant_id'];
    $quantity = $variants['quantity'];
    $find = Activity::where('variant_id', $id)->first();
    $act_points = $find->points * $quantity;
    $sum += $act_points;
}
dd($sum);

If you do not want to halt the execution of your script, use the dump function instead.

https://laravel.com/docs/5.7/helpers#method-dd
Answer: I figure out you are doing Debug dump (dd) inside foreach loop so it will just stop after the first iteration.
You should do dd outside of foreach loop.
Answer: To rationalize and avoid multiple DB calls yu can do the next
$input = [
    [
        "variant_id" => "393c6c70-8cb7-11e8-815a-f9c70a1fbe8e",
        "name" => "Medicine 1",
        "quantity" => "1",
    ],
    [
        "variant_id" => "8a80d340-e0c1-11e8-86a4-3b06d2b50e37",
        "name" => "Medicine 2",
        "quantity" => "1",
    ],
];

$sum = Activity::whereIn('variant_id', array_column($input, 'variant_id'))->get()->sum(function ($s) use ($input) {
    foreach ($input as $k => $v) {
        if ($s->variant_id == $v['variant_id']) {
            return $s->points * $v['quantity'];
        }
    }
});

This will work if in $input array there is no repeating elements by variant_id.
In other words if each $input[n]['variant_id'] value is unique.

Laravel: Sum of foreach


Cluster or classify tree species data into distinct categories

Question: I'm an experienced data analyst who is unfortunately ignorant about statistical techniques and clustering. I'm looking for help in identifying the best technique to solve the problem below.
A cross tabulation sample of my data is pasted below: in short I have 6,500 survey plots with tree species records (% polygon cover) for each plot. There are 14 species in total.
How do I go about classifying these polgyons into distinct groups? Clearly the 14 species are not randomly distributed, so there will be common patterns and associations across the dataset. But how do I go about identifying these commonalities over 14 variables? What kind of test or procedure do I need to read up on?
Once I have identified initial groupings, I can then share these with a tree expert who can hopefully translate them into rules such as "if polygon > 80 species X -> Category 1 etc"
I use Alteryx for my data manipulation, and it has various tools such as K centroids, see https://help.alteryx.com/10.6/index.htm#Getting_Started/AllTools.htm#Predictive_Grouping
I would be grateful if you could suggest what type of analysis I need to pursue. I'm guessing it must be pretty common, and I'm sorry for being ignorant. Hopefully someone can point me the right direction. Thanks
Comment: This looks like a spatial problem, there must be spatial correlation in the data.
Comment: You're correct, but in the first instance I want to ignore the spatial element to focus purely on the categorisation. I want to present my ecological domain expert with the most common 'clusters' of species observed in the data. Then he can fine tune the decision tree based on those initial clusters
Answer: It looks like you're interested in some kind of hierarchical clustering here. Take a look at the hclust function, it will do the work of producing a classification tree.
However, your data seem to have many zeros, so you'll need to use a proper data transformation to deal with that, take a look at the vegan::decostand function and the hellinger transformation.
Sometimes, it's not so easy to find the best limit to define the groupings, using Bootstrap can help, take a look at the pvclust package.


Switch theme per user upon login

Question: I'd like to switch theme per user upon user login success in my drupal 6 site. I need to check username of a particular user to change a particular theme for that user.
Is there any module around to accomplish this?
Or, do I have to write a hook like
<code>function mymodule_init(){
    global $custom_theme;
    global $user;
    // check username here.
    $custom_theme = 'garland';
}
</code>
But, I'm finding a module which have admin interface so that I can define usernames as much as I can.
Answer: Try the Themekey module which allows content, user, or role -specific themes.
Comment: The optional module ThemeKey User Profile that comes with theme key allows per user based theme.
Answer: Why not use the Role Theme Switcher module?
Considering you have a limited number of themes and you can combine roles for a user, why not creating one specific role per theme that you will assign to your users.
Comment: Can I change theme per user of the same role?
Comment: Role theme switcher allows theme by role.. So obviously you cannot change theme per user of same role...

Switch theme per user upon login