text:
Q: Verify if a word have a letter repeated in any position I'd like know if there are a way to test if a word have a letter repeated in any position?
I'm currently using this regex to test it, but not work, becouse if I add more then 2 's' the test returns true.
  /s{0,2}/.test('süuaãpérbrôséê'); //expected true
  /s{0,2}/.test('ssüuaãpérbrôéê'); //expected true
  /s{0,2}/.test('süuaãpérbrôéê'); //expected true
  /s{0,2}/.test('süuaãpérbrôséês'); //expected fail

Thanks.

A: /s{2,}/

or generally for any character:
/(.)\1/

A: /(\w)\1/ finds two alphanumeric characters next to each other
This will find and replace the duplicates:
s/(\w)\1/$1/

A: The only way that I found to resolve this problem is using php preg_match_all, on this way I can count how much times the character repeat.
  $s = 'süuaãpérbrôséê';
  preg_match_all('/s/i', $s, $m);
  echo count($m[0]); //outputs 2

My initial idea was pass a regex and use preg_match to verify the match exists in a determined number of times, but I think that it's not possible, so I'll create a method that receive the word and the regex that I need match and it will return the number of matches.
Thanks.

A: using lookahead you can achieve something like that:
^(?=.*(\w)(.*\1){1}.*$)((?!\1).)*\1(((?!\1).)*\1){1}((?!\1).)*$

Where {1} is number of repeatings minus 1, so for finding if there are three repeations this would look like:
^(?=.*(\w)(.*\1){2}.*$)((?!\1).)*\1(((?!\1).)*\1){2}((?!\1).)*$

And for two or three:
^(?=.*(\w)(.*\1){1,2}.*$)((?!\1).)*\1(((?!\1).)*\1){1,2}((?!\1).)*$

etc.
The lookaheads with backreferences can be very powerful :)


text:
Q: No image is displayed : python import pylab
import skimage
from skimage import io, color
import numpy as numpy

rgb = io.imread('img.jpg')
skimage.io.imshow(img)

i am trying to display an image using skimage. On executing, neither an image is displayed nor an error is shown. Can anyone tell me where am going wrong

A: Try add skimage.io.show() to show pending images.

redpajama_set_name: RedPajamaStackExchange


text:
Q: org.mockito.exceptions.misusing.InvalidUseOfMatchersException Misplaced argument matcher I am getting the following exception
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Misplaced argument matcher detected here:

You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
    when(mock.get(anyInt())).thenReturn(null);
    doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
    verify(mock).someMethod(contains("foo"))

for the line of code
@Mock
Template templateParser = new TemplateParser();
when(templateParser.getLayoutIdsFromTemplate(any(HashMap.class)))
                           .thenReturn(Arrays.asList("id1", "id2"));

The function I am mocking is as below
public class TemplateParser {
    public List<String> getLayoutIdsFromTemplate(HashMap<String, Object> parsedTemplate)
    {
        List<String> listOfLayoutIds = new ArrayList<String>();

        //Loading listOfLayoutIds here

        return listOfLayoutIds;
    }
}

Can anyone tell me what the problem is?

A: Your mocked method getLayoutIdsFromTemplate is receiving a typed HashMap<String, Object> as parameter, not a simple HashMap. This is the cause of InvalidUseOfMatchersException.
If you can make a little refactor, you can solve it doing:
1) Change your method to receive a Map<String, Object> instead a Hashmap<String, Object>:
   public List<String> getLayoutIdsFromTemplate(Map<String, Object> parsedTemplate) {
      ...
   }

2) In your test class, match the parameter using Mockito.anyMapOf(String.class, Object.class)) instead of Mockito.any(HashMap.class)):
when(templateParser.getLayoutIdsFromTemplate(anyMapOf(String.class, Object.class))).thenReturn(Arrays.asList("id1", "id1"));

Hope it helps.


text:
Q: WiFi Drivers Not Working I just installed Linux Mint 17.3 on my mid 2012 MacBook Pro. I'm currently trying to install the necessary drivers for WiFi via Driver Manager (nvidia-331 and bcmwl-kernel-source) for my BCM4222 broadcom network card. Yet whenever I try to apply changes an error popup occurs with the message "Package dependencies cannot be resolved." and within the details this message is present:
The following packages have unmet dependencies.
nvidia-331: Depends: x11-common (>= 1:7.0.0) but 1:7.7+1ubuntu8.1 is to be installed.
Depends: xorg-video-abi-15 but it is a virtual package.
How do I fix this?


text:
Q: shopify.Order.find(id=1400) returns error? Any ideas what might be wrong? I have a shopify shop and an admin app written in django. The python api works well. However, I have not yet explored working with "order". Here is what I tried and an error I got...any idea why - and how to fix?
>>> o = shopify.Order.find(id=1402)

Error:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Python/2.7/site-packages/pyactiveresource/activeresource.py", line 351, in find
    return cls._find_every(from_=from_, **kwargs)
  File "/Library/Python/2.7/site-packages/pyactiveresource/activeresource.py", line 490, in _find_every
    prefix_options)
  File "/Library/Python/2.7/site-packages/pyactiveresource/activeresource.py", line 521, in _build_list
    resources.append(cls(element, prefix_options))
  File "/Library/Python/2.7/site-packages/shopify/base.py", line 133, in __init__
    return super(ShopifyResource, self).__init__(attributes, prefix_options)
  File "/Library/Python/2.7/site-packages/pyactiveresource/activeresource.py", line 328, in __init__
    self._update(attributes)
  File "/Library/Python/2.7/site-packages/pyactiveresource/activeresource.py", line 904, in _update
    attr = [klass(child) for child in value]
  File "/Library/Python/2.7/site-packages/shopify/base.py", line 133, in __init__
    return super(ShopifyResource, self).__init__(attributes, prefix_options)
  File "/Library/Python/2.7/site-packages/pyactiveresource/activeresource.py", line 328, in __init__
    self._update(attributes)
  File "/Library/Python/2.7/site-packages/pyactiveresource/activeresource.py", line 904, in _update
    attr = [klass(child) for child in value]
  File "/Library/Python/2.7/site-packages/shopify/base.py", line 132, in __init__
    prefix_options, attributes = self.__class__._split_options(attributes)
  File "/Library/Python/2.7/site-packages/pyactiveresource/activeresource.py", line 431, in _split_options
    for key, value in options.iteritems():
AttributeError: 'str' object has no attribute 'iteritems'

A: I figured it out - this was probably a bug in one of the older ShopifyAPI releases.
A simple

easy_install -U ShopifyAPI

fixes this for good.
Hope this helps.


text:
Q: how to display files from ftwebrequest not in html format Using ftpwebrequest to list all the files in a directory but they are coming back in html format it seems, is there any way I can just get the filenames one per line without the timestamp and all the other stuff?
Here's some code
    StreamWriter fileout = new StreamWriter(@"C:\test\output4.txt");
    FtpWebRequest ftp;
    string addr = "ftp://blah/";
    string usr = "foo";
    string pwd = "bar";
    ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(addr));
    ftp.Method = WebRequestMethods.Ftp.ListDirectory;
    ftp.Credentials = new NetworkCredential(usr, pwd);

    ftp.Method = WebRequestMethods.Ftp.ListDirectory;
    FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();

    Stream responseStream = response.GetResponseStream();
    StreamReader reader = new StreamReader(responseStream);
    fileout.WriteLine(reader.ReadToEnd());

    fileout.WriteLine("Directory List Complete, status {0}", response.StatusDescription);

I just tried printWorkingDirectory instead of listDirectory and didn't work either
sure I'll add some output btw I just tried using ftpstream and got the exact same thing.
    FileStream outputStream = new FileStream(@"C:\test\output6.txt", FileMode.Create);

    FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
    Stream ftpStream = response.GetResponseStream();
    long cl = response.ContentLength;
    int bufferSize = 2048;
    int readCount;
    byte[] buffer = new byte[bufferSize];

    readCount = ftpStream.Read(buffer, 0, bufferSize);
    while (readCount > 0)
    {

        outputStream.Write(buffer, 0, readCount);
        readCount = ftpStream.Read(buffer, 0, bufferSize);
    }

    ftpStream.Close();
    outputStream.Close();
    response.Close();

finally output
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">

<TITLE>FTP Listing of /point/download/archive/ at indexftp.barcap.com</TITLE>
<BASE HREF="ftp://foo:bar@indexftp.blah.com/test">

FTP Listing of /point/download/archive/ at indexftp.barcap.com

Parent Directory

Jul 29 2013 10:00       147280 foo1.csv
Jul 30 2013 10:04       147079 foo2.csv
Jul 31 2013 10:05       146935 foo3.csv

where foo1, foo2, foo3 are sitting on the ftp and I only want the output
foo1.csv
foo2.csv
foo3.csv


text:
Q: Azure B2C login issue When I run signupsignin user flow in Azure B2C portal to test Open ID Connect (external Azure Tenant login), received below error.
Sorry, but we're having trouble signing you in.
We track these errors automatically, but if the problem persists feel free to contact us. In the meantime, please try again.
Correlation ID: 6744ccb7-eb8d-47f6-bb0a-bcd2f84f5771
Timestamp: 2021-08-04 04:10:53Z
ConnectionTimeOut: An exception has occurred.

A: This article describes a similar error that occurs when you try to sign in to an app that's set up for Azure AD B2C

Cause: The client ID may be missing or incorrect in the Web.config file for the app.
Resolution
To fix this issue, follow these steps:

*

*Open the Web.config file for the app.

*In the Web.config file, find the app key ida:ClientId.

*Replace the value of the app key with the client ID that is provided for your app in the Azure AD B2C admin portal.

The changed part of the file resembles the following:
<appSettings>
<add key="ida:ClientId" value="**xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx**">
</appSettings>

References:

*

*troubleshooting-with-application-insights

*azure-ad-b2c-importing-in-users

A: Could be the case:
Make sure you are using the API Key and API Key Secret.
Not the ClientId and Client Secret

https://learn.microsoft.com/en-us/azure/active-directory-b2c/identity-provider-twitter?pivots=b2c-user-flow


text:
Q: Node attaches url to static directory If I have
app.get('/articles', function(req, res){
    res.render('views/public/postbycat.ejs',{id:req.params.id}); // load the index.ejs file
  })

