text:
Q: Python monotonically increasing memory usage (leak?) I'm using this simple code and observing monotonically increasing memory usage. I'm using this little module to dump stuff to disk. I observed it happens with unicode strings and not with integers, is there something I'm doing wrong?
When I do:
>>> from utils.diskfifo import DiskFifo
>>> df=DiskFifo()
>>> for i in xrange(1000000000):
...     df.append(i)

Memory consumption is stable
but when I do:
>>> while True:
...     a={'key': u'value', 'key2': u'value2'}
...     df.append(a)

It goes to the roof. Any hints?  below the module...

import tempfile
import cPickle

class DiskFifo:
    def __init__(self):
        self.fd = tempfile.TemporaryFile()
        self.wpos = 0
        self.rpos = 0
        self.pickler = cPickle.Pickler(self.fd)
        self.unpickler = cPickle.Unpickler(self.fd)
        self.size = 0

    def __len__(self):
        return self.size

    def extend(self, sequence):
        map(self.append, sequence)

    def append(self, x):
        self.fd.seek(self.wpos)
        self.pickler.dump(x)
        self.wpos = self.fd.tell()
        self.size = self.size + 1

    def next(self):
        try:
            self.fd.seek(self.rpos)
            x = self.unpickler.load()
            self.rpos = self.fd.tell()
            return x

        except EOFError:
            raise StopIteration

    def __iter__(self):
        self.rpos = 0
        return self

A: The pickler module is storing all objects it has seen in its memo, so it doesn't have to pickle the same thing twice. You want to skip this (so references to your objects aren't stored in your pickler object) and clear the memo before dumping:
def append(self, x):
    self.fd.seek(self.wpos)
    self.pickler.clear_memo()
    self.pickler.dump(x)
    self.wpos = self.fd.tell()
    self.size = self.size + 1

Source: http://docs.python.org/library/pickle.html#pickle.Pickler.clear_memo
Edit:
You can actually watch the size of the memo go up as you pickle your objects by using the following append function:
def append(self, x):
    self.fd.seek(self.wpos)
    print len(self.pickler.memo)
    self.pickler.dump(x)
    self.wpos = self.fd.tell()
    self.size = self.size + 1

A: To add to the answer by combatdave@:
I just bypassed the terrible memo caching in pickle since clearing the memo on the reader side seems impossible and was an apparently unavoidable memory leak. Pickle streaming seem to be designed for reading and writing moderately sized files, not for reading and writing unbounded streams of data.
Instead I just used the following simple utility functions:
def framed_pickle_write(obj, stream):
    serial_obj = pickle.dumps(obj)
    length = struct.pack('>I', len(serial_obj))
    stream.write(length)
    stream.write(serial_obj)

def framed_pickle_read(stream):
    data = stream.read(4)
    length, = struct.unpack('>I', data)
    serial_obj = stream.read(length)
    return pickle.loads(serial_obj)


text:
Q: Michelson interferometer with and without Gaussian beam In this video from MIT OpenCourseWare for a Michelson interferometer are demonstrated circular fringes.

I'm curious, how the mode of the laser influences the shape of the fringes. Can one conclude from the circular pattern to a Gaussian beam with TEM00 profile?

A: The fringes you see on the top photo and their circular pattern are nothing to do with the laser output mode and are the classic pattern one sees when a noncollimated beam from a point source is input into a well aligned Michelson. The quadratic terms in the fringe shapes betoken defocus arising from an imbalance between the two arm lengths and the decenter and linear components betoken lateral offset between the beams and / or tilt between the beams.
Suppose we see a point source at the Michelson's output port. If the field of view is close to uniformly lit, the field copy from one mirror (looking at one EM field component and assuming that the electric and magnetic fields are all aligned) can be written, to second order in the transverse co-ordinates $(x,\,y)$:
$$\frac{1}{R-\frac{\Delta}{2}}\,\exp\left(\frac{2\,\pi\,i}{\lambda}\frac{\left(x-\frac{x_0}{2}\right)^2+ \left(y-\frac{y_0}{2}\right)^2}{2\,\left(R-\frac{\Delta}{2}\right)} + \frac{2\,\pi\,i}{\lambda}\left(R-\frac{\Delta}{2}\right)-i\,\frac{k_x}{2}\,x - i\,\frac{k_y}{2}\,y\right)\tag{1}$$
whilst the second copy can be written:
$$\frac{1}{R+\frac{\Delta}{2}}\,\exp\left(\frac{2\,\pi\,i}{\lambda}\frac{\left(x+\frac{x_0}{2}\right)^2+ \left(y+\frac{y_0}{2}\right)^2}{2\,\left(R+\frac{\Delta}{2}\right)} + \frac{2\,\pi\,i}{\lambda}\left(R+\frac{\Delta}{2}\right)+i\,\frac{k_x}{2}\,x + i\,\frac{k_y}{2}\,y\right)\tag{2}$$
where:

*

*$(x_0,\,y_0)$ are the components of transverse offset between the beams;

*$R$ is the distance from the point source at the system input along the pathlength of the two beams through the instrument;

*$\Delta$ is the difference between the pathlengths for the two beam copies; and

*$k_x,\,k_y$ represent relative tilt between the beams owing to residual misalignment in the instrument.

