text:
Q: Fullscreen background img combined with Fullscreen repeating background I'm trying to place a fullscreen background image combined with a repeating background image without the use of J-query. Is it possible?
This is the code I use to get my image fullscreen:
body {
background: url(../img/bg1.jpg) no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

But now I want this completely overlapped by a .png image background that needs to have a repeat function, for the simple reason that the .png contains lines which will rescale and look awful on certain screen sizes.
Any ideas?
Already tried:

*

*Giving html a background and body a background, it will only display one of both.

A: It is possible to include two background images on one tag.

How it Works
Multiple background images can be specified using either the
  individual background properties or the background shorthand property.

This should be a Helpful resource to get you started.
css:
body {
    background-image: url(http://www.wallcoo.com/paint/Chiplegal_vector_art/images/%5Bwallcoo.com%5D_vector_art_0seasons.jpg), url(http://nopgc.org/v2/images/body_bg.jpg);
    background-position: top center, center;
    background-repeat: no-repeat, repeat;
    width: 100%;
    height: 100%;
}

fiddle: Demo

A: Be aware that multiple backgrounds won't work on ie8 if needed:
http://caniuse.com/multibackgrounds
This answer will work on every browser:
You must give width and height to the elements.
You can see answer here: http://jsfiddle.net/Rc38f/
HTML Code:

CSS Code:
html {
    width: 100%;
    height: 100%;
}

body {
    background-image: url('http://www.colourbox.com/preview/4632391-637684-seamless-small-white-flowers-pattern-background.jpg');
    background-repeat: repeat;
    width: 100%;
    height: 100%;
}

#wrapper {
    background: url('http://i.telegraph.co.uk/multimedia/archive/02403/Jonstockshooting_2403237b.jpg') no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
    width: 100%;
    height: 100%;
}


text:
Q: Send image over tcp from raspberry pi to program in pc and display it on pc I am having a client - server program in which raspberry pi has the client and pc contains the server. I want to send image captured by pi to server and want to process it there. The code is given below.
Client side :
import io
import socket
import struct
from PIL import Image

s = socket.socket(socket.AF_INET , socket.SOCK_STREAM)
s.connect(('ip', 12345))
connection = s.makefile('wb')
try:
    camera = picamera.PiCamera()
    camera.resolution = (640, 480)
    camera.start_preview()
    time.sleep(2)
    stream = io.BytesIO()
    camera.capture(stream , format='jpeg')
    connection.write(struct.pack('<L', stream.tell()))
    connection.flush()
    stream.seek(0)
    connection.write(stream.read())
    stream.seek(0)
    stream.truncate()
finally:
    camera.stop_preview()
    connection.close()
    client_socket.close()

Server:
import io
import socket
import struct
from PIL import Image

s = socket.socket()
host = '' #ip of raspberry pi
port = 12345
s.bind((host, port))

s.listen(5)
connection = s.accept()[0].makefile('rb')
try:
        image_len = struct.unpack('<L',connection.read(struct.calcsize('<L')))[0]
        image_stream = io.BytesIO()
        image_stream.write(connection.read(image_len))
        image_stream.seek(0)
        image = Image.open(image_stream)
        image.show()
        print('Image is verified')

finally:
    connection.close()
    s.close()

When this program is executed, an error occurs stating :
  Traceback (most recent call last):
  File "server.py", line 24, in <module>
    image = Image.open(image_stream)
  File "C:\Users\USER\AppData\Local\conda\conda\envs\cvv\lib\site-packages\PIL\I
mage.py", line 2687, in open
    % (filename if filename else fp))
OSError:

 cannot identify image file <_io.BytesIO object at 0x000000D6

Please help me with this.

A: client:
import io
import socket
import struct
from PIL import Image
import picamera
import time

s = socket.socket(socket.AF_INET , socket.SOCK_STREAM)
ip = '192.168.1.2'
port = 12345
print("ok")
s.connect(('192.168.1.2', 12345))
print("ok")
connection = s.makefile('wb')
print("ok")
try:
    camera = picamera.PiCamera()
    camera.resolution = (640, 480)
    camera.start_preview()
    time.sleep(2)
    stream = io.BytesIO()
    camera.capture(stream , format='jpeg')
    connection.write(struct.pack('<L', stream.tell()))
    connection.flush()
    stream.seek(0)
    connection.write(stream.read())
    stream.seek(0)
    stream.truncate()
finally:
#    camera = picamera.PiCamera()
    camera.stop_preview()
    connection.close()
    client_socket.close()

server:
import io
import socket
import struct
from PIL import Image