It worked fine but with this
app.get('/articles/:id', function(req, res){
    res.render('views/public/postbycat.ejs',{id:req.params.id}); // eg /articles/12345679      })

the file is sent but instead of getting as i got in the first code 'css/style.cs', i get 'articles/css/style.cs' thereby leading to a wrong url of my image.
I have this in the server.js:
app.use(express.static(__dirname + '/public'));

How can I fix this please
Thanks

A: I'm guessing that your css include doesn't have slash at the beginning of the path.
You have something like that: css/style.css
it should be : /css/style.css


text:
Q: Using the law of large numbers to calculate an integral Let $f:[0,1]\to\mathbb{R}$ be continuous. Prove
$$
\lim_{n\to\infty}\int_0^1\int_0^1\cdots\int_0^1f\left((x_1x_2\cdots x_n)^{1/n}\right)dx_1dx_2\cdots dx_n = f\left(\frac1e\right)
$$
My idea so far is to use uniform distributions to calculate this. Let $X_1,X_2,\dots$ be independent Uniform$(0,1)$ variables. My idea is to somehow use that this integral is equal to
$$
\lim_{n\to\infty}\mathbb{E}\left((X_1X_2\cdots X_n)^{1/n}\right).
$$
I think I can somehow use the fact that $\frac1n\sum_{i=1}^n\log X_i\overset{a.s.}{\to}\mathbb{E}\log X_i=-1$.
I think I have some of the ideas, but my question is how can I actually put together these ideas in a rigorous way prove this? Do I need the full power of the SLLN, or would I somehow be able to just use the WLLN? I also think maybe I will have to use the dominated convergence theorem, but I'm not sure. I'm struggling with self doubt on this question. Any help appreciated!

A: WLLN is sufficient but SLLN might be easier to think about.
You have that $\frac{1}{n} \sum_{i=1}^n \log X_i \to -1$ in probability.  By the continuous mapping theorem for convergence in probability, this implies $$(X_1 \dots X_n)^{1/n} = \exp\left(\frac{1}{n} \sum_{i=1}^n \log X_i\right) \to \exp(-1) = 1/e$$ in probability, and likewise, $f((X_1 \dots X_n)^{1/n}) \to f(1/e)$ in probability.  Now $f$ is bounded, and the dominated convergence theorem is valid for convergence in probability, so we do indeed get $\mathbb{E}[f((X_1 \dots X_n)^{1/n})] \to f(1/e)$.
If you use the strong law instead, then you don't have to think about the continuous mapping theorem, and you can use the more familiar version of the dominated convergence theorem.


text:
Q: Can't run Google apps script, error 401: disabled_client I have a Google Sheets document that has a script attached to it and this AppScript includes a function that runs on a trigger every hour. The script fills in the sheet with importrange-formulas to get data from other sheets. It's been running fine for 6 months, but today I got an error.
The scheduled script has stopped running. When I try to manually run the function I get authorization request, and when I try to grant the script permission to run I get "Error 401: disabled_client".
I have similar scripts running in  other Google Sheets document on similar trigger settings, and those keep running just fine. All the scripts are running on the same enterprise account.
Any ideas what can be going on here?
Grateful for any help to solve this.


text:
Q: Double quotes in PHP I don't know PHP at all, so I am struggling through this. I need to add an or section to a MySQL query, but the values I'm searching have double quotes. I need to figure out how to add them in PHP so they are passed in to MySQL. The current query looks like:
$query = 'SELECT * FROM ' .$tableName.' WHERE allowed_countries LIKE "%'.$regionId.'%" and skurules  REGEXP "i:'.$secondlastdigit.';" and status = 1 ORDER BY id DESC LIMIT 1';

But I need to add an or statement to search for string values that looks like:
$query = 'SELECT * FROM ' .$tableName.' WHERE allowed_countries LIKE "%'.$regionId.'%" and skurules  REGEXP "i:'.$secondlastdigit.';" or skurules  REGEXP "s:1:'.$secondlastdigit.';" and status = 1 ORDER BY id DESC LIMIT 1';

with double quotes surrounding the second instance of '.$secondlastdigit.'; when passed into MySQL.
My JSON string I'm searching looks like this:
a:12:{i:1;s:2:"15";i:2;s:2:"10";i:3;s:2:"30";i:4;s:2:"50";i:5;s:3:"120";i:6;s:3:"240";i:7;s:3:"480";i:8;s:3:"960";i:9;s:4:"3786";s:1:"A";s:3:"100";s:1:"C";s:2:"60";s:1:"B";s:5:"18930";}

A: First of all: DON'T.
If you still want to, then...REALLY DO NOT.
Making SQL queries on serialized arrays is just hell. You should try to avoid it at all costs.
Either:

*

*Convert the serialized column into a standard SQL table

*or select the column into a PHP variable, unserialize it and search through it.

Example:
$properPhpArray = unserialize($sqlResult['column_name']);

A: Agreed, searching serialized string is not the best solution and what the developer did despite having a bottle_size table available. I needed a quick fix and no time/skill to rewrite a tax calculation magento extension so I used replace in the query to solve my problem for now.
Since "s:1:X" will always be just one alpha character after the 1 and will not match anything else. I change the query to:
$query = 'SELECT * FROM ' .$tableName.' WHERE allowed_countries LIKE "%'.$regionId.'%" and skurules  REGEXP "i:'.$secondlastdigit.';" or replace(skurules,char(34),0)  REGEXP "s:1:0'.$secondlastdigit.'0;" and status = 1 ORDER BY id DESC LIMIT 1';
Very hackish fix but gets me out of a bind for now..
Mark


text:
Q: Downloading files in a webpage I need to make the user able to download a file from my webpage on clicking a link on my website
I tried     Download file
By it just opened a new window and i need to right click  and select "save page as"
What I am expected is ,after clicking my link user must see a dialogue box "save as" as usual...How to do it..Is there any way in HTML to force download by showing such a dialogue
Note:Since stackoverflow is not allowing anchor tag,i just typed it as a.Please do not treat it as a mistake

A: If you're using an Apache web server, you can use the .htaccess file to force file download for certain file extensions.  Add this line to your .htaccess to cause the "Save As" dialog to appear when the link is clicked:
AddType application/octet-stream .ext

If you wanted the same behaviour for a PDF or AVI, the following lines would do it:
AddType application/octet-stream .pdf
AddType application/octet-stream .avi

A: You can use php to readfile() the file to the user.
this tutorial would be helpful for you :
http://webdesign.about.com/od/php/ht/force_download.htm

A: I know it is lame, but I found a solution here


text:
Q: npm install locally In the past when I installed packages using npm(>=1.0) they would be installed locally, but not  anymore.
My setup:

*

*First I use nvm to install node.js.

*My operating System:
alfred@alfred-laptop:~/node/so/6513101$ cat /etc/lsb-release
DISTRIB_ID=Ubuntu<br>
DISTRIB_RELEASE=10.10
DISTRIB_CODENAME=maverick
DISTRIB_DESCRIPTION="Ubuntu 10.10"

*My node version:
alfred@alfred-laptop:~/node/so/6513101$ node -v
v0.4.8

*My npm version:
alfred@alfred-laptop:~/node/so/6513101$ npm -v
1.0.15

Installing random package
alfred@alfred-laptop:~/node/so/6513101$ npm install notifo
notifo@0.0.2 ../../../node_modules/notifo

In the past it would install into the same directory but it does not install in the same directory anymore. is my npm/node.js broken or am I missing something or does npm not anymore install local packages(inside same folder => ~/node/so/6513101/node_modules)  which I thought was a cool feature because I could bundle all my dependencies so that other users did not have to install npm to use my code(I still believe users should install npm because it is a great product). The bundle command is gone so I can't use that? Could someone please explain to me what is going on?

A: npm walks up the folder tree until it finds a node_modules or a package.json and uses that as the root.  What does npm root print out?
If you mkdir node_modules or create a package.json file, then it'll use the cwd.
EDIT: I won't see updates you post here.  For better results, just post everything in the github issue, and let's do the support over there.


text:
Q: Insert Form Textbox value into next free cell So I'm very new to VBA in excel, and I'm using it to communicate with an MySQL db to populate a budgeting sheet.
I've built a very simple form which fetch's the data, like this:

This form will be used to fetch the desired product and then print its specs into the worksheet, like this:

As you can see, I get the data from the MySQL into the ListView and then the selected row into 2 TextBoxs. But the 2 values are not printing in the right locations as its obvious in the picture. I'm using the following code:
Private Sub Print_Values_Click()

If Select_prod.Value = "" Or Select_quant.Value = "" Then
If MsgBox("Form is not complete. Do you wan to continue?", vbQuestion + vbYesNo) <> vbYes Then
Exit Sub
End If
End If

Dim LastRow As Long

With ThisWorkbook.Sheets("Folha1")

Range("A" & Rows.Count).End(xlUp).Offset(1, 0).Value = Select_prod.Value
Range("B" & Rows.Count).End(xlUp).Offset(0, 1).Value = Select_quant.Value

End With
End Sub

So, not only is not printing the values where it should, its creating a new column (its supposed to be only 2) and prints in the same spot every time (overwrites the existent values and do not go to the next empty cell/row).
What is wrong in my code?

A: The issue is that Range("A" & Rows.Count).End(xlUp) doesn't find the last used row correctly because you use formatted tables (ListObjects). If you want to find the next free row in a formatted table you need to do it like this:
With ThisWorkbook.Sheets("Folha1")
    With .ListObjects("Table1") 'make sure to adjust the table name here
        Dim NextFreeRow As Long
        NextFreeRow = .DataBodyRange(.DataBodyRange.Rows.Count, 1).End(xlUp).Row + 1
    End With

    .Cells(NextFreeRow, "A").Value = Select_prod.Value
    .Cells(NextFreeRow, "B").Value = Select_quant.Value
End With

Explanation why your approach did not work
If you use this technique Range("A" & Rows.Count).End(xlUp) on a worksheet with ListObjects it will not find the last used row (of data) but always the last row of the ListObject.


text:
Q: Run two scripts from package.json My package.json:
  "scripts": {
    "dev": "cross-env NODE_ENV=development nodemon src $NODE_DEBUG_OPTION --exec babel-node",
    "build": "babel src -s -D -d dist",
    "tsc:w": "tsc -w"
  }

I have to run two commands:
npm run dev

And
npm run tsc:w

Is it possible to include the typescript watcher in the dev?

A: You can use pre and post scripts that will run before and after your intended script.
This should run tsc on .ts files, and then browserify on the compiled .js files:
"scripts": {
    "prebuild": "tsc",
    "build": "browserify dev/main.js -o docs/js/main.js"
}

In terminal:
npm run build


text:
Q: wpf nested foreach index array out of bounds i created 2 foreach loop and i am getting error ( index outside of bounds of array ) , because i use 2 arrays .
This is what i do :
using (StreamReader reader = File.OpenText(@"C:\Users\apr13mpsip\Documents\Visual Studio 2010\Projects\iStellarMobile\iStellarMobile\Puzzle\educational.txt"))
{
    string line;

    while ((line = reader.ReadLine()) != null) // read line by line.
    {
        column = line.Split(new string[] { "," }, StringSplitOptions.None);
        rowcol = column;
    }

    int  i = 0;
    int  j = 0;

    foreach (string r in rowcol)
    {
        foreach (string c in column)
        {
            var currentValue = rowcol[i][j];
            j++;
        }
        i++;
    }
}

i have already global string[] column; and string[] rowcol;
Error happens in this line :

var currentValue = rowcol[i][j];

-------EDIT--------------------
This is how my textfile looks like :

From Tim's answer , rowcol[0][0] will print h and , rowcol[0][1] will print E , but the first [] of rowcol is null , whenever is more than 0 , it gives me an null error , Object not set to reference .

A: I would suggest using a jagged array, that way if you encounter a situation where you have more than 10 columns in a line it won't throw an out of bound error.
I'd also recommend using File.ReadAllLines as that will return an array of all the lines in the file.
Something like this (not tested) should get you going:
string[] fileData = File.ReadAllLines(@"C:\Users\apr13mpsip\Documents\Visual Studio 2010\Projects\iStellarMobile\iStellarMobile\Puzzle\educational.txt");

string[] lineValues;

int row = 0;
int col;

string[][] rowcol = new string[fileData.Length][];

foreach (string line in fileData)
{
    lineValues = line.Split(new string[]{ ',' }, StringSplitOptions.None);

    rowcol[row] = new string[lineValues.Length];

    col = 0;

    foreach (string value in splits)
    {
        rowcol[row][col] = value;
        col++
    }

    row++;
}

What this code does is as follows:

1.  Populates the array `fileData` with the lines from the text file.
2.  Sets up an array to hold the split result on each line.
3.  Declares variables for row and col, and sets row to 0.
4.  Sets the first dimension of the jagged array `rowcol` to the length of the array of lines returned from `ReadAllLines` (i.e., the number of rows).
5.  Loop through each line in `fileData`, doing the following:
    a.  split the current line on ',' and put the results in `lineValues`.
    b.  Set the second array of `rowcol` for the current row equal to the length
        of the array `lineValues` (number of columns).
    c.  Set the `col` variable to 0 (first column).
    d.  Loop through each value in `lineValues`, assigning the current value to
        the proper column for the current row, and then increment the column counter.
6.  Once the inner loop is done, increment the row counter.

Edit
rowcol is a jagged array (an array of arrays), which basically means you have an array where each element is another array reference. Each of these array references can (but don't have to) have different lengths (in your case they don't).
string rowcol[][] = new string[fileData.Length][];

This initializes the jagged array rowcol to a length equal to the number of lines in your file (10). You now have 10 elements in the array, but they are all null.
rowcol[row] = new string[lineValues.Length];

This initializes the array reference for the current element (row) to equal the length (number) of values from the split.  Continuing with your example, you know have "x" elements (the number of values from the split) in the array at element "row", but they are null.
rowcol[row][col] = value;

You know have a value (string) that you can access.
So if you are in the inner loop, and you have code that will print the value of rowcol[0][0] and rowcol[1][0], after the first time through the inner loop you'll have a value in rowcol[0][0], but you won't in rowcol[1][0] because you haven't gotten to row 1 yet, you're still on row 0.
I tested this in a console app, and used the following snippet to print the values of the jagged array after the outer loop had finished:
for (int i = 0; i < rowcol.GetLength(0); i++)
{
    for (int j = 0; j < rowcol[i].GetLength(0); j++)
    {
        Console.WriteLine("Row {0}, Col {1}: {2}", i, j, rowcol[i][j]);
    }
}

This results in the following output (whole output is not shown, just enough to give the general idea):

Row 0, Col 0: h
Row 0, Col 1: e
Row 0, Col 2: l
Row 0, Col 3: l
Row 0, Col 4: o
Row 0, Col 5:
Row 0, Col 6:
Row 0, Col 7:
Row 0, Col 8:
Row 0, Col 9:
Row 1, Col 0: o
Row 1, Col 1:
Row 1, Col 2:
Row 1, Col 3:
Row 1, Col 4:
Row 1, Col 5:
Row 1, Col 6:
Row 1, Col 7:
Row 1, Col 8:
Row 1, Col 9:
Row 2, Col 0: l
Row 2, Col 1: i
Row 2, Col 2: v
Row 2, Col 3: e
Row 2, Col 4:
Row 2, Col 5:
Row 2, Col 6:
Row 2, Col 7:
Row 2, Col 8:
Row 2, Col 9:
....
Row 9, Col 0:
Row 9, Col 1:
Row 9, Col 2:
Row 9, Col 3: d
Row 9, Col 4:
Row 9, Col 5:
Row 9, Col 6:
Row 9, Col 7:
Row 9, Col 8:
Row 9, Col 9:


text:
Q: Why does wcwidth return -1 with a sign that I can print on the terminal? Why does here wcwidth return "-1" (not a printable wide character) width "Ԥ" (0x0524)?
#include <stdio.h>
#include <wchar.h>
#include <locale.h>

int wcwidth(wchar_t wc);

int main()
{
    setlocale(LC_CTYPE, "");

    wchar_t wc1 = L'合'; // 0x5408
    int width1 = wcwidth(wc1);
    printf("%lc - print width: %i\n", wc1, width1);

    wchar_t wc2 = L'Ԥ'; // 0x0524
    int width2 = wcwidth(wc2);
    printf("%lc - print width: %i\n", wc2, width2);

    return 0;
}

Output:

合 - print width: 2
Ԥ - print width: -1

A: Most likely U+0524 was not a valid character when your libc character database was created. It was added in Unicode 5.2. Your font may include the character already, but wcwidth does not look at which font is used.


text:
Q: How do I use the same Wistia video multiple times? I've been able to embed a wistia video on to a page of mine, but now I'm confused about how I could use multiple instances of the same video.
Like, for example, if I wanted to have a second version of the video that doesn't autoplay like video1 has been assigned to do below.
window._wq = window._wq || [];
_wq.push({ "hashedidhere": function(video) {
  video1 = Wistia.api("hashedidhere");
  video1.play();
}});

Can anyone give me some insight?
edit: To further illustrate my question, I want to do something like this...
window._wq = window._wq || [];
_wq.push({ "hashedidhere": function(video) {
video1 = Wistia.api("hashedidhere");
video2 = Wistia.api("thesamehashedidhere");
video1.play();
video2.someotherfunction();
}});

A: Good question! You can pull that off without writing any JS, but instead by including the autoPlay=true embed option in the class name of the video container:


text:
Q: Is it possible to re-present the camera after taking a picture and selecting "Use" with ImagePickerController? After taking a picture using the ImagePickerController and selecting "Use", I want the camera screen to appear again to continue taking more shots, how do I achieve this so I can keep taking shots without stopping? I am not using AVFoundation but ImagePickerController.

A: If you set showsCameraControls of your UIImagePickerController to NO and provide your own camera controls you can take multiple pictures after each other and dismiss the interface when you see fit.


text:
Q: Finding the number of values from users not in a 2D array I want to have a function that looks at an array of users and gets the total number of 1's from users not in that array. The default is Group1 so I want to count all of the Group1 1's and all the 1's from users not in the list at all. My formula so far is =SUMPRODUCT(NOT(ISNUMBER(MATCH(D11:D19,G11:H14,0)))*(A11:C19=1))
The match function doesn't seem to work when I have a 2D array as a parameter though. For the example below, the output should be 6.

A: Match does not work with two Dimensional Arrays.
Use COUNTIF instead:
=SUMPRODUCT((COUNTIF(G11:H14,D11:D19)=0)*(A11:C19=1))


text:
Q: Change input value and add cursor at the end of input I change input value and don't want to blur and focus again on input to make the cursor at the end tried other ways but didn't work
thisEl.val("0"+thisEl.val()+"/");

A: You can use the inbuilt focus() method to bring focus to an element. Details can be found here: mdn link.
Example on jsfiddle: https://jsfiddle.net/oao0kw36/
thisEl.val("0"+thisEl.val()+"/").focus();


text:
Q: Multiplicity of indecomposable stable summands of $BG^{\wedge}_p$ I am reading the article Homotopy stable classification of $BG^{\wedge}_p$ by Martino-Priddy. Let $P_u$, $P_v$ be $p$-subgroups of a finite group $G$, such that $P_u\leq x^{-1}P_v x$ for some $x\in G$, if  $X$ is a common indecomposable stable summand of $BP_u$ and $BP_v$, $\iota: X\rightarrow BP_u$ is an inclusion map of $X$ as a summand of $BP_u$, the proof of proposition 3.2 part b) seems to say implicitly that the composite
$$X\xrightarrow{\iota} BP_u\xrightarrow{Bi\circ Bc_x} BP_v$$ is an inclusion map of X as a summand of $BP_v$. Is it true?.
P.D: All objects here are $p$-completed spectra, $X$ is also a summand of $BG$.

A: Here is a counterexample: Let $P_u = C_2$, $P_v = G = C_4 \times C_2$, and $i: C_2 \rightarrow C_4 \times C_2$ inclusion into the $C_4$ summand.  Let $X = BC_2$, obviously a stable summand in both $BC_2$ (!) and $B(C_4 \times C_2)$.  However, $X=BC_2 \xrightarrow{Bi} B(C_4 \times C_2)$ does not have a left inverse, since if it did, then $BC_2$ would be a summand in $BC_4$.  But it is not.


text:
Q: Which one is the correct form of reported speech for the following sentence? Which one is the correct form of reported speech for the following sentence? why?
"When were you born?", he asked him.
=>

1- He asked him when he had been born.
  2- He asked him when he was born.

A: The first version is correct.  The second version sounds fine (to my native ear), probably because being born is not a repeated event, so the grammatical distinction between the time of the event and the time of asking is unambiguous.

*

*"When did you eat?" he asked him.  => He asked him when he had eaten.

*"When did you get married?" he asked him. => He asked him when he had gotten married. / He asked him when he got married.  (Both sound okay.)


text:
Q: How to set div using Z-index and fix css Area of concern -

*

*My Blue Div is overlapping over the green div. (I want to have a
green Div then at the side Blue Div)

*On Mouseover loaded content is making the blue div to fall down
however im trying to set "mydatatoshow" div to be over
"rightsideblock" using jquery z-index property.

Kindly have a look at it and let me know the possible solution.
My Working code ---
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>Test To Test</title>

Monday 07 July 2012

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Friday 06 July 2012 8:00AM

Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

    This is right sidebar data.This is right sidebar data.This is right sidebar data.This is right sidebar data.This is right sidebar data.This is right sidebar data.This is right    sidebar data.This is right sidebar data.This is right sidebar data.This is right sidebar data.This is right sidebar data.This is right sidebar data.This is right sidebar data.

A: z-index only works if you specify a type of position.

A: try this

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<title>Test To Test</title>

                        Monday 07 July 2012

                            Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

                    Friday 06 July 2012 8:00AM

                        Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

                This is right sidebar data.This is right sidebar data.This is right sidebar data.This is right sidebar data.This is right sidebar data.This is right sidebar data.This is right    sidebar data.This is right sidebar data.This is right sidebar data.This is right sidebar data.This is right sidebar data.This is right sidebar data.This is right sidebar data.

                    Friday 06 July 2012 8:00AM

                        Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.


text:
Q: Create thumbnails of images and store them in cache I have a WPF application that has a list box of images. Right now I am using  BitmapImage and BitmapCacheOption.OnLoad to load the images.
The problem is that when there are a lot of images, the RAM usage sky rockets due to the size of the images.
How can I create thumbnail images of the originals to display in the list box?
It probably has to be cached since the image files in the directory may be deleted or modified while the application is running.

A:
The problem is that when there are a lot of images, the RAM usage sky rockets due to the size of the images.

C# example from: http://msdn.microsoft.com/en-us/library/ms748873.aspx
// Create source
BitmapImage myBitmapImage = new BitmapImage();

// BitmapImage.UriSource must be in a BeginInit/EndInit block
myBitmapImage.BeginInit();
myBitmapImage.UriSource = new Uri(@"C:\Water Lilies.jpg");

// To save significant application memory, set the DecodePixelWidth or
// DecodePixelHeight of the BitmapImage value of the image source to the desired
// height or width of the rendered image. If you don't do this, the application will
// cache the image as though it were rendered as its normal size rather then just
// the size that is displayed.
// Note: In order to preserve aspect ratio, set DecodePixelWidth
// or DecodePixelHeight but not both.
myBitmapImage.DecodePixelWidth = 200;
myBitmapImage.EndInit();
//
//when you are ready to render the BitmapImage, do:
imageThumb.Source = myBitmapImage;

Note the DecodePixelWidth and DecodePixelHeight properties to cache the image at the desired reduced pixel size. Use both to stretch the image to fit the thumbnail size.

A: You can create decent thumb bitmaps using InterpolationMode.HighQualityBicubic
   Bitmap bitmap = ...
   Bitmap thumbBitmap = new System.Drawing.Bitmap(thumbWidth, thumbHeight);
   using (Graphics g = Graphics.FromImage(thumbBitmap))
   {
      g.InterpolationMode = InterpolationMode.HighQualityBicubic;
      g.DrawImage(bitmap, 0, 0, thumbWidth, thumbHeight);
   }

If you are creating the thumbs in a background thread just save them into a memory stream which you can then lazily use to create the BitmapImage when requested:
   _ms = new MemoryStream();
   thumbBitmap.Save(_ms, ImageFormat.Png);
   _ms.Position = 0;
   ImageLoaded = true;

    //thumb image property of this class, use in binding
    public BitmapImage ThumbImage
    {
        get
        {
            if (_thumbImage == null && ImageLoaded)
            {
                BitmapImage bi = new BitmapImage();
                bi.BeginInit();
                bi.StreamSource = _ms;
                bi.EndInit();
                _thumbImage = bi;
            }
            return _thumbImage;
        }
    }

A: Here is a method I wrote not too long ago that may help you.
byte[] IImageResizer.CreateThumbnailBytes(byte[] originalImage)
    {
        Image thumbnail = null;

        Image tempImage = Image.FromStream(new MemoryStream(originalImage));

        int desiredWidth = 160;

        int newPixelWidth = tempImage.Width;
        int newPixelHeight = tempImage.Height;

        if (newPixelWidth > desiredWidth)
        {
            float resizePercent = ((float)desiredWidth / (float)tempImage.Width);

            newPixelWidth = (int)(tempImage.Width * resizePercent) + 1;
            newPixelHeight = (int)(tempImage.Height * resizePercent) + 1;
        }

        Bitmap bitmap = new Bitmap(newPixelWidth, newPixelHeight);

        using (Graphics graphics = Graphics.FromImage((Image)bitmap))
        {
            graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            graphics.DrawImage(tempImage, 0, 0, newPixelWidth, newPixelHeight);
        }

        thumbnail = (Image)bitmap;

        MemoryStream ms = new MemoryStream();
        thumbnail.Save(ms, ImageFormat.Jpeg);

        return ms.ToArray();
    }

I pass in the original images binary, and resize the image to be around roughly 160px.
Hope it helps!

A: After checking MSDN I don't see any straightforward way to do this, but perhaps you could just sample the image every so many pixels and write the data to a new image, and then clean up the full size one.


text:
Q: Is memory managed on the newest iPhones? I'm getting into iOS and coming with an Android background.  Will I have to manually allocate and remove memory in Objective C?  I'm getting conflicting answers from blog posts...  How does ARC fit in to this?

A: Yes it is, ARC is the garbage collection system in iOS that checks for nil references and then auto deallocates the objects for you. You still have to manually allocate objects yourself.


text:
Q: Burger Menu does not open Hello my Burger Menu does not open when i resize the browser. I tried many different thinks and nothing worked. Also theres a weird second right after you resize the window where the menu opens for a split second
Error : Uncaught TypeError: Cannot read property 'toggle' of undefined at HTMLDivElement.burger.addEventListener

  const navSlide = () => {
  const burger = document.querySelector('.burger');
  const nav = document.querySelector('.navul');

  burger.addEventListener('click', () => {
    nav.classlist.toggle('nav-active');
  });
}

navSlide();
nav {
     display: flex;
     justify-content: space-around;
     align-items: center;
     min-height: 8vh;
     background-color: red;
     font-family: 'Poppins', sans-serif;
     font-weight: 400;
}
 .logo {
     color: white;
     letter-spacing: 6px;
     text-transform: uppercase;
     font-size: 20px;
}
 .navul {
     display: flex;
     width: 45%;
     color: white;
     list-style: none;
     justify-content: space-around;
}
 .navul a {
     text-decoration: none;
     color: white;
     letter-spacing: 2px;
     font-size: 14px;
}
 .burger {
     display: none;
     cursor: pointer;
}
 .burger div {
     width: 25px;
     height: 3px;
     color: white;
     margin: 5px;
     background-color: white;
}
 @media screen and (max-width:768px){
     body{
         overflow-x: hidden;
    }
     .navul {
         position: absolute;
         right: 0px;
         height: 92vh;
         top: 8vh;
         background-color: red;
         display: flex;
         flex-direction: column;
         align-items: center;
         width: 50%;
         transform: translateX(100%);
         transition: transform 0.5s ease-in;
    }
     .navul li {
         opacity: 0;
    }
     .burger {
         display: block;
    }
}
 .nav-active {
     transform: translateX(0%);
}

Spieker Manufaktur

Home

Über Uns

Produkte

Herstellung


text:
Q: Scala: accessing java primitives done directly or via a wrapper? I know that you can access java primitives directly from Scala
val javaDouble = new java.lang.Double(1.0)

Does this mean that we are accessing the primitives via a wrapper or directly? The syntax new java.lang.Double(1.0) looks like creating a new object, hence there is a wrapper which gives us the access to java primitives. If this is true, I wonder how much extra memory footprint and computation does it cost.

A: You say "I know you can access Java primitives directly" and then follow immediately with an example of not a Java primitive but the Java class used to box a primitive.
Scala can access unboxed primitives--the length method on strings, for instance:
scala> val l = "fish".length
l: Int = 4

This is a just plain Int (int in Java).  No boxing in sight.
Scala can also access Java's version of boxed primitives.
scala> val boxed = new java.lang.Integer(2)
boxed: Integer = 2

scala> val isJavaObject = boxed.isInstanceOf[Object]
isJavaObject: Boolean = true

When using generics, primitives are transparently boxed and unboxed as needed (similar to how it works in Java, but a bit more comprehensively).  It keeps track of whether you expect a primitive or not, so it looks like everything "just works".
scala> def ident[A](a: A): A = a
ident: [A](a: A)A

scala> def lAgain = ident(l)
lAgain: Int

scala> def boxedAgain = ident(boxed)
boxedAgain: Integer

However, if you start pattern matching, you will find that the illusion is only skin-deep: Int is boxed to java.lang.Integer in a variety of contexts (generics or a cast to Any) because that is a JVM requirement.
scala> def isInt(a: Any) = a match { case i: Int => true; case _ => false }
isInt: (a: Any)Boolean

scala> val test = (isInt(l), isInt(boxed))
test: (Boolean, Boolean) = (true,true)

scala> def isBoxedInt(a: Any) = a match { case _: java.lang.Integer => true; case _ => false }
isBoxedInt: (a: Any)Boolean

scala> val test2 = (isBoxedInt(l), isBoxedInt(boxed))
test2: (Boolean, Boolean) = (true,true)

So, as long as the compiler knows the right type, it uses primitives as primitives whenever possible, and boxes them transparently whenever not.  If you lose track of the type and use pattern matching to try to figure out what's there, it will pull out whichever version you ask for.  (When it needs to do so automatically, e.g. with equality, it will assume a boxed primitive is supposed to act like a primitive.)

A:
Does this mean that we are accessing the primitives via a wrapper or directly

In your example, Scala will internally create an object of class type java.lang.Double which is a subtype of AnyRef (the root class of all reference types in Scala). There are no primitives in Scala. Everything is an object.
This can be proved:
val javaDouble = new java.lang.Double(1.0)
val x: AnyRef = "hi"
val y: AnyVal = 2 // AnyVal is the root class of all primitive types
typeOf(javaDouble) <:< typeOf(x)  // true
typeOf(javaDouble) <:< typeOf(y)  // false


text:
Q: Does javadoc support other comment styles? I have been working in a C++ project that uses doxygen to generate documentation output.  The method of documentation we use looks like this:
//! This is an awesome method.  You should totally use this method for all sorts
//! of cool stuff that you might want to do.
//! @returns something useful
string my_awesome_method() {...}

As you can see, we use the //! comment prefix to indicate a doxygen comment block.  We have found that this works very well for our needs.
Now we are adding a Java component and would like to maintain consistency with the commenting style that we have used in C++ rather than move to the, what we consider to be awkward, /** */ style used by javadocs.  Is there a way to get javadocs to recognize other prefixes like doxygen does?  Or does javadocs require the use of /** */?  We could just use doxygen, but there are all sorts of niceties that are built around javadocs such that we would like to maintain the interface with this ecosystem.
Is this possible?  I'm afraid that the answer is probably no.  :(

A: Yes, /** */ is the only comment format recognized by javadoc. See http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html#format.


text:
Q: infinite ring with non-zero finite characteristic For every natural number n, i have to give a finite and a infinite ring with characteristic n.
For the finite case is it simple: for all n $\in\mathbb{N}$, the ring $\mathbb{Z}_n$ is a finite ring with characteristic n.
But in the infinite case i can't think of a ring...
The only infinite ring with a finite characteristic that is not 0, is the ring of all subsets of a infinite set X. With the operations of symmetric difference and intersection. Here is the characteristic equal to 2.

A: $A_n:= \prod \mathbb Z/n\mathbb Z$ (infinite product, fixed $n$). This is an infinite ring with characteristic $n.$

A: Consider the ring $\Bbb Z_n[x]$ of polynomials in one variable $x$ with coefficients in $\Bbb Z_n$, where $n$ is prime.  It is an infinite ring since $x^m \in \Bbb Z_n[x]$ for all positive integers $m$, and $x^{m_1} \ne x^{m_2}$ for $m_1 \ne m_2$.  But the charactetistic of $\Bbb Z_n[z]$ is clearly $n$.


text:
Q: how can i change date format for joomla to d/m/Y? I tried to change the date format of Joomla 3 DB table after several attempts like this
echo date_format("end_date", "%d/%m/%Y");
echo $result->format('$result->end_date', 'd-m-Y');

// also tried to get kind of result March 10, 2001, 5:16 pm
echo date_format("end_date", "F j, Y, g:i a");
echo date_format("$result->end_date", "F j, Y, g:i a");
echo date_format('$result->end_date', 'F j, Y, g:i a');
echo date_format({$result->end_date}, 'F j, Y, g:i a');
echo date($result->end_date}, 'F j, Y, g:i a');
echo date('$result->end_date', 'F j, Y, g:i a');
echo "<time datetime='$result->end_date'>"  "</time>";

