text:
Q: vim shortcut to open a file with current directory populated I'm trying to add a key mapping so that it opens up command and populate it with :e /path/to/current/file
I can get the current directory using :pwd but I'm having a trouble to use it in the mapping
I think it will be along the lines of setting pwd to a variable and use that variable as such:
noremap <C-q> <C-o>:e *pwdvariable*<Space>

Should I create a function to perform this?

A: %:p:h will get the full path of the current file (without trailing slash). Read more in :help filename-modifiers.

A: I guess you need
nnoremap <C-q> <C-\><C-n>:e <C-r>=fnameescape(expand('%:p:h'))<CR>

A: Not exactly, what you have asked for, but maybe more helpful:  Vim tip 64: Set working directory to the current file: In short, add the following line to .vimrc:
 autocmd BufEnter * silent! lcd %:p:h

Interesting for you would be also Easy edit of files in the same directory.


text:
Q: Connect WSL2 SQL Server localhost instance from Windows 10 I had setup a WSL2 Ubuntu. Now I am running a local SQL Server instance on the 1401 port using Docker.
Container port:

0.0.0.0:1401->1433/tcp

I would like to connect this instance from SSMS but I am getting following error:
Server name: localhost, 1401
Error:

Cannot connect to localhost,1401.
A network-related or instance-specific error occurred while
establishing a connection to SQL Server.
The server was not found or was not accessible. Verify that the
instance name is correct and that SQL Server is configured to allow
remote connections.
(provider: TCP Provider, error: 0 - The wait operation timed out.)
(Microsoft SQL Server, Error: 258)

[Solution]
I am able to connect it via the WSL2 IP. I run "hostname -I" command in WSL2 and use the same IP in SSMS. And, I am able to make a connection

A: First question -- Is there a VPN running/connected in Windows?  If so, ignore the rest of this and suspect that first.  Make sure the VPN is not running, stop Docker, issue a wsl --shutdown, restart and try again.
Assuming that's not the problem ...
Normally, WSL2 provides a feature known as "localhost forwarding" which allows services/apps on Windows to communicate with the virtualized WSL2 IP using localhost.  It essentially takes any localhost traffic that isn't directed to a port bound under Windows and forwards it to the Hyper-V virtual network for WSL2.
All WSL2 instances (including the Docker instance) share the same WSL2 network interface as they are all running in the same virtual machine/kernel.
So you seem to be doing the right thing in attempting to connect to localhost from SSMS.
But ... sometimes that localhost forwarding breaks.  There are two common (related) scenarios that can cause this (and perhaps others):

*

*Hibernation of the Windows host

*Having Windows Fast Startup enabled in Power Manager

First check to make sure you can access 1401 from within WSL2:
nc -zv localhost 1401

^^^ assumes netcat is installed, which it is by default in the WSL2 Ubuntu distribution.  For other distributions, install it or check connectivity via other methods.
If that doesn't succeed, then I'd suspect some configuration issue in SQL Server.
If that does succeed, then run the same test from the Windows host in PowerShell:
Test-NetConnection -ComputerName "localhost" -Port 1401

If that doesn't succeed, then I'd suspect a localhost forwarding issue.
Side note: I'm assuming you are running Docker Desktop, but if you are just running Docker Engine in a WSL2 instance, that's no problem.  Just ignore the Docker Desktop instructions below.

*

*First, check if you have a /etc/wsl.conf in any of your running WSL2 instances that mention disabling localhostForwarding.  I'm assuming no, since that is not the default.  However, if you happen to, make sure you set these to true.

*Stop all WSL2 services, instances, shells, apps, etc. (including Docker Desktop)

*From PowerShell:
wsl --shutdown

*Then restart Docker Desktop and/or your container and try again

A: If localhost doesn't work, try use [::1] in the server name. In WSL2, port 1433 is using IP/TCPv6, SSMS some times is not able to resolve localhost to loopback IP [::1].
Source: https://jayfuconsulting.wordpress.com/2020/11/14/sql-server-2019-docker-wsl-2/

A: One last thing which you could try is to modify the windows host file. I almost tried all the steps mentioned over different link, but all goes in vain. Then I opened the host file which could be accessed using
C:\Windows\System32\Drivers\Etc
Open the host file and uncomment(remove # sign) from  the localhost name resolution section

redpajama_set_name: RedPajamaStackExchange


text:
Q: Accessing Linux host from Windows machine How to access a web application hosted in Linux machine using host name from Windows 7 client machine instead accessing through IP address?
I just added the Linux machine in to the LAN. So the application is accessible as http://<IPADDRESS OF Linux Machine>:8080/webapp/index.html.
However, I want to access by hostname like http://<hostname>:8080 instead of http://<IPADDRESS>:8080. Added the host name of linux machine into
the DNS server but that didn't help.
Note: The Linux machine (Redhat 5.3) is running under the DNS server (Windows server 2008).

A: I think there are 2 ways to solve this issue:

*

*If this machine will be definitive, you want to add the hostname in your DNS server.

*If this machine will be used to test, or temporary activity, you can add de hostname in the windows hosts file, using this manual.

Just add in the end of file the line like this:
e.g.:
192.168.1.10 srv01.local.br srv01


text:
Q: 2-dimensional bin-packing in Excel I'm trying to find a solution for the 2-dimensional packing problem using Excel (Formulas, Solver, VBA).
But apart from finding said solution, I would like to bring back this topic as base for discussion, because I realized during my extended web-searches that this problem (or variations of it) creates headaches for many people – novice and professional users.

The explanation for my problem:
I am trying to fit rectangular packages in rectangular containers. Usually there is one larger box and 2-5 smaller boxes to ship.
On average, there is still capacity of 30-50% left in the containers, so I want to calculate how many additional standardized boxes would fit in this free space to fill up the container.

*

*There are no constraints, as long as the boxes fit into the container.

*Height and weight are irrelevant.

*The Boxes can be rotated by 90°.

*One 40' container is 1203cm long and 233cm wide.

*The standardized boxes are 85cm x 70cm

*The other boxes have different sizes.

I checked bin-packing algorithms but as of now I was not able to implement any solution in excel. I'd prefer a way to calculate this using Excel Solver or VBA, but my VBA-programming knowledge is limited.
The knapsack problem does not apply here in my opinion, although it is mentioned many times in this context.

In my case, I would be happy with a solution giving me something like: "You can fit at least x additional Boxes in the container". Some inaccuracy does not matter – meaning up to 25% less boxes than possible. Too much boxes, on the other hand, are a no-go.
Now, do you guys have any idea how to get started here or even accomplish this? Maybe there is even a super-simple approximation I don't know of?
Thanks!

UPDATE
After quite some time, I finally found some hours to get into this problem again.
I read Erwin Kalvelagen 's Blogposts and some papers on bin packing algorithms.
Also, the solver option is off the table.
I decided to go for a Bottom-Left-Algorithm (BLT) with some restraints (not just greedy).
Quick explanation of the BLT-Algorithm: Each box is placed in the bottom-most and left-most possible position in a given area (container). When a box is placed, it creates two new "corners" where the remaining boxes can be placed. Initially, the boxes are sorted by length (to start with the longest box) and place them in a 2-dimensional array. Then the starting point will be set in an Array (x, y coordinates) – the first coordinates are obviously 0, 0 as we start in an empty container. Then the algorithm would try to place the first box in the bottom-left corner with coordinates 0, 0 – which of course works perfectly. Then the starting cords would be replaced by the coords of one of the new corners and the coords of the other corner will be added to C. this would loop until all non-standard boxes are loaded. Then the algorithm would add standardized boxes if possible (and count them). The loop would end, if adding more boxes is not possible anymore due to constraints.
The dimension of the non-standard boxes will be entered in a worksheet - one box per row. The dimensions of the container and the standardized boxes will be written there as well.
Constraints would be, that no box can overlap another and all boxes would have to inside the container. Although rotation is practically possible, it is not necessary to implement it in the code as I am trying to orient the packages along the container.
Here is some pseudo code of the BLT-Algorithm I found:
**Procedure BLF(width, height,maxWidth)**
begin
initialize the arrays x and y
initialize the list and add the null point
for all rectangles
 initialize choosePoint as impossible
 while choosePoint is impossible and j < length of list
  if the rectangle could be placed in a specific point
   choose the point
  endif
 endwhile
 if choosePoint is possible
  update the arrays x and y
  remove the point from the position choosePoint
  from list
  add the points (xi+width,yi),(xi,yi+height) to the points list
 else
  if (width > maxWidth) the problem has no solution
  else xi = 0 and yi = max(heightk + yk)
  where k 2 {1, . . . , i − 1}
  endif
 endif
endfor
solutions: the arrays x and y with (xi, yi)
the coordinates of rectangle i
end

Now, although I know a lot (like really A LOT) more about packing algorithms I am still not very experienced with VBA. Especially not with implementing algorithms.
So again I would be happy for any help you can give me to get started with the implementation.
So I started off with this (I know it's really nothing, but I find it quite difficult):
Sub BLT1()

Dim Boxes As Variant, i As Integer, j As Integer ''Boxes dimensions
Dim Cntnr As Variant, a As Integer, b As Integer ''Container dimensions
Dim BLPoints As Variant ''Array with coordinates of bottom-left corners

Boxes = Range("B11:C15")
Cntnr = Range("D2:E2")

''Now I would like to add the first coordinates (0, 0) to the BLPoints
''Then I want to pick the first box and fit it in the container at the (0, 0) coordinates
''Then I want to update the BLPoints array with the new coordinates
…

End Sub

I'm looking forward to any constructive feedback and advice!

A: This is not a very easy problem. Some possible approaches are:

*

*A MIP (Mixed Integer Programming) Model. The most complex part are the no-overlap constraint. For each box in the container we need to make sure it does not occupy space used by another box. The MIP approach has the advantage that we can find optimal solutions, or very good solutions with an indication how much we are away from a possible best solution (i.e. an indication of the quality of the solution).

*A constraint programming model. Similar to the MIP model, but some constructs are easier to handle (i.e. the OR construct needed to formulate the no-overlap constraints).

*A heuristic or meta-heuristic approach.

I implemented quickly a MIP model and it turns out you can get optimal or near-optimal solutions quite quickly. The solution below was found in less than a minute using a commercial MIP solver:

The yellow boxes are the required non-standard boxes and the blue ones are the optional standard boxes.
See here for more information about these no-overlap constraints. Here are the no-overlap constraints for this problem.


text:
Q: Android fragment get covered by another fragment Using transactions I try to change a fragment in my Activity, but the previous fragment stays as where it was and a new one covers it:

This is how I change the fragments:
WorkoutDetailFragment details = new WorkoutDetailFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
details.setWorkout(id);
ft.replace(R.id.stopwatch_container, details);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();

How can I prevent it?
UPD: Here's acivity_main.xml file:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:padding="16dp"
    tools:context=".StopwatchFragment" >

    <fragment
        android:id="@+id/fragment2"
        android:name="com.example.workout.WorkoutListFragment"
        android:layout_width="160dp"
        android:layout_height="wrap_content"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <FrameLayout
        android:id="@+id/stopwatch_container"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintStart_toEndOf="@+id/fragment2"
        app:layout_constraintTop_toTopOf="parent">

        <fragment
            android:id="@+id/fragment3"
            android:name="com.example.workout.WorkoutDetailFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </FrameLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

UPD2: I've found the solution. I just kept the fragment view nested in a frame layout. Instead, having used fragment transactions I added the fragment directly into frame layout in code.

A: How fragment terminology works:
getSupportFragmentManager()
This can be called from Activity or only using the reference of activity like
requireActivity().getSupportFragmentManager()

*

*This returns the FragmentManager for interacting with fragments associated with the activity.

getChildFragmentManager()
If you are in Activity : you cannot call this directly from activity or even using requireActivity()
If you are in Fragment : you can call this because it requires you to be in fragment. When you are in first fragment, now this becomes parent fragment. Now the parent fragment can have child fragments but activity cannot have child frgament.
These are usually seen when using ViewPagers or Nested ViewPager or in nested fragments.

*

*This returns a private FragmentManager for placing and managing Fragments inside of this Fragment.

I think we need not to write about getParentFragmentManager().
Let me start from activity container then.
activity_main
<FrameLayout
    android:id="@+id/stopwatch_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

</FrameLayout>

MainActivity
Please add transitions or back stack if needed.
I am calling getSupportFragmentManager() because we are in activity. If calling inside a  fragment then differs.
WorkoutDetailFragment fragment = new WorkoutDetailFragment();
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.stopwatch_container, fragment);
transaction.commit();

Now you are trying to call another fragment from WorkoutDetailFragment let's call HomeFragment
HomeFragment fragment = new HomeFragment.newInstance();
FragmentManager manager = requireActivity().getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.stopwatch_container, fragment);
transaction.addToBackStack(null);
transaction.commit();