Now work out the interference between the terms in (1) and (2), assuming $\Delta$ is small compared to $R$ (i.e. that the point source is some distance from the Michelson's input). You'll get a quadratic equation for the fringe lines which shows they are generally laterally offset circles. You'll find the quadratic terms vanish if the arms are balanced, leaving linear fringes of tilt and offset.
To see how the laser mode affects the result, you can replace my expressions with tilted and offset versions of the general equations for a propagating Gaussian mode, as defined, for example, in the Wikipedia page for Gaussian Beam.

redpajama_set_name: RedPajamaStackExchange


text:
Q: T-SQL Fixing Row Order / Sequence Overview:
I have a page in my application that allows a user to set the priority of a list of records. These records are essentially tasks or goals that the team will need to complete. The order they are given is determined by the user dragging and dropping them into place. Once the user is done and saves the changes, it loops over the data and updates the records in the database with their respective order.
Issue:
The problem I am now running into is on a separate page at which the user can delete a record that may have a priority assigned to it. Since the saving and calculation of a priority is done on another page, deleting a record causes gaps in the sequence.
Example:
Projects that are prioritized:
A (1)
B (2)
C (3)
D (4)
E (5)
F (6)
G (7)

Project gets deleted from another page / function:
A (1)
B (2)
C (3)
D (4)
F (6)
G (7)

Question:
I need to make some type of function I can run after a record is deleted to "repair/re sync" this number sequence. Essentially the single column priority needs to be updated and in the example, F would need to be updated to 5 and G updated to 6 in order to fix the sequence gap.
What I have tried:
Mostly researching a way to solve for this to be honest. I was thinking of putting all the records into a temp table with an Auto Increment number and using that to update the priority level but I feel like there is probably a more simple solution and wanted some opinions.

A: After you delete you simple need to update the rows that are greater than the priority just deleted. So if your column name is Priority and you delete the row where Priority = 5 you simply do something like this. Notice you don't need to use loops here.
Update YourTable
set Priority = Priority - 1
where Priority > 5

A: You could use triggers, which would trigger automatically when delete is done. You could always take values from deleted.
More info
SQL Server ON DELETE Trigger

A: As others have suggested, if you're only deleting one at a time, just update the numbers immediately after deletion. If you want to renumber the whole table at once (perhaps there have been multiple deletions), you can use ROW_NUMBER() and a CTE:
DECLARE @Project TABLE (
    Name nvarchar(100)
    , Priority int
);

-- Projects that are prioritized
INSERT @Project ( Name, Priority ) VALUES
  ('A', 1)
, ('B', 2)
, ('C', 3)
, ('D', 4)
, ('E', 5)
, ('F', 6)
, ('G', 7)
;

SELECT * FROM @Project;

-- Projects get deleted
DELETE @Project WHERE Name = 'E';
DELETE @Project WHERE Name = 'C';

SELECT * FROM @Project;

-- Renumber
WITH P AS
(
    SELECT Name, Priority, ROW_NUMBER() OVER ( ORDER BY Priority ) AS NewPriority
    FROM @Project
)
UPDATE P SET Priority = NewPriority
;

-- Ta da!
SELECT * FROM @Project;

A: Why not just set the Priority in the procedure that extracts the records from the database? that way you don't need to change the priority cause it's always computed on the fly when you read the rows. the only issue is that when you save the new sequence after a user changes the priority sequence, you delete all the records and add them back in in the correct sequence, with an auto-incrementing primary key (pk).
I don't know your sequence, but this example should give you the idea.
Select Record,
  (Select count(*) From table
   Where pk <= t.pk) Priority
From Table t


text:
Q: Server Manager For telnet I want to enable telnet on Windows 10.  I only see a telnet client but not a telnet server.  There is a web page telling me to open server manager and do a lot of stuff.  But, I don't have a server manager.  Please help!  I want to enable telnet.

A: Microsoft depreciated Telnet Servers in Windows Server 2012 R2, and subsequently in Windows 10.
Telnet is considered completely insecure these days, because it sends everything across the wire in plain text, so they removed it.
Since you'd need to install a 3rd party Telnet server, you should (instead) consider installing a SSH server. Similar abilities and results, but SSH is generally considered secure.
Perhaps check out this Serverfault question for some suggested SSH servers:
What is a good SSH server to use on Windows?

A: Windows 8 (2012)
To install telnet in Windows 8, you can use pkgmgr command in the CMD terminal:

*

*Telnet Client: pkgmgr /iu:"TelnetClient"

*Telnet Server: pkgmgr /iu:"TelnetServer"

Applies To: Windows 7, Windows 8, Windows Server 2008, Windows Server 2008 R2, Windows Server 2012, Windows Vista

Windows 10
In Windows 10, pkgmgr is deprecated, so use dism instead, e.g.

*

*Telnet Client: dism /online /Enable-Feature /FeatureName:TelnetClient

*Telnet Client: dism /online /Enable-Feature /FeatureName:TelnetServer
To disable, use /Disable-Feature param instead.

Related:

*

*Using Command Prompt To Install Telnet Client On Windows

*Enable Telnet through Command Prompt or Control Panel in Windows 10


text:
Q: How to change the Direction of Action Buttons of Window Manager (Explorer) in Windows 7 I need to change the direction of Action Buttons (Close,Maximize and Minimize)of Window Manager (Explorer) in Windows 7 from Right side of window to Left of Window Just like in Ubuntu.
Because mostly I use Ubuntu so it became my habit that if I have to close or minimize the window my hand automatically goes to left side of screen.

A: There is a third-party utility for this named LeftSider.
The application runs in the System Tray and moves all Title bar buttons to the left side. Closing the application restores the buttons to right.
I don't think that it will work flawlessly, it might break badly in some applications.
Source


text:
Q: adprep /rodcprep WS2008 y WS2019 I have a WS2008r2 domain with the next conditions:

*

*
Domain functional level: WS2008r2

*
Forest functional level: WS2003

I want to deploy a RODC in a remote site in the same domain, but in a WS2019.
When I execute "adprep /rodcprep" on the main domain, I have this error:
D:\support\adprep>adprep /rodcprep

Adprep connected to the domain FSMO: XXX-DC01.XXX.XXX.

==============================================================================

Adprep found partition DC=DomainDnsZones,DC=XXX,DC=XXX, and is about to update the permissions.

Adprep could not contact a replica for partition DC=DomainDnsZones,DC=XXX,DC=XXX.

Adprep encountered an LDAP error.

Error code: 0x0. Server extended error code: 0x0, Server error message: (null).

Adprep failed the operation on partition DC=DomainDnsZones,DC=XXX,DC=XXX. Skipping to next partition.

==============================================================================

==============================================================================

Adprep found partition DC=ForestDnsZones,DC=XXX,DC=XXX, and is about to update the permissions.

Adprep could not contact a replica for partition DC=ForestDnsZones,DC=XXX,DC=XXX.

Adprep encountered an LDAP error.

Error code: 0x0. Server extended error code: 0x0, Server error message: (null).

Adprep failed the operation on partition DC=ForestDnsZones,DC=XXX,DC=XXX. Skipping to next partition.

==============================================================================

Adprep detected the operation on partition DC=XXX,DC=XXX has been performed. Skipping to next partition.

==============================================================================

Adprep completed with errors. Not all partitions are updated. See the ADPrep.log

 in the C:\Windows\debug\adprep\logs\20211020101000 directory for more information.

To successfully update all partitions, the currently logged-on user needs to be a member of the Enterprise Admins group.  If that is not the case, please correct the problem, and then restart Adprep.

The forest functional level I can't up at this moment because there are applications that are in WS2003 servers.
Is there any way to configure RODC on WS2019?
Thank you so much.

A: •   Since your forest functional level operates on Windows Server 2003 which is retired actively by Microsoft due to which nor its updates and support is available. Thus, due to this, would recommend you upgrade your domain functional level to Windows Server 2012 R2 and the forest functional level to Windows Server 2008 compatibility level. Though, due to some application and process related dependency, many organizations continue to work and rely on these functional levels.
•   Thus, for installing a domain controller on Windows Server 2019 OS, the minimum forest functional level needed in the environment is Windows Server 2008. Also, you can set the domain functional level to a value that is higher than the forest functional level, but you cannot set the domain functional level to a value that is lower than the forest functional level, so the domain functional level value is always set a level higher than the forest functional level.
You can upgrade the forest functional level in your environment from Windows Server 2003 to Windows Server 2008 and domain functional level from Windows Server 2008 to Windows Server 2012 by referring the below article: -
https://learn.microsoft.com/en-us/troubleshoot/windows-server/identity/raise-active-directory-domain-forest-functional-levels
•   Though for the error that you are receiving, you can try migrating the old sysvol FRS replication to DFSR and do a metadata cleanup for the orphaned partition using the 'remove nc' parameter of the Dsmgmt tool. For more information, please refer the below documentation links: -
https://learn.microsoft.com/en-us/troubleshoot/windows-server/identity/error-run-adprep-rodcprep-command
https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2008-R2-and-2008/cc730970(v=ws.10)?redirectedfrom=MSDN


text:
Q: 403 forbidden message while executing a rest message through Jmeter I am trying to test a Rest service through HTTP sampler using Jmeter. The first sampler generates a token and I am using this token for authorization in the header manager of another HTTP sampler "GetUserandPolicies"(Rest WS request) using RegEx and ForEach controller. I can see in the view results tree that RegEx is working fine passing the actual token to the next request. But the Rest Request is failing giving a response message as Forbidden and Response Code 403 which means that the server is able to recognise the request but denying the access.There is no port number for this HTTP sampler which I suspect would be the culprit. But, the same test is passing with another tool (iTKO LISA) without any port value. Both the samplers "TokenGeneration" and "GetUserandPolicies" have no port values. I need some help on this. I am using the POST method in the HTTP  sampler
Please find the sampler result:
Thread Name: Thread Group 1-1
Sample Start: 2014-01-13 12:12:29 IST
Load time: 1390
Latency: 1390
Size in bytes: 382
Headers size in bytes: 354
Body size in bytes: 28
Sample Count: 1
Error Count: 1
Response code: 403
Response message: Forbidden

Response headers:
HTTP/1.1 403 Forbidden
Server: Apache-Coyote/1.1
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Authorization, X-Requested-With, Content-Type
Content-Type: text/plain;charset=UTF-8
Content-Length: 28
Date: Mon, 13 Jan 2014 06:42:30 GMT

HTTPSampleResult fields:
ContentType: text/plain;charset=UTF-8
DataEncoding: UTF-8

A: Looking into Access-Control-Allow-Headers: Authorization, X-Requested-With, Content-Type stanza I guess that you're missing proper Authorization header.
In regards to empty port everything is fine, it defaults to port 80 in case of HTTP and 443 in case of HTTPS
There are 2 options on how you can deal with Basic HTTP Authentication:

*

*Pass username and password in URL like protocol://username:password@host:port/path
i.e. http://user:pass@your.server.com/somelocation

*Use JMeter HTTP Authorization Manager to construct required "Authorization" header for you.

In case if your authentication system uses other approaches, i.e. Cookie-based, NTLM or Kerberos it's still possible but a little bit more tricky. If so - update this post with all details you can get (i.e. request details) and don't hesitate to leave a comment requesting for more input


text:
Q: PHP generate a crontab I want to have a web interface to control when to call a PHP script. In this interface I want to be able to set certain times or ranges that a script will be called. This information will be stored in a DB. When I hit save I want to have it read all the scheduled times from the DB, then format it and write it to a crontab for a cron job. Is there a way to have PHP modify a crontab file?

A: I would go for creating a "cron_runner.php" script that runs every minute, reads the cron data and runs them accordingly. It feels like reinventing the wheel but at least you have no problems with the file permissions.

A: It should be possible, but you need PHP to have the necessary rights to access the user's crontab or to execute "crontab" from the command line. In a shared hosting environment this is mostly not the case.

A: Actually, you can manipulate the cron jobs as simple as text files. You have to be careful not to brake anything tho.
The cron daemon saves the cronjobs for each user using the following structure:
/var
   /spool
        /cron
            /crontabs
                /root
                /user1
                /user2
                ..
                /user5

Using this information, you can modify the text file corresponding the user for which you would like to set the new cron.
Be aware that modifying system files can be dangerous and you should be extremely careful. Your application will also need some additional privileges for modifying these files.


text:
Q: Need help Clarifying the meaning to something in Complex Analysis My professor has lately been writing $\text{Re }z$ and $\text{Im }z$ for my complex analysis class and I'm confused to what this means. Could someone explain? Does it mean the real parts, so just $x$ and the imaginary parts, so just $yi$?

A: Given a complex number $z=x+iy$,
$$
\text{Re}(z)=x,\quad \text{Im}(z)=y
$$

A: A complex number is expressed by two real numbers $x$ and $y$ such that:
$$z=x+iy \in \mathbb{C}$$
and by definition:

*

*$\text{Re}(z)=x\in \mathbb{R}$

*$\text{Im}(z)=y\in \mathbb{R}$

Note also that by the definition of complex conjugate $\bar z= x-iy$, we have that:

*

*$\text{Re}(z)=\frac{z+\bar z}{2}=x\in \mathbb{R}$

*$\text{Im}(z)=\frac{z-\bar z}{2i}=y\in \mathbb{R}$

A: Let $z = x + i\cdot y$ be a complex number.
Then $\text{Re}\ z = x$, $\text{Im}\ z = y$.


text:
Q: Variations of the transportation problem in linear programming The transportation problem is a famous problem in linear programming. For instance,
http://www.utdallas.edu/~scniu/OPRE-6201/documents/TP1-Formulation.pdf
or
http://www.math.ucla.edu/~tom/LP.pdf       Chapter 8
Some specific results are developed for this special linear programming problem.
I'm considering variations of this problem. The scenario is: you can only transfer from some supply points to some demand points (in other words, for each supply point, it cannot supply all the demand points; for each demond point, it cannot demand from all the supply points). Is there any existing paper/literature on this variation? I want to know if there are any specific results developed for this variation.
In other words, when we draw the bipartite graph (V1, V2), not every pair (one node in V1 and one node in V2) can reach each other.

A: This is just the standard transportation problem with some of the costs being infinite.  In practice, any large number would qualify as infinite.


text:
Q: TFS API C# query syntax I am trying to compose a query where I can execute to retrieve the backlog items like the one in the image below.
  WorkItemCollection queryResults = workItemStore.Query(
     "Select [State], [ID], [Title], [Description] " +
     "From WorkItems " +
     "Where [Work Item Type] IN ('Task', 'Bug', 'Product Backlog Item')" +
     "AND [Iteration Path]  Under 'ProjectName'" +
     "AND [Area Path]  Under 'ProjectName'" +
     "And State IN ('New', 'Approved', 'Committed')");

However, I am getting no data. not sure how to properly construct the query.

A: I ended up using this query to avoid hitting TFS twice. Then, I kept track of child items based on the WorkItemLinks that is exposed at the WorkItem that you get back from executing the wql below. Once that is done, I rearranged the entries where parents come before children to give a (treeview) style.
string query = string.Format(@"
   SELECT
    [System.Title],
    [System.Description],
    [System.WorkItemType],
    [System.Id]
    FROM WorkItem
    WHERE
    ([System.WorkItemType] IN GROUP 'Microsoft.RequirementCategory'  OR   [System.WorkItemType] IN GROUP 'Microsoft.BugCategory'  OR   [System.WorkItemType] IN GROUP 'Microsoft.TaskCategory' )
    AND [System.IterationPath] UNDER '{0}'
    AND [System.State] IN ('New', 'To Do')
    AND [System.AreaPath] UNDER '{0}'
    ORDER BY
    [Microsoft.VSTS.Common.Priority],
    [System.Id]", teamProjectName);

A: Get rid of the @project in your query. I is not replaced automatically when using the API.
You also have no space before the AND's.
Your query does not match the image! You can construct the query that you want in Team Explorer and then "Save as" to the desktop. Open in notepad and copy out the query.

A: I wanted up following the article below to retrieve the query.
http://blogs.msdn.com/b/jsocha/archive/2012/02/22/retrieving-tfs-results-from-a-tree-query.aspx


text:
Q: Filter on a list with headings and keep heading of filtered item(s) I have a data set where each object has a heading and an items array with multiple values. I need to be able to filter on the items while maintaining their heading. The filter component below works without the headings. The data output I want is something like:
If I filter on 'ap...'
Output:
fruits
apple
const FilterList = () => {
  const [searchTerm, setSearchTerm] = useState("")
  const [searchResults, setSearchResults] = useState([])

  const data = [
    {
      heading: 'fruits',
      items: [
        { item: 'apple' },
        { item: 'orange' },
        { item: 'peach' }
      ]
    },
    {
      heading: 'veggies'
      items: [
        { item: 'carrot' },
        { item: 'broccoli' },
        { item: 'spinach' },
      ]
    }
  ]

  const handleChange = e => {
    setSearchTerm(e.target.value)
  }

  useEffect(() => {
    let results = []
    if (data && Object.prototype.hasOwnProperty.call(data[0], "heading")) {
      data.forEach(item => {
        results = item.values.filter(value =>
          value.value.toLowerCase().includes(searchTerm)
        )
      })
      setSearchResults(results)
    }
  }, [searchTerm])

  return (

      <input
        type="text"
        placeholder={'placeholder}
        value={searchTerm}
        onChange={handleChange}
      />
      <Typography>
        {heading}
      </Typography>
      <List>
        {searchResults.map((value, i) => (
          <ListItem key={i}>
            {value.value}
          </ListItem>
        ))}
      </List>

  )
}

A: Modify the useEffect :
useEffect(() => {
    console.log("changed");
    const newSearchResults = data.map(value => ({
      heading: value.heading,
      items: value.items.filter(item => item.item.includes(searchTerm))
    }));
    setSearchResults(newSearchResults);
  }, [searchTerm]);

Change your return to:
return (

      <input
        type="text"
        placeholder={"placeholder"}
        value={searchTerm}
        onChange={handleChange}
      />

        {searchResults.map(value => {
          if (value.items.length !== 0) {
            return (
              <>
                <Typography>
                  {value.heading}
                </Typography>
                <List>
                  {value.items.map((item, i) => (
                    <ListItem key={i}>{item.item}</ListItem>
                  ))}
                </List>
              </>
            );
          }
        })}

A:

const data = [{heading:'fruits',items:[{item:'apple'},{item:'orange'},{item:'peach'}]},{heading:'veggies',items:[{item:'carrot'},{item:'broccoli'},{item:'spinach'},{item: 'peach'}]}]

const filterData = (data, val) => {
  const result = []
  data.forEach(obj => {
    let r = obj.items.filter(item => item.item.includes(val))
    if(r.length > 0) {
      result.push({
        ...obj,
        items: r
      })
    }
  })
  return result
}

console.log(filterData(data, "ap"))
console.log(filterData(data, "pe"))

Hope this helps.

A: Created a sandbox: https://codesandbox.io/s/strange-robinson-tvl7d?file=/src/App.js
Explanation
In essence, two changes are required:

*

*need to restructure your searchResults to have the same structure as data, with heading and items. Instead of just pushing the items found, we specify the corresponding heading also, in the searchResults array

// new filtering function
  useEffect(() => {
    const results = [];
    data.forEach(cate => {
      const { heading, items } = cate;

      // remains as is
      const filterdItems = items.filter(item =>
        item.item.toLowerCase().includes(searchTerm)
      );

      // only if filtered items are found
      // add BOTH category & filtered items to results
      if (filterdItems.length) {
        results.push({
          heading,
          items: filterdItems
        });
      }
    });

    setSearchResults(results);
  }, [searchTerm]);

*

*And then, update the render block to loop through the categories array and then the items inside each category

// updated render
{
 searchResults.map((resultCate, i) => {
  return (

      {resultCate.heading}
      {resultCate.items.map((item, idx) => (

{item.item}

      ))}

  );
})}


text:
Q: Erro de CORS XMLHttpRequest cannot load Estou com o seguinte problema:

XMLHttpRequest cannot load

Sempre que envio dados do Angular para o PHP.
Meu PHP está assim:
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method");

$_POST = json_decode(file_get_contents('php://input'), true)

$name = $_POST['name'];
echo json_encode($name);

O angular tá certinho..
var app = angular.module('myapp',[]);

app.controller('mycontroller', function($scope, $http){
    $scope.sendPost =  function (send) {
        $http.post('http://localhost/meuSite/www/server/sendemail.php', send).then(function success(data){
            console.log(data);
            console.log(data.data);
        }).then(function error(err){
            if(err){
                console.log(err);
            }
        });
    }
});

E coloquei um arquivo .htaccess na raiz com esse conteudo:
header set Access-Control-Allow-Origin "*"

Por enquanto, está tudo localhost. O front eu to rodando com o http-server e o back com o apache do xampp.


text:
Q: Instagram OAuth user data I have an app for client side Instagram login. So far, user can successfully login into Instagram and recieve access token. The problem is that I want to make a request, and get the Instagram user data, but don't know how. I also want to know how to clear user's access token to logout.
My code:
angular.module('instagramApp.services', []).factory('instagramService', function($q) {

   var authorizationResult = false;

   return {
      initialize: function() {

        authorizationResult = OAuth.create('instagram');
      },

      isReady: function() {
        return (authorizationResult);
      },
      connectInstagram: function() {
        var deferred = $q.defer();
        OAuth.redirect('instagram', 'https://instagram.com/oauth/authorize/?client_id='CLIENT_ID'&redirect_uri=http://localhost/insta-login&response_type=token');
        return deferred.promise;
    }
  }

});


text:
Q: Máscara a inputs generados de manera dinámica en php Tengo la siguiente función

$("#price").on({
  "focus": function(event) {
    $(event.target).select();
  },
  "keyup": function(event) {
    $(event.target).val(function(index, value) {
      return value.replace(/\D/g, "")
        .replace(/([0-9])([0-9]{2})$/, '$1,$2')
        .replace(/\B(?=(\d{3})+(?!\d)\.?)/g, ".");
    });
  }
});

Esta máscara se aplica tal a como necesito en el input #price de mi formulario, pero ahora estoy generando varios inputs por medio de un ciclo en php, los inputs generados tienen un id así:
<input type="text" id="price_'.$i.'">

Donde $i toma un valor distinto para cada input según se ejecuta el ciclo.
Puedo solicitar su apoyo para entender cómo logro con .find o del modo que crean mejor que la función de máscara aplique a cada input generado con php, independientemente del número de inputs que sean generados?
Gracias.

A: jQuery funciona con una especie de expresiones regulares para acceder a elementos:
Encierra la expresión entre corchetes para indicar que vas a buscar elementos por algún atributo, por ejemplo: [id='price_'], lo que viene después del signo igual es el valor que debe tener el atributo.
Para este caso, necesitas especificar que el valor del atributo buscado no es un valor absoluto, sino que inicia con price_; basta con agregar un circunflejo ^ antes del signo igual, quedando así: [id^='price_']

$("[id^='price_']").on({
  "focus": function(event) {
    $(event.target).select();
  },
  "keyup": function(event) {
    $(event.target).val(function(index, value) {
      return value.replace(/!\D/g, "")
        .replace(/([0-9])([0-9]{2})$/, '$1,$2')
        .replace(/\B(?=(\d{3})+(?!\d)\.?)/g, ".");
    });
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" id="price_1">
<input type="number" id="price_2">
<input type="number" id="price_3">
<input type="number" id="price_4">

Ahora solo falta afinar detalles de la función para que realice los remplazos correctamente.


text:
Q: How to flip a CGImageRef over y-axis I'm trying to animate a sprite using only CoreAnimation. It's working so far except I can't figure out how to flip the sprite sheet.
Right now, I have a walking animation, but I want the sprite to face the direction it's walking (because it looks kind of silly walking backwards).
I guess I could add the reversed images on the sprite sheet, but I would rather avoid that because it could make it really big when I decide to add more.
Right now, my sprite is extending CALayer and I've set its contents to the CGImageRef which is the sprite sheet:
self.contents = (id) image;

To flip it I tried:
UIImage *tmp = [UIImage imageWithCGImage:image scale:1.0 orientation:UIImageOrientationUpMirrored];
CGImageRef flippedImage = tmp.CGImage;
self.contents = (id) flippedImage;

..and that's not working.
I found other solutions which involve animating, but I don't want to animate the flip. I just want it to happen instantly.
Is there a simple way to do this?
If there's a way to flip the whole CALayer, I'd like to know that too. =]
Thanks!

A: Rather than flipping your image, you could try applying a transform to your layer object.
Something like:
self.transform = CATransform3DMakeScale(-1, 1, 1);

This may be better for performance too; if the sprite needs to walk in the opposite direction, you can just set your transform back to CATransform3DIdentity rather than allocing a new image and rotating it.


text:
Q: Physics related question on Divergence Theorem for "general" smooth manifolds I'm a physics major so bear with me here on the math. This is related to a problem from the textbook General Relativity - Wald. In classical electromagnetism say we have a vector field $V$ defined on all of $\mathbb{R}^{3}$ such that $V=O(1/r^{3})$ in the limit as $r\rightarrow \infty$.
When calculating
$$\int_{\mathbb{R}^{3}}\partial _{i}V^{i}d^{3}x$$
one usually takes a closed ball $\bar{B_{r}}(x)\subset \mathbb{R}^{3}$ and, using the fact that $\bigcup _{r}\bar{B_{r}}(x) = \mathbb{R}^{3}$ we get
$$\int_{\mathbb{R}^{3}}\partial _{i}V^{i}d^{3}x = lim_{r\rightarrow \infty }\int_{\bar{B_{r}}(x)}\partial _{i}V^{i}d^{3}x$$
We can then apply the divergence theorem to state that
$$lim_{r\rightarrow \infty }\int_{\bar{B_{r}}(x)}\partial _{i}V^{i}d^{3}x = lim_{r\rightarrow \infty }\int_{\partial \bar{B_{r}}(x)}V^{i}n_{i}d^{2}x = 0$$
where the zero comes from the fact that the integral will drop off as $O(1/r^{2})$ as $r\rightarrow \infty $ so the sequence of integrals will eventually converge to zero.
This is all fine and dandy but my problem deals with a background flat spacetime with metric perturbation $(M,\eta _{ab} + \gamma _{ab})$ where $\eta _{ab}$ is the Minkowski metric and $|\gamma _{ab}| << 1$ as usual. We have a spacelike hypersurface $\Sigma $ of this manifold, the Landau Lifshitz pseudo tensor $t_{ab}$, which is divergence free, and the total energy $E = \int_{\Sigma } t_{00}d^{3}x$. I want to show that $E$ is time translation invariant.
Using the facts that $\partial ^{a}t_{ab} = 0, \partial _{0}E = -\partial ^{0}E$ we proceed as follows
$$\partial _{0}E = -\partial ^{0}E = -\partial ^{0}\int_{\Sigma }t_{00}d^{3}x = -\int_{\Sigma }\partial ^{0}t_{00}d^{3}x = \int_{\Sigma }\partial ^{i}t_{i0}d^{3}x$$
We are also given that $t_{\mu \nu }\rightarrow 0$ identically, dropping off as $O(1/r^{3})$, in the limit $r\rightarrow \infty $.
This is, of course, very similar in situation to the electromagnetic case and one would ideally like to use the divergence theorem to get the desired result that $\partial _{0}E = 0$. But here we do not have a prescribed metric $d$ on $\Sigma$ to make sense of closed balls as far as I can tell. Even if there is some natural choice of metric $d$ for $\Sigma$ how will we know if the closed balls with respect to $d$ will be orientable?
Thanks for any and all help and sorry if this was a bit long winded; it is my first post here so I'm not sure how it is meant to work! I just wanted to be thorough in explaining my issue. Thanks again.

A: Since $\Sigma$ is a submanifold of your spacetime you can define the induced metric which will give you a notion of distance.
So long as you original manifold is orientable, you can define an orientation of $\Sigma$ by restriction. See p111-112 of these notes for more details.
Putting these two together you can define a notion of integration on $\Sigma$ which is consistent with the usual divergence theorem.
Proving that the divergence theorem holds for arbitrary manifolds is nontrivial though! If you're interested in learning more I'd recommend reading Lee - Introduction to Smooth Manifolds.


text:
Q: @staticmethod vs @classmethod vs functions outside of class in Python I have some static functions in a Python class.  The advantage to using the @staticmethod decorator is that it informs the reader that the method doesn't require any information from the class or instance.  However, what I've discovered is that if I have another static method that's called by my first static method, then even if I preface that static function with the @staticmethod decorator, I still have to call it by prefacing it with the class name, and not self.
Alternatively, I can go without any decorators and just call all the static functions with the class name prefix.  This makes the code easier to read.  Is there any reason why I shouldn't do this?

A: Python's static methods are intended for methods that are part of a class, and can be called as either a class method or an instance method: both Class.the_method() and self.the_method() would work. When the static method is called, it is not given an implicit first argument:
class Example:
  def instance_method_example(self, arguments):
    ...

  @classmethod
  def class_method_example(cls, arguments):
    ...

  @staticmethod
  def static_method_example(arguments):
    ...

If you merely want to create a helper function that is used within your class, do not use @staticmethod. Define a free function outside of the class. For example:
class Example:
  def some_method(self, argument):
    return _helper(argument, self.x)

def _helper(a, b):
  ...

The background of static methods in Python is the following: when you access an attribute of an object x.attribute or getattr(x, 'attribute'), then this name is looked up in the instance dict or the class dict. If an object is found in the class dict, it is checked whether that object is a "descriptor": an object that describes how this attribute behaves, not an object that would be directly returned. Descriptors have dunder-methods like __get__, __set__, and __del__ that are invoked depending on whether the descriptor is accessed, assigned to, or deleted with the del operator.
Functions – the things you declare with def – are descriptors. By default, the __get__ descriptor binds the function to the instance argument (typically called self) and returns the bound function, so that it can be invoked as a method. But the various decorators change this behaviour:

*

*a @classmethod def binds to the class object, not the instance

*a @staticmethod def does not bind to any object and just returns the underlying function directly

*a @property invokes the underlying function to retrieve a value

These differences are (partially) visible when looking at the repr() of the bound methods. With the first Example class:

*

*instance_method_example

*

*with class: Example.instance_method_example
is <function Example.instance_method_example at 0x7f1dfdd6fd30>,
the unbound function

*with instance: <function Example.instance_method_example at 0x7f1dfdd6fd30>
is <bound method Example.instance_method_example of <__main__.Example object at 0x7f1dfdddcb80>>,
a method bound to the instance

*class_method_example

*

*with class: Example.class_method_example
is <bound method Example.class_method_example of <class '__main__.Example'>>,
a method bound to the class

*with instance: Example().class_method_example
is <bound method Example.class_method_example of <class '__main__.Example'>>,
also a method bound to the class

*static_method_example

*

*with class: Example.static_method_example
is <function Example.static_method_example at 0x7f1dfdd6fe50>,
the unbound function

*with instance: Example().static_method_example
is <function Example.static_method_example at 0x7f1dfdd6fe50>,
also the unbound function

As a table:

invoked on…
no decorator
@classmethod
@staticmethod

… instance
bound to instance
bound to class
unbound

… class
unbound
bound to class
unbound

A: If your method calls a static method on the class, then it does require information on the class. You have a class method, not a static method. By declaring it @classmethod (and adding the cls parameter), you not only properly inform the reader, you allow polymorphism. An inheritor can reimplement the called static method and change behavior.


text:
Q: Iterate over a multidimensional javascript array and create new array? I have a multidimensional JavaScript array with some string data.
var array = [];

array[0] = ["A","B","C"];
array[1] = ["G","H"];

I want to merge these together into a new array.
Value 1 from the first array should merge with value 1 from array 2 and so on.
Of course, I can do like this.
var array2 = array[0][0] + array[1][0];

But I don't the data so the first array could hold 6 values and there could also be more than 2 arrays.
Is there a way to dynamically iterate over the multidimensional array and create a new array.

A: You can use Array#map and Array#join methods.
// iterate over multi diamensional array and
// generate array with first element of each nested array
var array2 = array.map(function(v){
   // retrieve the first element
   return v[0];
   // join them to convert into a string as your output
}).join('')

var array = [];

array[0] = ["A", "B", "C"];
array[1] = ["G", "H"];

var array2 = array.map(function(v) {
  return v[0];
}).join('')

console.log(array2);

If you want to do the same with all index then use Array#reduce method.

var array = [];

array[0] = ["A", "B", "C"];
array[1] = ["G", "H"];

// iterate and reduce a single array
var array2 = array.reduce(function(arr, e) {
  // iterate over nested array
  e.forEach(function(v, i) {
    // concatenate with the elements in parent array
    arr[i] = (arr[i] || '') + v;
  });
  return arr
  // set initial value as array
}, [])

console.log(array2);

A: The most compact way of writing this would be the following:
arrays[0].map((_, i) => arrays.map(array => array[i]).join(''))

Breaking it down:
arrays[0]                     // Starting with the first sub-array,
  .map(                       // create a corresponding array
    (_, i) =>                 // whose value, for each index is,
      arrays                  // for each of the sub-arrays,
        .map(                 // an array whose values are
          array => array[i])  // the subarray at that index
        )
        .join('')             // with its elements joined together
  );

A: I believe you need to do something like this:
myArray = [["s","m","a"],["d","f"],["t","h","r"]];

function generateStrings(array2d){
    newArray = [];

    function interate(n){
     newString = myArray.reduce((p,c)=>{return c[n]?p+c[n]:p},"")
     console.log(newString)
     if (newString)newArray.push(newString),interate(n+1)
    }
    interate(0)

    return newArray;
}

generateStrings(myArray);

A: You can use a simple reduce function to merge the Array.
const arr = [ [1, 2, 3], [4, 5] ];
const newArr = arr.reduce((acc, x) => [...acc, ...x], [])

console.log(newArr) // [1, 2, 3, 4, 5]

If you need to create an String object after the merge you just have to apply join('') on the returned array.
With Concat
This is the concat version of the function in case you want to use it.
const newArr = arr.reduce((acc, x) => acc.concat(...x), [])


text:
Q: Grafana: different colors between plot and legend on Time Series panel I am using Grafana version 8.5.10 on Windows 10 (but the same on Grafana 9.3.6), with Sql Server as data source.
I have a difference between legend (and tootltip) colors and plot colors on Time Series Panel. The colors are different and the right ones are the colors of the plot:

If I re-render the plot (reload page, reload dashboard, close and reopen the corresponding row) all the colors adjust in the right way.
If I change the plot in some way (changing time span, changing some dashboard variable values that are included in the queries ect.) the plot changes again its colors in a wrong way.
I have some different queries and no Transforms.
The colors scheme selected is "Classic palette".
I think the problem is in the assignment of the colors on classic palette when there are multiple queries and some can be empty: If I manually disable the queries that are empty then the time series always behaves correctly.
It seems that the colors on legend and tooltip are assigned wrongly assuming that the empty queries have some values, but the colors of the plot are correctly assigned based only on the query that actually have values.
Thanks


text:
Q: Problems with getting VS10 debugger to jump certain libs? I'm getting debugger errors when using the boost serilazation library. To fix these I am trying to get Visual Studio 10 to skip the debugging the boost library, after som reading I found out how this coult be achived but the solution somehow doesn't work. Here is a picture of the regedit.

From what i've read this is the way to do it, but when debugging in VS10 it still gives me errors on boost files. Can someone see what i've done wrong?
EDIT
Found a problem with the solution, was in the 32bit part of regedit instead of 64 which my system is on. Changing this didn't however solve the problem. Here is a new picture.

A: Here is a related post that will answer your question.
How to skip common classes in VS 2008 when stepping in?
You can do this by entering entries into the registry (I know, it sucks). The key you are looking for varies from 32 to 64 bit systems. For 32-bit systems the key is
HKEY_LOCAL_MACHINE\Software\Microsoft\VisualStudio\9.0\NativeDE\StepOver
If you're running a 64 bit OS and a 32 bit Visual Studio the key is
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\9.0\NativeDE\StepOver
The Wow6432Node key is a key present for 32 bit applications running on 64 bit systems. (Sidenote: searching the registry for "_RTC_CheckEsp" probably will lead you to the right place, it's a default entry in Visual Studio 9)
The syntax should be familiar to you, but as an example, a simple entry could be string value boost::.*=NoStepInto which will avoid the debugger to step into Boost. See http://www.cprogramming.com/debugging/visual-studio-msvc-debugging-NoStepInto.html for some other examples.


text:
Q: Invariant submanifolds Let $M$ be a smooth manifold, and let $N$ be a submanifold.  Let $V$ be a smooth vector field on $M$ which generates a flow $\Phi_t$ on $M$.  My intuition tells me (perhaps modulo some technical assumptions) that the following is true:

If $V(p)$ is tangent to $N$ for all $p\in N$, then $N$ is an invariant submanifold of $\Phi_t$.

Is this true? What sorts of technical assumptions would I need to worry about to make the statement rigorous?  I imagine, for example, that there could be global topological issues so that perhaps the statement only holds locally.
Is there a good (basic) reference on invariant submanifolds?

A: I am a physicist, not a mathematician, so my answer may lack some of the rigor you expect.  Still, since no one else has taken a stab at this problem in the last year, I will shed what little light I can.
The reference you are looking for may be Sophus Lie's 1884 Differential Invariant Paper.  I was introduced to it in Oak Ridge in 1992 by Dr. Lawrence Dresner, an applied mathematician in Magnetics Division of the Y-12 lab.  Lie's work was being used to solve nonlinear PDE pertaining to superconductor stability problems in the Tokamak fusion reactor.
Sophus Lie was an 18th century Norwegian mathematician, but his style was rooted in the 17th century, so his work can be somewhat dense.  I recommend the translation by M Ackerman with the comments and additional material by Robert Hermann.  It was published in English in 1976 by MATH SCI PRESS, ISBN 0-915692-13-9.  The original paper is "On Differential Invariants", S. Lie, Math. Annallen, Vol. 24 (1884), 537-578.  I am just a student, and not really qualified to speak with authority on this issue, but as I understand it Lie's basic premise is precisely your statement.
Sophus Lie was trying to do for differential equations what Evariste Galois did for polynomials.  A Lie Group is a group that preserves the structure of the smooth manifold.  Lie Group stabilizers, or "differential invariants" as he called them, form an embedded, invariant submanifold.  Because of this, DEQ's may be rewritten in terms of group stabilizers.  Because a function of stabilizers is itself a stabilizer, this puts the DEQ into the kernel of the map with the Lie algebra of the group which is used to find a solution. As Hermann says in the preface, "The key idea is that one should study the structure of the orbit space of a symmetry group on the space of solutions."
Again, pardon the lack of rigor, but perhaps you might benefit from a practical example. If a projectile is fired into a fluid the force of friction is proportional to the square of the velocity, so deriving an equation for how far a projectile penetrates a fluid as a function of time can be a challenge.
$$ F=-\alpha v^2 \rightarrow m\ddot{y}=-\alpha \dot{y}^2$$Here y is the penetration distance, m is mass and $\alpha$ is the drag coefficient, a unitless constant dependent on projectile shape and the density and viscosity of the fluid. ($\dot{y}=\frac{dy}{dt}$ and $\ddot{y}=\frac{d^2y}{dt^2}$) Also, y(0)=0 and $\dot{y}(0)=v_o$, the initial velocity of the projectile.
This DEQ is invariant to the Lie group G(t,y)=$(\lambda t, \lambda^\beta y)\lambda_o=1$  Note that if $t'=\lambda t$ and $y'=\lambda^\beta y$, $\dot{y}'=\frac{dy'}{dt'}=\frac{\lambda^\beta dy}{\lambda dt}=\lambda^{\beta -1}\dot{y}$ and $\ddot{y}'=\lambda^{\beta -2}\ddot{y}$.  Applying these to the DEQ,
$$m\lambda^{\beta -2}\ddot{y}=-\alpha \lambda^{2\beta -2}\dot{y}^2$$
For invariance, $\beta =0$.  Now find the infinitestimal transformations of the primed variables and use the method of characteristics to find the stabilizers (differential invariants).
$$\bigg(\frac{dt'}{d\lambda}\bigg)_{\lambda _o=1}=t$$
$$\bigg(\frac{dy'}{d\lambda}\bigg)_{\lambda _o=1}=\beta y$$
$$\bigg(\frac{d\dot{y}'}{d\lambda}\bigg)_{\lambda _o=1}=(\beta -1)\dot{y}$$
$$\bigg(\frac{d\ddot{y}'}{d\lambda}\bigg)_{\lambda _o=1}=(\beta -2)\ddot{y}$$
$$d\lambda=\frac{dt}{t}=\frac{dy}{\beta y}=\frac{d\dot{y}}{(\beta -1)\dot{y}}=\frac{d\ddot{y}}{(\beta -2)\ddot{y}}$$
$$\frac{dt}{t}=\frac{dy}{\beta y}\rightarrow \beta ln t=ln y + \mu \rightarrow \mu=\frac{y}{t^\beta}\bigg|_{\beta =0}=y$$
$$\frac{dt}{t}=\frac{d\dot{y}}{(\beta -1)\dot{y}} \rightarrow \nu=\frac{\dot{y}}{t^{\beta -1}}\bigg|_{\beta =0}=t\dot{y}$$
$$\frac{dt}{t}=\frac{d\ddot{y}}{(\beta -2)\ddot{y}} \rightarrow \eta=\frac{\ddot{y}}{t^{\beta -2}}\bigg|_{\beta =0}=t^2\ddot{y}$$
These constants of integration, $\mu$, $\nu$, and $\eta$, are group stabilizers for the group of differential equations, a subset of the group of polynomials.  There are an infinite number of them but we only need the first three for our DEQ.  These differential invariants form an embedded submanifold in the solution space, which means the DEQ may be rewritten in terms of the invariants.  Multiplying the DEQ by $t^2$, we have
$$mt^2\ddot{y}=-\alpha(t\dot{y})^2 \rightarrow m\eta=-\alpha \nu^2$$
Since $$t\frac{d\nu}{dt}=\eta-(\beta-1)\nu$$ we can use this expression of the Lie algebra to solve our DEQ.  $$t\frac{d\nu}{dt}=\nu -\frac{\alpha}{m}\nu^2 \rightarrow \frac{d\nu}{\nu-\frac{\alpha}{m}\nu^2}=\frac{dt}{t}$$
This separation of variables is a direct result of the group invariance.  With a little fractional decomposition, some integration, substitution of $\nu=t\dot{y}$, more integration and application of initial conditions, you get
$$y=\frac{m}{\alpha}ln\bigg(1+\frac{\alpha}{m}v_o t\bigg)
$$This solution is easily verified and provides accurate results.
Again, the applied math may not be exactly what you are looking for, but hopefully it will spark some thoughts.  On page 102 of the afore-mentioned book is Lie's Theorem 4.4.1.  "Every infinite continuous group determines an infinite sequence of differential invariants, which can be defined as the solutions of complete systems."  In the following comments by Hermann, he states "As far as I can tell, Lie (in the spirit of the 18th century) assumes that everything is suitably 'general', and that these facts are self evident.  As far as I know, they are not proved to this day!"  What was true for Hermann in 1976 may still hold.  The method obviously works so the proof should exist, but since nobody has answered your post in a year it may be possible that such a valuable proof is still out there waiting to be discovered.


text:
Q: Excel find text, sum cell next to text I am writing here as a last resort, found similar tutorials and forum questions, but none of them isdoing the exact same thing (and I can't/don't know if/how its possible to combine different ideas in one formula/code).
Assume I have a table where I list all my furniture in the house, sorted by the rooms they are in. I need a command that will scan for an exact text in selected cell range (e.g. chair) and then sum the cell next to that (number that represents number of chairs in the room), so that I get as an output the total chairs in the house (5 in this case).
I will have over 50 items and 50 rooms and doing it manually seems obsolete.

A: If the rooms are not all in the same column, you could use SUMPRODUCT:
=SUMPRODUCT(--(A:E="chair"),B:F)
In my example it checks the first 5 columns to equal the value chair and sums the value of the column next to it.

A: if everything is in the same columns as shown, then use the sumif() formula in the appropriate cell (I8 in this case).  No need for vba.
=SUMIF(C[-6],"chair",C[-5])

A: If the tables containing the figures are below each other, then you can select columns B:C then insert a pivot table. You can then drag and drop column D in row headers, then column C in the aggregate column.


text:
Q: CSS/HTML iphone puts some additional space around edges of background image position. how do i remove it? Summary
I've created a box with CSS and HTML.  It scales horizontally and vertically, and maintains a nice gradient background and rounded corners.  It only uses a single PNG background image (with multiple sprites).  It works in IE7+
I'm not using CSS3, because there are subtleties in the corners and borders that make that almost impossible to reproduce with CSS3 alone.  Also, it has to work in IE7 and 8.
I've had success making it work in all browsers that it needs to, but the problem is the iphone

Demo
A working example here:
http://www.trevorsimonton.com/iosbg/index.html
At the bottom of that page, I have links to output in various devices and browsers.  It also works great on my HTC Evo, but I don't have the ability to post a screenshot from that device.

The problem
For some reason, there seems to be some kind of padding or margin or border or something on around the background image of each div.  I've posted screenshots of these at the above site, and a few at the bottom of this post.

*

*This only appears on the iphone.

*It works great on the latest releases of Chrome, Safari and Firefox.
It also works great in IE7, IE8 and IE9

*User zoom is disabled, and the scale is locked at 1.0

The code
The box has complex markup to allow it to scale and show image borders in IE7+
The markup is like this:
HTML

             CONTENT -- FINALLY!

*

*The background image of each key div is the same.  "box.png" -- that
contains all the different "sprites" for the various parts of the
puzzle.

*There's also a "brace" inside the box to make min-height work in IE7.

*Yes this markup seems excessive... but it does work as expected in all
browsers.  It's a totally scalable, rounded corner, gradient
x-browser box.

CSS:
.ksrfasw-top,
.ksrfasw-top div,
.ksrfasw-ls,
.ksrfasw-rs,
.ksrfasw-bottom,
.ksrfasw-bottom div,
.ksrfasw-tab
{
background-image:url("box.png");
background-repeat:no-repeat;
padding:0px;
margin:0px;
border:0px;
outline:0px;
width:100%;
background-size:725px 1120px;
}
.ksrfasw-top div
{
background-position:0px -40px;
}
.ksrfasw-top
{
background-position:100% -60px;
padding-right:12px;
}
.ksrfasw-rs
{
background-position:100% -600px;
padding-right:12px;
}
.ksrfasw-ls
{
background-position:0 -100px;
}
.ksrfasw-bottom div
{
background-position:0px -20px;
}
.ksrfasw-bottom
{
background-position:100% 0px;
padding-right:12px;
}
.ksrfasw-brace
{
height:190px;
float:right;
width:1px;
}

.ksrfasw,
.ksrfasw-content-container
{
position:relative;
}
.ksrfasw-tabbed
{
padding-top:34px;
}
.ksrfasw-content-container
{
z-index:5;
}
.ksrfasw-tab
{
position:absolute;
width:154px;
display:block;
text-decoration:none;
height:61px;
top:0px;
}
.ksrfasw-tab-location
{
left:1px;
}
.ksrfasw-tab-name
{
left:151px;
}
.ksrfasw-tab-active
{
z-index:10;
background-position:-515px -700px;
}
.ksrfasw-tab-active-first .ksrfasw-tab-active
{
background-position:-515px -780px;
}
.ksrfasw-tab-active-first .ksrfasw-top div
{
background-position:5px -40px;
}
.ksrfasw-tab-inactive
{
z-index:1;
background-position:-515px -620px;
}
.ksrfasw-tab-content-inner
{
padding:20px 25px;
}

body
{
text-align:center;
}
#wrapper
{
width:95%;
max-width:700px;
min-width:300px;
margin:0 auto;
}
/**
 * Markup free clearing.
 *
 * @see http://perishablepress.com/press/2009/12/06/new-clearfix-hack
 */
.clearfix:after {
  content: ".";
  display: block;
  height: 0;
  clear: both;
  visibility: hidden;
}
/* IE6 */
* html .clearfix {
  height: 1%;
}
/* IE7 */
*:first-child + html .clearfix {
  min-height: 1%;
}
.clearfix:after {
  font-size: 0;
}

(Note: there are other things going on in the CSS and HTML to create tabs over the box... don't worry about that.  in the example i have 1 box with tabs, and another without.  both exibit the same behaviour)

iPhone Screenshots showing problem
Here is one:

and a zoomed version of the mysterious "padding"

iPad screenshot showing expectation
here's a rendering by ipad, working as expected:

I've tried all i can with background-position, position, top, left, margin, padding, border and even background-size properties, and although it works great on every device tested, (including ipad!) these lines just won't go away on iphone.
Is there something about iphone that spaces background images that I can prevent??
thanks, let me know if more examples or explanation of the linked example are necessary.

A: its the image. if you zoom in any browser, you see the same lines as on the iphone.
i think it comes from the retina-display, doubling all pixels.
you can make a proper image at double size and set it with an media query like
@media only screen and (-webkit-min-device-pixel-ratio: 2) {
  .ksrfasw-top,.ksrfasw-top div,.ksrfasw-ls,.ksrfasw-rs,
  .ksrfasw-bottom,.ksrfasw-bottom,div,.ksrfasw-tab{
    background-image:url("box-doublesize.png");
}

this should fix your issue.


text:
Q: Integrity of the application password Does anyone know how to securely store passwords in the text file. I have an local application on C# in VS with login window and I need to store user passwords. I know about hashing and encrypting, but the problem is that anyone can delete passwords file or change data in it. Is there any way to solve this problem? My attacker model is a user with administrator rights.
Thanks, everyone! I've solved the problem by running a service that keeps the file open, so you cannot edit or delete it unless you shutdown the service. It's not the best solution I think, but it's working.

A: Like others have said, it depends on your threat model. If the locally stored password will be used to validate ANYTHING, then it need's to be encrypted, and stored in an encrypted database/file.
Are you storing this password locally in order to SAVE the users password for a remote login?
Or are you storing this password to actually validate the users login data? (In general you don't want to do this, because as others have stated, you can't trust files on the users side.)
The best solution would be to use a remote server to store the password, and to also validate the login data.
However..
There is no one size fits all security model. It depends on your needs, the users needs, the type of service you are providing, and accordingly the level of security this application needs. (An MSN Chat account doesn't need the same security as a bank login.)
Your original question was how to prevent user editing of a local password file:
You need to encrypt the file when saving it. (also hash the stored password with sha256, using a salt)
Then in your application decrypt the password-file(in memory), then read the password hash from it to use in your application. In addition to this you could store the decryption key/salts for the file/password remotely. Your app needs internet access to fetch the key/salt, then decrypt the local file/password.
More Reading & Code References:
Encrypting Files in C-Sharp
Sha256 Hashing with Salt in C-Sharp
Using Remote SQL Databases in C-Sharp

A: expanding zaph comment: use hashing.
Run the users password through a good hash function (SHA2) and store the hash.
When the use enters a password and you want to check it, run their input through the same hash function and see if you get the same hash.
THis is more secure since you are not storing something that can be converted back to the password and stolen


text:
Q: How to find out if a value of an array shows up more then once I'm trying to find out if a value of an array shows up more then once and if it does then I need to know how many duplicates there is.
For example I have an array that looks like this
array:5 [
  0 => "PR001"
  1 => "PR002"
  2 => "PR002"
  3 => "PR003"
  4 => "PR004"
]

I would like to do something like this
if($array[$productCode] > 2)
{
    echo 'this has duplicates';
}else{
    echo 'this has no duplicates';
}

My code is like this
$productArr = [];
foreach($products as $productCode => $product)
{
    $productArr = $productCode;
}

My $productArr prints out the array above.

A: $values = array_count_values(['PR001', 'PR002', 'PR002', 'PR003']);
if (1 < $values['PR002']) {
    echo 'Value is not unique';
}


text:
Q: Drawing Multiple lines in pcl with known model coefficients I have extracted segments from a point cloud and and  used pcl::SACSegmentation<pcl::PointXYZ> seg;  to fit all the lines simultaneously. All my file segments are stored in the same folder, and I'm able to read them one by one and calculate their model coefficients individually.
The best way to get around this problem is through a for loop, but viewer.addLine gives errors on the second iteration saying that addLine has already been used after drawing one line (RANSAC). I have used the method from the PCL site http://pointclouds.org/documentation/tutorials/cylinder_segmentation.php to determine the coefficients of all my segments. According to what I have learned so far, the model coefficients are stored internally.
Goal: Draw all the lines from the model coefficients simultaneously using RANSAC and add them to the PCL visualizer.
This is the snippet I used to load the all the files (example)
std::stringstream ss;
ss << "./cloud_cluster_" << j << ".pcd";
reader.read<pcl::PointXYZ> (ss.str (), *cloud_cluster, false);
j++;

// snip

pcl::visualizer viewer ("Sample programme")
viewer.addCloud();
viewer.addLine(model_coefficients)

Your help would be appreciated.

A: The addLine function that you are using is documented in the API here:
http://docs.pointclouds.org/trunk/classpcl_1_1visualization_1_1_p_c_l_visualizer.html#a5fd2b99b85da61df8b58980bdb6b0f41
The signature:
bool addLine (const pcl::ModelCoefficients &coefficients, const std::string &id="line", int viewport=0)

Here you can see that when you add a line, it is automatically given a string id "line". This is fine if you add only one line but for multiple lines you need to give a unique id for each line.
e.g.
std::stringstream ss;
ss<<"line"<<j;
viewer.addLine(model_coefficients,ss.str());


text:
Q: what is use of get_HZ() please tell me what is the use of get_HZ() system call. Any link for its documentation??
I tried to search for this in google but could not get the usage of this function
Thanks,
Vivek

A: Probably from the old days, when computer clocks ran from the power supply frequency (50Hz in some parts of the world, 60Hz elsewhere). The value is needed when converting from # of clock interrupts to actual, real wallclock seconds.


text: Q: Middle button does "back" in browser, how to disable? I'm using KDE and for some reason my middle mouse button activates "Back" in both Firefox and Chrome. I cannot find anything about those browsers to disable it, so presume it is some kind of global behaviour. How would I disable/change this behaviour?


text:
Q: What is this line of code really doing? Assuming "structName" is a defined struct:
structName ** sarray = (structName **) malloc(0 * sizeof(structName *));
I know its creating a pointer to a struct pointer called sarray, but why is there (structName **) placed at the start of the expression? Also, why is the struct size multiplied by 0 in the malloc call?
The source of the code is here

A: malloc returns void *. The pointer sarray is of type structName **. The (structName **) is a type cast, converting void * to structName **. Pointers are very malleable in C; malloc will always return something that can safely be cast to any kind of pointer. In this case you have a pointer to structName *.
Multiplying sizeof(structName *) by 0 does what you think, asking malloc for a zero-length chunk of memory. I suspect the sizeof is in there because the author considers it the standard pattern. You could remove it without consequence and just supply 0. Given that realloc works with a NULL argument you could also just initialise sarray to NULL.
For the record, for malloc:

If the size of the space requested is zero, the behavior is
  implementation- defined: either a null pointer is returned, or the
  behavior is as if the size were some nonzero value, except that the
  returned pointer shall not be used to access an object.

So that initial call may or may not return NULL, with essentially identical results: accessing anything via the pointer shall have undefined results.

A: The reason for the (structName **) is to convert the return value of malloc() from void * to (structName **), so the assignment to sarray doesn't produce an incompatible type error.
The reason for the multiplication by zero is compatibility with the statement that follows:
long sarray_len = 0;

If the example had chosen to start with
long sarray_len = initialCount;

instead, then the malloc would have to be
structName ** sarray = (structName **) malloc(initialCount * sizeof(structName *));

.

A: The malloc function returns a pointer of type (void *).
The (structName **) casts that pointer into type (structName **). This cast is not required in C.
He multiplies by 0 because he don't want to allocate any struct yet, and waits for reallocation later.

A:
Why is there (structName **) placed at the start of the expression?

It's called type casting. malloc returns a void * which is cast to structName ** so that it can be assigned to sarray.

Also, why is the struct size multiplied by 0 in the malloc call?

The code pattern malloc(size * sizeof(datatype)) is generally followed everywhere, hence the multiplication was used there, IMO.

A: structName ** sarray = (structName **) malloc(0 * sizeof(structName *));

is equivalent to :
structName ** sarray = NULL;

A: The (structName **) before malloc is a mistake.  It was required in the 1970s, but has been a mistake since 1989. Many people didn't update their learning materials since 1989 ;-)
At best it is redundant text (and redundant text should usually be avoided as it makes the important text harder to read), and at worst it can hide an error. For further reading on that topic see this thread.

Regarding the second part, 0 * sizeof(structName *) . This is of course 0 and you may well ask why the person didn't just write 0.
The reason is that the person is conforming to a particular style for use of malloc. Conforming to a pattern is a way of minimizing errors. If you read this site regularly you'll know that incorrect use of malloc is one of the most common sources of bugs that people have trouble tracking down.  The pattern being used is:
T *ptr = (T *) malloc( number_of_elements * sizeof(T) );

which allocates an array of a certain number of elements of type T. This is legal even if the number is 0 (but not legal for negative numbers); in which case it may either return a null pointer, or a non-null pointer. In either case, you can't try and access any array elements , of course.
This pattern is common, but as mentioned in the linked thread, has problems and since 1989 there has been a better option.
NB. Consider using calloc to allocate memory. It's slightly clearer in that the two numbers are separated by a comma instead of by a multiplication operator, and on some operating systems (e.g. Linux) it can perform faster than malloc.


text:
Q: Invalid base64-encoded string: number of data characters (217) cannot be 1 more than a multiple of 4 I am learning Django and creating a to-do app using the framework. While setting up the Django rest framework API, I got an unusual error. I've been using Django for quite a while, but have never come across this error before. I don't know why this error is getting thrown.
The error occurred the very first time when I executed the command manage.py runserver and navigated to users.
The error is as below:
Invalid base64-encoded string: number of data characters (217) cannot be 1 more than a multiple of 4
Request Method: GET
Request URL:    http://127.0.0.1:8001/users/
Django Version: 3.1
Exception Type: Error
Exception Value:
Invalid base64-encoded string: number of data characters (217) cannot be 1 more than a multiple of 4
Exception Location: /usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/base64.py, line 87, in b64decode
Python Executable:  /Users/yogendrakumar/PycharmProjects/todo_app/bin/python
Python Version: 3.8.5
Python Path:
['/Users/yogendrakumar/PycharmProjects/todo_app',
 '/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python38.zip',
 '/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8',
 '/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/lib-dynload',
 '/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages']
Server time:    Sat, 29 Aug 2020 12:25:01 +0530

views.py:
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from rest_framework import permissions
from todo.serializers import UserSerializer, GroupSerializer

class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer
    permission_classes = [permissions.IsAuthenticated]

class GroupViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows groups to be viewed or edited.
    """
    queryset = Group.objects.all()
    serializer_class = GroupSerializer
    permission_classes = [permissions.IsAuthenticated]

Below is the stack trace/traceback:
Environment:

Request Method: GET
Request URL: http://127.0.0.1:8001/users/

Django Version: 3.1
Python Version: 3.8.5
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'rest_framework',
 'todo']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback (most recent call last):
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/django/contrib/sessions/backends/base.py", line 215, in _get_session
    return self._session_cache

During handling of the above exception ('SessionStore' object has no attribute '_session_cache'), another exception occurred:
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/django/contrib/sessions/backends/base.py", line 118, in decode
    return signing.loads(session_data, salt=self.key_salt, serializer=self.serializer)
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/django/core/signing.py", line 135, in loads
    base64d = TimestampSigner(key, salt=salt).unsign(s, max_age=max_age).encode()
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/django/core/signing.py", line 201, in unsign
    result = super().unsign(value)
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/django/core/signing.py", line 184, in unsign
    raise BadSignature('Signature "%s" does not match' % sig)

During handling of the above exception (Signature "xnqTuv_ylPs2HNImqZUFHZYYDRY5IfETbWXc5_4zbB8" does not match), another exception occurred:
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/rest_framework/viewsets.py", line 114, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/rest_framework/views.py", line 505, in dispatch
    response = self.handle_exception(exc)
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/rest_framework/views.py", line 465, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception
    raise exc
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/rest_framework/views.py", line 493, in dispatch
    self.initial(request, *args, **kwargs)
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/rest_framework/views.py", line 410, in initial
    self.perform_authentication(request)
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/rest_framework/views.py", line 324, in perform_authentication
    request.user
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/rest_framework/request.py", line 220, in user
    self._authenticate()
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/rest_framework/request.py", line 373, in _authenticate
    user_auth_tuple = authenticator.authenticate(self)
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/rest_framework/authentication.py", line 123, in authenticate
    if not user or not user.is_active:
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/django/utils/functional.py", line 240, in inner
    self._setup()
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/django/utils/functional.py", line 376, in _setup
    self._wrapped = self._setupfunc()
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/django/contrib/auth/middleware.py", line 23, in <lambda>
    request.user = SimpleLazyObject(lambda: get_user(request))
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/django/contrib/auth/middleware.py", line 11, in get_user
    request._cached_user = auth.get_user(request)
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/django/contrib/auth/__init__.py", line 174, in get_user
    user_id = _get_user_session_key(request)
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/django/contrib/auth/__init__.py", line 58, in _get_user_session_key
    return get_user_model()._meta.pk.to_python(request.session[SESSION_KEY])
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/django/contrib/sessions/backends/base.py", line 65, in __getitem__
    return self._session[key]
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/django/contrib/sessions/backends/base.py", line 220, in _get_session
    self._session_cache = self.load()
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/django/contrib/sessions/backends/db.py", line 44, in load
    return self.decode(s.session_data) if s else {}
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/django/contrib/sessions/backends/base.py", line 122, in decode
    return self._legacy_decode(session_data)
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/django/contrib/sessions/backends/base.py", line 126, in _legacy_decode
    encoded_data = base64.b64decode(session_data.encode('ascii'))
  File "/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/base64.py", line 87, in b64decode
    return binascii.a2b_base64(s)

Exception Type: Error at /users/
Exception Value: Invalid base64-encoded string: number of data characters (217) cannot be 1 more than a multiple of 4

serializers.py:
from django.contrib.auth.models import User, Group
from rest_framework import serializers

class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ['url', 'username', 'email', 'groups']

class GroupSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Group
        fields = ['url', 'name']

A: The reason this error crops up because you're on a wrong version of Django. If you haven't changed anything with the version of Django, then the issue most probably is that you've forgotten to activate your correct virtual environment.

A: Delete all old sessions from the DJANGO_SESSION table

A: I have the same problem, but I get the error when my Django version is 3.0.8 and when I upgrade it to 3.1, the problem has been fixed

A: Clear the browser cache and try again. :)

A: Really dont know why, but clear the cookies from browser fix the problem.

A: Clear your Browser cache and cookies of all time.

A: Clear your browsing history: cookies and other side data Then work


text:
Q: RubyMine 5.4 sinatra support I can't get the Sinatra support to work on RubyMine 5.4. Everything runs well but i would love to have some support from the RubyMine IDE.

A: Should I assume you have the rack gem installed?  Seems it would be unusual for that not to be the case, but it seems to be required.  EDIT: I would guess that, if Sinatra is used in place of Rails, it wouldn't be that unusual not to have rack.
From Rubymine 5.4.3.2.1 Help:

Gems sinatra and rack are supported With the 'sinatra' and
  'rack' gems installed, it is possible to create and run sinatra
  applications. Code completion, error and syntax highlighting are
  available.

I included it in my Gemfile, did a Bundle Install, and required it.  The result is displayed.
I did no further configuration than this, so I can't think of any settings that would be causing you a problem.
You can search at JetBrains, but I didn't see a hit there myself.  You can post an issue here.  Serge provides great support!  I should know, as I bug him all the time for help...


text:
Q: Big query sql Using lag function with missing days I am using sql in Big Query superset to create a pivot table to calculate the difference of a game between a range of days:
Game    Date        Sum     Prev_sum
First   2022-08-15  178.68
        2022-08-16  345.09  166.41
        2022-08-18  570.53  991.89   --wrong input ,missing day
        2022-08-19  173.69  -396.84
        2022-08-20  532.35  358.66
        2022-08-21  248.35  -284
Second  2022-08-17  518.59  600.53   --wrong input ,missing day
        2022-08-20  182.91  148.3
Third   2022-08-15  527.35
        2022-08-17  359.93  426.53
        2022-08-20  539.05  564.57
        2022-08-21  543.74  4.69

i m using
 select Date , SUM(Sum) ,
           SUM(Sum) -
           lag(SUM(Sum)) over(partition by Game order by min(Date) ASC)
   from my_table

ideally i would like to have the difference of sum between each row regardless of the date shown
Game    Date        Sum     Prev_sum
First   2022-08-15  178.68
        2022-08-16  345.09  166.41
        2022-08-18  570.53  225
        2022-08-19  173.69  -396.84
        2022-08-20  532.35  358.66
        2022-08-21  248.35  -284
Second  2022-08-17  518.59
        2022-08-20  182.91  -336

A: Consider below query:
SELECT Game, Date,
       Sum - LAG(Sum) OVER(PARTITION BY Game ORDER BY Date) Prev_sum
  FROM my_table
 ORDER BY 1, 2;

Query results:

Game
Date
Prev_sum

First
2022-08-15

First
2022-08-16
166.40999999999997

First
2022-08-18
225.44

First
2022-08-19
-396.84

First
2022-08-20
358.66

First
2022-08-21
-284.0

Second
2022-08-17

Second
2022-08-20
-335.68000000000006

Third
2022-08-15

Third
2022-08-17
-167.42000000000002

Third
2022-08-20
179.11999999999995

Third
2022-08-21
4.6900000000000546

Sample Table
create temp table my_table AS
select 'First' Game,   '2022-08-15' Date,  178.68  Sum union all
select 'First',   '2022-08-16',  345.09 union all
select 'First',   '2022-08-18',  570.53 union all
select 'First',   '2022-08-19',  173.69 union all
select 'First',   '2022-08-20',  532.35 union all
select 'First',   '2022-08-21',  248.35 union all
select 'Second',  '2022-08-17',  518.59 union all
select 'Second',  '2022-08-20',  182.91 union all
select 'Third',   '2022-08-15',  527.35 union all
select 'Third',   '2022-08-17',  359.93 union all
select 'Third',   '2022-08-20',  539.05 union all
select 'Third',   '2022-08-21',  543.74 ;


text:
Q: iOS 14 Crash on using banner ad with google admob on Flutter I imagine it can be hard to impossible to say anything about this but I wanted to give it a go anyway. I've just changed to using the google_mobile_ads library in my Flutter application to show banner ads. It works alright although I do see some performance issues in showing these in list. I reckon it is to do with the banner rendering as a webview which I can imagine is pretty slow.
Anyhow, on iOS I get crashes after having scrolled the list up and down quite a lot and it looks from the log as though it might have to do with the ad library.
I'm running on iPhone OS 14.4.2 (18D70) on a iPhone8,1. This is the log I get:
Exception Type:  EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Exception Note:  EXC_CORPSE_NOTIFY
Triggered by Thread:  0

Application Specific Information:
abort() called

Last Exception Backtrace:
0   CoreFoundation                  0x1a08b19d8 __exceptionPreprocess + 216
1   libobjc.A.dylib                 0x1b4c34b54 objc_exception_throw + 55
2   CoreFoundation                  0x1a091bd98 _CFThrowFormattedException + 111
3   CoreFoundation                  0x1a09271f4 -[__NSPlaceholderDictionary initWithObjects:forKeys:count:].cold.4 + 47
4   CoreFoundation                  0x1a07ac8a8 -[__NSPlaceholderDictionary initWithObjects:forKeys:count:] + 239
5   CoreFoundation                  0x1a079fc04 +[NSDictionary dictionaryWithObjects:forKeys:count:] + 55
6   Runner                          0x1006d7688 -[FLTAdInstanceManager onAdLoaded:responseInfo:] + 2340488 (FLTAdInstanceManager_Internal.m:82)
7   Runner                          0x1006d5268 -[FLTBannerAd bannerViewDidReceiveAd:] + 2331240 (FLTAd_Internal.m:207)
8   Runner                          0x1005ef224 GAD_GADBannerView_arm64_8_5_0 + 5139
9   Runner                          0x1006433f8 __destroy_helper_block_e8_32s40s48s56s64s72w + 159

Not sure if it could have to do with how I load the ad, but I've pretty much followed the example on the official codelabs. It looks like this:

void initState() {
  super.initState();

  final adUnit = DebugPlaceholder.isDebugMode
    ? debugAdUnit
    : liveAdUnit;

  _ad = BannerAd(
      adUnitId: adUnit,
      size: AdSize.largeBanner,
      request: AdRequest(),
      listener: BannerAdListener(
        onAdLoaded: (_) {
          setState(() {
            _adLoaded = true;
          });
        },
        onAdFailedToLoad: (ad, error) {
          _ad.dispose();
          print('Ad load failed (code=${error.code} message=${error.message})');
        }
      )
  );

  _ad.load();
}

@override
void dispose() {
  _ad.dispose();
  super.dispose();
}

@override
Widget build(BuildContext context) {
  if (!_adLoaded) return Container();

  return Container(
      color: Colors.white,
      alignment: Alignment.center,
      height: _ad.size.height.toDouble(),
      width: _ad.size.width.toDouble(),
      child: AdWidget(ad: _ad)
  );
}

Any tips, even if not on the actual problem but on how to troubleshoot it greatly appreciated!


text:
Q: Laravel eloquent relationship 4 table problem my db table is
===batches ===
id
batch_title

===courses===
id
course_title
batch_id

===students ===
id
name

===course_student===
course_id
student_id

now i want to show how many students are join in this batch and also how many students in this course
my Student model
public function courses()
{
    return $this->belongsToMany('App\Course');
}

Course Model
public function students(){

            return $this->hasManyThrough('App\Course','App\Student');
        }

    public function batch() {

                return $this->belongsTo('App\Batch','batch_id');
      }

Batch Model
public function courses(){
        return $this->hasOne('App\Course','batch_id');
    }

A: You have many weakness in your code:
first to should rebuild your many to many relation between Course and Student according to many to many doc
Student Model
public function courses()
{
    return $this->belongsToMany(Course::class);
}

Course Model
public function students()
{
    return $this->belongsToMany(Student::class);
}

now: to get how many Student in this course:
$value = Course->withCount('students')->find($courseId);

$studentsCount = $value->students_count;

$students_count will have the student count for Course with id = $couserId
if you want to get Student Count for specific Batch will may walk in the same way:
$coursesInBatch = Course->withCount('students')->where('batch_id',$batchId)->get();

now $coursesInBatch holds the courses for this batch including there students_count
$studentCountInBatch = 0;

foreach ($coursesInBatch as $course) {
    $studentCountInBatch += $course->students_count;
}

now $studentCountInBatch will hold how many student in Batch with id($batchId)


text:
Q: What does "what's the hangup?!" mean? On this page: http://bugs.mysql.com/bug.php?id=27645
There is a sentence:

All these database servers allow this, so what's the hangup?!

What does what's the hangup mean?

A: A "hangup" in this context (doesn't refer to someone hanging-up the phone on you), but rather, has the meaning of : (By Dictionary.com)

a source of annoying difficulty or burden; impediment; snag:

Your example in view of the definition above, is asking what the problem is, seeing that all databases allow "PostgreSQL,MSSQL, Oracle", what's stopping everyone from doing something (I'm not quite sure what the something, but it's got to do with adding a new option or something similar) in the past one year.
Perhaps, it could have the alternative meaning of "Psychological block", that is, someone's having problem accepting doing that "something" :

Hang-up : a preoccupation, fixation, or psychological block; complex

This could also apply to your context, in that, the commentor is saying, as all databases allow "PostgreSQL,MSSQL, Oracle", what's the problem(in a psychological sense this time), that's stopping everyone for the past year from doing that "something?"


text:
Q: Securing my API to only work with my front-end I'm building a node/express backend. I want to create an API that only work with my reactjs frontend (private API).
Imagine if this is an e-commerce website, my users will browse products and will then choose what to buy and at the time of order they might or might not login.
What is the best practice to make sure my APIs will only work with my reactjs frontend?
What happens when users decide to login or if they remain as guests?

A: This use case is an interesting one and I think a problem for many e-commerce sites. The product I am working on has actually had some conversations with companies trying to handle exactly this sort of thing in the mobile space. User logins can be used to tell you who is using the API, but if you don't want to force people to have a username/login you have to search for alternate solutions. What you seem to want is a way of identifying what software is attempting to use your API.
There are a couple of straightforward ways that are typically used to address this problem:
Embedded Secret
You can add a secret key to your app and require that any access to the API identifies itself using the key. People will tell you not to do this because it is really easy to extract the key. This is true, but with all security there is a cost/benefit analysis to be done to assess how much work you want to put in to protecting your API. The problem with javascript is that it is not that easy to obfuscate or hide secrets because all of the source code is right there.
If you were thinking about an environment where you had other options for your language choice then you can do more to obfuscate the secret in your app (like using the NDK in android for example). Javascript is difficult though.
The important thing to remember with an API key is that you shouldn't ever transmit it in the clear. It is really easy to steal it that way. Instead you would sign your API traffic using the key so that the server can verify that the request came from something that has the key and knows how to sign it.
Rate Limiting
Though not actually a solution to the problem, depending on what you are trying to achieve this is an option. If you are worried about large numbers of requests coming from other applications, you can rate limit to a level above what a genuine app would do and you could further block or rate limit by ip address if too many requests came in.

A: As of today, any user can see what is being passed to your backend by inspecting the network tabs in your browser console. The only way to ensure your api is secured is through user's authentication using JWT or the likes. If your app is opened to guest users, then cors cannot really help because all a user has to do is make requests identical to what they've seen in the browser's console to your apis through curl or postman.

A: I took help from the above-mentioned solution by @ThePragmatist.
I have a few environment-based configs on my React website like backend API base URL (ex. staging-api.test.com, dev-api.test.com), the current domain name (ex. staging.test.com, dev.test.com), etc. so I used the variables to create a token to be sent on each public request (from a public request I mean the requests that don't need authorization). So the process I followed:
On Client side:

*

*Create a string with user-agent/IP/something else from the header + request timestamp + _ + random 6 digit string

*Create a JWT token using any environment config (I used the combination of few like backend_api + domain + another config) as the secret key and the string generated in above step

*Send the generated token in a custom header named token
On server-side to verify:

*

*A middleware is used to authenticate any public API request which has the Redis implementation to stop the user to use the same token for a new request.

*Verify the JWT token received in the header token. If JWT can verify, then process ahead otherwise return with 403

*Check the timestamp received in the request. If the timestamp is of 2 mins or earlier, reject the request with 524 (or something else according to your need) otherwise move ahead

*Check if the token has a random 6 digit string at the end. If not, reject the request as the format of the token was wrong

*Check if a redis-key for the mentioned token header value exists. If it does, that means the same header was used in a request earlier, then simply reject the request with 403 otherwise move ahead

*Save the token header in Redis with expire time of 2 mins + 10 seconds (took 10 seconds extra just for a buffer)

This way, all the public requests will send a token which is hard enough to guess by the spammer/hacker as we used multiple configs as private-key to sign the header. Also, they won't be able to use the same header in another request. Only the client app will be able to generate the token as we followed multiple things like a header, the timestamp, a random string in the end (just to create some confusion), etc.
I hope it solves someone's query.
EDIT:
The random 6 digit string can be verified too on the server-side if we use TOTP (Time-based OTP) with an expiry time of 2-4 mins. This will make the generated token stronger as we will be able to verify every possible part of the token.

A: Apply CORS - server specifies domains allowed to request your API.
How does it work?

*

*Client sends special "preflight" request (of OPTIONS method) to server, asking whether domain request comes from is among allowed domains. It also asks whether request method is OKAY (you can allow GET, but deny POST, ...) .

*Server determines whether to allow, or deny request. It responds with "OK" response and set special headers that tell what domains/request methods are allowed.

*If client is allowed to query your API, it performs intended request, or bails out...

Clients that do respect CORS (browsers do) will be (or will not be if denied) able to connect. If client ignores CORS (REST clients, CLI tools, ...) it will be able to connect no matter what...
Still, require signed requests (authorisation)

A: I know this is late. But just putting my thoughts here.
Use of reCAPTCHA V3 might help in your case as the reCAPTCHA tokens can be created only in browser(depends on your configuration) and bound to a domains mentioned while creating the keys. When ever a request is made to backend, send the short-lived token created on the frontend. Backend can cross check the token and verify its validity.
Below code provides token using Google reCAPTCHA
<script src="https://www.google.com/recaptcha/enterprise.js?render=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"></script>
<script>
grecaptcha.enterprise.ready(function() {
    grecaptcha.enterprise.execute('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', {action: 'login'}).then(function(token) {
       ...
    });
});
</script>

A: So, this might be a slightly lengthy answer -- but you've posted a rather interesting and important question.
As someone who spends a majority of my time writing security libraries in Node and Python to handle this exact sort of thing, I figured I'd jump in here.
The protocol you want to use to protect your React app and backend API is the OAuth2 Password Grant flow. The way it works in theory is quite simple.
On your React app, you collect a user's username/password (this could also be an email/password if that's how you've structured your application).
You then send a POST request to your backend API that looks something like this:
POST api.myapp.com/oauth/token

grant_type=password&username=USERNAME&password=PASSWORD

Make sure you use the application/x-www-form-urlencoded content type when posting to your server.
Your server will then take this request, run it through an OAuth2 library, and generate two tokens: and Access and Refresh token.
Once you've got the tokens generated on your server side API, you'll then store those tokens in a cookie which will then be stored by the user's browser.
From this point on: everything should be automatic. When your React server makes API requests to your backend, the browser will identify the user via that cookie containing those two tokens automatically.
You'll need to use an OAuth2 library for your server-side, as this will handle things like:

*

*Generating tokens.

*Exchanging a Refresh token for a new Access token when it expires.

*Identifying the user based on the tokens.

*Revoking tokens if they are compromised, etc.

There's quite a lot more to it, but this is the basic, high level idea.
As you'll notice: there are no API keys involved here. When you're working with untrusted environments (eg: mobile apps, or client side javascript apps) it is completely unsafe to store permanent API tokens -- the reason is that they can be easily extracted from source code, or javascript.
Using the flow mentioned above instead is much safer, as you get a lot of protection:

*

*No permanent credentials stored in an unsafe location.

*Short-lived tokens are used as identifiers. These are rotated over time.

*Tokens are stored in cookies that are NOT accessible to Javascript. This means less risk of web exposure.

*Password are only exchanged once, for the duration of a session -- this means less sensitive information is going over wire less frequently =)

Anyhow: hope this helps!
And, if you're looking for some tools, any oauth library (server-side) should help you with this stuff. If you're looking for a service that can do this for you, you might want to check out the product I work on (Stormpath). It's a paid service, but handles a lot of this complexity on your behalf.