text:
Q: List Box User Form for multiple inputs into single cell Can someone please help me with an issue? The new requirement was for a combobox to be replaced by a listbox that will allow multiple selections and entered into a single cell. The one I am speaking about is the Me.Reason_RRT_Called Any help would be greatly appriciated. The code is below.
            Option Explicit
Dim WrkSheet As Worksheet

Private Sub CommandButton1_Click()
    Application.EnableEvents = False

    Dim ssheet As Workbook
    Dim cellVal1 As String, cellVal2 As String, cellVal3 As String, cellVal4 As String
    Dim cellVal5 As String, cellVal6 As String, cellVal7 As String, cellVal8 As String
    Dim cellVal9 As String, cellVal10 As String, cellVal11 As String, cellVal12 As String
    Dim cellVal13 As String, cellVal14 As String

    Dim shtCmb As String
    Dim RwLast As Long
    Dim Reasons As String
    Dim n As Integer

    shtCmb = Me.Year.Value
        If shtCmb = "" Then
             MsgBox "Please choose a Year.", vbOKOnly
             Me.Year.SetFocus
    End If
         For n = 0 To Reason_RRT_Called.ListCount - 1
             If Reason_RRT_Called.Selected(n) = True Then
                Reasons = Reasons & Reason_RRT_Called.List(n) & "; "
             End If
         Next n

    cellVal1 = Me.Year.Text
    cellVal2 = Reasons
    cellVal3 = Me.Type_Of_Recomendations.Text
    cellVal4 = Me.Documentation_On_Templates.Text
    cellVal5 = Me.MD_Notified.Text
    cellVal6 = Me.Location.Text
    cellVal7 = Me.Code_Rapid_Response.Text
    cellVal8 = Me.Report_Sent_To_QM.Text
    cellVal9 = Me.Vital_Signs_Documneted.Text
    cellVal10 = Me.Assessments_Completed.Text
    cellVal11 = Me.Response_Time.Text
    cellVal12 = Me.Date_Of_Incedent.Text
    cellVal13 = Me.Patients_Name.Text
    cellVal14 = Me.Unit_Location.Text

    RwLast = Worksheets(shtCmb).Range("B" & Worksheets(shtCmb).Rows.Count).End(xlUp).Row

    Worksheets(shtCmb).Range("B" & RwLast + 1).Value = cellVal1
    Worksheets(shtCmb).Range("H" & RwLast + 1).Value = cellVal2
    Worksheets(shtCmb).Range("K" & RwLast + 1).Value = cellVal3
    Worksheets(shtCmb).Range("L" & RwLast + 1).Value = cellVal4
    Worksheets(shtCmb).Range("N" & RwLast + 1).Value = cellVal5
    Worksheets(shtCmb).Range("E" & RwLast + 1).Value = cellVal6
    Worksheets(shtCmb).Range("D" & RwLast + 1).Value = cellVal7
    Worksheets(shtCmb).Range("G" & RwLast + 1).Value = cellVal8
    Worksheets(shtCmb).Range("I" & RwLast + 1).Value = cellVal9
    Worksheets(shtCmb).Range("J" & RwLast + 1).Value = cellVal10
    Worksheets(shtCmb).Range("M" & RwLast + 1).Value = cellVal11
    Worksheets(shtCmb).Range("A" & RwLast + 1).Value = cellVal12
    Worksheets(shtCmb).Range("C" & RwLast + 1).Value = cellVal13
    Worksheets(shtCmb).Range("F" & RwLast + 1).Value = cellVal14

    Application.EnableEvents = True

End Sub
Private Sub optionCancel_Click()
    Unload Me
End Sub

Private Sub UserForm_Initialize()

    Dim SH As Worksheet
    Dim Entry As Variant

    'Auto date fill text box
    'Date_Of_Incedent.Value = Format(Date, "mm/dd/yyyy")

      'Year(Year(Now)) - Will return the name of the current Year
    For Each SH In ThisWorkbook.Worksheets
        If SH.Name = Year Then
            Set WrkSheet = SH
            Exit For
        End If
    Next

    'fill the combo box
    With Me.Year
        For Each Entry In [List1]
            .AddItem Entry
        Next Entry
        .Value = Year
    End With

    'fill the listBox
    With Me.Reason_RRT_Called
        For Each Entry In [List2]
          .AddItem Entry
        Next Entry
    End With

       'fill the combo box
    With Me.Type_Of_Recomendations
        For Each Entry In [List3]
            .AddItem Entry
        Next Entry
    End With

           'fill the combo box
    With Me.Documentation_On_Templates
        For Each Entry In [List4]
            .AddItem Entry
        Next Entry
    End With

              'fill the combo box
    With Me.MD_Notified
        For Each Entry In [List5]
            .AddItem Entry
        Next Entry
    End With

        'fill the combo box
    With Me.Location
        For Each Entry In [List6]
            .AddItem Entry
        Next Entry
    End With

    'fill the combo box
    With Me.Code_Rapid_Response
        For Each Entry In [List7]
            .AddItem Entry
        Next Entry
    End With

    'fill the combo box
    With Me.Report_Sent_To_QM
        For Each Entry In [List8]
            .AddItem Entry
        Next Entry
    End With

    'fill the combo box
    With Me.Vital_Signs_Documneted
        For Each Entry In [List9]
            .AddItem Entry
        Next Entry
    End With

 'fill the combo box
    With Me.Assessments_Completed
        For Each Entry In [List10]
            .AddItem Entry
        Next Entry
    End With

  'fill the combo box
    With Me.Response_Time
        For Each Entry In [List11]
            .AddItem Entry
        Next Entry
    End With

End Sub

A: To create a drop down list for a cell I use data validation. In order to create a drop down list using VBA, Use the following lines of code:
With range("A1").Validation
    .Delete
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
    xlBetween, Formula1:="=B1:B6"
    .IgnoreBlank = True
    .InCellDropdown = True
    .InputTitle = ""
    .ErrorTitle = ""
    .InputMessage = ""
    .ErrorMessage = ""
    .ShowInput = True
    .ShowError = True
End With

Instead of "A1" put the cell you want the drop down list to appear in.
Instead of "=B1:B6"  put the range to get the data from.


text:
Q: Conditional execution behind `set VAR 2> nul` fails

The set command with a variable name (prefix) sets the exit code to a non-zero value in case there is no matching variable defined; the exit code can be queried by conditional execution operators:
set VAR && echo Yes. || echo No!!

The above would return Yes. if VAR (or VARiable, etc.) is defined, and No!! otherwise, together with the error message Environment variable VAR  not defined from the set command.
However, when I try to suppress the error message, No!! is always echoed, independent on whether or not VAR is defined:
set VAR 2> nul && echo Yes. || echo No!!

The outcome is the same when I execute the command line in Command Prompt or in a batch file.
Why does insertion of the redirection part (2> nul) change the exit code received by the operators && and ||?

A: Referring to the command line:
set VAR 2> nul && echo Yes. || echo No!!

It seems that the SPACE between nul and && becomes treated as part of the variable name, so set does not check variables whose names begin with VAR, but instead VAR + SPACE, which is apparently not defined.

I created a batch file with a lot of tests, incorporating the cases from the useful comment by user LotPings:
@echo on
@rem /* Execute test cases in a sub-routine twice,
@rem    once with variable `VAR` defined and once not: */
@for %%I in ("Value" "") do @(
    set "VAR=%%~I"
    echo/& < nul set /P ="VARIABLE: "
    if defined VAR (set VAR) else echo VAR=
    call :SUB
)
@goto :EOF

:SUB
@rem // This constitutes a list of test cases:
@echo/& echo UNQUOTED (VAR):
set VAR && echo Yes. || echo No!!
set VAR> nul && echo Yes. || echo No!!
set VAR > nul && echo Yes. || echo No!!
set VAR 2> nul && echo Yes. || echo No!!
(set VAR > nul) && echo Yes. || echo No!!
(set VAR 2> nul) && echo Yes. || echo No!!
set VAR > nul&& echo Yes. || echo No!!
set VAR 2> nul&& echo Yes. || echo No!!
> nul set VAR && echo Yes. || echo No!!
2> nul set VAR && echo Yes. || echo No!!
@echo/& echo QUOTED ("VAR"):
set "VAR" && echo Yes. || echo No!!
set "VAR"> nul && echo Yes. || echo No!!
set "VAR" > nul && echo Yes. || echo No!!
set "VAR" 2> nul && echo Yes. || echo No!!
(set "VAR" > nul) && echo Yes. || echo No!!
(set "VAR" 2> nul) && echo Yes. || echo No!!
set "VAR" > nul&& echo Yes. || echo No!!
set "VAR" 2> nul&& echo Yes. || echo No!!
> nul set "VAR" && echo Yes. || echo No!!
2> nul set "VAR" && echo Yes. || echo No!!
@goto :EOF

And this is the related console window output:

>>> test-set.bat

VARIABLE: VAR=Value

UNQUOTED (VAR):

>>> set VAR   && echo Yes.   || echo No!!
VAR=Value
Yes.

>>> set VAR  1>nul  && echo Yes.   || echo No!!
Yes.

>>> set VAR   1>nul  && echo Yes.   || echo No!!
Environment variable VAR   not defined
No!!

>>> set VAR   2>nul  && echo Yes.   || echo No!!
No!!

>>> (set VAR  1>nul )  && echo Yes.   || echo No!!
Yes.

>>> (set VAR  2>nul )  && echo Yes.   || echo No!!
VAR=Value
Yes.

>>> set VAR  1>nul  && echo Yes.   || echo No!!
Yes.

>>> set VAR  2>nul  && echo Yes.   || echo No!!
VAR=Value
Yes.

>>> set VAR  1>nul  && echo Yes.   || echo No!!
Yes.

>>> set VAR  2>nul  && echo Yes.   || echo No!!
VAR=Value
Yes.

QUOTED ("VAR"):

>>> set "VAR"   && echo Yes.   || echo No!!
VAR=Value
Yes.

>>> set "VAR"  1>nul  && echo Yes.   || echo No!!
Yes.

>>> set "VAR"   1>nul  && echo Yes.   || echo No!!
Yes.

>>> set "VAR"   2>nul  && echo Yes.   || echo No!!
VAR=Value
Yes.

>>> (set "VAR"  1>nul )  && echo Yes.   || echo No!!
Yes.

>>> (set "VAR"  2>nul )  && echo Yes.   || echo No!!
VAR=Value
Yes.

>>> set "VAR"  1>nul  && echo Yes.   || echo No!!
Yes.

>>> set "VAR"  2>nul  && echo Yes.   || echo No!!
VAR=Value
Yes.

>>> set "VAR"  1>nul  && echo Yes.   || echo No!!
Yes.

>>> set "VAR"  2>nul  && echo Yes.   || echo No!!
VAR=Value
Yes.

VARIABLE: VAR=

UNQUOTED (VAR):

>>> set VAR   && echo Yes.   || echo No!!
Environment variable VAR  not defined
No!!

>>> set VAR  1>nul  && echo Yes.   || echo No!!
Environment variable VAR  not defined
No!!