s = socket.socket()
host = '192.168.1.2' #ip of host
port = 12345
print("waiting")
s.bind((host, port))
print("waiting")
s.listen(5)
connection = s.accept()[0].makefile('rb')
print("waiting")
try:
        image_len = struct.unpack('<L',connection.read(struct.calcsize('<L')))[$
        image_stream = io.BytesIO()
        image_stream.write(connection.read(image_len))
        image_stream.seek(0)
        image = Image.open(image_stream)
        image.show()
        print('Image is verified')

finally:
    connection.close()
    s.close()

There were some mistakes in your code have corrected it this should work now.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Loop unroll issue with Visual Studio compiler I have some simple setup, where I noticed that VS compiler seems not smart enough to unroll loop, but other compilers like clang or gcc do so. Do I miss some optimization flag for VS?
#include <cstddef>

struct A
{
  double data[4];
  double *begin() { return data; }
  double *end() { return data + 4; }
  double const *begin() const { return data; }
  double const *end() const { return data + 4; }
};

double sum_index(A const &a) {
  double ret = 0;
  for(std::size_t i = 0; i < 4; ++i)
  {
    ret += a.data[i];
  }
  return ret;
}

double sum_iter(A const &a) {
  double ret = 0;
  for(auto const &v : a)
  {
    ret += v;
  }
  return ret;
}

I used https://godbolt.org/ compiler explorer to generate assembler code.
gcc 11.2 with -O3:
sum_index(A const&):
        pxor    xmm0, xmm0
        addsd   xmm0, QWORD PTR [rdi]
        addsd   xmm0, QWORD PTR [rdi+8]
        addsd   xmm0, QWORD PTR [rdi+16]
        addsd   xmm0, QWORD PTR [rdi+24]
        ret
sum_iter(A const&):
        movsd   xmm1, QWORD PTR [rdi]
        addsd   xmm1, QWORD PTR .LC0[rip]
        movsd   xmm0, QWORD PTR [rdi+8]
        addsd   xmm1, xmm0
        movupd  xmm0, XMMWORD PTR [rdi+16]
        addsd   xmm1, xmm0
        unpckhpd        xmm0, xmm0
        addsd   xmm0, xmm1
        ret
.LC0:
        .long   0
        .long   0

clang 13.0.1 with -O3:
sum_index(A const&):                       # @sum_index(A const&)
        xorpd   xmm0, xmm0
        addsd   xmm0, qword ptr [rdi]
        addsd   xmm0, qword ptr [rdi + 8]
        addsd   xmm0, qword ptr [rdi + 16]
        addsd   xmm0, qword ptr [rdi + 24]
        ret
sum_iter(A const&):                        # @sum_iter(A const&)
        xorpd   xmm0, xmm0
        addsd   xmm0, qword ptr [rdi]
        addsd   xmm0, qword ptr [rdi + 8]
        addsd   xmm0, qword ptr [rdi + 16]
        addsd   xmm0, qword ptr [rdi + 24]
        ret

MSVC 19.30 with /O2 (there is no /O3?):
this$ = 8
double const * A::begin(void)const  PROC                         ; A::begin, COMDAT
        mov     rax, rcx
        ret     0
double const * A::begin(void)const  ENDP                         ; A::begin

this$ = 8
double const * A::end(void)const  PROC                       ; A::end, COMDAT
        lea     rax, QWORD PTR [rcx+32]
        ret     0
double const * A::end(void)const  ENDP                       ; A::end

a$ = 8
double sum_index(A const &) PROC                     ; sum_index, COMDAT
        movsd   xmm0, QWORD PTR [rcx]
        xorps   xmm1, xmm1
        addsd   xmm0, xmm1
        addsd   xmm0, QWORD PTR [rcx+8]
        addsd   xmm0, QWORD PTR [rcx+16]
        addsd   xmm0, QWORD PTR [rcx+24]
        ret     0
double sum_index(A const &) ENDP                     ; sum_index

a$ = 8
double sum_iter(A const &) PROC                            ; sum_iter, COMDAT
        lea     rax, QWORD PTR [rcx+32]
        xorps   xmm0, xmm0
        cmp     rcx, rax
        je      SHORT $LN12@sum_iter
        npad    4
$LL8@sum_iter:
        addsd   xmm0, QWORD PTR [rcx]
        add     rcx, 8
        cmp     rcx, rax
        jne     SHORT $LL8@sum_iter
$LN12@sum_iter:
        ret     0
double sum_iter(A const &) ENDP                            ; sum_iter

Obviously there is problem with unrolling the loop for MSVC. Is there some additional optimization flag I have to set?
Thanks for help!


text:
Q: C# Getting most popular combination of 2 items in collection I have a collection of items, here it is:
    ID    ELECT1        ELECT2
    1      FDI           AED
    2      BPG           AED
    3      AED           FDI
    4      FDI           AED
    5      GPH           AED
    6      AED           BPG
    7      GPH           FDI

And I would like to group elect1 and elect2 and than output the 2 most popular so like
These items are chosen 3 times
FDI AED
AED FDI
FDI AED

And then the second most popular combination is
AED BPG
BPG AED

So the output would be
2 Most popular combinations are
    FDI AED
    AED BPG

I have written some code but I don't know how I could possibly do this
var groups = cStudent.GroupBy(x => new { x.elective1, x.elective2 });
foreach (var group in groups)
{
    Console.WriteLine("{0} / {1}:", group.Key.elective1, group.Key.elective2);
    foreach (var item in group)
    {
        Console.WriteLine("  {0} ({1})", item.elective1, item.elective2);
    }
}

So this is what I get with my code it is halfway there just don't know how to finish.
IMAGE

A: IMHO, the cleanest way to solve this is implementing a custom equality comparer that provides the needed equality semantics to solve your current problem:
class IgnoreElectiveOrderStudentEqualityComparer
    : IEqualityComparer<Student>
{
    public bool Equals(Student x, Student y)
        => (x.ElectiveOne == y.ElectiveOne &&
            x.ElectiveTwo == y.ElectiveTwo) ||
           (x.ElectiveOne == y.ElectiveTwo &&
            x.ElectiveTwo == y.ElectiveOne);

    public int GetHashCode(Student obj)
        => obj.ElectiveOne.GetHashCode() ^
           obj.ElectiveTwo.GetHashCode();
}

And now you simply use GroupBy and the custom comparer:
var mostPopular =
    students.GroupBy(s => s,
                     new IgnoreElectiveOrderStudentEqualityComparer())
            .OrderByDescending(g => g.Count())
            .Select(g => new
            {
                g.Key.ElectiveOne,
                g.Key.ElectiveTwo
            })
            .Take(2);

A: The trick is to have the order of the two electives of not matter so the alpha first one is always first (thus if you have (math, art) it is the same as (art, math):
var most_pop = cStudent.GroupBy(x => { if (string.Compare(x.elective1,x.elecitive2) > 0)
                                         return(new Tuple(x.elective1.x.elective2);
                                       else
                                         return(new Tuple(x.elective2,x.elective1);
                                     },
                                (b, a) => new {  Key = b, Count = a.Count() })
                .OrderyByDesending(x => x.Count).Take(2);

You could add a select of the key if you don't want an object with the count.

A: This should work for you:
cStudent
    .Select(x => new[] { x.elective1, x.elective2 }.OrderBy(y => y).ToArray())
    .GroupBy(x => Tuple.Create(x[0], x[1]), (k, g) => new { Elective = k, Count = g.Count() })
    .OrderByDescending(x => x.Count)
    .Select(x => new { elective1 = x.Elective.Item1, elective2 = x.Elective.Item2 })
    .Take(2)


text:
Q: How to find out how much memory in RAM is allocated to my shiny app I have an app that I have made with the package shinydashboard. It has three scripts: ui.R, server.R, and global.R. For a year this app has been hosted on shinyapps.io without a problem. It does however use an API to extract data from a database in Amazon web services. Over time the data grew and grew and eventually my app went over the 1GB of RAM memory that is allowed for the free account. I received the error, "exited normally with code 137, signal 9 (SIGKILL)". I looked at the logs in shinyapps.io and I saw that it said: "out of memory!". I decided to simplify my app and greatly reduce the amount of data imported with the API however I still was getting the same error.
I decided to use the package profvis to profile my app and to see what is running slow and what needs a great deal of memory allocation, but I can't tell exactly how much memory is being allocated to my app.
Here is an image of the flame graph
and here is the data section
Am I to understand that all the merges that I am doing is the thing that is taking up the most time in my app? Also when looking at the data section it says for the profvis row that 1251.1 MB of memory was allocated. Does that mean that's the total amount of memory needed for my app?


text:
Q: Add files/folders to a visual studio project using command line tool Is there a way to automatically add/include new files/folders into a Visual Studio project or to add/include them using a command line tool?

A: You can access Visual Studio automation from VB Script. See the following sample .vbs file that can be run as an executable:
Dim dte
Dim project

Set dte = CreateObject("VisualStudio.DTE.11.0")
dte.Solution.Open("C:\Users\sv\Documents\Visual Studio 2012\Projects\ConsoleApplication1\ConsoleApplication1.sln")

For Each project In dte.Solution.Projects
 If project.Name = "ConsoleApplication1" Then
  project.ProjectItems.AddFromFile("C:\Users\sv\Documents\Visual Studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\1.txt")
  project.Save(project.FullName)
 End If
Next

dte.Solution.Close()


text:
Q: Pods terminating in AWS EKS cluster because the pod limit is reached even with enought resources We have 4 t3.medium instances (technically 17 pods allowed), but at some point, a lot of services crash and can't be restarted because the pod limit is reached.
0/3 nodes are available: 1 Too many pods, 2 node(s) had taint {node.kubernetes.io/unreachable: }

The problem is, that we only have deployed 13 Services in total, with 1 replicasets. How is this possible?
Even the AWS management interface tells us, that there is free space for more pods.

A: your error message says that 3 nodes, not 4, and obviously maybe your 13 services running on only one node cause 2 of them are unreachable.
so first make sure that 2 nodes are reachable
then you shall make sure of application resources


text:
Q: FFT on a signal with a length that is not a multiple of the period of its harmonics I was very surprised to find an apparent limitation to a FFT on a simple signal.
Let's consider a timeseries made of L=100 points, and simply composed of the sum of two sinus waves: one with a wavelength of 7 points, the other with a wavelength of 13 points (the phase or amplitude does not matter).
If you compute the FFT of this signal, you won't find exactly the two harmonics, because L is not an exact multiple of 7 or 13.
How do you deal with this problem? Interpolation of the data on a higher resolution?
Edit : this problem can be "minimized" with zero padding


text:
Q: Find each field's max sequence number where unique identifier repeats I have a list of users, IDs, and activity time stamps. The data is ordered by user, ID, activity time, and a sequence number that is assigned based on all of these dimensions. I need to extract the earliest time stamp based on sequence number, then latest time stamp by sequence number for each user and ID. The problem is when the IDs repeat at a later time in the day or even the next day my code is not picking up the unique sequence of events for each ID.
So if user A performs 5 events on ID A123, then moves on the ID A567 to perform 6 events, then moves back to A123 to perform 4 additional tasks, I need the results to reflect first and last activity on ID A123, then A567, then A123 again.
Below is the current code I'm using to generate the table:
SELECT
user_id,
activity_date,
foc_id,
ROW_NUMBER() OVER ( PARTITION BY user_id, mno ORDER BY activity_date ) AS seq_num

FROM   cf.activity_history
MATCH_RECOGNIZE (
  PARTITION BY user_id
  ORDER     BY activity_date
  MEASURES
    MATCH_NUMBER() AS mno
  ALL ROWS PER MATCH
  PATTERN (same_foc_id * last_row  )
  DEFINE
    same_foc_id AS FIRST(foc_id) = NEXT(foc_id )
)

where
user_id in ('UVAC3','UVAH161','UVEK29','UVRB152')
and (activity_date < (sysdate - 11)
and activity_date > (sysdate - 13))

order by
user_id,
activity_date,
foc_id

enter image description here

A: This reads like a gaps and island problem: an island represents a series of "adjacent" rows where a user performs the same activity, and you want the start and end of each island.
One option uses lead() and lag(). Assuming that foc_id identifies the activities:
select user_id, activity_date, foc_id
from (
    select a.*,
        lead(foc_id) over(partition by user_id order by activity_date) lead_foc_id,
        lag(foc_id) over(partition by user_id order by activity_date) lag_foc_id
    from cf.activity_history a
    where
        user_id in ('UVAC3', 'UVAH161', 'UVEK29', 'UVRB152')
        and activity_date < sysdate - 11
        and activity_date > sysdate - 13
) a
where
    lead_foc_id is null
    or lag_foc_id is null
    or foc_id <> lead_foc_id
    or foc_id <> lag_foc_id


text:
Q: SQL Server - Refactor Large Union Query I have the following tables:
CREATE TABLE Forms (
    ID int NOT NULL PRIMARY KEY,
    FormName varchar
);

INSERT INTO Forms (ID, FormName)
VALUES (1, 'Password_Reset_Form'), (2, 'Service_Request_Form');

 CREATE TABLE Cases (
    ID int NOT NULL PRIMARY KEY,
    CreatedDt datetime
 );

 INSERT INTO Cases (ID, CreatedDt)
 VALUES (1, '2018-05-8'), (2, '2018-05-9'), (3, '2018-05-10');

 CREATE TABLE Password_Reset_Form (
    ID int NOT NULL PRIMARY KEY,
    CaseID int FOREIGN KEY REFERENCES Cases(ID),
    Subject varchar,
    FormName varchar FOREIGN KEY REFERENCES Forms(FormName)
 );

 INSERT INTO Password_Reset_Form (ID, CaseID, Subject, FormName)
 VALUES (1, 1, 'Password Issue', 'Password_Reset_Form');

 CREATE TABLE Service_Request_Form (
    ID int NOT NULL PRIMARY KEY,
    CaseID int FOREIGN KEY REFERENCES Cases(ID),
    Subject varchar,
    FormName varchar FOREIGN KEY REFERENCES Forms(FormName)
 );

 INSERT INTO Service_Request_Form (ID, CaseID, Subject, FormName)
 VALUES (1, 2, 'Add User', 'Service_Request_Form'), (1, 3, 'Delete User', 'Service_Request_Form');

When each type of form is submitted a new case is recorded in the Cases table and all the form data logged in the respective form table e.g. in the above case either the Password_Reset_Form table or Service_Request_Form table. I have over a 400 these type of form tables and each can contain different fields in addition to the CaseID, Subject and FormName fields.
I want to list all the forms and the number of cases raised for each form between certain dates.
I can do the following but I have to union 100's of tables
SELECT t2.FormName, COUNT(1) as TotalCases
FROM Cases t1
INNER JOIN (
   select CaseID, FormName FROM Password_Reset_Form
   union all
   select CaseID, FormName FROM Service_Request_Form
   /* 400 + more unions */ ) t2
WHERE t1.CreatedDt BETWEEN '2018-05-08' AND '2018-05-10'
GROUP BY t2.FormName

Is there a way I can use the Form table since that already has a list of form names to simplify the query i.e. use the FormName value from this table as table name in my union query or something?
* Note I cannot change the design as it's propriety database *

A: Yes, you could use the Form table. But you need some other additional structural changes if you want to avoid a large UNION query.
So it depends in how flexible the current database structure is. Are you allowed to change the table structures in your database? If so, I would create a single table for the forms instead of multiple tables. Suppose this table would be called FormCases. It would look like this:
CREATE TABLE FormCases (
    ID int NOT NULL PRIMARY KEY,
    FormID int FOREIGN KEY REFERENCES Forms(ID),
    CaseID int FOREIGN KEY REFERENCES Cases(ID),
    Subject varchar
);

INSERT INTO FormCases (ID, FormID, CaseID, Subject)
VALUES
    (1, 1, 1, 'Password Issue'),
    (1, 2, 2, 'Add User'),
    (1, 2, 3, 'Delete User');

Edit: Just saw you cannot change the DB. Then you're out of luck and you do need to use large UNION queries. Sorry.


text:
Q: How to use keyTextTransform() for nested json? My model has a json field. I can access jsonfield['key1'] with the following query
from django.contrib.postgres.fields.jsonb import KeyTextTransform
MyModel.objects.annotate(val=KeyTextTransform('key1', 'jsonfield')).order_by('val')

But how can I access a key like jsonfield['key1']['key2'] or even more nested ones?
This can't be the only solution, right?
MyModel.objects.annotate(val=KeyTextTransform('key2', (KeyTextTransform('key1', 'jsonfield'))).order_by('val')

A: The hard part is already done, thankfully. KeyTextTransform is composable. All we have to do is compose it.
class NestableKeyTextTransform:
    def __new__(cls, field, *path):
        if not path:
            raise ValueError("Path must contain at least one key.")
        head, *tail = path
        field = KeyTextTransform(head, field)
        for head in tail:
            field = KeyTextTransform(head, field)
        return field

MyModel.objects.annotate(
    single_nested_value=NestableKeyTextTransform(
      "json_field", "query", "name"
    ),
    array_access=NestableKeyTextTransform(
      "json_field", "query", "address_line", 1
    ),
)

Though I would like to point out that this may be a better way to do it:
from django.db.models import F

MyModel.objects.annotate(
    single_nested_value=F("json_field__query__name"),
    array_access=F("json_field__query__address_line__1"),
)

A: NB as of the start of 2023 (in django's development version) you can now also do:
from django.db.models.fields.json import KT
Dogs.objects.annotate(
     first_breed=KT("data__breed__1"),
     owner_name=KT("data__owner__name")
)

See docs and feature request


text:
Q: Numpy, BLAS and CUBLAS Numpy can be "linked/compiled" against different BLAS implementations (MKL, ACML, ATLAS, GotoBlas, etc). That's not always straightforward to configure but it is possible.
Is it also possible to "link/compile" numpy against NVIDIA's CUBLAS implementation?
I couldn't find any resources in the web and before I spend too much time trying it I wanted to make sure that it possible at all.

A: here is another possibility :
http://www.cs.toronto.edu/~tijmen/gnumpy.html
this is basically a gnumpy + cudamat environment which can be used to harness a GPU. also the same code can be run without the gpu using npmat. refer to the link above to download all these files.

A: In a word: no, you can't do that.
There is a rather good scikit which provides access to CUBLAS from scipy called scikits.cuda which is built on top of PyCUDA. PyCUDA provides a numpy.ndarray like class which seamlessly allows manipulation of numpy arrays in GPU memory with CUDA. So you can use CUBLAS and CUDA with numpy, but you can't just link against CUBLAS and expect it to work.
There is also a commercial library that provides numpy and cublas like functionality and which has a Python interface or bindings, but I will leave it to one of their shills to fill you in on that.


text:
Q: How to get the word under the cursor in Windows? I want to create a application which gets the word under the cursor (not only for text fields), but I can't find how to do that. Using OCR is pretty hard. The only thing I've seen working is the Deskperience components. They support a 'native' way, but I they cost a lot. Now I'm trying to figure out what is this 'native' way (maybe somehow of hooking). Any help will be appreciated.
EDIT:
I found a way, but it gets only the whole text of the control. Any idea how to get only the word under the cursor from the whole text?

A: This is non-trivial if the application you want to "spy" on is drawing the text themselves. One possible solution is to trigger the other application to paint a portion of it's window by invalidating the area directly under the cursor.
When the other application paints, you will have to intercept the text drawing calls. One way to do so is to inject code in the other application, and intercept calls into GDI functions that draw text. When you debug native applications, this is what visual studio does to implement breakpoints. To test the idea you could use a library like detours (but that's not free for commercial use).
You could also check if the application supports one of the accessability API's that are in Windows to facilitate things like screen readers for blind people.
One word of caution: I have not done any of this myself.

A: If the app need to handle not only .Net apps I would start with importing functions (P/Invoke):

*

*WindowFromPoint

*ChildWindowFromPointEx
Later you can iterate over the controls and try to get the text from inside based on type. If I will find some time I will try to publish such code.
After some checking it looks like the best way (unfortunately the hard also) is to hook into GDI text rendering some discussion

A: I'd echo what Patricker said, but I think there is no reliable way to do what you want.
You probably obtained the window text or something like that. But what if the cursor is over a window that doesn't use the window text to store its content? Windows are under no obligation to store their data in a particular way.
This ends up pointing you towards character recognition where you look at the pixels under the cursor and try and figure out what words are there. But not only is this very non-trivial, it also is not foolproof. What if part of the word is not visible because it extends out of the window?
This is definitely not trivial. There are a couple of ways to approach it. But there is no reliable way that will work with all windows.

A: On recent versions of Windows, the recommended way to gather information from one application to another (if you don't own the targeted application of course) is to use the UI Automation technology.
Wikipedia is pretty good for more information on this: Microsoft UI Automation
Basically, UI automation will use all necessary means to gather what can be gathered
Here is a small console application code that will spy the UI of other apps. Run it and move the mouse over to different applications. Each application has a different support for various "UI automation patterns". For example, there is the Value pattern and the Text pattern as demonstrated here.
static void Main(string[] args)
{
    do
    {
        System.Drawing.Point mouse = System.Windows.Forms.Cursor.Position; // use Windows forms mouse code instead of WPF
        AutomationElement element = AutomationElement.FromPoint(new System.Windows.Point(mouse.X, mouse.Y));
        if (element == null)
        {
            // no element under mouse
            return;
        }

        Console.WriteLine("Element at position " + mouse + " is '" + element.Current.Name + "'");

        object pattern;
        // the "Value" pattern is supported by many application (including IE & FF)
        if (element.TryGetCurrentPattern(ValuePattern.Pattern, out pattern))
        {
            ValuePattern valuePattern = (ValuePattern)pattern;
            Console.WriteLine(" Value=" + valuePattern.Current.Value);
        }

        // the "Text" pattern is supported by some applications (including Notepad)and returns the current selection for example
        if (element.TryGetCurrentPattern(TextPattern.Pattern, out pattern))
        {
            TextPattern textPattern = (TextPattern)pattern;
            foreach(TextPatternRange range in textPattern.GetSelection())
            {
                Console.WriteLine(" SelectionRange=" + range.GetText(-1));
            }
        }
        Thread.Sleep(1000);
        Console.WriteLine(); Console.WriteLine();
    }
    while (true);
}

UI automation is actually supported by Internet Explorer and Firefox, but not by Chrome to my knowledge. See this link: When will Google Chrome be accessible?
Now, this is just the beginning of work for you :-), because:

*

*Most of the time, all this has heavy security implication. Using this technology (or direct Windows technology such as WindowFromPoint) will require sufficient rights to do so (such as being an administrator). And I don't think DExperience has any way to overcome these limitations, unless they install a kernel driver on the computer.

*Some applications will not expose anything to anyone, even with proper rights. For example, if I'm writing a banking application, I don't want you to spy on what my application will display :-). Other applications such as Outlook with DRM will not expose anything for the same reasons.

*Only the UI automation Text pattern support can give more information (like the word) than just the whole text. Alas, this specific pattern is not supported by IE nor FF even if they support UI automation globally.
So, if all this does not work for you, you will have to dive deeper and use OCR or Shape recognition techniques. Even with this, there will be some cases where you won't be able to do it at all (because of security rights).

A: There is an sdk for getting the text using OCR. It's not free but it's quite cheap compared to other products: http://www.screenocr.com/screen-ocr-library-sdk.htm They have an application which provides the same features so you can try the demo too.

A: To achieve this you need a multi-pronged approach.
UIA does work in many applications but you need to experiment to see where the text is returned. It may be in Element, Value or Range. There is no consistency even across office applications.
If UIA fails then enumerate the running object table (ROT) and retreive the COM pointers to various apps registered in the ROT. You can then cast these pointers to the underlying office types:
for example:
enumerate ROT  - then
 wb = (Excel._Workbook)enumerator.Value;
string strText = wb.Application.ActiveCell.Text.ToString();

If the above two methods fail then make use of the free OCR system in MODI (Microsoft Office Document Imaging 12.0 Type Library)


text:
Q: Trying to position my date range picker across one row When I select the date range option from my dropdown button, the date range options appear on top of each other (see image below). I would like for them to appear in the same row.  One option I tried was playing with width, in both pixels and percentages, and when I added it, the entire card stretched to to the right. Does anybody know why this is happening?
This is how it normally looks prior to selecting "Date Range" from the dropdown menu.

When I select "Date Range", this is how it appears. Would like for it to be on one row, instead on top of each other.

When I play with the width property in CSS, the card stretches to the right, which is what I don't want.

ABC Corp - Summary

                @{
                    <select onchange="updateDates(this, null, null, null )">
                        <option value="0" selected></option>

                        @for (int i = 1; i < @Model.droplist i++)
                        {
                            var tempValue = i;
                            <option value="@tempValue">@Model.droplist.ElementAt(i)</option>
                        }
                    </select>
                }

                            <input id="startDate" name="startDate" type="text" class="form-control" style="background-color: inherit; width: 85px" placeholder="dd/mm/yyyy" value="@Model.StartDate">

                    to

                            <input id="endDate" name="endDate" type="text" class="form-control" style="background-color: inherit; width: 85px" placeholder="dd/mm/yyyy" value="@Model.EndDate">

                    <button id="btnTest" class="btn-orange fa-orange btn-sm" onclick="updateDateRanges()" style="margin-left: 10px">Submit</button>

Number of Deliveries

Deliveries per day

Gross Amount Due

Monthly Total

YTD Total

A: There was a structural issue. Try this

            @{
            <select onchange="updateDates(this, null, null, null )">
                <option value="0" selected></option>

                @for (int i = 1; i < @Model.droplist i++) { var tempValue=i; <option value="@tempValue">
                    @Model.droplist.ElementAt(i)</option>
                    }
            </select>
            }

                            <input id="startDate" name="startDate" type="text" class="form-control"
                                style="background-color: inherit; width: 85px" placeholder="dd/mm/yyyy"
                                value="@Model.StartDate">

                    to

                            <input id="endDate" name="endDate" type="text" class="form-control"
                                style="background-color: inherit; width: 85px" placeholder="dd/mm/yyyy"
                                value="@Model.EndDate">

                    <button id="btnTest" class="btn-orange fa-orange btn-sm" onclick="updateDateRanges()"
                        style="margin-left: 10px">Submit</button>


text:
Q: Status 200, but JSP in Spring only displaying un-rendered code Although my index.jsp opens in a browser with a Status 200 it only displays the JSP code.
I've read through what seem to be all related issues/solutions on this site, but none of the solutions have worked. e.g. adding jstl, jasper, etc. jars into my pom.xml and build path; mapping variations like "/", "/*", etc. No errors in the Spring log- just that JSPs aren't rendering or being "seen" as JSPs. My newest theories are that something is over-writing or conflicting, or that Spring needs something to "see" JSPs under the WEB-INF folder, but it's not easy to debug. Seems a stupid thing that a JSP doesn't render, so any insight would be helpful.
AppConfig
package mil.dfas.springmvc.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

/**
 * @author David Higgins
 */

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"mil.dfas.springmvc.controller"})
public class AppConfig {

    @Bean
    public InternalResourceViewResolver resolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setViewClass(JstlView.class);
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }
}

LMSInitializer
package mil.dfas.springmvc.config;

import java.util.EnumSet;

import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;

import mil.dfas.filters.LoginFilter;
import mil.dfas.filters.TimeoutFilter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

/**
 * The Spring MVC DispatcherServlet needs to be declared and mapped for all request processing.
 * In a Servlet 3.0+ environment, AbstractAnnotationConfigDispatcherServletInitializer class is used to register and initialize the DispatcherServlet programmatically.
 *
 * @author $Author: David Higgins $
 * @version $Revision: 1.0 $ $Date: 2019/05/12 $
 */

public class LMSInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    private static final Logger LOGGER = LoggerFactory.getLogger(LMSInitializer.class);

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        FilterRegistration timeoutFilter = servletContext.addFilter("timeoutFilter", new TimeoutFilter());
        timeoutFilter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "*.do");

        super.onStartup(servletContext);
    }
    @Override
    protected Filter[] getServletFilters() {
        LOGGER.info("LMSInitializer: Configuring Servlet Filters" );
        LoginFilter loginFilter = new LoginFilter();
        return new Filter[] {new LoginFilter()};
    }

    @Override
    protected Class <?> [] getRootConfigClasses() {
        return null;
    }

    @Override
    protected Class <?> [] getServletConfigClasses() {
        return new Class[] {AppConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] {"/"};
    }
}

