text:
Q: When dealing with Razor Pages and a Page Model class is the constructor called on each request? Something I have struggled with is understanding the lifecycle of the Page Model class for my Razor Pages usages. I'm trying to think about how and when to deal with common data I pass to my business logic like the userId that is running the request. So many times I need to save this information with the results of the action.
So where is the best place to handle something over and over like geting User details that might be in the persistence model and not in the context of the page model's User from the HTTPContext?
I should mention I am using authorize tags with cookie backed authenication to a webservice.

A: For accessing Reuqest from other layers except the Razor Page, you could try IHttpContextAccessor.
For general way to handling user details from request, you could create a service like below:
public interface IUserService
{
    IdentityUser GetUser();
}

public class UserService:IUserService
{
    private readonly ApplicationDbContext _context;
    private readonly HttpContext _httpContext;

    public UserService(ApplicationDbContext context
        , IHttpContextAccessor httpContextAccessor)
    {
        _context = context;
        _httpContext = httpContextAccessor.HttpContext;
    }
    public IdentityUser GetUser()
    {
        StringValues userId = "";
        if (_httpContext.Request.Headers.TryGetValue("userId", out userId))
        {
            var user = _context.Users.FirstOrDefault(u => u.Id == userId);
            return user;
        }
        else
        {
            return null;
        }
    }
}

And then register like
    services.AddScoped<IUserService, UserService>();

Then, you could resolve IUserService from DI to use them when you want to access user info.
public class IndexModel : PageModel
{
    private readonly IUserService _userService;

    public IndexModel(IUserService userService)
    {
        _userService = userService;
    }

    public void OnGet()
    {
        var user = _userService.GetUser();
    }
}


text:
Q: Mongoose query not deep populating fully I have the following query:
const comments = await Comment.findById("comment1").populate({
  path: "replies",
  populate: [
    {
      path: "replies"
    }
  ]
});

This query yields the following JSON response:
{
    "parentCommentId": null,
    "_id": "comment1",
    "user": "user1",
    "text": "OP",
    "post": "post1",
    "replies": [
        {
            "parentCommentId": "comment1",
            "replyCount": 1,
            "_id": "comment2",
            "user": "user2",
            "text": "reply",
            "post": "post1",
            "replies": [
                {
                    "parentCommentId": "comment2",
                    "_id": "comment3",
                    "user": "user3",
                    "text": "reply to a reply",
                    "post": "post1",
                    "replies": [
                        "5d7757a2e6835f6d98ce723f" // <--- this is not populated
                    ]
                }
            ]
        }
    ]
}

For some reason, it is only populating the Comment document down two levels only, but I need it to go down all the way until the length of replies will be 0.
My schema:
const commentSchema = new Schema({
    parentCommentId: {
        type: String,
        default: null
    },
    replyCount: {
        type: Number,
        default: 0
    },
    user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "user"
    },
    text: {
        type: String,
        required: true
    },
    post: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "post"
    },
    replies: [
        {
        type: mongoose.Schema.Types.ObjectId,
        ref: "comment"
        }
    ]
});

Not sure what I am doing wrong here.

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP кукиес не работают. Можно удалить php? Не работают куки в PHP, имеем массив со всеми переводами текста: $local
ассоциативный массив в котором ещё массивы выглядит это всё примерно так
$local = array(
    'ru' => array(
        'title' => 'Название проекта',
        'authTitle' => 'Авторизация на проекте'
    ),
    'en' => array(
        'title' => 'Name project',
        'authTitle' => 'Sign in'
    )
);

По дефолту ключ страны равен предпочтением пользователя и выяснение кода страны выглядит примерно так:
$localCode = $_SERVER['HTTP_ACCEPT_LANGUAGE'];

if (isset($_COOKIE['lang'])) {//эта х+етень почему то возвращает false то биж он считает что НЕТУ куки lang но сам куки есть (в браузере зачекал)
    $lang = $_COOKIE['lang'];
} else {
    $lang = $localCode[0] . $localCode[1];//$localcode вернёт несколько кодов страны через запятую и мы выберем 2 первых символа тем самым выберем самый предпочитаемый язык пользователя
}

То биж если есть куки то код страны равен этому куки, если его нет то код страны равен первому предпочтению пользователя
В итоге когда я создаю куки lang:
session_start();

setcookie("lang", "en", time() + 3600);

Куки создаётся в браузере и принимает нужное значение, но когда я отдельном файле local.php я пытаюсь их использовать система считает что их просто нет
код с функцией выдачи нужного языка:

function lang ($name) {

    global $local;

    global $lang;

    echo $local[$lang][$name];
}

вынесен в отдельный файл и при создании куки lang он не хочет менять язык
Теперь про некоторые детали:

*

*Почему я сделал global $local и $lang вместо того что бы просто внести их в функцию. Ответ: имеется 2 функции которые дают нужный перевод и одна их них выводит этот перевод а другая возвращает его это нужно что бы я не писал миллион раз echo а когда нужно вернуть а не вывести просто применялась другая функция.

*Я не знаю обязательно ли начинать сессию в файле но в начале файла есть
session_start();

Ниже 3 картинки примеров кода как подключается local.php и сам код local.php в наглядности (его stackoverflow не хочет по красоте вставить)

A:
когда я отдельном файле local.php я пытаюсь их использовать система считает что их просто нет

setcookie() задает cookie, которое будет передано клиенту вместе с другими HTTP-заголовками. Как и любой другой заголовок, cookie должны передаваться до того как будут выведены какие-либо другие данные скрипта (это ограничение протокола). Это значит, что в скрипте вызовы этой функции должны располагаться до остального вывода, включая вывод тегов <html> и <head>, а также пустые строки и пробельные символы.
---> После передачи клиенту cookie станут доступны через массив $_COOKIE при следующей загрузке страницы. Значения cookie также есть в $_REQUEST. <---
*Источник: https://www.php.net/manual/ru/function.setcookie.php
Ответ простой - смотрите, где у Вас что не соответствует - или приведите полный код, с которым можно было разбираться.


text:
Q: WP Rest Api GET method restriction on route, but POST method also works I'm doing some basic API testing and notice that restricting my new route to GET doesn't work. POST requests also go though using Postman. (PUT, PATCH, DELETE do not however, displaying a "no matching route/method" error):
function displayDummyData() {
  return 'dummy data'; // responds 'dummy data' on POST request
}

function checkIfAnyone() {
  return true;
}

function registerDummyRoute() {
  register_rest_route('wp/v2', 'tut', [
    'methods' => 'GET',
    'callback' => 'displayDummyData',
    'permission_callback' => 'checkIfAnyone'
  ]);
}
add_action('rest_api_init', 'registerDummyRoute');

How can I restrict this route to only GET requests?


text:
Q: how to merge two array into one in python and numpy? I want to merge two arrays (a,b) ( each shape = (30,192,192,1)) into one (input) like this shape = (30,192,192,2).
Is there anyone who can help me?
My code is as below:
input = np.ndarray((a.shape[0], a.shape[1], a.shape[2],2))
input[:,:,:,0] = a
input[:,:,:,1] = b

but I get this error:
input[:,:,:,0] = a
ValueError: could not broadcast input array from shape (30,192,192,1) into shape (30,192,192)

A: You can reshape the a and b arrays before:
a=a.reshape((30,192,192))
input[:,:,:,0] = a


text:
Q: Google script notifies all email adresses everytime the script runs Is there a way to make it so you do not send a notification to the user's email when using addEditor(email) on Google script. Been looking through the references for Google developers and haven't found anything.

var ss = SpreadsheetApp.openById("1aU3MOdUKHEgGRCtVaSJs3iRqRIRhLSvpCuXzOVT7Ko8")
var sheet = ss.getSheetByName("Ark 1")
var range = sheet.getRange("B:C")
//Column B is the emails, and C is a list of Edit, View, None

var range_length = range.getValues().length + 1

function scriptTesting(row) {
  var scriptTesting = DriveApp.getFolderById("0B8FOoqX6_Y84eHZFaFBGTlJzMTQ")

  for (var a = 1; range_length > a; a++) {
     var email = range.getCell(a, 1).getValue()
     var choice = range.getCell(a, 2).getValue()

     if (choice == "Edit") {
     scriptTesting.addEditor(email)
     } else if (choice == "View") {
     scriptTesting.addViewer(email)
     } else if (email == "") {
     break
     } else if (choice == "None") {
       try {
       scriptTesting.removeViewer(email)
       } catch(err) {
         continue
       }
     } else {
     continue
     }
     }

}


text:
Q: What is $|a_n|$ of the power series $\sum_{n = 1}^{\infty}\frac{(-1)^n}{2n + 1} x^{2n + 1}$ What is $|a_n|$ of the power series $\sum_{n = 1}^{\infty}\frac{(-1)^n}{2n + 1} x^{2n + 1}$?
A power series has the form $\sum_{n = 1}^{\infty}a_nx^n$, so $|a_n| = \frac{1}{2n + 1}$ in this case. My professor wrote $|a_n|$ as a piece-wise function:
$|a_n| =
\begin{cases}
0 & \text{ if n even }  \\
\frac{1}{n}{} & \text{ if n odd }
\end{cases}
$
I don't really understand how he got those?

A: The powers of $x$ in your series is the set $\{1, 3, 5, 7, 9, ...\}.$ You see, it contains no even numbers. That's why you can say it's $|a_n| = 0$ if $n$ is even and $\frac{1}{n}$ if $n$ odd.

A: .......hint: what are the coefficients of the terms $a_{2n}x^{2n}$ ?


text:
Q: How to open up a popup in Zoho CRM I currently have a Zoho Blueprint for a conversion that sends a request to Stripe to create the customer, create and finalize an invoice and then send me the invoice payment link in Slack.
How could I open a popup in the window so the invoice link shows up right in my face in the browser?
I use Chrome.

A: I guess you are using Zoho CRM.
Solutions:

*

*The only way to create something like a popup is to create a button
that will display a message with the link you want.

*But it is possible to automatically open the link you
want when the button is pressed.

To implement any of those solutions you should have a field in each record you want to use to open/show the link via the button.
To create & automatically fill this field with Stripe invoice link follow the steps below:

*

*Create a URL field in the module from you want to show the URL
(Example: "Stripe Invoice Link").

*Create an automation that will fill this field with the returned
from Stripe link (when the link is generated in Stripe)

*Fill the new field in historical records if you want to open the
link from them.

Then you should create the button that will open/show the link you have stored in the field you created.

*

*Create a button (Example: "Show Stripe Invoice Link") in the module
you want to show the URL from.

*Add a function to this button.

*Add "recordID" parameter with the record ID value to this function.

The next step depends on what you want.
If you want to just show the link, copy the code below to this function:
record = zoho.crm.getRecordById("MODULE_API_NAME", recordId);
s = record.get("FIELD_API_NAME");
return s;