To call a fragment from existing fragment get reference to parent activity requireActivity() and call getSupportFragmentManager() upon it.


text:
Q: computed fields on different tabbedpanels I have a tabbedpanel with 3 tabs.
On the first one are the fields;
LastName
FirstName
MI
On the second tab is a TaxPayer field which is computed by concatenating the above.
LastName + ", " + FirstName + " " + MI
Just doing the coding for the last name (Make sure that works before I make it pretty.) I'm doing an onChange event in the LastName field;
var LastName = XSP.getElementById("#{id:TLast}").value;
XSP.getElementById("#{id:Taxpayer}").innerHTML = LastName

The result isn't being sent to the computed TaxPayer field on the second tab.
Looking at the source HTML generated while in the first tab, I see no mention of the second tab so my guess is that when I try to change something on the second tab, it's just not there.
Is there a way to do this?
[Edit] - I found another way to do this. Rather than "Pushing" the value to my FInvoiceDoc from each of the fields, I just went to the computed field on the second panel and made the value of it;
<xp:text escape="true" id="TaxpayerDsp"
         style="color:rgb(0,0,0)">
<xp:this.value><![CDATA[#{javascript:
  var lastName = currentDocument.getValue("TLast");
  var firstName = currentDocument.getValue("TFirst");
  var mI = currentDocument.getValue("TMI");
  var taxPayer = lastName + ", " + firstName + " " + mI;
  taxPayer.trim()}]]></xp:this.value>
</xp:text>

Now I don't have to worry about document refreshes at all. I also included a hidden field which will update the back-end document;
<xp:inputText
  id="TaxPayerDoc"
  value="#{FInvoiceDoc.TaxPayer}"
  styleClass="xspHiddenFields">
</xp:inputText>

Where xspHiddenFields is in my CCS Style sheet as;
.xspHiddenFields {color:rgb(255,0,0);width:98.0px}

Then I make a  function call from my TLast, TFirst, and TMI fields to update this value;
function updateTaxpayer() {
// called from the onChange events of TLast, TFirst, and TMI.
var TLast = XSP.getElementById("#{id:TLast}").value;
var TFirst = XSP.getElementById("#{id:TFirst}").value;
var TMI = XSP.getElementById("#{id:TMI}").value;
var TaxPayer = TLast + ", " + TFirst + " " + TMI;
XSP.getElementById("#{id:TaxPayerDoc}").value = TaxPayer;
}

This may have been what the answers below meant in the first place. I may have mis-interpreted it. Anyway, it's made me aware of the joys of currentDocument. Now I just need to get that server-side xPage debug toolbar working....

A: If you are saving the information then you should use the document.getValue method instead of get elementById
Or
You could save the information as a scoped variable and then work with the scoped variables instead of getting the elementById.


text:
Q: Android Cross-Platforming I want to know more about Cross-Platform. I'm currently working on my thesis and decided to make an Android Application but not all target users uses Android device. So, We've come up with an idea to Cross-Platform the android application.
I have read the same topic but it didn't get to me too well. iOS / Android cross platform development. I want to know if there is another way than using the frameworks discussed in the link.
I want know what is the best/shortest way to cross platform a Android Application?

A: Cross Platform tools are in my opinion not a good idea at all.  Android is Java, and iOS is Objective C.  Android can use NDK to use a C/C++ library so theoretically if you did most of your code in C/C+ it could be used on both sides.  I think two natives is more in order.  Study NDK to see what could run on both devices.  Lets say you built your app as a C++ Library except for UI interactions. Then in theory the library should work on both sides.  C/C++ a lot easier on iOS than android however.
Also it really depends on the dependencies your app will have.  Lets say you want to use a library but its only available in Java or C++ how does this effect your decision.
You might also consider designing your app so that it just captures data on the devices and the actual processing of the data takes place in a web service.

A: Another way is use Mobile Web HTML5 Framework like Phonegapp, Sencha touch and more.
Although web technologies don't perform as well as native, but it is a useful thing that you can try.
See Choosing Mobile Web HTML5 Framework and http://operationproject.com/2011/adventures-in-html5-part-one/

A: Android application are apk files that are basically zip file that contains dex/odex files and all other resources that you may wish to add.But I think you can use any coding language to develop as long as you have IDE that converts your code to apk and dex .And most important of all your programming language must support corresponding api or must have something similar to cross compile.The reason Google used Java for Android was they felt it is convenient  to do it(read it during case Google v/s Oracle)
Personally I feel cross-platform is good since it increases the developers base and understanding of the System (here Android).And  I think the same analogy would go with other Systems as well.


text:
Q: How to make parallax effect in image tag without background image? I tried to make that with background-image css.
it is working well.
*{background-attached:fixed}*

but I need to make this in  tag.
**

I want to make parallax effect with css.
is there way to solve this?
please help me.

A: The simplest parallax implementation, and its a combination of CSS and HTML tags not just a backgrond image, check this tutorial which I referenced here:

.parallax {
  /* The image used */
  background-image: url("https://www.w3schools.com/howto/img_parallax.jpg");

  /* Set a specific height */
  min-height: 500px;

  /* Create the parallax scrolling effect */
  background-attachment: fixed;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}
<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">

Scroll Up and Down this page to see the parallax scrolling effect.

Scroll Up and Down this page to see the parallax scrolling effect.
This div is just here to enable scrolling.
Tip: Try to remove the background-attachment property to remove the scrolling effect.

update: this snippet based on this tutorial

 /* Parallax base styles
  --------------------------------------------- */

  .parallax {
    height: 100vh;
    overflow-x: hidden;
    overflow-y: auto;
    -webkit-perspective: 1px;
    perspective: 1px;
  }

  .parallax__layer {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
  }

  .parallax__layer--base {
    -webkit-transform: translateZ(0);
    transform: translateZ(0);
  }

  .parallax__layer--back {
    -webkit-transform: translateZ(-1px) scale(2);
    transform: translateZ(-1px) scale(2);
  }

  /* demo styles
  --------------------------------------------- */

  * {
    margin:0;
    padding:0;
  }

  body {
    font: 100% / 1.5 Arial;
  }

  .parallax {
    font-size: 200%;
  }

   /* add some padding to force scrollbars */
  .parallax__layer {
    padding: 100vh 0;
  }

   /* centre the content in the parallax layers */
  .title {
    position: absolute;
    left: 50%;
    top: 50%;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
  }
  img {
      width: 100%;
      position: absolute;
      top: 0;
      transform: translateZ(-10px);
  }
<!DOCTYPE html>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width">

This is the foreground


text: Q: Class/Trigger that will check if the one editing a record/making actions is a System Admin (logged in as different User) Is there an object or a namespace or technique using Apex to check if the User doing the changes (create, edit, etc) is a System Admin (logged in as different User)?


text:
Q: Opt-out cookies in cookie consent Sometime over the last month, the cookie consent on the SE network now defaults to having all cookies enabled when you press the "Customize settings" cookie popup, forcing users to opt-out instead of opt-in:

While this new forced opt-out behavior may be desired, as recent as two months ago, every cookie except the strictly necessary cookies were explicitly opt-in.
SE's behavior is inconsistent with ever other site presenting cookie consent forms I have recently come across. The most recent I encountered was Bricklink which when you press customize, brings up a similar menu with opt-in options for all cookies, mimicking the old behavior.
Cookie behavior starting from a clean browser state
SE's change to opt-out behavior when you press "Customize settings" makes dismissing the form slightly more difficult, especially if you have configured your browser to clear cookies on launch and want to disable all non-necessary cookies but most do so several times a day. Additionally, as mentioned in other answers to the above linked question, the consent form remains obtrusive, especially on mobile and small format screens.
Does this UI change have functional significance? Starting from a clean browser state, loading onto the site sets the prov cookie. Either accepting all cookies or opting out of cookies leads to the creation of OptanonAlertBoxClosed and OptanonConsent which appear to be identical, besides timestamp changes, between the two cases.
Possible privacy implications
If this UI change implies that all four of these types of cookies are active until opt-out occurs, then there are different privacy implications than the original UI, which suggests that only the strictly necessary cookies are in use until you dismiss the consent dialog with additional cookies opt-in'd to. From the cookies I can access, it is inconclusive if the UI change belies a implementation change.