LMSController
package mil.dfas.springmvc.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author David Higgins
 */
@Controller
public class LMSSpringController {

    @RequestMapping(value = "/index", method = RequestMethod.POST)
    public ModelAndView forward(Model model) {
        System.out.println("LMS Controller");

        model.addAttribute("msg","Forward Handled");

        return new ModelAndView("index");
    }
}

WEB-INF/views/index.jsp
No error messages. JSPs just don't displays as JSPs.
The problem must be something with the pom.xml. It must be a conflict with dependencies. I've added jasper, jstl, and others, but no change. Status 200 and no log errors, but no jsp rendering.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.7.RELEASE</version> <!-- 2.1.5.RELEASE ? -->
        <relativePath />
    </parent>

    <groupId>mil.dfas.springmvc</groupId>
    <artifactId>EmployeeDevelopment</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>
        <failOnMissingWebXml>false</failOnMissingWebXml>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>

        <!-- Spring-boot-starter -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId>
            </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>

        <!-- I think maybe including servlet dependencies is forcing servlet version
            to 4.0 since no versions are included, so Spring Boot parent will provide
            the defaults and maybe force latest version (?) A lot of this servlet stuff
            should already be included in Tomcat bin (on build path) -->

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <!-- <scope>provided</scope> -->
        </dependency>
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.1</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
        </dependency>

        <dependency>
            <groupId>com.keypoint</groupId>
            <artifactId>png-encoder</artifactId>
            <version>1.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.ant</groupId>
            <artifactId>ant</artifactId>
            <version>1.8.2</version>
        </dependency>
        <dependency>
            <groupId>xerces</groupId>
            <artifactId>xercesImpl</artifactId>
            <version>2.12.0</version>
        </dependency>
        <dependency>
            <groupId>org.jfree</groupId>
            <artifactId>jfreechart</artifactId>
            <version>1.0.14</version>
        </dependency>
        <dependency>
            <groupId>jfree</groupId>
            <artifactId>jcommon</artifactId>
            <version>1.0.16</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>xalan</groupId>
            <artifactId>xalan</artifactId>
            <version>2.7.2</version>
        </dependency>
        <dependency>
            <groupId>com.lowagie</groupId>
            <artifactId>itext</artifactId>
            <version>2.1.7</version>
        </dependency>

        <!-- As Oracle JDBC drivers are not in public Maven repositories (legal
            reasons) downloading the jar was the best available option. -->
        <dependency>
            <groupId>com.oracle.jdbc</groupId>
            <artifactId>ojdbc8</artifactId>
            <version>12.2.0.1</version>
            <scope>system</scope>
            <systemPath>${basedir}/src/lib/ojdbc8.jar</systemPath>
        </dependency>

        <!-- Added 5/17/19 DJM, may want to get directly from Maven repo -->
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mailapi</artifactId>
            <version>1.4.3</version>
        </dependency>

        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
        </dependency>
    </dependencies>

    <build>
        <sourceDirectory>src/main/java</sourceDirectory>
        <plugins>
            <plugin>
                <!-- <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source>
                    <target>1.8</target> </configuration> -->
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <!-- Package as an executable jar/war -->

        </plugins>
    </build>