If you want to automatically open the link, copy the code below to this function:
record = zoho.crm.getRecordById("MODULE_API_NAME", recordId);
openUrl(record.get("FIELD_API_NAME"), "new window");
return null;


text:
Q: Where are my .pst files, for Outlook 2013? This answer introduced another problem with Outlook:  my computer lacks .pst files.

*

*4 of 5 email accounts are @outlook.com, and are listed as 'Exchange ActiveSync' under 'Type'. But these 4 are all personal accounts; they don't concern any servers or administrators.
1 is my work email, and is listed as 'IMAP/SMTP'.

*I confirm my selection to view all hidden files and folders.

*I tried searching for .pst files with Windows Explorer, but nothing emerged.

*I assume that Outlook ought have already created and then automatically updated .PSTs:

[Source:] Although the default install of Outlook creates a .PST file [...]

*The following quote discusses 3 methods. 6 simply led me to the same folder cited in 8, which contains only .ost files. No .pst files appear.

7 led me to F:\Documents\Outlook Files, but this was empty.

[Source:] The fastest way to open the folder where your Outlook Data File (.pst and .ost) is saved is to do the following:
[6.] I. In Outlook, click the File tab.
  II. Click Account Settings, and then click Account Settings.
  III. On the Data Files tab, click an entry, and then click Open Folder Location.
[7.] Outlook Data Files (.pst) created by using Outlook 2013 are saved on your computer in the Documents\Outlook Files folder.
[8.] If you upgraded to Outlook 2013 on a computer that already had data files that were created in Microsoft Office Outlook 2007 or earlier, these files are saved in a different location in a hidden folder at drive:\Users\user\AppData\Local\Microsoft\Outlook.

A: What are .ost and.pst files?

Outlook Data Files (.ost) are used when you have an Exchange account and want to work offline or use or use the default Cached Exchange Mode. This type of data file is also used for accounts that you set up with the Outlook Connector for Outlook.com (formerly Hotmail). Outlook Data Files (.ost) are always copies of items that are saved on a mail server and don't have to be backed up like Outlook Data Files (.pst).

Source Introduction to Outlook Data Files (.pst and .ost)

My computer seems to lack .pst files.

"4 (of 5) email accounts are @outlook.com, and are listed as 'Exchange ActiveSync', under 'Type'. However, these 4 are all personal accounts on my personal computer. They don't concern any servers or administrators.
1 (of the 5) is my work email, and is listed as 'IMAP/SMTP'."

This confirms that your email is using Microsoft Exchange (in the case of your work IMAP/SMTP account). The .ost files are from accounts that you have set up with the Outlook Connector for Outlook.com (formerly Hotmail).

Outlook Data Files (.ost) are always copies of items that are saved on a mail server and don't have to be backed up like Outlook Data Files (.pst).

The adminstrator of your work Exchange Server (in the case of your work IMAP/SMTP account) should be responsible for backing up the server (and your emails).
You might like to confirm with them that backups are actually taking place.
For the other email accounts @outlook.com then Microsoft is the administrator of 'your email server'

Do I need to backup an .ost file?

Some accounts use an offline Outlook Data File (.ost). This is a synchronized copy of the messages saved on a server and that can be accessed from multiple devices and applications such as Outlook. These accounts include IMAP, Microsoft Exchange Server, and Outlook.com accounts.
Offline Outlook Data Files are saved in
drive:\Users\user\AppData\Local\Microsoft\Outlook.
It isn't necessary to back up an offline Outlook Data File (.ost) as it is a copy of the information on the server. If you set up the account again or on another computer or device, a synchronized copy of your messages are downloaded from the server.

Source Create an Outlook Data File (.pst) to save your information

But I really want to backup these 4 .OST accounts
In this case you might like to backup the local .ost files using your normal backup program (or trust Microsoft not to mess up your accounts)
You can also export your mail as a .pst file by following the instructions in Exporting and Importing Mailbox Content in Outlook 2013.
The .pst file can then also be backed up using your normal backup program.
The advantage of using a .pst file is you can then import all of your email to another computer running Outlook.
Note:
If you access your email account from multiple computers or devices, it's important to know that when messages are moved to an Outlook Data File (.pst) they are available only on the computer where the file is saved.

Clarifications as per your comments.

You wrote Microsoft Exchange (in the case of your work IMAP/SMTP account). Does this mean a Microsoft Exchange account that also runs on IMAP/SMTP?

Microsoft Exchange can be configured to support IMAP/SMTP. It could also be some other mail server that supports IMAP/SMTP. Only your work IT department can answer this question.

How do I backup .ost files? Do I just copy and paste them onto backup storage (ie an USB, external hard drive)?

You can copy and paste but it is better to use a scheduled windows backup.

It's important to know that when messages are moved to an Outlook Data File (.pst) : How can email messages be moved to a .pst?

Email messages will be moved if you create a local archive, and drag and drop emails into the local archive.
You can configure Outlook to automatically move your emails to the local pst file if you wish. See How to Automatically Move Mails From Outlook to PST.
Note:
If you export your mail from .ost to .pst you are creating a copy of your email not moving it.

Further reading

*

*Archive or back up your mailbox (video)

*Create and use Personal Folders (Outlook Data Files) (video)

*Outlook 2013 training courses, videos and tutorials

A: Microsoft Outlook 2013 creates OST file by default. So if you're using Outlook 2013, there would be no PST file. Why don't you read this article https://support.microsoft.com/en-us/kb/2752583


text:
Q: Java Assertion in getter method Lets say we have this code:
Owner owner;
public Owner getOwner(int id)
{
    if (owner == null)
        owner = Owners.getOwner(id);
    assert owner != null;
    return owner;
}

What will happen if the Owners.getOwner(id) returns null? will the method die or it will still return null if an assertion is added before the return?
if getOwner(id) is asserted to null will still throw an NPE if getOwner(id).doSomething(); is called?

A: Assertions can be turned on and off to run a program, and are off by default. If they are turned on and their condition is triggered the JVM throws an AssertionError. From your comments it seems that you don't have assertions enabled.
Because assertions can go away, you shouldn't base application logic on assertions: if you want to raise an error in a certain unexpected situation, throw an exception.


text:
Q: Change from .apply() to a function that uses list comprehension to compare one dataframe with a column of lists to values in another dataframe Simply put, I want to change the following code into a funtion that doesn't use apply or progress_apply, so that the performance doesn't take 4+ hours to execute on 20 million+ rows.
d2['B'] = d2['C'].progress_apply(lambda x: [z for y in d1['B'] for z in y if x.startswith(z)])
d2['B'] = d2['B'].progress_apply(max)

Full question below:
I have two dataframes. The first dataframe has a column with 4 categories (A,B,C,D) with four different lists of numbers that I want to compare against a column in the second dataframe, which is not a list like in the first dataframe but instead just a single value that will start with one or more values from the first dataframe. As such, after executing some list comprehension to return a list of matching values in a new column in the second dataframe, the final step is to get the max of those values per list per row:
d1 = pd.DataFrame({'A' : ['A', 'B', 'C', 'D'],
               'B' : [['84'], ['8420', '8421', '8422', '8423', '8424', '8425', '8426'], ['847', '8475'], ['8470', '8471']]})

    A   B
0   A   [84]
1   B   [8420, 8421, 8422, 8423, 8424, 8425, 8426]
2   C   [847, 8475]
3   D   [8470, 8471]

d2 = pd.DataFrame({'C' : [8420513, 8421513, 8426513, 8427513, 8470513, 8470000, 8475000]})

    C
0   8420513
1   8421513
2   8426513
3   8427513
4   8470513
5   8470000
6   8475000

My current code is this:
from tqdm import tqdm, tqdm_notebook
tqdm_notebook().pandas()
d1 = pd.DataFrame({'A' : ['A', 'B', 'C', 'D'], 'B' : [['84'], ['8420', '8421', '8422', '8423', '8424', '8425', '8426'], ['847', '8475'], ['8470', '8471']]})
d2 = pd.DataFrame({'C' : [8420513, 8421513, 8426513, 8427513, 8470513, 8470000, 8475000]})
d2['C'] = d2['C'].astype(str)
d2['B'] = d2['C'].progress_apply(lambda x: [z for y in d1['B'] for z in y if x.startswith(z)])
d2['B'] = d2['B'].progress_apply(max)
d2

and successfully returns this output:
    C       B
0   8420513 8420
1   8421513 8421
2   8426513 8426
3   8427513 84
4   8470513 8470
5   8470000 8470
6   8475000 8475

The problem lies with the fact that the tqdm progress bar is estimating the code will take 4-5 hours to  run on my actual DataFrame with 20 million plus rows. I know that .apply should be avoided and that a custom function can be much faster, so that I don't have to go row-by-row. I can usually change apply to a function, but I am struggling with this particular one. I think I am far away, but I will share what I have tried:
def func1(df, d2C, d1B):
    return df[[z for y in d1B for z in y if z in d2C]]

d2['B'] = func1(d2, d2['C'], d1['B'])
d2

With this code, I am receiving ValueError: Wrong number of items passed 0, placement implies 1 and also still need to include code to get the max of each list per row.

A: Let's try, using explode and regex with extract:
d1e = d1['B'].explode()
regstr = '('+'|'.join(sorted(d1e)[::-1])+')'
d2['B'] = d2['C'].astype('str').str.extract(regstr)

Output:
         C     B
0  8420513  8420
1  8421513  8421
2  8426513  8426
3  8427513    84
4  8470513  8470
5  8470000  8470
6  8475000  8475

Since, .str access is slower than list comprehension
import re
regstr = '|'.join(sorted(d1e)[::-1])
d2['B'] = [re.match(regstr, i).group() for i in d2['C'].astype('str')]

Timings:
from timeit import timeit
import re

d1 = pd.DataFrame({'A' : ['A', 'B', 'C', 'D'], 'B' : [['84'], ['8420', '8421', '8422', '8423', '8424', '8425', '8426'], ['847', '8475'], ['8470', '8471']]})
d2 = pd.DataFrame({'C' : [8420513, 8421513, 8426513, 8427513, 8470513, 8470000, 8475000]})
d2['C'] = d2['C'].astype(str)

def orig(d):
    d['B'] = d['C'].apply(lambda x: [z for y in d1['B'] for z in y if x.startswith(z)])
    d['B'] = d['B'].apply(max)
    return d

def comtorecords(d):
    d['B']=[max([z for y in d1.B for z in y if str(row[1]) .startswith(z)]) for row in d.to_records()]
    return d

def regxstracc(d):
    d1e = d1['B'].explode()
    regstr = '('+'|'.join(sorted(d1e)[::-1])+')'
    d['B'] = d['C'].astype('str').str.extract(regstr)
    return d

def regxcompre(d):
    regstr = '|'.join(sorted(d1e)[::-1])
    d['B'] = [re.match(regstr, i).group() for i in d['C'].astype('str')]
    return d