>>> set VAR   1>nul  && echo Yes.   || echo No!!
Environment variable VAR   not defined
No!!

>>> set VAR   2>nul  && echo Yes.   || echo No!!
No!!

>>> (set VAR  1>nul )  && echo Yes.   || echo No!!
Environment variable VAR  not defined
No!!

>>> (set VAR  2>nul )  && echo Yes.   || echo No!!
No!!

>>> set VAR  1>nul  && echo Yes.   || echo No!!
Environment variable VAR  not defined
No!!

>>> set VAR  2>nul  && echo Yes.   || echo No!!
No!!

>>> set VAR  1>nul  && echo Yes.   || echo No!!
Environment variable VAR  not defined
No!!

>>> set VAR  2>nul  && echo Yes.   || echo No!!
No!!

QUOTED ("VAR"):

>>> set "VAR"   && echo Yes.   || echo No!!
Environment variable VAR not defined
No!!

>>> set "VAR"  1>nul  && echo Yes.   || echo No!!
Environment variable VAR not defined
No!!

>>> set "VAR"   1>nul  && echo Yes.   || echo No!!
Environment variable VAR not defined
No!!

>>> set "VAR"   2>nul  && echo Yes.   || echo No!!
No!!

>>> (set "VAR"  1>nul )  && echo Yes.   || echo No!!
Environment variable VAR not defined
No!!

>>> (set "VAR"  2>nul )  && echo Yes.   || echo No!!
No!!

>>> set "VAR"  1>nul  && echo Yes.   || echo No!!
Environment variable VAR not defined
No!!

>>> set "VAR"  2>nul  && echo Yes.   || echo No!!
No!!

>>> set "VAR"  1>nul  && echo Yes.   || echo No!!
Environment variable VAR not defined
No!!

>>> set "VAR"  2>nul  && echo Yes.   || echo No!!
No!!

The only cases that fail are those:
set VAR > nul && echo Yes. || echo No!!
set VAR 2> nul && echo Yes. || echo No!!

When the command parser recognises and temporarily removes the redirection part (see description of phase 2 in How does the Windows Command Interpreter (CMD.EXE) parse scripts?), potential SPACEs before > and/or after nul are left behind, which seem to be treated as part of the variable name by set, unless the given variable name is quoted; just one SPACE in total seems to be tolerated though.
Take also a look at the error messages Environment variable VAR   not defined with different numbers of SPACEs behind the variable name.

The set command seems to handle its arguments in a particular way:
@set "VAR=Value"
rem // No trailing spaces -- returns `VAR=Value`:
set VAR
rem // One trailing space -- returns `VAR=Value`:
set VAR
rem // Two or more trailing spaces -- returns an ERROR!
set VAR
rem // No trailing spaces -- returns `VAR=Value`:
set "VAR"
rem // One trailing space -- returns `VAR=Value`!?
set "VAR "
rem // Two or more trailing spaces -- returns an ERROR!
set "VAR  "

The unquoted syntax seems not to follow the standard rules for tokenisation where two or more consecutive token separators like the SPACE become combined into a single one.
The big surprise to me is that even the quoted syntax tolerances one SPACE, though it ignores all SPACEs following the closing " at least.
Even more surprising is the fact that some other text (like X) behind a SPACE still returns no error:
@set "VAR=Value"
rem // No spaces behind `X`, one in front -- returns `VAR=Value`!?
set VAR X
rem // No spaces behind `X`, two in front -- returns an ERROR!
set VAR  X
rem // No spaces behind `X`, one in front -- returns `VAR=Value`!?
set "VAR X"
rem // No spaces behind `X`, two in front -- returns an ERROR!
set "VAR  X"

redpajama_set_name: RedPajamaStackExchange


text:
Q: Xcode: Adding transition animation on UITabBar Can we add transition animation on UITabBar when clicking on tab bar item?

A: The similar kind of problem has been solved here:
http://haveacafe.wordpress.com/2009/04/06/animated-transition-between-tabbars-view-on-iphone/


text:
Q: Create trails of particles for the bullets I'm creating a space shooting game in which a spaceship will fire out bullets every time the user clicks the left mouse and since I want the bullets to be a bit fancier I want them to have a trail of particles behind them after being fired. I tried something to my code (which ended up to be the code that I'll show below) yet the result isn't good.

*

*The particles keep sticking to the bullets.

*Only one particle appeared.

What should I do to fix this? This is my code:
bullet_surf = pygame.image.load('graphics for b/beam.png')
bullet_surf = pygame.transform.rotozoom(bullet_surf,0,0.08)
bullets = []
while True:
....
    for event in pygame.event.get():
        if event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:
                bullets.append([[*ship_rect.midright],6,[random.randint(-20,20)/10,random.randint(-20,20)/10]])

    for b in range(len(bullets)):
        bullets [b][0][0] +=20

    for bullet in bullets[:]:
        if bullet [0][0] > 1100:
            bullets.remove(bullet)

    for bullet in bullets:
        bullet_rect = bullet_surf.get_rect(midleft = (bullet[0][0],bullet[0][1]))
        screen.blit(bullet_surf,bullet_rect)
        bullet_rect.centerx += bullet[2][0]
        bullet_rect.centery += bullet[2][1]
        bullet[1] -= 0.1
        print(bullet_rect.center)
        pygame.draw.circle(screen,(255,255,255),bullet_rect.center,int(bullet[1]))

A: You need to create a list of particles for each bullet. I suggest using a Class for the bullets:
self.particles = []

Add a new particle to the list and animate the particles in the list as the bullet moves:
for particle in self.particles:
    particle[0][0] -= 2
    particle[0][1] += particle[1]
particle = [list(self.rect.midleft), random.uniform(-2, 2), pygame.Color(255, random.randrange(255), 0)]
self.particles.append(particle)
if len(self.particles) > 30:
    self.particles.pop(0)