</project>


text:
Q: Python, Matplotlib: How to set the axis range when x is time? I am doing my school Arduino project at home, and the teacher asks me to visualize my data for him. On my x-axis, I have more than 20K time points need to show, and I try to set a range for it.
The graph I am trying to achieve:

What I got up till now:

It is very clear I am doing something wrong, and I have researched for a way to solve it.
The # part of my plotting part is what I learned from the internet, but they do not work here.
Please help me and if anything in question is unclear, let me know!
import csv
import matplotlib.pyplot as plt
from datetime import datetime

header = []
data = []

path="DATALOG.csv"   #CHANGE filename to match file
file = open(path, newline='')
reader=csv.reader(file)

header=next(reader) #This reads the first row and stores the words in header.
data=[row for row in reader]  #This reads the rest and store the data in a list

file.close()  #closes the file when complete

# This function will print the headings with their index. Helpful when dealing with many columns
def print_header():
   for index, column_header in enumerate(header):
       print(index, column_header)

# I want the high and low temperatures in New Glasgow for June 2010
# Key headings
# 0 date/time
# 1 temperature
# 2 humidity %
# 3 light level%

days = []
light = []

for row in range (len(data)):
    day = data[row][0]
    lights = data[row][3]
    current_date=datetime.strptime(data[row][0], "%A %H:%M:%S %d/%m/%Y")

    light.append(float(lights))        #store the day's high temp in list
          #store the day's low temp in list
    days.append(str(day))

fig = plt.figure(dpi=128, figsize = (50, 6))

#x = [dc[0] for dc in days]

#xticks = range(0,len(x),10)
#xlabels=[x[index] for index in xticks]
#xticks.append(len(x))
#xlabels.append(days[-1][0])
#ax.set_xticks(xtick)
#ax.set_xticklabels(xlabels,rotation=40)

plt.plot(days,light,c = 'red',label = 'temprature')

plt.title("LIGHT")
plt.xlabel('days',fontsize = 5)
#ax.plot(np.arange('Wednesday 12:00:00 08/01/2020',' Thursday 11:58:10 09/01/2020'), range(10))
fig.autofmt_xdate()
plt.ylabel('light (%)', fontsize = 12)
plt.tick_params(axis='both', which='major', labelsize = 10)

plt.legend()
plt.show()
plt.savefig('plot.png')

A: Here an example of how you can plot your data using r:
As you did not provide a reproducible example, I created a fake one using my understanding of your code. Basically, it looks that you have a file with 4 columns: Days, Temperature, Humidity and Light_levels. Here, I only create two columns.
set.seed(123)
df <- data.frame(Day = as.character(seq.Date(from = as.Date("2019-01-01", format = "%Y-%m-%d"), to =as.Date("2019-02-01", format = "%Y-%m-%d"), by = "days" )),
                 Light_levels = sample(0:100,32, replace = TRUE))

The datafame df should looks like:
> head(df)
         Day Light_levels
1 2019-01-01           30
2 2019-01-02           78
3 2019-01-03           50
4 2019-01-04           13
5 2019-01-05           66
6 2019-01-06           41

I think your issue came from the management of date format. In r, it's pretty common that when you import a csv file as a dataframe, it will convert dates in a factor or character format.
You can check by looking at the structure of the dataframe by using str function:
> str(df)
'data.frame':   32 obs. of  2 variables:
 $ Day         : Factor w/ 32 levels "2019-01-01","2019-01-02",..: 1 2 3 4 5 6 7 8 9 10 ...
 $ Light_levels: int  30 78 50 13 66 41 49 42 100 13 ...

So, to use dates in a date format, you need to convert this factor format into a date format using:
df$Day = as.Date(df$Day, format = "%Y-%m-%d")

Now, if you check the structure of df, you will see:
str(df)
'data.frame':   32 obs. of  2 variables:
 $ Day         : Date, format: "2019-01-01" "2019-01-02" "2019-01-03" ...
 $ Light_levels: int  30 78 50 13 66 41 49 42 100 13 ...

Now, you can plot it with the package ggplot2(you have ton install ggplot2 first):
library(ggplot2)
ggplot(df, aes(x = Day, y = Light_levels))+
  geom_line()+
  scale_x_date(date_breaks = "days", date_labels = "%b %d")+
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

and get the following plot:

You can adjust the display of each dates by playing with arguments of scale_x_date (see more information here: https://ggplot2.tidyverse.org/reference/scale_date.html)
Alternatively, without to install ggplot2 package, you can do it using base R plot function:
plot(x = df$Day, y = df$Light_levels, type = "l", xaxt = "n", xlab = "")
axis.Date(1,at=seq(min(df$Day), max(df$Day), by="days"), format="%b %d")

Hope it will help you to figure it out how to plot your data.


text:
Q: Drag and Drop Image from UITableviewCell to other View I am working on a iPhone app, where I need to drag an image from UITableViewCell
and drop it in some other UIView outside the tableview.
(imageview added as :[cell.contentView addSubview:imageView]).
Please help me on this, any useful hint , sample code ?? Touch event delegates are not triggering since i am adding UIImageView to UITableViewCell.

A: You will not get much event in UIImageView so use UIButton and try something like this to drag:
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self action:@selector(imageTouch:withEvent:) forControlEvents:UIControlEventTouchDown];
[button addTarget:self action:@selector(imageMoved:withEvent:) forControlEvents:UIControlEventTouchDragInside];
[button setImage:[UIImage imageNamed:@"vehicle.png"] forState:UIControlStateNormal];
[self.view addSubview:button];

- (IBAction) imageMoved:(id) sender withEvent:(UIEvent *) event
{
    CGPoint point = [[[event allTouches] anyObject] locationInView:self.view];
    UIControl *control = sender;
    control.center = point;
}