, checked all relative posts on stack overflow for the similar type of code, all lessons, and examples but couldn't change this end_date format to d/m/Y
<?php
    $db = JFactory::getDbo();
    $query = $db->getQuery(true);
    $select = array(
        $db->quoteName('title'),
        $db->quoteName('id'),
        $db->quoteName('start_date'),
        $db->quoteName('end_date')
    );
    $query->select(array($select));
    $query->from($db->quoteName('#__rbid_auctions'));
    $query->order($db->quoteName('id') . " DESC");
    $query->setLimit(3);
    $db->setQuery($query);
    $results = $db->loadObjectList();

    // display the results
    foreach ( $results as $result) {
        echo "id}\">{$result->title} . ";
        echo "
" . $result->start_date . "
";
        echo "
" . $result->end_date . "
";
    }
?>

Thanks in advance

A: try using the following:
// instantiate a new Joomla Date Object
$date = new JDate($result->start_date);

// echo the formatted date
echo $date->format('F j, Y, g:i a');

Hope it helps,
Gez


text:
Q: Refresh Layout and update data I have the following pyqt code that displays a grid of data.
I am able to click on a letter, open a text input box and successfully save the data to the grid and print the updated data in the terminal.
I have tried update() and repaint() but they do nothing aand calling the createLayout() method throws an error of QLayout: Attempting to add QLayout "" to Widget "", which already has a layout
How can I refresh the grid/widget/layout to display the new data?
from PyQt5 import QtWidgets, QtCore, QtGui
import string

