text:
Q: SHBrowseForFolder on WinCE does not layout correctly I'm attempting to p/invoke the SHBrowseForFolder API to prompt the user to select a folder and I am seeing the title static / label field float on top of the tree control.

The code was downloaded from an article referenced in multiple place on the net and the converted from C# to VB.NET (it was being dropped into an existing app).
If anyone has any tips on either getting this to layout correctly, please enlighten me.
The calling code is simple:
  Using getLocDialog As New FolderBrowserDialog()

     getLocDialog.Description = "This is a test"
     getLocDialog.ShowDialog()

  End Using

Next, here is the VB.NET version of the code:
Public Class FolderBrowserDialog
   Inherits CommonDialog

   '---------------------------------------------------------------------------
   ' instance
   '---------------------------------------------------------------------------

   Private info As BrowseInfo
   Private folder As String = String.Empty

   '---------------------------------------------------------------------------
   ' ctor
   '---------------------------------------------------------------------------

   Public Sub New()
      info = New BrowseInfo()
      info.Title = String.Empty
      InitCommonControls()
   End Sub

   '---------------------------------------------------------------------------
   ' public
   '---------------------------------------------------------------------------

   Public Shadows Function ShowDialog() As DialogResult

      Dim pitemidlist As IntPtr

      Try
         pitemidlist = SHBrowseForFolder(info.ToByteArray())
      Catch mme As MissingMethodException
         Throw New PlatformNotSupportedException("Your platform doesn't support the SHBrowseForFolder API", mme)
      End Try

      If pitemidlist = IntPtr.Zero Then
         Return DialogResult.Cancel
      End If

      '//maxpath unicode chars
      Dim buffer As Byte() = New Byte(519) {}
      Dim success As Boolean = SHGetPathFromIDList(pitemidlist, buffer)
      '//get string from buffer
      If success Then

         folder = System.Text.Encoding.Unicode.GetString(buffer, 0, buffer.Length)

         Dim nullindex As Integer = folder.IndexOf(Convert.ToChar(0))
         If nullindex <> -1 Then
            folder = folder.Substring(0, nullindex)
         End If
      End If
      LocalFree(pitemidlist)

      Return DialogResult.OK

   End Function

   Public ReadOnly Property SelectedPath() As String
      Get
         Return folder
      End Get
   End Property

   Public Property Description() As String
      Get
         Return info.Title
      End Get
      Set(ByVal value As String)
         info.Title = value
      End Set
   End Property

   '---------------------------------------------------------------------------
   ' private
   '---------------------------------------------------------------------------

   <DllImport("commctrl", SetLastError:=True)> _
   Private Shared Sub InitCommonControls()
   End Sub

   <DllImport("ceshell", SetLastError:=True)> _
   Private Shared Function SHBrowseForFolder(ByVal lpbi As Byte()) As IntPtr
   End Function

   <DllImport("ceshell", SetLastError:=True)> _
   Private Shared Function SHGetPathFromIDList(ByVal pidl As IntPtr, ByVal pszPath As Byte()) As Boolean
   End Function

   <DllImport("coredll", SetLastError:=True)> _
   Private Shared Function LocalFree(ByVal ptr As IntPtr) As IntPtr
   End Function

   '---------------------------------------------------------------------------
   ' inner classes
   '---------------------------------------------------------------------------

   Private Class BrowseInfo

      Private m_data As Byte()
      Private m_displayname As Byte()
      Private m_title As Byte()
      Private namehandle As GCHandle
      Private titlehandle As GCHandle

      Public Sub New()

         m_data = New Byte(31) {}
         m_displayname = New Byte(511) {}
         m_title = New Byte(127) {}

         namehandle = GCHandle.Alloc(m_displayname, GCHandleType.Pinned)
         titlehandle = GCHandle.Alloc(m_title, GCHandleType.Pinned)

         BitConverter.GetBytes(namehandle.AddrOfPinnedObject().ToInt32 + 4).CopyTo(m_data, 8)
         BitConverter.GetBytes(titlehandle.AddrOfPinnedObject().ToInt32 + 4).CopyTo(m_data, 12)

      End Sub

      Public Function ToByteArray() As Byte()
         Return m_data
      End Function

      Protected Overrides Sub Finalize()
         namehandle.Free()
         titlehandle.Free()
         MyBase.Finalize()
      End Sub

      Public Property Title() As String
         Get
            Dim ttl As String = System.Text.Encoding.Unicode.GetString(m_title, 0, m_title.Length)
            Dim nullindex As Integer = ttl.IndexOf(Convert.ToChar(0))
            If nullindex = -1 Then

               Return ttl
            End If
            Return ttl.Substring(0, ttl.IndexOf(Convert.ToChar(0)))
         End Get
         Set(ByVal value As String)
            Dim titlebytes As Byte() = System.Text.Encoding.Unicode.GetBytes(value & Convert.ToChar(0))
            If titlebytes.Length > m_title.Length Then
               Throw New ArgumentException("Description must be no longer than 64 characters")
            End If
            Try
               Buffer.BlockCopy(titlebytes, 0, m_title, 0, titlebytes.Length)
            Catch ex As Exception
            End Try
         End Set
      End Property

      Public Property FileName() As String
         Get
            Dim fn As String = System.Text.Encoding.Unicode.GetString(m_displayname, 0, m_displayname.Length)
            Dim nullindex As Integer = fn.IndexOf(Convert.ToChar(0))
            If nullindex = -1 Then
               Return fn
            End If
            Return fn.Substring(0, fn.IndexOf(Convert.ToChar(0)))
         End Get
         Set(ByVal value As String)
            Dim filenamebytes As Byte() = System.Text.Encoding.Unicode.GetBytes(value & Convert.ToChar(0))
            If filenamebytes.Length > m_title.Length Then
               Throw New ArgumentException("SelectedFolder must be no longer than 256 characters")
            End If
            Buffer.BlockCopy(filenamebytes, 0, m_displayname, 0, filenamebytes.Length)
         End Set
      End Property

      '/*HWND hwndOwner;
      'LPCITEMIDLIST pidlRoot;
      'LPTSTR pszDisplayName;
      'LPCTSTR lpszTitle;
      'UINT ulFlags;
      'BFFCALLBACK lpfn;
      'LPARAM lParam;
      'int iImage;*/

   End Class

End Class

The original C# was this:
public class FolderBrowserDialog : CommonDialog
    {
        private BrowseInfo info;
        private string folder = string.Empty;

        /// <summary>
        /// Initializes a new instance of the FolderBrowserDialog class.
        /// </summary>
        public FolderBrowserDialog()
        {
            info = new BrowseInfo();
            info.Title = string.Empty;
            InitCommonControls();
        }

        /// <summary>
        /// Runs a common dialog box with a default owner.
        /// </summary>
        /// <returns></returns>
        public new DialogResult ShowDialog()
        {
            IntPtr pitemidlist;

            try
            {
                pitemidlist = SHBrowseForFolder(info.ToByteArray());
            }
            catch(MissingMethodException mme)
            {
                throw new PlatformNotSupportedException("Your platform doesn't support the SHBrowseForFolder API",mme);
            }

            if(pitemidlist==IntPtr.Zero)
            {
                return DialogResult.Cancel;
            }

            //maxpath unicode chars
            byte[] buffer = new byte[520];
            bool success = SHGetPathFromIDList(pitemidlist, buffer);
            //get string from buffer
            if(success)
            {
                folder = System.Text.Encoding.Unicode.GetString(buffer, 0, buffer.Length);

                int nullindex = folder.IndexOf('\0');
                if(nullindex!=-1)
                {
                    folder = folder.Substring(0, nullindex);
                }
            }
            LocalFree(pitemidlist);

            return DialogResult.OK;
        }

        /// <summary>
        /// Gets the path selected by the user.
        /// </summary>
        public string SelectedPath
        {
            get
            {
                return folder;
            }
        }

        /// <summary>
        /// Gets or sets the descriptive text displayed above the tree view control in the dialog box.
        /// </summary>
        public string Description
        {
            get
            {
                return info.Title;
            }
            set
            {
                info.Title = value;
            }
        }

        #region P/Invokes

        [DllImport("commctrl", SetLastError=true)]
        private static extern void InitCommonControls();

        [DllImport("ceshell", SetLastError=true)]
        private static extern IntPtr SHBrowseForFolder(byte[] lpbi);

        [DllImport("ceshell", SetLastError=true)]
        private static extern bool SHGetPathFromIDList(IntPtr pidl, byte[] pszPath);

        [DllImport("coredll", SetLastError=true)]
        private static extern IntPtr LocalFree(IntPtr ptr);

        #endregion

        #region helper class for BROWSEINFO struct
        private class BrowseInfo
        {
            private byte[] m_data;
            private byte[] m_displayname;
            private byte[] m_title;
            private GCHandle namehandle;
            private GCHandle titlehandle;

            public BrowseInfo()
            {
                m_data = new byte[32];
                m_displayname = new byte[512];
                m_title = new byte[128];

                namehandle = GCHandle.Alloc(m_displayname, GCHandleType.Pinned);
                titlehandle = GCHandle.Alloc(m_title, GCHandleType.Pinned);

                BitConverter.GetBytes((int)namehandle.AddrOfPinnedObject() + 4).CopyTo(m_data, 8);
                BitConverter.GetBytes((int)titlehandle.AddrOfPinnedObject() + 4).CopyTo(m_data, 12);
            }

            public byte[] ToByteArray()
            {
                return m_data;
            }

            ~BrowseInfo()
            {
                namehandle.Free();
                titlehandle.Free();
            }

            public string Title
            {
                get
                {
                    string title = System.Text.Encoding.Unicode.GetString(m_title, 0, m_title.Length);
                    int nullindex = title.IndexOf('\0');
                    if(nullindex==-1)
                    {
                        return title;
                    }
                    return title.Substring(0, title.IndexOf('\0'));
                }
                set
                {
                    byte[] titlebytes = System.Text.Encoding.Unicode.GetBytes(value + '\0');
                    if(titlebytes.Length > m_title.Length)
                    {
                        throw new ArgumentException("Description must be no longer than 64 characters");
                    }
                    try
                    {
                        Buffer.BlockCopy(titlebytes, 0, m_title,0, titlebytes.Length);
                    }
                    catch
                    {
                    }
                }
            }

            public string FileName
            {
                get
                {
                    string filename = System.Text.Encoding.Unicode.GetString(m_displayname, 0, m_displayname.Length);
                    int nullindex = filename.IndexOf('\0');
                    if(nullindex==-1)
                    {
                        return filename;
                    }
                    return filename.Substring(0, filename.IndexOf('\0'));
                }
                set
                {
                    byte[] filenamebytes = System.Text.Encoding.Unicode.GetBytes(value + '\0');
                    if(filenamebytes.Length > m_title.Length)
                    {
                        throw new ArgumentException("SelectedFolder must be no longer than 256 characters");
                    }
                    Buffer.BlockCopy(filenamebytes, 0, m_displayname,0, filenamebytes.Length);
                }
            }

                        /*HWND hwndOwner;
                        LPCITEMIDLIST pidlRoot;
                        LPTSTR pszDisplayName;
                        LPCTSTR lpszTitle;
                        UINT ulFlags;
                        BFFCALLBACK lpfn;
                        LPARAM lParam;
                        int iImage;*/

        }
        #endregion
    }

Additional details:  Dev environment is Visual Studio 2008, Compact Framework 3.5.  The device runs Windows CE 4.2.

A: I had the same experience with SHBrowseForFolder, that FolderBrowserDialog and Windows CE 5.0.
A workaround could be to set BIF_STATUSTEXT for the flags. This way the layout is displaced and the title appears above the TreeView.
To do this, add a data member uint m_flags to the BrowseInfo class. In it's constructor add :
const uint BIF_STATUSTEXT = 0x00000004;
m_flags |= BIF_STATUSTEXT;

