text:
Q: Modify data in R by combining some of the rows based on (partially) regular expression I have a dataset that comes from an RNASeq experiment.
> dim(expression)
[1]   149 39879

like this:
> expression[1:5, 1:5]
# A tibble: 5 × 5
       sample_id ENSG00000004059 ENSG00000003056 ENSG00000173153 ENSG00000004478
           <chr>           <dbl>           <dbl>           <dbl>           <dbl>
1 123 (Colon)        6.518498        7.141934        5.766983        5.471909
2 121 (Colon)        6.983914        7.078940        5.909575        5.911879
3 004 (Ileum)        6.403912        7.131915        6.191672        5.771549
4 045 (Colon)        6.890916        7.233934        6.019052        6.272799
5 010 (Ileum)        6.674921        7.645998        5.859013        5.322049

The first column is called "sample_id" and in that column I have ids that look like this: "123(colon)", "142(ileum)", "123(ileum) etc. where 123 is the id of the patient and colon and ileum is where the samples were taken from.
The rest of the columns are gene names and their expression values.
Sometimes one patient has only one sample: colon or ileum, the other one missing.
The rows begin with 123(colon) and then the rest of the values for each gene.
I want to modify my data in such way that I don`t have two rows for one patient, for example 123.colon and 123.ileum but a single row combining the two.
Something like: "123 colon.gene1 colon.gene2...ileum.gene1 ileum.gene2..."
so far I was able to select the data from one patient (the two samples or just one if the case) with this code:
ptn = '^010.*?'
ndx = grep(ptn, expression$sample_id, perl=T)
selected_rows = expression[ndx,]
selected_rows

This however just selects the information I want, like this:
> selected_rows
# A tibble: 2 × 39,879
       sample_id ENSG00000004099 ENSG00000003956 ENSG00000973153 ENSG00000004498 ENSG00000003139
           <chr>           <dbl>           <dbl>           <dbl>           <dbl>           <dbl>
1 010 (Ileum)        6.674229        7.645929        5.850019        5.322049       0.6259249
2 010 (Colon)        6.861709        6.768619        5.950409        5.752779       0.3727669
# ... with 39873 more variables: ENSG00000003509 <dbl>, ENSG00000001036 <dbl>,

but I can`t figure out how to go from here.
I need to concatenate but still keep track of which gene expression belongs to which organ.
Thank you.
Expected result something in the shape of:
sample_id   ENSG1-Ileum ENSG2-ileum ENSG3-Ileum ENSG4-Ileum ENSG5-Ileum… ENSG1-Colon ENSG2-Colon ENSG3-Colon ENSG4-Colon ENSG5-Colon…
010         6.674229 7.645929 5.850019 5.322049 0.625924… 9.861709 6.768619 5.950409 5.752779 0.3727669…
# ... with 39873 more variables: ENSG00000003509 <dbl>, ENSG00000001036 <dbl>,

#

To say it otherwise (removing the biological factor):
How do I transform this:
p_id   g1   g2   g3
p1_a   vn   vn   vn
p1_b   vn   vn   vn
p2_a   vn   vn   vn
p2_b   vn   vn   vn

into this:
p_id   g1pa    g2pa    g3pa   g1pb    g2pb    g3pb
p1     vn      vn      vn     vn      vn      vn
p2     vn      vn      vn     vn      vn      vn

vn are just floating points that may or may not be equal

A: With lots of help, here is the solution:
library(pbapply)

expressions <- lapply(selected.patients, function(pat) {
  expr.ileum <- expression[sample.info$patient == pat & sample.info$origin == "Ileum",-1]
  expr.colon <- expression[sample.info$patient == pat & sample.info$origin == "Colon",-1]
  expr.comb <- data.frame(Patient = pat, Ileum = expr.ileum, Colon = expr.colon)
  expr.comb
})

library(dplyr)
expression.comb <- bind_rows(expressions)
dim(expression.comb)
expression.comb[1:6, 1:6]
rm(expressions)

and here is the output:
> expression.comb[1:6, 1:6]
  Patient Ileum.ENSG58 Ileum.ENSG47 Ileum.ENSG36 Ileum.ENSG56 Ileum.ENSG54
1  SV-121    5.635079    5.538374     3.543571    2.579083     5.2418536
2  07-004    6.403112    2.131415     1.171672    5.771545     0.9711039
3  01-010    1.674221    3.645928     8.850013    2.322047     0.6259241
4  KD-081    6.714947    6.643261     6.328018    9.709639     4.4346171
5  KV-247    6.771593    2.798890     6.370311    1.830785     5.5326661
6  MK-101    6.312121    2.570204     2.632856    3.402819     5.6695553


text:
Q: Variant of Sliding Ladder Related Rates Problem We all know the related rates problem of a ladder sliding off a wall.
In this we are told how fast the bottom or top is sliding and then asked to find how fast the other end of the ladder is moving at. My question is fairly similar.
A ladder of length $2l$ is sliding off of a wall. The bottom moves at a velocity $v$. How fast will the middle of the ladder (which is located a distance $l$ from the ends of the ladder) be sliding when the angle between the rod, wall, and floor is $\alpha = 45^{\circ}$?

A: Let the bottom of the ladder have position $(x(t),0)$.
Let the top of the ladder have position $(0,y(t))$.
We know that $x^2+y^2=4l^2$
Differentiating with respect to $t$ gives $2x \frac {dx}{dt}+2y \frac {dy}{dt}=0$.
We know that $\frac {dx}{dt}=v$, so $2xv+2y \frac {dy}{dt}=0  \Rightarrow \frac {dy}{dt}=-\frac {vx}y$.
The midpoint has position $(x_m,y_m)=(\frac x2, \frac y2)$
$\frac {dx_m}{dt}=\frac 12 \frac {dx}{dt}=\frac v2$
$\frac {dy_m}{dt}=\frac 12 \frac {dy}{dt}=\frac {vx}{2y}$
Speed is given by $\sqrt{\left(\frac {dx_m}{dt}\right)^2+\left(\frac {dy_m}{dt}\right)^2}$
Speed is $\sqrt{\frac {v^2}{4}+\frac {v^2x^2}{4y^2}}=\sqrt{\frac {v^2y^2+v^2x^2}{4y^2}}=\sqrt{\frac {v^2(y^2+x^2)}{4y^2}}=\sqrt{\frac {v^24l^2}{4y^2}}=\frac {vl}{y}$
When $\alpha = 45^\circ$, $x=y=l\sqrt2$
So speed of midpoint is $\frac v{\sqrt 2}$

A: Going with saulspatz's interpretation, let the top of the ladder be at $(0,y_1)$ and the bottom at $(x_2,0)$ at time $t.$ Then the middle of the ladder is at $$(x,y)=(\frac{x_2}{2},\frac{y_1}{2})$$.$$\dot s=\sqrt{\dot x^2+\dot y^2}$$
$$=\sqrt{(\frac {\dot x_2}{2})^2+(\frac {\dot y_1}{2})^2}$$
$$\frac {1}{2}\sqrt{\dot x_2^2+\dot y_1^2}$$ Since $\dot {x_2}$ is how fast the bottom of the ladder is sliding along the floor and $\dot{y_1}$ is how fast the top of the ladder is sliding down the wall, you should be able to take it from there.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can you sort a python zip function by a particular key I have two lists that I am trying to zip.  I would like to zip them so that they match by their id value.  So, for row, the id would be 'Video ID' and for founded_evideo, the id would be 'post_id'.  I would like to zip so that the ids match.
I have tried sorting the panda frame first using sort_values function, but this doesn't seem to have an effect on the zip function.  Ex:
Code
founded_edvideos_list = find_matching_posts_forupdate(video_id_list, stop_at_page=stop_at_page)
founded_edvideos_df = pd.DataFrame(founded_edvideos_list)
founded_edvideos_df = founded_edvideos_df.sort_values(by=['post_id'], ascending=True)
founded_edvideos_df = founded_edvideos_df.where(pd.notnull(founded_edvideos_df), None)

excel_data = file_as_df[file_as_df['Video ID'].isin(founded_edvideos_df['post_id'])]
excel_data = excel_data.copy()
excel_data['Video ID'] = excel_data['Video ID'].astype("category")
excel_data['Video ID'].cat.set_categories(file_as_df['Video ID'].to_list(), inplace=True)
excel_data.sort_values(["Video ID"])
excel_data = excel_data.to_dict('r')

for (row,founded_evideo) in zip(excel_data,founded_edvideos_list):
     more code

row example
{
    'Video ID': 12894,
    'Title': 'Trailblazer Melba Pattillo Beals',
    'Excerpt': 'Meet Melba Pattillo Beals PhD., member of the Little Rock Nine, and trailblazer for civil rights.',
    'Video Description': 'Meet Melba Pattillo Beals PhD., member of the Little Rock Nine, and trailblazer for civil rights.',
    'Quick Ideas for Using the Video': '',
    'Video URL': 'https://vimeo.com/32351',
    'Keywords': "African American History, African American Studies, America and Civil Rights"
}

founded_evideo example
{
    'post_id': 12994,
    'title': 'Trailblazer Melba Pattillo Beals',
    'video_page_description': 'Meet Melba Pattillo Beals PhD., member of the Little Rock Nine, and trailblazer for civil rights.',
    'content': '
Meet Melba Pattillo Beals PhD., member of the Little Rock Nine, and trailblazer for civil rights.
\n',
    'quick_ideas': '',
    'video_url': 'https://vimeo.com/3242',
    'keywords': ''
}

A: You could try like this:
l1 = [
    {"Video ID": 12894, "Title": "title1"},
    {"Video ID": 14897, "Title": "title2"},
    {"Video ID": 45124, "Title": "title4"},
    {"Video ID": 54613, "Title": "title3"},
]

l2 = [
    {"post_id": 54613, "Title": "title3"},
    {"post_id": 10278, "Title": "title4"},
    {"post_id": 12894, "Title": "title1"},
    {"post_id": 14897, "Title": "title2"},
]

common_ids = set(item["post_id"] for item in l2).intersection(
    set(item["Video ID"] for item in l1)
)

def new(list, key):
    """Helper function which returns list of dicts which ids are found in common_ids."""
    return sorted(
        [item for item in list if item[key] in common_ids], key=lambda x: x[key]
    )

for item1, item2 in zip(new(l1, "Video ID"), new(l2, "post_id")):
    print(item1, item2)

# Output
{'Video ID': 12894, 'Title': 'title1'} {'post_id': 12894, 'Title': 'title1'}
{'Video ID': 14897, 'Title': 'title2'} {'post_id': 14897, 'Title': 'title2'}
{'Video ID': 54613, 'Title': 'title3'} {'post_id': 54613, 'Title': 'title3'}


text:
Q: The query processor ran out of internal resources exception I have the following query which runs in Sql Server 2008, it works well if data is small but when it is huge i am getting the exception. Is there any way i can optimize the query
select
        distinct olu.ID
            from olu_1 (nolock) olu

            join mystat (nolock) s
                on s.stat_int = olu.stat_int

            cross apply
                dbo.GetFeeds
                        (
                                s.stat_id,
                                olu.cha_int,
                                olu.odr_int,
                                olu.odr_line_id,
                                olu.ID
                        ) channels

            join event_details (nolock) fed
                on fed.air_date = olu.intended_air_date
                and fed.cha_int = channels.cha_int
                and fed.break_code_int = olu.break_code_int

            join formats (nolock) fmt
                on fed.format_int = fmt.format_int

            where
                fed.cha_int in (125, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 35, 36, 37, 38, 39, 40, 41, 43, 117, 45, 42, 44, 47, 49, 50, 51, 46, 52, 53, 54, 55, 56, 48, 59, 60, 57, 63, 58, 62, 64, 66, 69, 68, 67, 65, 70, 73, 71, 74, 72, 75, 76, 77, 78, 79, 82, 80, 159, 160, 161, 81, 83, 84, 85, 88, 87, 86, 89, 90, 61, 91, 92, 93, 95, 96, 97, 98, 99, 100, 94, 155, 156, 157, 158, 103, 104, 102, 101, 105, 106, 107, 108, 109, 110, 119, 111, 167, 168, 169, 112, 113, 114, 115, 116, 170, 118, 120, 121, 122, 123, 127, 162, 163, 164, 165, 166, 128, 129, 130, 124, 133, 131, 132, 126, 134, 136, 135, 137, 171, 138, 172, 173, 174) and
                fed.air_date between '5/27/2013 12:00:00 AM' and '6/2/2013 12:00:00 AM' and

                fmt.cha_int in (125, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 35, 36, 37, 38, 39, 40, 41, 43, 117, 45, 42, 44, 47, 49, 50, 51, 46, 52, 53, 54, 55, 56, 48, 59, 60, 57, 63, 58, 62, 64, 66, 69, 68, 67, 65, 70, 73, 71, 74, 72, 75, 76, 77, 78, 79, 82, 80, 159, 160, 161, 81, 83, 84, 85, 88, 87, 86, 89, 90, 61, 91, 92, 93, 95, 96, 97, 98, 99, 100, 94, 155, 156, 157, 158, 103, 104, 102, 101, 105, 106, 107, 108, 109, 110, 119, 111, 167, 168, 169, 112, 113, 114, 115, 116, 170, 118, 120, 121, 122, 123, 127, 162, 163, 164, 165, 166, 128, 129, 130, 124, 133, 131, 132, 126, 134, 136, 135, 137, 171, 138, 172, 173, 174) and
                fmt.air_date between '5/27/2013 12:00:00 AM' and '6/2/2013 12:00:00 AM'