Draw all the particles in the list in a loop:
for i, particle in enumerate(self.particles):
    pygame.draw.circle(screen, particle[2], particle[0], (i//3+2))

Minimal example

import pygame, random

pygame.init()
window = pygame.display.set_mode((400, 200))
clock = pygame.time.Clock()

class Bullet:
    def __init__(self, x, y):
        self.image = pygame.image.load("rocket.png")
        self.rect = self.image.get_rect(center = (x, y))
        self.particles = []

    def move(self):
        for particle in self.particles:
            particle[0][0] -= 2
            particle[0][1] += particle[1]
        particle = [list(self.rect.midleft), random.uniform(-2, 2), pygame.Color(255, random.randrange(255), 0)]
        self.particles.append(particle)
        if len(self.particles) > 30:
            self.particles.pop(0)
        self.rect.centerx += 3

    def draw(self, screen):
        for i, particle in enumerate(self.particles):
            pygame.draw.circle(screen, particle[2], particle[0], (i//3+2))
        screen.blit(self.image, self.rect)

background = pygame.Surface(window.get_size())
ts, w, h, c1, c2 = 50, *background.get_size(), (32, 32, 32), (64, 64, 64)
tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)]
[pygame.draw.rect(background, color, rect) for rect, color in tiles]

bullet = Bullet(0, 100)

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    bullet.move()
    if bullet.rect.left >= 400:
        bullet.rect.right = 0

    window.blit(background, (0, 0))
    bullet.draw(window)
    pygame.display.flip()
    clock.tick(100)

pygame.quit()
exit()

Example of firing bullets by mouse click:

import pygame, random

pygame.init()
window = pygame.display.set_mode((400, 400))
clock = pygame.time.Clock()

class Bullet:
    def __init__(self, x, y):
        self.image = pygame.image.load("rocket.png")
        self.rect = self.image.get_rect(center = (x, y))
        self.particles = []

    def move(self):
        for particle in self.particles:
            particle[0][0] -= 2
            particle[0][1] += particle[1]
        particle = [list(self.rect.midleft), random.uniform(-2, 2), pygame.Color(255, random.randrange(255), 0)]
        self.particles.append(particle)
        if len(self.particles) > 30:
            self.particles.pop(0)
        self.rect.centerx += 3

    def draw(self, screen):
        for i, particle in enumerate(self.particles):
            pygame.draw.circle(screen, particle[2], particle[0], (i//3+2))
        screen.blit(self.image, self.rect)

background = pygame.Surface(window.get_size())
ts, w, h, c1, c2 = 50, *background.get_size(), (32, 32, 32), (64, 64, 64)
tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)]
[pygame.draw.rect(background, color, rect) for rect, color in tiles]

bullets = []

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.MOUSEBUTTONDOWN:
            bullets.append(Bullet(*event.pos))

    for bullet in bullets[:]:
        bullet.move()
        if bullet.rect.left >= 400:
            bullets.remove(bullet)

    window.blit(background, (0, 0))
    for bullet in bullets[:]:
        bullet.draw(window)
    pygame.display.flip()
    clock.tick(100)

pygame.quit()
exit()


text:
Q: Mdi parent form with other mdi parent form as a child I would like to create two mdi parent forms one containing another. Is it possible to so?

A: I'm afraid not, Windows does not support nested MDI forms.
http://support.microsoft.com/default.aspx?scid=kb;en-us;74041


text:
Q: List of past bounties on a SE site I would wish to look at past bounties that had been started on a SE site. The purpose is to gauge their "success rate" i.e. how effective have they been in pulling required answers from the community in the past. This would help me decide how large a bounty to put and whether to even put a bounty or not.
I know that once a bounty period (7 days + 24 hour grace period) has passed, it is removed from the "featured" tab. Hence, I have been unable to view the bounties that had been raised, say, in the past six months. Is such a list possible?

A: The following query does that by looking at the votes table with votetypeid = 8 (bountystart). From there it is easy to join the winning answer.
with awarded as
(
select v.postid
     , v.bountyamount
     , v.creationdate
     , p.parentid questionid
     , p.owneruserid
     from votes v
     inner join posts p on p.id = v.postid
     where v.votetypeid = 9 -- award
)

select top ##maxrows?100##
'site://q/' + cast(v.postid as nvarchar)+ '|' + q.title as [Question]
     , v.bountyamount
     , v.creationdate
     , v.userid as [User Link]
     , a.postid as [Post Link]
     , a.bountyamount
     , a.owneruserid as [User Link]
from votes v
inner join posts q on q.id = v.postid
left outer join awarded a
  on v.postid = a.questionid
 and a.creationdate
 between v.creationdate
 and dateadd(d, 8, v.creationdate)
where v.votetypeid = 8 -- bounty start
order by v.creationdate desc

When run today on Stack Overflow your result will look like this:

The first userlink is the user who offered the bounty, the second userlink is the OP of the answer that received the bounty. I included both bounty amounts as only 50% of the awarded bounty amount is given if the system selects the winner (instead of the user who started the bounty) in which case the second amount would then be lower.
In the votes table all creationdates are sanitized and have their time part removed so voters remain anonymous. This is maybe not needed for bounties but the rule applies to the whole table to prevent mishaps (the votes table also include up and down votes).
Keep in mind SEDE is only updated once a week, on Sunday.
Don't forget to check the awesome tutorial that learns you how to get the best out of SEDE.


text:
Q: AttributeError: 'NoneType' object has no attribute 'mainloop' from sys import platform as sys_pf
if sys_pf == 'darwin':
import matplotlib
matplotlib.use("TkAgg")

from tkinter import *
from tkinter.ttk import *
import ui

def init_UI():

    main = Tk()
    main.title('data2knowledge')
    n = Notebook(main)

    ProcessTab = Frame(n)
    MergeTab = Frame(n)
    LearningTab = Frame(n)
    ReportTab = Frame(n)
    AboutTab = Frame(n)

    n.add(ProcessTab, text = "Process")
    n.add(MergeTab, text = "Merge")
    n.add(LearningTab, text = "Learn")
    n.add(ReportTab, text = "Report")
    n.add(AboutTab, text = "About")

if __name__ == '__main__':
    '''initialize GUI and start it'''
    gui = init_UI()
    gui.mainloop()

The error I get when running this code is:
AttributeError: 'NoneType' object has no attribute 'mainloop'
I believe I need this last if-statement / mainloop() function to get the interface up and running, but I keep getting this error. I really hope someone knows how to solve this! Thanks!

A: Your init_UI has no return. Therefore, with gui = init_UI(), gui is None.
Perhaps you meant to return main at the end of init_UI?

A: You need to return main from init_UI().
So add at the end of your function:
def init_UI():
   # ...
   return main

Explanation
Your init_UI function does not have any return statement. Thus doesn't return any value, which in Python is marked as None.
And thus the last two lines of your program effectively become:
 gui = init_UI()
 None.mainloop()

A: init_UI() returns None by default; this None value is assigned to gui.
gui = init_UI()
gui.mainloop()

You must return the Tk object main from init_ui, so it is assigned to gui, then call mainloop on ``gui`.


text:
Q: Заполнения массива POST Есть страница с формой списком товара. мне нужно получить названия товара и количество.
<input type="text" class="spinner-input form-control"  name="count" value="0">
 <input name="name_product" type = "hidden" value = "<?=$item['name'];?>">

таких полей формируется штук 10-15.
$suppliers_data = array();
$suppliers_data['count'] = $this->input->post('count');
$suppliers_data['name'] = $this->input->post('name_product');

тут якобы я получаю данные и заполняю массив
но когда делаю echo,print_r у меня выводиться данные с последнего поля.
Я так предполагаю тут нужно куда то цикл засунуть..но у меня ничего не получилось..
вообще мне их нужно потом в бд засунуть, но для проверки использую вывод echo,print_r
A:
таких полей формируется штук 10-15

<input name="name_product[]" type = "hidden" value = "<?=$item['name'];?>">

Теперь это массив, ключевой момент в имени инпута name_product[], теперь и print_r() можно выполнять!
UPD для далеких
Из комментария:

когда будет прохордить цикл по
созданию этих форм

//$query = тут Sql запрос
while($item = mysql_fetch_assoc($query))
{
    echo '<input name="name_product[]" type = "hidden" value = "'.$item['name'].'">';
}

//После отправки на сервер
print_r($_POST['name_product']);


text:
Q: What is a 'known_hosts' file and what does it contains I have navigated to /home/some-user/.ssh/ folder and found a file named known_hosts.
What is the purpose of this file and what does it contains?

A: The purpose of the known_hosts file is described quite well in man ssh:

 ssh automatically maintains and checks a database containing identifica‐
 tion for all hosts it has ever been used with.  Host keys are stored in
 ~/.ssh/known_hosts in the user's home directory.  Additionally, the file
 /etc/ssh/ssh_known_hosts is automatically checked for known hosts.  Any
 new hosts are automatically added to the user's file.  If a host's iden‐
 tification ever changes, ssh warns about this and disables password
 authentication to prevent server spoofing or man-in-the-middle attacks,
 which could otherwise be used to circumvent the encryption.  The
 StrictHostKeyChecking option can be used to control logins to machines
 whose host key is not known or has changed.


text:
Q: Eloquent casting int as string So, I'm experiencing the following situation with two models:
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

use App\Models\Landing;

class Network
{
    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function landings()
    {
        return $this->belongsToMany(Landing::class);
    }
}

And:
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

use App\Models\Network;

class Landing
{
    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function networks()
    {
        return $this->belongsToMany(Network::class);
    }
}

So, when I call the relation:
<?php

$landing = Landing::find(16);
$networks = $landing->networks()->get();

Eloquent generate the following SQL:
SELECT *
FROM `landings`
    INNER JOIN `landing_network` ON `landings`.`id` = `landing_network`.`landing_id`
WHERE `landing_network`.`network_id` = '16' AND `landings`.`deleted_at` IS NULL;

As you can see, the landing_network.network_id snippet, is generated as string, but is has a performance issue on MySQL due to casting.
How can I make Laravel/Eloquent create this relation/join query without casting integer to string?


text:
Q: "libcontainerd: failed to receive event from containerd: rpc error: code = 13 desc = transport is closing" We are suffering this error in our Dataflow job for three or four months:

libcontainerd: failed to receive event from containerd: rpc error: code = 13 desc = transport is closing

My notions about Dataflow are quite limited, but it seems to be a correlation between the appearance of this error and a sudden decay of the CPU activity of our worker.
I have been reading a bit about it in different entries and at first I thought it had to do with the google.cloud.datastore library (we make a lot of queries and write a great number of entities in our datastore database) , but I am not sure at all right now. Do you have any idea concerning this error? If you do, any ideas on how to solve it?

A: The issue seems to be related to reaching the machine resources limits, you should try using a higher machine type . You can specify the machine type within the Pipeline configuration options
There is a similar issue reported on Public Issue Tracker


text:
Q: Webpack v4 — how to access 'mode' option value Webpack v4 has introduced two sets of defaults: production and development. My question is: Is there a way to refer to those inside a configuration file? I know I can still pass environment variables as:
--env.NODE_ENV=development

by doing this I have two independent environment variables and this doesn't feel right. Another option would be obviously to refer to a different config file and this doesn't look like an optimal solution for simple configurations as well.
Am I missing something here?

A: Found a better way in a webpack github issue.
Since webpack 2 you can export a function in webpack.config.js, the parsed argv will be passed to that function.
For webpack 4 you can write the config like:
// webpack.config.js
module.exports = (env, argv) => {
    console.log(argv.mode);
    return { /* your config object */ };
};

// $webpack-cli --mode development
// development

Original Answer:
You can use some libs like minimist to parse the arguments passed by the cli:
// webpack.config.js
const args = require('minimist')(process.argv.slice(2));
console.log(args.mode);

// $webpack-cli --mode development
// development

A: I've just built this simple NPM package for importing current Webpack 4 mode: https://github.com/mckomo/webpack-mode. Here is how you can use it:
// webpack.config.js
const { isProduction } = require('webpack-mode');

console.log(isProduction); // => true

// ... rest of the config

It works very simply, just reads process arguments to determine the value of mode argument. By default webpack-mode.isProduction will return true (original behaviour of the Webpack 4).


text:
Q: Environment variables in .erb file I am creating a dashboard with dashing. I have some environment variables I am using in my jobs .rb file. Whenever I try to use any environment variable in my dashboard .erb file it doesnt seem to work. I am trying to put the environment variable within a url. My environment variable is #{ENV['Variable']}. Any ideas how to get environment variables to work in .erb file?

<% content_for :title do %>xxxxxx<% end %>

A: I got it. I just had to do:
'https://xxxxx.<%= ENV['ENVHOST'] %>.xxxxx.com/'


text:
Q: Pandas groupby percentage of total and add subtotals Similar to this previous post, I would like to derive the percentage within each group but based on the sum of multiple columns and add subtotals. For example given the dataframe below:
import numpy as np
import pandas as pd

np.random.seed(0)

df = pd.DataFrame({'state': ['CA', 'WA', 'CO', 'AZ'] * 3,
               'office_id': list(range(1, 7)) * 2,
               'sales': [np.random.randint(100000, 999999) for _ in range(12)],
               'sales2': [np.random.randint(100000, 999999) for _ in range(12)],
               'sales3': [np.random.randint(100000, 999999) for _ in range(12)]})

The ideal results would yield:

Update
It would be ideal to groupby both state and office id for situations where there are repeating values for office id column. Here is an example:
df = pd.DataFrame({'state': ['CA', 'WA', 'CO', 'AZ'] * 3,
               'office_id': [1,1,1,2,2,2] * 2,
               'sales': [np.random.randint(100000, 999999) for _ in range(12)],
               'sales2': [np.random.randint(100000, 999999) for _ in range(12)],
               'sales3': [np.random.randint(100000, 999999) for _ in range(12)]})

This should then yield:

A: We need create you need step by step, include groupby with append the subtotal per group on column , then transform the total sum with state
s = df.groupby('state')[['sales','sales2','sales3']].sum().assign(office_id = 'Subtotal').set_index('office_id',append=True)
out = pd.concat([df,s.reset_index()]).sort_values('state')
out['Subtotal'] = out[['sales','sales2','sales3']].sum(axis=1)
v = out.groupby('state')['Subtotal'].transform('sum')/2
out.update(out[['sales','sales2','sales3','Subtotal']].div(v,axis=0))
out
   state office_id     sales    sales2    sales3  Subtotal
3     AZ         4  0.047124  0.175385  0.118068  0.340578
7     AZ         2  0.041571  0.087926  0.087902  0.217399
11    AZ         6  0.156107  0.131998  0.153919  0.442023
0     AZ  Subtotal  0.244802  0.395309  0.359889  1.000000
0     CA         1  0.062026  0.127860  0.145870  0.335756
4     CA         5  0.150188  0.107702  0.068203  0.326092
8     CA         3  0.108636  0.129193  0.100323  0.338152
1     CA  Subtotal  0.320849  0.364755  0.314396  1.000000
2     CO         3  0.058604  0.072756  0.142734  0.274095
6     CO         1  0.108667  0.208210  0.145513  0.462390
10    CO         5  0.127604  0.095630  0.040282  0.263516
2     CO  Subtotal  0.294875  0.376596  0.328529  1.000000
1     WA         2  0.106233  0.081434  0.085797  0.273463
5     WA         6  0.091156  0.127159  0.138270  0.356585
9     WA         4  0.108694  0.195807  0.065451  0.369952
3     WA  Subtotal  0.306083  0.404399  0.289518  1.000000

A: Here's a one-liner (except for the extra cols variable to shorten the code overall):
cols = df.filter(like='sales').columns

new_df = df.assign(**{k:list(v.values()) for k,v in df[cols].apply(lambda c:c/c.groupby(df['state']).transform(sum)).to_dict().items()}).groupby('state').apply(lambda x:x.append(pd.Series({'office_id':'subtotal',**x.sum().to_dict()},name=''))).droplevel(1).drop('state',axis=1).reset_index()

Output:
>>> new_df
   state office_id     sales    sales2    sales3
0     AZ         4  0.192500  0.443666  0.328069
1     AZ         2  0.169814  0.222423  0.244248
2     AZ         6  0.637686  0.333910  0.427683
3     AZ  subtotal  0.964236  0.636485  1.399280
4     CA         1  0.193319  0.350536  0.463970
5     CA         5  0.468094  0.295272  0.216932
6     CA         3  0.338587  0.354192  0.319098
7     CA  subtotal  1.007825  0.980298  1.011877
8     CO         3  0.198743  0.193194  0.434464
9     CO         1  0.368519  0.552873  0.442923
10    CO         5  0.432739  0.253933  0.122613
11    CO  subtotal  0.826401  1.364314  0.809285
12    WA         2  0.347072  0.201369  0.296343
13    WA         6  0.297815  0.314438  0.477587
14    WA         4  0.355113  0.484192  0.226070
15    WA  subtotal  0.844785  1.089840  1.065375

It's gnarly, so I'll provide a breakdown:
new_df = (df
    # This assign call selects all the sales columns, computes the percentages, and assigns them back to the dataframe
    .assign(**{
        k: list(v.values())
        for k,v
        in df[cols].apply(
            lambda c: c / c.groupby(df['state']).transform(sum)
        )
        .to_dict()
        .items()
    })
    .groupby('state')
    .apply(lambda x: x.append(
        pd.Series(
            {
                'office_id': 'subtotal',
                **(x[cols]
                    .sum(1)
                    .to_dict()
                )
            },
            name=''
        )
    ))
    .droplevel(1)
    .drop('state', axis=1)
    .reset_index()
)


text:
Q: Add stuff above header edit form I am searching for a hook that gives me the opportunity to add some stuff above the heading line in the edit page.
I found these hook but this place some stuff between the heading and the title.
add_action( 'edit_form_top', 'test' );

function test(){
?>

    hello

<?php
}
?>

Is there somebody who know if there is a hook for this?

A: You can use this hook
add_action( 'in_admin_header', 'testt');

It fires between
 and
 tags.


text:
Q: Prevent Selecting Same value in multiple dropdown working fine but after click add / Delete button then prevent duplication function not working I have six interface list in option menu , but in future it may be increases.I want when someone click on add button then it shows only rest interface list that are not selected before in option menu.

$(document).ready(function() {
  var maxField = 3; //Input fields increment limitation
  var addButton = $('.add_button'); //Add button selector
  var wrapper = $('.field_wrapper'); //Input field wrapper
  var fieldHTML = '
' +
    '<select name="name[]" class="select">' +
    '<option value="">Select</option>' +
    ' <option value="eth0">eth0</option> ' +

    '<option value="eth1">eth1</option>' +

    '<option value="eth2">eth2</option>' +
    '<option value="eth3">eth3</option>' +
    '<option value="eth4">eth4</option>' +

    '<option value="eth5">eth5</option>' +
    '<option value="eth6">eth6</option>' +

    '</select>' +

    '<select name="name[]" class="select">' +
    '<option value="">Select</option>' +
    ' <option value="eth0">eth0</option> ' +

    '<option value="eth1">eth1</option>' +

    '<option value="eth2">eth2</option>' +
    '<option value="eth3">eth3</option>' +
    '<option value="eth4">eth4</option>' +

    '<option value="eth5">eth5</option>' +
    '<option value="eth6">eth6</option>' +

    '</select>Delete
'; //New input field html

  var x = 1; //Initial field counter is 1

  //Once add button is clicked
  $(addButton).click(function() {
    //Check maximum number of input fields
    if (x < maxField) {
      x++; //Increment field counter
      $(wrapper).append(fieldHTML); //Add field html
    }
  });

  //Once remove button is clicked
  $(wrapper).on('click', '.remove_button', function(e) {
    e.preventDefault();
    $(this).parent('div').remove(); //Remove field html
    x--; //Decrement field counter
  });
});

$('select').change(function() {
  var myOpt = [];
  $("select").each(function() {
    myOpt.push($(this).val());
  });
  $("select").each(function() {
    $(this).find("option").prop('hidden', false);
    var sel = $(this);
    $.each(myOpt, function(key, value) {
      if ((value != "") && (value != sel.val())) {
        sel.find("option").filter('[value="' + value + '"]').prop('hidden', true);
      }
    });
  });
});

  <form method="post" action="dashboard.php">

           Interface
          <select name="name[]" class="select">
            <option value="">Select</option>
            <option value="eth0">eth0</option>
            <option value="eth1">eth1</option>
            <option value="eth2">eth2</option>
            <option value="eth3">eth3</option>
            <option value="eth4">eth4</option>
            <option value="eth5">eth5</option>
            <option value="eth6">eth6</option>
          </select>

            <select name="name[]" class="select">
              <option value="">Select Pair</option>
              <option value="eth0">eth0</option>
              <option value="eth1">eth1</option>
              <option value="eth2">eth2</option>
              <option value="eth3">eth3</option>
              <option value="eth4">eth4</option>
              <option value="eth5">eth5</option>
              <option value="eth6">eth6</option>
            </select>
            <select name="name[]" class="select">
              <option value="">Select Pair</option>
              <option value="eth0">eth0</option>
              <option value="eth1">eth1</option>
              <option value="eth2">eth2</option>
              <option value="eth3">eth3</option>
              <option value="eth4">eth4</option>
              <option value="eth5">eth5</option>
              <option value="eth6">eth6</option>
            </select>

            <select name="name[]" class="select">
              <option value="">Select Pair</option>
              <option value="eth0">eth0</option>
              <option value="eth1">eth1</option>
              <option value="eth2">eth2</option>
              <option value="eth3">eth3</option>
              <option value="eth4">eth4</option>
              <option value="eth5">eth5</option>
              <option value="eth6">eth6</option>
            </select>
            <select name="name[]" class="select">
              <option value="">Select Pair</option>
              <option value="eth0">eth0</option>
              <option value="eth1">eth1</option>
              <option value="eth2">eth2</option>
              <option value="eth3">eth3</option>
              <option value="eth4">eth4</option>
              <option value="eth5">eth5</option>
              <option value="eth6">eth6</option>
            </select>
            Add

  </form>

I have tried many things but didn't work. Please help me to resolve this problem.

A: Problem here is your newly created select don't get assign change event.
Instead of
$('select').change(function() {
   ...
});

Try
$(document).on('change', 'select', function(){
   ...
});


text:
Q: Как добавить "-" перед репликой? Как добавить "-" перед каждой репликой разных людей, однако, если несколько реплик поступает от одного человек - то после первой не ставить?
Пример:
-Привет
-Привет
 Как дела?

document.addEventListener('DOMContentLoaded', function() {

  const messagesContainer = document.querySelector("#messages_container");
  const messageInput = document.querySelector('[name=message_input]');
  const sendMessageButton = document.querySelector('[name=send_message_button]');

  let websocketClient = new WebSocket("ws://localhost:12345");

  websocketClient.onopen = () => {
    console.log("Client conntected!");
    websocketClient.send("Hello!");

    sendMessageButton.onclick = () => {
      websocketClient.send(messageInput.value);
      messageInput.value = "";
    };

  };

  websocketClient.onmessage = (message) => {
    const newMessage = document.createElement('div');
    newMessage.innerHTML = message.data;
    messagesContainer.appendChild(newMessage);
    console.log(message.data);
  }

  document.onkeydown = (e) => {
    if (e.key === 'Enter') {
      websocketClient.send(messageInput.value);
    }
  }

}, false);
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Version1</title>

  <link href="style.css" rel="stylesheet" type="text/css">

    <input type="text" name="message_input">

<input type="button" name="send_message_button" value="Send message">

A: Допустим, если имя отправившего сообщение лежит в message.nameFrom:
let last;
websocketClient.onmessage = (message) => {
  const newMessage = document.createElement('div');
  const pref = last !== message.nameFrom ? '- ' : '';
  last = message.nameFrom;
  newMessage.innerHTML = pref + message.data;
  messagesContainer.appendChild(newMessage);
  console.log(message.data);
}

Т.е. надо просто запоминать, кто последний и сравнивать имя нового сообщения.
Не совпадает, добавляем, совпадает, не добавляем


text:
Q: При optimistic locking не меняется значение столбика version в таблице Для реализации оптимистических блокировок добавил поле с аннотацией @Version:
package com.example.my_api.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.*;
import java.util.List;

@Entity
@Table(name = "clients")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Client {

    // ...

    @Version
    private Long version;

    // ...

}

В соответствующей таблице добавил столбик version. Далее тестирую Postman-ом. Сначала создаю нового клиента запросом POST, потом обновляю его данные (имя, возраст) запросом PUT. Если я правильно понял, то при обновлении сущности у нас автоматически должно увеличиваться значение поля version на единицу. Но в моём случае этого не происходит:

Значение 0 и не увеличивается. Можете подсказать, в чём ошибка?


text:
Q: Best and fast practice to reload an external javascript file? Hello guys i have a big doubt....
In my javscript code i need to reload a js file (where there's a multidimensional array) every 1 minutes.
To reload it suggest me to use ajax or another way ?
Example A:
       try {
          jQuery.ajax({
            url: "http://www.fake.con/scripts/out/array/week-quakes.js",
            dataType: "script",
            cache: false
          });
        }
        catch(e){
            var aggiungi= 'there's error about server';
            $(aggiungi).appendTo('#lista-eq');
        }

Example B
$("head script[src='http://www.fake.con/scripts/out/array/week-quakes.js']").remove();

$('head').append('


text:
Q: How to handle NULL Dates in an "Accumulating fact table" One type of fact table in Dimensional modeling is Accumulating Snapshot fact Table. if you think you need to review the meaning and definition of this type , you can take a look at this article :
https://www.holistics.io/blog/the-three-types-of-fact-tables/.
Imagine we have an accumulating fact table which has three important date column in it
'Order_Datekey , Manufacturing_Datekey , Ship_Datekey'

When the table is being inserted for the first time ,there is no data for columns Manufacturing_Datekey and Ship_Datekey'. We only know the date in which the product has been ordered (Order_date). What I need to know is that how we can handle null values for Date columns ?
The important point I read in Kimbal book is that null should be avoided in a foreign key column.
'Referential
integrity is violated if you put a null in a fact table column declared as a foreign key
to a dimension table'

On the other hand we don't have any value for these two date columns at first. What do you suggest?
Thanks in advance

A: You say "null should be avoided in a foreign key column," but are these dates really FKs?
Most likely, these dates are just attributes of an order, and if the dates are unknown (and the reason they are unknown may be "because it hasn't happened yet"), then NULL is the best way to represent those attributes.
If the Manufacturing Date or Shipping Date is your Foreign Key (or part of your Foreign Key) to other tables, then it would be an indication that you might want to rethink your table structure.


text:
Q: Loading Objective C code dynamically I am looking for a possibility of loading Obj C based source dynamically and show the view in my iOS application. For example: I have a set of code written for showing a view, i want to dynamically load this code and show this view.
Some thing like,

*

*I'll have a service running in the background of my iOS app.

*It will get a set of Obj C code from my server in text format

*This dynamic Obj C code should get executed dynamically and show the respective iOS view

From Comments Not released in the appstore.. its for internal
Is this possible?

A: Short answer: No
Not so short answer:
You could—in theory—include either the C, or C++ interface to the Clang compiler toolchain in your project, have that library compile the code you download, and then (through either NSBundle or direct interaction with dlopen) link that compiled code into your app.
In practice, if what you want to achieve is submitting to the App Store, this is explicitly prohibited by the Terms and Conditions.

A: You can't do this for deployment to the app store.
You wouldn't use plain text for this, you'd use a bundle (NSBundle). A bundle can contain both file (graphics, NIBs) resources and code so you can create your view classes and any associated NIBs, compile the bundle and then store it on your server. The app can then download the bundle and load it at runtime.

A: You can do it for non-app store apps.  I have not tried  this approach.
From Apple Docs:

The key to loading code from an external bundle is finding an
  appropriate entry point into the bundle's executable file. As with
  other plug-in schemes, this requires some coordination between the
  application developer and the plug-in developer. You can publish a
  custom API for bundles to implement or define a formal plug-in
  interface. In either case, once you have an appropriate bundle or
  plug-in, you use the NSBundle class (or the CFBundleRef opaque type)
  to access the functions or classes implemented by the external code.
Loading Objective-C Classes If you are writing a Cocoa application,
  you can load the code for an entire class using the methods of
  NSBundle. The NSBundle methods for loading a class are for use with
  Objective-C classes only and cannot be used to load classes written in
  C++ or other object-oriented languages.


text:
Q: Macchanger returns error but mac adress is changed Because I wanted to understand how my ISP is assigning the IP addresses to the different devices connected to the same router I first tried to change my IP with disconnecting from the network and reconnect to it.
Online I read that I might get a new IP address if I change the Mac address.
So I tried to change the Mac address using the following commands:
$ sudo ifconfig wlan0 down

$ sudo macchanger -m 00:11:22:33:44:55 wlan0

what I got, was the following output:

Current MAC:   aa:bb:cc:dd:ee:ff (unknown)
  Permanent MAC: aa:bb:cc:dd:ee:ff (unknown)
  [ERROR] Could not change MAC: interface up or insufficient permissions: Too   many open files in system

But if I set the wifi adapter up again with:
$ sudo ifconfig wlan0 up

and then check for the mac adress with:
$ sudo macchanger wlan0

the output i got was:

Current MAC:   00:11:22:33:44:55 (CIMSYS Inc)
  Permanent MAC: 44:1c:a8:f9:bb:bd (unknown)

So apparently the mac address was changed even though I got an error message.
I know the mac address was definitely changed because I was also not able to connect to my wifi anymore (if I change back to the permanent one I can connect again).
Now my question:
Can anybody tell me why I get an error message even though the mac address was changed?
Thanks for your help and sorry if I didn't use the perfectly correct terms to describe everything. But I hope it is still understandable and else please ask and correct me.
Cheers, Baba Shrimp
First of all thanks a lot for your fast answer.
I checked for further information and found the Information for the Ethernet interface as well as for the wireless connection.
But to be honest I have no idea what I should do with this information now?
Then I checked out the website of macchanger where I could find the zipped macchanger version 1.6.0 as well as the pgp signature which belongs to it.
So I downloaded both and tried to check for it's integrity. I never used gpg before so I tried to read into it. I tried to verify the integrity with:
gpg --verify macchanger-1.6.0.tar.gz.sig  macchanger-1.6.0.tar.gz

Which resulted basically in:

gpg: signature can not be verified: no public key.

So I started looking for the public key of macchanger but didn't even came close to find infos about where I can find the key. I found how to import a key. But how import a key if you don't know where to import it from?
apt source macchanger does not work because of the following ussue:

Source package for macchanger can not be found

And for your last hint I don't even understand what macchanger-1.7.0/src/netinfo.c
should be. So I think it is not necessary to mention that I have idea what code underneath it means.
I can understand if you have no interest in answering all this questions. So maybe you could just give me a better hint where to start with my research if I just want to learn something about how networks work?
Thanks a lot
Baba Shrimp

A: Possibly a bug in macchanger with your particular hardware. The hardware accepted the change, but the reported status was misunderstood by macchanger.
sudo lshw -C network will show what hardware you're using, which driver, ...
macchanger has it's own web page: http://www.gnu.org/software/macchanger.
apt source macchanger will download the source, so you can see how it works.
The error message comes from macchanger-1.7.0/src/netinfo.c:
 85 mc_net_info_set_mac (net_info_t *net, const mac_t *mac)
 86 {
 87         int i;
 88
 89         for (i=0; i<6; i++) {
 90                 net->dev.ifr_hwaddr.sa_data[i] = mac->byte[i];
 91         }
 92
 93         if (ioctl(net->sock, SIOCSIFHWADDR, &net->dev) < 0) {
 94                 perror ("[ERROR] Could not change MAC: interface up or insufficient permissions");
 95                 return -1;
 96         }
 97
 98         return 0;
 99 }


text:
Q: BRNN implementation issue I am trying to implement bidirectional RNN from scratch and have the issue with it.
Let's assume we have implemented RNN cell with given number of hidden units, in this case the forward pass for BRNN will be the next (pseudocode):
def brnn_forward(input):
    hiddden_state = RNN.forward(input)
    reversed_input = reverse(input)
    hiddden_state_reversed = RNN.forward(reversed_input)
    output = concatenate(hiddden_state, hiddden_state_reversed)
    return output

But then I don't know how to implement backward pass. I get derivative error dA (shape = (hidden_units, batch_size, times)) from the next layer with the shape of forward pass output (assuming of course we didn't have concatenation of outputs which doubled amount of hidden units after forward pass).
However the standard RNN cell backward function takes dA with the shape of forward input, so I've tried:
def brnn_backward(dA):
    h = number_of_hidden_units
    d_hiddden_state = RNN.backward(dA[:h,:,:])
    d_hiddden_state_reversed = RNN.backward(dA[h:,:,:])
    dA_for_previous_layer = d_hiddden_state+d_hiddden_state_reversed
    return dA_for_previous_layer

But it didnt work and gave me results worse then with unidirectional RNN.
Also I am not sure how to find derivative error for previous layer (in case we have embedding layer before for instance). Could someone help with backward pass?

A: In my opinion, backward and forward in BiRNN are the same process, their difference is the sequence of input.
You don't need to implement a specific function for forward or backward cell, just create a normal RNN cell, give input states and get output states. In forward chain, you could pass normal input sequence into it, and pass a reverse sequence of input in backward chain.
If you have time, you could read the code how TensorFlow implement BiRNN based on normal RNN. https://github.com/tensorflow/tensorflow/blob/r1.9/tensorflow/python/ops/rnn.py#L315


text:
Q: How to use FontIcon and Glyph in ShellPage with XAML? The Symbol enum does not cover my icon needs. So I need to use FontIcon and glyph. Is it an easy solution to make this work just like having: Icon="Home"? I cant get it to allign properly. This is my XAML and how it looks in the preview(Profile icon just to illustrate how I want it to look):
        <winui:NavigationViewItem x:Uid="Shell_Trips" Icon="Home" helpers:NavHelper.NavigateTo="views:MainPage" />
        <winui:NavigationViewItem x:Uid="Shell_Scanner" helpers:NavHelper.NavigateTo="views:MainPage">
            <FontIcon FontFamily="{StaticResource SymbolThemeFontFamily}" Glyph=""/>
        </winui:NavigationViewItem>

The profile Icon works like I want it to. How can I achieve this with FontIcon?

A:   <winui:NavigationViewItem x:Uid="Shell_Scanner" helpers:NavHelper.NavigateTo="views:MainPage">
      <winui:NavigationViewItem.Icon>
          <FontIcon FontFamily="{StaticResource SymbolThemeFontFamily}" Glyph=""/>
      </winui:NavigationViewItem.Icon>
  </winui:NavigationViewItem>


text:
Q: PostGis geometry name lookup failed for table I have a table name erpAssets which has column name Region of type polygon. it contains entries of points also like (-79.4609576808001,43.9726680183837)).
I have written query which convert these points to geometry which is used by mapnick to generate tiles.
(
SELECT replace(concat(concat('POINT',concat(trim(TRAILING ')'FROM  concat('(',trim(LEADING '(' FROM region::TEXT)::TEXT) ),')')),''),',',' ') as data
 from "erpAssets" where parent=326815) as foo
        ) as points
My osm.xml file is as follows:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE Map [
<!ENTITY % entities SYSTEM "inc/entities.xml.inc">
%entities;
]>
<Map background-color="#bb0000" srs="&srs900913;" minimum-version="2.0.0">
  &fontset-settings;
 <Style name="theme_park">
     <Rule>
      <PointSymbolizer file="&symbols;/alpinehut.p.16.png"

      />

    </Rule>

</Style>

&layer-shapefiles;
<Layer name="theme_park" status="on" srs="&osm2pgsql_projection;">
    <StyleName>theme_park</StyleName>
    <Datasource>
      <Parameter name="table">
        (SELECT ST_GeomFromText(data)
FROM
(
SELECT replace(concat(concat('POINT',concat(trim(TRAILING ')'FROM  concat('(',trim(LEADING '(' FROM region::TEXT)::TEXT) ),')')),''),',',' ') as data
 from "erpAssets" where parent=326815) as foo
        ) as points

      </Parameter>
      &datasource-settings;
    </Datasource>
</Layer>
</Map>

Tiles are not generated and i am getting error on console as follows:
Postgis Plugin: geometry name lookup failed for table '"erpassets"'. Please manually provide the 'geometry_field' parameter or add an entry in the geometry_columns for '"erpassets"'.
I have converted region column into geometry by aliasing then why i am not getting points on map?

A: How applications use PostGIS is they look up the metadata for geometry columns in the geometry_columns view (formerly a table). How you have set up the query is that each time regions, a text column, is translated and converted to a geometry column. However, since this result is part of a query, and not part of a table, it does not appear in geometry_columns, as Mapnik expects.
Add a geometry column and update your source table:
ALTER TABLE "erpAssets" ADD COLUMN geom(POINT,4326);

UPDATE "erpAssets" SET
  geom = ST_GeomFromText('SRID=4326;POINT' ||
              replace(substr(region, 2, length(region) - 2), ',', ' '));

Then update your Mapnik query to something simpler, like:
SELECT geom
FROM "erpAssets"
WHERE parent=326815;

(Note: use the SRID that applies to your question. I'm only guessing 4326)


text:
Q: How do I use a different query for a facet count Given a search for q=*:*&facet=true&facet.field=category solr returns something like:
jackets (10)
shirts (5)

If I change the query to q=name:shirt&facet=true&facet.field=category then I get
jackets (0)
shirts (5)

I want to use a different query to generate the facets so it will count all facets not just those matching the query i.e. for a search of "q=name:shirt" it should return
jackets (10)
shirts (5)

I tried adding a facet.query parameter but it seems to have no effect. facet.query=*:* still returns
jackets (0)
shirts (5)

if I use a query of q=name:shirt
How do I use a different query to generate the facets? I'm using solr 5.5.0

A: So it seems facet.query is a facet query within the query search results. The solution is to use tags and exclusions e.g.
q={!tag=name}name&facet=true&facet.field={!ex=name}category

So for each query that I want to exclude I tag it and then reference it in the ex section of the facet.field
Although I'm starting to think that it may be better to use two queries and simply cache the facet results on the app server ...


text:
Q: Get Toolbar's navigation icon view reference I would like to highlight drawer icon in my Toolbar (working on a tutorial). For that, I need its position. How do I get a reference to drawer's navigation icon (hamburger) view?

A: After looking into Toolbar's child views in debug mode, I saw that drawer icon can be found there, as an ImageButton. (Thanks Elltz)
I use a Toolbar with custom xml layout with 2 children (LinearLayout and ImageView), so my Toolbar had 4 children in the end, with these positions:
[0] LinearLayout(from custom xml)
[1] ImageView(from custom xml)
[2] ImageButton(drawer icon)
[3] ActionMenuView(menu icon)

Knowing this, I can now use:
View drawerIcon = toolbar.getChildAt(2);

to get a reference to drawer menu icon. In my case, the position is 2. This position should be equal to the number of child view's in your custom toolbar layout.
If someone finds better solution please let me know.

A: If you just want to get the Drawable representing the toolbar navigation icon, you can do this:
Drawable d = mToolbar.getNavigationIcon();

You can get a reference to the ImageButton used for the toolbar's navigation icon by having a method as this:
public ImageButton getToolbarNavigationButton() {
    int size = mToolbar.getChildCount();
    for (int i = 0; i < size; i++) {
        View child = mToolbar.getChildAt(i);
        if (child instanceof ImageButton) {
            ImageButton btn = (ImageButton) child;
            if (btn.getDrawable() == mToolbar.getNavigationIcon()) {
                return btn;
            }
        }
    }
    return null;
}

A: You can make use of content description of the view and then use findViewWithText() method to get view reference
 public static View getToolbarNavigationIcon(Toolbar toolbar){
        //check if contentDescription previously was set
        boolean hadContentDescription = !TextUtils.isEmpty(toolbar.getNavigationContentDescription());
        String contentDescription = hadContentDescription ? toolbar.getNavigationContentDescription() : "navigationIcon";
        toolbar.setNavigationContentDescription(contentDescription);
        ArrayList<View> potentialViews = new ArrayList<View>();
        //find the view based on it's content description, set programatically or with android:contentDescription
        toolbar.findViewsWithText(potentialViews,contentDescription, View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION);
        //Nav icon is always instantiated at this point because calling setNavigationContentDescription ensures its existence
        View navIcon = null;
        if(potentialViews.size() > 0){
            navIcon = potentialViews.get(0); //navigation icon is ImageButton
        }
         //Clear content description if not previously present
        if(!hadContentDescription)
            toolbar.setNavigationContentDescription(null);
        return navIcon;
     }

More
Kotlin extension property:
val Toolbar.navigationIconView: View?
        get() {
            //check if contentDescription previously was set
            val hadContentDescription = !TextUtils.isEmpty(navigationContentDescription)
            val contentDescription = if (hadContentDescription) navigationContentDescription else "navigationIcon"
            navigationContentDescription = contentDescription
            val potentialViews = arrayListOf<View>()
            //find the view based on it's content description, set programatically or with android:contentDescription
            findViewsWithText(potentialViews, contentDescription, View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION)
            //Clear content description if not previously present
            if (!hadContentDescription) {
                navigationContentDescription = null
            }
            //Nav icon is always instantiated at this point because calling setNavigationContentDescription ensures its existence
            return potentialViews.firstOrNull()
        }

A: Improvised @Nikola Despotoski's answer
public static View getNavigationIconView(Toolbar toolbar) {

    String previousContentDescription = (String) toolbar.getNavigationContentDescription();
    // Check if contentDescription previously was set
    boolean hadContentDescription = !TextUtils.isEmpty(previousContentDescription);
    String contentDescription = hadContentDescription ?
            previousContentDescription : "navigationIcon";
    toolbar.setNavigationContentDescription(contentDescription);

    ArrayList<View> potentialViews = new ArrayList<>();
    // Find the view based on it's content description, set programmatically or with
    // android:contentDescription
    toolbar.findViewsWithText(potentialViews, contentDescription,
            View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION);

    // Nav icon is always instantiated at this point because calling
    // setNavigationContentDescription ensures its existence
    View navIcon = null;
    if (potentialViews.size() > 0) {
        navIcon = potentialViews.get(0); //navigation icon is ImageButton
    }

    // Clear content description if not previously present
    if (!hadContentDescription)
        toolbar.setNavigationContentDescription(previousContentDescription);

    return navIcon;
}


text:
Q: Explain the mutual exclusion?
Aren't $A$ and $B$ Mutually exclusive? SO why isn't the answer just
$P(A \cup B) = P(A) + P(B)$

A: Sample space
 11  12  13  14  15  16
 21  22  23  24  25  26
 31  32  33  34  35  36
 41  42  43  44  45  46
 51  52  53  54  55  56
 61  62  63  64  65  66

Event $A$ consists of the 6 points in the last row.
Event $B$ consists of the 6 points in the last column.
Event $A\cap B$ consists of the single point 66; this is an event 'in common'.
So $A$ and $B$ are not mutually exclusive (disjoint).
However, $A$ and $B$ are independent because $P(A\cap B) = P(A)P(B).$
If I am told that a 6 occurred on the first roll, that tells me nothing
about my chances of getting a 6 again on the second roll.
As you begin to study probability, it is important that you not confuse
the concepts of disjointness and independence.

*

*Disjointness is a
logical concept. In a draw from a deck of cards, I can tell you that
Hearts and Spades are disjoint without knowing anything about whether
the draw is 'fair'.

*But I can't begin to discuss whether two events
are independent, unless I know about the probability structure.
If I know that I'm drawing 'at random' from a full standard deck of 52 cards,
then I know that Ace and Heart are independent events.


text:
Q: Overlay Panel shows arrow on the wrong position (primeng) I have a p-table and I am using a p-overlaypanel to filter. The problem is that the overlaypanel shows the arrow wrong.The arrow appears on the right and I want it to appear on the left. See the image
Click to see the image
In this image, the overlaypanel must be associated with the row called username.
This is my code HTML of span
   <span class="filter-button" *ngIf="col.filter">
              <p-button id={{col.field}} styleClass="no-bg-button" icon="fas fa-filter"
                [style]="{'padding':0, 'width': '20px', 'height': '20px'}" (click)="filter($event, col.field)">
              </p-button>
   </span>

And this is the code of overlay:
 <p-overlayPanel #filterOverlay id="overlay">
  <input [(ngModel)]="filterInput" pInputText type="text"
    (input)="incTable.filter($event.target.value, filterField, 'contains')" placeholder=""/>
 </p-overlayPanel>

And this is my code in javascript:
filter(event: Event, field: string) {
  event.preventDefault();
  event.stopPropagation();

  this._incTable.reset();
  this.filterField = field;
  this.filterInput = '';
  this.filterOverlay.toggle(event);
}

When I click in the span, the overlaypanel appears. The solution of setting a width to the table or changing the css doesn't work for me. Any solution?

*

*Version Angular: 8.2.14

*Version PrimeNG: 8.1.1

A: Kumbirai Bodzo's answer, with the double-quotation marks around the value, didn't work for me. I found that you don't need those at all. Just do:
appendTo='body'

A: Try
[appendTo]="'body'"


text:
Q: Should I list the sitemap index files of all the subdomains in the root domain? I have a root domain website www.example.com and multiple subdomains - sub1.example.com, sub2.example.com, sub3.example.com.
All these subdomains have sitemap index file of their own, sub1.example.com/sitemap_index.xml, sub2.example.com/sitemap_index.xml, etc.. and it is being indexed properly.
Is it required for me to list all the sitemap index files in robots.txt of the root domain (www.example.com/robots.txt)? Or is it not mandatory?
Please explain how sitemap listing works across subdomains. Thank you.

A: I'm wondering the same thing too. According to Sitemap.org
"Note: A Sitemap index file can only specify Sitemaps that are found on the same site as the Sitemap index file.
For example:
http://www.yoursite.com/sitemap_index.xml can include Sitemaps on http://www.yoursite.com but not on http://www.example.com or http://yourhost.yoursite.com. As with Sitemaps, your Sitemap index file must be UTF-8 encoded."


text:
Q: Getting the value textfield from Form based UITableView I got UITableView with one custom cell which will show the question data from server response json,So,I got 1 UILabel,3 UIButtons (Which will be radio button) and 1 UITextField which I declare like that.

The below textfield at each table cell is remark and the radio button (Yes,No,N/A) are just UIButtons.
These are survey questions as you can see,set that at UITableView.
If there are 21 Questions response from server,I will show 21 rows which show question title,selection buttons,and remark on each tablecell.
So,What is my problem,I really don't know how to get the data from each table cell when user click submit button.
When i submit,i want to get the data like that :
[[String:String],[String:String],...]
Example : Assume I do survey on 1st and 2nd table cell,I want to get the data like that.You will see the 3rd one is empty data if the user didn't fill.
[
     ["QuestionID": 1,"Type":"Yes","Remark":"Nothing special everything good"],
     ["QuestionID": 2,"Type":"No","Remark":"Yeah,it will be alot helpful"],
     ["QuestionID": 3,"Type":"","Remark":""]
]

Any Help?Please?How to get the data and save like that even the user didnt fill when we submit the survey.

A: You can identify the particular UITextField or UIButton by getting the NSIndexPath. You just need to addTarget and get the current NSIndexPath and from there you can get the current clicked UITableViewCell.
First addTarget to the UITextField in cellForRowAtIndexPath:
cell.textFieldSearch.addTarget(self, action: "textChange:", forControlEvents: UIControlEvents.EditingChanged)

Then you can handle the click event in the below function:
func textChange(textField: UITextField){

    var cellIndexPath = tableViewSearch.indexPathForCell(textField.superview!.superview! as! UITableViewCell)!
    let cell = tableViewSearch.cellForRowAtIndexPath(cellIndexPath!) as! SearchRatingCell
    cell.textFieldSearch.text = textField.text!
}

Update (UIButton):

cell.yesButton.addTarget(self, action: "searchByRating:", forControlEvents: UIControlEvents.TouchUpInside)

Custom Method:
func searchByRating(sender: UIButton){

    let cellIndexPath = tableViewSearch.indexPathForCell(sender.superview!.superview! as! SearchRatingCell)!
    let cell = tableViewSearch.cellForRowAtIndexPath(cellIndexPath!) as! SearchRatingCell
    cell.yesButton.selected = true
}

Let me know, if you have any confusion.


text:
Q: Can one open multiple CMD shortcuts that open in different paths? Is it possible to have multiple CMD shortcuts, in the desktop for example, that open CMD in a specific directory?
For example, my work directories:
W:\PRJ_1\\...
W:\PRJ_2\\...

So I would have two shortcuts on my desktop:
"PRJ_1" that opens CMD in "W:\PRJ_1>"
"PRJ_2" that opens CMD in "W:\PRJ_2>"

A: Yes, make sure the shortcut's target is set to something like:
C:\Windows\System32\cmd.exe /k pushd W:\PRJ_1
or
C:\Windows\System32\cmd.exe /k cd /D W:\PRJ_1
The first option, with pushd will also work for UNC paths, e.g. \\servername\path, in which case a drive letter will be created automatically.

A: You may set the "Start in" field of the desktop shortcut:


text:
Q: Minimal Example: Opening a window in electron from react application? Say I am building a desktop application with react/redux & electron. So my index.html file in electron looks like this:
<!DOCTYPE html>

 ...

My biggest React container (call it app.js) is loaded into the 'id=content' div. This works fine so far, but now I am wondering how to open a new file dialog window (or any new window for that matter) when the user clicks a button in my react application.
I found some examples here & here, but both examples only explain how to load the file dialog window from the main electron processes (in renderer or main).
However, I want the user to engage with my React Application and then, once he or she clicks a button, my app should then tell electron to spawn a new window, and this new window should, of course, somehow be part of my react application.
I would really appreciate it if someone could provide a minimal example here, on how these to things work together.

A: To open a react component in a new window on button click and detect when the window is closed because the component will not simply call componentWillUnmount when you close the window Your app should look like this
App.js
export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      // To keep track of the new window if opened or closed
      isNewWindow: false,
    };
  }

  render() {
    return(
    // onClose will be fired when the new window is closed
    // everything inside NewWindowComponent is considered props.children and will be
    // displayed in a new window
    {(this.state.isNewWindow) &&
    <NewWindowComponent
      onClose={() => this.setState({ isNewWindow: false })>

This will display in a new window

    </NewWindowComponent> }

    <button
      onClick={() => this.setState({ isNewWindow: true })}>
      Open in new window</button>
    )
  }
}

NewWindowComponent.js
export default class NewWindowComponent extends Component {
  // Create a container
 for the window
  private containerEl = document.createElement('div');

  // This will keep a reference of the window
  private externalWindow = null;

  // When the component mounts, Open a new window
  componentDidMount() {
    // The second argument in window.open is optional and can be set to whichever
    // value you want. You will notice the use of this value when we modify the main
    // electron.js file
    this.externalWindow = window.open('', 'NewWindowComponent ');

    // Append the container div and register the event that will get fired when the
    // window is closed
    if (this.externalWindow)
    {
      this.externalWindow.document.body.appendChild(this.containerEl);
      this.externalWindow.onunload = () => this.props.onClose();
    }
  }

  render() {
    return ReactDOM.createPortal(this.props.children, this.containerEl);
  }
}

electron-main.js or however your main electron file is named
...
function createWindow() {
  mainWindow = new BrowserWindow({
    ...
    // You need to activate `nativeWindowOpen`
    webPreferences: { nativeWindowOpen: true },
  });
  ...
  mainWindow.webContents.on('new-window',
    (event, url, frameName, disposition, options, additionalFeatures) =>
    {
      // This is the name we chose for our window. You can have multiple names for
      // multiple windows and each have their options
      if (frameName === 'NewWindowComponent ') {
        event.preventDefault();
        Object.assign(options, {
          // This will prevent interactions with the mainWindow
          parent: mainWindow,
          width: 300,
          height: 300,
          // You can also set `left` and `top` positions
        });
        event.newGuest = new BrowserWindow(options);
    }
  });
  ...
}
...

A: The "createPortal" api in react 16 will help you.
First let's say we have a component like this:
<SubWindow>

bar

</SubWindow>

Then open(or close) a window in its lifecycle methods like this:
export class SubWindow extends React.Component {
  nativeWindowObject: null;

  componentWillMount() {
    this.nativeWindowObject = window.open('');
  }
  render() {
    return this.nativeWindowObject ? ReactDOM.createPortal(this.props.children, this.nativeWindowObject.document.body) : null;
  }
}

Notice: You MUST set webPreferences:{nativeWindowOpen: true} in your main window to make sure "window.open" returns a native Window object. Visit https://electronjs.org/docs/api/window-open for more infomation.

A: On clicking the button handleNewWindow is called. Make the nodeIntegration to true or preload js.
const handleNewWindow =()=> {
    const remote=require('electron').remote;
    const BrowserWindow=remote.BrowserWindow;
    const win = new BrowserWindow({
      height: 600,
      width: 800,
      frame:false,
      webPreferences: {
        nodeIntegration: true,
    }
    });
    win.loadURL(`file://${__dirname}/app.html#/login`);

  }

And on the router file
<Route path="/login" component={Login} />

By using this code we can open the reactjs file and route to login. The app.html is main file which is loaded in main.dev.js in electron-react-boilerplate code. The hashing is simplest method to open the reactjs file.
   As the loadURL in electron only loads urls and htmls files we can't open js files.


text:
Q: Inheriting from MyClass : UIViewController causes error 'Cannot find interface declaration' I've got a UIViewController named StreamController. It has a XIB with a UITableViewController in it.
I want to build another slightly different view of this StreamController but use the same code that the original provides, so I've created another controller called Stream2Controller. Stream2Controller inherits from StreamController and has it's own XIB file.
My intent is to have the referencing outlets from the Stream2Controller XIB file point to the StreamController.h file. I'm pretty sure I've been successful at this in the past, but for some reason I'm getting this error:
Cannot find interface declaration for StreamViewController, superclass of Stream2Controller; did you mean SomeOtherController?
This error is happening in Stream2Controller.h
UPDATE: Here's some source
`StreamController.h'
@interface StreamViewController : UIViewController

`Stream2Controller.h'
#import "StreamViewController.h"

@interface Stream2Controller : StreamViewController

Suggestions?

A: Looks like I had a recursive include elsewhere in my project that caused this error.
Not a very intuitive error message though. :)