And in the ToByteArray() method add:
BitConverter.GetBytes(m_flags).CopyTo(m_data, 16);


text:
Q: read a content from a file and store it in database tables in ruby I am having some content in file. I already read the specific needed content and store it in one array and variables
Now i need to pass those value of the array and variable to the created table in database
Please help me to do this.
con = PG.connect :dbname => 'user1', :user => 'user1'
puts con.server_version
con.exec "SELECT exists(select schema_name FROM information_schema.schemata WHERE schema_name = 'testing');"
con.exec "set search_path TO testing;"
con.exec "create table table1(name varchar());"

Now lets say i am having the below value,
a="someone"

How do i insert that value to the table.
Thanks in advance.

A: We have to parse the value like this,
con.exec "insert into xox values('#{a}');"

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is Einstein-Hilbert action the unique action whose variation gives Einstein's field equations? I know that

*

*scaling the action with a non-zero multiplicative constant, or

*adding a total divergence term to the Lagrangian density
do not change the Euler-Lagrange equations, cf. e.g. this Phys.SE post.
Apart from such trivial modifications (1&2), is Einstein-Hilbert action the unique action whose variation gives Einstein's field equations? If not, is there any other action known which differs non-trivially from Einstein-Hilbert action and whose variation gives Einstein's equations?