grid = [[["text", "GREEN"], 0, ["text", "RED"], 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0]]

BTN = """QPushButton{{font-weight: bold; color: {};
        font-size: 14px; background-color: {};
        border-width: 2px; border-radius: 100px}}"""

class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)

        self.letter_count = dict(zip(string.ascii_uppercase, [x for x in range(26)]))

        self.initUI()
        self.createLayout()
        self.center_widget()

    def initUI(self):
        p = self.palette()
        gradient = QtGui.QLinearGradient(0, 0, 0, 400)
        gradient.setColorAt(0.0, QtGui.QColor('#f1f1f1'))
        gradient.setColorAt(1.0, QtGui.QColor('#00a1de'))
        p.setBrush(QtGui.QPalette.Window, QtGui.QBrush(gradient))
        self.setPalette(p)

    def createLayout(self):
        hlay = QtWidgets.QHBoxLayout(self)
        frameL = QtWidgets.QFrame()

        vlay = QtWidgets.QVBoxLayout(frameL)
        frame = QtWidgets.QFrame()
        frame.setObjectName("principal")
        frame.setStyleSheet("#principal{border: 2px solid white;}")
        hlay.addWidget(frameL)
        hlay.addWidget(frame)

        gridLayout = QtWidgets.QGridLayout(frame)

        h = 60  # height

        for i, row in enumerate(grid):
            letter = "{}".format(string.ascii_uppercase[i])
            frameButton = QtWidgets.QFrame()
            frameButton.setFixedHeight(h)
            frameButton.setContentsMargins(0, 0, 0, 0)
            lay = QtWidgets.QVBoxLayout(frameButton)
            button = QtWidgets.QPushButton(letter)
            button.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
            button.clicked.connect(lambda x, letter=letter: self.populate_row(letter)) # Every button click returns 'J'
            lay.addWidget(button)
            vlay.addWidget(frameButton)
            for j, val in enumerate(row):
                gridButton = QtWidgets.QPushButton()
                gridButton.setFixedSize(h, h)
                if isinstance(val, list):
                    gridButton.setText(val[0])
                    if val[1] == "GREEN":
                        gridButton.setStyleSheet(BTN.format('white', 'green'))
                    elif val[1] == "RED":
                        gridButton.setStyleSheet(BTN.format('white', 'red'))
                else:
                    gridButton.setStyleSheet(BTN.format('black', 'white'))
                    gridButton.setText("{}".format(val))
                gridLayout.addWidget(gridButton, i, j)

        for ix in range(j + 1):
            label = QtWidgets.QLabel("{}".format(ix + 1))
            label.setAlignment(QtCore.Qt.AlignCenter)
            gridLayout.addWidget(label, i + 1, ix)
        vlay.addWidget(QtWidgets.QLabel())

    def center_widget(self):
        self.window().setGeometry(
            QtWidgets.QStyle.alignedRect(
                QtCore.Qt.LeftToRight,
                QtCore.Qt.AlignCenter,
                self.window().size(),
                QtWidgets.QApplication.desktop().availableGeometry())
        )

    def populate_row(self, letter):
        """ Populate the row from index 0 - end """
        print(letter)
        self.wi = QtWidgets.QWidget()
        self.wi.resize(660, 360)
        textBox = QtWidgets.QPlainTextEdit(self.wi)
        Rbtn = QtWidgets.QPushButton('Add To Row')
        Rbtn.clicked.connect(lambda: self.input_to_grid(textBox.toPlainText(), letter))

        layout = QtWidgets.QVBoxLayout()
        layout.addWidget(textBox)
        layout.addWidget(Rbtn)

        Rbtn.move(600, 300)

        self.wi.setLayout(layout)

        self.wi.show()
        return self.wi

    def input_to_grid(self, text, letter):
        print(text, letter)
        lst = text.split(' ')
        for i, x in enumerate(lst):
            self.add_to_grid((letter, i + 1), x)
            print((letter, i + 1), x)
        self.print_grid()

    def add_to_grid(self, loc, item):
        x, y = self.translate(loc)
        grid[x][y] = [item]

    def translate(self, loc):
        for k, v in self.letter_count.items():
            if loc[0].upper() == k:
                x = v
        y = int(loc[1]) - 1
        return x, y

    def print_grid(self):
        """ Print the grid prettier than normal.. """
        print('\n'.join(['\t'.join([str(c) for c in r]) for r in grid]))