res = pd.DataFrame(
    index=[10, 30, 100, 300, 1000, 3000, 10000, 30000],
    columns='orig comtorecords regxstracc regxcompre'.split(),
    dtype=float
)

for i in res.index:
    d = pd.concat([d2]*i)
    for j in res.columns:
        stmt = '{}(d)'.format(j)
        setp = 'from __main__ import d, {}'.format(j)
        print(stmt, d.shape)
        res.at[i, j] = timeit(stmt, setp, number=100)

# res.groupby(res.columns.str[4:-1], axis=1).plot(loglog=True);
res.plot(loglog=True);

Output:

A: I have found yet faster solution, compared to both propositions of Scott.
def vect(d):
    def extr(txt):
        mtch = pat.match(txt)
        return mtch.group() if mtch else ''
    d1e = d1.B.explode()
    pat = re.compile('|'.join(sorted(d1e)[::-1]))
    d['B'] = np.vectorize(extr)(d.C)
    return d

One speed gain is from prior compilation of the regex.
The second gain is due to use of a Numpy vectorization, instead of
a list comprehension.
Running a testing loop like the one employed by Scott, I received
the following result:

So "my" execution time (the red line), especially for larger data volumes,
is about 60 % of both regxstracc and regxcompre.

A: Try explode the d1 so we reduce one for loop
[max([z for z in d1.B.explode() if  x.startswith(z)]) for x in d2.C.astype(str) ]

['8420', '8421', '8426', '84', '8470', '8470', '8475']