A: From IN (Transact-SQL)

Including an extremely large number of values (many thousands) in an
  IN clause can consume resources and return errors 8623 or 8632. To
  work around this problem, store the items in the IN list in a table.

So I would recomend inserting the values into a temp table and then either joining onto that table or selecting the IN from the table
So something like
DECLARE @TABLE TABLE(
        val INT
)

INSERT INTO @TABLE VALUES(1),(2),(3),(4),(5)

SELECT  *
FROM    MyTable
WHERE   ID IN (SELECT val FROM @TABLE)

SQL Fiddle DEMO

A: Do a backup from your production database (with many rows) and play with it locally on you development machine. The optimization may take some time it may actually be quite hard if you are new to sql. Break down the Query into several temporary tables and join them toghether in the end. Try and remove the dbo.GetFeeds(...) function from the Query to see if that function is the problem.


text:
Q: marathonITE script to tick a checkbox in a JTable cell I'm using marathonITE testing tool to automate testing of a java swing application.
In one of the windows i have a JTable with 6 columns and N number of rows.
Two columns of that table are checkbox type columns.
My requirement is to write the automation script to tick the check box when the row and column is given.
select('table', 'true', '[row=1][column=0]')

I tried this line but it directs the script to
class Fixture:

def teardown(self):
    '''Marathon executes this method at the end of test script.'''
    pass

which then stops the process.
Is there a way to tick the checkbox within a table when column and row is given?

A: I found a workaround for this problem.
In the first part i traverse through the table and checks whether the test value is equal to each of those cell values.
In the second part i use keystrokes to traverse to that particular row and column and use space and enter keystrokes to tick the check box.
Note that this method works only for checking a single check box. For multiple check boxes will have to traverse back using key strokes and re do the keystroke traversing.
#1st Part

            textValue = "Test Value"
            deplTable = get_component('table')
            no_of_columns = deplTable.getColumnCount()
            no_of_rows = deplTable.getRowCount()

            for col in range (no_of_columns):
                if ( col == 1 or col == 4 ):
                    for row in range (no_of_rows):

                        if ( deplTable.getValueAt( row ,col) == textValue ):
                            print 'Found at row:',row,' col:',col
#2nd Part
                            for x in range (row+1) :
                                keystroke('table', 'Down')
                            keystroke('table', 'Left')
                            if ( col > 1 ):
                                for  y in range (col-1) :
                                    keystroke('table', 'Right')

                            keystroke('table', 'Space')
                            keystroke('table', 'Enter')

A: Write your code in this way:
select('table', 'true', '{1,0}')

This is working for me.


text:
Q: Parsing xml/svg Why is this not printing all the paths only the first instance/tag?
from xml.dom import minidom

def converter():
 xmldoc= minidom.parse("file.svg")
 a=xmldoc.getElementsByTagName("svg")[0]
 b=a.getElementsByTagName("g")[0]
 pth=b.getElementsByTagName("path")

 for p in pth:
      a = p.getAttribute('class')
      b = p.getAttribute('d')

      return a , b

<g id="group">
<path
class="pp-region pp-Citiesregi2014 pp-citis-nro-666"
d="
M 455385.23 7717427.99
L 457750.49 7722100.53
L 458363.99 7725704.59
L 458364 7725704.64
L 457375.58 7730965.44
L 458418.95 7732463.37
L 460373.42 7735446.16
L 464487.75 7738223.56
L 467881.88 7741720.66
L 469719.4 7745286.72
z" />

So i would only need the class pp-citis-nro-666 and its correspondig value. This applied to all the elements.


text:
Q: SolrCloud admin page showing Slave (Searching) I am not using the master slave settings in solrconfig(as far as I know) but still solr admin page shows this in browser.
                  Version        Gen             Size

Master (Searching)  1444735428179    4390         5.4 GB
Master (Replicable) 1444735488272    4391          -
Slave (Searching)   1444735428184    4390         5.4 GB
I am not able to understand why it is showing slave part. Any help would be appreciated.
Thanks


text:
Q: rsync makes 2 backups if cron runs while file is being written I have a crontab to run this rsync command every 30m
rsync -rtbpgoi --suffix="."$(date +"%Y%m%d%H%M") --exclude=".*" \
--exclude="~*" --exclude="[Tt][Hh][Uu][Mm][Bb][Ss].[Dd][Bb]" \
--exclude="[Dd][Ee][Ss][Kk][Tt][Oo][Pp].[Ii][Nn][Ii]" \
--info=STATS0,FLIST0,NAME1 /mnt/datastore/ /mnt/dsbackup

What happens is if a file is in the process of being written, such as a long download for example, I end up with an extra backup copy of the file one being a backup of the incomplete download.
Is there some way to make rsync ignore files that are still being written to or some other way to avoid backing up incomplete files? I know I can remove the -b and --suffix switches but I do want to keep the functionality of having it keep a version history when files change.