if __name__ == '__main__':
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

A: It is a bad idea to replace the layouts or widgets since time and memory are wasted, the correct thing is to reuse, in this case I will create a list of lists that maps the buttons, so when you want to update some data in the grid the data will be updated in the buttons.
from PyQt5 import QtWidgets, QtCore, QtGui
import string

grid = [[["text", "GREEN"], 0, ["text", "RED"], 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0]]

BTN = """QPushButton{{font-weight: bold; color: {};
        font-size: 14px; background-color: {};
        border-width: 2px; border-radius: 100px}}"""

class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)

        self.letter_count = dict(zip(string.ascii_uppercase, [x for x in range(26)]))

        self.initUI()
        self.buttons = []
        self.createLayout()
        self.center_widget()

    def initUI(self):
        p = self.palette()
        gradient = QtGui.QLinearGradient(0, 0, 0, 400)
        gradient.setColorAt(0.0, QtGui.QColor('#f1f1f1'))
        gradient.setColorAt(1.0, QtGui.QColor('#00a1de'))
        p.setBrush(QtGui.QPalette.Window, QtGui.QBrush(gradient))
        self.setPalette(p)

    def createLayout(self):
        hlay = QtWidgets.QHBoxLayout(self)
        frameL = QtWidgets.QFrame()

        vlay = QtWidgets.QVBoxLayout(frameL)
        frame = QtWidgets.QFrame()
        frame.setObjectName("principal")
        frame.setStyleSheet("#principal{border: 2px solid white;}")
        hlay.addWidget(frameL)
        hlay.addWidget(frame)

        self.gridLayout = QtWidgets.QGridLayout(frame)

        h = 60  # height

        for i, row in enumerate(grid):
            letter = "{}".format(string.ascii_uppercase[i])
            frameButton = QtWidgets.QFrame()
            frameButton.setFixedHeight(h)
            frameButton.setContentsMargins(0, 0, 0, 0)
            lay = QtWidgets.QVBoxLayout(frameButton)
            button = QtWidgets.QPushButton(letter)
            button.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
            button.clicked.connect(lambda x, letter=letter: self.populate_row(letter)) # Every button click returns 'J'
            lay.addWidget(button)
            vlay.addWidget(frameButton)
            self.buttons.append([])
            for j, val in enumerate(row):
                gridButton = QtWidgets.QPushButton()
                gridButton.setFixedSize(h, h)
                self.buttons[i].append(gridButton)
                self.gridLayout.addWidget(gridButton, i, j)
        for ix in range(j + 1):
            label = QtWidgets.QLabel("{}".format(ix + 1))
            label.setAlignment(QtCore.Qt.AlignCenter)
            self.gridLayout.addWidget(label, i + 1, ix)
        vlay.addWidget(QtWidgets.QLabel())
        self.update_data()

    def update_data(self):
        for i, row in enumerate(grid):
            for j, val in enumerate(row):
                btn = self.buttons[i][j]
                if isinstance(val, list):
                    btn.setText(val[0])
                    if val[1] == "GREEN":
                        btn.setStyleSheet(BTN.format('white', 'green'))
                    elif val[1] == "RED":
                        btn.setStyleSheet(BTN.format('white', 'red'))
                else:
                    btn.setStyleSheet(BTN.format('black', 'white'))
                    btn.setText("{}".format(val))

    def center_widget(self):
        self.window().setGeometry(
            QtWidgets.QStyle.alignedRect(
                QtCore.Qt.LeftToRight,
                QtCore.Qt.AlignCenter,
                self.window().size(),
                QtWidgets.QApplication.desktop().availableGeometry())
        )

    def populate_row(self, letter):
        dialog = QtWidgets.QDialog()
        dialog.resize(660, 360)
        textBox = QtWidgets.QPlainTextEdit(dialog)
        Rbtn = QtWidgets.QPushButton('Add To Row')
        Rbtn.clicked.connect(lambda: self.input_to_grid(textBox.toPlainText(), letter))

        layout = QtWidgets.QVBoxLayout(dialog)
        layout.addWidget(textBox)
        layout.addWidget(Rbtn)
        dialog.exec_()

    def input_to_grid(self, text, letter):
        print(text, letter)
        lst = text.split(' ')
        for i, x in enumerate(lst):
            self.add_to_grid((letter, i + 1), x)
            print((letter, i + 1), x)
        self.print_grid()
        self.update_data()

    def add_to_grid(self, loc, item):
        x, y = self.translate(loc)
        grid[x][y] = item

    def translate(self, loc):
        for k, v in self.letter_count.items():
            if loc[0].upper() == k:
                x = v
        y = int(loc[1]) - 1
        return x, y

    def print_grid(self):
        """ Print the grid prettier than normal.. """
        print('\n'.join(['\t'.join([str(c) for c in r]) for r in grid]))

if __name__ == '__main__':
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())


text:
Q: How to easily distribute Python software that has Python module dependencies? Frustrations in Python package installation on Unix My goal is to distribute a Python package that has several other widely used Python packages as dependencies.  My package depends on well written, Pypi-indexed packages like pandas, scipy and numpy, and specifies in the setup.py that certain versions or higher of these are needed, e.g. "numpy >= 1.5".
I found that it's immensely frustrating and nearly impossible for Unix savvy users who are not experts in Python packaging (even if they know how to write Python) to install a package like mine, even when using what are supposed to be easy to use package managers.  I am wondering if there is an alternative to this painful process that someone can offer, or if my experience just reflects the very difficult current state of Python packaging and distribution.
Suppose users download your package onto their system.  Most will try to install it "naively", using something like:
$ python setup.py install

Since if you google instructions on installing Python packages, this is usually what comes up.  This will fail for the vast majority of users, since most do not have root access on their Unix/Linux servers.  With more searching, they will discover the "--prefix" option and try:
$ python setup.py install --prefix=/some/local/dir

Since the users are not aware of the intricacies of Python packaging, they will pick an arbitrary directory as an argument to --prefix, e.g. "~/software/mypackage/".  It will not be a cleanly curated directory where all other Python packages reside, because again, most users are not aware of these details.  If they install another package "myotherpackage", they might pass it "~/software/myotherpackage", and you can imagine how down the road this will lead to frustrating hacking of PYTHONPATH and other complications.
Continuing with the installation process, the call to "setup.py install" with "--prefix" will also fail once users try to use the package, even though it appeared to have been installed correctly, since one of the dependencies might be missing (e.g. pandas, scipy or numpy) and a package manager is not used.  They will try to install these packages individually.  Even if successful, the packages will inevitably not be in the PYTHONPATH due to the non-standard directories given to "--prefix" and patient users will dabble with modifications of their PYTHONPATH to get the dependencies to be visible.
At this stage, users might be told by a Python savvy friend that they should use a package manager like "easy_install", the mainstream manager, to install the software and have dependencies taken care of.  After installing "easy_install", which might be difficult, they will try:
$ easy_install setup.py

This too will fail, since users again do not typically have permission to install software globally on production Unix servers.  With more reading, they will learn about the "--user" option, and try:
$ easy_install setup.py --user

They will get the error:
usage: easy_install [options] requirement_or_url ...
   or: easy_install --help

error: option --user not recognized

They will be extremely puzzled why their easy_install does not have the --user option where there are clearly pages online describing the option.  They might try to upgrade their easy_install to the latest version and find that it still fails.
If they continue and consult a Python packaging expert, they will discover that there are two versions of easy_install, both named "easy_install" so as to maximize confusion, but one part of "distribute" and the other part of "setuptools".  It happens to be that only the "easy_install" of "distribute" supports "--user" and the vast majority of servers/sys admins install "setuptools"'s easy_install and so local installation will not be possible.  Keep in mind that these distinctions between "distribute" and "setuptools" are meaningless and hard to understand for people who are not experts in Python package management.
At this point, I would have lost 90% of even the most determined, savvy and patient users who try to install my software package -- and rightfully so!  They wanted to install a piece of software that happened to be written in Python, not to become experts in state of the art Python package distribution, and this is far too confusing and complex.  They will give up and be frustrated at the time wasted.
The tiny minority of users who continue on and ask more Python experts will be told that they ought to use pip/virtualenv instead of easy_install.  Installing pip and virtualenv and figuring out how these tools work and how they are different from the conventional "python setup.py" or "easy_install" calls is in itself time consuming and difficult, and again too much to ask from users who just wanted to install a simple piece of Python software and use it. Even those who pursue this path will be confused as to whether whatever dependencies they installed with easy_install or setup.py install --prefix are still usable with pip/virtualenv or if everything needs to be reinstalled from scratch.
This problem is exacerbated if one or more of the packages in question depends on installing a different version of Python than the one that is the default.  The difficulty of ensuring that your Python package manger is using the Python version you want it to, and that the required dependencies are installed in the relevant Python 2.x directory and not Python 2.y, will be so endlessly frustrating to users that they will certainly give up at that stage.
Is there a simpler way to install Python software that doesn't require users to delve into all of these technical details of Python packages, paths and locations?  For example, I am not a big Java user, but I do use some Java tools occasionally, and don't recall ever having to worry about X and Y dependencies of the Java software I was installing, and I have no clue how Java package managing works (and I'm happy that I don't -- I just wanted to use a tool that happened to be written in Java.)  My recollection is that if you download a Jar, you just get it and it tends to work.
Is there an equivalent for Python?  A way to distribute software in a way that doesn't depend on users having to chase down all these dependencies and versions?  A way to perhaps compile all the relevant packages into something self-contained that can just be downloaded and used as a binary?
I would like to emphasize that this frustration happens even with the narrow goal of distributing a package to savvy Unix users, which makes the problem simpler by not worrying about cross platform issues, etc.  I assume that the users are Unix savvy, and might even know Python, but just aren't aware (and don't want to be made aware) about the ins and outs of Python packaging and the myriad of internal complications/rivalries of different package managers.  A disturbing feature of this issue is that it happens even when all of your Python package dependencies are well-known, well-written and well-maintained Pypi-available packages like Pandas, Scipy and Numpy.  It's not like I was relying on some obscure dependencies that are not properly formed packages: rather, I was using the most mainstream packages that many might rely on.
Any help or advice on this will be greatly appreciated.  I think Python is a great language with great libraries, but I find it virtually impossible to distribute the software I write in it (once it has dependencies) in a way that is easy for people to install locally and just run.  I would like to clarify that the software I'm writing is not a Python library for programmatic use, but software that has executable scripts that users run as individual programs. Thanks.