A: Using re.compile() to compile the pattern prior to execution (i.e. outside of the 'loop') helps a lot when solving these big data row-by-row 'requires a custom solution that isn't a NumPy vector function already' problems.
Using the correct flags when compiling a pattern is work checking too.
Not to sound like a broken record but with NLP/text processing it's definitely significant.
Another suggestion: Also use efficient chunking.
Each computing project has some X memory threshold and some Y processing threshold; balancing these by chunking helps improve execution speed.
Pandas chunking with its read/write functions are useful from my experience.
Finally, if you are executing I/O operations you might squeeze out some extra performance mapping the function within a ThreadPoolExecutor (A quick google can give you some good template code, and the documentation explains the utility well; I found the template code from documentation hard to implement at first so I'd check other resources).
Best of luck!


text:
Q: How to render Multiple PDFs from a single Visualforce page? I working on a visualforce page (running a tabular report) with a table (13 columns) and am rendering a PDF as well for this.
Firstly, all the columns are not fitting in a single PDF. Secondly, how do I turn the PDF into a landscape mode, like a full width of the browser. Thirdly, is there a way through which I could render in multiple PDFs for the single VF page (the 13 columns coming in probably 2 PDFs).
Any suggestion on how to achieve these.

A:
Firstly, all the columns are not fitting in a single PDF.

Use fewer columns, a smaller font, or some other design, such as a multi-line row. You can't go as wide as you'd like, that's a limitation of Flying Saucer, the underlying rendering engine.

Secondly, how do I turn the PDF into a landscape mode, like a full
  width of the browser.

Use the following CSS:
@page { size: A4 landscape; }

Thirdly, is there a way through which I could render in multiple PDFs
  for the single VF page (the 13 columns coming in probably 2 PDFs).

You can render as many PDFs as you'd like, assuming you don't run into other limits, such as CPU time. If each row is the same height, you could render the table in two parts, say 7 columns and 6 columns. You can use the CSS page-break-after: always to effectively re-align the tables without much effort. It would look like:


text:
Q: Default struct values In Go I get that there are default values for types.  Take int in this case which is initialised as a 0.
I have an issue where for me a 0 in an int can be a valid value so I need to check if it's been set by me or initialised as such.  Is there any way to tell the difference between them at all?
Considering the following code... I need to be able to tell the difference between testIntOne and testIntTwo but they look the same!
package main

import "log"

type test struct {
    testIntOne int
    testIntTwo int
}

func main() {
    s := test{testIntOne: 0}

    log.Println(s)
}

A: You can't tell the difference, it is not tracked whether a field (or a variable) has been set or not.
Using a pointer
You may use a pointer which has a nil zero value, so if not set, you can tell:
type test struct {
    testIntOne *int
    testIntTwo *int
}

func main() {
    s := test{testIntOne: new(int)}

    fmt.Println("testIntOne set:", s.testIntOne != nil)
    fmt.Println("testIntTwo set:", s.testIntTwo != nil)
}

Output (try it on the Go Playground):
testIntOne set: true
testIntTwo set: false

Of course new() can only be used to obtain a pointer to an int value being 0. See this question for more options: How do I do a literal *int64 in Go?
Using a method
You may also use a method to set a field, which could take care of additionally tracking the "isSet" property. In this case you must always use the provided method to set the field. Best is to make fields unexported, so others (outside your package) won't have direct access to them.
type test struct {
    testIntOne int
    testIntTwo int

    oneSet, twoSet bool
}

func (t *test) SetOne(i int) {
    t.testIntOne, t.oneSet = i, true
}

func (t *test) SetTwo(i int) {
    t.testIntTwo, t.twoSet = i, true
}

func main() {
    s := test{}
    s.SetOne(0)

    fmt.Println("testIntOne set:", s.oneSet)
    fmt.Println("testIntTwo set:", s.twoSet)
}

Output (try it on the Go Playground):
testIntOne set: true
testIntTwo set: false


text:
Q: Core Data: restore from backup on different device Data saved with Core Data is part of the iTunes backup, so if you 'backup and restore' on your phone all your application data should be back.
I have been getting user reports that when migrating to a different device like a new phone, a 'restore from backup' on the new phone does not restore the application data. Are there any further means necessary to fix this? Unfortunately I don't have a second device at hand for verification. Thank you


text:
Q: Prove $ \langle g^k\rangle = \langle g^{\gcd(n,k)}\rangle$ Let $g\in G$, $G$ a group. Let $|g|=n.$
Prove $ \langle g^k\rangle = \langle g^{\gcd(n,k)}\rangle$.
Denote $d=\gcd(n,k) , (g^{d})^x\in\langle g^{d}\rangle , x\in \mathbb {Z}$.
Since $d=\gcd(n,k) \space \exists a,b\in \mathbb{Z}$ such that $d=an+bk$.
$$\begin{align}
(g^{d})^x &=(g^{an+bk})^x\\
&=(g^n)^a (g^{bk})^x\\
&=(g^{k})^{bx} \\
&\overset{s=bx}{=}(g^{k})^{s} \in \langle g^k\rangle
\end{align}$$
Is my proof correct?
Thanks!


text:
Q: Why does not work for default shipping method? For WooCommerce I want to default DHL. But it doesn't work, why is that? In WooCommerce from WordPress.
You can see here: img. Way - functions.php
function reset_default_shipping_method( $method, $available_methods ) {

    if ( ! empty( $method ) ) {
        return $method;
    }

    $method = 'shipping_method_0_flat_rate9';

    return $method;
}

add_filter('woocommerce_shipping_chosen_method', 'reset_default_shipping_method', 10, 2);

A: The filter has been updated you should try this.
I've tested it and it works for me.
Also, the default shipping is stored in your session so if you want to test it you can try from a new browser or log out and log back in.
 function prefix_reset_default_shipping_method( $default, $package, $chosen_method ) {

        if( $default !== 'flat_rate:9')
            $default = 'flat_rate:9';

        return $default;

    }

    add_filter('woocommerce_shipping_chosen_method', 'prefix_reset_default_shipping_method', 10, 3);

A: function reset_default_shipping_method( $method, $available_methods ) {
    $default_method = 'wf_fedex_woocommerce_shipping:FEDEX_GROUND'; //provide here the service name which will selected default
    if( array_key_exists($method, $available_methods ) )
        return $default_method;
    else
        return $method;
}
add_filter('woocommerce_shipping_chosen_method', 'reset_default_shipping_method', 10, 2);

Add this to your theme's functions.php changing the $default_method var.
source: https://www.xadapter.com/set-default-shipping-method-woocommerce/


text:
Q: ASP.NET MVC Synchronous vs Asynchronous WCF calls I working on an ASP.NET MVC which is loading its data completely via a WCF service. What my model does is just call the WCF service. The controller then passes the model to the view. I read in this article that it is always better to do async calls if you can. However I am still not sure which call to use. What would happen if the data form the service takes a while to load? Does it mean that my controller code will keep running and if the data is not there when the return statement is reached my controller will return an empty view, which could also cause a null pointer exception because of the view accessing unpopulated model fields?

A: If your controller returns a Task then you will be fine. If you are on C# 5.0 you can use async/await to make your code more maintainable than what is shown in the article. Basically your code will look like this
public async Task<ActionResult> SomeAction()
{
    var someData = await wcfServiceProxy.GetDataAsync() //alternatively an async call to your model service which should also be async
    //some work with the data here
    return View(someData);
}

or you can just not care and use all synchronous calls. The downside of using synchronous calls is that your throughput would suffer. You will be able to handle 200 requests per second instead of 50K requests per second (and I am pulling these numbers out of thin air). Of course in most cases you simply don't care because your project never does more than 20 requests per second.


text:
Q: java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to model class android I am passing the response of an API call (Retrofit used) to a class and trying to cast it to my model class. Since i am using retrofit for the API call, it generates a linked hashmap based on the response from the server prior to convert it into model class object using Gson. (That is what i understand, correct me if i am wrong). I have attached an image of what i can see when i debug with the response object. How can i convert this response into an object of my model class or type Object. I am getting class cast exception when i attempt to cast type Object into my model class inside my activity.
Here is my code
API Call
call.enqueue(new Callback() {

        @Override
        public void onResponse(Call call, Response response) {
            if (response.body() != null) {
                        List<CategoriesBaseModel> categoryBaseResponseList = (List<CategoriesBaseModel>) response.body();
                        List<Object> categoryResponseList = (List<Object>) categoryBaseResponseList.get(0).getData();
                        if (categoryResponseList != null) {
                           mCategoriesInterface.passCategoriesResponse(categoryResponseList, "HomeFragment");
                        }
            }
        }
        @Override
        public void onFailure(Call call, Throwable t) {

            call.cancel();
        }
    });

Activity
CategoriesInterface categoriesInterface = new CategoriesInterface() {
    @Override
    public void passCategoriesResponse(List<Object> scheduleList, String name) {
        CategoriesModel categoriesModel;
        for (Object model : scheduleList){
            categoriesModel = (CategoriesModel) model;
            Log.d("TAG", "");
        }
    }
};

A: Solved this by converting the Object into Json string and coverting it back directly to the model class object.
Gson gs = new Gson();
String js = gs.toJson(model);
categoriesModel = gs.fromJson(js, CategoriesModel.class);


text:
Q: Using the split function to group a dataframe by factor, alternatives for large dataframes I have a question regarding using the split function to group data by factor.
I have a data frame of two columns snps and gene. Snps is a factor, gene is a character vector. I want to group genes by the snp factor so I can see a list of genes mapping to each snp.  Some snps may map to more than one gene, for example rs10000226 maps to gene 345274 and gene 5783, and genes occur multiple times.
To do this I used the split function to make a list of genes each snp maps to.
snps<-c("rs10000185", "rs1000022", "rs10000226", "rs10000226")

gene<-c("5783", "171425", "345274", "5783")

df<-data.frame(snps, gene)  # snps is a factor

df$gene<-as.character(df$gene)

splitted=split(df, df$gene, drop=T) # group by gene

snpnames=unique(df$snps)

df.2<-lapply(splitted, function(x) { x["snps"] <- NULL; x })   # remove  the snp column

names(df.2)=snpnames    # rename the list elements by snp

df.2 = sapply(df.2, function(x) list(as.character(x$gene)))

save(df.2, file="df.2.rda")

However this is not effective for my full dataframe (probably due to its size - 363422 rows, 281370 unique snps, 20888 unique genes) and R crashes whilst trying to load df.2.rda` later on.
Any suggestions for alternative ways to do this would be much appreciated!

A: There is a shorter way to create your df.2:
genes_by_snp <- split(df$gene,df$snp)

You can look at the genes for a given snp with genes_by_snp[["rs10000226"]].

Your data set does not sound so big to me, but you could avoid creating the list above by storing your original data differently. Expanding on @AnandoMahto's comment, here's how to use the data.table package:
require(data.table)

setDT(df)
setkey(df,snps)

You can look at the genes for a given snp with df[J("rs10000226")].


text:
Q: Setting Manual charset in PHP casing internal server error I my project the data stored in mysql DB is in Bangla language. To handle Bangla i need utf-8 unicode encoding. So i have manually set encoding in php file-
mysqli_query($connect, "SET NAMES 'utf8'");

But on adding it it is showing 500 Internal Server Error.
The project link is
http://www.goraifilms.com/heros/showdata.php
Please help. Thanks in advance

A: Try using this instead:
//assuming $connect is your connection
$connect = mysqli_connect($host, $user, $password, $database);
$connect->set_charset('utf8');


text:
Q: Trazer determinado campo, pelo MAX(ID) Como eu faço para trazer um campo qualquer, pelo maior ID da tabela. Fiz um MAX(Campo1), Campo2 e tive que fazer um agrupamento pelo Campo2 e o resultado ele me trouxe vários Campo2 e não apena um, que tenha o maior ID.
Select MAX(ID), campo2 from tabela where campo3 = valor group by campo2

Isso não deu certo, me trouxe vários campo2

A: Se você quer simplesmente trazer o maior Id da tabela, apenas isso resolve:
Select MAX(ID) from tabela;

Afinal, Id é único e não precisa agrupar valores.
Se você precisa trazer outro campo baseado no MAX(ID), o correto é:
select campo2
from tabela
where ID = (select MAX(ID) from tabela);

A: Assim resolveu, mas tive que colocar uma subquery na jogada
select campo2 from tabela where campo3= 49 and campo1  in (select max(campo1) from tabela where campo3 = 49)

Aí resolveu.


text:
Q: Using external jar as dependency file while running spring boot jar I have a Maven-Springboot project setup. After doing a mvn install I can run the jar file in command prompt using java -jar <my-jar-file.jar>
There was a dependency to a jar say as-common-1.0.0.jar that is there in my-jar-file.jar. Now I want to override the version of this dependent jar at run time by giving an external jar. something like:
java -jar my-jar-file.jar using as-common-1.0.1.jar

I went through many SO posts like thisinclude external jar when running java -jar but they didn't help.
is it achievable?
EDIT: The issue we have is many of our applications depend upon one of our internal framework jar which gets updated(version) often.
So every time changing the pom file and re-deploying all the apps doesn't look feasible to us. We want somehow the dependency of this particular jar is given at run time. Any idea regarding best possible way to manage this scenario?

A: No, this is not sensible. At best, you would load classes twice and this may/may not work.
If you build a complete jar containing everything, you cannot swap content at runtime. You need to rebuild it.


text:
Q: Как грамотно распределить код PHP и поправить файл с CSS-стилями? Подскажите, есть ли какие-нибудь средства разработки, в которых можно было бы быстро и грамотно выделить код, к примеру PHP?
К примеру, есть код в "быдло"виде:
function DateForm($date) {
global $weekday,$months,$offset,$dformat,$tformat;
$date = $date+30*24*60*60;
list($wday,$mday,$month,$year,$hour,$minutes,$hour12,$ampm) = explode("( )",date("w j n Y H i h A",$date));
if ($tformat == "AMPM") {
$newtime = " $hour12:$minutes $ampm";
} else {
$newtime = " $hour:$minutes";
}
if ($dformat == "USx") {
$newdate = " $month-$mday-$year";
} elseif ($dformat == "US") {
$month -= 1;
$newdate = "$weekday[$wday], $months[$month] $mday, $year";
} elseif ($dformat == "Euro") {
$month -= 1;
$newdate = "$weekday[$wday], $mday. $months[$month] $year";
} else {
$newdate = "$mday.$month.$year";
}
return $date;
return ($newdate=$newdate.$newtime);
}

В какой программе можно выделить его красиво с учетом вложенностей и привести его к такому виду с отступпами:
  function DateForm($date) {

  global $weekday,$months,$offset,$dformat,$tformat;

  $date = $date+30*24*60*60;

  list($wday,$mday,$month,$year,$hour,$minutes,$hour12,$ampm) = explode("( )",date("w j n Y H i h A",$date));

  if ($tformat == "AMPM") {
      $newtime = " $hour12:$minutes $ampm";
  } else {
      $newtime = " $hour:$minutes";
  }

  if ($dformat == "USx") {
      $newdate = " $month-$mday-$year";
  } elseif ($dformat == "US") {
      $month -= 1;
      $newdate = "$weekday[$wday], $months[$month] $mday, $year";
  } elseif ($dformat == "Euro") {
      $month -= 1;
      $newdate = "$weekday[$wday], $mday. $months[$month] $year";
  } else {
      $newdate = "$mday.$month.$year";
  }

  return $date;
  return ($newdate=$newdate.$newtime);

}

Сейчас я работаю в PHP Expert Editor.
Также, хотелось бы узнать, как можно поправить файл css-стилей... привести его к виду с отступами.
A: В PhpStorm комбинацией клавиш Ctrl+Alt+L. Можно форматировать как выделенный фрагмент кода, весь файл или все файлы в директории.

Так же есть куча настроек того, как  форматировать код. Вы сами можете задавать стиль, если например в компании используется определенное форматирование, достаточно настроить форматирование на одной машине, экспортировать настройки в виде xml файла и импортировать на остальные машины, тем самым у всех будет единый формат кода.
PhpStrom умеет форматировать не только PHP:

*

*Желтый - поддерживаемые языки

*Зеленый - опции

*Красный - как будет выглядеть код после форматирования


text:
Q: Как получить класс из класса selenium? я не могу получить класс из класса Selenium.
К примеру есть такая html страница

 Иван

 Иванов

Я пытаюсь сделать так driver.find_element(By.CLASS_NAME,"element").get_attribute("first_name")
но не выходи.

A: Например, так:
driver.find_element(By.CLASS_NAME, "element").find_element(By.CLASS_NAME, "first_name")

Если вам нужен не сам элемент, а текст "Иван" - добавьте .text:
driver.find_element(By.CLASS_NAME, "element").find_element(By.CLASS_NAME, "first_name").text


text:
Q: List - distinction by T.field I have a List<X> where X has a couple of fields:
public string word;
public int count;

how do I get a List<X> with distinct X.word elements?

A: You can use grouping
var n = from n in items
    group n by n.word into g
    select g.First();

A: MoreLinq has a DistinctBy method:
var distinctByWord = list.DistinctBy(x => x.Word).ToList();

A: From your data structure, I'd suggest you probably want a Dictionary instead of a list.
If you are doing something like counting the number of times a word is seen, or even combining (word,count) pairs from some other input by adding the counts, it will be more efficient to do this with a Dictionary because you won't have to scan the list to find the entry to update.

A: You'll need to use the overload of the Distinct method that takes an instance of IEqualityComparer<X>:
new List<X>().Distinct(new XComparer());

public class XComparer : IEqualityComparer<X> {
    public bool Equals(X x, X y) {
        return x.word.Equals(y.word);
    }

    public int GetHashCode(X obj) {
        return obj.word.GetHashCode();
    }
}

public class X {
    public string Word { get; set; }
    public int Count { get; set; }
}

And then:
var myList = new List<X>() {
    new X(){ Count = 1, Word = "A" },
    new X(){ Count = 2, Word = "A"},
    new X(){ Count = 1, Word = "B"}
};

foreach(var x in myList.Distinct(new XComparer()))
    Console.WriteLine(x.Count + " " + x.Word);

Prints:
1  A
1  B

A: I think the idea is to count the words and not to lose counts for words with the same name, right? If so, it reminds me map-reduce algorithm. You have already done map, so you need to do reduce somehow. I recommend you to create new Dictionary<string,int> and loop your list. If Dictionary does not have word - add it (key - word, count - value), if has - add count to value.


text:
Q: command prompt display "This should not be &" When I open CMD, display "This should not be &."

I tried to look for "&" in the environment variable, but nothing here

How can I solve it?

A: The problem, based upon the answers you've supplied in your comments, is that you have a rogue entry in your registry. Your response to my initial comment is not really a permanent fix, for anything, I only used that to determine what your issue was.
As you've not yet replied to second comment I have not been able to determine the exact location of that entry. For that reason I will offer two possible solutions.
If when you open a new Command Prompt window, cmd, using the Run as administrator option, the issue is not there, then copy and paste the following, then press the ENTER key.
%SystemRoot%\System32\reg.exe Delete "HKCU\SOFTWARE\Microsoft\Command Processor" /V AutoRun /F >NUL

If the issue still exists when you opened using the Run as administrator option, copy and paste the following, then press the ENTER key.
%SystemRoot%\System32\reg.exe Delete "HKLM\SOFTWARE\Microsoft\Command Processor" /V AutoRun /F >NUL

Your issue should now be permanently resolved.


text:
Q: Intermediate components on nested routes As in the documentation for vue-router say I have the following rout configuration:
const router = new VueRouter({
  routes: [
    {
      path: '/user/:id',
      component: User,
      children: [
        {
          // UserProfile will be rendered inside User's <router-view>
          // when /user/:id/profile is matched
          path: 'profile',
          component: UserProfile
        },
        {
          // UserPosts will be rendered inside User's <router-view>
          // when /user/:id/posts is matched
          path: 'posts',
          component: UserPosts
        }
      ]
    }
  ]
})

My question is about the User component. If I access /user/:id/profile followed by /user/:id/posts will the User component be render 0, 1, or 2 times?


text:
Q: Is it possible to have a subform that changes based on a indirectly related form? I have a database structure in this format: Relationship Structure
I have worked out how to attach a subform which displays children of a particular record:
Ex 1
Ex 2
However, I can't seem to find a way of having a subform listing the related grandchildren of a record. For example, all formulations that reference a particular material.

A: Don't bind your subform directly to the table, but bind it to a query instead.
Handle the Child - Grandchild relation in the query, and the parent-child relation in the form, like you're already familiar with.


text:
Q: AsyncHTTPClient, Netty HashedWheelTimer .waitForNextTick() и четыре секунды задержки Пишу свой (NIH) API-клиент, используя AsyncHttpClient в качестве транспорта. Столкнулся с проблемой долгой инициализации Netty (которая входит в состав AsyncHttpClient), в логах это выглядит примерно так:
15:22:03.188 [main] DEBUG io.netty.util.internal.logging.InternalLoggerFactory - Using SLF4J as the default logging framework
15:22:03.207 [main] DEBUG io.netty.util.ResourceLeakDetector - -Dio.netty.leakDetection.level: simple
15:22:03.210 [main] DEBUG io.netty.util.ResourceLeakDetector - -Dio.netty.leakDetection.maxRecords: 4
...
15:22:04.317 [main] DEBUG io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.normalCacheSize: 64
15:22:04.317 [main] DEBUG io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.maxCachedBufferCapacity: 32768
15:22:04.317 [main] DEBUG io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.cacheTrimInterval: 8192
15:22:08.447 [main] DEBUG me.etki.grac.ClientBuilder - Building client

К моменту последней строки из моего кода вызывается только создание ClientBuilder'а и обвязок для AsyncHTTPClient, чтобы он соответствовал моим интерфейсам, т.е. всего ничего, и никаких тяжеловесных I/O операций там точно нет.
С брейкпоинтами, JVisualVM и грехом пополам удалось увидеть, что эти четыре секунды тратятся на io.netty.util.HashedWheelTimer$Worker.waitForNextTick() (точнее, 99% загрузки за эти четыре секунды приходилось на этот метод, а блокировать могло что-то другое). Про safe points знаю, нормальным профайлером пока что обдавать это дело не приходилось - это просто минимум информации, которую удалось собрать.
Вопрос: как мне выяснить причину утечки времени старта? Может, кто-то уже имел аналогичные проблемы с Netty?


text:
Q: How to find the value of the parameter a in this transfer function?
Possible Duplicate:
How to find the value of the parameter $a$ in this transfer function?

I am given a transfer function of a second-order system as:
$$G(s)=\frac{a}{s^{2}+4s+a}$$
and I need to find the value of the parameter a that will make the damping coefficient $$\zeta=.7$$ I am not sure how to do this but I might have found something that might have helped so I am going to take a stab at it. I found a transfer function in the book of a second order spring-mass-damper system with an external applied force in the book as:
$$G(s)=\frac{a}{m\omega_{n}^{2}}(\frac{\omega_{n}^{2}}{s^{2}+2\omega_{n}\zeta+\omega_{n}^{2}})$$
I was thinking that I could writeZx:
$$2\omega_{n}^{2}\zeta=4$$ and $$\omega_{n}^{2}=a$$
asd
And then solve for a. Would this be possible?

A: A general second order equation is given as
                 G(s)= ω^2/(s^2+ 2ζω+ω^2 )

Hence, ω = √a,
   2ζω = 4

Solving yeild a=8.163 rad/sec
So, I guess you were headed in the right direction. :)


text:
Q: Inverse of Next Siblings Selector So I came across the Next Sibling Selector on the jQuery docs today:
$("label + input")

And was wondering - is there an inverse of this selector? i.e. select the Previous Sibling?
I could use:
$("label + input").prev()

For example in this fiddle, I get all labels in which a label is followed by an input, which is what I want, but is this the only way to do it?

A: You can use array provided by sibling()
Check this out:
http://api.jquery.com/category/traversing/tree-traversal/


text:
Q: Handle any error in NUnit I have got a standard NUnit unit test.
    [TestFixture]
    public class MyTest
    {
        [SetUp]
        public virtual void Setup()
        {
        }

        [TearDown]
        public void CleanUp()
        {
        }

        [Test]
        public void Test01()
        {
            Assert.AreEqual(10, 10);
        }

        [Test]
        public void Test02()
        {
            Assert.AreEqual(4, 1);
        }

        [Test]
        public void Test03()
        {
            Assert.AreEqual(1, 51);
        }

        //......a huge amount of Tests
        [Test]
        public void TestN()
        {
            Assert.AreEqual(1, 1);
        }
 }

As you see, there are a lot of tests here. What I need to do is to handle any error in each test and to get the information about the error without modifying the body of a test method.
So in JUnit there is an interface called TestListener which allows to handle any test error, see the error message, see the name of the test,  etc.
I didn't find something similar in NUnit. Does it exist? Or is there is a way to do it?

A: It sounds like you probably want EventListeners:

EventListeners are able to respond to events that occur in the course of a test run, usually by recording information of some kind. Note that EventListeners called asynchronously with respect to test execution and are not able to affect the actual execution of the test.

It sounds like you'll be interested in this method:
void TestFinished(TestResult result);

(As an aside, it seems odd to me that this doesn't use normal .NET events or provide a no-op interface implementation in an abstract class, but there we go...)


text:
Q: async pattern in a top-level worker method We have some worker threads in a web role. It is created in the OnStart method
Task.Factory.StartNew(() => DoWorkAsync(), TaskCreationOptions.LongRunning);

Then the DoWorkAsync method will continue polling the queue and do some time consuming work. The actual work takes several minutes as it submits a query job and waits for the result to come back. Those functions are in async pattern. What's the right way to implement the top-level DoWorkAsync method? If I do the following, then it's kind of blocking here, and only one PollingQueueAndWorkAsync() is called.
public async void DoWorkAsync()
{
  while (_continue)
  {
    await PollingQueueAndWorkAsync();
  }
}

Or the following? It doesn't look right as it keeps running the method in a different thread.
public async void DoWorkAsync()
{
  while (_continue)
  {
    Task.Run(() => PollingQueueAndWorkAsync());
  }
}

I was trying the refactor the code to be "async all the way". But how should it end in the top-level worker method?
[Update]
After trying more, here is what I have:
public async void DoWorkAsync()
{
  while (_continue)
  {
    Task.Run(async () => await PollingQueueAndWorkAsync());
  }
}

The behavior is what I want, since new messages keep adding to the queue, this loop can process as many as messages in the queue. However after running this for a while, it throws our of memory exception. Is it because it creates too many continuations? So I should use SemaphoreSlim to throttle number of tasks?

A: I generally discourage code executing in ASP.NET that is not tied to a request. However, if it is carefully written as an independent worker (and it sounds like it is), then you can use the BackgroundTaskManager type from my blog.
BackgroundTaskManager understands both synchronous and asynchronous tasks, and these tasks are registered with the ASP.NET runtime to minimize the chance that a recycle will terminate them unexpectedly. Also, the type exposes a CancellationToken called BackgroundTaskManager.Shutdown which your PollingQueueAndWorkAsync can use to detect when it should exit cleanly.

A: You should create your polling threads like this:
public async void DoWorkAsync()
{
    await Task.Run(() => PollingQueueAndWorkAsync());
}

Then you should check for '_continue' within the threads themselves, so they can exit cleanly when the work is cancelled.


text:
Q: multiple modals on my page shows the same images I have been researching trying to figure out why its doing this, maybe I just dont understand modals. IDK.
Anyways what is happening is I started with a light box: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_js_lightbox
and changed the body to:

Title

     ×

1 / 4

2 / 4

3 / 4

4 / 4

         ❮
         ❯

to create a single image in the modal, and to scroll through it.  I love it, and I thought that it would solve my issue. Alas
When I implemented it in my web page it worked. but then I copied and pasted, and it in another area of the page, changed the images, but it is still showing the original images from the first modal.  So I dont know where to turn.
I have 0 experience in jscript, jquery.  (those classes are yet to come in my schooling...).
I was thinking:
1.) have the images on an external html page and import that I have looked at AJAX, but im confused. (dont necessarily want to use bootstrap)
I have looked at these resources, and they kinda help but again, I dont know how to craft them to my needs.
using Bootstrap
modals, nonimported html
modals

See the Pen Work issue by Michael Barnhouse (@Kardee785) on CodePen.

A: So as Curious 13, and Nate Whittaker Suggested I needed to make each section have its own unique Id.  I had posted that that didn't work, and the reason it didnt work was because my .js wasnt reading/importing what to display.  So I had to create a var in js (named modalId), and then call that information into the opening, closing, and navigating of the modal.
Here is the .js, I had one of my friends help me with.
function openModal(modalId) {
  document.getElementById(modalId).style.display = "block";
}

function closeModal(modalId) {
  document.getElementById(modalId).style.display = "none";
}

var slideIndex = 1;
showSlides(slideIndex);

function plusSlides(modalId, n) {
  showSlides(modalId, slideIndex += n);
}

function currentSlide(modalId, n) {
  showSlides(modalId, slideIndex = n);
}

function showSlides(modalId, n) {
  var i;
  var modal = document.getElementById(modalId);
  var slides = modal.getElementsByClassName("mySlides");
  var captionText = document.getElementById("caption");

  if (n > slides.length) {slideIndex = 1}
  if (n < 1) {slideIndex = slides.length}
  for (i = 0; i < slides.length; i++) {
      slides[i].style.display = "none";
  }
  for (i = 0; i < dots.length; i++) {
      dots[i].className = dots[i].className.replace(" active", "");
  }
  slides[slideIndex-1].style.display = "block";
  dots[slideIndex-1].className += " active";
  captionText.innerHTML = dots[slideIndex-1].alt;
}


text:
Q: Calling DynamoDB query and then writing result to s3 bucket: How to simplify this code with async await? I have the following lambda function that reads from a DynamoDB table then writes the result to a spreadsheet on the S3 bucket.
It works fine but I'd like to improve it using async await. Is this possible?
'use strict';
const AWS = require('aws-sdk');
const S3 = new AWS.S3();
const excel = require('excel4node');
const workbook = new excel.Workbook();
const worksheet = workbook.addWorksheet('Sheet 1');
const db = new AWS.DynamoDB.DocumentClient({ apiVersion: '2012-08-10'});

const contactsTable = process.env.CONTACTS_TABLE;
const contactsBucket = process.env.CONTACTS_BUCKET;
const bucketRegion = process.env.REGION;

  module.exports.exportContactsByID = (event, _context, callback) => {
  const id = event.pathParameters.id;
  const params = {
    TableName: contactsTable,
    IndexName: "company_id-created_at-index",
    KeyConditionExpression: "company_id = :v_ID",
    ExpressionAttributeValues: {
      ":v_ID": id,
    },
    ProjectionExpression: "company_name, contact_name, age, phone, email, dsr_ratio, max_eligibility, created_at_local, selected_banks"
  };

return db.query(params).promise()
.then((res) => {
  const items = res.Items;
  if(res.Count === 0){
    return callback(null, response(200, `No records found for id ${id}`));
  }
  // Headers + Columns
  worksheet.cell(1, 1).string('Client').style({font: {bold: true}});
  worksheet.cell(1, 2).string('Name').style({font: {bold: true}});
  worksheet.cell(1, 3).string('Age').style({font: {bold: true}});
  worksheet.cell(1, 4).string('Email').style({font: {bold: true}});
  worksheet.cell(1, 5).string('Phone').style({font: {bold: true}});
  worksheet.cell(1, 6).string('DSR Ratio').style({font: {bold: true}});
  worksheet.cell(1, 7).string('Max Eligibility').style({font: {bold: true}});
  worksheet.cell(1, 8).string('Submission Date').style({font: {bold: true}});
  worksheet.cell(1, 9).string('Banks').style({font: {bold: true}});
  // Rows
  items.forEach((item, i) => {
    worksheet.cell(i + 2, 1).string(item.company_name);
    worksheet.cell(i + 2, 2).string(item.contact_name);
    worksheet.cell(i + 2, 3).string(item.age);
    worksheet.cell(i + 2, 4).string(item.email);
    worksheet.cell(i + 2, 5).string(item.phone);
    worksheet.cell(i + 2, 6).string(item.dsr_ratio);
    worksheet.cell(i + 2, 7).string(item.max_eligibility);
    worksheet.cell(i + 2, 8).string(item.created_at_local);
    worksheet.cell(i + 2, 9).string(item.selected_banks);
  });
  return workbook.writeToBuffer().then(buffer => {
    const params = {
      Bucket: contactsBucket,
      Key: `contacts/${id}.xlsx`,
      Body: buffer,
      ACL: 'public-read'
    }
    const fileURL = `https://${contactsBucket}.s3-${bucketRegion}.amazonaws.com/contacts/${id}.xlsx`;
    return S3.upload(params).promise().then(_data => {
      callback(null, response(200, fileURL));
});
  })
})
.catch((err) => callback(null, response(err.statusCode, err)));
};