text:
Q: How do I check if a textinput in a form includes just a number and a certain prefix? I want my form to only accept inputs like:
BS-142
bs-213421
Bs-111111
meaning just this prefix and a number or just the number
This is what my current try looks like:
function validateForm(){
    var tag = document.forms["add"]["tag"].value;
    if (isNaN(tag) || tag != "BS-") {
        alert('FALSCHE FORMATIERUNG!'); window.location='index.php';
        return false;

    } else {
        return true;
    }
}

A: You could either use the pattern attribute of your input element (reference: https://www.w3schools.com/tags/att_input_pattern.asp) or check the String using JavaScript's String.match() method (reference: https://www.w3schools.com/jsref/jsref_match.asp).
Although I highly recommend also checking on your server-side as client-side validation is not very secure.


text:
Q: Entity Framework code first create a superclass in two existing classes, This is my first time here so sorry if I did not put the doubt by default. In my project I have two models class doubts and a class of works, I want to create a classification for both using a superclass, like the design pattern strategy. But I have a problem, the project state is advanced and I have used the doubt and works classes many times. Already tried in many ways, but either the error in the update-database or the error in what I had done before.
Does anyone know one way that I can implement a generic class classification for the doubts and works classes without many changes of what I had already done?
My code is below
public abstract class Classificable
{

    [Key]
    public int id { get; set; }
    public virtual Classification classication { get; set; }
}

public class Doubt : Classificable
{

    public int doubtID { get; set; }
    public string question { get; set; }
    public string content { get; set; }

    public virtual Student student { get; set; }
    public virtual Course course { get; set; }
    public virtual Work work { get; set; }
    public virtual ICollection<Answer> answers { get; set; }
}

public class Work : Classificable
{

    public int workID { get; set; }
    public string name { get; set; }
    public string nameWork { get; set; }
    public string filePath { get; set; }

    public virtual Student student { get; set; }
    public virtual Course course { get; set; }
    public virtual ICollection<Doubt> doubts { get; set; }
}

public class DB_DIS : DbContext
{

    public DB_DIS()
        : base("name=DB_DIS")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Doubt>().ToTable("Doubts");
        modelBuilder.Entity<Work>().ToTable("Works");

    }

    public virtual DbSet<Doubt> Doubts { get; set; }
    public virtual DbSet<Work> Works { get; set; }
}`

A: What is the property or method in Classificable that you are trying to apply to Doubt and Work?
Have you written your data structure in such a way that is contains an id field AND workID feild?
In my experience, if you are trying to share properties between EF Classes you are better off sharing common fields.  I've used it in the past for base classes of AuditableBase as follows:
public class AuditableBase
{
    public string UpdateUserId { get; set; }
    public DateTime UpdateDate { get; set; }
}

Then all my classes that I want to "Audit" will have a UpdateUserId and UpdateDate, and I can do some pre-save processing to set those based on the type of AuditableBase.


text:
Q: Ctrl + Z not working to exit while loop I've been looking around and trying a whole a bunch ways, but cannot for the life of me get Ctrl z to exit the console. Here is my code, can some one point me in the right direction:
This is on Windows.
int main()
{
    string s;
    Stack *stack = new Stack();
    while (cin >> s)
    {
        if (cin)
        {
            for (int i = 0; i < (int)s.length(); i++)
            {
                stack->push(s[i]);
            }
            for (int i = 0; i < s.length(); i++)
            {
                cout << stack->top();;
                stack->pop();
            }

            cout << endl;
        }
    }
    stack->~Stack();
    delete stack;
    return 0;
}

A: On Windows, press Ctrl-Z to signal EOF. On Linux, it's Ctrl-D. On either system you need to press it at the beginning of the line (i.e., after hitting enter).
By the way, there's no need to call destructors explicitly. Get rid of this line:
stack->~Stack();
In fact, it'd be better if you got rid of the new and delete altogether. Those smell like Java-isms. In C++ you don't have to always use new to create new objects. The more basic syntax is to write:
Stack stack;

That will create a Stack object and call the default no-arg constructor. The object will be automatically destructed when main() exits, so you don't need a delete or an explicit destructor invocation.
Finally, the if (cin) check is redundant. The while loop already checks that a string was read.
while (cin >> s)
{
    if (cin)
    {
        ...
    }
}

A: Since you are using built-in stack so you don't need to use .-> and there is no need of if(cin) either as  while (cin >> s) is check is exertion stream has reached the end or not.Here is the correct code.
#include <string>
#include <stack>
#include <iostream>
#include <fstream>

using namespace std;
int main()
{
     string s;
     stack <string> st;

     while (cin >> s)
     {
            st.push(s);
            cout << st.top();;

            st.pop();
            cout << endl;

      }

     st.~stack();

     return 0;

}


text:
Q: ASP.NET Core MVC : page does not render the hrefs I am experiencing a problem with a page in my ASP.NET Core 3.1 web app. Please see the screenshot attached for the page structure in the folder.
When I first land on the dashboard page, the hrefs are generated. The minute I click on either the "Patients" or the "Add a new patients" page, the rest of the hrefs aren't generated, but this doesn't happen when I click on "Create New Admin" and "Change Email" links.
I would appreciate that if you could help me out with this problem. many thanks.
 Dashboard
 Create New Admin
 Change Email
 Patients
 Add a new patients

A: You can use Anchor Tag Helper attributes, like this:
Controller:
 public IActionResult Test()
        {
            return View();
        }

        public IActionResult Test1()
        {
            return View("~/Views/Test/patients.cshtml");
        }

View:
Add a new patients

Result:

For more related usage, please refer to this document:
https://learn.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/built-in/anchor-tag-helper?view=aspnetcore-6.0

A: If you're using the Razor Pages functionality (which I think you are based on the screenshots), you need to generate the URLs by using the UrlHelper.
Try the following:
 Patients

https://learn.microsoft.com/en-us/aspnet/core/razor-pages/?view=aspnetcore-6.0&tabs=visual-studio


text:
Q: (response.ok === false) { setError('show') I get a 400 bad request when typing less than 5 characters in a textarea. And I am trying to show an error message to the user when he/she inputs a text message that is too short. But the message won't show up.

    const handleFormSubmit = (e) => {
    e.preventDefault()

    const options = {
        method: 'POST',
        headers: {
          'Content-type': 'application/json'
        },
        body: JSON.stringify({ message: newThought })
      }

    fetch(HAPPY_THOUGHTS_URL, options)
      .then(response => response.json())
      .then((response => {
        if (response.ok === false) {
          setError('show')
        } else {
          fetchThoughtsList()
        }
      }))
      .catch(error => console.error(error))
  }

......

  return (
   <div>
     {error === 'show' &&
        <ErrorPopup
          message="Oops, your message needs to be more than 4 characters. Please give it one more try!"
          setError={setError}
        />
      }
    </div>
  )

A: There is an issue with the order of events, in your first then you can read ok field, but in the second one, there is just data you get from calling json. Try something like this instead
 fetch(HAPPY_THOUGHTS_URL, options)
.then(response => {
    if (!response.ok) {
      setError('show');
      return null;
    }
    return response.json();
   })
  .then(response => {
    if (response) {
      fetchThoughtsList()
    }
  })
  .catch(error => console.error(error))

I assume you just didn't include the part where you're processing response data, but if you really don't do anything with it, you don't need response.json() and the second then:
 fetch(HAPPY_THOUGHTS_URL, options)
 .then(response => {
    if (response.ok) {
      fetchThoughtsList()
    }
    else{
      setError('show');
    }
  })
  .catch(error => console.error(error))

try inserting .then(response => {console.log('actual ok value',response.ok); return response} as the first then and see what it prints, maybe the response is indeed ok

A: fetch(API_URL, options)
    .then(response => {
      if (!response.ok) {
        setError(true)
        throw new Error ('Ups, something went wrong')
      } else {
        setNewThought('')
        return response.json()
      }
    })
    .then(recievedThought => setThoughtsList([recievedThought, ...thoughtsList]))
    .catch(err => console.error(err))
  }


text:
Q: $\mathbb{P}[A]\cdot\mathbb{E}[X|A] = \mathbb{E}\big[X\cdot\mathbf{1}[A]\big]$? Let $A$ denote an event and $X$ denote a random variable. Is it true that
$$\mathbb{P}[A]\cdot\mathbb{E}[X|A] = \mathbb{E}\big[X\cdot\mathbf{1}[A]\big],$$
where $\mathbf{1}[A]$ is an indicator function that event $A$ happens? We assume $\mathbb{P}[A] > 0$.


text:
Q: Drupal 7 Commerce keeps giving "PDOException: SQLSTATE[42S02]" errors The actual error is

PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'dbaname.cache_views' doesn't exist: TRUNCATE {cache_views} ; Array ( ) in cache_clear_all() (line 165 of C:\Me\dev\xampp\htdocs\dbname\includes\cache.inc).

I got this error earlier on an recently installed drupal commerce site, after trying some fixes I gave up and reinstalled it. So now on a fresh install of Drupal Commerce KickStarter without the sample store this error keeps getting thrown.
I had this problem with cache_views, cache_views_data and another.
I found some fixes on the web to do with Dropping the table and then creating it again. There is a weird side to this, if you try to create the table directly it can't as its already there, but you can't see it!
Anyway weird drop/create thing aside, anyone know the source of this issue?
running  PHP v.5.6.11
Drupal Commerce Kickstarter 7.x-2.11
cheers
EDIT:
Appreciate the answers that came in already, but i'm thinking its more a XAMPP issue. The XAMPP PHP log file was throwing [warnings] regarding InnoDB (sorry deleted the file already), which appears related to the issue above. I've now reinstalled XAMPP and the InnoDB warnings have cleaned up. going to try a fresh commerceKickstart now and see where its at. cheers

A: This problem can occur because of an older Drupal version. Download the latest Drupal 7 version and install it and try it again.

A: Basically, such as cache_views and cache_views_data, etc., used for cache bin in Drupal. so  please try to reinstall views module correctly, this issue would be fixed.


text:
Q: Java setReadTimeout() does not work how and where would implement bellow a setReadTimeout or a setConnectTimeout?
My tests bellow always throw me error its undefined before compiling
When there is no connection it blocks at in.readLine() and the app waits forever
try {
    URL url = new URL("http://mydomain/myfile.php");

    //url.setReadTimeout(5000); does not work

    InputStreamReader testi= new InputStreamReader(url.openStream());
    BufferedReader in = new BufferedReader(testi);

        //in.setReadTimeout(5000); does not work

    stri = in.readLine();
    Log.v ("GotThat: ",stri);
    in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}

thanks for your help
chris

A: Use the URLConnection.
 URL url = new URL("http://mydomain/myfile.php");
 URLConnection connection = url.openConnection()
 int timeoutMs = 2000;
 connection.setReadTimeout(timeoutMs );

 InputStream urlInputStream = connection.getInputStream();
 BufferedReader in = new BufferedReader(new InputStreamReader(urlInputStream));

 String firstLine = in.readLine();
 System.out.println("GotThat: " + firstLine);
 in.close();

This works for me.
Because of your comment christian Muller I tried it with several websites and adjusted the timeoutMs value. Set timeoutMs to 250 ms should cause a SocketTimeoutException. If you then increase it step by step you will see that finally you read a line.
For example if I try:
URL url = new URL("http://msdn.microsoft.com/en-US/");
URLConnection connection = url.openConnection();
int timeoutMs = 250;
connection.setReadTimeout(timeoutMs);

I get
Exception in thread "main" java.net.SocketTimeoutException: Read timed out
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.read(SocketInputStream.java:129)
    at java.io.BufferedInputStream.fill(BufferedInputStream.java:218)
    at java.io.BufferedInputStream.read1(BufferedInputStream.java:258)
    at java.io.BufferedInputStream.read(BufferedInputStream.java:317)
    at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:695)
    at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:640)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1195)
    at test.Main.main(Main.java:25)

If I try the same with 550 timeoutMs it works:
 GotThat: <!DOCTYPE html>


text:
Q: What does it mean to write an integral in its explicit form? The first part of Fundamental Theorem of Calculus gives an abstract way of producing antiderivatives:
Write $F(x) = \int^x_1 (t + 1)dt$ in an explicit form. Check that its derivative is indeed $x + 1$.
What does it mean to find an integral in it explicit form? Does it mean to find its anti derivative?

A: Here you have a "definite integral" with a variable in one of the limits, so you need to find the antiderivative and actually substitute the limits into it. The general antiderivative is $F(t)=t^2/2+t+C$ so when you substitute the limits you get $x^2/2+x-3/2$.
Edit: Since the general antiderivative is $F(t)=t^2/2+t+C$, you find your integral by substituting in the limits. That is,
$$\int_1^x (t+1)dt = F(x)-F(1)=x^2/2+x+C-(3/2+C)=x^2/2+x-3/2.$$
This is not really any different than you would do if the upper limit were $2$ or $4/3$, except that the result depends on the variable $x$.


text:
Q: Defining SqlCommand.CommandTimeout from the config file I need to set CommandTimeout property for a particular SqlCommand. The premise is that, the main connection string and SqlConnection being used cannot be changed. I like to make defining the timeout value configurable. Wanted to know if its good and fair practice to define it in the app.config (it's a desktop app)?

A: The app.config is a fantastic place for that type of setting. Maybe something like this:
<appSettings>
  <add key="commandTimeout" value="2" />
</appSettings>

and that would then be in some perspective duration based on how you leverage it. Maybe something like this:
var timeout = cnn.ConnectionTimeout;
var configTimeout = ConfigurationManager.AppSettings["commandTimeout"];
if (!string.IsNullOrEmpty(configTimeout))
{
    timeout = Convert.ToInt32(configTimeout);
}

That could of course exist in a static class, like this maybe:
public static class AppSettings
{
    private static int _commandTimeout = -1;
    public static int CommandTimeout
    {
        get
        {
            if (_commandTimeout != -1) { return _commandTimeout; }

            var configTimeout = ConfigurationManager.AppSettings["commandTimeout"];
            if (!string.IsNullOrEmpty(configTimeout))
            {
                _commandTimeout = Convert.ToInt32(configTimeout);
            }
            else
            {
                _commandTimeout = 1; // this is the default if the setting doesn't exist
            }

            return _commandTimeout;
        }
    }
}

Then all you'd have to do is:
var timeout = AppSettings.CommandTimeout;

or even more concisely:
cmd.CommandTimeout = AppSettings.CommandTimeout;

A: You can use the CommandTimeout property and a Time Paramater in the application config file.
connection = Factory.CreateConnection();
connection.ConnectionString = ConnectionString.ConnectionString;
connection.Open();

this.cmd = connection.CreateCommand();
cmd.CommandTimeout = ConfigurationManager.AppSettings["TimeConfigParam"];

A: I would extend @mike-perrenoud's answer with using TimeSpan as type for the AppConfig option value. It is more readable and understandable for further adjustments.
The option could be added via Project Properties -> Settings tab. So that the code would like
SqlCommand command = connection.CreateCommand();
command.CommandTimeout = (int)Properties.Settings.Default.SqlCommandTimeout.TotalSeconds;

app.config
<setting name="SqlCommandTimeout" serializeAs="String">
  <value>00:05:00</value>
</setting>

Properties/Settings.settings
// generated by VS
<Setting Name="SqlCommandTimeout" Type="System.TimeSpan" Scope="Application">
  <Value Profile="(Default)">00:05:00</Value>
</Setting>

Properties/Settings.Designer.cs
// generated by VS
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("00:05:00")]
public global::System.TimeSpan SqlCommandTimeout {
  get {
    return ((global::System.TimeSpan)(this["SqlCommandTimeout"]));
  }
 }


text:
Q: Server-Side Code to Execute Based on a Time Range We have a Try/Catch block of code in our web application to trap a certain exception.  What we want to do with this exception depends on the current time.  If it is between 4:30PM and 3:00AM we will want to send an email, otherwise we will throw the exception.  What is the best way to accomplish this?
Try
    'Yada
Catch ex as WebException
    Dim Time As DateTime = DateTime.Now

    'Not sure where to go from here!
End Try

A: Since it is between those times every day the easiest thing would be to check to see if now is before 3:00 AM on the current day, or if now is after 4:30 PM on the current day. That would then cover both the 4:30 PM to 12 midnight and midnight to 3 am time spans.
Edited by Josh Stodola to add code:
  Dim Time As DateTime = DateTime.Now
  Dim Low As New Date(Time.Year, Time.Month, Time.Day, 16, 30, 0)
  Dim High As New Date(Time.Year, Time.Month, Time.Day, 3, 0, 0)

  If Time > Low OrElse Time < High Then
      'Send Email
  Else
      Throw Ex
  End If