A: To answer your question: rsync, to my knowledge, does not have any built-in way to know that some separate program that you're running (web browser, etc) is actively modifying a file.
Given your type of backup (running over the same source and destination every 30 minutes), you can achieve eventual removal of any intermediate files which have different names than the final file (for example, download_1.zip.tmp might be an intermediate file for download_1.zip) by adding the --delete option to the command.
During the first run of rsync, the download_1.zip.tmp file would be copied to your backup location. Assuming that the download finishes within 30 minutes, the intermediate file download_1.zip.tmp would be renamed to download_1.zip. Upon the next run of rsync, rsync would no longer find the intermediate file download_1.zip.tmp (because it's been renamed to download_1.zip) and it would remove download_1.zip.tmp and replace it with download_1.zip in the backup. This would also remove any other files from your backup (/mnt/dsbackup) which no longer exist in the source (/mnt/datastore).
From rsync's man page (version 3.1.0):

This tells rsync to delete extraneous files from the receiving side (ones that aren't on the sending side), but only for the directories that are being synchronized.  You must have asked rsync to send the whole directory (e.g. "dir" or "dir/") without using a wildcard  for the directory's contents (e.g. "dir/*") since the wildcard is expanded by the shell and rsync thus gets a request to transfer individual files, not the files' parent directory.  Files that are excluded from  the  transfer  are  also  excluded  from  being deleted  unless  you use the --delete-excluded option or mark the rules as only matching on the sending side (see the include/exclude modifiers in the FILTER RULES section).


text:
Q: Replacing String Between two special charters in shell script I am trying to replace a string in my shell script from localhost:7101/RPAS to sound.mojo.com:5555/rpas in my HTML file.
${myDeployment} =<\/td><\td width="0">http://localhost:7101/RPAS<\/td>

My output should be:
${myDeployment} =<\/td><\td width="0">http://sound.mojo.com:5555/rpas<\/td>

*

*The strings that are fixed are ${myDeployment} and </td> and localhost:7101 is not a fixed string.

*http://occurs multiple times in document and the above mentioned string occurs at the last , but not at the end of the document.

*Is there a way to extend this command to only change the string of the last occurring pattern in the file.

sed -e 's#>http://[^/]*/#>http://sound.mojo.com:5555\/rpas/#' tst.html
Please let me know if there is a way to do it.

A: You can use this sed command:
sed 's#>http://[^/]*/#>http://sound.mojo.com:5555#' file

${myDeployment} =<\/td><\td width="0">http://sound.mojo.com:5555RPAS<\/td>


text:
Q: Firebase functions auth user onCreate uni test How would you achieve stubbing the below call?
I have managed to stub the user object
admin.firestore().collection('roles').where('role', '==', 'unassigned');

Functions
exports.userRegistration = functions.auth.user()
.onCreate((user, context) => {
    let unassignedRole;
    let roleRef = admin.firestore().collection('roles').where('role', '==', 'unassigned');
    await roleRef.get()
    .then(snapshot => {
        snapshot.forEach(doc => {
            unassignedRole = doc.ref;
        });
    })
    .catch(err => {
        console.log('Error getting documents', err);
    });

    await admin.firestore().collection('users').add({
        firstName: user.firstName || "",
        lastName: user.lastName || "",
        fullName: user.displayName || "",
        profilePic: user.photoURL || "",
        email: user.email,
        dateRegistered: admin.firestore.FieldValue.serverTimestamp(),
        role: unassignedRole
    });
});

Unit Test
describe('Cloud Functions', () => {
    let myFunctions, adminInitStub;

    before(() => {
        adminInitStub = sinon.stub(admin, 'initializeApp');
        myFunctions = require('../index');
    });

    after(() => {
        adminInitStub.restore();
        test.cleanup();
    });

    describe('userRegistration', () => {
        it('should write the newly registered user to /users', () => {
            const mockUser = test.auth.makeUserRecord({
                email: "test@email.com"
            });

            const wrapped = test.wrap(myFunctions.userRegistration);
        })
    });
});


text:
Q: Source-level definition of `seq` in Haskell I'm trying to understand seq in Haskell. I've got some understanding of seq in English, so now I'd like to read its implementation.
However, the source code says
infixr 0 `seq`
seq :: a -> b -> b
seq = seq

How can I read this? It this an infinitely recursive definition? I suspect it's not, though.

A: seq cannot be implemented in plain Haskell. That is a "dummy" definition. It is "replaced" with the actual seq behavior by GHC. So the real implementation (so to speak) of seq is inside the compiler.
To put it another way: If we ignore the name of the function in that code snippet, that definition has no relationship to seq. The compiler sees the name "seq" (and maybe the fact that it's defined in that specific module; I'm not sure about the details) and that tells it to replace the definition with the actual seq behavior during compilation.

A: The file you linked starts with

{- This is a generated file (generated by genprimopcode). It is not
code to actually be used. Its only purpose is to be consumed by
haddock. -}

hence it is only generated so that it can in turn cause documentation to be generated.
Every single definition in the file is given by a dummy recursion x = x. That is not the real definition, but only a placeholder.
Haskell's primitives in GHC.Prim like seq can not be simply implemented in a Haskell module (otherwise they would not be called primitives). Instead, they are handled in a special way during compilation.


text:
Q: What is the name of the Windows 8 start menu? I'm trying to discuss it with my friends and I know whatever I call it will be the way they reference it probably forever.
Is it just Start Menu?
Metro Start Menu?
Modern Start Menu?

A: It's the "Start screen".
According to the MSDN "Building Windows 8" blog article "Designing the Start screen" anyway. :)
And according to Wikipedia:

The Start screen is the successor of the Start menu. This feature is present in Windows Phone, Windows 8, and Windows Server 2012.


text:
Q: Switching views in storyboard after executing code in xcode I made a log-in screen that once you press the button to log-in and it authenticates the user name and password. What I want to do it switch to a different view after the authentication is completed. I am using a storyboard for this application and I have set it up so that the log-in button does a modal seque but it doesn't switch the view. I tested this with a sample button and all it does it switch the view back to the same view and refreshes the view. What do I need to add in order for my function to switch from my ViewController View (the main view) to the next view (RootViewController).
I have a navigationController and an object created from the ViewController class but I don't know how to use them in order to switch views.
Can anyone point me in the right direction? I can provide more information or sample code if needed.

A: If I'm following your question correctly, what you're looking for is performSegueWithIdentifier:sender:.
In general the apple documentation on view controllers in storyboards is pretty good and covers all of the relavent bits for transitioning between views in storyboards.


text:
Q: Unable to find the socket transport "ssl" in Zend framework 1.12 i tried to sent email from my system but got this error messages.
Unable to find the socket transport "ssl" - did you forget to enable it when you configured PHP?

i already see the others similar post but can't resolve my problem. i tried to change my code from "ssl" to "tls' but get1 the another error. Since i upload my project into University server, so i can't do anything with server configuration. This is my code so far :
$config = array('ssl' => 'ssl',
            'auth' => 'login',
            'username' => 'somename@gmail.com',
            'password' => 'password');

$transport = new Zend_Mail_Transport_Smtp('smtp.gmail.com', $config);

$email = 'somename1@gmail.com';
$username = 'John';
$mail = new Zend_Mail();
$mail->setBodyHtml("sdsd");
$mail->setFrom('somename@gmail.com');
$mail->addTo($email, $username);
$mail->setSubject('Profile Activation');
$mail->send($transport);

A: as suggested openSSL is Not enable in your php..
Open php.ini
uncomment the following:
extension=php_openssl.dll

then restart the server..
Hope this helps, also you can use this http://www.php.net/manual/en/openssl.installation.php

A: OpenSSL support isn't enabled on your web server. You can use phpinfo() to see what extensions your PHP installation supports. If OpenSSL isn't one of them you're out of luck using SSL or TLS.


text:
Q: Pyhook crashes when it tries to interpret the window name as ASCII Context: I am developing a mouse and keyboard listener with PyHook.
Experience in python: Beginner
Python interpreter: 3.7
Problem: When I move the mouse over the header Google Chrome browser and the current website is Spotify, I am getting the following error:
TypeError: MouseSwitch() missing 8 required positional arguments: 'msg', 'x', 'y', 'data', 'flags', 'time', 'hwnd', and 'window_name'.
What I found: I found the following related post in this community:
pythoncom crashes on KeyDown when used hooked to certain applications
In that post, the solution indicates that there is a bug with Pyhook when it tries to interpret the window name as ASCII. Based on this answer, the post suggests changing the source C code of Pyhook. Also, I found the following post, which explains how to modify in general a library in Python:
How to rebuild a python module/libary
Question: Is there another workaround to overcome this issue without modifying the source code?. In case the only option is by changing the source code, could someone give me more details about:

*

*How to find the source code of this library

*How to implement the suggested changes in that post with more explanation to someone who has no many experiences with Python.

Stacktrace:
File "C:\....\Local\Programs\Python\Python37\lib\site-packages\pyHook\HookManager.py", line 322, in MouseSwitch

event = MouseEvent(msg, x, y, data, flags, time, hwnd, window_name)

SystemError: <class 'pyHook.HookManager.MouseEvent'> returned a result with an error set

TypeError: MouseSwitch() missing 8 required positional arguments: 'msg', 'x', 'y', 'data', 'flags', 'time', 'hwnd', and 'window_name'

Thank you for your help. Please forgive me if I explained something incorrectly.
Piece of code:
import pyHook
import pythoncom
import traceback
import threading

lock = threading.Lock()

try:

    def create_element(event):
       global t
       lock.adquire()
       print('MessageName:', event.MessageName)
       lock.release()

    def onMouseEvent(event):
       global t
       t = threading.Thread(target=create_element, args=(event))
       t.start()

    def onKeyboardEvent(event):
       global t
       t = threading.Thread(target=create_element, args=(event))
       t.start()

    hm = pyHook.HookManager()
    hm.KeyDown = onKeyboardEvent
    hm.MouseAll = onMouseEvent

    hm.HookKeyboard()
    hm.HookMouse()
    pythoncom.PumpMessages()

except:

    hm.UnhookMouse()
    hm.UnhookKeyboard()
    hm=None
    traceback.print_exc()


text:
Q: Express the following in terms of y. If $y = 2^{2x}$, express the following in terms of y.
$2^{2x-1} - 4^{2x+1} + 16^{x-1}$
I began it in this way:
$2^{2x}\cdot 2^{-1} - (2^2)^{2x+1} + (2^4)^{x-1}$
$2^{2x}\cdot \frac{1}{2} - 2^{4x}\cdot2^2 + 2^{4x}\cdot2^{-1}$
$2^{2x}\cdot\frac{1}{2}-2^{2x}\cdot2^{2x}\cdot2^2+2^{2x}\cdot2^{2x}\cdot\frac{1}{2}$
$\frac{y}{2} - 4y^2 + \frac{y^2}{2}$
Is this right?

A: Almost. Note that $$(2^4)^{x-1}=2^{4(x-1)}=2^{4x-4}=2^{4x}\cdot2^{-4}\ne2^{4x}\cdot 2^{-1}.$$ Also note that you can gather like terms (specifically, the $y^2$ terms).


text:
Q: Number of possible ways to distribute 15 chocolate bars among 10 children (Introduction to Probability, Blitzstein and Nwang, p. 39)

There are 15 chocolate bars and 10 children. In how many ways can the chocolate bars
  be distributed to the children, in each of the following scenarios?
(a) The chocolate bars are fungible (interchangeable).
(b) The chocolate bars are fungible, and each child must receive at least one.
  Hint: First give each child a chocolate bar, and then decide what to do with the rest.
(c) The chocolate bars are not fungible (it matters which particular bar goes where).
(d) The chocolate bars are not fungible, and each child must receive at least one.
  Hint: The strategy suggested in (b) does not apply. Instead, consider randomly giving
  the chocolate bars to the children, and apply inclusion-exclusion.

My solutions:
a) I'm imagining for each chocolate bar to randomly sample from the children with replacement, with order not mattering. This would yield $\binom{10+15-1}{15}$ possibilities.
b) Now I first choose one chocolate bar for each child, and then I do the same as in a) with the remaining 5 bar, so I get $\binom{15}{10} \binom{10+5-1}{5}$ possibilities.
EDIT
I'm ignoring here that the bars are exchangeable, so it should be only $\binom{10+5-1}{5}$. Or said differently, there is only one way to give a bar to each child.
c) I think this is sampling with replacement where order matters, so $10^{15}$ possible sequences.
d)
\begin{align}
\Omega &:= \lbrace s|s \text{ is a 15 digit number with digits form [1-10]}\rbrace \\
A_i &:=\lbrace s \in \Omega | s \text{ contains at least (one or more) i's} \rbrace \\
\neg A_i &= \Omega \setminus A_i \\
|\Omega| &= 10^{15} \\
|\neg A_i| &= 9^{15} \\
|\neg A_i \cap \neg A_j| &= 8^{15} \\
\text{etc.}
\end{align}
\begin{equation}
\text{Possibilities that each childs gets at least one bar} = \sum_{i=0}^{i=10} \binom{10}{i} (10-i)^{15} (-1)^i
\end{equation}
Are those results correct? I'm not quite sure about a) and b), since I think the number of possibilities in b) should be less than in a).

A: I have a different view of your question. I will focus on question b). Firstly, we put all the chocolate bars in a line. Because all the bars are interchangeable, there is only one way to line them up(it's $15!$ ways if bars are different from each other). Just like this:
$$ 0\;0 \;0\;0\;0\;0\;0\;0\;0\;0\;0\;0\;0\;0\;0 $$
Then we can cut 9 lines to divide the bars line into 10 parts and give the first part to first child, second part to second child and so on. Here is one example for partition:
$$ 0\;|0 \;|0\;0\;|0\;|0\;|0\;|0\;0\;0\;|0\;0\;|0\;0\;|0 $$
One advantage of this partition is that we can guarantee that each students will receive at least one chocolate.
We are looking for 9 places to cut and (15-1) places are available. So the total number of partitions is $ \begin{pmatrix}14  \\9 \end{pmatrix} $.
This solution can be also applied to question a). But we need to add another 10 bars in the line, and subtract 1 bars for each child. The number of partitions in this setting is
 $ \begin{pmatrix}24  \\9 \end{pmatrix} $ which is the same as your answer.

A: A comment on your b) answer.
(Due to it being indistinguishable chocolate bars)
Look at it from the aspect of not having any excess first, so you only have the amount of candy bars as children. So to give each child a candy bar will equal out to 1 possible way or (10 choose 10), then choose what to do with the rest.
${10 \choose 10}* {10 + 5 - 1 \choose 5} = 2002$
or
${14 \choose 5}= 2002$

A: For part c) yes you have a set of 15 that involves all possible combinations. so each child has 15 possibilities of getting assigned candy hence $10^{15}$ is correct.   yes part d) is correct.


text:
Q: MongoDB: Strategy to remove / merge duplicate documents Situation:
Let's consider we have a big application which contains an Address Book with contacts. And a huge part of the application saves references to those contacts.
Problem:
Now the Address Book contains lot's of duplicate contacts (where Contact A and Contact B for example have the same name and address but different phone numbers, or one has a typing mistake within the name, etc.)
Both Contact A and Contact B were used within the application, though there are references for both of them saved in the DB. That's why we can't simply delete one of them and throw away its ID.
When a user now searches for a contact, he can't be sure which one is the right one to choose.
Question:
What's the best / easiest / fastest solution, to handle this?
Ideas:

*

*Basic and clean solution: Merge the data: Contact A -> Contact B. Then update the whole database and replace everywhere Contact A ID with Contact B ID. Afterwards Contact A can be deleted safely. But this way may take a lot of time and you've got to write a lot of code.

*Two query solution: Merge the data. Add a field replaces to Contact B which contains the ID of Contact A. Then delete Contact A. When there's a contact reference, the query it executes will look first for _id = ..., then for replaces = .... If the second query succeeds, then we should update the reference with the right ID. But this way we need to create an additional Index.

*Two query solution reverse: This is similar to 2.: Merge the data. Add a field replacedBy to Contact A. When a query returns a contact that contains a replacedBy field, we must do another query to get the right contact and then replace the reference. But this way we will never delete Contact A, because we can't determine when all those references have been updated.

*Just hide the old/wrong entry: Merge the data. And add some deleted = true field to the old/wrong contact. This way it won't appear in the address book. But the reference will still bring up the old/wrong data.
Ideally I'd use _id with an array of ObjectIds, but that's not supported by MongoDB as far as I know.

Please share your thoughts, pros and cons.
And maybe you've got another solution, that's event better / faster / more efficient / more elegant.


text:
Q: Gradle DSL method not found: compile() I use the IDE android studio 1.0.2 version.
I get the following error:
Gradle DSL method not found: 'compile()'
Error(0,9):   The project 'MiarrayAdapter' may be using a version
of Gradle that does not contain the method
the built file may be missing a Gradle plugin

My file build.gradle is:
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.0.0'
        compile 'com.android.support:appcompat-v7:+'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

I´ve other file build.gradle (Module app), the code is:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "com.cursoandroid.miarrayadapter"
        minSdkVersion 6
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:+'
}

    allprojects {
        repositories {
            jcenter()
        }
    }

A: Remove the following from your top-level build.gradle:
compile 'com.android.support:appcompat-v7:+'

and also note the comment there:
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files


text:
Q: Cannot Serve Static Files Currently, sending a postman request out to my API on my static-file-serving route gives me a 404 error, despite me double-checking that I'm GETting from the right route. The server worked fine in terms of serving files before adding SocketIO. Unfortunately, even when I remove the flask-socketio middleware, I cannot get the files to serve. Currently, I haven't touched this route in a long time, so I'm not sure what exactly happened.
Previously, I didn't have the static_url_path and static_folder options set when initiating the flask app object. I just added them after reading up on some other answers, but I get a 404 regardless of their presence.
All my other routes are working as intended.
UPLOAD_FOLDER = '/profile_pictures'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}
app = flask.Flask(__name__, static_url_path='/', static_folder="/profile_pictures")

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