The code above is the improved version from the original code I had earlier. Thank you for reading.

A: After reading this, I simplified the code as the following - by having multiple awaits
  module.exports.exportContactsByID = async (event, _context) => {
  const id = event.pathParameters.id;
  const params = {
    TableName: contactsTable,
    IndexName: "company_id-created_at-index",
    KeyConditionExpression: "company_id = :v_ID",
    ExpressionAttributeValues: {
      ":v_ID": id,
    },
    ProjectionExpression: "company_name, contact_name, age, phone, email, dsr_ratio, max_eligibility, created_at_local, selected_banks"
  };

try {
    const res = await db.query(params).promise();
    if(res.Count === 0){
      const response = {
        statusCode: 200,
        headers: {
          'Access-Control-Allow-Origin': '*',
          'Access-Control-Allow-Credentials': true,
        },
        body: JSON.stringify({
          status: `No records found for company id ${id}`,
        }),
      };
      return response;
    }
    else {
    // Headers + Columns
    const items = res.Items;
    worksheet.cell(1, 1).string('Client').style({font: {bold: true}});
    worksheet.cell(1, 2).string('Name').style({font: {bold: true}});
    worksheet.cell(1, 3).string('Age').style({font: {bold: true}});
    worksheet.cell(1, 4).string('Email').style({font: {bold: true}});
    worksheet.cell(1, 5).string('Phone').style({font: {bold: true}});
    worksheet.cell(1, 6).string('DSR Ratio').style({font: {bold: true}});
    worksheet.cell(1, 7).string('Max Eligibility').style({font: {bold: true}});
    worksheet.cell(1, 8).string('Submission Date').style({font: {bold: true}});
    worksheet.cell(1, 9).string('Banks').style({font: {bold: true}});
    // Rows
    items.forEach((item, i) => {
      worksheet.cell(i + 2, 1).string(item.company_name);
      worksheet.cell(i + 2, 2).string(item.contact_name);
      worksheet.cell(i + 2, 3).string(item.age);
      worksheet.cell(i + 2, 4).string(item.email);
      worksheet.cell(i + 2, 5).string(item.phone);
      worksheet.cell(i + 2, 6).string(item.dsr_ratio);
      worksheet.cell(i + 2, 7).string(item.max_eligibility);
      worksheet.cell(i + 2, 8).string(item.created_at_local);
      worksheet.cell(i + 2, 9).string(item.selected_banks);
    });
    const buffer = await workbook.writeToBuffer();
    const params = {
            Bucket: contactsBucket,
            Key: `contacts/${id}.xlsx`,
            Body: buffer,
            ACL: 'public-read'
    }
    const fileURL = `https://${contactsBucket}.s3-${bucketRegion}.amazonaws.com/contacts/${id}.xlsx`;
    const s3 = await S3.upload(params).promise();
    const response = {
      statusCode: 200,
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Credentials': true,
      },
      body: JSON.stringify({
        fileURL: fileURL,
      }),
    };
    return response;
  }
}
catch (err){
  console.log(err);
  return err;
}
};