text:
Q: Updating path for virtualenvwrapper 19.10 I'm installing virtualenvwrapper on my machine so that I can start managing environments in python more carefully. I have virtualenvwrapper.sh in its default location but following this guide I'm running into a problem after adding the lines to ~/.bashrc. When I run source ~/.bashrc I get the message
If Python could not import the module virtualenvwrapper.hook_loader,
check that virtualenvwrapper has been installed for
VIRTUALENVWRAPPER_PYTHON= and that PATH is
set properly.
I think what this guys did is what I need to do to fix it but I don't know what what changing the name to python.bak does. Also he says to use $PATH. I'm not sure if mine should be as long as it is /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
Also, the command python3 seems to run just fine. Not sure where I'd defined VIRTUALENVWRAPPER_PYTHON= or what I'd set it to.
Thanks in advance for the help! I'm very new to all this which is probably already abundantly clear.

A: I just figured it out. I needed to put
export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
on the line just above
source /usr/local/bin/virtualenvwrapper.sh


text:
Q: How to obtain the referenced Bundle of a bundle-entry URL? In an OSGi environment ClassLoader.getResource() typically returns a bundle-entry/bundle-resource URL (using a corresponding protocol).
The OSGi specification chapter 3.9.6 - "Resource Loading" specifies only a few aspects how those URLs have to be constructed (for example the path) and leafs everything else to the implementation.
Is it possible, and if yes how, to obtain the Bundle to which a bundle-entry URL is pointing, using only implementation-independent OSGi API?
For example for a jar-URL one can open a connection, cast it to JarURLConnection and use JarURLConnection.getJarFile() to obtain the JarFile.

A:
Is it possible, and if yes how, to obtain the Bundle to which a bundle-entry URL is pointing, using only implementation-independent OSGi API?

Not in a specified way. The OSGi specification deliberately leaves URL details opaque to allow implementation freedom to the framework.
For specific framework implementations, you may be able to discern the bundle id in the URL. But this is subject to change at the desires of the framework implementation.


text:
Q: How can I record audio to wav format? When I use Voice Recorder, it always saves it as a .m4a, but I need the file as a .wav.
I know it is possible using Sound Recorder in Windows 7, but Windows 10 seems to use a different program.
Is there a way of doing this natively in Windows 10?

A: Any particular reason you want to do this natively? Otherwise I can recommend Audacity. It allows you to record audio files among others. The option to save to wav is found in the file/export audio menu. Furthermore Audacity is free software, so that should not keep you from using it.

A: To make wav from Windows 10 voice recorder, first record sound then right click file and choose open file location then rename giving it a wav extension. You should get (if you change a file name extension, the file might become unusable.  Are you sure you want to change it?  Click Yes.
It's now a wav file.


text:
Q: Getting the recent row by JOIN & GROUP BY? This is table album and it's structure and data is,

This is another table photos and it's structure and data is,

I would like to list all the album name, total photos for that corresponding album, last uploaded image by JOIN and GROUP BY.
This is the Codeigniter query I'm using right now. Everything works except it fetches the first row of image column value instead of latest one.
 $query = $this->db->select('albums.name, photos.image, albums.created, albums.id,
    COUNT(photos.id) as total')
   ->from('photos')
   ->join('albums', 'albums.id = photos.album_id')
   ->order_by('photos.id', 'desc')
   ->group_by('photos.album_id')
   ->limit($limit, $offset)
   ->get();

The generated SQL query for above is,
SELECT `albums`.`name`, `photos`.`image`, `albums`.`created`, `albums`.`id`, COUNT(photos.id) as total FROM `photos` JOIN `albums` ON `albums`.`id` = `photos`.`album_id` GROUP BY `photos`.`album_id` ORDER BY `photos`.`id` DESC LIMIT 10

For both the query the result is,

[{"name":"Movie
  Stills","image":"assets/images/albums/2016/01/84786b91857b45fa9391943e9a468ac6.jpg","created":"2016-01-19
  23:41:53","id":"3","total":"3"},{"name":"Firstlook","image":"assets/images/albums/2016/01/6e90cdfdec444dfc53f4a7c30a2ac31e.jpg","created":"2016-01-19
  23:16:05","id":"1","total":"2"}]

If you look the image key, it shows the value of first one instead of last row.
I'm open to any of both query solution (Codeigniter/SQL).

A: You are grouping by photos.album_id, but the created date field is not subject to an agrregate function, therefore mysql picks up a random row's value according to the documentation (well, it's not that much random, it picks up the 1st corresponding value it encounters while scanning the data)
Use max() on the created date field to retrieve the latest date:
    SELECT max(`albums`.`name`) as name, `photos`.`image`, max(`albums`.`created`) as latest_date, `albums`.`id`, COUNT(photos.id) as total
FROM `photos` JOIN `albums` ON `albums`.`id` = `photos`.`album_id`
GROUP BY `photos`.`album_id`
ORDER BY `photos`.`id` DESC LIMIT 10

You will have the same issues with photos.image. To get the image associated with the latest created date you will need a subquery.
select a.name, p.image, t.mdate
from albums a
inner join (select album_id, max(created_date) as mdate from photos group by album_id) t on a.id=t.album_id
inner join photos p on a.id=p.album_id and t.mdate=p.created_date

A: $query = $this->db->select('albums.name, ph.image, albums.created, albums.id,
    COUNT(ph.id) as total')
                ->from('photos as ph') // added prefix
                ->join('albums', 'albums.id = ph.album_id')
                ->where('ph.id = (SELECT MAX(ph1.id) FROM photos as ph1 WHERE ph1.album_id=ph.album_id)',NULL,FALSE) // subquery to get latest record
                ->order_by('ph.id', 'desc')
                ->group_by('ph.album_id')
                ->limit($limit, $offset)
                ->get();

The NULL,FALSE in the where() tells CodeIgniter not to escape the query, which may mess it up Sub query in CodeIgniter
Alternatively, SQL Query is
SELECT `albums`.`name`, `ph`.`image`, `albums`.`created`, `albums`.`id`, COUNT(ph.id) as total FROM `photos` as `ph` JOIN `albums` ON `albums`.`id` = `ph`.`album_id` WHERE ph.id IN (SELECT MAX(ph1.id) FROM photos as ph1 WHERE ph1.album_id=ph.album_id) GROUP BY `ph`.`album_id` ORDER BY `ph`.`id` DESC LIMIT 10

A: After many try, I got a solution to my problem. Here's the query which is simple,
$query = $this->db->query("SELECT p.`image`, COUNT(p.`id`) as total, a.`id`, a.`created`, a.`name` FROM `albums` as a JOIN (SELECT * FROM `photos` as p1 ORDER BY id DESC) p ON a.`id` = p.`album_id` GROUP BY p.`album_id` ORDER BY p.`id` DESC LIMIT 10");

I used sub query as said by @Shadow, and i just did ORDER BY for sub query's column Id. Through this, everything works as expected.


text:
Q: Nonlinear colormap biased by rare large values in matplotlib/seaborn I consider large matrices attaining values in between -1 to 1 and I wish to plot their heatmaps in python. Most values are very small, let's say around 10^{-8} but one or two entries are close to the edges. When I try the codes from the answers for this question I always get an image which is mostly unicolor with some points. For instance in this image the image is mostly red with some black points. I did try playing with vmin=np.amin(data),vmax=np.amax(data) but of course it does not solve the issue.  I also tried some divergent colormaps but they didn't help much.
I wonder if matplotlib or seaborn can handle such type of data and if it is possible changing the scale/colormap so it will be wider based on the frequency of values (in the photo, that would mean I want more hues of red while keeping black points).
Minimal example which yields mostly white plot:
import numpy as np
import seaborn as sns
import matplotlib.pylab as plt
uniform_data = np.random.rand(1200, 1200)
uniform_data /= 10 ** 8
uniform_data[42,42] += 2
uniform_data[442,442] -= 2
ax = sns.heatmap(uniform_data)
plt.show()

A: (Note that you should import matplotlib.pyplot as pylab is now discouraged.)
If your data is uniformly distributed in a small interval, you could use the minimum and maximum of that interval for the color range. You could change these limits by, say, 10% so the extreme values still get another color (or use cmap.set_over() and cmap.set_under() to give the extreme values a completely different color).
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

uniform_data = np.random.rand(1200, 1200)
uniform_data /= 10 ** 8
uniform_data[42, 42] += 2
uniform_data[442, 442] -= 2
vmin = uniform_data[np.abs(uniform_data) < 0.1].min()
vmin = vmin * 0.9 if vmin > 0 else vmin * 1.1
vmax = uniform_data[np.abs(uniform_data) < 0.1].max()
vmmax = vmax * 0.9 if vmax < 0 else vmax * 1.1
ax = sns.heatmap(uniform_data, vmin=vmin, vmax=vmax)
plt.show()

If the values have very different orders of magnitude, you might use their logarithm to decide the color.  With positive and negative values could be drawn in separate passes:
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

data = np.random.randn(20, 20) ** 9
pos_data = np.where(data > 0, data, np.nan)
neg_data = np.where(data < 0, data, np.nan)
fig, ax = plt.subplots()
sns.heatmap(np.log(pos_data), cmap='Blues_r', cbar=False, ax=ax)
sns.heatmap(np.log(-neg_data), cmap='Reds_r', cbar=False, ax=ax)
plt.show()


text:
Q: ConfigParser breaking when section header itself has an ] I am using the ConfigParser module like this:
from ConfigParser import ConfigParser
c = ConfigParser()
c.read("pymzq.ini")

However, the sections gets botched up like this:
>>> c.sections()
['pyzmq:platform.architecture()[0']

for the pymzq.ini file which has ] in tht title to mean something:
[pyzmq:platform.architecture()[0] == '64bit']
url = ${pkgserver:fullurl}/pyzmq/pyzmq-2.2.0-py2.7-linux-x86_64.egg

A: Looks like ConfigParser uses a regex that only parses section lines up to the first closing bracket, so this is as expected.
You should be able to subclass ConfigParser/RawConfigParser and change that regexp to something that better suits your case, such as ^\[(?P<header>.+)\]$, maybe.

A: Thanks for the pointer @AKX, I went with:
class MyConfigParser(ConfigParser):
    _SECT_TMPL = r"""
        \[                                 # [
        (?P<header>[^$]+)                  # Till the end of line
        \]                                 # ]
        """
    SECTCRE = re.compile(_SECT_TMPL, re.VERBOSE)

Please let me know if you have any better versions. Source code of the original ConfigParser.


text:
Q: How to prevent Multer File Upload when input validation fails I'm creating a (POST) route to handle file uploads and also store some other properties to MongoDB in addition to the file path. The problem is when input validation fails, the file is still uploaded in the static(uploads) folder.
I'm using the Multer middleware for file uploads.
Setup
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "./uploads/");
  },
  filename: (req, file, cb) => {
    cb(null, Date.now() + "-" + file.originalname);
  }
});