UPLOAD_FOLDER = './profile_pictures'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}

#unrelated code

@app.route('/profile_pictures/<filename>', methods=['GET'])
@cross_origin(supports_credentials=True)
def get_profile_picture(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'],filename,  as_attachment=True)

Any insight as to what the issue may be is greatly appreciated.

A: You don't need both static_url_path='/', static_folder="/profile_pictures" and route for static files.
Choose one you prefer to use and delete the other.
Or change the
static_url_path='/', static_folder="/profile_pictures"
into
static_url_path='/static', static_folder="/profile_pictures"
and static files can be accessed from both
HOST:PORT/static/<filename> and HOST:PORT/profile_pictures/<filename>.
The static_folder is basically for static files like css, js and images.
The route is for user to download files directly.

A: Ended up being I set the UPLOAD_FOLDER directory to
UPLOAD_FOLDER = '/profile_pictures'
Where it should've been
UPLOAD_FOLDER = 'profile_pictures'
Thanks for the answer @ Alexander : )


text:
Q: Android :understanding the download process I'm trying to compute my wifi speed. So i'm downloading a file from a server (10 Mb ). Well the download is working pretty well. But i'm not sure how to cmpute the download spped of every received data packet.
This a part of the code i'm using. I woud like to understand the difference between the two sizes : 8192 and the 1024 ,the purpse of every size .
 InputStream input = new BufferedInputStream(url.openStream(), 8192);

And this line
 byte data[] = new byte[1024];

And this how i used them :
protected String doInBackground(String... f_url) {
    int count;
    int lenghtOfFile = 0;

    try {
        URL url = new URL(f_url[0]);
        comm = (HttpURLConnection)url.openConnection();
        URLConnection conection = url.openConnection();
        conection.connect();
         lenghtOfFile = conection.getContentLength();

        // download the file
        InputStream input = new BufferedInputStream(url.openStream(), 8192);

        // Output stream
        OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg");

     byte data[] = new byte[1024];
        long total = 0;
        while ((count = input.read(data)) != -1) {
            actuaStartlTime = System.currentTimeMillis();
            total += count;

}}

This is a sample of output :curret time and downloaded data. I don't see any relatiosheep between the size of downloaded data.
    05-06 15:32:36.883: I/downloaded data(13146): 244392
05-06 15:32:36.883: I/current time in millisecond(13146): 1399386756881
05-06 15:32:37.329: I/downloaded data(13146): 245840
05-06 15:32:37.329: I/current time in millisecond(13146): 1399386757328
05-06 15:32:37.331: I/downloaded data(13146): 247288
05-06 15:32:37.332: I/current time in millisecond(13146): 1399386757330
05-06 15:32:37.334: I/downloaded data(13146): 250184
05-06 15:32:37.334: I/current time in millisecond(13146): 1399386757333
05-06 15:32:37.347: I/downloaded data(13146): 251632
05-06 15:32:37.347: I/current time in millisecond(13146): 1399386757345
05-06 15:32:37.349: I/downloaded data(13146): 262144
05-06 15:32:37.349: I/current time in millisecond(13146): 1399386757348
05-06 15:32:37.637: I/downloaded data(13146): 288208
05-06 15:32:37.637: I/current time in millisecond(13146): 1399386757636
05-06 15:32:38.050: I/downloaded data(13146): 289656
05-06 15:32:38.050: I/current time in millisecond(13146): 1399386758049
05-06 15:32:38.063: I/downloaded data(13146): 298344
05-06 15:32:38.063: I/current time in millisecond(13146): 1399386758062
05-06 15:32:38.067: I/downloaded data(13146): 304136
05-06 15:32:38.068: I/current time in millisecond(13146): 1399386758066
05-06 15:32:38.070: I/downloaded data(13146): 309928
05-06 15:32:38.071: I/current time in millisecond(13146): 1399386758069
05-06 15:32:38.079: I/downloaded data(13146): 317168

Thank you in advance.


text:
Q: Befriending a template template parameter I've got a class template with a template template parameter, and I want to declare this parameter (that is, all of its specializations) as a friend. But I can't find the correct syntax.
template <template <class> class T>
struct Foo {

    template <class U>
    friend T;           // "C++ requires a type specifier for all declarations"

    template <class U>
    friend struct T;    // "declaration of 'T' shadows template parameter"

    template <class U>
    friend struct T<U>; // "cannot specialize a template template parameter"

    pretty<please>
    lets(be) friends T; // Compiler shook its standard output in pity
};

How can I declare a template template parameter as friend?
Coliru snippet

A: I've found this problem is very interesting to research. According to standard (C++11 and above) this should works fine, I guess:
template <template <class> class U>
struct identity {
    template <typename T>
    using type = U<T>;
};

template <template <class> class U>
struct Foo {
    template <typename>
    friend class identity<U>::type;
};

Due to one indirection level, there are no any shadowing and name reusing here, and this situation described as following:

cppreference:
Both function template and class template declarations may appear with the friend specifier in any non-local class or class template (...). In this case, every specialization of the template becomes a friend, whether it is implicitly instantiated, partially specialized, or explicitly specialized. Example: class A { template<typename> friend class B; }

However, it seems like clang and MSVC think otherwise: see coliru or godbolt. Moreover, their error messages seem meaningless, so it looks like a compiler bug (or just an incorrectly detected syntax error). GCC compiles and executes mentioned snippets perfectly, but I still not sure it's a correct solution.

A: Templates tend to get programmers to over-complicate things. I'm not exactly sure what you are trying to do, and I suspect that there is probably a better way to do it, but this should work.
template <template <class> class T, class U>
class Foo {
    friend class T<U>;
};


text:
Q: Add a background map for sigma js I have created a graph in Gephi using GeoLayout (showing network over the world). Now for my visualization I would like to add a background map in sigma.js ideally something like openstreetmap or a similar service. Is that possible?
Otherwise I could also imagining adding the graph to a leaflet map if that is easier. In any case I would need to know how this can be achieved. Any help is appreciated. Thanks!


text:
Q: C# restricting use of a class The below code does what I would like it to do. The code in the Main method looks and behaves exactly as desired. However, it would be preferable if the class UserMenu, Home and DropdownMenu2 could only be used by the HeaderNavigationMenu to protect other developers from trying to used them outside of the HeaderNavigationMenu class. Additionally most articles frown upon making everything public.
Question:
Is the design patter being used below appropriate or is there something better and more acceptable to use in this scenario?

Edit: The reason for this design.

*

*I wanted the end user of HeaderNavigationMenu to just be able to use the dot notation to get a list of available options. This Architecture accomplishes this goal (ex: navigationMenu.DropdownMenu2.SelectOption3())

*Wanted anyone else who eventually might need to edit the code to understand that the classes UserMenu, Home and DropDownMenu2 where very specifically designed to be implemented by HeaderNavigationMenu class.

public class HeaderNavigationMenu
{
    public HeaderNavigationMenu()
    {
        UsersMenu = new UsersMenu();
        Home = new Home();
        DropdownMenu2 = new DropdownMenu2();
    }

    public UsersMenu UsersMenu { get; set; }
    public Home Home { get; set; }
    public DropdownMenu2 DropdownMenu2 { get; set; }
}

public class UsersMenu
{
  ...
}

public class Home
{
  ...
}

public class DropdownMenu2
{
  public void SelectOption3()
  {
    ...
  }
  ...
}

static void Main(string[] args)
{
  HeaderNavigationMenu navigationMenu = new HeaderNavigationMenu();
  navigationMenu.DropdownMenu2.SelectOption3();

  // The following code is an example of undesired capability;
  // prefer if Home class could only be
  // used by HeaderNavigationMenu class
  Home home = new Home();
}

A: Restrict access to the class constructors. If they are declared as "internal" then the classes may only be created by your code.

A: If you're looking to protect against the instantiation of UsersMenu, DropdownMenu2, and Home from outside HeaderNavigationMenu but still within the same project as HeaderNavigationMenu then there is a neat trick that can achieve this behavior. You can use public nested classes with private constructors which statically initialize their own factory methods. The basic template for this would be:
public class Outer{
  private static Func<Inner> _innerFactory;
  public Inner ExposedInner {get; private set;}

  public Outer(){
    // Force the static initializer to run.
    System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(Inner).TypeHandle);

    // Call the newly created factory method instead of a regular constructor.
    ExposedInner = _innerFactory();
  }

  public class Inner {
    static Inner(){
      // Initialize Outer's static factory method.
      _innerFactory = () => new Inner();
    }

    // Inner cannot be instantiated (without reflection) because its constructor is private.
    private Inner(){}

    // This method is now exposed for anyone to use.
    public void DoStuff(){ Console.WriteLine("Did stuff"); }
  }
}

Here's this concept implemented in your example:
class Program
{
    static void Main(string[] args)
    {
        HeaderNavigationMenu navigationMenu = new HeaderNavigationMenu();
        navigationMenu.DropdownMenu2.SelectOption3();

        // This line will no longer work because the constructors
        // for the inner classes are private.
        HeaderNavigationMenu.HomeImpl home = new HeaderNavigationMenu.HomeImpl();

        Console.ReadKey();
    }
}

public class HeaderNavigationMenu
{
    //Private factory methods that are statically initialized
    private static Func<UsersMenuImpl> _createUsers;
    private static Func<DropdownMenu2Impl> _createDropdown;
    private static Func<HomeImpl> _createHome;

    public HeaderNavigationMenu()
    {
        //Force the static constructors to run
        System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(UsersMenuImpl).TypeHandle);
        System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(HomeImpl).TypeHandle);
        System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(DropdownMenu2Impl).TypeHandle);

        UsersMenu = _createUsers();
        Home = _createHome();
        DropdownMenu2 = _createDropdown();
    }

    public UsersMenuImpl UsersMenu { get; set; }
    public HomeImpl Home { get; set; }
    public DropdownMenu2Impl DropdownMenu2 { get; set; }

    public class UsersMenuImpl
    {
        //Static constructor to make the class factory method
        static UsersMenuImpl()
        {
            _createUsers = () => new UsersMenuImpl();
        }

        private UsersMenuImpl() { }
    }

    public class HomeImpl
    {
        //Static constructor to make the class factory method
        static HomeImpl()
        {
            _createHome = () => new HomeImpl();
        }

        private HomeImpl() { }
    }

    public class DropdownMenu2Impl
    {
        //Static constructor to make the class factory method
        static DropdownMenu2Impl()
        {
            _createDropdown = () => new DropdownMenu2Impl();
        }

        private DropdownMenu2Impl() { }

        public void SelectOption3()
        {
        }
    }
}

With this, you will still be able to use all the public properties of the inner classes however no one will be able to instantiate the inner classes from outside HeaderNavigationMenu and only HeaderNavigationMenu has access to the factory methods.

A: I don't really understand what your use case is and I've never coded like this but one way of only exposing the required behaviour of HeaderNavigationMenu would be to make the classes internal and the variables private and then expose only the SelectOption3() method, as below.
If you uncomment the line
//Home home = new Home();

you will get a compiler error.
class Program
{
    static void Main(string[] args)
    {
        HeaderNavigationMenu navigationMenu = new HeaderNavigationMenu();
        navigationMenu.DropdownMenu2SelectOption3();

        // The following code is an example of undesired capability;
        // prefer if Home class could only be
        // used by HeaderNavigationMenu class
        //Home home = new Home();
    }
}
public class HeaderNavigationMenu
{
    UsersMenu usersMenu;
    Home home;
    DropdownMenu2 dropdownMenu2;

    public HeaderNavigationMenu()
    {
        usersMenu = new UsersMenu();
        home = new Home();
        dropdownMenu2 = new DropdownMenu2();
    }

    public void DropdownMenu2SelectOption3()
    {
        dropdownMenu2.SelectOption3();
    }

    class UsersMenu
    {
    }

    class Home
    {
    }

    class DropdownMenu2
    {
        public void SelectOption3()
        {
        }
    }
}

A: You could make UsersMenu, Home, and DropdownMenu2 public abstract classes. Then have private classes nested inside of HeaderNavigationMenu which extend the public abstract versions.
public abstract class UsersMenu
{
}