text:
Q: Set BackGround Color of Textbox to Transparent I am trying to set the background color of textbox to transparent, to blend with my backcolor of my form.
I have tried the following below.
 TextBox1.BackColor = Color.Transparent 'This doesn't work it stays white'

Is there something I am missing?

A: When I set TextBox.BackColor to Color.Transparent, it throws System.ArgumentException. I got this message :
Unvalid property value, The control does not support transparent colors background.

A: Hope am not late to the party, but this actually works for me. First create a class for the panel as below
Partial Public Class iPanel
    Inherits Panel
    Public Sub New()
        SetStyle(ControlStyles.SupportsTransparentBackColor Or ControlStyles.OptimizedDoubleBuffer Or ControlStyles.AllPaintingInWmPaint Or ControlStyles.ResizeRedraw Or ControlStyles.UserPaint, True)
        BackColor = Color.Transparent
    End Sub
End Class

Then create a RichTextBox (Instead of a Textbox) as below
Protected Overrides ReadOnly Property CreateParams() As CreateParams
    Get
         Dim CP As CreateParams = MyBase.CreateParams
         CP.ExStyle = CP.ExStyle Or &H20
         Return CP
    End Get
End Property

Now compile the code and add the iRichTextBox inside the panel. Works for me

A: Private Sub TextBox1_Paint(sender As Object, e As PaintEventArgs) Handles TextBox1.Paint
    TextBox1.ForeColor = Color.White
    TextBox1.BackColor = Color.Transparent
End Sub

Instead of doing the first one, You can try this. Just put your code in Form Load
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    TextBox1.BackColor = color.(color of your Choice, same color of your background)
    TextBox1.ForeColor = color.White

End Sub

As simple as that, it works for me

A: As far as I know textbox does not support transparent color property. But if you set the back color of the textbox to the same color as of its background component, still it can be considered as transparent.
How to do that - You can get the color name of the background component(in your case it is the form) and pass that name to the component which you want to be transparent.
Dim lname As String = Me.BackColor.ToString
Dim name As String = lname.Substring(7, lname.Length - 8)
txtbox1.BackColor = System.Drawing.Color.FromName(name)

Explanation -

*

*The first line in the code gets you the name of the color, but there's a rub, it gets the name something like this - Color [Dark Orange] and we need only the name of the color i.e Dark Orange.

*Thus the second line is to get the exact color name by removing this - Color [] part

*And the last line to set that color same as of the background component color.
Hope it works, still have problem let me know...


text:
Q: Default height of status bar is not showing properly after upgrade library to android 23.2.1 I am working on an app, need to apply bottomsheet dialog, so I updated my android.supppcom.android.support:design:23.1.1 to com.android.support:design:23.2.1. Everything is working fine, but here is the problem.

*

*Status bar's default height is wider than normal(say if default is 10dp now height is 30dp).

*It's preview is ok in Android studio's preview.

I don't know how it's working, so can anyone help me on this.Please find the gradle information.
Thanks
   dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.inkapplications.viewpageindicator:library:2.4.3'
compile 'com.facebook.android:facebook-android-sdk:4.6.0'
compile 'com.google.android.gms:play-services:8.4.0'
compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
compile 'commons-codec:commons-codec:1.9'
// compile 'com.android.support:multidex:1.0.0'
    compile 'com.codesnippets4all:quick-json:1.0.4'
   //    compile 'javax.persistence:persistence-api:1.0'
  //    compile 'com.android.support:design:23.1.1'
      compile 'com.android.support:design:23.2.1'
  //    compile 'com.android.support:cardview-v7:23.1.1'
    compile 'com.android.support:cardview-v7:23.2.1'
   //    compile 'com.android.support:recyclerview-v7:23.1.1'
   compile 'com.android.support:recyclerview-v7:23.2.1'
   //    compile 'com.android.support:appcompat-v7:23.1.1'
   compile 'com.android.support:appcompat-v7:23.2.1'
   //    compile 'com.android.support:support-v4:23.1.1'
   compile 'com.android.support:support-v4:23.2.1'

    }

    <?xml version="1.0" encoding="utf-8"?>
     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
     <android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">
     <android.support.v7.widget.Toolbar
        android:id="@+id/toolbarAppHome"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />
      </android.support.design.widget.AppBarLayout>
     <FrameLayout
    android:id="@+id/frag_placeholder"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1">
    </FrameLayout>
    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="70dp"
    android:background="@color/colorPrimaryDark"
    android:orientation="horizontal">

    <LinearLayout
        android:id="@+id/tab_home"
        android:orientation="vertical"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:gravity="center_vertical|center_horizontal"
        android:layout_height="match_parent">
        <ImageView

            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_home_white_24dp"/>
        <TextView

            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Lable"/>

    </LinearLayout>

    <LinearLayout
        android:id="@+id/tab_tournament"
        android:orientation="vertical"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:gravity="center_vertical|center_horizontal"
        android:layout_height="match_parent">
        <ImageView

            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_group_white_24dp"/>
        <TextView

            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Lable"/>

    </LinearLayout>
    <LinearLayout
        android:id="@+id/tab_team"
        android:orientation="vertical"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:gravity="center_vertical|center_horizontal"
        android:layout_height="match_parent">

        <ImageView

            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_group_work_white_24dp"/>
        <TextView

            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Lable"/>

    </LinearLayout>
    <LinearLayout
        android:id="@+id/tab_notification"
        android:orientation="vertical"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:gravity="center_vertical|center_horizontal"
        android:layout_height="match_parent">

        <ImageView

            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_notifications_white_24dp"/>
        <TextView

            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Lable"/>

    </LinearLayout>

</LinearLayout>