A: In some sense, yes it is, and in others it is certainly not.
The fact that in the Einstein field equations:
$G_{\mu \nu} = 8 \pi T_{\mu \nu}$, you have complete 'freedom' to define $T_{\mu \nu}$ however you would like (within some kind of exceptions), means  you can allow for highly non-trivial curvature dependent terms to be coupled to the stress-energy. See this really interesting paper by Capozziello et al (http://arxiv.org/abs/grqc/0703067) that shows how you can 'bunch' the additional curvature terms for an $f(R)$ gravity into the 'effective' stress-energy tensor. In this way, the uniqueness of what you may call the 'Einstein' field equations does not hold.
However, once one moves to the vacuum the answer is suddently a definitive yes. The Einstein equations are generated by having an action that contains a geometric invariant quantity. If it did not then the principles of general covariance would no longer hold since arbitrary coordinate transformations would necessarily destroy the gauge symmetries. Now, that being said, one can consider the most general possible geometric invariant Lagrangian in this sense, it would look something like.. $\mathcal{L} = f(g_{\mu \nu} R^{\mu \nu}, R^{\mu \nu} R_{\mu \nu}, R^{\alpha \beta \gamma \delta} R_{\alpha \beta \gamma \delta}, C^{\alpha \beta \gamma \delta} C_{\alpha \beta \gamma \delta}, g^{\mu \nu} R^{\alpha \beta} R_{\alpha \beta \mu \nu}...)$ and the list of possibilities goes on. Since you want to replicate the Einstein equations in themselves you can immediatly throw away all but the linear terms in the above. Any of the other variants when you perform the calculus of variations gives you higher than second order derivatives.
Now, keeping only the linear terms you see that the action will necessarily be the Einstein-Hilbert one plus (maybe) some other curvature invariants. Since these will not vanish once you perform the variation, unless they either vanish identically or vanish on the boundary as a divergence term, your field equations will necessarily still be the Einstein-Hilbert ones provided you only keep $\mathcal{L} = R^{\sigma}_{\sigma}$.
A rigorous proof of this would be interesting. I am unaware of any in the literature.

A: The so-called spin content of GR with respect to the restricted Lorentz group is made of weight (also called spin) = 2 tensor fields which can be taken to be the linearized gravity field of Einstein and Fierz-Pauli (this is also known as the Pauli-Fierz field, after Pauli and Fierz's articles of 1939 in Helv. Phys. Acta and PRSL). In 2000 here http://arxiv.org/abs/hep-th/0007220 it is shown (as a particular case) using BRST (antifield) perturbation theory, that the cubic vertex of the single graviton theory is unique, hence the only way gravitons can self-couple is the E-H action + the cosmological term.
Regarding point 2 of your post: boundary terms in curved space-time are a most delicate subject and a careful analysis needs to be performed. You are invited to read the relevant section of Wald's GR test.
Another useful read would be the whole book and especially the chapter 8 of http://www.amazon.com/Tensors-Differential-Variational-Principles-Mathematics/dp/0486658406/ref=sr_1_1?ie=UTF8&qid=1392672388&sr=8-1&keywords=Lovelock+Tensors

A: You can also add terms that allow for the nonmetricity and torsion of the connection, and then constrain these terms to zero by explicit constraints.


text:
Q: How do I choose an appropriate max_children value for Sphinx? We have a Sphinx install (2.0.3) running on a cluster of 3 EC2 instances (currently m3.large).
Currently we have workers = threads and max_children = 30 in our Sphinx config (same on each box).  We are periodically getting the dreaded "temporary searchd error: server maxed out, retry in a second".  Our instances are hovering around 5% CPU utilization.  Some example top output:
top - 19:51:56 up 22:15,  1 user,  load average: 0.08, 0.04, 0.01
Tasks:  82 total,   2 running,  80 sleeping,   0 stopped,   0 zombie
Cpu(s):  1.0%us,  0.0%sy,  0.0%ni, 98.5%id,  0.3%wa,  0.0%hi,  0.0%si,  0.2%st
Mem:   7872040k total,  2911920k used,  4960120k free,   245168k buffers
Swap:        0k total,        0k used,        0k free,  2190992k cached

All the Sphinx doc seems to say about setting max_children is that it is "useful to control server load".  While searching I found a forum post indicating that setting it either too high or too low can cause "server maxed out" - I presume the former is because the individual queries are starved - but had no further tips on choosing the right level.  (I can't find the link to this post again to save my life.  Sorry.)
Two related questions:

*

*Am I right in thinking the low CPU suggests max_children could/should be higher than 30?

*How can I find the optimal number (i.e., the max number of children which [usually] does not lead to query slowdown)?  I'm not entirely sure what kind of info Sphinx logs beyond query.log.  Is there a tool I can use to determine whether query slowdown is occurring (due to too many parallel queries), and if not, are queries CPU-bound or memory-bound (or should I be looking at some other value entirely)?


text:
Q: Scroll ScrollView to top on content change, without glitching (React Native) I have a ScrollView component (in React Native [iOS]) that is vertically-paged and populated with full-height images.
The result is a vertically-swipable 'gallery' of images that I only want a user to be able to scroll past once.
When onMomentumScrollEnd is triggered, I delete the top-most image, and reset the scroll offset to zero. However, due to the state-change of the image content, the scrollTo call does not sync and results in visual glitching (i.e. the topmost image flashes as it is deleted). I've tried putting my scrollTo call after a state-change, to no avail.
I also tried it in the onContentSizeChange trigger, such as:
//...<ScrollView> props:
onContentSizeChange={(contentWidth, contentHeight)=>{
  this.photoScroll.scrollTo({x: 0, y: 0, animated: false});
}}

Is there any way to 'sync' a ScrollView's content adjustment with a scrollTo({x: 0, y: 0, animated: false}) call?
Note: I am using create-react-native-app and would really rather not have to eject — as a former iOS dev, I am aware there are libraries out there that can handle this kind of behaviour, but I was hoping to achieve this with vanilla-React somehow.
Note 2: Principally interested in iOS implementations for now — Android is a bonus.
Code Appendix:
Scroll View Component:
  <ScrollView
    ref={(ref) => this.photoScroll = ref}
    pagingEnabled
    style={{
      flex: 1,
    }}
    onScroll={this.onScroll}
    scrollEventThrottle={16}
    scrollEnabled={this.scrollEnabled}
    pinchGestureEnabled={false}
    onMomentumScrollBegin={this.onMomentumScroll}
    onMomentumScrollEnd={this.offMomentumScroll}
    onContentSizeChange={(contentWidth, contentHeight)=>{
      this.photoScroll.scrollTo({x: 0, y: 0, animated: false});
    }}
  >
    {/* Array of image source-views, stored in State */}
    {demoImages}
  </ScrollView>

Class Method for removing image data:
  offMomentumScroll = (event) => { // onMomentumScrollEnd
    this.isScrolling = false;
    this.shouldCancelScroll = false; // used to block touches
    this.recalibratePhotos();
  }

  recalibratePhotos = () => {
    const { height, width } = Dimensions.get('window');
    const { scrollOffset } = this;
    const numberToDelete = scrollOffset / height;

    let photoData = this.state.photoData.slice();
    photoData.splice(0, numberToDelete);

    this.setState({
      photoData,
    }, () => {
      this.scrollEnabled = true; // used to block extra touches
      // onScroll has also appeared here — still glitches
    });

  }


text:
Q: How can I fetch the media files of the products in Shopware 6 using Rest API? I am beginner to Shopware and following documentation most of the time. According to the documentation for REST API https://docs.shopware.com/en/shopware-platform-dev-en/how-to/working-with-the-api-and-an-http-client
I can retrieve product data by calling the request function
$this->restService->request('GET', 'product');

Basically, it makes following request which is returning me product data.
private function createShopwareApiRequest(string $method, string $uri, ?string $body = null): RequestInterface
{
    return new Request(
        $method,
        getenv('APP_URL') . '/api/v3/' . $uri,
        [
            'Authorization' => 'Bearer ' . $this->accessToken,
            'Accept' => '*/*'
        ],
        $body
    );
}

I couldn't find the media files related to the product. Can anybody help me how can I fetch products along with the images ?

A: You need to add association parameter to your request. In the case of GET product request it should look like this /api/v3/product?associations[media][]
When you did it in product response you will get objects like this:
"media": {
            "data": [
                {
                    "type": "product_media",
                    "id": "41e9b70e1df84b999bbf08ce7bf3fb77"
                }
            ],
            "links": {
                "related": "http://localhost:8000/api/v3/product/a1d20f10d019491fbf889ad5651aab23/media"
            }
        },

by product media id, you can find the full object in included object of your response and real mediaId inside. Then search media object in included by mediaId.
{
        "id": "41e9b70e1df84b999bbf08ce7bf3fb77",
        "type": "product_media",
        "attributes": {
            "versionId": "0fa91ce3e96a4bc2be4bd9ce752c3425",
            "productId": "a1d20f10d019491fbf889ad5651aab23",
            "productVersionId": "0fa91ce3e96a4bc2be4bd9ce752c3425",
            "mediaId": "1bf12b4bae5e4d288ce049aacfd2cc24",
            "position": 1,
            "customFields": null,
            "createdAt": "2020-05-22T13:10:37.255+00:00",
            "updatedAt": null,
            "apiAlias": null
        }
},
{
        "id": "1bf12b4bae5e4d288ce049aacfd2cc24",
        "type": "media",
        "attributes": {
            "userId": null,
            "mediaFolderId": "fd22d1ef41994f6ea05f9b4cb01d85d3",
            "mimeType": "image/jpeg",
            "fileExtension": "jpg",
            "uploadedAt": "2020-05-22T13:10:37.227+00:00",
            "fileName": "10062415_1",
            "fileSize": 74503,
            "metaData": {
                "type": 2,
                "width": 1500,
                "height": 1000
            },
            "mediaType": {
                "name": "IMAGE",
                "flags": [],
                "extensions": []
            }
}


text:
Q: Objects are not created when they should be I'm currently making a relatively small project in Qt. There are 2 objects and 2 vectors that have to be available throughout the whole program life. So to achieve that, I made 4 declarations in corresponding header files, marked them extern and defined them in MainWindow.cpp where i use them for the first time.
However, runtime error std::out_of_range occurs when one of the object is being created. After long session of debugging i finally found the cause and source of error :
MainWindow.cpp
#include "task.h"  //Vectors; Works
#include "date.h" //Error
#include "db.h"  //Works

std::vector<Task> task_vec; //extern from task.h
std::vector<Group> group_vec; //extern from task.h
Date date; //extern from date.h <- Error when instantinating this one
Database db; //extern from db.h

MainWindow::MainWindow(){//...}
//date and db objects are used in this file

date.cpp
#include "date.h" //it has "consants.h" included in it

//..Stuff
Date::Date()
{
    //Use const int variable from "constants.h"
    year = constants::START_YEAR; //Works, START_YEAR is initialized
    year_count = constants::YEAR_COUNT //Works aswell
    Month month(m, y);
}
Month::Month(int month, int year)
{
    //Use const std::map<QString, std::pair<int,int>> from "constants.h"
    day_count = constants::MONTH_DAY_MAP_LY.at(0).second //ERROR, MONTH_DAY_MAP_LY is not initialized
}

constants.h
namespace constants {
const int START_YEAR = 2016;
const int YEAR_COUNT = 83;

const QList<QString> MONTH { "January", "February", "March",
        "April", "May", "June", "July", "August", "September", "October", "November", "December"};

const std::map<QString, std::pair<int, int>> MONTH_DAY_MAP{
    {MONTH[0], std::make_pair(0, 31)}, {MONTH[1], std::make_pair(1, 28)}, {MONTH[2], std::make_pair(2, 31)},
    {MONTH[3], std::make_pair(3, 30)}, {MONTH[4], std::make_pair(4, 31)}, {MONTH[5], std::make_pair(5, 30)},
    {MONTH[6], std::make_pair(6, 31)}, {MONTH[7], std::make_pair(7, 31)}, {MONTH[8], std::make_pair(8, 30)},
    {MONTH[9], std::make_pair(9, 31)}, {MONTH[10], std::make_pair(10, 30)}, {MONTH[11], std::make_pair(11, 31)}
};
const std::map<QString, std::pair<int, int>> MONTH_DAY_MAP_LY {
    {MONTH[0], std::make_pair(0, 31)}, {MONTH[1], std::make_pair(1, 29)}, {MONTH[2], std::make_pair(2, 31)},
    {MONTH[3], std::make_pair(3, 30)}, {MONTH[4], std::make_pair(4, 31)}, {MONTH[5], std::make_pair(5, 30)},
    {MONTH[6], std::make_pair(6, 31)}, {MONTH[7], std::make_pair(7, 31)}, {MONTH[8], std::make_pair(8, 30)},
    {MONTH[9], std::make_pair(9, 31)}, {MONTH[10], std::make_pair(10, 30)}, {MONTH[11], std::make_pair(11, 31)}
};
}

I have no idea why. If the START_YEAR and YEAR_COUNT are initialized, then the rest of the header should be aswell, right?
Here's where i declare extern object:
date.h
//...Stuff
class Date
{
public:
    Date();

    Year& operator[](int);

private:
    std::array<Year, constants::YEAR_COUNT> date_arr;
} extern date;

A: date.cpp includes constants.h, which declares MONTH_DAY_MAP and MONTH_DAY_MAP_LY global objects; hence those global objects are defined in the date.cpp translation unit.
mainwindow.cpp declares its four global objects. It constructs a Date object. Date's constructor invokes Month's constructor, which references the globally-scoped objects from the date.cpp translation unit.
The problem is that C++ does not specify the relative order of initialization of globally scoped objects in different translation units. Global objects from different translation units can be initialized, at runtime, in any order.
In this case, at the time that mainwindow.cpp's globally scoped objects get constructed, mainwindow.cpp's globally scoped objects are not yet constructed, and accessing them results in undefined behavior, and a crash.
There are various solutions, and ways to deal with this static initialization order fiasco. You should find plenty of material to study and learn about, in Google.

A: You have several problems.
You violate the one definition rule. constants.h defines variables that get defined in each translation unit that includes that file. These constants should either be defined in an anonymous namespace, or declared in the header but defined in a .cpp file. The integer constants could be declared static: they can then be used in a context of constant expression even if the definition is missing.
The global variables will suffer from the undefined initialization order between multiple translation units. If any of them have interdependencies, even implicit ones, you'll end up using uninitialized data somewhere. So don't do that. Instead, use dependency injection, and consider a modern lightweight dependency injection framework like e.g. boost.DI.
You have a mismatch between the location of the definition and declaration of global variables. This doesn't lead to undefined behavior, but the developer's lives harder for no reason. If task_vec is declared in task.h, then it should be defined in task.cpp. Otherwise you're likely to thoroughly confuse yourself and any maintainers working on your project.


text:
Q: copy of select not working My XML:
<?xml version="1.0" encoding="utf-8"?>
 <Items>
  <Item>
   <Name>Ram-345D</Name>
   <Price>$21.00</Price>
   <Warranty>2 Years </Warranty>
  </Item>
 </Items>

My XSL:
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="Items">
        <xsl:copy-of select="/Item"/>
</xsl:template>
</xsl:stylesheet>

I want to select all the nodes and the elements of Item and display them. But my copy of select is not working. what have i done wrong?

A: You could adjust your XSLT as follows:
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes"/>
  <xsl:template match="/Items">
    <xsl:copy-of select="Item"/>
  </xsl:template>
</xsl:stylesheet>

to copy the Item elements as you requested:
<?xml version="1.0" encoding="UTF-8"?>
<Item>
    <Name>Ram-345D</Name>
    <Price>$21.00</Price>
    <Warranty>2 Years </Warranty>
  </Item>

But note if you have multiple Item elements, your output will not be well-formed XML document because it will lack a single root element.
Instead, consider starting with the identity transformation, and overriding it for those elements with which you'd like to do something different than copy exactly.
For example, this XSLT will copy everything over to the output except for the Price of Items named "Ram-345D", which it will change to "Free":
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes"/>
  <xsl:template match="node()|@*">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
  </xsl:template>
  <xsl:template match="Item[Name = 'Ram-345D']/Price">
    <Price>Free</Price>
  </xsl:template>
</xsl:stylesheet>

A: Your xpath is wrong. This should be
    <xsl:copy-of select="/Item"/>

this;
    <xsl:copy-of select="//Item"/>

then you will get the Items and its children with the elements,
<?xml version="1.0" encoding="UTF-8"?>
<Item>
   <Name>Ram-345D</Name>
   <Price>$21.00</Price>
   <Warranty>2 Years </Warranty>
</Item>


text:
Q: javascript concat running time If I have two arrays both with 10000 items, now I want to merge them into one array, so I do it with concat:
 array1=array1.concat(array2);

but does any body know what is the running time? constant or N? is there a better way to merger them in term of speed. thanks for any tips.

A: I doubt that the ECMAScript specification mandates any big-oh performance requirements for any operations, so it will be implementation dependent.  The only way to verify would be to write a benchmark and run it on your target interpreters.
That said, I would guess that most JavaScript interpreters implement Arrays as vector-type arrays rather than linked lists, so the concat operation is likely to be O(n) on most engines.


text:
Q: Same Query Same Server Different Filter Conditions on Dates I have a Query that's behaving differently for different dates. The Filer Condition in the Query is as below
Last_Update_Date>TO_DATE(SUBSTR('#BIAPPS.LAST_EXTRACT_DATE',0,19),'YYYY-MM-DD HH24:MI:SS')
The value for variable #BIAPPS.LAST_EXTRACT_DATE is being passed from a Application and datatype is Alphanumeric for #BIAPPS.LAST_EXTRACT_DATE.
If the Value passed to #BIAPPS.LAST_EXTRACT_DATE is 2017-12-20 00:00:00 this Query is extracting 200K records in 10 Mins.
If the Value passed to #BIAPPS.LAST_EXTRACT_DATE is 2018-01-02 00:00:00 this Query is extracting 80K records in 120 Mins.
Any Reason the Oracle behaves like this and Do I need to correct anything?

A: My guess is that in the first case it is using an index on LAST_EXTRACT_DATE, while in the second case it is not. (Another guess is that the reverse is true, and the query without the index is actually faster.)
The best first step to diagnose the problem is to view the execution plan for both queries.  If you don't know how to do that, you may find questions related to it here.  The quick way in SQLPlus is SET AUTOTRACE TRACEONLY EXPLAIN.
I assume you mean that you are doing text substitution into this query template, so from the Oracle parser's point of view they are two different queries.  One possible solution to your problem would be to use a bind variable instead, so the parser would see both as the same query and use the same execution plan. (At least, it probably would; in recent versions of Oracle there can be more variation for the same query.)  However, this could lead to a situation where you get the "bad" execution plan in more cases.
Based on the fact you are using very recent dates, a possible root cause is that the statistics on this table have been gathered sometime between the two dates in question.  So the parser has a good estimate of how many records the first query will return based on recorded column statistics and/or histogram; but for the second query it needs to do an extrapolation since the date is outside the range of values recorded in the statistics.  (I saw this a lot in a system I used to work on.)
In that case, another possible solution is to explicitly refresh statistics on that table every night.  This may not help if the query uses today's date, but if all the queries use dates before today, it may work well.
There are also various ways to force/guide Oracle to use a desired execution plan.  The old-fashioned one is explicit hinting.  In this case, if my first guess was correct, you might add an INDEX hint to the query.  There have been a number of features added to Oracle over the years to help with this.  I think the current primary one is called "SQL Plan Management" so you could research that.


text:
Q: Создание корректного запроса для поиска в SQLite Есть база данных SQLite куда импортирована база адресов - КЛАДР. Хочу сделать общий запрос для поиска по названию города/населённого пункта. Не очень понимаю как это можно реализовать по данной таблице. Пишу приложение на C# для поиска по этой базе, пока только додумался как сделать поиск по региону.
Пример запроса:
SELECT NAME, SOCR FROM KLADR WHERE substr(CODE, 3, 11) = '00000000000' AND (NAME LIKE '%{0}%' OR SOCR LIKE '%{0}%');

Только вот я ищу по региону, а мне необходимо чтобы возвращал таблицу совпадений по населенному пункту, как на этой картинке:

Структура CODE:
СС РРР ГГГ ППП УУУУ АА, где
СС - код субъекта РФ (региона)
РРР - код района
ГГГ - код города
ППП - код населенного пункта
УУУУ - код улицы (отсутствует у населенных пунктов)
АА - признак актуальности
Сама КЛАДР-база в формате SQLite - https://drive.google.com/file/d/1Mgw5TlJ_4pQs-X6m0z6ZjtCZIbdQUZa-/view?usp=sharing


text:
Q: How to handle repeating view element with backbone-stickit What is the best way to do a bindings for a repeating view element?
Here is a view fragment currently implemented with underscore template.
How can I replace this block with backbone.stickit ?
<% _.forEach(model.estimates, function(estimate) { %>

              <%= estimate.estimateNo %>
              <%= estimate.name %>
              <%= estimate.validity %>
              <%= estimate.grossPrice %>
              <%= estimate.status %>

<% }) %>

bindings: {
    '#estimateNo': ???,
    '#name': ???,
    '#validity': ???,
    '#grossPrice': ???,
    '#status': ???
}

A: I answer my own question...
there is a design issue with my view, i should move the content of the loop into a sub-view and use stickit for each individual view.
The loop should be in the code and not in the template ...


text:
Q: Upload Image to mySQL server using php in android Please bare my English
How can I upload the captured image in the database?
@Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate( savedInstanceState );
    setContentView( R.layout.activity_main );

    camera = (ImageButton) findViewById( R.id.camera );

    camera.setOnClickListener( new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog = new Dialog( MainActivity.this );
            dialog.setContentView( R.layout.camera_gallery );
            dialog.setTitle( "Upload Image" );
            dialog.setCancelable( true );
            dialog.show();

            capture = (Button) dialog.findViewById( R.id.capture );
            download = (Button) dialog.findViewById( R.id.download );

            capture.setOnClickListener( new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Intent intent = new Intent( MediaStore.ACTION_IMAGE_CAPTURE );
                    Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    getFileUri();
                    i.putExtra(MediaStore.EXTRA_OUTPUT, file_uri);
                    startActivityForResult(i, 10);
                }
            } );

            download.setOnClickListener( new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent( Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI );
                    intent.setType("image/*");
                    startActivityForResult( intent, gallery );
                }
            } );

        }
    } );

}