public abstract class Home
{
}

public abstract class DropdownMenu2
{
   public void SelectOption3()
   {
      // Code for SelectOption3...
   }
}

public class HeaderNavigationMenu
{
    public HeaderNavigationMenu()
    {
        UsersMenu = new UsersMenuImpl();
        Home = new HomeImpl();
        DropdownMenu2 = new DropdownMenu2Impl();
    }

    public UsersMenu UsersMenu { get; }
    public Home Home { get; }
    public DropdownMenu2 DropdownMenu2 { get; }

    private class UsersMenuImpl : UsersMenu
    {
    }

    private class HomeImpl : Home
    {
    }

    private class DropdownMenu2Impl : DropdownMenu2
    {
    }
}

Fellow developers can see and use the UsersMenu, Home, and DropdownMenu2 abstract classes, but cannot create instances of them. Only HeaderNavigationMenu can.
Of course, another developer could always create their own classes deriving from the public abstract ones, but there is only so much you can do. UsersMenu, Home, and DropdownMenu2 have to be public in order to be public properties.


text:
Q: how to connect esp32 with a mac address that i have using blutooth? i'm trying to connect my e-scooter to blutooth using esp32 i got the scooter's mac address so is it possible to only connect them with each other
I searched everywhere on how to connect any device with mac address but couldn't find


text:
Q: Railscasts #396 not working for importing Excel sheet I used the Railscasts to create a feature for uploading CSV and Excel files. Importing CSV files is working well, but when I use Ryan's code for importing Excel sheets using the Roo gem, it throws an error:
TypeError in InventoryItemsController#import "can't convert nil into Hash"
Here is the import method in the controller:
def import
  InventoryItem.import(params[:file])
  redirect_to inventory_items_path, notice: "Inventory Items imported successfully!"
end

I have require 'roo' in the application.rb file along with require 'csv'
The code in the model is:
def self.import(file)
  spreadsheet = open_spreadsheet(file)
  header = spreadsheet.row(1)
  (2..spreadsheet.last_row).each do |i|
    row = Hash[[header, spreadsheet.row(i)].transpose]
    inventory_item = InventoryItem.find_by_inventory_id(row["inventory_id"]) || new
    inventory_item.attributes = row.to_hash #.slice(*accessible_attributes)
    inventory_item.save!
  end
end

def self.open_spreadsheet(file)
  binding.pry
  case File.extname(file.original_filename)
  when ".csv" then CSV.new(file.path, nil)
  when ".xls" then Excel.new(file.path, nil)
  when ".xlsx" then Excelx.new(file.path, nil)
  else raise "Unknown file type: #{file.original_filename}"
  end
end

So, the point I'm stuck on is that the CSV file imports successfully with the following code:
  def self.import(file)
    CSV.foreach(file.path, headers: true) do |row|
      inventory_item = InventoryItem.find_by_inventory_id(row["inventory_id"]) || new
      inventory_item.attributes = row.to_hash #.slice(*accessible_attributes)
      inventory_item.save!
    end
  end