Above added is XML code of the activity view which launches when application starts. This activity has a framelayout in centre. That framelayout display a fragment say fragmentA. Here is the XML view code of this fragment.
    <?xml version="1.0" encoding="utf-8"?>
    <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:background="#F8F8FF">

   <android.support.v7.widget.RecyclerView

    android:id="@+id/appHomeRecycleView"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

   </android.support.v7.widget.RecyclerView>

   <android.support.design.widget.FloatingActionButton
    android:id="@+id/xyz1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="16dp"
    android:scaleType="center"
    android:src="@drawable/ic_mode_edit_white_24dp" />

    </android.support.design.widget.CoordinatorLayout>

A: Generally speaking, you should not assume a fixed height of the status bar (especially when targeting older devices by various manufacturers). I used to do that and regretted it :p  AFAIK a ScrimInsetsFrameLayout (or similar) is the way to go here, see https://github.com/google/iosched/blob/master/android/src/main/java/com/google/samples/apps/iosched/ui/widget/ScrimInsetsFrameLayout.java

A: Thanks for your responses. I worked on it for more than 10 hours and finally found the solution. Here is the solution:
You can see a parameter inside the fragmentA layout XML file:
    android:fitsSystemWindows="true"

Change this paramter to false as:
    android:fitsSystemWindows="false"

Frankly telling, I don't why this is not working with new library 23.2.1, but it works fine in 23.1.1 version.
Hope this will help others.
Thanks
Prabhakar


text:
Q: More effecient way of changing PHP results displayed I have a PHP script that displays a bunch of database results in a nice grid and paginates them.
I'm trying to figure out how I can create a way to change the number of results displayed per page using a drop down system so I started to play with AJAX.
I have a variable that determines the amount of items to be displayed so what I've done is I've created a few more pages that have the exact same PHP code, but with a different number for that variable. It does what its intended to do, but I can't help but feel I've gone about doing this in the most inefficient way imaginable because I had to create three additional pages with the differing variable.
How can this be improved?
This is the php code. I used to have it in the page itself but have move it to another file which the ajax looks at.
<?php

                //Add the file that connects to the database
                include("C://wamp/www/site/config.php");
                //Selects which database to get the data from
                mysql_select_db("products");

                //Variables for pagination

                $per_page = 24;
                // get the number of items that actually have Oven in their name
                $sql = "SELECT SUM(rowcount)
                        FROM (
                        SELECT COUNT(1) AS rowcount
                        FROM brand1
                        WHERE description LIKE '%oven%'
                        UNION ALL
                        SELECT COUNT(1)
                        FROM brand2
                        WHERE description LIKE '%oven%'
                        ) AS counts";
                $pages_query = mysql_query ($sql) ;
                //Ceil rounds up to the nearest number so that we don't get pages with decimals on the end
                $pages = ceil(mysql_result($pages_query, 0) / $per_page);

                //append a page=1,2,3 at the end of the URL to indicate which page the user is on

                //set : 1 so that if a person doesn't pick a page it automatically sets them on page 1.
                $page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;

                $start = ($page -1) * $per_page;

                //Selects which table to extract the data from
                $i = 0;
                $result = mysql_query("SELECT * FROM brand1 WHERE description LIKE '%oven%' UNION ALL SELECT * FROM brand2 WHERE description LIKE '%oven%' LIMIT $start, $per_page") ;
                $dyn_table = '
';

                //create a variable to store the data in
                while($row = mysql_fetch_array($result))
                    {
                        //Variables to store vendors information, product number and image as retrieved from the database
                        $brand = $row["Brand"];
                        $model_number = $row["Model Number"];
                        $product_image = $row["Image"];

                        //Set up a loop that puts the information into a grid rather than a single line
                        if($i%4==0) //First number sets the column number
                            {
                                // Starts to draw the table. Adds the vendor name, the product number then breaks line to draw the image underneath the titles
                                $dyn_table .= '
' .  $brand . " " . $model_number . '
' . $product_image .'	';
                            }
                        else
                            {
                                //This line does the same thing, but once the first if condition hits 4, it jumps to this line to contine drawing.
                                $dyn_table .= '' . $brand . " " . $model_number . '
' . $product_image . '	';
                            }
                        //Simply adds 1
                        $i++;
                    }
                    //Adds the ending of the table
                    $dyn_table .= '

';

                    //Draws the table
                    echo $dyn_table;

                    //Set the pagination links at the bottom of the page
                    if ($pages >=1 && $page <= $pages)
                        {
                            for($x=1; $x<=$pages; $x++)
                                {
                                    echo ($x == $page) ? ''.$x.' ' : ''.$x.' ';
                                }
                        }
            ?>