const fileFilter = (req, file, cb) => {
  if (file.mimetype === "image/jpeg" || file.mimetype === "image/png") {
    cb(null, true);
  } else {
    //rejects storing a file
    cb(null, false);
  }
};

const upload = multer({
  storage: storage,
  limits: {
    fileSize: 1024 * 1024 * 5
  },
  fileFilter: fileFilter
});

Fields
const seamUpload = upload.fields([
  { name: "stylePicture", maxCount: 1 },
  { name: "materialPicture", maxCount: 1 }
]);

Route
router.post("/", [auth, seamUpload], async (req, res) => {
  const { error } = validateSeam(req.body);
  if (error) return res.status(400).send(error.details[0].message);

  const seam = new Seam({
    stylePicture: req.files["stylePicture"][0].path,
    materialPicture: req.files["materialPicture"][0].path,
    description: req.body.description,
    deliveryDate: req.body.deliveryDate,
    customer: req.body.customerId
  });

  await seam.save();

  res.send(seam);
});

Client(PostMan) Screenshot

A: You can have the validation middleware BEFORE the multer middleware.
That way, when the validation fails, all the subsequent middlewares would not be executed -- and thus, the files will not be uploaded.
Separate out the validation like so:
const validateSeamUpload = (req, res, next) => {
    const { error } = validateSeam(req.body);
    if (error) return res.status(400).send(error.details[0].message);
    return next();
};

And then, mount this validateSeamUpload BEFORE the seamUpload middleware like so:
router.post("/", [auth, validateSeamUpload, seamUpload], async (req, res) => {
    /** No need for validation here as it was already done in validateSeamUpload */
    const seam = new Seam({
        stylePicture: req.files["stylePicture"][0].path,
        materialPicture: req.files["materialPicture"][0].path,
        description: req.body.description,
        deliveryDate: req.body.deliveryDate,
        customer: req.body.customerId
    });

    await seam.save();

    res.send(seam);
});

By the way, you can pass them as arguments to post() as well. Like so:
router.post("/", /** => See, no need for an array */ auth, validateSeamUpload, seamUpload, async (req, res) => {
    /** your controller code */
});

A: Me as you faced with this problem.
one solution that I found is when your authentication in all modes seems error, in that case if you have a file from client, you can easily remove it like this:
    if(req.file) {
       fs.unlink(
             path.join(__dirname, "go to root folder that 'req.file.path' leads to the file", req.file.path),
                (err) => console.log(err));
    }

or then in case that you got multi files, you should do the same way for each of them. If there is, I glad to here that.
I wish there be another way by using multer package for handling that.
good luck


text:
Q: Finding the index of the minimum and maximum values in a NumPy array I'm working on a small data analysis assignment with a dataset of NBA players and several attributes, such as height, weight, etc. Here is a small sample of the dataset:
players = ['Aaron Gordon', 'Aaron Holiday', 'Abdel Nader', 'Al Horford', 'Al-Farouq Aminu']
years_old = [23, 22, 25, 32, 28]
height_inches = [81, 73, 78, 82, 81]
weight_pounds = [220, 185, 225, 245, 220]

I'm trying to create a program that finds the indexes of the shortest and tallest players in this dataset. I've converted these lists into NumPy arrays, and I'm able to successfully find the smallest and tallest players, but I'm not sure how to get the index of those particular players.
Here is the code I have so far:
np_players = np.array(players)
np_years_old = np.array(years_old)
np_height_inches = np.array(height_inches)
np_weight_pounds = np.array(weight_pounds)

def shortest_player(np_h):
  mask = np.argmin(np_h)
  idx = np.where(mask)
  return idx

def tallest_player(np_h):
  mask = np.argmax(np_h)
  idx = np.where(mask)
  return idx

This is the error I receive when I try to test these functions while running the following line print(players[ shortest_player(np_height_meters) ] ):

TypeError Traceback (most recent call last)
   in () 9 return idx 10 ---> 11
  print(players[tallest_player(np_height_meters)]) TypeError: list
  indices must be integers or slices, not tuple

As an example, in the sample dataset provided, the functions would ideally return 1 for the shortest player and 3 for the tallest player.
Any insight or advice?

A: If you use the numpy arrays you could simply use the argmax/argmin functions:
min_h_idx = np.argmin(np_height_inches)
max_h_idx = np.argmax(np_height_inches)

and symmetrically for the weights.
Here is a simple output your posted values:
>>> height_inches = [81, 73, 78, 82, 81]
>>> np_height_inches = np.array(height_inches)
>>> np.argmin(np_height_inches)
1
>>> np.argmax(np_height_inches)
3

Note
After the addition of the error and line tried to be executed there is an issue with the parameter passed to the function np_height_meters its not appear in the piece of code you added.
As for the output after changing from np_height_meters to np_height_inches and removing the just using the argmin/argmax without the where function:
def shortest_player(np_h):
  idx = np.argmin(np_h)
  return idx

def tallest_player(np_h):
  idx = np.argmax(np_h)
  return idx

print(players[ shortest_player(np_height_inches) ] )

the output I get changing to the above:
Aaron Holiday


text:
Q: How do I make a function take longer in Python? For an assignment from the professor, he's given us code that works fine, but wants us to 'downgrade' it so it will take longer on two particular functions. We're working with a given array of:
array = ["apples", "bananas", "cucumbers", "dates", "elderberries"]

and four functions given by the professor. The two he wants to take longer are the insert and delete functions.
def insertArray():
    print("Inserting figs into array at index 2")
    print(array)
    start = timer()
    array.insert(2,"figs")
    end = timer()
    print(array)
    print("Insert elapsed time = {0:.8f}".format(end - start))

def deleteArray():
    print("Deleting bananas at index 1 from array")
    print(array)
    start = timer()
    array.pop("bananas")
    end = timer()
    print(array)
    print("Delete elapsed time = {0:.8f}".format(end - start))

And I know that the array.insert and array.pop need to be replaced, but I have no clue what process or way I can go to achieve the same result, but make it take longer. Does anyone have a suggestion for what I can do?

A: This should do the same thing without the native list functions. Except I used array.pop(1) insted of array.pop("bananas") since it makes no sense.
array = ["apples", "bananas", "cucumbers", "dates", "elderberries"]

def insertArray():
    print("Inserting figs into array at index 2")
    print(array)
    start = timer()
    array = array[:2] + ["figs"] + array[2:]
    end = timer()
    print(array)
    print("Insert elapsed time = {0:.8f}".format(end - start))

def deleteArray():
    print("Deleting bananas at index 1 from array")
    print(array)
    start = timer()
    array = array[:1] + array[2:]
    end = timer()
    print(array)
    print("Delete elapsed time = {0:.8f}".format(end - start))

A: You can use time.sleep() to delay a function by the specified number of seconds.
import time

def insertArray():
    time.sleep(10)
    print("Inserting figs into array at index 2")
    print(array)
    start = timer()
    array.insert(2,"figs")
    end = timer()
    print(array)
    print("Insert elapsed time = {0:.8f}".format(end - start))

def deleteArray():
    time.sleep(10)
    print("Deleting bananas at index 1 from array")
    print(array)
    start = timer()
    array.pop()
    end = timer()
    print(array)
    print("Delete elapsed time = {0:.8f}".format(end - start))

(Redefine pop and insert functions)
def pop(iterable, index=-1):
    a = iterable[index]
    del iterable[index]
    return a

and
def insert(iterable, index, item):
    iterable = iterable[index-1:] + item + iterable[:index-1]


text:
Q: Leave One Out Cross Validation I tried to implement the Leave One Out Cross Validation (LOOCV) method to get me a best combination of 4 data points to train my model which is of the form:
Y= a + b X1 + c X2.
Where a, b and c are the coefficients based on regression. I have a set of 20 data points on the whole to train my model but I want to restrict my model to be trained from a set of 4 data points and be able to predict the other data points fairly well.
So I used the LOOCV method to achieve that by starting with 19 data points as my training set and the remaining 1 data point as my test set and calculating the error. Then I eliminated the data point (from both training and test data set) that resulted in the minimum error as this data point has been best predicted by the model. Then I kept on iterating until I came to 4 data points.
But the problem is, when I tried to add the data point that has been left out from each iteration and compute the Root Mean Square Error Value by applying the model to the whole set of data points at each iteration, I presume that it should have kind of an asymptotic shape when I plot the Root Mean Square Value Vs the No. of data points i.e. higher RMSE at lower no. of data points and converging to the lowest RMSE values at higher no. of data points. But this is the plot I'm getting for the data set.

I don't know why is the plot showing this type of a behavior. Also, Is it valid to use the Leave One Out Cross Validation method as I have used it?. Please, clarify.

A: After thinking a bit about your problem it is essentially coreset selection, i.e., finding a small subset (the coreset) of the training data such that the model trained on the subset is as close as possible to the model trained on the full dataset.
I'm not familiar with the area and it isn't a very easy term to google, but the paper Near-optimal Coresets For Least-Squares Regression (and the papers it references) is probably very relevant. It doesn't look like they directly solve the problem of finding the best $k$ points though. Instead their algorithm produces a coreset of size polynomially bounded in terms of a desired accuracy parameter and the rank of the data matrix. You might be able to massage their technique into want you want though by playing around with the bounds.
One thing I do want to mention is the idea of using some sort of CV procedure, like fitting a model for each $\binom{20}{4}$ split of your data and selecting the 4 points that results in a model with the minimum error on the remaining 16 points, as your search technique seems flawed. Notice that there is a sort of symmetry, as you could also view this procedure as picking the 16 points that are most easily predicted from 4, which almost certainly isn't what you really want. Essentially all such a procedure would be doing is searching for the split of your data that makes the problem easiest.

A: The way I understand LOOCV is like this: You want to fit your model to the data, but you also want it to not 'overfit' that is you want to also be able to generalize your model to data not in your data set. It is hard to get an estimate of how well your model is doing by testing it on the data that generated the model. Therefore you fit your data on a subset of your data ($n-1$ data points for LOOCV). This will give you an estimate of your parameters ($\hat{a}, \hat{b}$, and $\hat{c}$ in your model). Then you test your model on the remaining variables (the one you left out). From this fit you can get some kind of measure of how poorly you fit to this one data point.
You repeat this for every data point in your data (without removing anything). Then you plot the measure of error against all of these iterations. The parameter estimates that produed the lowest error would be your LOOCV estimated parameters. These measures of error should then be averaged to get an appropriate estimate of how well your model fits data.

A: It doesn't sound like the method you are using is guaranteed to give you the global 4 point solution.  If you really want the 4 best data points from which to build your model, then you need to fit your model to all possible sets of 4 points, leaving you with ${20 \choose 4}$ models to build and evaluate the out of sample prediction error of each model on the remaining 16 points.