when your center point match to other UIView use [UIView adSubview:] method to add UIButton in UIView
I have take this code from Basic Drag and Drop in iOS
Have a look at : Drag an Image within the Bounds of Superview


text:
Q: Swift MapKit Multiple Polylines with different colors I am trying to have different colors for each Polyline in MapKit in Swift.
Here is a simplified example.
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        if let overlay_ = overlay as? MKPolyline {
            let renderer = MKPolylineRenderer(overlay: overlay)
            if overlay_.title == "2" {
                renderer.strokeColor = UIColor.red
            } else {
                renderer.strokeColor = UIColor.blue
            }
            renderer.lineWidth = 5
            return renderer
        } else {
            return MKOverlayRenderer()
        }
    }

I have multiple polylines in a map where I set different overlay.title to differentiate between the colors.
Unfortunately it always take the last set color and applies it to all polylines.
In my example below I have 3 polylines with title: "0", "1" and "2". The result is red stroke color for all polylines.
Does anyone has an idea how to fix this? Do you need more code?
Code to add title:
  func showAllRoutes(map: MKMapView, route: Routes) {
    var coordinates: [CLLocationCoordinate2D] = []

    if dm.show_all_routes {
        for x in route.routes.indices {
            for y in route.routes[x].route_numbers {
                coordinates.append(CLLocationCoordinate2D(latitude: dm.alle_staende.locations[y].latitude, longitude:dm.alle_staende.locations[y].longitude))
            }

            let overlay = MKPolyline(coordinates: coordinates, count: coordinates.count)
            overlay.subtitle = "Route"
            overlay.title = "\(x)"

            map.addOverlay(overlay)

        }

    }
}

A: I believe your If statement isn't executed.your code seems right. I once did what you want to do, and the result as you see is what you want.

My code :
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if overlay is MKPolyline {
            let renderer = MKPolylineRenderer(overlay: overlay)
            renderer.strokeColor = .random()
            renderer.lineWidth = 0
            return renderer

        } else if overlay is MKPolygon {
            let renderer = MKPolygonRenderer(polygon: overlay as! MKPolygon)
            renderer.strokeColor = .random()

            renderer.fillColor = renderer.strokeColor?.withAlphaComponent(0.1)
            renderer.lineWidth = 2
            return renderer
        }

        return MKOverlayRenderer()
}

You better to check your code with this if statement
if overlay_.title == "2" {

   renderer.strokeColor = UIColor.red

} else {

   renderer.strokeColor = UIColor.blue
}

to see if your code is ok or not, set a random color just to test it.

A: Got it.
The problem is:
var coordinates: [CLLocationCoordinate2D] = []

It was placed wrong, it adds all lines and then they are basically the same. That's why they have the same color
 func showAllRoutes(map: MKMapView, route: Routes) {

    if dm.show_all_routes {
        for x in route.routes.indices {

            var coordinates: [CLLocationCoordinate2D] = []

            for y in route.routes[x].route_numbers {
                coordinates.append(CLLocationCoordinate2D(latitude: dm.alle_staende.locations[y].latitude, longitude:dm.alle_staende.locations[y].longitude))
            }

            let overlay = MKPolyline(coordinates: coordinates, count: coordinates.count)
            overlay.subtitle = "Route"
            overlay.title = "\(x)"

            map.addOverlay(overlay)

        }

    }
}


text:
Q: UIScrollView doesn't scroll even though nearly identical others do in same view controller I have a view controller's view laid out in IB, and in particular I have three views that all have identical layout constraints concerning their frames and have all been set to UIScrollView. Their content is different (I fade in one view and then another as the user navigates through a progression). I set all three of these views to UIScrollView and then I dropped the following code into my .m file in viewWillAppear:
NSArray <UIScrollView *> *viewsForScrolling = @[view1, view2, view3];
for (UIScrollView *smallView in viewsForScrolling) {
    NSLog(@"here is the class %@", [smallView class]);
    smallView.scrollEnabled = YES;
    smallView.contentSize = CGSizeMake(smallView.frame.size.width, smallView.frame.size.height*1.4);
    smallView.delegate = self;
}

This is doing the trick beautifully with view1 and view3 but view2 does not scroll. I have verified that they all have the same class, UIScrollView and that they are all wired to the instance variable I expected.
The principal difference between view2 and view1, view3 is that view 2 contains a UITableView for which scrolling is not enabled. That's the only difference I can figure out as compared to the other views.
I have also tried the following:

*

*for view2 I log the value of scrollingEnabled and userInteractionEnabed and these are both YES as I would desire

*I tried reordering the views in their z components within IB. This made no difference.

*I tried programmatically resizing the contentSize of view2 again outside the loop above thinking maybe it was 'not enough' but this was not the case

*I verified that scrollViewDidScroll is not running again when view2 is visible and the other views are not visible.

*I changed the background color of view2 to make sure it was as big as I thought it was and that I was indeed touching it when I tried to scroll. No dice.

*Per the suggestion below, I tried disabling user interaction for the tableview contained in view2. The interaction was disabled but this did not result in scrolling.

*Removing the scroll view entirely from view2 does enable scrolling in view2 but that's not really a solution.
I could really use another set of eyes and additional suggestions as to what to troubleshoot. Thank you.

A: Try making your viewController conform to UIGestureRecognizerDelegate protocol, set it as delegate for view2 and tableview, and implement the following protocol method this way:
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}


text:
Q: Regexp, greediness until second match I am trying something like this
^(.*)[\s]*(?:\[[\s]*(.*)[\s]*\])?$

My idea is that first match returns everything but the occasional second match which is anything inside []. Incoming string to match is already trimmed.
For instance
'aaaaa [] [ddd]' -> returns 'aaaa []' plus 'ddd'
'[] [ddd]' -> returns '[]' plus 'ddd'
'aaaaaaaa' -> returns 'aaaaaaa' plus NULL
'aaaaaaaa []' -> returns 'aaaaaaa' plus ''
'aaaaaa [' -> returns 'aaaaaa [' plus NULL
'aaaa [] ddd' -> returns 'aaaa [] ddd' plus NULL
'[a] [b] [c] [d]' returns '[a] [b] [c]' plus 'd' instead of '' plus 'a] [b] [c] [d'
'[fff]' -> return '' plus 'fff' <- That's particular since first match can never be null

My main problems are due to the first match, since both .* (swallows all) and *? (swallows only until first ] if multiple) give an undesired result
Pseudocode for algorithm would be something like:

*

*If last char is a ']', second match will be anything inside up to the
closest '[' backwards (if exist) -> this can be null or '' if input
string ends with '[]'

*Rest is first match, which cannot be NULL, only
''

Any suggestion?

A: If there are no nesting, you can use this regex:
^(.*?)\s*(?:\[([^\]]*)\])?$

regex101 demo
Otherwise, if you can have nested [] in the main [], then the regex will have to be revised. You can make a regex for nested [] but only up to a certain level of nesting; if you have up to 2 levels of nesting, you make a regex for 2, if you have up to 5 levels of nesting, you make a more complex one for 5, etc.

A: I'm not sure to understand what you want to do but, here is a try : /(.*?)\[(.*?)\]$/.
Another try, allowing the second group to remain undefined : /(.*?)(?:\[(.*?)\])?$/.
I have never used Scriptular but here is what Chrome's console says :
// result : [full match, group 1, group 2]
'abc'.match(/(.*?)(?:\[(.*?)\])?$/) // ["abc", "abc", undefined]
'[abc]'.match(/(.*?)(?:\[(.*?)\])?$/) // ["[abc]", "", "abc"]