A: We're currently working to make it easier for users to get started installing Python software in a platform independent manner (in particular see https://python-packaging-user-guide.readthedocs.org/en/latest/future.html and http://www.python.org/dev/peps/pep-0453/)
For right now, the problem with two competing versions of easy_install has been resolved, with the competing fork "distribute" being merged backing into the setuptools main line of development.
The best currently available advice on cross-platform distribution and installation of Python software is captured here: https://packaging.python.org/

A: We also develop software projects that depend on numpy, scipy and other PyPI packages. Hands down, the best tool currently available out there for managing remote installations is zc.buildout. It is very easy to use. You download a bootstrapping script from their website and distribute that with your package. You write a "local deployment" file, called normally buildout.cfg, that explains how to install the package locally. You ship both the bootstrap.py file and buildout.cfg with your package - we use the MANIFEST.in file in our python packages to force the embedding of these two files with the zip or tar balls distributed by PyPI. When the user unpackages it, it should execute two commands:
$ python bootstrap.py # this will download zc.buildout and setuptools
$ ./bin/buildout # this will build and **locally** install your package + deps

The package is compiled and all dependencies are installed locally, which means that the user installing your package doesn't even need root privileges, which is an added feature. The scripts are (normally) placed under ./bin, so the user can just execute them after that. zc.buildout uses setuptools for interaction with PyPI so everything you expect works out of the box.
You can extend zc.buildout quite easily if all that power is not enough - you create the so-called "recipes" that can help the user to create extra configuration files, download other stuff from the net or instantiate custom programs. zc.buildout website contains a video tutorial that explains in details how to use buildout and how to extend it. Our project Bob makes extensive use of buildout for distributing packages for scientific usage. If you would like, please visit the following page that contains detailed instructions for our developers on how they can setup their python packages so other people can build and install them locally using zc.buildout.


text:
Q: Google Cloud vs Amazon S3: Best option for cloud storage in a implementation We need to implement a solution in Salesforce Lightning based on a service to uploading large videos or pictures. But the traffic will not be significant. On the other hand, the service will be accessible from to multiple external sites.
In terms of cost and performance, what would you recommend me?


text:
Q: Front Facing Camera Issue in IPhone 5S IOS 7 I have problem on IPhone 5S with front camera output, the same session resolution like rear camera. (AVCaptureSessionPreset352x288) and kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange setting for kCVPixelBufferPixelFormatTypeKey.
I found some discussion on apple forum about exact issue, here is the link: https://discussions.apple.com/message/23079639#23079639
What is the problem?
Please Help.
Good output, rear-facing camera.
Printing description of imageBuffer:
<CVPixelBuffer 0xd5e2f30 width=352 height=288 pixelFormat=420v iosurface=0xd80e724 planes=2>
<Plane 0 width=352 height=288 bytesPerRow=352>
<Plane 1 width=176 height=144 bytesPerRow=352>
<attributes=<CFBasicHash 0xd5c3710 [0x3bf18ad0]>{type = immutable dict, count = 1,
entries =>
    1 : <CFString 0x3bf971b4 [0x3bf18ad0]>{contents = "PixelFormatDescription"} = <CFBasicHash 0xb9fce0 [0x3bf18ad0]>{type = immutable dict, count = 7,
entries =>
    0 : <CFString 0x3bf97164 [0x3bf18ad0]>{contents = "IOSurfaceCoreAnimationCompatibility"} = <CFBoolean 0x3bf18e80 [0x3bf18ad0]>{value = true}
    2 : <CFString 0x3bf97194 [0x3bf18ad0]>{contents = "OpenGLESCompatibility"} = <CFBoolean 0x3bf18e80 [0x3bf18ad0]>{value = true}
    3 : <CFString 0x3bf972c4 [0x3bf18ad0]>{contents = "ContainsAlpha"} = <CFBoolean 0x3bf18e88 [0x3bf18ad0]>{value = false}
    5 : <CFString 0x3bf97184 [0x3bf18ad0]>{contents = "IOSurfaceOpenGLESFBOCompatibility"} = <CFBoolean 0x3bf18e80 [0x3bf18ad0]>{value = true}
    7 : <CFString 0x3bf972d4 [0x3bf18ad0]>{contents = "Planes"} = <CFArray 0xb24830 [0x3bf18ad0]>{type = mutable-small, count = 2, values = (
    0 : <CFBasicHash 0xb99420 [0x3bf18ad0]>{type = mutable dict, count = 3,
entries =>
    0 : <CFString 0x3bf973b4 [0x3bf18ad0]>{contents = "FillExtendedPixelsCallback"} = <CFData 0xba06a0 [0x3bf18ad0]>{length = 12, capacity = 12, bytes = 0x00000000917cbb3100000000}
    1 : <CFString 0x3bf97334 [0x3bf18ad0]>{contents = "BlackBlock"} = <CFData 0xb9deb0 [0x3bf18ad0]>{length = 1, capacity = 1, bytes = 0x10}
    2 : <CFString 0x3bf97324 [0x3bf18ad0]>{contents = "BitsPerBlock"} = <CFNumber 0xb277e0 [0x3bf18ad0]>{value = +8, type = kCFNumberSInt32Type}
}

    1 : <CFBasicHash 0xba0e50 [0x3bf18ad0]>{type = mutable dict, count = 5,
entries =>
    0 : <CFString 0x3bf97334 [0x3bf18ad0]>{contents = "BlackBlock"} = <CFData 0xb9c550 [0x3bf18ad0]>{length = 2, capacity = 2, bytes = 0x8080}
    2 : <CFString 0x3bf97344 [0x3bf18ad0]>{contents = "HorizontalSubsampling"} = <CFNumber 0xc0f720 [0x3bf18ad0]>{value = +2, type = kCFNumberSInt32Type}
    4 : <CFString 0x3bf97324 [0x3bf18ad0]>{contents = "BitsPerBlock"} = <CFNumber 0xba0e80 [0x3bf18ad0]>{value = +16, type = kCFNumberSInt32Type}
    5 : <CFString 0x3bf973b4 [0x3bf18ad0]>{contents = "FillExtendedPixelsCallback"} = <CFData 0xba16d0 [0x3bf18ad0]>{length = 12, capacity = 12, bytes = 0x00000000817bbb3100000000}
    6 : <CFString 0x3bf97354 [0x3bf18ad0]>{contents = "VerticalSubsampling"} = <CFNumber 0xc0f720 [0x3bf18ad0]>{value = +2, type = kCFNumberSInt32Type}
}

)}
    8 : <CFString 0x3bf97294 [0x3bf18ad0]>{contents = "PixelFormat"} = <CFNumber 0xb7acf0 [0x3bf18ad0]>{value = +875704438, type = kCFNumberSInt32Type}
    12 : <CFString 0x3bf97174 [0x3bf18ad0]>{contents = "IOSurfaceOpenGLESTextureCompatibility"} = <CFBoolean 0x3bf18e80 [0x3bf18ad0]>{value = true}
}

}
 propagatedAttachments=<CFBasicHash 0x126e2130 [0x3bf18ad0]>{type = mutable dict, count = 4,
entries =>
    1 : <CFString 0x3bf70edc [0x3bf18ad0]>{contents = "MetadataDictionary"} = <CFBasicHash 0xd5da1a0 [0x3bf18ad0]>{type = mutable dict, count = 7,
entries =>
    0 : <CFString 0x3bf70f4c [0x3bf18ad0]>{contents = "SNR"} = <CFNumber 0xd5da1d0 [0x3bf18ad0]>{value = +33.11550123401803347178, type = kCFNumberFloat64Type}
    2 : <CFString 0x3bf70ddc [0x3bf18ad0]>{contents = "sensorDGain"} = <CFNumber 0xd58def0 [0x3bf18ad0]>{value = +256, type = kCFNumberSInt32Type}
    3 : <CFString 0x3bf70f3c [0x3bf18ad0]>{contents = "SensorID"} = <CFNumber 0x126f7b40 [0x3bf18ad0]>{value = +356, type = kCFNumberSInt32Type}
    6 : <CFString 0x3bf7054c [0x3bf18ad0]>{contents = "ExposureTime"} = <CFNumber 0xd5d83d0 [0x3bf18ad0]>{value = +0.03332500000000000046, type = kCFNumberFloat64Type}
    7 : <CFString 0x3bf70dec [0x3bf18ad0]>{contents = "ispDGain"} = <CFNumber 0xd54d620 [0x3bf18ad0]>{value = +273, type = kCFNumberSInt32Type}
    11 : <CFString 0x3bf7017c [0x3bf18ad0]>{contents = "AGC"} = <CFNumber 0xd5e21f0 [0x3bf18ad0]>{value = +780, type = kCFNumberSInt32Type}
    12 : <CFString 0x3bf7114c [0x3bf18ad0]>{contents = "AEAverage"} = <CFNumber 0xd5e27a0 [0x3bf18ad0]>{value = +126, type = kCFNumberSInt32Type}
}

    3 : <CFString 0x3bf96f54 [0x3bf18ad0]>{contents = "CVImageBufferYCbCrMatrix"} = <CFString 0xd5c34b0 [0x3bf18ad0]>{contents = "ITU_R_601_4"}
    5 : <CFString 0x3bf96f94 [0x3bf18ad0]>{contents = "CVImageBufferColorPrimaries"} = <CFString 0x126bced0 [0x3bf18ad0]>{contents = "ITU_R_709_2"}
    6 : <CFString 0x3bf96fd4 [0x3bf18ad0]>{contents = "CVImageBufferTransferFunction"} = <CFString 0xd58dfa0 [0x3bf18ad0]>{contents = "ITU_R_709_2"}
}
 nonPropagatedAttachments=<CFBasicHash 0x126e2100 [0x3bf18ad0]>{type = mutable dict, count = 0,
entries =>
}
>