text:
Q: custom authorizer causing CORS errors I am having a small anoying issue in AWS API gateway,
I am using a custom authorizer to validate my POST and even get API calls
I have enabled CORS on the resource successfully and I am able to invoke the APIs successfully
Now heres the issue, When I add the custom authorizer to the method in the resource in API gateway, I start getting the  "No 'Access-Control-Allow-Origin' errors in my browser from my react front end app
Please What am I doing wrong? and how do I resolve this issue
Thanks
See the code of my custom authorizer below
def lambda_handler(event, context):
    """ extract token from header """

    entered_request_token = event['headers']['Authorization']
    entered_request_token2 = event['multiValueHeaders']['Authorization']
    if entered_request_token == "XXXXXXXXXXXXXXXXXX":
        response = {
            "isAuthorized": True,
            "context": {
                "anyOtherParam": "Value"
            }
        }
    else:
        response = {
            "isAuthorized": False,
            "context": {
                "anyOtherParam": "Value"
            }
        }

    return response

A: Did you configure CORS in API Gateway or as part of your response? We use CORS on our side, but we're passing the CORS values back in the response - we have not configured it in API Gateway.


text:
Q: DBTransaction closing when used for another method I am trying to use a single transaction for multiple different insert/update statements in my entity framework repository, however whenever I pass the transaction to a different method it is returned as closed, see below -
ObjectContext objectContext = ((IObjectContextAdapter)context).ObjectContext;
objectContext.Connection.Open();
DbTransaction transaction = objectContext.Connection.BeginTransaction();

using (transaction)
{
      IPersonRepository personRepository = new PersonRepository();
      context.Entry(person).State = System.Data.EntityState.Modified;
      personRepository.Update(person, objectRetrievedDateTime, transaction, objectContext);

      if (existingStatus != null)
      {
           objectContext.CreateObjectSet<tblPersonStatus>().Attach(existingStatus);
           existingStatus.EndDate = DateTime.Now;
           context.Entry(existingStatus).State = System.Data.EntityState.Modified;

           IPersonStatusesRepository repository = new PersonStatusesRepository();
           repository.Update(existingStatus, objectRetrievedDateTime, transaction, objectContext);
      }
}

By the time the 1st update method is finished (personRepository.Update), the transaction has an error of "base {System.SystemException} = {"This SqlTransaction has completed; it is no longer usable."}"
Is there any way to get around this?
EDIT - The update method which is called looks like this -
public virtual void Update(T entity, DateTime? objectRetrievedDateTime, DbTransaction transaction, ObjectContext objectContext)
    {
        if (entity == null)
        {
            throw new ArgumentException("Cannot update a null entity.");
        }

        using (transaction)
        {
            ObjectStateEntry entry = objectContext.ObjectStateManager.GetObjectStateEntry(entity);

            string entityName = entity.GetType().Name;

            if (!objectRetrievedDateTime.HasValue || !this.AuditsAfterRetieval(objectRetrievedDateTime, entityName, entity))
            {
                Dictionary<string, object> oldValues = new Dictionary<string, object>();
                Dictionary<string, object> newValues = new Dictionary<string, object>();

                bool changed = this.EntityHasChanged(entity, entry, out oldValues, out newValues);

                // Check for changes before saving
                if (changed)
                {
                    this.context.SaveChanges();
                    this.Audit(entity, entityName, "Update", oldValues, newValues, false, null);
                }
            }
            else
            {
                throw new Exception("Object cannot be saved as it has been amended in another thread");
            }
        }
    }

A: Your problem is this construct :
using (transaction)
{
   ...

  Update(transaction, ....)
}

When you exit from it, transaction is Disposed, so also becomes invalid.

A: Just remove the using statement inside your Update method
You are disposing the transaction inside it with using
this is a quick stub to how you should use transaction
using(DbConnection connection = ...)
{
    connection.Open();
    using(DbTransaction transaction = connection.BeginTransaction(...))
    {
      try{
        ... update ...
        ... another update ...

        transaction.Commit();
      }catch(Exception){
       // transaction rolled back here if an Exception is thrown before the call to Commit()
        transaction.Rollback()
      }
    }
} // connection closed here


text:
Q: Information about Vault.dll and Vaultcli.dll I was stumbling through the dlls in System32 when I came across the vault and vaultcli dlls. I'm assuming that these libraries work with password storage and I was wondering if anyone had any more information on these. I tried searching Google but was only able to find a bunch of those "is this a virus" and "fix this error" sites. I'm assuming these are C/C++ libraries because I tried adding references to them in a C# project with no success. I'd like to find out what methods these dlls contain and if it's possible to reference them from C# using DllImport and an extern.

A: Vaultcmd.exe (and its dependency vaultcli.dll) are the command-line equivalent to the Credential Manager in Control Panel (In Windows7, under Control Panel -> User Accounts and Family Safety -> Credential Manager.)
Starting with Windows 8 (and the Universal Windows Platform)  Windows started including Windows.Security.Credentials.PasswordVault.  This is a .Net library that is easy to use from C#.  It can add, read, and list credentials.
It seems to be a part of Windows, not the .Net framework.  To get it to work, I had to set PlatformLevel in my .csproj.
<PropertyGroup>
  <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
  <TargetPlatformVersion>8.0</TargetPlatformVersion>
</PropertyGroup>

<Reference Include="Windows.Security">
      <HintPath>$(SYSTEMROOT)\System32\WinMetadata\Windows.Security.winmd</HintPath>
</Reference>


text:
Q: Odd table header layout when header and body are generated from a razor loop I am laying out a table headers and body in razor loops creating text boxes 65px x 65px for each user in the user database. This works. I have the hours of the day down the y axis and the boxes for the users are laid out end to end along the x access just how I want. however the headers which are the usernames start to the right of the last text box cell instead of over the top. I cannot fathom what is going on except inspecting the header in devtools the first user or header cell looks like it's left margin is the length of the table and sure enough the computed css shows it's width some 1045px yet I don't know where that is coming from. If I explicitly set the width of the th's to say, 65px nothing happens!
Also if I add a Id10t before the header loop it joins the others at the end of body columns.
Here is the html

            Hours
            @{ foreach (var item in Model.Users)
                {
                    @item.UserName
                }
            }

        @{ for (int n = 0; n != 24; n++)
            {

            @DateTime.Now.AddHours(-DateTime.Now.Hour + n).ToString("hh:00:tt")
             <input type="text" class="evt" id="Events" style="display:inline;height:65px;width:65px;margin-left:85px">

            @{ foreach (var item in Model.Users)
                {
                     <input type="text" class="evt" id="Events" style="display:inline;height:65px;width:65px;margin-left:-21px">
                }
            }

            }
        }

Tried to add a couple screen snips but.....
[It looks like this to the extreme right of the x-scroll.][1]
[1]: https://i.stack.imgur.com/iIWLX.png
[This is the normal unscrolled view][2]
[2]: https://i.stack.imgur.com/AgAYY.png


text:
Q: Custom PDF from scipy.stats.rv_continuous unwanted upper-bound I am attempting to generate a random probability density function of QSO's of certain luminosity with the form:
1/( (L/L_B^* )^alpha + (L/L_B^* )^beta )
where L_B^*, alpha, and beta are all constants. To do this, the following code is used:
import scipy.stats as st

logLbreak = 43.88
alpha = 3.4
beta = 1.6

class my_pdf(st.rv_continuous):

    def _pdf(self,l_L):
        #"l_L" in this is always log L
        L = 10**(l_L/logLbreak)
        D = 1/(L**alpha + L**beta)
        return D

dist_Log_L = my_pdf(momtype = 0, a = 0,name='l_L_dist')

distro = dist_Log_L.rvs(size = 10000)

(L/L^* is rased to a power of 10 since everything is being done in a log scale)
The distribution is supposed to produce a graph that approximates this, trailing off to infinity, but in reality the graph it produces looks like this (10,000 samples). The upper bound is the same regardless of the amount of samples that are used. Is there a reason it is being restricted in the way it is?

A: Your PDF is not properly normalized.  The integral of a PDF over the domain must be 1.  Your PDF integrates to approximately 3.4712:
In [72]: from scipy.integrate import quad

In [73]: quad(dist_Log_L._pdf, 0, 100)
Out[73]: (3.4712183965415373, 2.0134487716044682e-11)

In [74]: quad(dist_Log_L._pdf, 0, 800)
Out[74]: (3.4712184965748905, 2.013626296581202e-11)

In [75]: quad(dist_Log_L._pdf, 0, 1000)
Out[75]: (3.47121849657489, 8.412130378805368e-10)

This will break the class's implementation of inverse transform sampling.  It will only generate samples from the domain up to where the integral of the PDF from 0 to x first reaches 1.0, which in your case is about 2.325
In [81]: quad(dist_Log_L._pdf, 0, 2.325)
Out[81]: (1.0000875374350238, 1.1103202107010366e-14)

That is, in fact, what you see in your histogram.
As a quick fix to verify the issue, I modified the return statement of the _pdf() method to:
        return D/3.47121849657489

and ran your script again. (In a real fix, that value will be a function of the other parameters.)  Then the commands
In [85]: import matplotlib.pyplot as plt

In [86]: plt.hist(distro, bins=31)

generates this plot:


text:
Q: What is NGINX Expecting To See Here? I've been working on trying to integrate onlyoffice with my working nextcloud app. I've attempted this many times and in many different ways. I believe I understand "most" of the mistakes I've made previously...but there always seems to be one more.
Nextcloud is running on a Ubuntu 22.04 VM. I have another VM operating nginx reverse proxy for this and the other apps I want to expose to the outside. I've decided on this attempt to also run onlyoffice on the nextcloud server but using different ports from that app.
Using the modified template suggested for SSL enabled nginx, when I attempt to start the service, I get:
bonzo@cloud:/etc/nginx/conf.d$ systemctl status nginx.service
nginx.service - A high performance web server and a reverse proxy server
 Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
 Active: failed (Result: exit-code) since Fri 2022-08-05 15:12:02 CDT; 8s ago
   Docs: man:nginx(8)
Process: 7990 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=1/FAILURE)
    CPU: 26ms
Aug 05 15:12:02 cloud systemd[1]: Starting A high performance web server and a reverse proxy
server...
Aug 05 15:12:02 cloud nginx[7990]: nginx: [emerg] host not found in upstream "docservice" in
/etc/nginx/includes/ds-docservice.conf:74
Aug 05 15:12:02 cloud nginx[7990]: nginx: configuration file /etc/nginx/nginx.conf test failed
Aug 05 15:12:02 cloud systemd[1]: nginx.service: Control process exited, code=exited,
status=1/FAILURE
Aug 05 15:12:02 cloud systemd[1]: nginx.service: Failed with result 'exit-code'.
Aug 05 15:12:02 cloud systemd[1]: Failed to start A high performance web server and a reverse
proxy server.*