private void getFileUri() {
    image_name = "testing123.jpg";
    file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
            + File.separator + image_name
    );

    file_uri = Uri.fromFile(file);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

                    //code here
    }
}

Here I want to Add the captured image into my database that too in original size, not the thumbnail.
And I have one more regarding MySQL. Can we store the Image file in the database and if not then how do they store images.
And Also any suggestion to how to store my captured image in internal storage.

A: you can convert image to base64 format. for example:
    bitmap2 = MediaStore.Images.Media.getBitmap(activity.getContentResolver(), uri);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap2.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] imageBytes = baos.toByteArray();
    String ImageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);


text:
Q: Create List of unique elements and display group membership parsed by commas and en-dash I'm an Excel VBA newbie and I'm trying to figure out how to create a unique list of names in one column with associated group names in the next column.
For example, the Name "cds" is a member of the following groups: "group1","group3","group4","group5", and "group6".
I would like the output to show:
  |Column D   | Column E                 |
     cds          group1, group3–group6

I did find a Macro on a different message board that displays the unique element with the associated Group Number(s) instead of Group Name(s). Membership in consecutive group numbers are represented by the en-dash, otherwise group numbers are separated by commas.
The sample output below shows a list of Names and the associated Group Number which I have copied and pasted from another spreadsheet. The Macro creates the output found in Column D and Column E. Given the key shown in Columns G and H, Is it possible to replace the associated group numbers in Column E with the "Group Name" found in Column H? Thanks for your help!
       |Column A | Column B | Column C | Column D       | Column E  | Column F | Column G     |   Column H        |
Row 1    NAME       GROUP #              NAME (UNIQUE)    GROUP(#s)              Group # (Key)   Group Name (Key)
Row 2    cds         1                     abc             1, 9-10                   1            group1
Row 3    cds         3                     cds             1, 3, 4-6                 2            group2a
Row 4    cds         4                     xyz             7-8                       3            group3
Row 5    cds         5                     zzz             10                        4            group4b
Row 6    cds         6                                                               5            group5
Row 7    abc         10                                                              6            group6
Row 8    abc         9                                                               7            group7
Row 9    xyz         7                                                               8            group8_1
Row 10   xyz         8                                                               9            group9_Z
Row 11   zzz         10                                                              10           group10A

Here is the associated code I used:
Sub OrganizeByNumber()

Dim a, i As Long, e, x, temp, buff

a = Range("a2").CurrentRegion.Value

With CreateObject("Scripting.Dictionary")
   For i = 2 To UBound(a, 1)
     If Not .exists(a(i, 1)) Then
        Set .Item(a(i, 1)) = _
        CreateObject("System.Collections.ArrayList")
     End If
    .Item(a(i, 1)).Add a(i, 2)
   Next

   For Each e In .keys
     .Item(e).Sort
     x = .Item(e).ToArray
     temp = x(0) & Chr(150)

       If UBound(x) > 0 Then
          For i = 1 To UBound(x)
            If x(i) - x(i - 1) = 1 Then
               buff = x(i)
            Else
              temp = temp & buff
            If temp Like "*" & Chr(150) Then temp = Left$(temp, Len(temp) - 1)
              temp = temp & ", " & x(i) & Chr(150)
              buff = ""
       End If
   Next

     If buff <> "" Then
        temp = temp & buff
     Else
        temp = Left$(temp, Len(temp) - 1)
     End If
       .Item(e) = Array(e, temp)
     Else
       .Item(e) = Array(e, Replace(temp, Chr(150), ""))
     End If
   Next

 Range("d2").Resize(.Count, 2).Value = _
 Application.Transpose(Application.Transpose(.items))

End With

End Sub

A: It's just a matter of replacing the code numbers in the string with the matching group name.
I used the VLookup worksheet function, but, depending on the size of your data and the speed with which it runs, there are faster routines (especially with a sorted list).
Since the original code did not output the names in sorted order, I did not do that. But it should be fairly simple to implement. One way would be use the SortedList object.
Edit: As pointed out by @T.M. in the comments below, there is a bug in the routine.  The bug is actually in your original code, which I unfortunately assumed was working.
I didn't go into it in detail, but under certain circumstances, the buff variable is not getting cleared.
I have changed the code below to ensure buff is always cleared after processing; and I also added some code to sort the output by Name. The sorting code is taken from the link in the comments below.
EDIT2: Code added to remove instances where Name/Group# might be duplicated.
Option Explicit
Sub OrganizeByNumber()

Dim a, b, i As Long, e, x, temp, buff
Dim d As Object

a = Range("a2").CurrentRegion.Value
b = Range("g2").CurrentRegion.Value

Set d = CreateObject("Scripting.Dictionary")
With d
   For i = 2 To UBound(a, 1)
     If Not .exists(a(i, 1)) Then
        Set .Item(a(i, 1)) = _
        CreateObject("System.Collections.ArrayList")
     End If
    .Item(a(i, 1)).Add a(i, 2)
   Next i

   For Each e In .keys
     .Item(e).Sort

     deDupArrList .Item(e)

     x = .Item(e).ToArray

     'temp = x(0) & Chr(150)
     temp = WorksheetFunction.VLookup(x(0), b, 2, False) & Chr(150)

       If UBound(x) > 0 Then
          For i = 1 To UBound(x)
            If x(i) - x(i - 1) = 1 Then

               'buff = x(i)
               buff = WorksheetFunction.VLookup(x(i), b, 2, False)
            Else
              temp = temp & buff
            If temp Like "*" & Chr(150) Then temp = Left$(temp, Len(temp) - 1)

              'temp = temp & ", " & x(i) & Chr(150)
              temp = temp & ", " & WorksheetFunction.VLookup(x(i), b, 2, False) & Chr(150)

              buff = ""
            End If
          Next i

     If buff <> "" Then
        temp = temp & buff
     Else
        temp = Left$(temp, Len(temp) - 1)
     End If
       .Item(e) = Array(e, temp)
     Else
       .Item(e) = Array(e, Replace(temp, Chr(150), ""))
     End If

   buff = ""
   Next e

   sortDict d

 Range("d2").Resize(.Count, 2).Value = _
 Application.Transpose(Application.Transpose(.items))

End With

End Sub

Sub sortDict(dict As Object)
    Dim i As Long, key, al

    'With CreateObject("System.Collections.SortedList")
    Set al = CreateObject("System.Collections.SortedList")
    With al
        For Each key In dict
            .Add key, dict(key)
        Next
        dict.RemoveAll
        For i = 0 To .keys.Count - 1
            dict.Add .getkey(i), .Item(.getkey(i))
        Next
    End With
End Sub

Sub deDupArrList(arrList As Object)
    Dim i As Long
For i = arrList.Count - 1 To 0 Step -1
    If arrList.indexof(arrList(i), 0) <> i Then arrList.removeat i
Next i

End Sub


text:
Q: New value after applying css() in jQuery I'm scaling a div in order to be visible without scrolling. So I have:
var sliderOffset = $('.field-slideshow-wrapper').offset().top,
    windowHeight = $(window).height(),
    sliderAllowed = (windowHeight - sliderOffset),
    sliderImage = $('.field-slideshow-slide img').height(),
    sliderOriginal = (sliderImage + 150),
    scale = (sliderAllowed / sliderOriginal);

$('.field-slideshow-wrapper').css({ transform: 'scale(' + scale + ')'});