What about this one : /(.*?)(?:\[([^\[]*?)\])?$/?
'aze[[[rty]'.match(/(.*?)(?:\[([^\[]*?)\])?$/) // ["aze[[[rty]", "aze[[", "rty"]

Last try : /(.+?)(?:\[([^\[]*?)\])?$/.
test         result
-------------------------------------------
''           null
'aze'        ["aze", "aze", undefined]
'[rty]'      ["[rty]", "[rty]", undefined]
'aze[rty]'   ["aze[rty]", "aze", "rty"]
'aze[]'      ["aze[]", "aze", ""]
'aze[][rty]' ["aze[][rty]", "aze[]", "rty"]
'aze[[]rty]' ["aze[[]rty]", "aze[", "]rty"]

A: I think regular expressions are not the answer here, especially because you give a simple algorithm to solve the problem. Just translate your algorithm into code.
Also regular expressions are not the solution because you have unbalanced and nested [] as you state in your comments, which make regex impractical.
Try some javascript like this :
function parse ( text ) {
    var first, inside;
    if ( text.substr (-1) == ']' ) {
        var pos = text.lastIndexOf ('[');
        first = text.substr (0, pos);
        inside = text.substr ( pos + 1, text.length -pos - 1);
    } else {
        first = text;
     }
     return [ first, inside ];
}


text:
Q: jQuery and $ not defined in ASP.NET Core project using webpack I'm developing an ASP.NET Core project, and recently switched out the default bootstrap and jQuery libraries for the npm packages to be able to theme bootstrap. I noticed, however, that jQuery doesn't seem to load in properly, or at all; with errors like $ is not defined and jQuery is not defined.
I tried fixing updating webpack to v5 from v4, and use dependOn on the entries, but that also did not fix the issue. I feel like the load order is to blame here, but everything I've tried didn't work. When looking at the bundled files, jQuery is always last to be loaded.
webpack.config.js:
const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const {CleanWebpackPlugin} = require('clean-webpack-plugin');

const bundleFileName = 'bundle';
const dirName = 'wwwroot/dist';

module.exports = (env, argv) => {
    return {
        mode: argv.mode === "production" ? "production" : "development",
        entry: ['./node_modules/jquery/dist/jquery.js', './node_modules/bootstrap/dist/js/bootstrap.bundle.js', './wwwroot/js/site.js', './wwwroot/scss/site.scss', './node_modules/jquery-validation/dist/jquery.validate.js', './node_modules/jquery-validation-unobtrusive/dist/jquery.validate.unobtrusive.js'],
        output: {
            filename: bundleFileName + '.js',
            path: path.resolve(__dirname, dirName)
        },
        module: {
            rules: [
                {
                    parser: {
                        amd: false,
                    },
                    test: /\.s[c|a]ss$/,
                    use:
                        [
                            'style-loader',
                            MiniCssExtractPlugin.loader,
                            'css-loader',
                            {
                                loader: 'postcss-loader', // Run postcss actions
                                options: {
                                    postcssOptions: {
                                        plugins: function () { // postcss plugins, can be exported to postcss.config.js

                                            let plugins = [require('autoprefixer')];

                                            if(argv.mode === "production") {

                                                plugins.push(require('cssnano'));
                                            }

                                            return plugins;
                                        }
                                    }
                                }
                            },
                            'sass-loader'
                        ]
                }
            ]
        },
        plugins: [
            new CleanWebpackPlugin(),
            new MiniCssExtractPlugin({
                filename: bundleFileName + '.css'
            })
        ]
    };
};

package.json:
{
  "name": "proj2aalst-g3",
  "version": "1.0.0",
  "scripts": {
    "build": "webpack --progress --profile",
    "production": "webpack --progress --profile --mode production"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "autoprefixer": "^10.0.1",
    "clean-webpack-plugin": "^3.0.0",
    "css-loader": "^4.3.0",
    "cssnano": "^4.1.10",
    "file-loader": "^6.1.0",
    "mini-css-extract-plugin": "^0.11.2",
    "node-sass": "^4.14.1",
    "postcss-loader": "^4.0.2",
    "sass-loader": "^10.0.2",
    "style-loader": "^1.2.1",
    "webpack": "^4.44.2",
    "webpack-cli": "^3.3.12"
  },
  "dependencies": {
    "@popperjs/core": "^2.9.1",
    "bootstrap": "5.0.0-beta2",
    "jquery": "3.6.0",
    "jquery-validation": "^1.19.3",
    "jquery-validation-unobtrusive": "^3.2.12",
    "postcss": "^8.2.9"
  }
}

A: You have to add the jQuery to the plugins like so:
plugins: [
   new webpack.ProvidePlugin({
      $: "jquery",
      jQuery: "jquery"
   })
]

This means, if webpack encounters $ or jQuery it will inject the plugin.


text:
Q: Background fade in on click I am trying get this background to fade in on click. I found one tutorial that was helpful, and I ended up created the code so it has two images, and they fade in and out on click to bring up the picture.
Here's the work: http://www.mccraymusic.com/bgchangetest.html
Only a couple of issues though:

*

*How do I make this work without the images getting selected at random? I'd like it to just switch from the plain black image to the image with the drum set. (And cross-fade to if possible, but not necessary)

*How do I center the image on the page, so the image of the drums are centered?

A: I'm guessing this is what you're after:
$(function() {
    var images = ["black.jpg","bg.jpg"];
    $('<img>').attr({'src':'http://www.mccraymusic.com/assets/images/'+images[0],'id':'bg','alt':''}).appendTo('#bg-wrapper').parent().fadeIn(0);

    $('.entersite').click(function(e) {
        e.preventDefault();
        var image = images[1];
        $('#bg').parent().fadeOut(200, function() {
            $('#bg').attr('src', 'http://www.mccraymusic.com/assets/images/'+image);
              $(this).fadeIn(1000);
        });
        $(this).fadeOut(1000, function() {
            $(this).remove();
        });
    });
});

DEMONSTRATION
Also added :
display: block;
margin-left: auto;
margin-right: auto;

to your #bg element to center the image.

A: Alright, assuming you use JQuery
You have #backgroundid and #imageid
Begin by setting
$('#backgroundid').css('opacity',1);
$('#imageid').css('opacity',0); // setting opacity (transparency) to 0, invisible

Now you have #buttonid.
Set up a jquery event so that when it's clicked, you fade out the background, and fade in the image using JQuery's animate.
$('#buttonid').click(function() {
    $('#backgroundid').animate(function() {
        opacity : 0 // fade it to 0 opacity, invisible
    }, 1000); // animation will take 1000ms, 1second
    $('#imageid').animate(function() {
        opacity : 1 // fade it to full opacity, solid
    }, 1000);
});

Now about that image centering.
You can either let css manage it with
body { /* Body or #imageid parent */
    text-align : center;
}
#imageid {
    margin: 0px auto;
}

Or you can stick to a JQuery solution, using absolute/fixed positioning.
First, use some css to fix the position of your image
#imageid {
    position: absolute; // or fixed, if you want
}

Now use JQuery to reposition it
function positionImage() {
    var imagewidth = $('#imageid').width();
    var imageheight = $('#imageid').height();
    $('#imageid').css('left', ($(window).width() - imagewidth) / 2);
    $('#imageid').css('top', ($(window).height() - imageheight) / 2);
}
$(document).ready(positionImage); // bind the ready event to reposition
$(window).resize(positionImage); // on window resize, reposition image too

A: if you keep a div element with height and width as 100% and bgcolor as black. And then change the opacity of the div as desired to get the fade in/out effect, that should generate the same effect. I guess..

A: You are better off using any available jQuery plugin as they would have optimized and fixed bugs for multiple browsers.
Try lightBoxMe plugin
http://buckwilson.me/lightboxme/
This is the simplest plugin available!


text:
Q: Как манипулировать изображением внутри элемента SVG? Проблема: не могу разобраться в правилах поведения изображения, являющегося заливкой svg-элемента с тегом <path>.
Я уже не знаю какие ключевые слова надо вбить в поисковик, чтобы найти соответствующую документацию, мучаюсь три месяца.
В тех статьях, что удается нагуглить описываются только примеры с <rect> и везде указано, что высота и ширина изображения задаются в теге <pattern>, но пытаясь их изменить в своем коде изображение только двигается по координатам, а иногда не двигается, или обрезается.
Каким-то чудом все-таки увеличивается иногда, но попытки воспроизвести то же самое с другим элементом заканчиваются провалом, так как изображения для фона не всегда удается подобрать одинакового разрешения.
Пытался убирать и viewbox и свойства ширины и высоты из тегов по очереди.  Собственно сам код:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 360 330">
    <defs>
        <style>.a{fill:url(#test);stroke:#000;stroke-width:10px;}</style>
        <pattern id="test" patternUnits="userSpaceOnUse" width="100%" height="100%"
    viewbox="0 0 360 330">
            <image xlink:href="https://i.pinimg.com/originals/4b/d7/fb/4bd7fb27221140b0c023e8fbec2b1285.jpg"
    width="100%" height="100%" />
        </pattern>
    </defs>

    <path class="a" d="M198.5,85.5c-65.45,5.64-120.09,40.55-136,90-15.1,46.95,9.53,92,27,124,16.24,29.73,37.8,69.19,81,84,37.9,13,71-.35,132-25,64.15-25.9,103-41.61,113-76,9.75-33.68-19.45-46.52-27-115-6.07-55,9.88-72.84-3-91C371.05,56.13,327.2,45.06,198.5,85.5Z"/>
</svg>

Никак не могу понять, какой из width и height за какое конкретно преобразование изображения отвечает.
Подскажите, пожалуйста, как друг от друга зависят viewbox в тегах <svg> и <pattern>, и как от них зависит каждый из значений width и height в тегах <pattern> и <image>?
И есть ли смысл манипулировать размером используемого для заливки изображения?
Может у меня имеются лишние свойства?
Какое свойство отвечает за увеличение этого изображения, не увеличивая размер самого svg-элемента, в конце концов?
Координаты (х,у) специально не задавал, так как они и без документации понятно чем управляют.

A: У вас несколько объектов и факторов, которые отвечают за размеры и масштабирование элементов SVG.
Нужно разделить ваш код на несколько простых частей и разобраться, как получить необходимые размеры и отчего зависит масштабирование.
Выбранное изображение имеет размеры 1920 х 1080px

*

*В  SVG  размеры, показанного изображения, зависят от соотношения:
Если viewport / viewBox = 1,
то при равенстве размеров, изображение выводится в том же масштабе, как нарисовано.
viewport это width и height в шапке SVG

<svg xmlns="http://www.w3.org/2000/svg" width="1920" height="1080" viewBox="0 0 1920 1080">
    <image xlink:href="https://i.stack.imgur.com/h0qca.jpg"
    width="100%" height="100%" />

</svg>

*При viewport / viewBox < 1 Изображение уменьшается

Например, для уменьшения изображения в два раза, уменьшаем width="960" и height="540" в два раза, при тех же значениях viewBox="0 0 1920 1080"

<svg xmlns="http://www.w3.org/2000/svg" width="960" height="540" viewBox="0 0 1920 1080">
    <image xlink:href="https://i.stack.imgur.com/h0qca.jpg"
    width="100%" height="100%" />
</

То есть два пикселя, взятые во viewBox, уплотняются в один пиксель vireport за счёт этого происходит уменьшение размера

*При viewport / viewBox > 1 происходит увеличение размера.
В этом случае, как раз возможна обрезка изображения

<svg xmlns="http://www.w3.org/2000/svg" width="1920" height="1080" viewBox="0 0 960 540">
    <image xlink:href="https://i.stack.imgur.com/h0qca.jpg"/>
 </svg>

viewBox="0 0 960 540" стал в два раза меньше, то есть захватил только половину изображения, остальное обрезалось, но в оставшейся части один пиксель viewBox растягивается до двух пикселей viewport, поэтому изображение увеличивается.
Другими словами viewport (это width, height SVG> это своеобразное окно, в котором мы видим результат вычислений масштабирования.
Для простоты усвоения, запомните простое правило: у viewBox всё наоборот:

*

*при увеличении viewBox изображение уменьшается

*при уменьшении viewBox изображение увеличивается

Более подробные объяснения с примерами можно посмотреть здесь
Практические советы
На первых шагах освоения SVG избегайте вложенных viewBox, так как при этом происходит многократное масштабирование и позиционирование, в которых легко запутаться.
Речь идет в этом конкретном примере о viewBox в pattern. Лучше указать фиксированные размеры.
Паттерн можно представить, как какую-то площадь, имеющие размеры, допустим 1920х1080px, которую нужно заполнить плитками допустим 100х100 px
Заполнение идет порядно. Итого должно быть 19 плиток по горизонтали и 10 целых плиток по вертикали.   Подробнее здесь

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1900 1080">
    <defs>
      <!--Одна плитка 100х100px в паттерне -->
     <pattern id="test" patternUnits="userSpaceOnUse" width="100px" height="100px">
            <rect width="100" height="100" fill="none" stroke="red" />
        </pattern>
    </defs>
    <!-- Заполняемый плитками объект-->
   <rect  width="100%" height="100%" fill="none" stroke="black" stroke-width="4" style="fill:url(#test)" />

</svg>

Вместо нескольких плиток вы можете добавить в паттерн фотообои, то есть изображение.
Необходимо, чтобы размеры паттерна и картинки совпадали.

.a {
fill:url(#test);
}
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1900 1080">
    <defs>
         <pattern id="test" patternUnits="userSpaceOnUse" width="1900px" height="1080px">
            <image xlink:href="https://i.stack.imgur.com/h0qca.jpg" width="1900" height="1080"  />
        </pattern>
    </defs>
   <rect class="a"  width="100%" height="100%" rx="3%" />

</svg>

Как видно, изображение получилось респонсивно.
Теперь вместо прямоугольника вы можете создать любой криволиниейный объект и заполнить его паттерном fill:url(#test);

.a{
 fill:url(#test);
 stroke:#000;
 stroke-width:10px;
 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1900 1080">
    <defs>
         <pattern id="test" patternUnits="userSpaceOnUse" width="1900px" height="1080px">
            <image xlink:href="https://i.stack.imgur.com/h0qca.jpg" width="1900" height="1080"  />
        </pattern>
    </defs>

    <path  class="a" d="M198.5,85.5c-65.45,5.64-120.09,40.55-136,90-15.1,46.95,9.53,92,27,124,16.24,29.73,37.8,69.19,81,84,37.9,13,71-.35,132-25,64.15-25.9,103-41.61,113-76,9.75-33.68-19.45-46.52-27-115-6.07-55,9.88-72.84-3-91C371.05,56.13,327.2,45.06,198.5,85.5Z"/>
</svg>

Теперь размер вырезанного изображения зависит от размеров кривой (path class="a")


text:
Q: how to accept value in date format in textbox in C# windows form? I have a Field in my windows form that asks user to enter their Birth Date...
How do i validate my form to accept only numbers and "/"( separator Symbol ) and also in dd/mm/yyyy format..
Also day should be less than 31, Month should be less than 12 and Year not greater than 2012

A: Textbox is not the control to accept datetime input. There is a built in control DateTimePicker that should be used instead. The problem with your approach is that even if you do masking of textbox for one format like dd/mm/yyyy user may want to enter in mm/dd/yyyy. So, quite a lot of error handling. Whereas you need not worry about any such thing in case of datetimepicker.
Even then if you want to go with textbox. Do this,
DateTime dt;
if (DateTime.TryParseExact(yourTexbox.Text.Trim(), "yourformattoaccept", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
   //your code if parsing is successful
}

A: I think you should go for DateTimePicker, however we can also use a TextBox with some Validating. There are many kinds of validating data. We can prevent user from typing invalid data or we can also check the data after user submitting. Here I'll introduce you the second approach because the first requires more code to do, it may prevent user from typing invalid data but it also has to prevent user from pasting invalid data. That's why the first approach needs more code.
For the second approach you can add code to a Validating event handler for your TextBox and use a little Regex like this:
private void textBox1_Validating(object sender, CancelEventArgs e)
    {
        Regex reg = new Regex(@"^(\d{1,2})/(\d{1,2})/(\d{4})$");
        Match m = reg.Match(textBox1.Text);
        if (m.Success)
        {
            int dd = int.Parse(m.Groups[1].Value);
            int mm = int.Parse(m.Groups[2].Value);
            int yyyy = int.Parse(m.Groups[3].Value);
            e.Cancel = dd < 1 || dd > 31 || mm < 1 || mm > 12 || yyyy > 2012;
        }
        else e.Cancel = true;
        if (e.Cancel)
        {
            if (MessageBox.Show("Wrong date format. The correct format is dd/mm/yyyy\n+ dd should be between 1 and 31.\n+ mm should be between 1 and 12.\n+ yyyy should be before 2013", "Invalid date", MessageBoxButtons.OKCancel, MessageBoxIcon.Error) == DialogResult.Cancel)
                e.Cancel = false;
        }
    }

You can add some Submit button to your form together with your textBox1 to test. I hope you know how to register the Validating event handler for your textBox1.

A: You make your life easier if you use the datatimepicker but if you still feel you want to present a textbox and help the user to prevent entering an illegal date this sample code will get you going.
I surpress keys and validate the textentry on exit of the field and prevent leaving if there is no valid date.
private void textBox1_Validating(object sender, CancelEventArgs e)
{
    TextBox tb = sender as TextBox;
    if (tb != null)
    {
        DateTime res;
        e.Cancel = !DateTime.TryParse(tb.Text, out res);
        if (e.Cancel)
        {
           // if you have an errorProvider...
           this.errorProvider1.SetError(
                 tb,
                 String.Format("'{0}' is not a valid date", tb.Text));
        }
    }
}

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    // add extra checks to determine if
    // this char is allowed, set Handled to
    // false. If you want to surpress the key
    // set it to true
    // get the current separator or have your own, then simply say @"/"
    var dateSep = CultureInfo.CurrentCulture.DateTimeFormat.DateSeparator;
    e.Handled = !(Char.IsDigit(e.KeyChar) ||
                (dateSep.IndexOf(e.KeyChar)>-1) ||
                Char.IsControl(e.KeyChar));
}

A: Do you want to do the validation after the user is done? In that case you could just try to parse the string as a date and see if it is a correct date. In that case you also get the days in month right.


text:
Q: Client seeing different version of page. Issues with Centering I'm having a few issues with a site I'm working on for a client which launched today. On my machine and my iphone everythings looks to spec, but on their machines they're seeing many issues.
there machine

my machine

there machine

my machine

I've tried clearing my browser cache, and I don't have any caching plugins on the wordpress so I'm not sure why I don't see the issues she is having. We're both using safari on macs as well.
It seems like there is an issue with centering. Can anyone figure out what's going on? I'm in a bit of a bind.
Heres the landing page
<div class="homepagewrap" id="portbgimage1" style="background-image: url('<?    php the_field('MC_homepagebackground'); ?>');">

            <a href="<?php bloginfo('url');?>/portfolio/"><img src="<?php     the_field('homepage_logo'); ?>">

617-227-5343  ∙  info@mcarterandco.com

and css
.homepagewrap{
background-attachment: fixed;
background-size: cover;
position: relative;

height:100vh;
box-sizing: border-box;
border: 20px solid rgba(0,0,0,0);
}

.logohome{
box-sizing: border-box;
padding: 10px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.logohome img{
max-width: 80%;
margin-left: 10%;
}

the second page

<a href="<?php bloginfo('url');?>/newclassic/">The New Classic

<div class="portbgimage" id="portbgimage1" style="background-image: url('<?php     the_field('portupload1'); ?>');">

<a href="<?php bloginfo('url');?>/artful-mix/">The Artful Mix

<div class="portbgimage" id="portbgimage2" style="background-image: url('<?php     the_field('portupload2'); ?>');">

<a href="<?php bloginfo('url');?>/historic-home/">The Historic Home

<div class="portbgimage" id="portbgimage3" style="background-image: url('<?php     the_field('portupload3'); ?>');">

<a href="<?php bloginfo('url');?>/escape/">The Escape

<div class="portbgimage" id="portbgimage4" style="background-image: url('<?php     the_field('portupload4'); ?>');">

and accompanying css
.portwrap{
position: relative;
float: left;
width: 50%;
height: 50%;
background-size: cover;
}

.portbgimage{
width:100%;
height:100%;
}

#portwrap1{
border-top: 20px solid #E0E0E0;
border-right: 10px solid #E0E0E0;
border-bottom: 10px solid #E0E0E0;
border-left: 20px solid #E0E0E0;
box-sizing: border-box;
}
#portwrap2{
border-top: 20px  solid #E0E0E0;
border-right: 20px solid #E0E0E0;
border-bottom: 10px solid #E0E0E0;
border-left: 10px solid #E0E0E0;
box-sizing: border-box;
}

#portwrap3{
border-top: 10px solid #E0E0E0;
border-right: 10px solid #E0E0E0;
border-bottom: 20px solid #E0E0E0;
border-left: 20px solid #E0E0E0;
box-sizing: border-box;
}

#portwrap4{
border-top: 10px solid #E0E0E0;
border-right: 20px solid #E0E0E0;
border-bottom: 20px solid #E0E0E0;
border-left: 10px solid #E0E0E0;
box-sizing: border-box;
}

.portwrapchild {
/*overflow: hidden;*/
z-index:99;
text-align: center;
font-family: 'Crimson Text', serif;
font-style: italic;
font-weight: 200;
font-size: 3.5em;
color: #E0E0E0;
width: 100%;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
transition: opacity .5s ease-in-out;
-moz-transition: opacity .5s ease-in-out;
-webkit-transition: opacity .5s ease-in-out;
}

A: Without knowing much else besides the small snippets of code you provided, you have not included browser-specific prefixes that make things work in older versions of different browsers.
So something like
-webkit-box-sizing:border-box;
 -moz-box-sizing:border-box;
 box-sizing:border-box;
would possibly help. Be sure to put the prefixes before the non-prefixed version, and to apply to other CSS attributes you are using that also need prefixes, like transform and background-size:cover


text:
Q: Codeigniter Social Register - Integration I'm using https://github.com/falexandrou/Codeigniter-Social-Register library for twitter login and get allow for my application. Everything okay till allow page of twitter. I'm allowing my application and click to allow button, it says you are redirecting to page but it goes allow page again. What is solve of this error?
My settings of my twitter application;
http://s1308.hizliresim.com/1d/4/r3yk8.jpg


text:
Q: Mysql query to convert table from long format to wide format I have a table called ContactAttrbiutes which contains a list of each contacts' attributes. The kind of data stored for these contacts include: Title, Forename, Surname telephone number etc.
Current Table
+-------------+-----------+------------------------------+
| attributeId | ContactId | AttributeValue               |
+-------------+-----------+------------------------------+
|           1 |         5 | Lady                         |
|           2 |         5 | Elizabeth                    |
|           3 |         5 | E                            |
|           4 |         5 | Anson                        |
|           5 |         5 |                              |
|           6 |         5 |                              |
|           7 |         5 |                              |
|           8 |         5 |                              |
|          10 |         5 | 0207 72776                   |
|          11 |         5 |                              |
|          12 |         5 | 0207 22996                   |
|          13 |         5 | 0207 72761                   |
|          14 |         5 |                              |
|          15 |         5 |                              |
|          60 |         5 | Lloyds                       |
|          61 |         5 |                              |
|           1 |        10 | Mr                           |
|           2 |        10 | John                         |
|           3 |        10 | J C                          |
|           4 |        10 | Beveridge                    |
|           5 |        10 | Esq QC                       |
|           6 |        10 | Retired                      |
|           7 |        10 |                              |
|           8 |        10 |                              |
|          10 |        10 | 0207 930                     |
|          11 |        10 |                              |
|          12 |        10 |                              |
|          13 |        10 | 0207 930                     |
|          14 |        10 |                              |
|          15 |        10 |                              |
|          60 |        10 |                              |
|          61 |        10 |                              |
+-------------+-----------+------------------------------+

However I would like to run a query to create a table that looks like...
New Table
+-----------+----------------------+-------------------------+-----------------------+------------------------+
| ContactId | AttributeValue_Title | AttributeValue_ForeName |AttributeValue_Initial | AttributeValue_Surname |
+-----------+----------------------+-------------------------+-----------------------+------------------------+
| 5         | Lady                 | Elizabeth               | E                     |  Anson                 |
+-----------+----------------------+-------------------------+-----------------------+------------------------+
| 10        | Mr                   | John                    | J C                   | Beveridge              |
+-----------+----------------------+-------------------------+-----------------------+------------------------+

I am sure there is a very simple answer but I have spent hours looking. Can anyone help?
The above is only a small extract of my table, I have 750,000 contacts. In addition I would like the final table to have more columns than I have described above but they will come from different Attributes with the existing table.
Thank you very much in advance.

A: try this
    SELECT ContactId ,
 max(CASE when attributeId = 1 then AttributeValue end) as AttributeValue_Title ,
 max(CASE when attributeId = 2 then AttributeValue end )as AttributeValue_ForeName ,
 max(CASE when attributeId = 3 then AttributeValue end )as AttributeValue_Initial ,
 max(CASE when attributeId = 4 then AttributeValue end) as AttributeValue_Surname
 from Table1
 group by ContactId

DEMO HERE

*

*if you want to make your result more longer for other attributeId then just add a case statment as in the code.

A: SELECT
    t_title.AttributeValue AS title,
    t_name.AttributeValue AS name,
    ...
FROM the_table AS t_title
JOIN the_table AS t_firstname USING(contact_id)
JOIN ...
WHERE
    t_title.attributeId = 1 AND
    t_firstname.attributeId = 2 AND
    ...

EAV "model" is an antipattern in most cases. Are you really going to have a variable number of attributes? If yes, then no-SQL solution might be more appropriate than a relational database.


text:
Q: pyglet - WindowsError: exception: access violation reading 0x00000000 I am testing pyglet on my laptop using this code:
import pyglet

window = pyglet.window.Window()

@window.event
def on_key_press(symbol, modifiers):
    print 'A key was pressed'

@window.event
def on_draw():
    window.clear()

pyglet.app.run()

I get this error:
Traceback (most recent call last):
  File "F:\Python Games\New Game\main.py", line 3, in <module>
    window = pyglet.window.Window()
  File "_build\bdist.win32\egg\pyglet\__init__.py", line 357, in __getattr__
  File "_build\bdist.win32\egg\pyglet\window\__init__.py", line 1817, in <module>
  File "_build\bdist.win32\egg\pyglet\gl\__init__.py", line 205, in _create_shadow_window
  File "_build\bdist.win32\egg\pyglet\window\win32\__init__.py", line 131, in __init__
  File "_build\bdist.win32\egg\pyglet\window\__init__.py", line 559, in __init__
  File "_build\bdist.win32\egg\pyglet\window\win32\__init__.py", line 263, in _create
  File "_build\bdist.win32\egg\pyglet\gl\win32.py", line 203, in attach
WindowsError: exception: access violation reading 0x00000000
[Finished in 2.313s]

My laptop is quite old. I am running windows 10;


text:
Q: Is $SL_1(D)$ toplogically finitely generated, for $D$ a division algebra over a local field? I've been struggling with this one all day, and I was wondering if someone can give me a hand with the proof. I'm not even sure if the group in question is finitely generated, so I would appreciate if anyone will tell me otherwise as well.
remark 1 I've posted this question on Math.stackexchange as well, and am posting here since I don't seem to get any replies. I don't know if this question is "MO standard", but I guess there's no harm in trying :-P..
remark 2 For infinite topological groups, I write $G$ is finitely generated to mean that $G$ has a dense subgroup which is finitely generated (i.e. $G$ is topologically finitely generated).
Let $F\supseteq \mathbb{Q}_p$ be a local field, and let $D$ be a finite dimensional division algebra over $F$, of degree $n$ (i.e $\dim_F D=n^2$).
It is known that $D$ contains an unramified extension $E$ of $F$, such that $E/F$ is cyclic Galois. It follows that $D$ contains an element $u\in D^\times$, and that there is some $\pi\in F$ such that $D=\bigoplus_{j=0}^{n-1}u^j E$, $u^n=\pi$ and such that the restriction of the map $x\mapsto u^{-1}xu$ to $E$ is a generator of the Galois group $\mathbf{G}(E/F)$.
Thus, $D$ embeds into the $F$ algebra $M_n(E)$ of $n\times n$ matrices over $E$, via the left regular action $x\mapsto \lambda_x$ where $\lambda_x:E^n\to E^n$ is defined by $$\lambda_x(y_0,\ldots,y_{n-1})=x\cdot(\sum_{j=0}^{n-1}u^jy_j).$$
Once this is done, one can define the reduced norm on $D$ by $$Nrd_{D/F}(x)=\det\lambda_x.$$
My interest specificaly is in the groups $G:=SL_1(D):=\lbrace x\in D\mid Nrd_{D/F}(x)=1\rbrace$. I'm trying to understand whether this group is finitely generated or not.
It is clear that the embedding defined above maps $G$ into the group $SL_n(E)$. Once we use the fact that the group $SL_n(E)$ is generated by transvections (i.e matrices with $1$s along the diagonal and at most one additional non-zero entry), it is not hard to use the local structure of $E$ to prove that $SL_n(E)$ is finitely generated.
Unfortunately, a subgroup of a finitely generated group need not be finitely generated in general. If anyone knows of a criterion that might prove why this case is special that would be a great help.
On additional possibility, is to use some heavy tools from asymptotic group theory (even though I must admit this turns out a bit cumbersome..):
We call a group $G$ positively finitely generate (abbreviated PFG), if there exists a number $k\in\mathbb N$ such that the probability that an arbitrary $k$-tuple $(x_1,\ldots, x_k)\in G^k$ generates $G$, is positive. Clearly, any PFG group is finitely generated (although the converse is not true, e.g the free group in two generators is not PFG).
For any $n\in\mathbb N$ we define $m_n(G)$ to be the number of maximal subgroups of $G$ with index $n$. It is a theorem of Avinoam Mann that the group $G$ is PFG if and only if $m_n(G)$ is bounded by some polynomial in $n$. So it would suffice to prove that the (maximal) subgroups of $G$ have polynomial growth.
As I said, this sort of proof seems a bit of an overkill, but if someone knows of a reference (or a direct proof) to why the group $G$ has polynomial (maximal) subgroup growth that will be swell :-).
Anyway, this question turns out to be a bit lengthy, so I'll stop here. I would very much appreciate If someone can offer any hints as to whether or not $SL_1(D)$ is finitely generated.
Thank you very much.

A: Yes, this follows from finiteness properties of arithmetic groups and the strong approximation theorem for simply connected groups.
Choose a global field $K$ with a non-archimedean place $v$ such that $K_v \simeq k$; this can be found via elementary approximation arguments.  By our knowledge of the Brauer groups of $K$ and $k$ via class field theory, there is a central division algebra $A$ over $K$ such that $A_v \simeq D$ over $k$.
Let $G$ be the absolutely simple semisimple $K$-group informally denoted as ${\rm{SL}}_1(A)$ (to be precise, $G$ represents the functor $R \rightsquigarrow
{\rm{SL}}_1(A \otimes_K R)$ on the category of $K$-algebras), so $G(k) = {\rm{SL}}_1(D)$.  Hence, it suffices to show that $G(k)$ contains a dense finitely generated subgroup.
By general "spreading out" arguments, for any connected semisimple $K$-group $H$ there is a finite set of places $S$ of $K$ containing the archimedean places and such that $H$ extends to a semisimple group scheme $\mathcal{H}$ over $O_{K,S}$, so $H$ is quasi-split at all places outside $S$ and hence (by the Borel--Tits structure theory) has positive rank at all places outside $S$. Thus, by enlarging $S$ to contain at least two such places, we can arrange that $$\sum_{w \in S} {\rm{rank}}(H_{k_w}) \ge 2.$$
We apply this with $H = G$ and therefore denote $\mathcal{H}$ as $\mathcal{G}$, and we enlarge $S$ if necessary so that $v \in S$.
Consider the arithmetic $S$-group $\Gamma = \mathcal{G}(O_{K,S})$ inside $G(K)$.  In the number field case this is finitely generated, by general finiteness results for arithmetic $S$-subgroups of the group of rational points of absolutely simple semisimple group over number fields. In the function field case the same holds because of the rank-sum condition arranged above (by a theorem of Behr).  So it suffices to prove that $\Gamma$ has dense image in $G(k) = G(K_v)$.
Let $S' = S - \{v\}$ (non-empty). Since $G$ is absolutely simple and simply connected, by the strong approximation theorem we know that $G(K)$ is dense in $G(\mathbf{A}_K^{S'}) = G(K_v) \times G(\mathbf{A}_K^S)$, where $\mathbf{A}_K^{S'}$ is the adele ring of $K$ with the $S'$-factors removed. Let $\widehat{O}_{K,S} \subset \mathbf{A}_K^S$ be the open subring $\prod_{w \not\in S} O_{K_w}$, so $\mathcal{G}(\widehat{O}_{K,S})$ is an open subset of $G(\mathbf{A}_K^S)$ that meets $G(K)$ in exactly $\mathcal{G}(O_{K,S}) = \Gamma$.
Hence, if $U \subset G(K_v)$ is a non-empty open subset then $U \times \mathcal{G}(\widehat{O}_{K,S})$ is an open subset of $G(\mathbf{A}_K^{S'})$ whose intersection with $G(K)$ is identified (via ${\rm{pr}}_v$) with $U \cap \Gamma$ inside $G(K_v)$.  But recall that $G(K)$ is dense in $G(\mathbf{A}_K^{S'})$, so its intersection with $U \times \mathcal{G}(\widehat{O}_{K,S})$ is non-empty.  In other words, $U \cap \Gamma$ is non-empty inside $G(K_v)$. Since $U$ was arbitrary, this says that $\Gamma$ is dense in $G(K_v) = G(k)$ as desired.
This argument is quite robust with respect to the permitted generality of the initial connected semisimple $k$-group, the main point being the existence of the "globalization" of some $K$.  One is then led to ask: if $G$ is a connected semisimple group over $k$ that is absolutely simple then does $G$ admit a "globalization" relative to some pair $(K,v)$ consisting of a global field $K$ and place $v$ such that $K_v \simeq k$ (and if so then can this be proved without case-checking). But this refinement was not part of the question, so I'll stop here.