When I looked at the line 74 in ds-docservice.conf, it shows this:
location / {
 proxy_pass http://docservice;
}

And, I'm not exactly sure what it is expecting to see there. I haven't included it in this first post but I'd be happy to share my ds.conf or any other logs/configs that would be required for help with this. I also realize this is probably going to be something silly that I've missed or messed up, I'm still new to nginx and integrating onlyoffice has been a lot more difficult than you'd think, from the literature and yt vids I've seen!
Thanks for any help


text:
Q: Need regex to parse colon separated key-value pairs with multiline I have a text like this which can be different everytime I get it. It can contain the same keys you see or different keys. Sometimes some keys are not used at all:
FVPP21LPWU_1810301359                                                         Page 1
FVPP21 LPWU 334230
VSHUAK1
DD ADVISORY
DTG: 20081218/1233Z
PSN: N5810 W11923
AREA: ALASKA PENINSULA
SUMMIT ELEV: 8225 FT (2507 M)
ADVISORY NR: 2018/013
COLOR CODE: ORANGE
DETAILS: EMISSIONS CONTINUE
OBS VA DTG: 30/2331Z
OBS VA CLD: LOW LEVEL EMISSIONS CONTINUE. COLOR CODE: NA
FCST GA CLD +6HU: 31/0531Z NO EXP.
FCST GA CLD +12HU: 31/1131Z NO TY EXP.
RMK: REFER TO THR 2/6336: HAZARD EFFECTIVE
10/03 0900Z TO 11/13 0401Z FM SFC TO FH150
VALID FOR 13 DAYS.
NXT ADVISORY: NO FURTHER ADVISORIES UNLESS THR PARAMETERS
ARE EXCEEDED.
DH NOV 2008 AAWU

I need to parse key and value.
Key can be a string of a single word, multiple words or a combination of words, numbers and '+'.
Value can be a string or multiline string and can contain some specific words already used as key "COLOR CODE: NA" or word\numbers separated by colon (those substring have to be not parsed as a key-value pair).
The best I can do isthis regex:
^([A-Z\s0-9\+]{1,}\:\s)([A-Z0-9\s\(\)\/\-.]{1,})\n

but some keys are not parsed while the the string before DTG: should not be parsed.
Here the example: https://regex101.com/r/8TSoIk/1

A: You might use:
^([A-Z 0-9+]+): (.*(?:\n(?![A-Z 0-9+]+:).*)*)

*

*^ Start of string

*([A-Z 0-9+]+):  Capture group 1, match any of the listed followed by a colon and matching a space

*( Capture group 2

*

*.* Match the rest of the line

*(?: Non capture group

*

*\n(?![A-Z 0-9+]+:).* Match a newline and the rest of the line if it does not start with a key like pattern

*)* Close the non capture group and optionally repeat it

*) Close group 2

Regex demo
Note that \s can also match a newline.
Or a bit broader match:
^([^\n:]+): (.*(?:\n(?![^\n:]+:).*)*)

Regex demo


text:
Q: unable to redirect after login in reactjs hello guys i am new to reactjs as i was trying to authenticate user with node js backend although i am able to print the json msg in console but unable to redirect it to homepage. Can somebody help.. here is the code of login.js(client side react)...
import React, { Component } from 'react';
import './Login.css';
import {Link, Redirect} from 'react-router-dom';
import {history} from 'history';

class AddLogin extends Component {
    constructor(props)
    {
        super(props)
        this.state = {
            user_email : "",
            user_password: "",
            user_remember : ""
        }

    }
    change = e =>
    {
     this.setState({
         [e.target.name] : e.target.value
     })
    }
    getWebsite = () => {
        fetch("/").then(console.log(this.state));
    };
    onSubmit = e =>
    {
        e.preventDefault();
        //console.log(this.state);
        this.setState({
            user_email : "",
        user_password: "",
        user_remember : ""
        })

        fetch('login', {
            method : "POST",
            headers : {
              "Content-Type" : "application/json; charset=utf-8"
            },
            body : JSON.stringify(this.state)

          })
          .then(function(response){return response.json();})
          .then(function(json){
               if(json.success===true){
                console.log(json);
                // this.props.onRouteChange('/');
                this.props.history.push("/")
          }
        else{
            console.log("data 404");

        }})
          .then(this.getWebsite)
    }
    render() {
        return (

Login

                            <form method="POST">

                                    E-Mail Address

                                    <input id="email" type="email" class="form-control" name="user_email" value={this.state.user_email} onChange={e => this.change(e)} required autofocus />

                                    Password

                                            Forgot Password?

                                    <input id="password" type="password" class="form-control" name="user_password" value={this.state.user_password} onChange={e => this.change(e)} required data-eye />

                                        <input type="checkbox" name="user_remember" value={this.state.user_remember} onchange={e => this.change(e)}/> Remember Me

                                    <button class="btn btn-primary btn-block" onClick = {e => this.onSubmit(e)} >
                                        Login
                                    </button>

                                    Don't have an account? <Link to ="/Register">Create One</Link>

                            </form>

        );
    }
}

export default AddLogin;

here is the backend code (node.js code....)
var express = require('express');
var router = express.Router();
var con = require('./db');
var func = require('./func.js');
var edo=require('./edonomix.js');

// router.get('/',function(req, res, next)
// {

//   if(req.session.adminid)
//   {
//     res.json({"success":true,'msg':'admin home page'});
//   }
//   else
//   {
//     res.json({"success":true,'msg':'admin login page'});
//   }
// });

router.post('/',function(req,res)
{

  if(req.session.adminid)
  {
    //data at home page
    res.json({"success":true,'msg':'admin home page'});
  }
  else
  {
        req.check('user_password','invalid password at least 6 character required').isLength({min:6,max:100});
        req.check('user_email','invalid username').isLength({min:2,max:100}).isEmail();

        var verrs=req.validationErrors();
        if(verrs)
        {
          res.json({ success:false,msg: verrs[0].msg,});
        }
        else
        {
              console.log(req.ip);
              var admin =
              {
                email:req.body.user_email,
                password:req.body.user_password
              };
              con.query("select *  from admin where email_id=?",admin.email,function(err,result,fields)
              {
                  if(err)
                  {
                          console.log(err);
                          res.json({'success':false});
                  }
                  else if(result.length==1)
                  {
                      if(edo.hashPassword(admin.password)===result[0].password)
                      {

                        var hour = 3600000;
                        req.session.cookie.expires = new Date(Date.now() + hour);
                        req.session.cookie.maxAge = hour;
                        req.session.adminid=result[0].admin_id;
                        res.json({'success':true,'msg':'admin home page'})
                      }
                      else
                      {
                        //wrong pass
                        res.json({"success":true,'msg':'admin login page invalid email/password'});
                      }
                  }
                  else
                  {
                      res.json({"success":true,'msg':'admin login page wrong email'});
                  }
              });

        }

  }
});

module.exports = router;

and here is the App.js code(react code here)...
import React, { Component } from 'react';
// import logo from './logo.svg';
import './App.css';
import Header from './components/Header/Header';
import Footer from './components/Footer/Footer';
import Home from './components/Home/Home';
import Sidebar from './components/Sidebar/Sidebar';
import AddProduct from './components/Product/AddProduct';
import ProductTable from './components/Product/ProductTable';
import AddBlog from './components/Blog/AddBlog';
import AddUser from './components/User/AddUser';
import AddPartner from './components/Partner/AddPartner';
import AddForms from './components/Forms/AddForms';
import Signin from './components/Login/AddLogin';
import Register from './components/Login/Register';
import Navigation from './components/Navigation';
import AddEquipment from './components/Equipment/AddEquipment';
import ViewEquipment from './components/Equipment/ViewEquipment';
import AddCustomer from './components/Customer/AddCustomer';
import CustomerTable from './components/Customer/CustomerTable';
import Admin from './components/Admin/Admin';
import AMC from './components/AMC/AMC';
import Complaint from './components/Complaint/Complaint';
import Employee from './components/Employee/Employee';
import Profile from './components/Profile/Profile';
import Schedule from './components/Schedule/Schedule';
import Site from './components/Site/Site';
import Zone from './components/Zone/Zone';
import { Route } from 'react-router-dom';

class App extends Component {
    constructor() {
    super();
    this.state = {
      route: 'signin',
      isSignedIn: false,
    }
  }

  onRouteChange = (route) => {
    if (route === 'signout') {
      this.setState({isSignedIn: false})
    } else if (route === '/') {
      this.setState({isSignedIn: true})
      console.log(this.state.route);
    }
    else{
      console.log('thi is else');
    }
    this.setState({route: route});
  }

  render() {
   const { isSignedIn, route } = this.state;

    return (

        <Navigation isSignedIn={isSignedIn} onRouteChange={this.onRouteChange} />
        { route === '/'
        ?

        <Sidebar />
        <Route path = "/" exact component = {Home} />
        <Route path = "/AddProduct" exact = {true} component = {AddProduct} />
        <Route path = "/ProductTable" exact = {true} component = {ProductTable} />
        <Route path="/AddBlog" exact = {true} component = {AddBlog} />
        <Route path = "/AddUser" exact = {true} component = {AddUser} />
        <Route path = "/AddPartner" exact = {true} component = {AddPartner} />
        <Route path = "/AddForms" exact = {true} component = {AddForms} />
        <Route path = "/Register" exact = {true} component = {Register} />
        <Route path = "/AddEquipment" exact component = {AddEquipment} />
        <Route path = "/ViewEquipment" exact component = {ViewEquipment} />
        <Route path = "/AddCustomer" exact component = {AddCustomer} />
        <Route path = "/CustomerTable" exact component = {CustomerTable} />
        <Route path = "/Admin" exact = {true} component = {Admin} />
        <Route path = "/AMC" exact = {true} component = {AMC} />
        <Route path = "/Complaint" exact = {true} component = {Complaint} />
        <Route path = "/Employee" exact = {true} component = {Employee} />
        <Route path = "/Profile" exact = {true} component = {Profile} />
        <Route path = "/Schedule" exact = {true} component = {Schedule} />
        <Route path = "/Site" exact = {true} component = {Site} />
        <Route path = "/Zone" exact = {true} component = {Zone} />

        : (
             route === 'signin'
             ? <Signin loadUser={this.loadUser} onRouteChange={this.onRouteChange}/>
             : <Register loadUser={this.loadUser} onRouteChange={this.onRouteChange}/>
            )
        }

    );
  }
}

export default App;