Bad output, front-facing camera.
Printing description of imageBuffer:
<CVPixelBuffer 0x12638980 width=352 height=288 pixelFormat=420v iosurface=0xd80e724 planes=2>
<Plane 0 width=352 height=288 bytesPerRow=384>
<Plane 1 width=176 height=144 bytesPerRow=384>
<attributes=<CFBasicHash 0x12638bb0 [0x3bf18ad0]>{type = immutable dict, count = 1,
entries =>
    1 : <CFString 0x3bf971b4 [0x3bf18ad0]>{contents = "PixelFormatDescription"} = <CFBasicHash 0xb9fce0 [0x3bf18ad0]>{type = immutable dict, count = 7,
entries =>
    0 : <CFString 0x3bf97164 [0x3bf18ad0]>{contents = "IOSurfaceCoreAnimationCompatibility"} = <CFBoolean 0x3bf18e80 [0x3bf18ad0]>{value = true}
    2 : <CFString 0x3bf97194 [0x3bf18ad0]>{contents = "OpenGLESCompatibility"} = <CFBoolean 0x3bf18e80 [0x3bf18ad0]>{value = true}
    3 : <CFString 0x3bf972c4 [0x3bf18ad0]>{contents = "ContainsAlpha"} = <CFBoolean 0x3bf18e88 [0x3bf18ad0]>{value = false}
    5 : <CFString 0x3bf97184 [0x3bf18ad0]>{contents = "IOSurfaceOpenGLESFBOCompatibility"} = <CFBoolean 0x3bf18e80 [0x3bf18ad0]>{value = true}
    7 : <CFString 0x3bf972d4 [0x3bf18ad0]>{contents = "Planes"} = <CFArray 0xb24830 [0x3bf18ad0]>{type = mutable-small, count = 2, values = (
    0 : <CFBasicHash 0xb99420 [0x3bf18ad0]>{type = mutable dict, count = 3,
entries =>
    0 : <CFString 0x3bf973b4 [0x3bf18ad0]>{contents = "FillExtendedPixelsCallback"} = <CFData 0xba06a0 [0x3bf18ad0]>{length = 12, capacity = 12, bytes = 0x00000000917cbb3100000000}
    1 : <CFString 0x3bf97334 [0x3bf18ad0]>{contents = "BlackBlock"} = <CFData 0xb9deb0 [0x3bf18ad0]>{length = 1, capacity = 1, bytes = 0x10}
    2 : <CFString 0x3bf97324 [0x3bf18ad0]>{contents = "BitsPerBlock"} = <CFNumber 0xb277e0 [0x3bf18ad0]>{value = +8, type = kCFNumberSInt32Type}
}

    1 : <CFBasicHash 0xba0e50 [0x3bf18ad0]>{type = mutable dict, count = 5,
entries =>
    0 : <CFString 0x3bf97334 [0x3bf18ad0]>{contents = "BlackBlock"} = <CFData 0xb9c550 [0x3bf18ad0]>{length = 2, capacity = 2, bytes = 0x8080}
    2 : <CFString 0x3bf97344 [0x3bf18ad0]>{contents = "HorizontalSubsampling"} = <CFNumber 0xc0f720 [0x3bf18ad0]>{value = +2, type = kCFNumberSInt32Type}
    4 : <CFString 0x3bf97324 [0x3bf18ad0]>{contents = "BitsPerBlock"} = <CFNumber 0xba0e80 [0x3bf18ad0]>{value = +16, type = kCFNumberSInt32Type}
    5 : <CFString 0x3bf973b4 [0x3bf18ad0]>{contents = "FillExtendedPixelsCallback"} = <CFData 0xba16d0 [0x3bf18ad0]>{length = 12, capacity = 12, bytes = 0x00000000817bbb3100000000}
    6 : <CFString 0x3bf97354 [0x3bf18ad0]>{contents = "VerticalSubsampling"} = <CFNumber 0xc0f720 [0x3bf18ad0]>{value = +2, type = kCFNumberSInt32Type}
}

)}
    8 : <CFString 0x3bf97294 [0x3bf18ad0]>{contents = "PixelFormat"} = <CFNumber 0xb7acf0 [0x3bf18ad0]>{value = +875704438, type = kCFNumberSInt32Type}
    12 : <CFString 0x3bf97174 [0x3bf18ad0]>{contents = "IOSurfaceOpenGLESTextureCompatibility"} = <CFBoolean 0x3bf18e80 [0x3bf18ad0]>{value = true}
}

}
 propagatedAttachments=<CFBasicHash 0x12638c10 [0x3bf18ad0]>{type = mutable dict, count = 4,
entries =>
    1 : <CFString 0x3bf70edc [0x3bf18ad0]>{contents = "MetadataDictionary"} = <CFBasicHash 0x12638650 [0x3bf18ad0]>{type = mutable dict, count = 7,
entries =>
    0 : <CFString 0x3bf70f4c [0x3bf18ad0]>{contents = "SNR"} = <CFNumber 0x126367e0 [0x3bf18ad0]>{value = +34.16280207318401096472, type = kCFNumberFloat64Type}
    2 : <CFString 0x3bf70ddc [0x3bf18ad0]>{contents = "sensorDGain"} = <CFNumber 0x12633120 [0x3bf18ad0]>{value = +256, type = kCFNumberSInt32Type}
    3 : <CFString 0x3bf70f3c [0x3bf18ad0]>{contents = "SensorID"} = <CFNumber 0x126360c0 [0x3bf18ad0]>{value = +38754, type = kCFNumberSInt32Type}
    6 : <CFString 0x3bf7054c [0x3bf18ad0]>{contents = "ExposureTime"} = <CFNumber 0x12636440 [0x3bf18ad0]>{value = +0.02999900000000000136, type = kCFNumberFloat64Type}
    7 : <CFString 0x3bf70dec [0x3bf18ad0]>{contents = "ispDGain"} = <CFNumber 0x12630f20 [0x3bf18ad0]>{value = +260, type = kCFNumberSInt32Type}
    11 : <CFString 0x3bf7017c [0x3bf18ad0]>{contents = "AGC"} = <CFNumber 0xd580830 [0x3bf18ad0]>{value = +1803, type = kCFNumberSInt32Type}
    12 : <CFString 0x3bf7114c [0x3bf18ad0]>{contents = "AEAverage"} = <CFNumber 0x12635ae0 [0x3bf18ad0]>{value = +176, type = kCFNumberSInt32Type}
}

    3 : <CFString 0x3bf96f54 [0x3bf18ad0]>{contents = "CVImageBufferYCbCrMatrix"} = <CFString 0x126383d0 [0x3bf18ad0]>{contents = "ITU_R_601_4"}
    5 : <CFString 0x3bf96f94 [0x3bf18ad0]>{contents = "CVImageBufferColorPrimaries"} = <CFString 0x12632d90 [0x3bf18ad0]>{contents = "ITU_R_709_2"}
    6 : <CFString 0x3bf96fd4 [0x3bf18ad0]>{contents = "CVImageBufferTransferFunction"} = <CFString 0x126372c0 [0x3bf18ad0]>{contents = "ITU_R_709_2"}
}
 nonPropagatedAttachments=<CFBasicHash 0x12638be0 [0x3bf18ad0]>{type = mutable dict, count = 0,
entries =>
}
>

A: As Spectravideo328 has mentioned the byte per row isn't the same as width of the image. Hence you'll need to copy the valid data from the source layers to your destination buffer skipping the extra paddings. That means for each row (which is equal to the "height" of the image) copy the first "width" amount of bytes.


text:
Q: Git Add - fatal: adding files failed My git-cmd.exe window looks like this:
git add "NextFolder/*"
error: unable to create temporary file: No such file or directory
error: NextFolder/SomeFile.txt: failed to insert into database
error: unable to index file 'NextFolder/SomeFile.txt'
fatal: adding files failed

I'm adding a large number of files to a new git repo.  I have over 14,000 files spread out across about 80 folders in the root level.  Due to the volume I've decided to add and commit one folder at a time.  Seems each folder has some number of files that cause the "git add" operation to have a fatal error (see above).
I'm using Git for Windows, portable version:
git --version
git version 2.22.0.windows.1

I believe the error is somehow related to the content of the file.  I can rename the file, copy contents to a new file, rename that file, none of that will make it work.  I've found that if I add a CRLF at the very bottom of the file the problem is "fixed" for that file but the git add operation just hangs up on some other file in the folder with the same condition.
I've been using Notepad++ to examine the files compared to other files that seem to get added without an issue.  Line endings look the same (CRLF), encoding looks the same (ANSI), etc.
One of the comments in this thread seem to be describing my exact problem, but it's the last comment on an answer with no upvotes and the thread is 5yr old...
git - unable to create temporary file: no such file or directory - only for certain files?
I'm also fairly certain this is not a permissions issue.  That's the first thing that comes up in my research but I've copied the source code, in it's entirety, to my local machine to get everything added to git. So I'm thinking it shouldn't be a permissions issue since everything is local and most of the files are getting added.  Unless it's related to the volume of files or the fact I'm using Git portable.
Been banging my head against this for hours, send help!
EDIT: I should have pointed out that the git repo is seperate from the working tree. They are actually on different drives. Both are network drives, e.g. S:\path\to\tree and H:\git\test.git.  This is thought to be temporary, I am attempting to characterize the frequency of changes we have on the (working tree) network location.  Once I have better understanding of where we have the most churn, I'm thinking we will make smaller repos with the typical configuration, having the .git folder at the root of the working tree.

A: I had the same problems it seems that I had an empty directory in the project folder. I deleted this and everything was fine. Could have used an error message that told me more about the correct direction.

A:
git add "NextFolder/*"

It should be git add "NextFolder": no star/wildcard needed here, as it would be interpreted by the Git bash instead of Git itself.
First, make sure to add those files in a CMD session using a simplified PATH: that will rule out any other program influence.
set PATH=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\
set GH=C:\path\to\git
set PATH=%GH%\bin;%GH%\usr\bin;%GH%\mingw64\bin;%PATH%

Second, make sure to type first:
git config core.autocrlf false

That will avoid Git trying to convert EOL on all files.
I mentioned core.fscache here, but with Git 2.22, the issue 1989 is resolved.
Do activate the core.commitGraph and add a folder (and subfolders) at a time, with a commit done after each add.
Finally, with Git 2.22, do activate trace2 for more traces.

I should point out when I had the error I had the repo separate from the worktree.
  They are on different volumes.

*

*The worktree is under S:\path\... and

*the .git folder is under H:\git\test.git

Try and check if the issue persists when doing a git add in a local repository, cloned on your local disk C:\ (no network should be involved at least for the .git folder).

With Git 2.24 (Q4 2019) trace2 will be applied to commit graphs as well.
See commit 0bd7f57 (27 Aug 2019) by Garima Singh (singhgarima).
(Merged by Junio C Hamano -- gitster -- in commit ccc2899, 15 Oct 2019)

commit-graph: emit trace2 cmd_mode for each sub-command
Signed-off-by: Garima Singh
Acked-by: Jeff Hostetler
Emit trace2_cmd_mode() messages for each commit-graph sub-command.
The commit graph commands were in flux when trace2 was making it's way to Git.
Now that we have enough sub-commands in commit-graph, we can label the various modes within them.
  Distinguishing between read, write and verify is a great start.

A: The folder which is giving you fatal: adding files failed message on git add command is actually implying that there is another .git folder inside the folder. If you navigate to the particular folder address, you can remove the file and put git add. It should work.


text:
Q: How to disable password prompt while mounting partitions? I'm using ubuntu mini.iso to setup a dual boot system. I've already installed polkit to be able to mount windows(and other ntfs partitions) while using GUI. But every time I try to mount them from file manager(Thunar) after a restart, I get a password prompt. I've tried adding following rules to /etc/polkit-1/rules.d/50-mount-partitions.rules:
// Password-less mounting of local partitions
polkit.addRule(function(action, subject) {
    if (action.id == "org.freedesktop.udisks2.filesystem-mount-system" && subject.isInGroup("sudo")) {
       return polkit.Result.YES;
    }
});
But this is not working.How can I disable it?