And the AJAX (Which I just grabbed off an example from W3

A: By your description, I assume you have something like page1.php, page2.php...?
Make a page.php, read $_GET['page'] to see which page you should be doing, and in HTML link to page.php?page=2 and similar.
As Charles says, that's as much as I can offer with the level of detail you provide.

A: Here, have a big fat boring answer.
Your code is fine, outside of the whole taint from the mysql_ family and that prehistoric manual ajax stuff.  Your pagination methodology is solid and follows the usual pattern of finding out how many pages you could possibly have, then grabbing the current page of results based on that limit.  You have all the correct validation bits and pieces there as well.
You're right in that this is a tad inefficient, but unless you have a convenient place to stick a pre-calculated maximum result count / maximum page count, there are very few ways around it.  You may well already have one.  Examine your database structure carefully.  You should also make sure you have appropriate indexing.  Time to play with EXPLAIN.
The only thing I could recommend might be unrelated.  It looks like you might need to read up on database normalization.  Your table names (brand1, brand2) suggest that you might have two tables that are entirely identical in structure, with the only difference being that they contain data intended for two different "brands."  This could easily be done in a single table, with the addition of the brand as another column.


text:
Q: Small sample sizes and the Kolmogorov-Smirnov test I have split my data set into four categories but one of them only has four data points in it.
I have run K-S normality tests on the other three categories which are each normal and when the data set is not split into four it is also normal.
For this fourth category, do I assume it is normal, and run a parametric analysis, or assume it is non-normal and run a nonparametric analysis?
This is one of many calculations I have run on the same method using the K-S test for normality but would it be inconsistent for me to suddenly switch to a Shapiro-Wilk test for this one analysis?

A: The Kolmogorov-Smirnov (K-S) test can be used to compare other distributions, so if you have enough data in the fourth category, I think you should be able to compare its distribution to the distribution(s) of the data in the other categories.  It seems unlikely that you will have enough power to reject the null with only four data points in the fourth category's distribution though.  I doubt this would provide sufficient power for most NHSTs, but there may be exceptions.
I think you should probably know already if it's safe to assume your four data points in the fourth category were sampled randomly from a normal distribution.  That is, if you don't know that it's safe to assume this for prior theoretical and methodological reasons, it probably isn't safe to assume. However, the degree and manner of deviation from a normal distribution is more important in most cases than the simple, binary outcome of a NHST of your distribution's normality. You may want to consider a related, popular question here on Cross Validated: Is normality testing 'essentially useless'?
Here's a useful quote I found in an answer to that question:

As a rule of thumb (not a law of nature), inference about means is sensitive to skewness and inference about variances is sensitive to kurtosis.

This suggests you might at least wish to test the skewness or kurtosis separately, focus on whichever is more relevant to the subsequent analysis you have in mind, and pay attention to the value of the skewness or kurtosis statistic itself, not just the $p$ value of whatever NHST to which you might've felt obligated to cede inferential authority.
Nonparametric analyses do not assume non-normal distributions.  Most also possess power and reliability that match equivalent parametric tests. Therefore you probably haven't got much to lose by just defaulting to the nonparametric alternative and skipping the normality test entirely. The main tradeoffs are usually computational complexity and the need to provide references due to methodological unconventionality, but all this necessitates are a modern computer and a little extra reading and writing, so it's probably generally advisable to just go for the nonparametric alternative. This depends on what analysis you have in mind though, so you may want to look into the drawbacks of the particular nonparametric alternative you have in mind for yourself.
Last, I don't see how you'd do any additional harm in switching to a Shapiro-Wilk (S-W) test, but if you want to compare its result to those of the K-S tests, I'd say you should also perform S-W tests on those distributions so you have some idea of how the method variance affects your test statistics within each sample distribution. Also, bear in mind that the S-W test is directly contraindicated by many of the answers to the aforementioned question...but I assume many of those objections would apply similarly to a K-S test that references a normal distribution.


text:
Q: Breaking Up A List Using Values As Breakpoints? I have a list that contains a few values, each followed by a number of Nones:
['Apple', None, None, None, None, None, None, 'Orange', None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, 'Pear', None, None, None, None, None, None, None, 'Banana', None, None]

I want an output like this, that breaks up the list into separates lists each with the non-None value as breakpoints:
['Apple', None, None, None, None, None, None]
['Orange', None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None]
['Pear', None, None, None, None, None, None, None]
['Banana', None, None]

I am scratching my head as to how to do it.

A: You said you wanted to replace the None's with the latest non-None value.  I'll skip the "how do I split" question, and answer the "replacing" question:
def fill_nones(seq):
    last = None
    for val in seq:
        if val is not None:
            last = val
        yield last

Now you can make a new list with:
filled = list(fill_nones(old_list))

A: Might be a better way with list comprehensions but something like this will split the original list into a list of smaller lists as long as the first value isn't None.
def splitlist(listin):
    newlist = []
    for val in listin:
        if val != None:
            newlist.append([val])
        else:
            newlist[-1].append(None)
    return newlist

A: Try the following:
x = ['Apple', None, None, None, None, None, None, 'Orange', None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, 'Pear', None, None, None, None, None, None, None, 'Banana', None, None]
output = []
sub = []
for i in range(len(x)):
    cur = x[i]
    if i > 0:
            if cur != None:
                    output.append(sub)
                    sub = [cur]
            elif i >= len(x)-1:
                    sub.append(cur)
                    output.append(sub)
                    sub = [cur]
            else:
                    sub.append(cur)
    else:
            sub.append(cur)

Which yields:
>>> output
[['Apple', None, None, None, None, None, None], ['Orange', None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None], ['Pear', None, None, None, None, None, None, None], ['Banana', None, None]]
>>>

A: I solve this problem using two new auxiliary lists.
The code looks like this:
def fill_list(seq):
    list_aux_1 = list()
    list_out   = list()

    for item in seq:
        if isinstance(item, str):
            list_out.append(list_aux_1)
            list_aux_1 = list()
        list_aux_1.append(item)
    else:
        list_out.append(list_aux_1)
        list_out = list_out[1:]
    return list_out

to use only
seq = ['Apple', None, None, None, None, None, None, 'Orange', None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, 'Pear', None, None, None, None, None, None, None, 'Banana', None, None]
print fill_list(seq)


text:
Q: How can I read two input files and create one output file via Python? So I have two files and I need to create an output file for them - my prof. wants me to use a while loop to process the first file and a for loop for the second file, as well as use a try/except block to read from the input and write to the output. I think I have like, a general idea for the initial code but I'm still lost.
#reads the file

n1 = open('nameslist1.txt', 'r')
n2 = open('nameslist2.txt', 'r')
print(n1.read())
print(n2.read())
n1.close()
n2.close()
#writes the file
n1_o = open('allnames.txt', 'w')
n2_o = open('allnames.txt', 'w')
n1_o.write('nameslist1.txt')
n2_o.write('nameslist2.txt')
n1_o.close()
n2_o.close()


text:
Q: Access AWS SSM Port inside Docker container I try to access some AWS resources from inside a docker container. Therefore I have a PortForwarding SSM session running on the host and everything works fine when I try to access the resources via localhost:<port>.
However, inside of a docker container I cannot access these same resources via 172.17.0.1:<port>. Host communication per se seems to work just fine, as I can communicate with a local web server via 172.17.0.1:8000. Only the combination of SSM and docker seems to be a problem.
nmap inside of the container also shows the port as closed.
Is there any way to get the combination of SSM and docker up and running?

A: I suspect that what is happening is that AWS SSM is port forwarding to localhost and is bound to the loopback adaptor.
If I run aws ssm port forwarding, I am able to access the port on the localhost and not via my machine IP:Port.
So when docker tries to access the port via its own natted IP it is unable to connect to the port.
I have the same issue that I am trying to solve with miniKube. Since I am only able to access my ports via localhost on my system, minikube is unable to access my localports.

A: If I understand correctly, you try to connect to a webserver from your container host and this works, but when logged into the docker container itself you cannot reach it?
If this is what you meant, It could be related to the fact that containers have a different network interface from the host and thus different security groups. If the receiving server's security group is configured to allow traffic from the host, but not from the security group of the containers running on the host, it would be a possible explanation for what you experienced.


text:
Q: Rails: why can I send a single record attribute via controller to new record but not array? Creating articles via the controller in Rails. A simple method, which more or less works; just call the method from some other place and it generates a new article via the back end and fills in the values:
def test_create_briefing
  a = Article.new
  a.type_id = 27
  a.status = 'published'
  a.headline = 'This is a headline'
  a.lede = 'Our article is about some interesting topic.'
  a.body = test_article_text
  a.save!
end

If test_article_text is just a single record, this works fine and prints the existing article body into the new article body. Looks right in the view and looks right in "edit". All perfect.
def test_article_text
  a = Article.find_by_id(181)
  a.body
end

But if I try to do the same thing with the last ten articles, it doesn't work:
def test_article_text
  Article.lastten.each do |a|
    a.body
  end
end

In the view you get:
[#, #, #, #, #, #, #, #, #, #]

And in "edit" you get:
[#<Article id: 357, headline: "This is a headline", lede: "Our article is about some interesting topic.", body: "[#<Article id: 356, headline: \"This is a headline\"...", created_at: "2017-12-31 20:40:16", updated_at: "2017-12-31 20:40:16", type_id: 27, urgency: nil, main: nil, status: "published", caption: nil, source: nil, video: nil, summary: nil, summary_slug: nil, topstory: false, email_to: nil, notification_slug: nil, notification_message: nil, short_lede: nil, short_headline: nil, is_free: nil, briefing_point: nil>, #<Article id: 356, headline: "This is a headline"…etc, etc, etc.

What do I not know? What am I missing?

A: It is returned as below because the Article.lastten is the returned variable from your controller.
[#<Article id: 357, headline: "This is a headline", lede: "Our article is about some interesting topic.", body: "[#<Article id: 356, headline: \"This is a headline\"...", created_at: "2017-12-31 20:40:16", updated_at: "2017-12-31 20:40:16", type_id: 27, urgency: nil, main: nil, status: "published", caption: nil, source: nil, video: nil, summary: nil, summary_slug: nil, topstory: false, email_to: nil, notification_slug: nil, notification_message: nil, short_lede: nil, short_headline: nil, is_free: nil, briefing_point: nil>, #<Article id: 356, headline: "This is a headline"…etc, etc, etc.

To return all Article body, do as below:
def test_article_text
  arr = Array.new
  Article.lastten.each do |a|
    arr << a.body
  end
  arr # should be added so it will be the last value returned from your controller
end

A: So, @Shiko was nearly right, certainly on the right path. Had to manipulate the array a bit and do two things to get it to work:

*

*.join the bits of the array to strip out all of the rubbish;

*Concatenate the different bits for each article in a different way than you normally do in a view. So to_sfor each of the attributes, concatenating things "" + "" and rebuilding the url with information available in the array (no link_to, etc.).

*The "**"is markdown, because I'm using that, but I suppose you could bung html tags in there if you needed to.
This works:
def test_article_text
  arr = Array.new
  Article.lastten.each do |a|
  arr << "**" + a.headline.to_s + "**: " + a.text.to_s + "[Read now](/articles/#{a.id}-#{a.created_at.strftime("%y%m%d%H%M%S")}-#{a.headline.parameterize})"
  end
  arr.join("\n\n")
end


text:
Q: jQuery - make a DIV visible on the browser I have designed a long form around two pages. After the user submits the form, I need to force him/her to see the top of the form if the form contains any errors.
I have an error holder on top of the form.
My question is how to make the browser scrolls to the error holder so that the user can easily see it?
Thank you
/////////////////////////////////////////// follow Peter's comments
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

    <title>jQuery</title>

Hello world

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

DDDDDDDDDDDDDD

    <button type="button" id="clearhere" name="clearhere">Click Me!</button>

///////////////////////////////////////////

A: To scroll to the top an element simply make use of the jQuery .animate() and .offset() functions. For example to scroll to the top of an element with a particular selector (such as an id) passed in as an argument, use this:
  // This is a function that scrolls to the element that matches selector
function goToByScroll(selector){
      // Scroll
    $('html,body').animate({
        scrollTop: $(selector).offset().top},
        'slow');
};

For example, if you have only one form on the page, you can use: goToByScroll("form");. If you want to scroll to an element with a particular id use goToByScroll("#myId"); ... etc.
If you want to adjust the scroll time to an exact number of milliseconds, just replace 'slow' with the number of millisecond, for example 1000 (no quotes) for a scroll of 1 second.
Just trigger the above function when you want to scroll to the top of your form.
Here's a live jsFiddle example (as a 5 line jQuery plugin)

A: You could use the jQuery ScrollTo plugin to smoothly scroll back up to the error holder:
// in your validation, on error
$(window).scrollTo($('#errorHolderId'), 500);

Sans plugin
If you don't want to use a plugin, you can do it with a combination of offset() or position() and scrollTop:
var errorHolderTop = $('#errorHolderId').offset().top;
$(window).scrollTop(errorHolderTop);

The reason I mentioned both offset and position is because they behave slightly differently.  Offset returns coordinates relative to the document whereas position is relative to your element's offset parent.
You could also animate the scrollTop property if you wanted to create the smooth scroll effect:
var errorHolderTop = $('#errorHolderId').offset().top;
$('html, body').animate({scrollTop: errorHolderTop});

In action here.


text:
Q: Need to sort a nested tuple with numbers I trying to sort a tuple as below
input: ROI:
[[191  60  23  18]
 [143  60  23  19]
 [ 95  52  24  21]
 [237  51  24  21]
 [ 47  38  27  22]
 [281  35  25  22]
 [  4  17  26  24]
 [324  13  22  21]]

Expected Output = S_ROI:
[[4  17  26  24]
 [47  38  27  22]
 [ 95  52  24  21]
 [143  60  23  19]
 [ 191  60  23  18]
 [237  51  24  21]
 [281  35  25  22]
 [324  13  22  21]]

I have got intermediate array
column=[191 143 95 237 47 281 4 324]

I have tried this - But ROI is getting updated inside loop
sort_index = np.argsort(column)
column.sort()

sorted_led_ROI=ROI;
index=0
    for y in sort_index:
        sorted_led_ROI[index]=ROI[y]
        index =index+1
    print('sorted_led_ROI:', sorted_led_ROI)

Result:
sorted_led_ROI:
[[  4  17  26  24]
 [ 47  38  27  22]
 [ 95  52  24  21]
 [ 47  38  27  22]
 [  4  17  26  24]
 [ 47  38  27  22]
 [ 47  38  27  22]
 [324  13  22  21]]

help me out to sort this in python using np or cv

A: Do you mean just this:
print(ROI[ROI[:,0].argsort()])

Output:
[[  4  17  26  24]
 [ 47  38  27  22]
 [ 95  52  24  21]
 [143  60  23  19]
 [191  60  23  18]
 [237  51  24  21]
 [281  35  25  22]
 [324  13  22  21]]


text:
Q: How to add Orcid ID in LaTex article? I want to add Orcid ID in Latex article. I have tried several methods that are used for other documentclasses, but none of them worked for me.

A: If you have a very up-to-date TeX installation, you can use the orcidlink package.
\documentclass{article}
\usepackage{orcidlink}
\begin{document}
\orcidlink{https://orcid.org} is an ORCID link.
\end{document}

Otherwise you can use this answer, which it is based on.


text:
Q: bit manipulation in CircuitPython I've to perform bit-level operations using CircuitPython, like extracting and manipulating 3 bits from a bytes() object.
In normal Python I use the Bitarray library.
Is there an equivalent for CircuitPython?
Thanks.

A: Even with regular Python it's typical to use the bitwise & and | operators and the bitwise shift operators for setting/selecting various bits. E.g., to test the 6th bit of an integer value:
if myValue & 0b100000:
  print('bit 6 was set')
else:
  print('bit 6 was not set')

To set bits 4-6:
myValue |= 0b111000

To extract bits 4-6:
extract = (myValue & 0b111000) >> 3

Etc.


text:
Q: Building Active Directory Operations in IIB without Java or JCN The Case is : to build an integration service with active directory, this service has many operations
such as create user, activate user, change password , ...etc I have developed theses operations using JCN
but,
the client refused any java implementations inside the service even calling java apis inside esql modules,
My question is :
from my experience it is impossible to build this service without any Java implementations if it is impossible using ESQL please tell me? If it was pure esql or tcpip?


text:
Q: How to make an a-frame part of an HTML grid and take up the width of the parent div? I have started toying around with A-Frame, and I have used their Model Viewer example as a starting point. I have tried to make this model viewer part of the html site, where it would be a smaller part of the grid:

        Some text here

In css I have set the container to have this styling:
.container {
  display: grid;
  grid-template-columns: 1fr 1fr;
}

But, that didn't work as expected as the model viewer was still taking the whole page and wasn't part of the container.
How can I fix this and make model viewer to take up the space of the given width by the parent div element.
Here is the code of the example I have edited.

A: If you want to embed a scene within some custom layout there is the embedded component:

like in this fiddle(with a grid layout).