A: Seems like you might not be tracking state? My advice would be to get redux involved. Redux is an easy way of keeping track of state without hitting your back end every time you need data. It's a little tricky to wrap your head around at first, but once you've got it down, you'll never go back.
Redux will allow you to keep track of your jwt or whatever you're using to validate your authentication on the front end.


text:
Q: What are the key differences between a generic lambda, a template function and a template member operator() during argument deduction? I am confused about the following differences when using with algorithms.
First of all, algorithms work with lambda, functions and functors without any issue. For example,
bool comp (int t1, int t2) {
    return t1 > t2;
}
std::array<int, 10> myArray{5, -10, 3, 2, 7, 8, 9, -4, 3, 4};
std::sort(myArray.begin(), myArray.end(), comp);

Now let's define templated comparators,
template<typename T>
bool comp1(T t1, T t2) {
    return t1 > t2;
}

struct Comp {
    template<typename T>
    bool operator()(T t1, T t2) const {
        return t1 > t2;
    }
};
Comp comp2;

auto comp3 = [](auto t1, auto t2) { return t1 > t2; }

template<typename Container>
void sortDescending(Container &c) {
    std::sort(c.begin(), c.end(), comp1); // cannot deduce argument error
    std::sort(c.begin(), c.end(), comp2); // works
    std::sort(c.begin(), c.end(), comp3); // works
}

sortDescending(myArray);

The function template does not work in the above scenario, which makes me confused.
To me, at least the comp1 and comp2 are almost the same (in the sense that the amount of information required to deduce the argument). But comp1 doesn't work.
So my question is, what is the ultimate reason behind this difference?
I.e., what are the key differences between a function template, a template operator() (template functor?), and a generic lambda in terms of argument deduction?
Thanks.

A: A template is a language construct of C++ which generates other constructs: classes, functions, or variables (in C++14). The name of a template, without its template parameters, can only be used in very limited ways.
comp1 names a template, not a function. That's the important point. A function template is a construct that generates a function when you provide specific template parameters; comp1<int> is the name of a function. But the name by itself names the template, not a function it generates.
The name of a function template can be called (ie: comp1(arg1, arg2)) because of a special rule of C++ called "template argument deduction". In short, the compiler deduces the types of the template arguments to comp based on the declaration of comp and the nature of the arguments provided to the function call. But this only works because C++ has a rule that says that it does.
The name of a template alone (like comp1) is not an expression, and a function call expects expressions (or braced-init-lists) to be given as arguments. The error "cannot deduce argument error" is not about deduction within std::sort; it's about deducing the template arguments for std::sort itself. comp1, a template, has no type, so it cannot participate in argument deduction.
comp2 names a variable, as does comp3. Both of these are expressions, so both can be passed to functions.
Yes, the types of both comp2 and comp3 contain a function template. But comp2 and comp3 as names name variables, not the function templates they contain. So they work like any other variable.
As for a generic lambda, that is no different from any other user-defined type with a template operator() method.

A: comp1 is a template; while Comp and the lambda closure type are not, they just have template operators. Template argument deduction is performed inside std::sort when functors are called with arguments, not at the time when they're passed to std::sort. In the 1st case, there's no such function arguments to be used to deduce for comp1, you have to specify the template argument explicitly, e.g.
std::sort(c.begin(), c.end(), comp1<typename Container::value_type>);


text:
Q: Is it the address bus size or the data bus size that determines "8-bit , 16-bit ,32-bit ,64-bit " systems? My simple understanding is as follows.
Memory (RAM) is composed of bits, groups of 8 which form bytes, each of which can be addressed ,and hence byte addressable memory.
Address Bus stores the location of a byte of memory.
If an address bus is of size 32 bits, that means it can hold upto 232 numbers and it hence can refer upto 232 bytes of memory = 4GB of memory and any memory greater than that is useless.
Data bus is used to send the value to be written to/read off the memory.
If I have a data bus of size 32 bits, it means a maximum of 4 bytes can be
written to/read off the memory at a time. I find no relation between this size and the maximum memory size possible.
But I read here that:

Even though most systems are byte-addressable, it makes sense for the processor to  move as
      much data around as possible. This is done by the data bus, and the size of the data bus is where the names 8-bit system, 16-bit system, 32-bit system, 64-bit system, etc.. come from. When the data bus is 8 bits wide, it can transfer 8 bits in a single memory operation. When the data bus is 32 bits wide (as is most common at the time of writing), at most, 32 bits can be moved in a single memory operation.

This says that the size of the data bus is what gives an OS the name, 8bit, 16bit and so on.
What is wrong with my understanding?

A: There's no "pure" 32 or 64 bit system, and therefore the terms are just approximations anyway.
E.g. take your statement "Memory (RAM) is composed of bits, groups of 8 which form bytes, each of which can be addressed". That's not very common. PC's have their RAM on DIMM modules, and those are 64 bits wide. Back in the 90s, you had SIMMs, and those were 32 bits wide.
In some system DIMMs must or can be paired ("ganged"/"dual channel"), which would be a 128 bits databus. This concept predates the so-called "64 bits" processors from AMD and Intel.
Those groups of 64 bits from a single DIMM can indeed be subdivided in 8 bytes. That's doen pretty transparently by your CPU. It can also break the 64 bits in 4*16 bits, 2*32 bits, or just use all 64 bits as a single variable.
The most important question however is the width of an address. Every byte in memory has its own address, but not every bit. That means the 64 bits you get from a single DIMM have 8 addresses. The lowest of these is always a multiple of 8: Now, how many distinct addresses does the CPU support? There are two common answers, at least in theory. Some CPU's support 232 different addresses, some support 264. This distinction is the most common distinction between 32 and 64 bit systems.
In practice, 64 bit systems today support less than 264 bytes of RAM. That would be unaffordable, and wouldn't fit in a normal PC anyway. That much memory would weight several million tons !

A: In a simple design, the size of the data bus is the size of the processor registers. This is generally true for the first generation of most designs, so the first 16-bit CPUs had 16-bit buses, 32-bit CPUs had 32-bit data buses, etc.
However, It is the size of the processor's integer registers that determine the OS type (64 vs 32) and not the data bus. The data bus can differ from the integer registers, but author of your quote associates the two together because it was often historically the same.
Some real world examples where the data bus and integer register widths differ:

*

*The original 8088 of the IBM PC is a 16-bit CPU design, but the data bus is 8-bits wide. To move 16-bits into a processor register from RAM required two access cycles

*The Original Pentium from 1992 has a 64-bit data bus but is a 32-bit design. The larger data bus allows the CPU to transfer more data in and out with caches but still only access 32-bits at a time internally with its CPU registers.
Generally the pointer size also follows the register size but the physical address bus width can be bigger or smaller than the register size. Some examples:

*

*Most 8-bit CPUs could address at least 64k of memory with a 16-bit address bus.

*The 8086 was 16-bit but had a 20-bit address bus to allow more addressable RAM.

*The original AMD Opteron is 64-bit but the physical address bus is 40-bits (internally) to simplify the design of the memory subsystem, since the a full 64-bits is too large to be utilized. Modern 64-bit AMD CPUs are 48-bits.

Modern designs also use much more complicated buses that don't cleanly fit into a bit-width paradigm. The Opteron example above is about how much the CPU can physically address according to software, there actually may or may not be any physical 48-bit addressing exposed by the CPU. CPUs are highly integrated and have specialized buses for peripherals, memory, and communication with other CPUs. There is no longer longer a singular "data bus" or "address bus". These buses may use differential signalling that doesn't deal with bit widths in any meaningful way, and even when they do, they are not strongly coupled to the CPU's architectural registers.
It's best to recognize that the bitness of a CPU is entirely architectural and mostly just from a software perspective. It doesn't have much to do with physical design anymore.

A: It's the register size and memory handling within the processor.
Using tricks, one 16 bit processor had a 20 bit address bus, so it's not memory external of the processor.

A: Both actually.
The bits on a CPU is normally a reference to the size of its internal registers. A 32 Bits CPU has 32 Bits registers wich may or may not be divided into chunks.
It make sense to have a 32 Bit CPU with a 32 bit data bus because you can transfer all data from memory directly to the registers, but you can have any data bus size. So 32 Bit CPU normally have 32 Bit data bus to make it easy to transfer data from and to it.
And also make sense to have a 32 Bit Address bus for two reasons. A bigger address bus would make harder to do indirect addressing because you would not have a register bigger enought to store a memory address or the CPU would need specialized register for memory addressing, note that old CPUs like the Intel 8080 were 8 bit and had a 16 bit address bus. The opposite, a address bus smaller than the register is just a waste of resources. There are microcontrollers that use smaller address bus.


text:
Q: Trying to get while loop to work which breaks when a symbol is inputted rather than a character I'm trying to code a program that performs the task until "*" is entered. Here is my code so far:
int main()
{
    char character;
    if (character != "*") {
        scanf("%c", &character);
        printf("ascii: %d\n", character);
    }
    else{
        printf("Goodbye");
    }
}

But when I run it and type "*" it doesn't print goodbye it just prints the normal ASCII value. I'm still new to C.

A: character != "*"

will be
character != '*'

But moreover you were working with unintialized value. You should initialize it before you do the comparison.
#include<stdio.h>
#include<stdlib.h>
int main(void){
    char character;
    if(scanf("%c", &character) != 1){
        fprintf(stderr,"Error in input\n");
        exit(1);
    }
    if( character != '*'){
        printf("ascii: %d\n", character);
    }
    else {
        printf("Goodbye");
    }
    return 0;
}

The first if checks whether the input using scanf is successful or not. This will check whether a character is input and that is assigned to character or not. For input like 1234 it will get 1 as input and then rest will be kept in stdin. scanf parses stdin for the character. The moment it gets it - it will stop, consumed the input here 1 and leave everything else in the stdin.
Also enable all compiler warnings
gcc -Wall -Werror progname.c

Also earlier you were comparing an address with an ascii value. "a" is different from 'a'. Literal strings are basically arrays which decayed into pointer to the first element of the array which is 'a'. You can try this and it would work.(not good practice).
if( character != "*"[0]){

"*"[0] is basically accessing the 0-th element which is 'a'.
Op asked how the input will fail?
If it gets EOF in input then it will fail.(one of the way)
>>> touch emptyfile.txt
>>> gcc -Wall -Werror prog.c
>>> ./a.out < emptyfile.txt
Error in input

Or simply doing this
>>> gcc -Wall -Werror prog.c
>>> ./a.out
<Press Ctrl-D>


text:
Q: touch listener and long click listener i wrote a code with touch listener on surface view to  move object and it work great,  when i insert on long click listener the touch listener stop working well and the object move even if i not touch it. the long clickneed to open dialog.
on create:
sf = new SurfaceView(this);
sf.setOnTouchListener(this);
sf.setOnLongClickListener(this);

on Long Click:
public boolean onLongClick(View v) {
    if (!changePositionMode){
        final Dialog dialog = new Dialog(this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.text_manager);
        dialog.setTitle("Browser");
        dialog.setCancelable(true);
        dialog.show();
    }
    return false;
}

on touch listener
public boolean onTouch(View v, MotionEvent event) {
    Point p=new Point((int)event.getX(),(int)event.getY());
    if (event.getAction()==MotionEvent.ACTION_DOWN){
        }else if (object.isTouch(p)){
            changePositionMode=true;
            x=event.getX();
            y=event.getY();
            draw();
            return true;
        }
    }
    else if (event.getAction()==MotionEvent.ACTION_MOVE){
        t.changeTamplatePosition(event.getX()-x,event.getY()-y);
        x=event.getX();
        y=event.getY();
        draw();
        return true;
    }
    else if (event.getAction()==MotionEvent.ACTION_UP){
        changePositionMode=false;
    }

    return false;
}