A: After 2 days found a solution from fedora website. Here's what I did:
sudo vi /etc/polkit-1/localauthority/50-local.d/10-mount-without-password.pkla
Entered the following lines of code into it:
[storage group mount override]
Identity=unix-user:USERNAME
Action=org.freedesktop.udisks2.filesystem-mount;org.freedesktop.udisks2.filesystem-mount-system
ResultAny=yes
ResultInactive=yes
ResultActive=yes
And replaced USERNAME my username.
Now, I don't need to enter password during mounting from thunar.
Edit : for beginners gnome-disk-utility is a good tool to manage /etc/fstab . To enable auto mount of a drive at startup open the disk app, select the partition,select 'additional partition options', select 'edit mount options' , disable 'User session Defaults' , tick 'mount at system startup' and enter your password to allow changes.
Note: Users facing same problem please consider using @M K 's solution of automounting all drives at stratup. It can be done by editing /etc/fstab using any editor or you can use gnome-disk-utility if you like to achieve same result with gui. In my case I wanted an answer specific to polkit due to reasons mentioned in the comments section of his answer. So choose a suitable method depending on your requirement.

A: I would disregard any workaround and add a permanent mount entry into /etc/fstab.
Try man fstab for reference.
There are no definitive steps to doing a very specific mount. Each case comes with its variables. Anyway, running Terminal:

*

*Run df -h and examine the output to know the block device address of your Windows partitions.

*Edit /etc/fstab as super-user (e. g. using GEdit) and add entries for each Windows partition, like:
/dev/sdb2   /my_mount_point_folder  ntfs    rw  0   0

This will mount block device /dev/sdb2 at folder /my_mount_point_folder with read-write permissions. This happens with every boot, automatically.
That should do it. It is still good to review fstab manual: in Terminal run man fstab.


text:
Q: Hand Cursor when rolling over MovieClips in AS3 My goal is to simply have the cursor swap to be a hand (pointer) when I roll over a MovieClip. Obviously I could use SimpleButton, but the situation is that I have some enemies that are obviously MovieClips, and when I select an ability to use I want the mouse to show as a pointer when I roll over them.
I assumed this would work:
var mc:MovieClip = new MovieClip();

mc.graphics.beginFill(0);
mc.graphics.drawRect(0,0,50,50);
mc.graphics.endFill();

mc.useHandCursor = true; // <---- doesn't work?

addChild(mc);

mc.addEventListener(MouseEvent.CLICK, _click);
function _click(e:MouseEvent):void
{
    trace('a');
}

There are workarounds such as adding a button into the enemy MovieClip and then removing it. Just seems there's an inbuilt way I'm missing.
Thanks.

A: mc.buttonMode = true;  You can use this,
this will works.

A: I think it's mc.buttonMode = true;

A: Sometimes you will need to use also :
mc.mouseChildren=false;

To have handcursor over some movieclips, like movieclip with a textfield inside. -


text:
Q: Go gorilla log each request duration and status code I have a REST API written in Go1.13 using gorilla/mux v1.7.3 and gorilla/context v1.1.1.
I want to log each request duration and status code. I already have a basic working version,  but I'm wondering if there is a cleaner option.
I have about 20 HTTP calls. Let's take one of them as an example:
client.HandleFunc("/register", register.Handle).Methods("POST")

and the signature of register.Handle is:
func Handle(w http.ResponseWriter, r *http.Request) { ... }

So in order to log each request duration and status code, I simply wrapped the method handler register.Handle with a "log handler":
client.HandleFunc("/register", log.HandleRequestWithLog(register.Handle)).Methods("POST")

when log.HandleRequestWithLog simply times the function execution, and logs it with the returned status code (logging with Azure metrics):
func HandleRequestWithLog(h func(http.ResponseWriter, *http.Request) int) http.HandlerFunc {
    return func(writer http.ResponseWriter, request *http.Request) {
        startTime := time.Now()
        statusCode := h(writer, request)
        duration := time.Now().Sub(startTime)
        trace := appinsights.NewRequestTelemetry(request.Method, request.URL.Path, duration, string(rune(statusCode)))
        trace.Timestamp = time.Now()
        client.Track(trace)
    }
}

So in order to extract the status code, I needed every HTTP method to return the status code. So I changed the signature to:
func Handle(w http.ResponseWriter, r *http.Request) int { .. }

I was wondering if there is a better option than returning the HTTP status code for each request. Also, what will happen if I want more information from the request? I'll return this value as well?

A: Instead of changing HTTP handler signature, you can define a LogResponseWriter that implements http.ResponseWriter to keep track of response data (status, body, etc..).

*

*Let's define LogResponseWriter
type LogResponseWriter struct {
    http.ResponseWriter
    statusCode int
    buf        bytes.Buffer
}

func NewLogResponseWriter(w http.ResponseWriter) *LogResponseWriter {
    return &LogResponseWriter{ResponseWriter: w}
}

func (w *LogResponseWriter) WriteHeader(code int) {
    w.statusCode = code
    w.ResponseWriter.WriteHeader(code)
}

func (w *LogResponseWriter) Write(body []byte) (int, error) {
    w.buf.Write(body)
    return w.ResponseWriter.Write(body)
}

*Define LogMiddleware (here, I use std log and mux.MiddlewareFunc)

type LogMiddleware struct {
    logger *log.Logger
}

func NewLogMiddleware(logger *log.Logger) *LogMiddleware {
    return &LogMiddleware{logger: logger}
}

func (m *LogMiddleware) Func() mux.MiddlewareFunc {
    return func(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            startTime := time.Now()

            logRespWriter := NewLogResponseWriter(w)
            next.ServeHTTP(logRespWriter, r)

            m.logger.Printf(
                "duration=%s status=%d body=%s",
                time.Since(startTime).String(),
                logRespWriter.statusCode,
                logRespWriter.buf.String())
        })
    }
}

*Start the server in main.go. Here, we can use the LogMiddleware in our router.

func main() {
    logger := log.New(os.Stdout, "", log.LstdFlags)

    router := mux.NewRouter()
    router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        time.Sleep(1 * time.Second)

        w.WriteHeader(http.StatusOK)
        w.Header().Set("Content-Type", "application/json")
        w.Write([]byte(`{"msg": "hello world"}`))
    })

    logMiddleware := NewLogMiddleware(logger)
    router.Use(logMiddleware.Func())

    logger.Fatalln(http.ListenAndServe(":8080", router))
}

The log result when I visit http://localhost:8080:
2020/10/08 00:51:38 duration=1.003927394s status=200 body={"msg": "hello world"}

*Follow up: What will happen if I want more information from the request?

In your log middleware, you can read the request header & body (from r *http.Request), then log them with the duration and response data. Note that you should reassign the request body so that your actual handlers can read the request body.


text:
Q: Not able to read COM3 port. Always output is 0 This code is able to run, however it only prints 0 even though the device has some value. The device is a roller machine where it should give the rolling meter to the port number 3; however, my code always reads the output as 0.
using System;
using System.Text;
using System.IO.Ports;
using System.Collections.Generic;
namespace ConsoleApplication3
{
    class Program
    {
        static SerialPort sp;
        string InputData = string.Empty;
        static void Main(string[] args)
        {
            sp = new SerialPort("COM3", 4800, Parity.None, 8, StopBits.One);
            sp.DiscardNull = false;
            sp.RtsEnable = true;
            sp.ReadTimeout = 500;
            sp.Handshake = Handshake.None;
            sp.Encoding = Encoding.UTF8;
            sp.DtrEnable = true;
            sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
            sp.Open();
            //sp.DataReceived += sp_DataReceived;
            string InputData = sp.ReadExisting();
            while (sp.IsOpen)
            {
                try
                {
                    System.Threading.Thread.Sleep(300);
                    int bytes = sp.BytesToRead;
                    byte[] buffer = new byte[bytes];
                    Console.WriteLine("Value - " + sp.Read(buffer, 0, bytes));
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }
        private static void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort sport = (SerialPort)sender;
            string indata = sport.ReadExisting();
            Console.WriteLine(indata);
        }
    }
}

The code Console.WriteLine("Value - " + sp.Read(buffer, 0, bytes)); prints always 0.

A: While executing this line of code Console.WriteLine("Value - " + sp.Read(buffer, 0, bytes)); you can't guarantee that there are received bytes to read, you should depend only on the event handler lsp_DataReceived


text:
Q: 'Open In Excel' option is grayed out for .xlsm files in Sharepoint 2013 We know that excel files with macros and password protections are not supported to view in Browser using Office Web App / Excel Web App. In this SharePoint shows small dialogue where it has 'Open In Excel' option. However, in our case for some documents this option is grayed out and for some of them its working as expected (Open In Excel option not grayed out). Please find following screenshot. 'Open In EXcel' button is grayed out.

Is there any limitations on Office Web Apps / Excel web app that we can only x number of macros / password protected sheet or x number of rows of data with password / macros? What is the best way to enable the Open in Excel option for this scenario on Excel Office Web App / Office Web Apps integrated with SharePoint 2013 environment?

A: As mentioned in error screen, i think those files are password protected or might be macro enabled file.. in online only limited feature supports
For checking is it password protected, download that excel file and Go to file and info, there you can see is it protected or non protected.

A: Are you using IE? Per my test,  open in excel would be enabled in IE.
Try to add the site in compatibility mode.
Try to add the site into trust site.


text:
Q: Fix the color order in a plotly gantt chart Trying to plot a gantt chart using plotly and a pandas dataframe. The plot comes fine, except the colors are in a different order.
Here is the dataframe
                  Goss     got
timestamp
16-01-21 10:00:09    M   Item1
04-02-21 20:28:30    T   Item2
06-02-21 00:45:57    V   Item3
24-07-21 11:07:39    M   Item4
26-08-21 16:15:01    T   Item5
28-08-21 14:05:13    I   Item6
02-09-21 16:57:26    D   Item7
15-09-21 15:35:07    M   Item8
13-10-21 18:19:42    D   Item9
18-10-21 02:39:40    G  Item10
31-10-21 22:07:27    D  Item11
01-11-21 09:58:21    I  Item12
01-11-21 11:37:44    V  Item13
28-11-21 10:44:39    K  Item14
28-11-21 14:52:39    M  Item15
29-11-21 18:40:32    G  Item16
01-12-21 23:34:00    G  Item17
03-12-21 00:11:11    T  Item18
05-12-21 15:55:50    G  Item19

We process the above data as follows:
import pandas as pd
import plotly
from plotly import figure_factory as FF

gdf=pd.read_clipboard(sep='\s\s+') #with this the df data above can be copied and read to a df
gdf.reset_index(inplace=True)
gdf.timestamp = pd.to_datetime(gdf.timestamp,format="%d-%m-%y %H:%M:%S")
gdf=pd.concat([gdf.timestamp.shift(),gdf], axis=1)
gdf.columns=['Start', 'Finish', 'Goss', 'Task']
gdf.at[0,'Start'] = pd.Timestamp("2021-01-01-00-00-00")
gfig = FF.create_gantt(gdf, colors=['#FFFF00',
                                    '#A0522D',
                                    '#808000',
                                    '#008000',
                                    '#FF0000',
                                    '#00CED1',
                                    '#00FFFF'],
                       index_col='Goss', show_colorbar=True,
                       bar_width=0.2, showgrid_x=True, showgrid_y=True)
plotly.offline.plot(gfig, filename='gorge.html')

Read the data from clipboard using
gdf=pd.read_clipboard(sep='\s\s+')
My data gets improperly colored. I tried few reorder of the colors, didn't come out correctly. The correct order should be as given in the dict below, item followed by the color it should have.
{'T':'#FFFF00','G':'#A0522D','M':'#808000','D':'#008000','V':'#FF0000', 'K':'#00CED1',"I':'#00FFFF'}

A: You can update the colors after the figure is created.
cmap = {'T':'#FFFF00','G':'#A0522D','M':'#808000','D':'#008000','V':'#FF0000', 'K':'#00CED1',"I":'#00FFFF'}
gfig.for_each_trace(lambda t: t.update(fillcolor=cmap[t.name]) if t.name in cmap.keys() else t)