Now that div is not on the same position from top as before and I need to determine new offset from top, after css({ transform: 'scale(' + scale + ')' is applied, so I can calculate some margin to move this div at the top.
How to determine new offset().top of the element?

A: There are two ways you could do this and the choice is yours. The transform: scale() shrinks the element toward its center, so the top of the element moves down. The scaled element will still return the non-scaled element's offset().top, so that won't work.
One option is to just make sure the newly scaled element will stick to the top of the old element's space. Just do this:
$('.field-slideshow-wrapper').css({
    transform: 'scale(' + scale + ') translateY(-50%)'
});

This makes the element move up by 50% of its new height, thus sticking it to the top of its old dimensions.
The other option is to do some simple calculation. Get the old element's height, then get the number of pixels the scale() method has moved it "down". You can find the number  by some calculations (see below), and that's the number you can add to the old offset().top to get the new one:
var sliderOffset = $('.field-slideshow-wrapper').offset().top,
            windowHeight  = $(window).height(),
            elHeight = $('.field-slideshow-wrapper').innerHeight(),
            sliderAllowed   = (windowHeight - sliderOffset),
            sliderImage = $('.field-slideshow-slide img').height(),
            sliderOriginal = (sliderImage + 150),
            scale = (sliderAllowed / sliderOriginal);
var addProportion = 1-scale / 2;

var newOffset = sliderOffset + (addProportion * elHeight);

Whether you should use innerHeight() or outerHeight() depends on your layout.

A: well just get the new offset after you've applied the scaling
...
$('.field-slideshow-wrapper').css({ transform: 'scale(' + scale + ')'});
var newOffset = $('.field-slideshow-wrapper').offset().top;


text:
Q: Delphi 10.2 Tokyo:Listview Custom Component is not displaying any records when ViewStyle = vsReport we are migrating Delphi 7 code to Delphi 10.2 tokyo. As part of this we have migrated all the components. List view component is not working as expected. It is not displaying column headings and data when ViewStyle = vsReport and for other styles(VsIcon,VsList) it is displaying data and Headers.
About the component:
we have added additional property DataSet, user can set DataSet property at design time and the component will take care of opening the Dataset, setting column headings and adding data when user calls BuildListView Method of this component.This component has popup menu to add, delete and edit the selected item. i have deleted this popup menu code. since it is not required.
Here is the code:
This package has Runtime Package(64 bit) and Design time package (32 bit). Design time package has the code to register the component.
Run time pkg BPL Source:
package MylistView_rn;

{$R *.res}
{$IFDEF IMPLICITBUILDING This IFDEF should not be used by users}
{$ALIGN 8}
{$ASSERTIONS ON}
{$BOOLEVAL OFF}
{$DEBUGINFO OFF}
{$EXTENDEDSYNTAX ON}
{$IMPORTEDDATA ON}
{$IOCHECKS ON}
{$LOCALSYMBOLS ON}
{$LONGSTRINGS ON}
{$OPENSTRINGS ON}
{$OPTIMIZATION OFF}
{$OVERFLOWCHECKS OFF}
{$RANGECHECKS OFF}
{$REFERENCEINFO ON}
{$SAFEDIVIDE OFF}
{$STACKFRAMES ON}
{$TYPEDADDRESS OFF}
{$VARSTRINGCHECKS ON}
{$WRITEABLECONST OFF}
{$MINENUMSIZE 1}
{$IMAGEBASE $400000}
{$DEFINE DEBUG}
{$ENDIF IMPLICITBUILDING}
{$RUNONLY}
{$IMPLICITBUILD ON}

requires
  rtl,
  vcl,
  dbrtl,
  adortl,
  vcldb;

contains
  uMyListView1 in 'uMyListView1.pas';

end.

Run time package Unit Source(uMyListView1.pas):
unit uMyListView1;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  ComCtrls, Menus, DB, ExtCtrls, Buttons, ADODB;

const ARROW_SIZE = 10;

type

  TMyListView = class(TListView)
  private
    FDataSet:                   TCustomADODataSet;

    FPressedColumn:             integer; //column index
    FLastPressedColumn:         integer; //last column to be pressed
    FSortDir:                   integer; //-1 = descending, 1 = ascending
    FSortOrder:                 integer;

    FMyHeaderHandle:            HWND;
    FMyHeaderInstance:          Pointer;
    FMyDefHeaderWndProc:        Pointer;
    FHeaderPopupMenu:           TPopupMenu;

    FDragging:                  boolean;

    procedure SetListViewColumns;
    function  GetArrowPos(ColumnIndex: integer): TPoint;
    function  DeleteLastArrow(DC: HDC): boolean;
    function  DrawArrow(DC: HDC; Direction: integer; Offset: TPoint): boolean;
    function  DrawColText(DC: HDC; ColumnIndex: integer): boolean;

    procedure WndProc(var msg : TMessage); override;
    procedure MyHeaderWndProc(var Message: TMessage);
  protected
  public
    constructor Create(AOwner: TComponent); override;
    destructor  Destroy; override;
    function    BuildListView: boolean;
  published
    property DataSet: TCustomADODataSet read FDataSet write FDataSet;
  end;

implementation

constructor TMYListView.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  FPressedColumn     := -1;
  FLastPressedColumn := -1;
  FSortOrder         := 0;
  FDragging          := FALSE;

  FMyHeaderInstance := MakeObjectInstance(MyHeaderWndProc);
end;

destructor TMYListView.Destroy;
begin
  inherited Destroy;
end;

procedure TMYListView.WndProc(var msg : TMessage);
begin
  inherited WndProc(Msg);
  if (Msg.Msg = WM_PARENTNOTIFY) and (Msg.WParam = WM_CREATE) then
  Begin
    inherited;
    FMyHeaderHandle := Msg.lParam;
    FMyDefHeaderWndProc := Pointer(GetWindowLong(FMyHeaderHandle, GWL_WNDPROC));
    SetWindowLong(FMyHeaderHandle, GWL_WNDPROC, LongInt(FMyHeaderInstance));
  end;
end;

procedure TMYListView.MyHeaderWndProc(var Message: TMessage);
var DC: HDC;
    Pos: TPoint;
begin
  with Message do
  Begin
    Result := CallWindowProc(FMyDefHeaderWndProc, FMyHeaderHandle, Msg, WParam, LParam);

    if Msg = WM_RBUTTONDOWN then
    Begin
      Pos.x := lParamLo;
      Pos.y := lParamHi;
      Pos := ClientToScreen(Pos);
      FHeaderPopupMenu.Popup(Pos.x, Pos.y);
    end

    //Draw SortArrows
    else if Msg = WM_PAINT then
    Begin
      DC := GetDC(FMyHeaderHandle);
      DeleteLastArrow(DC);
      if (FPressedColumn > -1) then
      Begin
        DrawColText(DC, FPressedColumn);
        DrawArrow(DC, FSortDir, GetArrowPos(FPressedColumn));
      end;
    end;

  end;
end;

function TMYListView.DrawColText(DC: HDC; ColumnIndex: integer): boolean;
var ColTitle: string;
    Rect: TRect;
    TextAlign, i: integer;
    Brush: TBrush;
begin
  Result := FALSE;
  if FPressedColumn < 0 then Exit;

  ColTitle := Columns[ColumnIndex].Caption;
  while copy(ColTitle, length(ColTitle), 1) = '.' do ColTitle := copy(ColTitle, 1, Length(ColTitle) - 1);
  GetWindowRect(WindowFromDC(DC), Rect);
  with Rect do
  Begin
    Bottom := Bottom - Top - 2;
    Top := 2;
    Left := 6;

    for i := 0 to Columns.Count - 1 do
    Begin
      if Columns[i].Index = ColumnIndex then break;
      Left := Left + Columns[i].Width;
    end;

    Right := Left + Columns[ColumnIndex].Width - 8;
  end;

  Brush := TBrush.Create;
  with Brush do
  Begin
    Style := bsSolid;
    Color := clBtnFace;
    SelectObject(DC, Handle);
  end;
  FillRect(DC, Rect, Brush.Handle);

  TextAlign := DT_VCENTER;

  if Columns[i].Alignment = taRightJustify then
  Begin
    if (ColumnIndex = FPressedColumn) then Rect.Left := Rect.Left + ARROW_SIZE;
    Rect.Right := Rect.Right - 4;
    TextAlign := TextAlign + DT_RIGHT;
  end
  else
  Begin
    if (ColumnIndex = FPressedColumn) then Rect.Right := Rect.Right - ARROW_SIZE - 10;
    TextAlign := TextAlign + DT_LEFT;
  end;

  SelectObject(DC, Font.Handle);
  SetBkColor(DC, GetSysColor(COLOR_3DFACE));
  DrawTextEx(DC, PWideChar(ColTitle), Length(ColTitle), Rect, TextAlign + DT_END_ELLIPSIS, nil);
  Result := TRUE;
end;

function TMYListView.DeleteLastArrow(DC: HDC): boolean;
var Rect: TRect;
    Brush: TBrush;
begin
  Result := FALSE;
  if FLastPressedColumn < 0 then Exit;
  with Rect do
  Begin
    TopLeft := GetArrowPos(FLastPressedColumn);
    Left := Left - 1;
    Top := Top - 1;
    Right := Left + 12;
    Bottom := Top + 13;
  end;

  Brush := TBrush.Create;
  with Brush do
  Begin
    Color := clBtnFace;
    Style := bsSolid;
    SelectObject(DC, Handle);
  end;

  FillRect(DC, Rect, Brush.Handle);
  Brush.Free;

  DrawColText(DC, FLastPressedColumn);
  Result := TRUE;
end;

function TMYListView.GetArrowPos(ColumnIndex: integer): TPoint;
var i: integer;
begin
  Result.x := 0;
  Result.Y := 0;

  if ColumnIndex < 0 then Exit;
  i := 0;
  while i < Columns.Count do
  Begin
    Result.x := Result.x + Columns[i].Width;
    if i = ColumnIndex then break;
    i := i + 1;
  end;
  with Columns[ColumnIndex] do if Alignment = taRightJustify then Result.x := Result.x - Width + 4
  else Result.x := Result.x - 20;
  Result.y := 2;
end;

function TMYListView.DrawArrow(DC: HDC; Direction: integer; Offset: TPoint): boolean;
var Pen: TPen;
begin
  Pen := TPen.Create;
  Pen.Style := PSSolid;

  case Direction of
    1: //Asc
    Begin
      Pen.Color := clWhite;
      SelectObject(DC, Pen.Handle);

      //The White
      MoveToEx(DC, Offset.x + 0, Offset.y + ARROW_SIZE, nil);
      LineTo(DC, Offset.x + ARROW_SIZE, Offset.y + ARROW_SIZE);
      LineTo(DC, Offset.x + 5, Offset.y + 0);

      Pen.Color := clBtnShadow;
      SelectObject(DC, Pen.Handle);

      //The Grey
      LineTo(DC, Offset.x + 0, OffSet.y + ARROW_SIZE);
    end;

    -1: //Desc
    Begin
      Pen.Color := clWhite;
      SelectObject(DC, Pen.Handle);

      //The White
      MoveToEx(DC, Offset.x + ARROW_SIZE, Offset.y + 0 + 1, nil);
      LineTo(DC, Offset.x + 5, Offset.y + ARROW_SIZE + 1);

      Pen.Color := clBtnShadow;
      SelectObject(DC, Pen.Handle);

      //The Grey
      LineTo(DC, Offset.x + 0, Offset.y + 0 + 1);
      LineTo(DC, Offset.x + ARROW_SIZE, Offset.y + 0 + 1);
    end;
  end;

  Pen.Free;
  Result := TRUE;
end;

procedure TMYListView.SetListViewColumns;
var
  NewColumn:        TListColumn;
  i:                integer;
begin
  if FDataSet <> nil then with FDataSet, Self.Columns do
  begin
    Clear;  //clears any columns
    for i := 0 to FieldCount - 1 do
      if Fields[i].Visible then
      begin
        NewColumn          := Add;
        NewColumn.Caption  := Fields[i].DisplayLabel;
        NewColumn.Width    := Fields[i].DisplayWidth * 10;
        NewColumn.Alignment := Fields[i].Alignment;
      end;
  end;
end;

function TMYListView.BuildListView: boolean;
var NewListItem:     TListItem;
    i:               integer;
begin
  Result := FALSE;

  FPressedColumn     := -1;
  FLastPressedColumn := -1;

  Items.Clear;

  if FDataSet = NIL then
  begin
    MessageDlg('The Dataset is NIL', mtError, [mbOK], 0);
    Exit;
  end;

  try
    FDataset.Open;
    SetListViewColumns;

    with FDataSet do
    Begin
      Items.BeginUpdate;
      if not EOF then while not EOF do
      begin
        NewListItem := Items.Add;
        for i := 0 to FieldCount - 1 do
        begin
          if Fields[i].Visible then
          begin
            if i = 0 then NewListItem.Caption := Fields[0].DisplayText
            else if Fields[i].Visible then NewListItem.SubItems.Add(Fields[i].DisplayText);

          end;
        end;
        Next;
        Application.ProcessMessages;
      end;
    end;

    Result := TRUE;
  finally
    FDataSet.Close;
    Items.EndUpdate;
  end;

end;

end.

Design time pkg BPL Source:
package MyListView_dcl;

{$R *.res}
{$IFDEF IMPLICITBUILDING This IFDEF should not be used by users}
{$ALIGN 8}
{$ASSERTIONS ON}
{$BOOLEVAL OFF}
{$DEBUGINFO OFF}
{$EXTENDEDSYNTAX ON}
{$IMPORTEDDATA ON}
{$IOCHECKS ON}
{$LOCALSYMBOLS ON}
{$LONGSTRINGS ON}
{$OPENSTRINGS ON}
{$OPTIMIZATION OFF}
{$OVERFLOWCHECKS OFF}
{$RANGECHECKS OFF}
{$REFERENCEINFO ON}
{$SAFEDIVIDE OFF}
{$STACKFRAMES ON}
{$TYPEDADDRESS OFF}
{$VARSTRINGCHECKS ON}
{$WRITEABLECONST OFF}
{$MINENUMSIZE 1}
{$IMAGEBASE $400000}
{$DEFINE DEBUG}
{$ENDIF IMPLICITBUILDING}
{$DESIGNONLY}
{$IMPLICITBUILD ON}

requires
  rtl,
  Vcl,
  dbrtl,
  adortl,
  MylistView_rn;

contains
  RegMyListView in 'RegMyListView.pas';

end.

Design time package Unit Source(RegMyListView.pas):
unit RegMyListView;

interface

Uses Classes,uMyListView1;

procedure Register;

implementation

procedure Register;
begin
  RegisterComponents('MyComponents', [TMyListView]);
end;
end.

After installing the component , Drop the TMyListView , TADOCOnnection,TADOQuery and button on form.

*

*TADOCOnnection : Set the Connection string .

*TADOQuery : Set the Connection and add SQL Property(Select Column1, Column2 from table)

*TMyListView : Set the DataSet to TADOQuery and ViewStyle  = vsReport

*Double click on button and Call TMyListView.BuildListView.

*Run the Application and Click on button no Column headings or Data.(check below screen shot)

if i comment the below line in TMYListView.WndProc Procedure or if i totally remove MyHeaderWndProc Procedure and its associated code, it is working as expected.
SetWindowLong(FMyHeaderHandle, GWL_WNDPROC, LongInt(FMyHeaderInstance));

I have no idea what's wrong with the code.

A: Maybe this helps, depending on your compiling target (SetWindowLong is marked as superseded): https://msdn.microsoft.com/en-us/library/windows/desktop/ms644898(v=vs.85).aspx


text:
Q: JCuda's JCublas2.cublasSdot: failed to use a device Pointer for the result Pointer parameter In the source code's comments of JCublas2.cublasSdot, it's commented that the 'result' parameter can be a 'host or device pointer'.
 public static int cublasSdot(
    cublasHandle handle,
    int n,
    Pointer x,
    int incx,
    Pointer y,
    int incy,
    Pointer result)/** host or device pointer */
{
    return checkResult(cublasSdotNative(handle, n, x, incx, y, incy, result));
}

However, I can use only a host pointer like Pointer.to(fs) with float[] fs ={0}. If I use a device pointer like 'CUdeviceptr devicePtr = new CUdeviceptr(); JCudaDriver.cuMemAlloc(devicePtr, 100 * Sizeof.FLOAT);', the program crashes with console messages like:
#
# A fatal error has been detected by the Java Runtime Environment:
#
#  EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x000007fed93af2a3, pid=9376, tid=0x0000000000003a7c
# .....

Minimization of data transfer between host and device saves time. How to use device Pointer as the 'result' argument for this method, as well as other JCuda methods with result Pointer commented with /** host or device pointer **/?

A: CUBLAS can write the results of certain computations (like the dot product) either to host or to device memory. The target memory type has to be set explicitly, using cublasSetPointerMode.
An example of how this can be used is shown in the JCublas2PointerModes sample.
It once writes the result of the dot product computation to host memory (which is also the default, when no pointer mode is set explicitly):
// Set the pointer mode to HOST
cublasSetPointerMode(handle, CUBLAS_POINTER_MODE_HOST);

// Prepare the pointer for the result in HOST memory
float hostResult[] = { -1.0f };
Pointer hostResultPointer = Pointer.to(hostResult);

// Execute the 'dot' function
cublasSdot(handle, n, deviceData, 1, deviceData, 1, hostResultPointer);

And then changes the pointer mode and calls the function again, this time writing the result to device memory:
cublasSetPointerMode(handle, CUBLAS_POINTER_MODE_DEVICE);

// Prepare the pointer for the result in DEVICE memory
Pointer deviceResultPointer = new Pointer();
cudaMalloc(deviceResultPointer, Sizeof.FLOAT);

// Execute the 'dot' function
cublasSdot(handle, n, deviceData, 1, deviceData, 1, deviceResultPointer);


text:
Q: Manually override the child using nightwatch.js I am currently writing a Nightwatch test to select a new document from a list. And I will need to be able to select the next in the list. Is there a way to manually override the child number that needs selecting?
For example the current selector being used is :

 <li class="dv-packdoc"

 <li class="dv-packdoc"

 <li class="dv-packdoc"

 <li class="dv-packdoc"

and the test would be something like :
viewer.selectNewDocument([2])

would this select the second child under the ul?
Or would I have to specify each child element?

A: If I understand correctly, you are trying to dynamically find the appropriate child element (li) from a dynamical length list (ul, where the list is populated based on user input, or other site actions). Correct?
I see two scenarios with two different approaches:
1. You have a set/fixed condition (way of identifying your target element): for example, in your list, the second li would be targeted by the below command.
viewer.selectNewDocument('ul.dv-packdocs li:nth-child(2)') (considering you are passing a complete selector to the selectNewDocument function)
, or
viewer.selectNewDocument(2), passing a number & form the selector inside the command (if you care for aesthetics):
selectNewDocument: function(index) {
  this.api.perform((done) => {
    // Click the second document in the list:
    let selector = `ul.dv-packdocs li:nth-child(${index})`;
    this.api.click(selector);
    done();
  });
  return this;
},

Alternatively, if you would want the last document added, then you would have to issue a elements call on the ul to retrieve the length of the list, then use that in the same way to determine which li you have to click: viewer.selectNewDocument('ul.dv-packdocs li:nth-child('+length+')') (where length is the result of your elements call).

2. You don't have a fixed condition (I'll fill this up if the first part doesn't cover it, or later today, kinda slammed after the holidays)
Hope it's what you were looking for! Cheers!


text:
Q: After applying clearInterval to an interval why doesn't the interval work again when called? My game is quite simply you are supposed to click on the start button and move your mouse along the track until you reach the end. At the end the timer stops and shows your score. My problem lies with the timer. The timer work perfectly fine the first time but when you click reset to play again it only calls the interval once. Why?
Link to my full code: http://www.codecademy.com/TictacTactic/codebits/AQBK4L/edit
Thank you in advance!
JAVA SCRIPT
var clicked = false;
var score = 1000;
var timer = setInterval(function(){countDown()}, 250);

$(document).ready(function() {
$('#start').click(function() {
if(!clicked){
    clicked = true;
    countDown();
}
});

$("#lava").mouseover(function(){
if(clicked){
    stopTimer();
    score = 0;
    $("#points").html(score);
}
});

$("#end").mouseover(function(){
if(clicked){
    stopTimer();
    $("#points").html(score);
    clicked = false;
}
});

$('#reset').click(function() {
if(clicked || !clicked){
    clicked = false;
    score = 1000;
    $('#points').html(score);
}
});

});

function countDown() {
score = score - 1;
}

function stopTimer() {
clearInterval(timer);
}

A: your code var timer = setInterval(function(){countDown()}, 250); is at the top and will be executed before the methods are even loaded.  Add at the end of the ready(), look at the bottom:
var clicked = false;
var score = 1000;
var timer = null;

$(document).ready(function() {
  $('#start').click(function() {

  if(!clicked){
    clicked = true;
    score = 1000;
    timer = setInterval(function(){countDown()}, 250);
    //countDown();
   }
  });

 $("#lava").mouseover(function(){
   if(clicked){
    stopTimer();
    score = 0;
    $("#points").html(score);
   }
 });

 $("#end").mouseover(function(){
   if(clicked){
    stopTimer();
    $("#points").html(score);
    clicked = false;
   }
});

 $('#reset').click(function() {
  if(clicked || !clicked){
    clicked = false;
    score = 1000;
    $('#points').html(score);
  }
});

});

function countDown() {
  score = score - 1;
  $('#points').html(score);
  }

function stopTimer() {
  clearInterval(timer);
  }


text:
Q: После создания билда с его запуска я получаю ошибку SyntaxError: Unexpected token '<' Как исправить? Задача поставить приложение на сервер.  Начну с того, что если я просто переношу app на сервер и делаю npm start то app запускается и работает нормально.
Если я делаю билд проекта то он создается с ошибками, но без проблем запускается. Вот после того как я сделал билд с его запустил я получаю в консоле вот такую ошибку:

далее ошибки которые возникают при создании билда:
Creating an optimized production build...
Compiled with warnings.

./src/containers/home/TrendingPosts/index.jsx
  Line 11:6:  React Hook useEffect has a missing dependency: 'getTrending'. Either include it or remove the dependency array. If 'getTrending' changes too often, find the parent component that defines it and wrap that definition in useCallback  react-hooks/exhaustive-deps

./src/containers/image/index.jsx
  Line 25:6:  React Hook useEffect has a missing dependency: 'getImageData'. Either include it or remove the dependency array. If 'getImageData' changes too often, find the parent component that defines it and wrap that definition in useCallback  react-hooks/exhaustive-deps

./src/components/simple/post/index.jsx
  Line 28:46:  Unexpected string concatenation of literals  no-useless-concat

./src/components/Routes.jsx
  Line 2:32:  'Redirect' is defined but never used                                                                         no-unused-vars
  Line 40:6:  React Hook useEffect has a missing dependency: 'dispatch'. Either include it or remove the dependency array  react-hooks/exhaustive-deps

./src/containers/Tape/index.jsx
  Line 30:6:  React Hook useEffect has missing dependencies: 'getImagesHandler' and 'loading'. Either include them or remove the dependency array  react-hooks/exhaustive-deps
  Line 34:6:  React Hook useEffect has a missing dependency: 'getImagesHandler'. Either include it or remove the dependency array                  react-hooks/exhaustive-deps

./src/containers/NavBar/index.jsx
  Line 32:6:  React Hook useEffect has a missing dependency: 'getUserBalance'. Either include it or remove the dependency array  react-hooks/exhaustive-deps

./src/core/hooks/useLikes.js
  Line 35:19:  'res' is assigned a value but never used                                                                                no-unused-vars
  Line 67:38:  The ref value 'el.current' will likely have changed by the time this effect cleanup function runs. If this ref points to a node rendered by React, copy 'el.current' to a variable inside the effect, and use that variable in the cleanup function  react-hooks/exhaustive-deps
  Line 68:8:   React Hook useEffect has a missing dependency: 'handler'. Either include it or remove the dependency array                                                                                react-hooks/exhaustive-deps

./src/containers/editPost/index.jsx
  Line 37:6:  React Hook useEffect has a missing dependency: 'getPostData'. Either include it or remove the dependency array. If 'getPostData' changes too often, find the parent component that defines it and wrap that definition in useCallback  react-hooks/exhaustive-deps

./src/components/smart/search/result/index.jsx
  Line 3:16:  'object' is defined but never used  no-unused-vars

./src/core/hooks/uploadFiles.js
  Line 43:6:  React Hook useEffect has missing dependencies: 'files' and 'uiFiles'. Either include them or remove the dependency array  react-hooks/exhaustive-deps

./src/containers/auth/walletConnect/index.jsx
  Line 48:7:  img elements must have an alt prop, either with meaningful text, or an empty string for decorative images  jsx-a11y/alt-text

./src/components/ordinary/TopPosts/TopPosts.jsx
  Line 4:10:  'swiperSettings' is defined but never used  no-unused-vars

./src/components/simple/RightNav/index.jsx
  Line 4:8:  'Link' is defined but never used  no-unused-vars

./src/containers/auth/metamask/index.jsx
  Line 50:13:  Using target="_blank" without rel="noopener noreferrer" is a security risk: see https://mathiasbynens.github.io/rel-noopener  react/jsx-no-target-blank

./src/core/api/likes/index.js
  Line 5:15:  'res' is assigned a value but never used  no-unused-vars

./src/core/api/user/index.js
  Line 61:13:  'user' is assigned a value but never used  no-unused-vars
  Line 72:13:  'res' is assigned a value but never used   no-unused-vars
  Line 81:13:  'res' is assigned a value but never used   no-unused-vars

./src/containers/user/index.jsx
  Line 64:6:  React Hook useEffect has a missing dependency: 'getUserDataQuery'. Either include it or remove the dependency array  react-hooks/exhaustive-deps

./src/components/ordinary/formPost/index.jsx
  Line 6:8:  'Link' is defined but never used  no-unused-vars

./src/components/smart/createPost/index.jsx
  Line 7:8:  'Link' is defined but never used  no-unused-vars

./src/components/smart/tape/index.jsx
  Line 7:9:  The 'scrollHandler' function makes the dependencies of useEffect Hook (at line 25) change on every render. Move it inside the useEffect callback. Alternatively, wrap the 'scrollHandler' definition into its own useCallback() Hook  react-hooks/exhaustive-deps

./src/containers/home/TopPosts/index.jsx
  Line 9:6:  React Hook useEffect has a missing dependency: 'getTopPosts'. Either include it or remove the dependency array. If 'getTopPosts' changes too often, find the parent component that defines it and wrap that definition in useCallback  react-hooks/exhaustive-deps

Search for the keywords to learn more about each warning.
To ignore, add // eslint-disable-next-line to the line before.

File sizes after gzip:

  456.65 KB  build\static\js\2.06539643.chunk.js
  27.42 KB   build\static\js\main.56d9c162.chunk.js
  3.49 KB    build\static\css\main.c9e009c8.chunk.css
  3.33 KB    build\static\css\2.b49f9c43.chunk.css
  1.73 KB    build\static\js\3.f7997a40.chunk.js
  1.17 KB    build\static\js\runtime-main.6d09a018.js

The project was built assuming it is hosted at ./public/.
You can control this with the homepage field in your package.json.

The build folder is ready to be deployed.

Find out more about deployment here:

  bit.ly/CRA-deploy

Насколько я понимаю тут нету ничего критичного в этих ошибках. Через npm start все работает и ошибки в консоле так же есть, но проект запускается, а вот при билде получаю вот такой результат. В чем может быть дело?

A: Решил вопрос. Дело все было в параметре homepage в package.json. Я просто удалил этот параметр и все заработало. Вебпак новенький как то странно работает с параметром homepage, пытаясь в жс засунуть голый хтмл, из за этого и проблема.

A: нажми на ошибку (там где написан номер.chunk.js) - что бы развернуть код, где она происходит и через глобальный поиск попробуй найти это место


text:
Q: Deno Server doesn't go through the Internet I built a simple Webserver with just the serve function from the std http module. It just redirects a request to a new URL:
import { serve } from "https://deno.land/std@0.120.0/http/server.ts";

serve(req => Response.redirect("https://google.com"))

It works, when I access the server through a browser on my laptop, where the server is running, but when I try to access it on another machine in the same network using the ip-address of my laptop, there simply is no response at all. Is this one of the security features Deno has and if so, how can you deactivate it?
Update:
So I tried looking up the requests I make on my local machine in Wireshark, but when I run the server and send a request, it doesn't show up there. I disabled my Wifi Connection to see if that changes anything and to my surprise, I still got an answer from the server when I sent a request through the browser. I came to the conclusion that the Deno server somehow doesn't serve over the local network which really confuses me. Is there a way to change that behaviour?

A: This is not related to Deno, but rather the firewall features of your device/router/network or an error in the method that you are using to connect from the other device (typo, network configuration, etc.).
Without additional configuration (by default), serve binds to 0.0.0.0:8000, so — as an example — if your laptop is assigned the local address 192.168.0.100 by your router, you could reach the server at the address http://192.168.0.100:8000.
You might want to do research on SE/NetworkEngineering and elsewhere to determine the cause of the blocked connection.


text:
Q: Display values in textarea separated with newline after post and reuse of values I have a solution in MVC, ASP.NET with the use of angularjs, where it is possible to input values into a textarea and post them to a server. I can receive the values from the server and show them in the textarea in the view by using ng-model. But I am unsure of how to display them by newline and to then reuse them (re-post them right away).
1) First of all the user is able to input values in the textarea and split them by the Return button. This is done by ng-list="/\n/":
<textarea rows="10" cols="80" id="autoGenerateInputField" ng-model="fighterList" ng-list="/\n/" />

2) I then post these values through angularJS and saves them in my database.
3) I can now get these values from a JSON. I convert them into a list and puts them into the fighterList using angularJS:
$scope.refreshListTournamentTree = function (CategoryId) {
        var serviceUrl = "/api/Match" + (CategoryId ? "/" + CategoryId : "");
        $http({
            method: 'GET',
            url: serviceUrl
        }).success(function (data, status, headers, config) {
            $scope.treeGenerated = data.length;
            $scope.totalMatches = data;
            var listOfFighters = [];
            if (data.length > 0) {
                $scope.finalMatch = [buildHierarchy(data)[0]];
                for (var i = 0; data.length > i; i++){
                    fighter1 = data[i].Fighter1;
                    fighter2 = data[i].Fighter2;
                    listOfFighters.push(fighter1);
                    listOfFighters.push(fighter2);
                }
            }
            else {
                $scope.finalMatch = [];
            }
            $scope.fighterList = listOfFighters;
            $scope.loading = false;
        }).error(function (data, status, headers, config) {
      });

    }