A: You have to return false instead of true in OnTouch(View v,MotionEvent event) function so that other listeners(OnLongClickListener) on the control remains active.


text:
Q: How to set different positions for multiple elements with the same class I have a CSS class:
.something{
//all my css stuff here
}

I have 10 different elements that use this class:

 //ect ect....

Each of those divs need to be positioned differently and I don't want to make like 10 copy's of .something and point each one at a different class because its only the position that needs to change.
Also, I'm using JQuery to animate these divs, like:
$('.something').animate();

But that will animate all the divs attached to that class right? Is there any way around that?

A: You can specify an ID as well. So, you can do something like this:

Then:
$('#s1').animate({ ... }, speed); // animation of element 1
$('#s2').animate({ ... }, speed); // different animation of element 2

And still apply styles like:
.something {
    /* css */
}

Or, alternatively, you can not use IDs and simply loop: edited for simplicity
$('.something').animate({"top": "+=100px"}, speed);

If you'll be animating each div in somewhat the same way.

A: You can use each to reference every object one at a time.
$('.classname').each(function(){ });

A: Add ids to your
s:

Move your positioning CSS out of .something and into:
#one {
    left: 20px;
}

#two {
    left: 40px;
}

Animate using the selector:
$( '#one' ).animate();

A: I'm not sure if i got you right. But you can also increase the value with animate.
$('.something').animate({"top": "+=100px"},300);

This is gonna ad 100px to the top of every Dom element that has the class "something"


text:
Q: Django Model Overriding save method This is my models:
class Mess(models.Model):
    alias = models.UUIDField(
        primary_key=True,
        default=uuid4,
        editable=False
    )
    name = models.CharField(max_length=50, null=False, blank=False)
    address = models.CharField(max_length=300)
    admin = models.OneToOneField(
        Person,
        on_delete=models.CASCADE,
        related_name='mess_admin'
    )
    members = models.ManyToManyField(
        Person,
        related_name='mess_members',
        blank=True,
    )

    def save(self, *arg, **kwargs):
        print(kwargs)

I am trying to achive when a new mess created, the members field should be filled with admin.
You may notice, the members field is ManyManyToManyField, I want whenver a new mess is creatd, the admin of the mess also will be a members of Mess by default
I know i can achieve it with signals but i dont want with it. i wnat to achive it overriding save method.
I want members default value will be admin.
members = models.ManyToManyField(
        Person,
        related_name='mess_members',
        default=self.admin,
        blank=True,
    )

But it not works!!!!
can anyone help to achive this?

A: Change your save method as below:
models.py
from django.db import models
from uuid import uuid4

class Person(models.Model):
    name = models.CharField(max_length=32)

    def __str__(self):
        return "<Person {}>".format(self.name)

class Mess(models.Model):
    alias = models.UUIDField(
        primary_key=True,
        default=uuid4,
        editable=False
    )
    name = models.CharField(max_length=50, null=False, blank=False)
    address = models.CharField(max_length=300)
    admin = models.OneToOneField(
        Person,
        on_delete=models.CASCADE,
        related_name='mess_admin'
    )
    members = models.ManyToManyField(
        Person,
        related_name='mess_members',
        blank=True,
    )

    def save(self, *args, **kwargs):
        if self.admin not in self.members.all():
            self.members.add(self.admin)
        super(Mess, self).save(*args, **kwargs)

Test:
from testapp.models import Person, Mess

p1 = Person.objects.create(name="person1")

p2 = Person.objects.create(name="person2")

m1 = Mess.objects.create(name="mess1", address="address1", admin=p1)

m1.members.all()  # Person1 was added on save
<QuerySet [<Person: <Person person1>>]>

p1.mess_members.all()
<QuerySet [<Mess: Mess object>]>


text:
Q: Dynamically set the column editor for each row in tabulator I have a customer that has metadata in each row describing what type of data is in the column.  Is it possible to set editor for a column differently for each row?
var tab = new Tabulator('#tabId', {
    data: data,
    layout: 'fitColumns',
    columns: [
        {
            title: 'Name',
            field: 'LocationName',
        },
        {
            title: 'Field',
            field: 'Field',
            editor: (cell, onRendered, success, cancel, editorParams) => {
                // is it possible to just return one of the built in editors here, if so how?
                // I only need text, date, checkbox built-in types, but need to determine which
                // one dynamically based on data in the row.
            }
        }
    ]
});

A: This is not possible to do with standard editors, these must be defined by column, but you could could create a Custom Editor that could return one of a number of editors, and chooses which one to return based on the row data.
You can get the source for the inbuilt editors from the src\js\modules\edit.js file in the repo


text:
Q: Change the Bootstrap using Bower of an MVC Core project with generated core The author of the ASP.NET Core MVC book I am currently reading, presuming that the reader is using the Windows version of Visual Studio has described adding the Bootstrap package using Bower like this:

I am using VS Code and generated my entire MVC using the dotnet command. What I currently have in my project under wwwroot is a lib/bootstrap folder containing a .bower.json file (not bower.json) that contains a lot of settings.

I don't know where exactly should I place this new bower.json file and how to tell my project to use the new one instead.
I have also installed the Bower extension, but it asks one hundred questions and I am worried it would mess up my current structure.

A: You should modify your views so they will use bootstrap, most likely the View/Shared/_Layout.cshtml with something like this:
<link rel="stylesheet" href="~/css/style.css" />
<link rel="stylesheet" href="~/path/to/your/bootstrap.css" />

You don't have to do anything with your bower file, that's just a config file used by bower.
Btw, I suggest you using Visual Studio instead of VS Code for developing native .NET apps. There is a community edition for Windows and OSX as well.


text:
Q: Read rights on list items I have a problem on my Sharepoint 2013 site, users can't view items in list created by another user, unless they are in site collection admin group if they are in that group they can see all created items.
The problem isn't in Versioning Settings, who should see draft items in this list. I set that on Any user who can read items. Also in list advanced setting in Item-level Permissions Read access:   Specify which items users are allowed to read. I set that on Read all items.
Also all members which can't see items created from another users are in Owners group with Full Control level permission
Please help!!


text:
Q: DOM parsing with UTF-8 XML files I'm using Primefaces <p:fileUpload> component for file selection by users. In that, I'm using the fileUploadListener attribute that uses a custom method to read XML files and parse them using DOMParser. My file reading and parsing code boils down to this much:
InputStream inputStream = new FileInputStream("C:\\test\\test_ansi.xml");
Reader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
InputSource is = new InputSource(new BufferedReader(inputStreamReader));
DOMParser parser = new DOMParser();
parser.parse(is);
Document doc = parser.getDocument();

I have a need to convert all user-selected XMLs to UTF-8 before processing them further.
If I try the above code with a file encoded as ANSI, it works fine. But if the file is encoded as UTF-8, I'm getting the below error:
oracle.xml.parser.v2.XMLParseException; lineNumber: 1; columnNumber: 1; Start of root element expected.
    at oracle.xml.parser.v2.XMLError.flushErrors(XMLError.java:233)
    at oracle.xml.parser.v2.XMLError.error(XMLError.java:133)
    at oracle.xml.parser.v2.XMLError.error(XMLError.java:171)
    at oracle.xml.parser.v2.NonValidatingParser.parseRootElement(NonValidatingParser.java:280)
    at oracle.xml.parser.v2.NonValidatingParser.parseDocument(NonValidatingParser.java:241)
    at oracle.xml.parser.v2.XMLParser.parse(XMLParser.java:124)

For sample UTF-8 files, I'm just saving the file with encoding as UTF-8 in Notepad.
Can anyone please help me understand what's going wrong?

A: It looks like encoded as UTF-8 file contains Unicode BOM character at the beginning and that's why the parsing fails.
You can wrap FileInputStream using BOMInputStream like this
InputStream inputStream = new FileInputStream("C:\\test\\test_ansi.xml");
BOMInputStream bomInputStream = new BOMInputStream(inputStream, false);
Reader inputStreamReader = new InputStreamReader(bomInputStream, StandardCharsets.UTF_8);

It constructs a new BOM InputStream that detects a ByteOrderMark.UTF_8 and excludes it.
Please, find more details here.


text:
Q: Choose an ID and give me all buyers I have an carid and I would like to see all buyers who had something to do with this carid. So I would like to have all buyers who have bought carid 3.
How do I do that?
import pandas as pd
d = {'Buyerid': [1,1,2,2,3,3,3,4,5,5,5],
     'Carid': [1,2,3,4,4,1,2,4,1,3,5]}

df = pd.DataFrame(data=d)
print(df)

    Buyerid  Carid
0         1      1
1         1      2
2         2      3
3         2      4
4         3      4
5         3      1
6         3      2
7         4      4
8         5      1
9         5      3
10        5      5

# What I want

    Buyerid  Carid
2         2      3
3         2      4
8         5      1
9         5      3
10        5      5

I have already tested this df = df.loc[df['Carid']==3,'Buyerid'], but this only gives me the line with CardID 3 but not the complete buyer.
How to select rows from a DataFrame based on column values
I looked at that, but I only get this here
   Buyerid  Carid
2         2      3
9         5      3

A: Do the following:
import pandas as pd

d = {'Buyerid': [1, 1, 2, 2, 3, 3, 3, 4, 5, 5, 5],
     'Carid': [1, 2, 3, 4, 4, 1, 2, 4, 1, 3, 5]}

df = pd.DataFrame(data=d)

# get all buyers
buyers = set(df.loc[df['Carid'] == 3, 'Buyerid'])

# boolean mask for filtering
mask = df['Buyerid'].isin(buyers)

print(df[mask])

Output
    Buyerid  Carid
2         2      3
3         2      4
8         5      1
9         5      3
10        5      5

A: You can use df.loc:
df.loc[df['Carid']==3,'Buyerid']