but it doesn't work when using the code from up above (self.import with self.open_spreadsheet).
This is using the Roo gem and I think that there is some rewriting to do in the methods but I'm not really sure... I'm stuck on what to do next to get this to work.
Any help would be much appreciated!
Thank you!
Full trace of error:
TypeError (can't convert nil into Hash)
/Users/marcacyr/.rvm/rubies/ruby-1.9.3-p448/lib/ruby/1.9.1/csv.rb:1565:in `merge'
/Users/marcacyr/.rvm/rubies/ruby-1.9.3-p448/lib/ruby/1.9.1/csv.rb:1565:in `initialize'
app/models/inventory_item.rb:27:in `new'
app/models/inventory_item.rb:27:in `open_spreadsheet'
app/models/inventory_item.rb:14:in `import'
app/controllers/inventory_items_controller.rb:85:in `import'
actionpack (3.0.9) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
actionpack (3.0.9) lib/abstract_controller/base.rb:150:in `process_action'
actionpack (3.0.9) lib/action_controller/metal/rendering.rb:11:in `process_action'
actionpack (3.0.9) lib/abstract_controller/callbacks.rb:18:in `block in process_action'
activesupport (3.0.9) lib/active_support/callbacks.rb:476:in `_run__2908593346646715497__process_action__1677791179652643815__callbacks'
activesupport (3.0.9) lib/active_support/callbacks.rb:410:in `_run_process_action_callbacks'
activesupport (3.0.9) lib/active_support/callbacks.rb:94:in `run_callbacks'
actionpack (3.0.9) lib/abstract_controller/callbacks.rb:17:in `process_action'
actionpack (3.0.9) lib/action_controller/metal/instrumentation.rb:30:in `block in process_action'
activesupport (3.0.9) lib/active_support/notifications.rb:52:in `block in instrument'
activesupport (3.0.9) lib/active_support/notifications/instrumenter.rb:21:in `instrument'
activesupport (3.0.9) lib/active_support/notifications.rb:52:in `instrument'
actionpack (3.0.9) lib/action_controller/metal/instrumentation.rb:29:in `process_action'
actionpack (3.0.9) lib/action_controller/metal/rescue.rb:17:in `process_action'
newrelic_rpm (3.6.1.88) lib/new_relic/agent/instrumentation/rails3/action_controller.rb:38:in `block in process_action'
newrelic_rpm (3.6.1.88) lib/new_relic/agent/instrumentation/controller_instrumentation.rb:318:in `perform_action_with_newrelic_trace'
newrelic_rpm (3.6.1.88) lib/new_relic/agent/instrumentation/rails3/action_controller.rb:37:in `process_action'
actionpack (3.0.9) lib/abstract_controller/base.rb:119:in `process'
actionpack (3.0.9) lib/abstract_controller/rendering.rb:41:in `process'
rack-mini-profiler (0.1.31) Ruby/lib/mini_profiler/profiling_methods.rb:108:in `block in profile_method'
actionpack (3.0.9) lib/action_controller/metal.rb:138:in `dispatch'
actionpack (3.0.9) lib/action_controller/metal/rack_delegation.rb:14:in `dispatch'
actionpack (3.0.9) lib/action_controller/metal.rb:178:in `block in action'
actionpack (3.0.9) lib/action_dispatch/routing/route_set.rb:62:in `call'
actionpack (3.0.9) lib/action_dispatch/routing/route_set.rb:62:in `dispatch'
actionpack (3.0.9) lib/action_dispatch/routing/route_set.rb:27:in `call'
rack-mount (0.6.14) lib/rack/mount/route_set.rb:148:in `block in call'
rack-mount (0.6.14) lib/rack/mount/code_generation.rb:93:in `block in recognize'
rack-mount (0.6.14) lib/rack/mount/code_generation.rb:68:in `optimized_each'
rack-mount (0.6.14) lib/rack/mount/code_generation.rb:92:in `recognize'
rack-mount (0.6.14) lib/rack/mount/route_set.rb:139:in `call'
actionpack (3.0.9) lib/action_dispatch/routing/route_set.rb:493:in `call'
newrelic_rpm (3.6.1.88) lib/new_relic/rack/error_collector.rb:12:in `call'
newrelic_rpm (3.6.1.88) lib/new_relic/rack/agent_hooks.rb:18:in `call'
newrelic_rpm (3.6.1.88) lib/new_relic/rack/browser_monitoring.rb:16:in `call'
newrelic_rpm (3.6.1.88) lib/new_relic/rack/developer_mode.rb:28:in `call'
meta_request (0.2.7) lib/meta_request/middlewares/app_request_handler.rb:13:in `call'
rack-contrib (1.1.0) lib/rack/contrib/response_headers.rb:17:in `call'
meta_request (0.2.7) lib/meta_request/middlewares/headers.rb:16:in `call'
meta_request (0.2.7) lib/meta_request/middlewares/meta_request_handler.rb:13:in `call'
meta_request (0.2.7) lib/meta_request/middlewares/request_id.rb:24:in `call'
bullet (4.6.0) lib/bullet/rack.rb:10:in `call'
actionpack (3.0.9) lib/action_dispatch/middleware/best_standards_support.rb:17:in `call'
actionpack (3.0.9) lib/action_dispatch/middleware/head.rb:14:in `call'
rack (1.2.8) lib/rack/methodoverride.rb:24:in `call'
actionpack (3.0.9) lib/action_dispatch/middleware/params_parser.rb:21:in `call'
actionpack (3.0.9) lib/action_dispatch/middleware/flash.rb:182:in `call'
actionpack (3.0.9) lib/action_dispatch/middleware/session/abstract_store.rb:149:in `call'
actionpack (3.0.9) lib/action_dispatch/middleware/cookies.rb:302:in `call'
activerecord (3.0.9) lib/active_record/query_cache.rb:32:in `block in call'
activerecord (3.0.9) lib/active_record/connection_adapters/abstract/query_cache.rb:28:in `cache'
activerecord (3.0.9) lib/active_record/query_cache.rb:12:in `cache'
activerecord (3.0.9) lib/active_record/query_cache.rb:31:in `call'
activerecord (3.0.9) lib/active_record/connection_adapters/abstract/connection_pool.rb:354:in `call'
actionpack (3.0.9) lib/action_dispatch/middleware/callbacks.rb:46:in `block in call'
activesupport (3.0.9) lib/active_support/callbacks.rb:416:in `_run_call_callbacks'
actionpack (3.0.9) lib/action_dispatch/middleware/callbacks.rb:44:in `call'
rack (1.2.8) lib/rack/sendfile.rb:106:in `call'
actionpack (3.0.9) lib/action_dispatch/middleware/remote_ip.rb:48:in `call'
airbrake (3.1.12) lib/airbrake/rails/middleware.rb:13:in `call'
actionpack (3.0.9) lib/action_dispatch/middleware/show_exceptions.rb:47:in `call'
railties (3.0.9) lib/rails/rack/logger.rb:13:in `call'
rack (1.2.8) lib/rack/runtime.rb:17:in `call'
activesupport (3.0.9) lib/active_support/cache/strategy/local_cache.rb:72:in `call'
rack (1.2.8) lib/rack/lock.rb:13:in `block in call'
<internal:prelude>:10:in `synchronize'
rack (1.2.8) lib/rack/lock.rb:13:in `call'
actionpack (3.0.9) lib/action_dispatch/middleware/static.rb:30:in `call'
rack-mini-profiler (0.1.31) Ruby/lib/mini_profiler/profiler.rb:278:in `call'
airbrake (3.1.12) lib/airbrake/user_informer.rb:16:in `_call'
airbrake (3.1.12) lib/airbrake/user_informer.rb:12:in `call'
railties (3.0.9) lib/rails/application.rb:168:in `call'
railties (3.0.9) lib/rails/application.rb:77:in `method_missing'
railties (3.0.9) lib/rails/rack/log_tailer.rb:14:in `call'
rack (1.2.8) lib/rack/content_length.rb:13:in `call'
rack (1.2.8) lib/rack/handler/webrick.rb:52:in `service'
/Users/marcacyr/.rvm/rubies/ruby-1.9.3-p448/lib/ruby/1.9.1/webrick/httpserver.rb:138:in `service'
/Users/marcacyr/.rvm/rubies/ruby-1.9.3-p448/lib/ruby/1.9.1/webrick/httpserver.rb:94:in `run'
/Users/marcacyr/.rvm/rubies/ruby-1.9.3-p448/lib/ruby/1.9.1/webrick/server.rb:191:in `block in start_thread'

A: The error is pointing to the place where you try to create a new CSV, and the error is telling you exactly what is wrong.  It can't convert nil into a hash.  Instead of CSV.new(file.path, nil) you should probably do CSV.new(file.path, {}) or CSV.new(file.path).

A: For Rails 4 and Ruby 2, I have error "500 Internal Server Error" when follow Railscast #396
My solution now is use:
Roo::CSV.new(file.path, csv_options: {col_sep: ";"})

instead of
Csv.new(file.path, nil, :ignore)


text:
Q: QUnit setup callbacks all being called before running any tests in Internet Explorer 9 I've come across a very strange problem when executing my QUnit tests in IE9. The test structure is something like this:
function setupTest() {
    // Adding some extra items to the DOM
}

function teardownTest() {
    // Removing dirtied items from the DOM
}

module("MODULE A", {setup: setupTest, teardown: teardownTest});

test("TEST 1", function () {
    // Some simple assertions
});

module("MODULE B", {setup: setupTest, teardown: teardownTest});

test("TEST 2", function () {
    // Some simple assertions
});

About 50% of the time these tests fail. I have made sure the tests are entirely independent and the setup/teardown fully completes before/after a test runs. The problem comes down to the setup callbacks being called out of sequence half of the time. With logging I can see this happening:
Successful run:
LOG: completing setup
LOG: MODULE A: TEST 1
LOG: completing teardown
LOG: completing setup
LOG: MODULE B: TEST 2
LOG: completing teardown

Unsuccessful Run:
LOG: completing setup
LOG: completing setup    <-- ?
LOG: MODULE B: TEST 2
LOG: completing teardown
LOG: MODULE A: TEST 1
LOG: completing teardown

As you can see on the unsuccessful run the setup callback is correctly executed twice, but before either of the tests are executed. Since teardown removes the required DOM elements the second executed test is bound to fail as its setup was called too early and the first executing test (correctly) ripped it out with its teardown.
This problem always occurs when the second test is executed before the first, but I can see no reason that this should cause a problem. The issue never appears in Chrome.

A: I had the same issue in Chrome (exactly 50% of the time my tests fail) and solved it in next way:
Code with bug:
require(["jquery", "jquerymobile", "QUnit", "underscore",
    "units/general.unit", "units/mapping.unit"],
function( $, jqm, __QUnit, _ ) {
    var test_modules = Array.prototype.splice.call(arguments, 4);
    _.each( test_modules, function(test){
        test.start();
    });
    QUnit.load();
    QUnit.start();
});

Corrected version
require(["jquery", "jquerymobile", "QUnit", "underscore",
    "units/general.unit", "units/mapping.unit"],
function( $, jqm, __QUnit, _ ) {
    QUnit.load();
    QUnit.start();
    var test_modules = Array.prototype.splice.call(arguments, 4);
    _.each( test_modules, function(test){
        test.start();
    });
});

QUnit.load() and QUnit.start() moved before the tests invocation and it do the trick.


text:
Q: NSURLRequest - get a cached response AND a current response? Before I continue writing my own infrastructure - is it possible to execute a request, have it return immediately if it's cached, and then return later if the cached version does not match the current version?  Is that kind of functionality built-in to NSURLCache/NSURLRequest?
In other words:

*

*request MYTHING.json

*return immediately with cached MYTHING.json

*display to user

*return again if the cached version was not current

*update display

A: You can query NSURLCache directly via cachedResponseForRequest: to find out whether anything is already in it. You can then issue the NSURLRequest and see whether what comes back is different. But I'm not aware of a built-in mechanism that would give you first anything that's already in the cache then whatever is fetched, if it determines that anything needs to be fetched and if what was fetched is different.


text:
Q: Do search engines take into considertaion ARIA roles (http://www.w3.org/TR/wai-aria/)? My company's web-site is all about online games, so accessibility is not high on our priority list. SEO best practices, however, are. Searching on the net we couldn't find any discussion of whether or not ARIA is such a best practice (which is a kind of answer already :-). I found this surprising because using ARIA roles seems like a natural thing to do -  they contain a lot of SEO-relevant meta-data (overall page structure, what parts of the page are the "main" as opposed to "service" navigation area, what parts contain "actual" vs. "related" vs. "independent" content, etc.). What's more, given they effect the user interface (screen readers and so on) they would tend to be pretty accurate when they exist.
Does anyone have specific knowledge about whether any search engines actually use this data, if it exists in a page?

A: Search engines like Google are pretty smart no matter how badly you set up your page, SEO relevant meta data or not.
The main thing is to make sure your page is marked up properly, that it validates and that you don't employ any "black-hat" techniques that could cause search engines to black list your page.
As for ARIA, I'm not sure if it's really going to make much difference one way or another.


text:
Q: Installing Spark with Maven (MAC OSX) I am very new to Spark and attempting a first time install. I have downloaded homebrew and installed Maven with it.
I have run the following to ensure the install was done correctly:
Command: maven - v
Apache Maven 3.3.9 (bb52d8502b132ec0a5a3f4c09453c07478323dc5; 2015-11-10T16:41:47+00:00)
Maven home: /usr/local/Cellar/maven/3.3.9/libexec
Java version: 1.8.0_111, vendor: Oracle Corporation
Java home: /Library/Java/JavaVirtualMachines/jdk1.8.0_111.jdk/Contents/Home/jre
Default locale: en_GB, platform encoding: UTF-8
OS name: "mac os x", version: "10.12.3", arch: "x86_64", family: "mac"

However, when I try to build spark using the following command:
 ./build/mvn -Pyarn -Phadoop-2.4 -Dhadoop.version=2.4.0 -DskipTests clean package

I get this error:
-bash: ./build/mvn: No such file or directory

UPDATE:
I went on to follow instructions on instaling Spark with Homebrew from here:
• https://medium.com/@josemarcialportilla/installing-scala-and-apache-spark-on-mac-os-837ae57d283f#.ru5hi42v3
This worked fine untill I restarted the terminal. When I execute
spark-shell
I get :
/usr/local/Cellar/apache-spark/2.1.0/libexec/bin/spark-shell: line 57: /usr/local/Cellar/apache-spark/2.0.1/libexec/bin/spark-submit: No such file or directory

Would appreciate any pointers in resolving this.
UPDATE
I have updated my .bash_profile to this.

Still getting the same error. However when I access the files directly by going to the folder via terminal, I can open it.

A: If the version of spark you installed is not 2.1.0, then you have to modify the line export SPARK_HOME= .... to correspond to version of spark you have.


text:
Q: How can I compact my Scrap Mechanic logic down? Is there a way for me to more easily compact my logic? For example, Here I have this start to a 64bit ALU:

I have no idea how I could just turn this into a 64-wide prism, but so often when you see complicated logic on the workshop, that is how it comes. A glass-enclosed cube.
How do people make these?
Note: If anyone reading this question knows a Scrap Mechanic logical engineer, share this question with them! Thank you.


text:
Q: How to refresh the page and overwriting content? Testing on IBM Worklight with a HTTP adapter.
My question is: How to refresh the page and overwriting old with new set of list items? Or emptying the list items and add/append new list items?

*

*Without page refresh concept,from drop down, if sport is selected the cnn sport news is appended then if technology is selected the cnn technology news is appended after the last list tag ended that is after sport news.

*With page refresh concept (window.location.reload();). By trying the js code, the page refreshes but cannot append rss feeds item.
I want at a time one news category will be displayed and previous list will be overwritten.
HTML
<!DOCTYPE HTML>

    <meta charset="UTF-8">
    <title>RSSnew</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0">
    <link rel="shortcut icon" href="images/favicon.png">
    <link rel="apple-touch-icon" href="images/apple-touch-icon.png">
    <link rel="stylesheet" href="css/RSSnew.css">

        <select size="2" id="cc">
        <option selected>select categories</option>
        <option value="Sport">Sport</option>
        <option value="Technology">Technology</option>
    </select>

    <input type = "button" onclick="search()" value="Search">//onclick="reload(),search()"

JS
function search()
{
    window.location.reload();
    var a=$("#cc").val();
    alert(a);
     var invocationData={

             adapter:'cnn',
             procedure:'getStories',
             parameters:[a]
     };

     var options={
             onSuccess:su,
             onFailure:fa
     };
     WL.Client.invokeProcedure(invocationData, options);
}

function su(result)
{

    alert("success");
    var a=result.invocationResult.rss.channel.item.length;
    var i;

    for(i=0;i<=a;i++)
        {
            var b=result.invocationResult.rss.channel.item[i].title;
            var c=result.invocationResult.rss.channel.item[i].description;

            var d=$("#news");

            var e=$('
'+b+'
');
            var f=$('
').html(c);
            d.append(e,f);

        }
}

function fa()
{
    alert("failure");
}

function reload() {

    window.location.reload();
    //$("#news").remove();
//  search();

}

A: Instead of using window.location.reload(); simply empty the contents of the #news UL element.
In the search() function, replace the reload line with ul.innerHTML = '';.
Should work.

A: If you use jQuery setInterval function method, you will refresh & overwrite your data without reloading page.
var doYourStuff = function () {
  // Your functionality
};
setInterval(doYourStuff, 1000);


text:
Q: Pra que serve um word boundary (\b) numa expressão regular? Há muito tempo, dei uma olhada a respeito do uso de word boundary, estudando sobre expressões regulares no PHP (PCRE Patterns).
Me deparei com o \b (que é chamado de word boundary).
Qual é a utilidade dele numa expressão regular?

A: Conforme já dito aqui, o atalho \b é conhecido como word boundary (algo como "fronteira entre palavras").
Um detalhe importante é que ele é um zero-length match (match de tamanho zero), pois ele não corresponde a um caractere, e sim a uma posição da string. Sendo mais específico, ele corresponde a uma posição que possui um caractere alfanumérico antes e não possui um caractere alfanumérico depois (ou vice-versa).

Na verdade a definição usa o termo "word character" em vez de "alphanumeric character", mas como achei que "caractere de palavra" (ou qualquer outra tentativa de tradução) não ficou bom, vou usar o termo "alfanumérico" mesmo. De qualquer forma, mais adiante tem uma discussão mais detalhada sobre esta definição.

Como já dito na outra resposta, o \b também acaba pegando o início e fim da string, desde que ela comece ou termine com um caractere alfanumérico. Por exemplo, se a string for 'abc.', então a regex \b[a-z] dá match na letra "a", pois o [a-z] indica uma letra de "a" a "z", e o \b indica uma posição que tem um caractere alfanumérico depois (no caso, a letra "a") e não possui um caractere alfanumérico antes, pois a letra está no início da string e portanto não tem nenhum caractere antes (interessante notar que não precisa ter um caractere não-alfanumérico antes, basta que não tenha um caractere antes - uma diferença sutil, porém importante na definição do \b).
Para ser mais preciso, o \b corresponde a qualquer posição da string que atenda a um desses critérios:

*

*início da string, se o primeiro caractere for alfanumérico

*final da string, se o último caractere for alfanumérico

*entre dois caracteres da string, se um deles é alfanumérico e outro não

Sua utilidade é para buscar palavras exatas em um texto, como já mencionado na outra resposta.

O problema é que, dependendo da engine/linguagem/ferramenta, a definição de "alfanumérico" pode variar.
No JavaScript, por exemplo, o \b só considera caracteres ASCII, e portanto não funciona com letras acentuadas:

console.log('café forte'.split(/\b/)) // [ 'caf', 'é ', 'forte' ]

Repare que o split separou "caf" e "é", pois ele considera que é não é um alfanumérico (ou sendo mais preciso, não é um word character). Vale notar que o \b faz a quebra nas posições em que os caracteres antes e depois não são do mesmo "tipo" (um é alfanumérico e o outro não), mas como ele é um zero-length match, nenhum caractere é excluído do resultado final, pois a quebra foi feita apenas na posição à qual o \b corresponde (é diferente, por exemplo, de split(/,/), que faz a separação pela vírgula e também exclui todas as vírgulas do resultado).
Isso ocorre porque o \b geralmente considera que "alfanumérico" (ou "word character") são os caracteres que correspondem ao atalho \w. E no JavaScript o \w só considera os caracteres ASCII (é equivalente a [a-zA-Z0-9_]). Mesmo que exista a flag u (que habilita o "modo Unicode"), no JavaScript ele não muda o comportamento do \w e \b. Na resposta já citada tem uma alternativa para considerar letras acentuadas.
Ou seja, as posições em que o split foi feito são:

*

*entre o primeiro "f" e o "é", pois é uma posição que possui um caractere alfanumérico antes ("f") e um não-alfanumérico depois ("é")

*entre o espaço (que está logo depois do "é") e a letra "f" (da palavra "forte"), pois é uma posição que possui um caractere não-alfanumérico antes (o espaço) e um alfanumérico depois ("f")

Em outras linguagens você pode mudar o comportamento do \w e \b. Em PHP, por exemplo, isso pode ser obtido usando-se a flag u, que faz com que o \w e \b passem a considerar caracteres acentuados. Ex:
print_r(preg_split('/\b/', 'café forte')); // sem flag, considera somente ASCII
print_r(preg_split('/\b/u', 'café forte')); // com flag u, considera acentos e quaisquer outros caracteres Unicode

A saída do código acima é:
Array
(
    [0] =>
    [1] => caf
    [2] => é
    [3] => forte
    [4] =>
)
Array
(
    [0] =>
    [1] => café
    [2] =>
    [3] => forte
    [4] =>
)

Já no Python 3, tanto \w quanto \b consideram todos os caracteres Unicode (a menos que se use a flag re.ASCII):
import re

s = 'café forte'
print(re.split(r'\b', s)) # ['', 'café', ' ', 'forte', '']
print(re.split(r'\b', s, flags=re.ASCII)) # ['', 'caf', 'é ', 'forte', '']
print(re.findall(r'\w+', s)) # ['café', 'forte']
print(re.findall(r'\w+', s, flags=re.ASCII)) # ['caf', 'forte']

Na maioria das engines, o \b é consistente com \w, ou seja, ele considera as posições entre dois caracteres da string na qual um deles corresponde a \w e o outro não. A exceção é Java, na qual \b por padrão está no "modo Unicode", enquanto \w por padrão só aceita ASCII. Ex:
String s = "café forte";

Pattern p = Pattern.compile("\\b");
System.out.println(Arrays.toString(p.split(s)));

Matcher matcher = Pattern.compile("\\w+").matcher(s);
while (matcher.find()) {
    System.out.println(matcher.group());
}

A saída é:
[café,  , forte]
caf
forte

Repare que \b considerou a letra acentuada corretamente, mas \w não. Para o \w considerar o acento, teria que mudar para Pattern.compile("\\w+", Pattern.UNICODE_CHARACTER_CLASS).

Resumindo:

*

*\b considera uma posição da string, não um caractere (e esta posição leva em conta as regras já mencionadas acima)

*seu comportamento pode ou não ser consistente com \w (geralmente é)

*pode ou não considerar caracteres Unicode por padrão, e pode ou não haver meios de configurar este comportamento

A: O \b (beta) é uma âncora assim como seus primos ^(alfa) e $(omega). Uma vez adicionado em um dos lados da regex vai capturar padrão especificado no inicio, final ou palavra exata, isso significa que é válido apenas para letras, números e o underline ([A-Za-z0-9_]) que é o equivalente ao \w.
Entrada:
dialogo dia melodia diafragma dialeto radial bom-dia

Âconra no início \bdia capturar strings(palavras) que contenham no início(não é o início da linha) o padrão dia, os itens que entram na captura são, dialogo, dia, diafragma, dialeto e bom-dia
Âncora no fim dia\b captura strings(palavras) onde o padrão especificado está no final, os itens capturados são: dia, melodia e bom-dia
Âncora exata \bdia\b captura a strings(palavras) extas dia e bom-dia
Referências
http://www.rexegg.com/regex-boundaries.html
http://www.regular-expressions.info/wordboundaries.html


text:
Q: Send audio to server in realtime I am trying to develop DJ web application. Here i am playing audio using web audio api. I am adding effect to the audio while playing. I want to share this updated audio live to other users. I am planning to use nodejs and socket io.
How can i send this updated audio to server in realtime?


text:
Q: I can't delete data multiple in mysql from python I made input 2 value row and num when input data so program throw Rollback not work if-else and thank for help
#!/usr/bin/python
import mysql.connector
conn = mysql.connector.connect(host="",user="",passwd="",db="")
cursor = conn.cursor()
try:
        row = raw_input("InputNameRow : ")
        num = int(input("InputNumber 1-10 : "))
        if num <= 10:
                sql1 = "SELECT * FROM dt WHERE '%s' = '%d' " %(row,num)
                cursor.execute(sql1)
                data = cursor.fetchall()
                print(data[0])
                sqlde = "DELETE FROM dt WHERE '%s' = '%d' " %(row,num)
                cursor.execute(sqlde, (num))
                print "DELETE SUCESS"
                conn.commit()
        else:
                print "Data Empty"
except:
        conn.rollback()
        print "Input Error"

conn.close()

A: Try :
cursor.execute(sqlde)

instead of
cursor.execute(sqlde, (num))


text:
Q: Binding dropdownlist without refresh I am adding Category using jquery/ajax.
$.ajax({
        type: "POST",
        url: "Admin.aspx/SaveCategory",
        data: JSON.stringify({ "kategorija": kategorija }),
        datatype: "JSON",
        contentType: "application/json; charset=utf-8",
        success: function (data) {

            if (data.d == "true") {
                //console.log(kategorija);
                kopce.removeClass("btn-default");
                kopce.addClass("btn-success");
                kopce.html("Dodadeno!");
            }

        }

At the WebMethod on the server SaveCategory i have this code, also here i am calling a function for populating the dropdown.
var context = new CategoryEntities();

            var t = new Category //Make sure you have a table called test in DB
            {
               // CategoryId = Guid(),
                CategoryName = kategorija,
            };

            context.Categories.Add(t);
            context.SaveChanges();
            FillDropDown();
            string result = "true";

            return result;

My function for populating dropdown :
public void FillDropDown()
        {
            var context = new CategoryEntities();

            var category = (from c in context.Categories
                            select new { c.CategoryId, c.CategoryName }).ToList();

            DropDownList1.DataValueField = "CategoryId";
            DropDownList1.DataTextField = "CategoryName";
            DropDownList1.DataSource = category;
            DropDownList1.DataBind();

        }

But function for populating a dropdown does not fire when SaveCategory function is called.
I want to bind/refresh dropdown when category is added. Some help ?


text:
Q: How to get an input[type="number"] to show all the values as selectable values? I have an input[type="number"] within Woocommerce Bookings and right now this  shows a field where I can type a number but I'd like to show all the possible values (in this case 1 up to and including 8) and be able to select one of these values. How can this be best achieved?
input type="number" value="1" step="1" min="1" max="8" name="wc_bookings_field_persons" id="wc_bookings_field_persons"

A: You can use javascript to do that
<input type = 'number' step = 1 min = 1 max = 8 onChange="limit_value(this)" onKeydown="limit_value(this)"  onKeyup="limit_value(this)" onKeypress="limit_value(this)"  >
<script type="text/javascript">
    function limit_value(_this){
        var value   = parseInt(_this.value) ;
        var min     = parseInt(_this.getAttribute('min')) ;
        var max     = parseInt(_this.getAttribute('max')) ;
        _this.value = (value < min) ? min : ( ( value > max ) ? max : value ) ;
    }
</script>


text:
Q: Kafka on the server failed the next day。(EndOfStreamException: Unable to read additional data from client,) The Kafka service I deployed on the server passed the test a few days ago and was running normally. Later, no other operations were carried out.
Then the service call failed today. I went online and looked at it. It's normal these days. Just this afternoon, the service hung up. Looking at the log, it seems to say that the Kafka service is restarted automatically, and then conflicts with the ID of zookeeper.
Restart the service. Everything is normal. Google doesn't have a good solution. What's the reason?
The following is the relevant log, please help to see, thank you
[2021-11-06 14:43:29,139] WARN Unexpected exception (org.apache.zookeeper.server.NIOServerCnxn)
EndOfStreamException: Unable to read additional data from client, it probably closed the socket: address = /159.89.4.236:59168, session = 0x0
    at org.apache.zookeeper.server.NIOServerCnxn.handleFailedRead(NIOServerCnxn.java:163)
    at org.apache.zookeeper.server.NIOServerCnxn.doIO(NIOServerCnxn.java:326)
    at org.apache.zookeeper.server.NIOServerCnxnFactory$IOWorkRequest.doWork(NIOServerCnxnFactory.java:522)
    at org.apache.zookeeper.server.WorkerService$ScheduledWorkRequest.run(WorkerService.java:154)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

[2021-11-06 15:00:18,301] INFO Completed load of Log(dir=/tmp/kafka-logs/__consumer_offsets-46, topicId=dPs0Kq4ERHKDaR440Nt8qA, topic=__consumer_offsets, partition=46, highWatermark=0, lastStableOffset=0, logStartOffset=0, logEndOffset=0) with 1 segments in 20ms (53/53 loaded in /tmp/kafka-logs) (kafka.log.LogManager)
[2021-11-06 15:00:18,303] INFO Loaded 53 logs in 2350ms. (kafka.log.LogManager)
[2021-11-06 15:00:18,303] INFO Starting log cleanup with a period of 300000 ms. (kafka.log.LogManager)
[2021-11-06 15:00:18,304] INFO Starting log flusher with a default period of 9223372036854775807 ms. (kafka.log.LogManager)
[2021-11-06 15:00:18,838] INFO [BrokerToControllerChannelManager broker=0 name=forwarding]: Starting (kafka.server.BrokerToControllerRequestThread)
[2021-11-06 15:00:19,148] INFO Updated connection-accept-rate max connection creation rate to 2147483647 (kafka.network.ConnectionQuotas)
[2021-11-06 15:00:19,165] INFO Awaiting socket connections on 0.0.0.0:9092. (kafka.network.Acceptor)
[2021-11-06 15:00:19,237] INFO [SocketServer listenerType=ZK_BROKER, nodeId=0] Created data-plane acceptor and processors for endpoint : ListenerName(PLAINTEXT) (kafka.network.SocketServer)
[2021-11-06 15:00:19,282] INFO [BrokerToControllerChannelManager broker=0 name=alterIsr]: Starting (kafka.server.BrokerToControllerRequestThread)
[2021-11-06 15:00:19,400] INFO [ExpirationReaper-0-DeleteRecords]: Starting (kafka.server.DelayedOperationPurgatory$ExpiredOperationReaper)
[2021-11-06 15:00:19,400] INFO [ExpirationReaper-0-Fetch]: Starting (kafka.server.DelayedOperationPurgatory$ExpiredOperationReaper)
[2021-11-06 15:00:19,400] INFO [ExpirationReaper-0-Produce]: Starting (kafka.server.DelayedOperationPurgatory$ExpiredOperationReaper)
[2021-11-06 15:00:19,409] INFO [ExpirationReaper-0-ElectLeader]: Starting (kafka.server.DelayedOperationPurgatory$ExpiredOperationReaper)
[2021-11-06 15:00:19,451] INFO [LogDirFailureHandler]: Starting (kafka.server.ReplicaManager$LogDirFailureHandler)
[2021-11-06 15:00:19,530] INFO Creating /brokers/ids/0 (is it secure? false) (kafka.zk.KafkaZkClient)
[2021-11-06 15:00:19,566] ERROR Error while creating ephemeral at /brokers/ids/0, node already exists and owner '72057654275276801' does not match current session '72057654275276802' (kafka.zk.KafkaZkClient$CheckedEphemeral)
[2021-11-06 15:00:19,572] ERROR [KafkaServer id=0] Fatal error during KafkaServer startup. Prepare to shutdown (kafka.server.KafkaServer)
org.apache.zookeeper.KeeperException$NodeExistsException: KeeperErrorCode = NodeExists
    at org.apache.zookeeper.KeeperException.create(KeeperException.java:126)
    at kafka.zk.KafkaZkClient$CheckedEphemeral.getAfterNodeExists(KafkaZkClient.scala:1904)
    at kafka.zk.KafkaZkClient$CheckedEphemeral.create(KafkaZkClient.scala:1842)
    at kafka.zk.KafkaZkClient.checkedEphemeralCreate(KafkaZkClient.scala:1809)
    at kafka.zk.KafkaZkClient.registerBroker(KafkaZkClient.scala:96)
    at kafka.server.KafkaServer.startup(KafkaServer.scala:319)
    at kafka.Kafka$.main(Kafka.scala:109)
    at kafka.Kafka.main(Kafka.scala)
[2021-11-06 15:00:19,596] INFO [KafkaServer id=0] shutting down (kafka.server.KafkaServer)
[2021-11-06 15:00:19,597] INFO [SocketServer listenerType=ZK_BROKER, nodeId=0] Stopping socket server request processors (kafka.network.SocketServer)```


text:
Q: Localization of Localization isomorphic to localization, prime ideals Let $R$ be a commutative ring, and $P,Q \subset R$ prime ideals such that $ P \subseteq Q$. Let $R_{P}$ denote the localization of $R$ at $P$. Prove that $R_{1} = R_{P}$ is isomorphic to $R_{Q}$ localized at $PR_{Q}$, denote this ring as $R_{2}$. I tried to give explicit definitions for $R_{1}$ and $R_{2}$. So $R_{1} = \left\{ \frac{r}{p} : r \in R, p \in P \right\}$, and $R_{2} = \left\{ \frac{\frac{r_{1}}{q_{1}}}{p \frac{r_{2}}{q_{2}}} : r_{1} , r_{2} \in R , q_{1}, q_{2} \in Q , p \in P\right\}$. I am assuming that $\frac{\frac{r_{1}}{q_{1}}}{p \frac{r_{2}}{q_{2}}} \sim \frac{r}{p}$ for some $r \in R$ to get the desired isomorphism, but I am stuck.

In a previous exercise, it was shown that $\phi' : D^{-1}R \rightarrow F^{-1}S$ defined by $\phi'(r/d) = \phi(r) / \phi(d)$ is a ring homomorphism for $\phi : R \rightarrow S$ a ring homomorphism, and $D = \phi^{-1}(F)$ where $F \subset S$ is a multiplicatively closed set.


text:
Q: Determining correction terms for an equivalent form to the relativistic Schrödinger equation I am reading the book Stochastic Processes in Quantum Physics by Masao Nagasawa and I am having a bit of trouble getting my head around the following result. I would much appreciate any help. The thing is that Theorem 7.2.1 says that if $\psi(x,t)=\exp(R(x,t)+iS(x,t))$, where $R$ and $S$ are real valued, satisfies the relativistic Schrödinger equation
$$i\partial_t \psi=\left(\sqrt{-c^2\Delta+m^2c^4 }-mc^2\right)\psi$$
then $\phi_{\pm}(x,t)$ defined as $\phi_{\pm}(x,t)=\exp(R(x,t)\pm S(x,t))$ satisfy
$$\pm\partial_t \phi_{\pm}-v(x,t)\phi_{\pm}=\left(\sqrt{-c^2\Delta+m^2c^4 +c\{\nabla, \textbf{B}(x,t)\}+v(x)^2}-mc^2\right)\phi_{\pm}$$
where ${v}(t, x)$ and $\textbf{B}(t, x)$ are determined by the equations
$$
c\textbf{B}  \cdot \nabla R-v \frac{\partial R}{\partial t}+\frac{\partial^{2} S}{\partial t^{2}}+2 \frac{\partial R}{\partial t} \frac{\partial S}{\partial t}=0
\tag{1}
$$
$$
c\textbf{B}\cdot \nabla S-v\left(\frac{\partial S}{\partial t}-mc^2\right)+c^{2} \Delta R+c^{2} (\nabla R)^{2}+\left(\frac{\partial S}{\partial t}\right)^{2}=0
\tag{2}
$$
under the gauge condition
$$
c\nabla \cdot \textbf{B}=\frac{\partial v}{\partial t}
$$
What I don't understand is the following claim: on page 239 it says that one can determine the correction terms $\textbf{B} (t, x)$ and $v(t, x)$ of vector and scalar potentials using equations (1) and (2).  That is what don't comprehend, I can't see how one could compute $\textbf{B}$ and $v$ from these equations. Maybe I could add that I am ultimately interested in taking the non-relativistic limit $c\to+\infty $, so what would be ideal would be to have a closed expression for the correction terms $\textbf{B}$ and $v$.

A: This was a bit too long of a response for a comment but I hope it can help:
In the limit $c \to \infty$, your equations reduce to
$$
\textbf{B}  \cdot \nabla R=0
\tag{1}
$$
$$
mv+ \Delta R+ (\nabla R)^{2}=0
\tag{2}
$$
with the non-relativistic gauge condition $ \nabla \cdot {\bf B} = 0$. So we can generally take ${\bf B}=\nabla \times A$ for some vector potential $A$. However, I notice that this is a strictly one dimensional problem, so we have ${\bf B}=k + f(t)$, a constant plus some function in time.
Additionally, $R$ is one dimensional, so we can re-write these equations as
$$
(k+f(t)) \cdot R'(x) = 0
\tag{1*}
$$
$$
mv+R''(x)+(R'(x))^2=0
\tag{2*}
$$
it looks like equation 1 can simplify to $R(x)=n$, another constant.
All told, this constant solution seems quite mundane, so hopefully someone can shed some further light on this problem.


text:
Q: QWT moving canvas I'm using QWT library for my widget, there are some curves on the canvas, like this:
void Plot::addCurve1( double x, double y, const char *CurveName,
                      const char *CurveColor,const char *CurveType )
{
...
    *points1 << QPointF(x, y);
    curve1->setSamples( *points1 );
    curve1->attach( this );
...
}

So, all my curves have the same coordinate system. I'm trying to build navigation interface, so I could put step into TextEdit (for example) and moving by using this step, or I could go the end/start of my defined curve.
I've found method in QwtPlotPanner class, that gives me such opportunity:
double QWT_widget::move_XLeft()
{
    //getting step from TextEdit
    QString xValStr = _XNavDiscrepancies->toPlainText();
    double xVal = xVal.toDouble();
    // moveCanvas(int dx, int dy) - the method of QwtPlotPanner
    plot->panner->moveCanvas(xVal,0);
    x_storage = x_storage - xVal;
    return x_storage;
}

So it works ok, but displacement in pixels and I need to stick it to my defined curve and it's coordinate system.
 Qwt User's Guide tells, that:

Adjust the enabled axes according to dx/dy
  Parameters
  dx    Pixel offset in x direction
  dy    Pixel offset in y direction

And this is the only information I've found. How can I convert pixels step into my coordinat system step? I need to go to the end of my curve, so I should return the last QPointF(x,y) of my curve and convert it to pixel-step? Or maybe I'm using wrong class/method?
Thank you very much :)

A: Thanks to @Pavel Gridin:
(https://ru.stackoverflow.com/a/876184/251026)

"For conversion from pixels to coordinates and back there are two
  methods: QwtPlot::transform and QwtPlot::invTransform"


text:
Q: Open Ms Word in write mode using microsoft.office.interop.word I am trying to open a MS Word Document through C#. But the open method is opening the document in a read-only mode. I want the file to be opened in write mode without creating another copy of i, so that I can save the changes to Database.
Here is the code for opening the file.
public void def()
{
    Word.Application app = new Word.Application();
    Word.Document dd = app.Documents.Open("C:\\hi12.docx", ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing,ref repair);
    dd.TrackRevisions = true;
    dd.CommandBars["Reviewing"].Controls["Reviewing Pane"].Execute();
    int count = dd.Words.Count;
    dd.Close(ref Nothing, ref format, ref Nothing);
}

A: Does this help? http://msdn.microsoft.com/en-us/library/microsoft.office.interop.word.view.readinglayoutallowediting
Also you should not use interop when not running on a client (asp.net runs on a server).
You also definitely need to close your app.


text:
Q: v-if inside v-for shows all instances (Vue) I have a v-if inside a v-for. I want to have a button inside that can toggle content on and off but a click on one instance will open all instances on the page. How I can I only open and close the particular div that I click.
Here is the code.

Note

{{ user_leav.note }}

Thanks

A: You could add showNote inside the user_leav

Note

{{ user_leav.note }}

Or else you would have to define showNote as an array

Note

{{ user_leav.note }}

For the second solution, you will have to make a watcher to "reinitialize" the showNote array, each time the filters change.
watch: {
  user_leave_filitered(newVal) {
    // Requires polyfill
    this.showNote = new Array(newVal.length).fill(false)
    // Or
    this.showNote = new Array(newVal.length);
    for( note of this.showNote ) {
      note = false;
    }
  }
}

Keep in mind: Array.prototype.fill is not supported in Edge, therefore would need a polyfill.

A: Use functions to manipulate the data and check if the id has been clicked.

Note

{{ user_leav.note }}

And then add add and remove items from an array and check against that array.
data () {
    return {
      showNote: []
    }
  },
methods: {
  toggle: function (userLeavePassed) {
    if (this.showNote.includes(userLeavePassed.id)) {
      var index = this.showNote.indexOf(userLeavePassed.id)
      if (index > -1) {
        this.showNote.splice(index, 1)
      }
    } else {
      this.showNote.push(userLeavePassed.id)
    }
  },
  checkNote: function(notePassed) {
    if (this.showNote.includes(notePassed)) {
      return true
    } else {
      return false
    }
  }
}


text:
Q: Call virtual method over multiple inheritance leves What is the easiest way in c#, to directly call the virtual method implementation in multiple levels of inheritance? I only know base for this, but with base it seems that i not call the virtual method, but an overriden. For example:

*

*Class A has a virtual method: public virutal void Do()

*Class B overrides the method: public override void Do()

*Class C wants to call the implementation in class A.

The inheritance is like this:

*

*class B : A

*class C : B
I think this is very easy but i did not get it.
Thank you...


text:
Q: Showing value after "While" from ACF repeater field Im trying to show custom post array by ACF repeater field ID-s.
I only get one value from $value, ex:
'post__in' => array(905)
But it should be:
'post__in' => array(15, 905, 1, 2, 3)
<?php
if( have_rows('take_away_order') ):
while ( have_rows('take_away_order') ) : the_row();
  $value = get_sub_field('food');
?>
<?php endwhile;?>
<?php if (is_tax() || is_category() || is_tag() ){
$qobj = $wp_query->get_queried_object();
$args = array(
    'posts_per_page' => 999,
    'post_type' => 'menuu_toit',
    'orderby' => 'menu_order',
    'order'   => 'ASC',
    'post__in' => array($value),
    'tax_query' => array(
        array(
            'taxonomy' => $qobj->taxonomy,
            'field' => 'id',
            'terms' => $qobj->term_id
        )
    )
);
}

A: Got it,
 <?php
 if( have_rows('take_away_order') ):
    $value = [];
  while ( have_rows('take_away_order') ) : the_row();

  $value[] = get_sub_field('food');

 ?>
 <?php endwhile;?>
 <?php if (is_tax() || is_category() || is_tag() ){
 $qobj = $wp_query->get_queried_object();
 $args = array(
    'posts_per_page' => 999,
    'post_type' => 'menuu_toit',
    'orderby' => 'menu_order',
    'order'   => 'ASC',
    'post__in' => $value,
    'tax_query' => array(
        array(
            'taxonomy' => $qobj->taxonomy,
            'field' => 'id',
            'terms' => $qobj->term_id
        )
    )
 );
 }


text:
Q: icomparer on multiple lists I have 3 different lists with the same items in it. ( List )
When I use an icomparer to sort them on date, my c# form sorts them in each list en doesn't take itemsall together and sort it after that.
    private List<Blog> lijstPublicBlogs;
    private List<Blog> lijstRestrictedBlogs;
    private List<Blog> lijstPrivateBlogs;

Those 3 lists I got, and I want that the comparer sorts all the items from all lists together, instead of sorting them per each list...
This is that my comparer is doing (For example, sorting on date):
List 1
03-04-2013
05-04-2013
List 2
04-04-2013
06-04-2013
List 3
01-04-2013
02-04-2013
But what I want is, put when sorting all list items together and do this:
01-04-2013
02-04-2013
03-04-2013
04-04-2013
05-04-2013
06-04-2013
Anyone got a clue how i can solve this... I really appreaciate it!
What I want to do is: Putting all the list items (from the 3 lists) together and use iComparer on the items.

A:
Those 3 lists I got, and I want that the comparer sorts all the items from all lists together, instead of sorting them per each list...

I strongly recommend that instead of maintaining three separate lists, you create one list with a type which contains all three items. Then you can sort the single list, and it's likely to be easier to work with the related items anyway. Whenever you have multiple collections which are all kept in sync, consider creating a type to encapsulate all the related items, so you can then create a single collection of that type. You'll save yourself a lot of headaches.