Now the list is shown in the textarea but the values are separated by "," and not with a new line. I have created a Fiddle that shows a simplyfied version of my question:
http://jsfiddle.net/Jtf3M/256/

So to my question: How do I display the values from the fighterList in the textarea separated with newline and so that I can reuse the values?

A: Can't you simply add a join?
Please see the fiddle updated: http://jsfiddle.net/Jtf3M/261/
Please look also at this alternative way using a filter and ng-init: http://jsfiddle.net/7516qere/


text:
Q: ASP.NET iFrame src requires preceding forward slash, hard coded path does not When I have an <iFrame/> in my razor file with its src hardcoded without a preceding slash, the pdf renders fine within the iFrame:
    <iframe src="UploadedPdfs/analytics.pdf"
            width="800"
            height="800"
            runat="server"
            id="iframepdf">
    </iframe>

But if I set up the src to be dynamically passed through a property on the model, It only works if I prepend the path with a forward slash:
    PdfView pView = (PdfView)ViewData["PdfView"];
    string pRelativePath = pView.relativePath;

    <iframe src=@( "/" + pRelativePath ) //pRelativePath when debugging is equal to UploadedPdfs/analytics.pdf
            width="800"
            height="800"
            runat="server"
            id="iframepdf">
    </iframe>

Here is what the html for the above variable passed path, without a slash looks like, this does not render the pdf:

With the forward slash preceding the variable value, this is the resulting html, which renders fine:

Is this normal / expected?

A: You have some weird quotes in your last bit of code. It should be like:
@{
    PdfView pView = (PdfView) ViewData["PdfView"];
    string pRelativePath = pView.relativePath;
}

<iframe src="@pRelativePath"
                width="800"
                height="800"
                runat="server"
                id="iframepdf">
</iframe>

That works without a forward slash in the beginning, and renders like your first bit of code:
<iframe src="UploadedPdfs/analytics.pdf"
                width="800"
                height="800"
                runat="server"
                id="iframepdf">
</iframe>


text:
Q: MarketingCloud crashing with CoreData failures We're seeing MarketingCloud crashing on our app while trying to perform few CoreData tasks. Here are the 2 stack traces with errors that we see on Crashlytics:
Fatal Exception: NSInvalidArgumentException
0  CoreFoundation                 0xa248 __exceptionPreprocess
1  libobjc.A.dylib                0x17a68 objc_exception_throw
2  CoreData                       0x164b0 +[NSEntityDescription entityForName:inManagedObjectContext:]
3  CoreData                       0x1615c +[NSEntityDescription insertNewObjectForEntityForName:inManagedObjectContext:]
4  MarketingCloudSDK              0x4bf7c __hidden#3438_ + 161 (__hidden#3463_:161)
5  MarketingCloudSDK              0x58bdc __hidden#3606_ + 1011 (__hidden#3975_:1011)
6  MarketingCloudSDK              0x5eb74 __hidden#3678_ + 1674 (__hidden#3975_:1674)
7  MarketingCloudSDK              0x5e378 __hidden#3675_ + 1626 (__hidden#3975_:1626)
8  Foundation                     0x3b000 __NSThreadPerformPerform
9  CoreFoundation                 0xd622c __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__
10 CoreFoundation                 0xe2614 __CFRunLoopDoSource0
11 CoreFoundation                 0x6651c __CFRunLoopDoSources0
12 CoreFoundation                 0x7beb8 __CFRunLoopRun
13 CoreFoundation                 0x811e4 CFRunLoopRunSpecific
14 GraphicsServices               0x1368 GSEventRunModal
15 UIKitCore                      0x3a2d88 -[UIApplication _run]
16 UIKitCore                      0x3a29ec UIApplicationMain
17 [app-name]                     0x25368 main + 24 (main.swift:24)
18 ???                            0x1ee22d948 (Missing)

Fatal Exception: NSInvalidArgumentException
0  CoreFoundation                 0x9e88 __exceptionPreprocess
1  libobjc.A.dylib                0x178d8 objc_exception_throw
2  CoreData                       0x17a880 __43-[NSManagedObjectContext setParentContext:]_block_invoke
3  MarketingCloudSDK              0x832dc __hidden#4635_ + 63 (__hidden#4688_:63)
4  MarketingCloudSDK              0x5c768 __hidden#3662_ + 1395 (__hidden#3975_:1395)
5  MarketingCloudSDK              0x9cebc __hidden#4984_ + 608 (__hidden#5237_:608)
6  MarketingCloudSDK              0x999ec __hidden#4951_ + 109 (__hidden#5237_:109)
7  MarketingCloudSDK              0xa658 __hidden#754_ + 252 (__hidden#719_:252)
8  CoreFoundation                 0xa3a0 __NSARRAY_IS_CALLING_OUT_TO_A_BLOCK__
9  CoreFoundation                 0x910e0 -[__NSArrayI enumerateObjectsWithOptions:usingBlock:]
10 MarketingCloudSDK              0x9834 __hidden#307_ + 269 (__hidden#719_:269)
11 MarketingCloudSDK              0xae50 __hidden#750_ + 334 (__hidden#719_:334)
12 libdispatch.dylib              0x3fdc _dispatch_client_callout
13 libdispatch.dylib              0x1364c _dispatch_async_and_wait_invoke
14 libdispatch.dylib              0x3fdc _dispatch_client_callout
15 libdispatch.dylib              0x127f4 _dispatch_main_queue_drain
16 libdispatch.dylib              0x12444 _dispatch_main_queue_callback_4CF
17 CoreFoundation                 0x9a6f8 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__
18 CoreFoundation                 0x7c058 __CFRunLoopRun
19 CoreFoundation                 0x80ed4 CFRunLoopRunSpecific
20 GraphicsServices               0x1368 GSEventRunModal
21 UIKitCore                      0x3a23d0 -[UIApplication _run]
22 UIKitCore                      0x3a2034 UIApplicationMain
23 [app-name]                     0x25368 main + 24 (main.swift:24)
24 ???                            0x1ebf0c960 (Missing)

We're using MarketingCloudSDK-iOS v.8.0.8 and sfmc-sdk-ios v.1.0.6 via SPM. The MarketingCloudSDK bundle is listed in the Copy Bundle Resources build phase. This bundle was copied from the v.8.0.8 of the SDK as this was the first one we integrated into our app.
Any other advice on how to prevent these issues?

A: Can you please help us with the scenario where the crash is happening?
Is there any case where the SDK is re-initialized or does any of your usecase requires re-initialization of the SDK ?
Just in case, if you have added the below code from https://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/get-started/get-started-configuresdk.html:
// SDK: OPTIONAL IMPLEMENTATION (if using Data Protection)
func applicationProtectedDataDidBecomeAvailable(_ application: UIApplication) {
    if (SFMCSdk.mp.getStatus() != .operational) {
        self.configureSFMCSdk()
    }
}

It is optional as mentioned and needs to be used only if the data protection is enabled in the app.
Request you to please create a support ticket with crash logs, sdk state, debug logs by running the app in debug mode and mention @ppattabiraman@salesforce.com and @bmote@salesforce.com
Thanks,
Prakashini


text:
Q: Парсинг страниц Есть страничка вот эта http://demonscity.combats.com/inf.pl?1186550345
Нужно получить данные вот этой функции

Как можно это сделать? не используя регулярные выражения!
A: А в чём проблема? Грубое решение -- ищете (без регулярных выражений, просто поиском строки) текст "DrawOnline" на странице, от него вперёд открывающую скобку, от неё вперёд закрывающую. То, что между скобками -- искомое.
Если хотите более концептуальное решение, попробуйте настоящий парсер. Например, такое (не пробовал, основываюсь на документации):
$xml = new DOMDocument();
$xml->loadHTMLFile($url);
foreach($xml->getElementsByTagName('script') as $scriptnode) {
    $script = $scriptnode->nodeValue;
    if (strpos($script, "DrawOnline") === false)
        continue;
    // анализируйте текст скрипта
}

A: Не очень понял под Вашим "данные".
function DrawOnline(last_enter, now){
if(now==='online'){
    doc.write('Персонаж сейчас находится в клубе.')
} else {
    doc.write('Персонаж не в клубе')
    if(last_enter!=='hide'){
        doc.write(
            ', но был тут:
'+
            CombatsUI.UTCMsec2PlainText(CombatsUI.UTCMsec2Moscow(last_enter*1000))+'
'+
            '('+LocalText.PeriodToText('ru', now-last_enter, 2, 'ACC')+' назад)'
        )
    }
}

}
Получает время в Unix-формате предположительно.

UPD:

@quaresma89, Вы посчитаете меня занудой, но я все равно Вас не понял)) Вам нужен результат выполнения этой функции или объяснение зачем нужны параметры этой функции?
Просто "их(параметры) мне и надо вытащить" - их незачем вытаскивать) Они уже тут))
Параметры: last_enter - время последнего посещения, now - текущее время. Хранятся в UNIX-формате, т.е. число секунд с 1 января 1980 года. Они генерируются (подставляются) на сервере вероятно. Если совпадают, то онлайн, иначе высчитывается разница между последним посещением и текущим временем (чтоб вывести как давно не заходил) и переводятся в "человеко-читаемый" формат. Если не то, то опишите подробней что Вам нужно)

UPD2

Не сразу заметил. now почему-то сравнивается со строкой "online", хотя передается число. Там наверно онлайн никого не бывает))
A: simple html dom тебе в помощь очень мощная вещь для работы с html


text:
Q: "[BABEL] Cannot find module" on a fresh PC install I'm setting up my dev environment on a fresh system. In my project folder:
npm install
npm run serve

And got this:
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: [BABEL] /Users/user/Documents/project/editor/src/main.js: Cannot find module '@babel/compat-data/corejs3-shipped-proposals'
Require stack:
- /Users/user/Documents/project/editor/node_modules/@babel/preset-env/lib/polyfills/corejs3/usage-plugin.js
- /Users/user/Documents/project/editor/node_modules/@babel/preset-env/lib/index.js
- /Users/user/Documents/project/editor/node_modules/@vue/babel-preset-app/index.js
- /Users/user/Documents/project/editor/node_modules/@vue/cli-plugin-babel/preset.js
- /Users/user/Documents/project/editor/node_modules/@babel/core/lib/config/files/plugins.js
- /Users/user/Documents/project/editor/node_modules/@babel/core/lib/config/files/index.js
- /Users/user/Documents/project/editor/node_modules/@babel/core/lib/index.js
- /Users/user/Documents/project/editor/node_modules/@vue/cli-plugin-babel/index.js
- /Users/user/Documents/project/editor/node_modules/@vue/cli-service/lib/Service.js
- /Users/user/Documents/project/editor/node_modules/@vue/cli-service/bin/vue-cli-service.js (While processing: "/Users/user/Documents/project/editor/node_modules/@vue/cli-plugin-babel/preset.js")
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:966:15)
    at Function.Module._load (internal/modules/cjs/loader.js:842:27)
    at Module.require (internal/modules/cjs/loader.js:1026:19)
    at require (internal/modules/cjs/helpers.js:72:18)
    at Object.<anonymous> (/Users/user/Documents/project/editor/node_modules/@babel/preset-env/lib/polyfills/corejs3/usage-plugin.js:10:55)
    at Module._compile (internal/modules/cjs/loader.js:1138:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
    at Module.load (internal/modules/cjs/loader.js:986:32)
    at Function.Module._load (internal/modules/cjs/loader.js:879:14)
    at Module.require (internal/modules/cjs/loader.js:1026:19)
    at require (internal/modules/cjs/helpers.js:72:18)
    at Object.<anonymous> (/Users/user/Documents/project/editor/node_modules/@babel/preset-env/lib/index.js:29:44)
    at Module._compile (internal/modules/cjs/loader.js:1138:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
    at Module.load (internal/modules/cjs/loader.js:986:32)
    at Function.Module._load (internal/modules/cjs/loader.js:879:14)

 @ multi (webpack)-dev-server/client?http://192.168.0.105:8080/sockjs-node (webpack)/hot/dev-server.js ./src/main.js

I checked in node_modules/@babel/compat-data/ and the module is there. Why doesn't webpack (is it webpack?) see it?
Note that I did the same thing on another system a few weeks ago and it worked fine.
I also have a vuepress project on the same new system and it also runs fine.
Thanks

A: In project folder:
rm package_lock.json
rm -r node_modules
npm install

Turns out I had package_lock.json on git from another system. Removed it and it worked.

A: you can remove the lock files generated (package-lock.json)
and then remove the node modules from your project.
And then again try to download the dependencies via npm
as  npm install


text:
Q: Simulator is not launching from xcode but app is building Problem
I run react native ios app from xcode, it build app but the simulator is not launching.
Tried

*

*When I try from terminal, simulator is  launching and app is running.

*I clean xcode derivedData and simulator cache too but its did not success.

*I even restarted my laptop too.

*I create swift project from xcode, it build and launch simulator every time.

Planning

*

*Uninstall and re-install xcode.

Any suggestion would be grateful.


text:
Q: Why I can't access my application inside Kubernetes cluster through tomcat server? I'm running a kubernetes cluster with minikube on ubuntu server 20.04.1 LTS. When I launch the deployments I can access the Tomcat server from the cluster, but I can't open my application, I got the error message :
HTTP Status 404 – Not Found

Here is my docker-compose file :
    version: "3"

#NETWORK
networks:
  network1:
    driver: bridge
volumes:
  dir-site:
    driver_opts:
      device: /smartclass_docker/site/
      type: bind
      o: bind
# Declare services
services:
  # service name
  server:
    container_name: server
    # Container image name
    image: repo/myimage
    ## Image used to build Dockerfile
    build:
      #dockerfile: Dockerfile
      context: ./smart/

    # Container ports and host matching
    ports:
      - "3306:3306"
      - "8080:8080"

    ## Startup Policy
    restart driver: bridge
volumes:
  dir-site:
    driver_opts:
      device: /smart/site/
      type: bind
      o: bind
# Declaration of services
services:
  # service name
  server:
    container_name: server
    # name of the image
    image: repo/myimage
    ## Use IMAGE BUILD DOCKERFILE
    build:
      #dockerfile: Dockerfile
      context: ./smart/

    # CONTAINER ports
    ports:
      - "3306:3306"
      - "8080:8080"

    ## Startup policy
    restart: always

    # connect to network1
    networks:
      - network1
    volumes:
            - /data/dockerStore/data/db_server_1:/var/lib/mysql/

    restart: always

    # connect to network1
    networks:
      - network1
    volumes:
            - /data/dockerStore/data/db_server_1:/var/lib/mysql/

Here is my kubernetes deployment file :
apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp
spec:
  replicas: 3
  selector:
      matchLabels:
        app: myapp
  # type: LoadBalancer
  template:
    metadata:
      labels:
        app: myapp
    spec:
      containers:
      - name: myapp
        image: jksun12/vdsaipro
        command: ["/run.sh"]
        ports:
        - containerPort: 80
        - containerPort: 3306
        - containerPort: 9001
        - containerPort: 9002
   # volumeMounts:
   #     - name: myapp-pv-claim
   #       mountPath: /var/lib/mysql
   #   volumes:
   #   - name: myapp-pv-claim
   #     persistentVolumeClaim:
   #       claimName: myapp-pv-claim
---
apiVersion: apps/v1
kind: PersistentVolumeClaim
metadata:
  name: myapp-pv-claim
  labels:
    app: myapp
spec:
  accesModes:
    - ReadWriteMany
  resources:
    requests:
      storage: 4Gi

My application files are in the /smart directory, which is a subdirectory of the directory where I actually run docker-compose and build my main Dockerfile.
How can I solve it ?
Thanks

A: I checked the logs inside the containers, and I found that the errors come from the extraction of the .war file inside the container.
There was also an error in the version of the tomcat server used for the application. So I changed the version of tomcat to another version.
It's solved now. Thanks


text:
Q: Validate given conditions across the rows in a database table I have a database table with positions and coresponding values like this
position    value

Z170S11     630
Z176S11     103
Z060S11     7162
Z143S01     47

'position' is unique for this table. The set of positions is fixed. The row entries for column 'value' will change with each new run of the application.
I also have a fixed list of conditions across all the values in this table. This list is part of an Excel file that I want to store in my database. The list has entries like this
left hand side       operator    right hand side

Z143S01 + Z060S11    =           Z176S11
Z143S01              >=          Z170S11

Both, left and right hand side may consist of sums and differences of up to 10 different values. Operators are '=', '<=' and '>='.
For each condition I need to check that the current 'value' fields are correct. E.g.
Z143S01 + Z060S11 = Z176S11

will evaluate to
47 + 7162 = 103

which is false. The result of each check should be presented to the user.
What is a good way to store these conditions as part of my database and automatically check if they are fulfilled with the given values from the table above?
I thought of storing them as string values in a table and evaluating each row individually using VBA's 'Split'- and 'DLookup'-functions. As I expect about 1.000 conditions to check, this might turn out too slow. Is there an easier/faster way, maybe relying more on SQL?

A: Custom function opens a recordset of Positions, loops records and performs replace operation on condition expression string, Eval() function evaluates new string, returns a True or False.
Function TestVal(sStr As String)
Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset("SELECT * FROM Positions")
Do While Not rs.EOF
    sStr = Replace(sStr, rs!Position, rs![Value])
    rs.MoveNext
Loop
Debug.Print sStr
TestVal = Eval(sStr)
End Function

Can call function in query or textbox.
SELECT Conditions.*, TestVal([LeftSide] & [Operator] & [RightSide]) AS IsTrue FROM Conditions;


text:
Q: What's the regex for restricted number of numeric characters? Having trouble figuring out a regex issue.
We are looking for 2 numbers then hyphen or space then 6 numbers. Must be only 6 numbers, so either an alpha character or some punctuation or space must follow the 6 numbers or the 6 numbers must be at the end of the string.
Other numbers are allowed elsewhere in the string, as long as they are separate.
So, these should match:
foo 12-123456 bar
12-123456 bar
foo 12-123456
foo12-123456bar
12-123456bar
foo12-123456
12-123456bar 99
foo12-123456 99

These should not match:
123-12345 bar
foo 12-1234567
123-12345bar
foo12-1234567

Here's what we were using:
\D\d{2}[-|/\ ]\d{6}\D
and in Expresso this was fine.
But running for real in our .net application this pattern was failing to match on examples where the 6 numbers were at the end of the string.
Tried this:
\D\d{2}[-|/\ ]\d{6}[\D|$]
and it still doesn't match
foo 12-123456

A: I would restate your pattern from

Must be only 6 numbers, so either an alpha character or some punctuation or space must follow the 6 numbers or the 6 numbers must be at the end of the string.

to

Must be only 6 numbers, so there must not be a number after the sixth number

and then use a negative look-ahead assertion to express this. Similarly, at the start of the pattern use a negative look-behind assertion to say that whatever is before the first two digits, it isn't a digit. Together:
var regex = new Regex(@"(?<!\d)\d{2}[- ]\d{6}(?!\d)");

var testCases = new[]
                    {
                        "foo 12-123456 bar",
                        "12-123456 bar",
                        "foo 12-123456",
                        "foo12-123456bar",
                        "12-123456bar",
                        "foo12-123456",
                        "123-12345 bar",
                        "foo 12-1234567",
                        "123-12345bar",
                        "foo12-1234567",
                    };

foreach (var testCase in testCases)
{
    Console.WriteLine("{0} {1}", regex.IsMatch(testCase), testCase);
}

This produces six Trues then four Falses, as required.
The assertions (?<!\d) and (?!\d) respectively say 'there isn't a digit just before here' and 'there isn't a digit just after here'.

A: This should do it:
(^|\D)\d{2}[- ]\d{6}($|\D)

It looks for either the beginning of the line or a non-number, then your mentioned pattern of either 2-6 or 2 6, then either the end of the line or another non-number.
Edited and tested with perl, matches the first 8, not the next 4.
C# may have other specifica for RegEx. I'm not sure if or which changes are necessary.

A: Ok, based on your further edited question the answer looks like this: ^(?:.*?\D+?)?(\d{2}[-|/\ ]\d{6})(?:\D+?.*?)?$ it matches all the string and captures the number.
upd: added some code to test ans show the matching.
MessageBox.Show(Regex.Replace(
  "1 foo 12-123456 bar\r\n12-123456 bar\r\nfo23o 12-123456\r\nfoo12-123456bar3\r\n" +
  "12-123456bar\r\nfoo12-123456\r\n\r\nThese should not match:\r\n\r\n" +
  "123-12345 bar\r\nfoo 12-1234567\r\n123-12345bar\r\nfoo12-1234567",
  @"^(?:.*?\D+?)?(\d{2}[-|/\ ]\d{6})(?:\D+?.*?)?$",
  @"[match, cap: '$1']",
  RegexOptions.Multiline
));