text:
Q: React: Change width of progress bar from state I want the width of my progress bar to change depending on the input percentage. So if you submit a number using the button the h4 changes but not yet the width of my progress bar. How do I achieve this? Here is my code:
function Progress() {

    const [progress, setProgress] = useState(0);

    return (

Title

Progress: {progress} %

                Progress (in %)

                    <form onSubmit={e => {
                        e.preventDefault();
                        const { value } = e.target.progress;
                        setProgress(value);
                        e.target.progress.value = '';
                    }}>
                        <input id="progress" type="text" placeholder="e.g. 75"></input>
                        <button type="submit" className="button">Update</button>
                    </form>

    );

  }

A: The style prop you are passing to the progress-bar div is not valid.
The style prop on a div is an object with property names as the keys. So you should instead be trying something like:
<div classname="progress-bar" style={ { width: `${progress}%` } }>

A: Hope this works as you wanted:

Progress: {progress} %

      <div
        className="progress-bar"
        style={{
          width: `${progress}%`,
          backgroundColor: "red",
          height: "100%",
        }}
      >


text:
Q: How to redirect to a specific page on click of app icon? We are working on iPhone app and we have implemented push notification functionality. When the app is inactive, any notification received shows an alert and the badge icon counter gets incremented. When the user clicks either on the app's icon or on the alert, the app becomes active and everything works fine.
What we want is this: On new notification, whenever a user clicks on the app icon, it should open a specific page (e.g. the Notifications page). Currently, when the app becomes active, it shows the last previously open page.
How can I redirect the app (on foreground) to a specific page?

A: assume that this is your PayLoad
{"aps":{"alert":"Hai User","type":"center","badge":1,"sound":"default"}}

the didReceiveRemoteNotification method handle the payload
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    // this is used for clear the count when user press the notification.

    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    [[UIApplication sharedApplication] cancelAllLocalNotifications];

  //When notification is pressed on background it comes here

  //Get strings based on information on your json payload for example

    NSMutableString *notificationType =[[userInfo objectForKey:@"aps"]objectForKey:@"type"];

  if([notificationType isEqualToString:@"center"]){
       //redirect/push a viewcontroler here , it automatically navigate to your VC.

       profileViewController *profile = [[profileViewController alloc] initWithNibName:@"profile ViewController" bundle:nil];

    [self.window.rootViewController presentViewController: profile animated:YES completion:NULL];
  }
}

notification types from Apple is here

A: Inside your
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
  [self openNewViewController]; // read the userInfo from the payload and based on that open new controller
}
method you can directly push/modal/addsubview your desired page.
And inside "didFinishLaunchingWithOptions:" check for remote notification payload
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
 if (launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey]) {
        NSDictionary *dict = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey];
        //Call your page here
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: macros defined in verilog file but error shows undifined macros in modelsim I have defined the macros of all my verilog files in one verilog file, say FabScalarParam.v
and I compile the FabScalarParam.v first in the system.do file then compile other verilog files.
But when I run "do system.do" to compile the design, it shows me the errors like this,
# ** Error: I:/programming/EDK/project_4/pcores/instruction_side_v1_00_a/hdl/verilog/StallUnit.v(6): (vlog-2163) Macro `MAX_STALL_CYCLES_LOG is undefined.

It says that some macros are not defined. Is there any method to choose the FabScalarParam.v as global file in compile list in modelsim? Due to the large number of macros, I cannot specify all the macros using the method: compile --> compile options --> verilog & system verilog --> other verilog options --> Macros.
I use modelsim 6.5, xilinx edk 12.4

A: This has to do with compile order. Compiler directives, which included macros are processed linearly by the compiler. See IEEE1364-2001 section 19 or IEEE1800-2009 section 22 for more detail. Make sure the macro file is the first file to that is compiled.
Manually adding the `include also works, however your compiler may give macro redefined warnings. It is recommend to encapsulate the macro definitions in a `ifdef/`ifndef. Doing so resolve the macro defined warnings. If multiple files refer to same `include then encapsulation of the macros may also improve compiler performance. See the following example.
macros.vh:
`ifndef macros_vh
// NOTE: for Verilog 1995 `ifndef is not supported use `ifdef macros_vh `else
`define macros_vh
/**************
* your macros *
* `define ... *
***************/
`endif

Then in your verilog files (*.v / *.sv)
`include "macro.vh"
/*************
 * your code *
 *************/

A: I cannot find anything useful on Internet to set global file in the compile list in modelsim. So, I just manually add `include ... in each file to solve the problem. Though it is stupid, It works fine.
If someone knows how to set the global file in the compile list in modelsim, please update it. :-) Thanks.

A: I had the same problem when I compiled my project with script.
At last, I figure out you can't compile your macro and verilog files in different scope.
EX:
vlog -work work macro.v
vlog -work work project.v

You have to:
vlog -work work macro.v project.v

Compiling them in one vlog command can solve the problem.

A: You can compile a verilog file and define the precompiler macro that will be applied for this file by adding the following option to vlog:
+define+<macro_name>[=<macro_text>]

which Same as compiler directive: `define macro_name macro_text
for example:
vlog +define+macro_name -work work project.v

A: This is my work around without adding `include in every files needing macros
vlog -mfcu -y <path/to/source/files> +libext+.v+.sv  <source file 1> <source file 2> <... source file N>
-mfcu let vlog treats all source files in one command line as one compilation unit. If macro are defined in <source file 1>, they are visible to all following source files after it.


text:
Q: Removing Docker Kubernetes k8s images from local machine I had a problem, maybe easy but I couldn't handle this. How to remove all k8s containers and images from local machine?
gcr.io/google_containers/k8s-dns-sidecar-amd64         Up 36 minutes       k8s_sidecar_kube-dns-6fc954457d-mwgvb_kube-system_fd5ebaed-c63c-11e7-b3c8-28d24484a79b_116
gcr.io/google_containers/k8s-dns-dnsmasq-nanny-amd64   Up 36 minutes       k8s_dnsmasq_kube-dns-6fc954457d-mwgvb_kube-system_fd5ebaed-c63c-11e7-b3c8-28d24484a79b_116
gcr.io/google_containers/k8s-dns-kube-dns-amd64        Up 36 minutes       k8s_kubedns_kube-dns-6fc954457d-mwgvb_kube-system_fd5ebaed-c63c-11e7-b3c8-28d24484a79b_116
gcr.io/google_containers/kubernetes-dashboard-amd64    Up 36 minutes       k8s_kubernetes-dashboard_kubernetes-dashboard-xpg2v_kube-system_fd403866-c63c-11e7-b3c8-28d24484a79b_222
gcr.io/google-containers/kube-addon-manager            Up 36 minutes       k8s_kube-addon-manager_kube-addon-manager-lenovo-e540_kube-system_9831e93c3188555873fdb49f43198eef_186
gcr.io/google_containers/pause-amd64:3.0               Up 36 minutes       k8s_POD_kube-dns-6fc954457d-mwgvb_kube-system_fd5ebaed-c63c-11e7-b3c8-28d24484a79b_116
gcr.io/google_containers/pause-amd64:3.0               Up 36 minutes       k8s_POD_kube-addon-manager-lenovo-e540_kube-system_9831e93c3188555873fdb49f43198eef_186
gcr.io/google_containers/pause-amd64:3.0               Up 36 minutes       k8s_POD_kubernetes-dashboard-xpg2v_kube-system_fd403866-c63c-11e7-b3c8-28d24484a79b_186

It's unpossible to stop them (they restart always), also to remove them by rm and rmi. Also tryint to kill kubelet.
$ ps ax | grep kubelet
17234 pts/18   S+     0:00 grep --color=auto kubelet

$ kill -KILL 17234
bash: kill: (17234) - No such process

systemctl stop kubelet
Failed to stop kubelet.service: Unit kubelet.service not loaded.

Also trying to force remove this containers:
$ docker rm -f $(docker ps -a -q --filter "name=k8s")
but they will recreate after that...
Checking available pods results like this...
$ kubectl get po -n=kube-system
Unable to connect to the server: dial tcp 192.168.99.100:8443: getsockopt: network is unreachable

I was looking for it in documentations, stack etc. but with no effect.
Here's bug on github, but no one could help: https://github.com/kubernetes/kubernetes/issues/61173
Thanks in advance!
Best regards,
Marcin

A: I was working with this guide a half year ago: https://kubernetes.io/docs/getting-started-guides/minikube/ so I guess it using VirtualBox. Maybe you know how I can check this?
@Remario thanks for the tip, now when I execute
$ systemctl disable localkube.service and
$ systemctl stop localkube.service
I'm able to delete k8s containers and they didn't restart immediately, so we resolve problem partially. Great!
I got this error when trying to execute docker rmi:
Error response from daemon: No such image: gcr.io/...
But images are still in docker images list. So I run
$ docker system prune -a and all gcr.io images was deleted.
Thanks for your time.
Best regards,
Marcin

A: Something useful
kubectl get deployment nginx-app

NAME         READY   UP-TO-DATE   AVAILABLE   AGE
nginx-app    1/1     1            1           2m

kubectl get po -l run=nginx-app

NAME                         READY     STATUS    RESTARTS   AGE
nginx-app-2883164633-aklf7   1/1       Running   0          2m
kubectl delete deployment nginx-app

deployment "nginx-app" deleted

kubectl get po -l run=nginx-app
# Return nothing


text:
Q: How to use Order By and With clause I am using following SQL query to fetch set of records.
;WITH SFPIPELINE AS (
    SELECT
        PIPELINE_STRING,
        PACKET_NUMBER,
        PIPELINE_NUMBER
    FROM
        [RTMASTER].[DBO].[SF_PIPELINE]
    WHERE
        PIPELINE_STRING IN (
            'SOLUTION_TEST',
            '2018.01_SVC_SANDBOX',
            '2018.01_SVC_ENG'
        )
        AND PACKET_NUMBER IN (98, 1090, 1092)
),
PROJ_INST_PIPELINE AS (
    SELECT
        DISTINCT PIP.PROJECT_INSTANCE_PIPELINE_ID,
        PIP.PROJECT_INSTANCE_ID,
        PIP.PACKET_NUMBER,
        PIP.PROJECT_NUMBER,
        PIP.SOURCE_SET_INSTANCE,
        SFP.PIPELINE_STRING
    FROM
        PROJECT_INSTANCE_PIPELINE PIP
        INNER JOIN SFPIPELINE SFP ON PIP.PACKET_NUMBER = SFP.PACKET_NUMBER
        AND PIP.PIPELINE_NUMBER = SFP.PIPELINE_NUMBER
        AND PIP.ACTIVE = 1
        AND PIP.PROJECT_INSTANCE_PIPELINE_ID >= 20481038
),
PROJ_INST_BASE AS (
    SELECT
        PIP.PROJECT_INSTANCE_PIPELINE_ID,
        PIP.PROJECT_NUMBER,
        PIP.PACKET_NUMBER,
        PIP.PIPELINE_STRING,
        PIP.SOURCE_SET_INSTANCE,
        PIP.PROJECT_INSTANCE_ID,
        PIB.ORIGINAL_PROMOTER,
        PIB.DEV_INSTANCE,
        PROJECT_TYPE_NUMBER,
        PIB.SUBVERSION_PROJECT_REVISION,
        PIB.SUBVERSION _PROJECT_URL,
        PIB.Front_End,
        PIB.Back_End
    FROM
        PROJECT_INSTANCE_BASE PIB
        INNER JOIN PROJ_INST_PIPELINE PIP ON PIB.PROJECT_INSTANCE_ID = PIP.PROJECT_INSTANCE_ID
        AND PIP.PROJECT_NUMBER = PIB.PROJECT_NUMBER
        AND PIB.PROJECT_TYPE_NUMBER IN (5, 105, 106)
),
SF_PROJ AS (
    SELECT
        PJTINST.PROJECT_INSTANCE_PIPELINE_ID,
        PJTINST.PROJECT_INSTANCE_ID,
        PJTINST.PROJECT_NUMBER,
        PJTINST.PIPELINE_STRING,
        PJTINST.ORIGINAL_PROMOTER,
        PJTINST.SOURCE_SET_INSTANCE,
        PJTINST.PROJECT_TYPE_NUMBER,
        PJTINST.PACKET_NUMBER,
        SFP.PROJECT_NAME,
        PJTINST.SUBVERSION_PROJECT_REVISION,
        PJTINST.SUBVERSION_PROJECT_URL,
        PJTINST.Front_End,
        PJTINST.Back_End
    FROM
        DBO.SF_PROJECT SFP
        INNER JOIN PROJ_INST_BASE PJTINST ON SFP.PROJECT_NUMBER = PJTINST.PROJECT_NUMBER
),
USER_DETAIL AS (
    SELECT
        SFP.PROJECT_NAME,
        SFP.PROJECT_NUMBER,
        SFP.PROJECT_TYPE_NUMBER,
        SFP.SOURCE_SET_INSTANCE,
        SFP.PACKET_NUMBER,
        SFP.PIPELINE_STRING,
        SFP.SUBVERSION_PROJECT_REVISION,
        SFP.SUBVERSION_PROJECT_URL,
        SFP.PROJECT_INSTANCE_PIPELINE_ID,
        SFP.PROJECT_INSTANCE_ID,
        AIAA.EMAIL_ADDRESS,
        SFP.Front_End,
        SFP.Back_End
    FROM
        SF_ASSOCIATE_INFO_ALL_ASSOCIATES AIAA
        INNER JOIN SF_PROJ SFP ON AIAA.OPER_ID = SFP.ORIGINAL_PROMOTER
),
FINAL AS (
    SELECT
        UD.PROJECT_NAME,
        FP.Feature_Number,
        UD.PROJECT_NUMBER,
        UD.PROJECT_TYPE_NUMBER,
        UD.SOURCE_SET_INSTANCE,
        UD.PACKET_NUMBER,
        UD.PIPELINE_STRING,
        UD.SUBVERSION_PROJECT_REVISION,
        UD.SUBVERSION_PROJECT_URL,
        UD.PROJECT_INSTANCE_PIPELINE_ID,
        UD.PROJECT_INSTANCE_ID,
        UD.EMAIL_ADDRESS,
        UD.Front_End,
        UD.Back_End
    FROM
        [RTMaster].[dbo].[Feature_Projects_History] FP
        INNER JOIN USER_DETAIL UD ON FP.Project_Instance_Pipeline_ID = UD.PROJECT_INSTANCE_PIPELINE_ID
)
SELECT
    *
FROM
    FINAL

Query is working fine only thing is the records are not sorted.
I want to use order by on PROJECT_INSTANCE_PIPELINE_ID so that all the rows are sorted. When I use ORDER BY clause seeing following error.
Error:
The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.
Not sure how to use Order By and With Clause together.
Any thoughts!

A: try like below i just used  PROJECT_NAME in order by
WITH SFPIPELINE AS
                    (SELECT PIPELINE_STRING, PACKET_NUMBER, PIPELINE_NUMBER FROM [RTMASTER].[DBO].[SF_PIPELINE]
                    WHERE PIPELINE_STRING IN ( 'SOLUTION_TEST', '2018.01_SVC_SANDBOX', '2018.01_SVC_ENG')
                    AND PACKET_NUMBER IN (98, 1090, 1092)),
                PROJ_INST_PIPELINE AS
                    (SELECT DISTINCT PIP.PROJECT_INSTANCE_PIPELINE_ID, PIP.PROJECT_INSTANCE_ID, PIP.PACKET_NUMBER, PIP.PROJECT_NUMBER, PIP.SOURCE_SET_INSTANCE, SFP.PIPELINE_STRING FROM PROJECT_INSTANCE_PIPELINE PIP
                    INNER JOIN SFPIPELINE SFP ON PIP.PACKET_NUMBER = SFP.PACKET_NUMBER AND PIP.PIPELINE_NUMBER = SFP.PIPELINE_NUMBER AND PIP.ACTIVE = 1
                    AND PIP.PROJECT_INSTANCE_PIPELINE_ID >=   20481038),
                PROJ_INST_BASE AS
                    (SELECT PIP.PROJECT_INSTANCE_PIPELINE_ID, PIP.PROJECT_NUMBER, PIP.PACKET_NUMBER, PIP.PIPELINE_STRING, PIP.SOURCE_SET_INSTANCE, PIP.PROJECT_INSTANCE_ID, PIB.ORIGINAL_PROMOTER, PIB.DEV_INSTANCE,PROJECT_TYPE_NUMBER, PIB.SUBVERSION_PROJECT_REVISION, PIB.SUBVERSION_PROJECT_URL,
                    PIB.Front_End, PIB.Back_End FROM PROJECT_INSTANCE_BASE PIB INNER JOIN PROJ_INST_PIPELINE PIP ON PIB.PROJECT_INSTANCE_ID = PIP.PROJECT_INSTANCE_ID AND PIP.PROJECT_NUMBER= PIB.PROJECT_NUMBER AND PIB.PROJECT_TYPE_NUMBER IN (5,105, 106)),
                SF_PROJ AS
                    (SELECT PJTINST.PROJECT_INSTANCE_PIPELINE_ID, PJTINST.PROJECT_INSTANCE_ID, PJTINST.PROJECT_NUMBER, PJTINST.PIPELINE_STRING, PJTINST.ORIGINAL_PROMOTER, PJTINST.SOURCE_SET_INSTANCE, PJTINST.PROJECT_TYPE_NUMBER, PJTINST.PACKET_NUMBER, SFP.PROJECT_NAME,
                    PJTINST.SUBVERSION_PROJECT_REVISION, PJTINST.SUBVERSION_PROJECT_URL, PJTINST.Front_End, PJTINST.Back_End FROM DBO.SF_PROJECT SFP INNER JOIN PROJ_INST_BASE PJTINST ON SFP.PROJECT_NUMBER = PJTINST.PROJECT_NUMBER),
                USER_DETAIL AS
                    (SELECT SFP.PROJECT_NAME, SFP.PROJECT_NUMBER, SFP.PROJECT_TYPE_NUMBER, SFP.SOURCE_SET_INSTANCE, SFP.PACKET_NUMBER, SFP.PIPELINE_STRING, SFP.SUBVERSION_PROJECT_REVISION, SFP.SUBVERSION_PROJECT_URL, SFP.PROJECT_INSTANCE_PIPELINE_ID, SFP.PROJECT_INSTANCE_ID, AIAA.EMAIL_ADDRESS, SFP.Front_End, SFP.Back_End
                    FROM SF_ASSOCIATE_INFO_ALL_ASSOCIATES AIAA INNER JOIN SF_PROJ SFP ON AIAA.OPER_ID = SFP.ORIGINAL_PROMOTER),
                FINAL AS
                    (SELECT UD.PROJECT_NAME, FP.Feature_Number, UD.PROJECT_NUMBER, UD.PROJECT_TYPE_NUMBER, UD.SOURCE_SET_INSTANCE, UD.PACKET_NUMBER, UD.PIPELINE_STRING, UD.SUBVERSION_PROJECT_REVISION, UD.SUBVERSION_PROJECT_URL,
                    UD.PROJECT_INSTANCE_PIPELINE_ID, UD.PROJECT_INSTANCE_ID, UD.EMAIL_ADDRESS, UD.Front_End, UD.Back_End  FROM [RTMaster].[dbo].[Feature_Projects_History] FP
                    INNER JOIN USER_DETAIL UD ON FP.Project_Instance_Pipeline_ID = UD.PROJECT_INSTANCE_PIPELINE_ID)
                SELECT * FROM FINAL order by PROJECT_NAME -- use here others column name as you need


text:
Q: What is the word for what an applicant applies to? If you are applying to a school you are an "applicant". What is the word for the thing you're applying to?
Similar to the sentence "the stalker stalks the stalkee", what would be in the blank in the sentence The applicant applies to the ______?

A: There are, as noted above, many things to which one can apply. A general concept that covers not every but a lot of things to which one can apply is an offer (of a position, grant, conference participation).

A: Grantor might be the closest.

An individual who conveys or transfers ownership of property. Syn: assignor, bequeather, bestower, contributor, devisor, donator, giver, investor, rewarder, testator. (TFD)

A: Position. "I am writing to apply for the position of Assistant Professor at  . . ."


text:
Q: How do I make these layers not overlap? http://removed.com/jquery/test.html#
I have three problems that I need help with.
1 ) When you click "More" on top right, it open a div #search and the background is being overlapped by the brown element below. I tried using z-index, but it didn't work.
2 ) I'm trying to make the div #search align directly beneath the "More", but upon setting the width of #search, it aligns to the left side.
3 ) When I hover over the navigation on the left, the popup is being overlapped by the text in the middle. I want the popup to be on top of the text.

A: Try giving the position:relative to element with id #search and set its z-index to a greater value such as 100


text:
Q: Стандартные средства для реализации Синхронизированной частично дублирующей коллекции Доброго времени суток.
Есть коллекция ObservalableCollection слева(3 поля) и ObservalableCollection справа(2 поля). Объекты в таблицах одинакового класса. По сути 2-ая таблица является отфильтрованной 1-ой таблицей. Я хочу связать 2 коллекции, чтобы при удаление из одной коллекции удалялся этот же элемент из другой коллекции и наоборот.
Вопрос: есть ли стандартные средства для подобного?(я имею ввиду код, фильтры в Xaml не могу использовать, ибо TreeView) и если нет, то как использовать ID элементов коллекции в другой коллекции?(не ID класса, а ID элемента. Т.е при добавлении элемента в одну коллекцию добавлялся в другую с тем же ID).
Чтобы не пересекалось, можно при добавлении в обе коллекции смотреть на главную таблицу.

A: Обычно, для этого используются представления. Например, CollectionView. Оберни в него свою коллекцию и установи свойство Filter. На изменения в ObservableCollection ты можешь подписаться - событие CollectionChanged. Так же для любого CollectionViewSource ты можешь задать свойство IsLiveFilteting для отслеживания изменений отдельных свойств.
Для того, чтобы обратится к отфильтрованным значениям, используйте обращение к свойству CollectionViewSource.View.


text:
Q: Generating invoice in django with Shiprocket API I'm trying to generate invoice of my order in django with shiprocket API. So far I'm getting success Response but the generated URL of PDF is somewhat not understandable.
#Response Im getting
"{\"is_invoice_created\":true,
\"invoice_url\":\"https:\/\/s3-ap-south-1.amazonaws.com\/kr-shipmultichannel-mum\/3116291\/invoices\/Retail000058ba9b309-c4bd-4c06-ba15-2cc76b7c5d1f.pdf\",
\"not_created\":[],\"irn_no\":\"\"}"

when I try to access above URL get - Access-Denied
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<Error>
AccessDenied
<Message>Access Denied</Message>
<RequestId>94ARWRYHGSBEZEH1</RequestId>
<HostId>j32LvksmWatylm3TdFGYuJ1qvBwJ39Lj+qIbbQ3CC7AEcrgHnOYGd9fDocMeEwDD4GpzjXQLQhg=</HostId>
</Error>

This is the way I want the url to be
https://s3-ap-south-1.amazonaws.com/kr-shipmultichannel-mum/3116291/invoices/Retail000058ba9b309-c4bd-4c06-ba15-2cc76b7c5d1f.pdf

When I remove the slashed I get in Response I'm able to download the PDF and that's done manually. So how do I get working URL.
#Views.py
class GenerateInvoice(APIView):

    def post(self, request):
        order_id = request.query_params.get("ids", None)
        print(order_id)
        data = json.dumps({"ids": [order_id]})
        headers = {
            "Content-Type": "application/json",
            "Authorization": settings.SHIPROCKET_TOKEN,
        }
        url = "https://apiv2.shiprocket.in/v1/external/orders/print/invoice"

        response = requests.post(url=url, data=data, headers=headers)

        return Response(response)

A: I think the result is response object. Try adding these:
response = json.loads(response.decode("utf-8"))


text:
Q: subsonic 3.0.0.3 MVC2 how to work paging Model.HasPreviousPage not working HI i wish to have some nice paging for my subsonic project, i am fine with the code behind
however i cant find any information with regards to paging on the view side of things ???
i have tried
Model.HasPreviousPage

but this no longer exists, so am all out of ideas on where to even begin, is there some hidden manual for this stuff somewhere, and activerecord as i really dont like having to come and ask
and would rather there was something i could read and search but for the most up to date stuff.
everything i find seems to be for old versions of MVC or old versions of subsonic or worse a mix of both.
much appreciated

A: okay this is what i have done of my own back, i would appreciate some views on if this is viable and acceptable please:
the code behind (Controller)
public ActionResult Index(int? page)
    {
        if (!validateInt(page.ToString()))
            page = 0;

        page = page - 1;

        if (page < 0)
            page = 0;

        const int pagesize = 9;

        IQueryable<material> myMaterial = material.All().Where(x => x.category == "Granite").OrderBy(x => x.id);
        var mycount = material.All().Where(x => x.category == "Granite").OrderBy(x => x.id).Count();

        ViewData["numpages"] = mycount / 9;
        ViewData["curpage"] = page;

        return View(new PagedList<material>(myMaterial, page ?? 0, pagesize));

    }

the Html
showing page <%=Convert.ToInt32(ViewData["curpage"]) + 1 %> of <%=ViewData["numpages"] %>

<%
   for (int i = 1; i <= Convert.ToInt32(ViewData["numpages"]); i++)
   {
      %>

      <%= Html.ActionLink(i.ToString(),"Index","granite",new{page=i},null) %>

      <%
   }

%>
the span is just basic, but if this is a good way then i will just style up my spans ???
I cant get this to page though, no matter what i seem to get the same 9 results, am a little confused now !!!
thanks


text:
Q: Yii2 load attribute of a referenced table I'm working with Yii2 to create an application. Consider a model A that has an attribute with an external reference to another model B (both of them have DB tables) by id. When I populate the view of the model A I need to show an attribute of the object B referenced which is not the id. By now I create a variable in the model A that is populated during the afterFind() by querying the db for the attribute relative to the id of the model B. Is there a better way to solve this problem that does not require to use afterFinds or more variables? Can you provide an example?

A: I think your solution is not the better way.
You can look at  this tutorial for sample about calculated and related field.
essentially you should do these step
1 ) Setup base model
 /* ActiveRelation */
public function getModelB()
{
    return $this->hasOne(TableB::className(), ['id' => 'country_id']);
}

/* Getter for ModelB Field name */
public function getModelBField() {
   return $this->modenB->name;

}
2 ) if useful  Setup search model
3 ) Setup view file
echo GridView::widget([
   'dataProvider' => $dataProvider,
   'filterModel' => $searchModel,
   'columns' => [
     ['class' => 'yii\grid\SerialColumn'],
     'id',
     'yuorField',
    'modelBName',
    ['class' => 'yii\grid\ActionColumn'],
  ]
 ]);

Look at the detail in the sample  for a complete explanation


text:
Q: Can't install datasets package via pip I'm trying to run a script that requires the datasets python package. I've tried installing this unsuccessfully using pip by calling:
pip install datasets
I know this hasn't worked because when I run the script I get the message:
Traceback (most recent call last):
  File "lda.py", line 2, in <module>
    import lda
  File "/Users/deepthought/lda.py", line 3, in <module>
    import datasets
ImportError: No module named datasets

I've installed python via homebrew.
When I run pip install datasets I get the error:
Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/ch/84cpkwc52zx0rsh4k5v4_7h40000gn/T/pip-build-gZWyT3/datasets/

I'm fairly new to scripting python or going under the hood of an OS X, so there's a risk I've missed something elementary.
I've been researching & trying to overcome this for about a week now including looking at similar questions on stackoverflow.com and haven't gotten past this stage for the duration. One of the tutorials I was working through told me to edit ~/.profile
This has been left like so:
# The orginal version is saved in .profile.pysave
#PATH="/Library/Frameworks/Python.framework/Versions/3.5/bin:${PATH}"
#export PATH
export PATH=/usr/local/bin:/usr/local/sbin:$PATH

/etc/paths contains:
/usr/local/bin
/usr/bin
/bin
/usr/sbin
/sbin

I'm running OS X El Capitan - 10.11.5 (15F34)
Python 2.7.11
Brew doctor flagged multiple items, but I've no idea whether it is worth fixing none/all of them:
Warning: Your XQuartz (2.7.7) is outdated
Please install XQuartz 2.7.9:
  https://xquartz.macosforge.org

Warning: Python is installed at /Library/Frameworks/Python.framework

Homebrew only supports building against the System-provided Python or a
brewed Python. In particular, Pythons installed to /Library can interfere
with other software installs.

Warning: Unbrewed dylibs were found in /usr/local/lib.
If you didn't put them there on purpose they could cause problems when
building Homebrew formulae, and may need to be deleted.

Unexpected dylibs:
    /usr/local/lib/libtcl8.6.dylib
    /usr/local/lib/libtk8.6.dylib

Warning: Unbrewed header files were found in /usr/local/include.
If you didn't put them there on purpose they could cause problems when
building Homebrew formulae, and may need to be deleted.

Unexpected header files:
    /usr/local/include/fakemysql.h
    /usr/local/include/fakepq.h
    /usr/local/include/fakesql.h
    /usr/local/include/itcl.h
    /usr/local/include/itcl2TclOO.h
    /usr/local/include/itclDecls.h
    /usr/local/include/itclInt.h
    /usr/local/include/itclIntDecls.h
    /usr/local/include/itclMigrate2TclCore.h
    /usr/local/include/itclTclIntStubsFcn.h
    /usr/local/include/mysqlStubs.h
    /usr/local/include/node/ares.h
    /usr/local/include/node/ares_version.h
    /usr/local/include/node/nameser.h
    /usr/local/include/node/node.h
    /usr/local/include/node/node_buffer.h
    /usr/local/include/node/node_internals.h
    /usr/local/include/node/node_object_wrap.h
    /usr/local/include/node/node_version.h
    /usr/local/include/node/openssl/opensslconf.h
    /usr/local/include/node/uv-private/ngx-queue.h
    /usr/local/include/node/uv-private/stdint-msvc2008.h
    /usr/local/include/node/uv-private/tree.h
    /usr/local/include/node/uv-private/uv-bsd.h
    /usr/local/include/node/uv-private/uv-darwin.h
    /usr/local/include/node/uv-private/uv-linux.h
    /usr/local/include/node/uv-private/uv-sunos.h
    /usr/local/include/node/uv-private/uv-unix.h
    /usr/local/include/node/uv-private/uv-win.h
    /usr/local/include/node/uv.h
    /usr/local/include/node/v8-debug.h
    /usr/local/include/node/v8-preparser.h
    /usr/local/include/node/v8-profiler.h
    /usr/local/include/node/v8-testing.h
    /usr/local/include/node/v8.h
    /usr/local/include/node/v8stdint.h
    /usr/local/include/node/zconf.h
    /usr/local/include/node/zlib.h
    /usr/local/include/odbcStubs.h
    /usr/local/include/pqStubs.h
    /usr/local/include/tcl.h
    /usr/local/include/tclDecls.h
    /usr/local/include/tclOO.h
    /usr/local/include/tclOODecls.h
    /usr/local/include/tclPlatDecls.h
    /usr/local/include/tclThread.h
    /usr/local/include/tclTomMath.h
    /usr/local/include/tclTomMathDecls.h
    /usr/local/include/tdbc.h
    /usr/local/include/tdbcDecls.h
    /usr/local/include/tdbcInt.h
    /usr/local/include/tk.h
    /usr/local/include/tkDecls.h
    /usr/local/include/tkPlatDecls.h

Warning: Unbrewed .pc files were found in /usr/local/lib/pkgconfig.
If you didn't put them there on purpose they could cause problems when
building Homebrew formulae, and may need to be deleted.

Unexpected .pc files:
    /usr/local/lib/pkgconfig/tcl.pc
    /usr/local/lib/pkgconfig/tk.pc

Warning: Unbrewed static libraries were found in /usr/local/lib.
If you didn't put them there on purpose they could cause problems when
building Homebrew formulae, and may need to be deleted.

Unexpected static libraries:
    /usr/local/lib/libtclstub8.6.a
    /usr/local/lib/libtkstub8.6.a

Warning: You have unlinked kegs in your Cellar
Leaving kegs unlinked can lead to build-trouble and cause brews that depend on
those kegs to fail to run properly once built. Run `brew link` on these:
    git
    python3

Warning: Broken symlinks were found. Remove them with `brew prune`:
    /usr/local/bin/github
    /usr/local/lib/perl5/site_perl/Git/I18N.pm
    /usr/local/lib/perl5/site_perl/Git/IndexInfo.pm
    /usr/local/lib/perl5/site_perl/Git/SVN/Editor.pm
    /usr/local/lib/perl5/site_perl/Git/SVN/Fetcher.pm
    /usr/local/lib/perl5/site_perl/Git/SVN/GlobSpec.pm
    /usr/local/lib/perl5/site_perl/Git/SVN/Log.pm
    /usr/local/lib/perl5/site_perl/Git/SVN/Memoize/YAML.pm
    /usr/local/lib/perl5/site_perl/Git/SVN/Migration.pm
    /usr/local/lib/perl5/site_perl/Git/SVN/Prompt.pm
    /usr/local/lib/perl5/site_perl/Git/SVN/Ra.pm
    /usr/local/lib/perl5/site_perl/Git/SVN/Utils.pm
    /usr/local/lib/perl5/site_perl/Git/SVN.pm
    /usr/local/lib/perl5/site_perl/Git.pm
    /usr/local/share/git-core/templates/description
    /usr/local/share/git-core/templates/hooks/applypatch-msg.sample
    /usr/local/share/git-core/templates/hooks/commit-msg.sample
    /usr/local/share/git-core/templates/hooks/post-update.sample
    /usr/local/share/git-core/templates/hooks/pre-applypatch.sample
    /usr/local/share/git-core/templates/hooks/pre-commit.sample
    /usr/local/share/git-core/templates/hooks/pre-push.sample
    /usr/local/share/git-core/templates/hooks/pre-rebase.sample
    /usr/local/share/git-core/templates/hooks/prepare-commit-msg.sample
    /usr/local/share/git-core/templates/hooks/update.sample
    /usr/local/share/git-core/templates/info/exclude
    /usr/local/share/man/man1/git-add.1
    /usr/local/share/man/man1/git-am.1
    /usr/local/share/man/man1/git-annotate.1
    /usr/local/share/man/man1/git-apply.1
    /usr/local/share/man/man1/git-archimport.1
    /usr/local/share/man/man1/git-archive.1
    /usr/local/share/man/man1/git-bisect.1
    /usr/local/share/man/man1/git-blame.1
    /usr/local/share/man/man1/git-branch.1
    /usr/local/share/man/man1/git-bundle.1
    /usr/local/share/man/man1/git-cat-file.1
    /usr/local/share/man/man1/git-check-attr.1
    /usr/local/share/man/man1/git-check-ignore.1
    /usr/local/share/man/man1/git-check-mailmap.1
    /usr/local/share/man/man1/git-check-ref-format.1
    /usr/local/share/man/man1/git-checkout-index.1
    /usr/local/share/man/man1/git-checkout.1
    /usr/local/share/man/man1/git-cherry-pick.1
    /usr/local/share/man/man1/git-cherry.1
    /usr/local/share/man/man1/git-citool.1
    /usr/local/share/man/man1/git-clean.1
    /usr/local/share/man/man1/git-clone.1
    /usr/local/share/man/man1/git-column.1
    /usr/local/share/man/man1/git-commit-tree.1
    /usr/local/share/man/man1/git-commit.1
    /usr/local/share/man/man1/git-config.1
    /usr/local/share/man/man1/git-count-objects.1
    /usr/local/share/man/man1/git-credential-cache--daemon.1
    /usr/local/share/man/man1/git-credential-cache.1
    /usr/local/share/man/man1/git-credential-store.1
    /usr/local/share/man/man1/git-credential.1
    /usr/local/share/man/man1/git-cvsexportcommit.1
    /usr/local/share/man/man1/git-cvsimport.1
    /usr/local/share/man/man1/git-cvsserver.1
    /usr/local/share/man/man1/git-daemon.1
    /usr/local/share/man/man1/git-describe.1
    /usr/local/share/man/man1/git-diff-files.1
    /usr/local/share/man/man1/git-diff-index.1
    /usr/local/share/man/man1/git-diff-tree.1
    /usr/local/share/man/man1/git-diff.1
    /usr/local/share/man/man1/git-difftool.1
    /usr/local/share/man/man1/git-fast-export.1
    /usr/local/share/man/man1/git-fast-import.1
    /usr/local/share/man/man1/git-fetch-pack.1
    /usr/local/share/man/man1/git-fetch.1
    /usr/local/share/man/man1/git-filter-branch.1
    /usr/local/share/man/man1/git-fmt-merge-msg.1
    /usr/local/share/man/man1/git-for-each-ref.1
    /usr/local/share/man/man1/git-format-patch.1
    /usr/local/share/man/man1/git-fsck-objects.1
    /usr/local/share/man/man1/git-fsck.1
    /usr/local/share/man/man1/git-gc.1
    /usr/local/share/man/man1/git-get-tar-commit-id.1
    /usr/local/share/man/man1/git-grep.1
    /usr/local/share/man/man1/git-gui.1
    /usr/local/share/man/man1/git-hash-object.1
    /usr/local/share/man/man1/git-help.1
    /usr/local/share/man/man1/git-http-backend.1
    /usr/local/share/man/man1/git-http-fetch.1
    /usr/local/share/man/man1/git-http-push.1
    /usr/local/share/man/man1/git-imap-send.1
    /usr/local/share/man/man1/git-index-pack.1
    /usr/local/share/man/man1/git-init-db.1
    /usr/local/share/man/man1/git-init.1
    /usr/local/share/man/man1/git-instaweb.1
    /usr/local/share/man/man1/git-log.1
    /usr/local/share/man/man1/git-lost-found.1
    /usr/local/share/man/man1/git-ls-files.1
    /usr/local/share/man/man1/git-ls-remote.1
    /usr/local/share/man/man1/git-ls-tree.1
    /usr/local/share/man/man1/git-mailinfo.1
    /usr/local/share/man/man1/git-mailsplit.1
    /usr/local/share/man/man1/git-merge-base.1
    /usr/local/share/man/man1/git-merge-file.1
    /usr/local/share/man/man1/git-merge-index.1
    /usr/local/share/man/man1/git-merge-one-file.1
    /usr/local/share/man/man1/git-merge-tree.1
    /usr/local/share/man/man1/git-merge.1
    /usr/local/share/man/man1/git-mergetool--lib.1
    /usr/local/share/man/man1/git-mergetool.1
    /usr/local/share/man/man1/git-mktag.1
    /usr/local/share/man/man1/git-mktree.1
    /usr/local/share/man/man1/git-mv.1
    /usr/local/share/man/man1/git-name-rev.1
    /usr/local/share/man/man1/git-notes.1
    /usr/local/share/man/man1/git-p4.1
    /usr/local/share/man/man1/git-pack-objects.1
    /usr/local/share/man/man1/git-pack-redundant.1
    /usr/local/share/man/man1/git-pack-refs.1
    /usr/local/share/man/man1/git-parse-remote.1
    /usr/local/share/man/man1/git-patch-id.1
    /usr/local/share/man/man1/git-peek-remote.1
    /usr/local/share/man/man1/git-prune-packed.1
    /usr/local/share/man/man1/git-prune.1
    /usr/local/share/man/man1/git-pull.1
    /usr/local/share/man/man1/git-push.1
    /usr/local/share/man/man1/git-quiltimport.1
    /usr/local/share/man/man1/git-read-tree.1
    /usr/local/share/man/man1/git-rebase.1
    /usr/local/share/man/man1/git-receive-pack.1
    /usr/local/share/man/man1/git-reflog.1
    /usr/local/share/man/man1/git-relink.1
    /usr/local/share/man/man1/git-remote-ext.1
    /usr/local/share/man/man1/git-remote-fd.1
    /usr/local/share/man/man1/git-remote-testgit.1
    /usr/local/share/man/man1/git-remote.1
    /usr/local/share/man/man1/git-repack.1
    /usr/local/share/man/man1/git-replace.1
    /usr/local/share/man/man1/git-repo-config.1
    /usr/local/share/man/man1/git-request-pull.1
    /usr/local/share/man/man1/git-rerere.1
    /usr/local/share/man/man1/git-reset.1
    /usr/local/share/man/man1/git-rev-list.1
    /usr/local/share/man/man1/git-rev-parse.1
    /usr/local/share/man/man1/git-revert.1
    /usr/local/share/man/man1/git-rm.1
    /usr/local/share/man/man1/git-send-email.1
    /usr/local/share/man/man1/git-send-pack.1
    /usr/local/share/man/man1/git-sh-i18n--envsubst.1
    /usr/local/share/man/man1/git-sh-i18n.1
    /usr/local/share/man/man1/git-sh-setup.1
    /usr/local/share/man/man1/git-shell.1
    /usr/local/share/man/man1/git-shortlog.1
    /usr/local/share/man/man1/git-show-branch.1
    /usr/local/share/man/man1/git-show-index.1
    /usr/local/share/man/man1/git-show-ref.1
    /usr/local/share/man/man1/git-show.1
    /usr/local/share/man/man1/git-stage.1
    /usr/local/share/man/man1/git-stash.1
    /usr/local/share/man/man1/git-status.1
    /usr/local/share/man/man1/git-stripspace.1
    /usr/local/share/man/man1/git-submodule.1
    /usr/local/share/man/man1/git-svn.1
    /usr/local/share/man/man1/git-symbolic-ref.1
    /usr/local/share/man/man1/git-tag.1
    /usr/local/share/man/man1/git-tar-tree.1
    /usr/local/share/man/man1/git-unpack-file.1
    /usr/local/share/man/man1/git-unpack-objects.1
    /usr/local/share/man/man1/git-update-index.1
    /usr/local/share/man/man1/git-update-ref.1
    /usr/local/share/man/man1/git-update-server-info.1
    /usr/local/share/man/man1/git-upload-archive.1
    /usr/local/share/man/man1/git-upload-pack.1
    /usr/local/share/man/man1/git-var.1
    /usr/local/share/man/man1/git-verify-pack.1
    /usr/local/share/man/man1/git-verify-tag.1
    /usr/local/share/man/man1/git-web--browse.1
    /usr/local/share/man/man1/git-whatchanged.1
    /usr/local/share/man/man1/git-write-tree.1
    /usr/local/share/man/man1/git.1
    /usr/local/share/man/man1/gitk.1
    /usr/local/share/man/man1/gitremote-helpers.1
    /usr/local/share/man/man1/gitweb.1
    /usr/local/share/man/man3/Git.3pm
    /usr/local/share/man/man3/Git::I18N.3pm
    /usr/local/share/man/man3/Git::SVN::Editor.3pm
    /usr/local/share/man/man3/Git::SVN::Fetcher.3pm
    /usr/local/share/man/man3/Git::SVN::Memoize::YAML.3pm
    /usr/local/share/man/man3/Git::SVN::Prompt.3pm
    /usr/local/share/man/man3/Git::SVN::Ra.3pm
    /usr/local/share/man/man3/Git::SVN::Utils.3pm
    /usr/local/share/man/man5/gitattributes.5
    /usr/local/share/man/man5/githooks.5
    /usr/local/share/man/man5/gitignore.5
    /usr/local/share/man/man5/gitmodules.5
    /usr/local/share/man/man5/gitrepository-layout.5
    /usr/local/share/man/man5/gitweb.conf.5
    /usr/local/share/man/man7/gitcli.7
    /usr/local/share/man/man7/gitcore-tutorial.7
    /usr/local/share/man/man7/gitcredentials.7
    /usr/local/share/man/man7/gitcvs-migration.7
    /usr/local/share/man/man7/gitdiffcore.7
    /usr/local/share/man/man7/gitglossary.7
    /usr/local/share/man/man7/gitnamespaces.7
    /usr/local/share/man/man7/gitrevisions.7
    /usr/local/share/man/man7/gittutorial-2.7
    /usr/local/share/man/man7/gittutorial.7
    /usr/local/share/man/man7/gitworkflows.7

Warning: Your Homebrew is outdated.
You haven't updated for at least 24 hours. This is a long time in brewland!
To update Homebrew, run `brew update`.

How do I make progress in diagnosing the issue with the installation of the datasets package?
Update
Here is the script I'm trying to run:
import sys
egg_path = '/usr/local/lib/python2.7/site-packages/datasets-0.0.9-py2.7.egg'
sys.path.append(egg_path)

import numpy as np
import lda
import datasets

X = lda.datasets.load_reuters()
vocab = lda.datasets.load_reuters_vocab()
titles = lda.datasets.load_reuters_titles()
X.shape
(395, 4258)
X.sum()
84010
model = lda.LDA(n_topics=20, n_iter=1500, random_state=1)
model.fit(X)  # model.fit_transform(X) is also available
topic_word = model.topic_word_  # model.components_ also works
n_top_words = 8
for i, topic_dist in enumerate(topic_word):
     topic_words = np.array(vocab)[np.argsort(topic_dist)][:-(n_top_words+1):-1]
     print('Topic {}: {}'.format(i, ' '.join(topic_words)))

A: Using pip install datasets I was also not able to properly install this package. It seems like there is a bug in this particular package.
The DESCRIBE.rst file is simply missing. To fix this just download the plain package from PyPi. https://pypi.python.org/pypi/datasets/0.0.9
Then adjust the setup.py file (remove the description).
Afterwards you need to install using python setup.py install. Don't forget to add the installed package to your Python path!
To do so, I would recommend that you add the following to your script.
import sys
egg_path = '__MODULE_PATH__/datasets-0.0.9-py3.5.egg'
sys.path.append(egg_path)
import datasets

Otherwise, you can also add your module using:
export PATH=__MODULE_PATH__:$PATH

Alternatively, you could also simply pull the source code from the Github repository and just include it in your project. https://github.com/realtimeweb/datasets
Hope this was kind of helpful to your problem. If you got any further questions just let me know.

A: I just hit the same issue on a rapsberry pi, just found out this had been fixed but the error comes from the lack of ram to extract properly the package.
You can fix this by disabling the creation of a cache dir in ram adding the parameter
--no-cache-dir

for example
pip2 install --user --no-cache-dir datasets


text:
Q: Retrieving only the last row of a table, in the absence of a primary key I have a table that has 3 columns:

*

*Column 1: contains XML data (that contains a timestamp value)

*Column 2: contains the file name(with the path to it) corresponding to  XML data record (as to which file that XML data is stored in)

*Column 3: contains the offset of the XML data within that file
For instance, different file names can be

*

*C:\Extended Events\ReadWrite_0_130863592475800000

*C:\Extended Events\ReadWrite_0_130863685030030000

*C:\Extended Events\ReadWrite_0_130864300903760000
That is, the names assigned to the files are in incremental order.
Further each file name has different offset values in it, corresponding to the XML data value, returned above.
For instance,
C:\Extended Events\ReadWrite_0_130863592475800000 can have offset values 24576, 34816, 62976 (in an increasing order too)
Then, C:\Extended Events\ReadWrite_0_130864300903760000 can have offset values for itself independent of the above offset values.
I want to retrieve the file name and offset value corresponding to the last record returned i.e. if a total of 9 rows have been returned, I need the file name and offset value corresponding only to the 9th row.
I also want it to be optimal.
Using the MAX function isn't helping my case. I tried max(file_name) and it simply opened the Documents folder.

A: If you want the row with the highest offset value for each file, then:
;WITH x AS (SELECT [Column 1], [Column 2], [Column 3],
  rn = ROW_NUMBER() OVER (PARTITION BY [Column 2] ORDER BY [Column 3] DESC
  FROM dbo.source_table
)
SELECT [Column 1], [Column 2], [Column 3]
  FROM x
  WHERE rn = 1
  ORDER BY [Column 2];

If yu just want the row with the highest offset across all files, you don't want MAX(), but you can use TOP (1):
SELECT TOP (1) [Column 1], [Column 2], [Column 3]
  FROM dbo.source_table
  ORDER BY [Column 3] DESC;


text:
Q: Safari renders wrong after details element when use rem font size Safari 10.0.1 renders element following a details element wrong, when font size ist set to rem. The elements after the details rendered with font-size 1px.
HTML

  Some details

More info about the details.

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

CSS
html{
  font-size: 1em;
}

ul {
  font-size: 1rem;
}

If element gets rerendering (e.g. hover) element get´s repainted correct.
Is there any Workaround?

A: A workaround is set the detail element to display none on default and the show it via JavaScript. Not clean but works.

A: Better workaround is to no use  tag at all, just use a standard  instead. This bug drove me crazy for weeks until I just found out how to easily fix it.
Seems like a big flaw in Safari, the other browsers render properly.

A: Have you tried using ems instead of rems?


text:
Q: How to get progress of ZipFile.Read() I'm using this code ;
using (ZipFile zip = ZipFile.Read(FileName))
{
    zip.ExtractProgress += ExtractProgressHandler;
    zip.ReadProgress += ReadProgressHandler;
    zip.ExtractAll(AppDomain.CurrentDomain.BaseDirectory + "\\Library\\" + zip.Comment,ExtractExistingFileAction.OverwriteSilently);
}

But ReadProgress event never fires. I think i need to add event handler before using ZipFile.Read(). But i don't know how to do.

A: You could call the overloaded ZipFile.Read that takes ReadOptions. You can specify the event handler in the ReadOptions.
ReadOptions myReadOptions = new ReadOptions { ReadProgress = ExtractProgressHandler };
using (ZipFile zip = ZipFile.Read(FileName, myReadOptions))
{
    zip.ExtractProgress += ExtractProgressHandler;
    zip.ExtractAll(AppDomain.CurrentDomain.BaseDirectory + "\\Library\\" + zip.Comment,ExtractExistingFileAction.OverwriteSilently);
}

Note: I didn't test it, code provided as is.


text:
Q: displaying html page through apache i am using ubuntu and i have a html page named first.html at home/sanu directory and i have apache2 installed and running.i want host this page through apache from my pc how can i do that. (My pc's IP is :218.248.80.51) .i have tried to access "http://218.248.80.51/sanu/first.html" but its not working(Google Chrome could not connect to 218.248.80.51) in my browser.plz help me.

A: By default Apache points to /var/www on ubuntu, it would required extra configuration to get it to point at your home directory. Try moving your html file there, then you should be able to access it through your browser at http://localhost/first.html
To host the page for public viewing you'd need to configure your pc's & router's firewalls correctly to allow port 80.


text:
Q: Avoid "save for web" in Gimp Previously Gimp could directly open and save JPEG and PNG-images. Since Ubuntu 12.10 Gimp is upgraded and requires me to save via a "save for web"-dialog. I have several issues with this dialog and consider it a severe regression:

*

*It does not open the location-dialog in the folder where the "current image" lives. Requiring deep clicking.

*When chaning some details in the image, re-saving it as PNG or JPG requires me to go through all the steps instead of hitting a shortcut [ctrl]-[s].

*When opening a JPG, gimp forces me to save the image as xcf; probably so it can retain information; which makes little sense, because the JPG it opened is already lossy (lost information).

Is there a (hidden) setting to revert to the previous situation or to tweak the current one?
Am I doing something wrong? I can hardly beleive that one of the most important usages of Gimp (preparing images for web) has such a severe lack of detailed finishing.
Is there a bug- or issue in the Gimp issuetracker that I am not aware of, which deals with these issues?

A: For my workflow here the definitely fastest way to safe an edited file back to the path it resides is using the "File -> Overwrite xxx" menu which appears after an existing file was edited:

To further speed things up we can also define a key shortcut for file-overwrite which, after removing the shortcut for file-save could also be  Ctrl  +  S :

A: Gimp is freeware software made for linux, and the deep clicking you are mentioning, thats a common problem, because it returns you to the home folder, or any other folder you used last session. Thats a bug i think should be reported to the developers of gimp.
ctrl+s is to save it as a Gimp-project. When saving it as an image, you should export it, using ctrl+shift+E instead. Then you select what kind of image type you want, JPEG, PNG, BMP or what else on the list.
When openening a JPG-file, you open it in gimp as a project, and projects are by default as .xcf. Again, when doing small changes, you need to export it into a JPEG - like in photoshop. ctrl+shift+E, and overwrite your old image.
A smart thing could be to save the project with ctrl+s if you need to edit it, and then export it. Then you can edit texts and other things on the image by opening the project file, and then exporting it again, overwriting the old or making a new copy.


text:
Q: How to make a button API I am trying to make an easy to use button API in Lua with ComputerCraft, and I'm having some trouble. When I do:
os.loadAPI("button")
action=function()
    term.clear()
    term.setCursorPos(1,1)
    print("Hello!")
end

button.newButton("B1",5,5,20,10)
button.drawButton("B1",colors.orange,colors.white)
button.onClick("B1",action,true)

Nothing happens, it doesn't even draw the colors. I have done tests, and when I store something like colors.white as a variable, then print the variable, it returns the number code of that color, which comes from the colors API. Here is what I have:
--to use the newButton function, do this:
--button.newButton(exampleButton)

--to use onClick function, create a variable like this:
--exampleFunc=function()
--(code)
--end
--Then call onClick with the same variable:

--button.onClick(exampleButton,exampleFunc)

buttons={}
xPos=0
yPos=0

function removeButton(buttonName)
    for key, fields in pairs(buttons) do
        if key == buttonName then
            table.remove(button,buttonName)
        else
            print("ERROR: button name not available")
        end
    end
end

function onClick(buttonName,action,boolean)
    for key, fields in pairs(buttons) do
        if boolean then
            testClick(action)
        end
    end
end

function drawSeparateButton(x,y,w,h,outLineColor,fillColor)
    if key == buttonName then
        x=buttons[buttonName]["x"]
        y=buttons[buttonName]["y"]
        w=buttons[buttonName]["w"]
        h=buttons[buttonName]["h"]
        paintutils.drawBox(x,y,x+(w-1),y+(h-1),outLineColor)
        paintutils.drawFilledBox(x+1,y+1,x+(w-2),y+(h-2),fillColor)
    end
end

function testClick(action)
    for key, fields in ipairs(buttons) do
        x=buttons[buttonName]["x"]
        y=buttons[buttonName]["y"]
        w=buttons[buttonName]["w"]
        h=buttons[buttonName]["h"]
        x2=x+(w-1)
        y2=y+(h-1)
        button,xPos,yPos=os.pullEvent("mouse_click")
        if xPos>=x and xPos<=x2 and yPos>=y and yPos<=y2 then
            action()
        end
    end
end

function newButton(buttonName,X,Y,W,H)
    buttons[buttonName] = {x=X,y=Y,w=W,h=H}
end

function drawButton(buttonName,outLineColor,fillColor)
    for key, fields in ipairs(buttons) do
        if key == buttonName then
            x=buttons[buttonName]["x"]
            y=buttons[buttonName]["y"]
            w=buttons[buttonName]["w"]
            h=buttons[buttonName]["h"]
            x2=x+w-1
            y2=y+h-1
            x3=x+1
            y3=y+1
            x4=x+w-2
            y4=y+h-2
            paintutils.drawBox(x,y,x2,y2,outLineColor)
            paintutils.drawFilledBox(x3,y3,x4,y4,fillColor)
        elseif key ~= buttonName then
            print("Button name not availabel")
        end
    end
end

I just need to be able to store a color like colors.white in a variable and have it returned as colors.white, and not the color code. I also need to be able to check which button is clicked and run a function specified by the user when one of the buttons are clicked.

A: I'm going to walk through your prototype code and point out some errors I see and also try to answer your question. I'm going to assume that you want to set a key value in a table to an array and access that externally.

A quick and short answer to your question is that you can store tables within tables and access them through keys or indices. A design change I would make, however, is to store your exampleFunc as a member of each button table to associate it with a specific button.
Example:
buttons = {}
buttons.playButton = {x=0, y=0, w=10, h=10, func=function() return end}
buttons.quitButton = {x=0, y=30, w=10, h=10, func=function() return end}
...
buttons.quitButton.x = 10
buttons.playButton.func()

Tables have a key-value structure, where keys can be strings or numbers. There are multiple ways to access an array using a key depending on the data type of the key.
For example, instead of writing buttons.quitButton.x = 10 we could've written buttons["quitButton"].x = 10 or buttons["quitButton"]["x"] = 10 or buttons.quitButton["x"] = 10.
This page is a great starting point for learning about Lua's tables.

According to this page, os.pullEvent() is blocking, and you will only be able to check if one button is clicked per mouse click. Consider looping through your buttons table and checking every button to see if the mouse falls within its rectangular bounds. Once you find which button the mouse clicked, you can call its func member. While we're still discussing this method, the while true do loop is completely unnecessary.

function removeButton(buttonName)
    for buttonName in pairs(button) do
    ...

function newButton(buttonName)
    state=true
    for buttonName in pairs(buttons) do
    ...

You may come from a Python background where the statement if element in list exists but Lua has no such statement. The for loops you use are looping through every member of the list. You also aren't capturing all of the variables returned by the pairs() function. A fix for that would look something like the following:
function buttonFunction(buttonName)
    for key, fields in pairs(buttons) do
        if key == buttonName then
        ...
    end
end

There are multiple instances where you refer to the variable button when you mean buttons.


text:
Q: Other user profile when I access the site So it's the second time happening today. I enter the site and on the up-right other user's picture rep and badges appear. I clicked on it and it took me to his profile page, when on his page the up-right part with picture rep and badges turned to normal. It happened now and about 2 hours ago, and there were 2 different profiles. Why is this happening?

A: One possible explanation, as noted by Martijn Pieters in the comments, is a badly posed Cache-Control header, which seems to be a side effect of using [OutputCache], even when we take pains to ensure that it doesn't cache for logged in users. I've had another stab at hacking our already hacked implementation, with the result that it should now continue to behave as normal for anonymous users, but logged in users will receive Cache-Control: private for these pages.
I cannot say for sure whether this was the actual cause, but it is consistent with what we would expect if an intermediate proxy decided to cache.
As side notes, note that the public header included no-cache="Set-Cookie", so this wouldn't have led to any cookie hijacking - and only applies to GET requests.
If you inspect this page now you should see this in action. I will deploy to the other sites after a brief stability check.


text:
Q: Django POST request Via ajax? I am trying to submit values via ajax to django backend,but I'm keep getting this error Advice matching query does not exist , But it does exist in the database. I dont know what I am doing wrong.
Here is my code snippet for AJAX Request:
$.ajax({
    type: 'POST',
    url: '{% url "recsystem:saveData" %}',
    data: {
        'csrfmiddlewaretoken' : "{{  csrf_token  }}",
        'ansId' : data.ansId,
        'queTitle': data.queTitle,
        'queText' : data.queText,
        'desc': data.desc,
        'optionType': data.optionType,
        'anstextArray': data.anstextArray,
        'ansAdvicesArray': data.ansAdvicesArray
     },
     success: function(data){
         console.log(data);
     },
     error: function(error){
         console.log(error);
     }
});

Here is my function in Django view to save this data.
def saveData(request):

if request.method =='POST' and request.is_ajax():
    q = Question()
    q.question_title = request.POST['queTitle']
    q.question_text = request.POST['queText']
    q.description = request.POST['desc']
    q.options_type = request.POST['optionType']
    q.save()

    if not request.POST['ansId'] is None:
        followup = FollowUp()
        followup.description = ""
        followup.answer = Answer.objects.get(pk=request.POST['ansId'])
        followup.question = q
        followup.save()

    if not request.POST.get('anstextArray', False) is None:
        answers = []
        advices = []
        answers = request.POST.get('anstextArray', False)
        advices = request.POST.get('ansAdvicesArray', False)
        for an, ad in zip(itertools.repeat(answers), itertools.repeat(advices)):
            adviceList = []
            adviceList = ad
            answer = Answer()
            answer.question = q
            answer.answer_text = an

            for id in itertools.repeat(adviceList):
                answer.advice = Advice.objects.get(pk=id)

            answer.save()

    return JsonResponse({'result':'ok'})

else:
    return JsonResponse({'result':'nok'})

Here is my Database model:
class Question(models.Model):
  question_title = models.CharField(max_length = 250)
  question_text = models.TextField(max_length = 3000)
  description = models.TextField(max_length = 3000)
  options_type = models.CharField(max_length = 250)

  def __str__(self):
         return self.question_title

class Advice(models.Model):
  advice_label = models.TextField(max_length = 2000)
  advice_text = models.TextField(max_length = 3000)
  time_stamp = models.TextField( default=timezone.now, max_length= 2000)

  def __str__(self):
        return self.advice_label

class Answer(models.Model):
  question = models.ForeignKey(Question, on_delete=models.CASCADE)
  answer_text = models.CharField(max_length = 250)
  advices = models.ManyToManyField(Advice)
  def __str__(self):
         return self.answer_text

class FollowUp(models.Model):
  description = models.CharField(max_length = 250)
  answer = models.ForeignKey(Answer, on_delete=models.CASCADE)
  question = models.ForeignKey(Question, on_delete=models.CASCADE)

The problem lies somewhere, where I am trying to save the arrays as lists as then iterating through it.
Traceback:

File "C:\Users\habib\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\django\core\handlers\exception.py" in inner
41.             response = get_response(request)

File "C:\Users\habib\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\django\core\handlers\base.py" in _get_response
187.                 response = self.process_exception_by_middleware(e,
request)

File "C:\Users\habib\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\django\core\handlers\base.py" in _get_response
185.                 response = wrapped_callback(request, *callback_args,
**callback_kwargs)

File "C:\Users\habib\Desktop\recommender\src\recsystem\views.py" in saveData
177.                     answer.advice = Advice.objects.get(pk=id)

File "C:\Users\habib\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\django\db\models\manager.py" in manager_method
 85.                 return getattr(self.get_queryset(), name)(*args,
**kwargs)

File "C:\Users\habib\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\django\db\models\query.py" in get
380.                 self.model._meta.object_name

Exception Type: DoesNotExist at /recsystem/saveData/
Exception Value: Advice matching query does not exist.

A: Your question bit unclear to me but this kind of error literally happened when you trying to retrieve a nonexistent data from db using Model.objects.get() method.
I suspect your problem lies on following code.
Advice.objects.get(pk=id)

So to ensure that, debug this point to get the id and then manually checked in db whether the data associated with that id is exist or not.
Also you can use other method to retrieve data from db like get_object_or_404(Advice, pk=id) or even filter() method can help you.

A: Exception Type: DoesNotExist means that you filter based on the pk, but the data behind "=" is not an ID.
Make sure this itertools.repeat(adviceList) is a list of ID.


text:
Q: Seaborn's Violin plot can't be chained in for loop? I have the following dataset:
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

test_data = pd.read_csv('./data.csv',index_col = 0,header = 0)

and I wanted to explore my data. I can plot multiple scatter plots in succession using a for loop:
for c_type in sorted(list(set(test_data['Designation'].values))):
    fil_test_data = test_data[test_data['Designation'] == c_type]
    t_plt = sns.lmplot(x = 'Age',
                      y = 'Property_1',
                      hue = 'Timepoint',
                      data = fil_test_data)

However, it seems that I can't accomplish this if I switch to Seaborn's Violinplot (or a categorical-type plot like boxplot):
for cat_column in test_data.columns[:4]:
    test_data[cat_column] = test_data[cat_column].astype('category')
for greek in sorted(list(set(test_data['Designation'].values))):
    fil_test_data = test_data[test_data['Designation'] == greek]
    t_plt = sns.violinplot(x = 'Group',
                      y = 'Property_1',
                      hue = 'Timepoint',
                      data = test_data)
    ax = plt.gca()
    ax.set_title('Designation {}'.format(greek))

Is there a reason why plotting violinplots (or a categorical plot) can't work in a for loop?


text:
Q: Why lambda in default scope in rails I am a beginner of Rails. I want to ask you about Default Scope. Why does default_scope use 'lambda'? Please take a look at the class below.
Class Category < ActiveRecord::Base
  default_scope labmda { order('categories.name') }
end

Why not a typical block used instead of lambda?
To summarize my questions,

*

*What is lambda?

*Why is lambda used in default scope?

A: lambdas are basically a way to save a block or an anonymous function (like you do in javascript all the time).  If you don't know what a block is...
[1,3,5,6].map { |n| n * 2 }

The stuff in the braces (or between the do and end statement} is a block.
So instead of rewriting the block a bunch of times, you could save it like so:
my_lambda = lambda { |n| n * 2 }

And you can call it like so:
[1,3,5,6].map(&my_lambda)

Like Sergio said, you don't really need to lambda there. But I suppose you could save the block somewhere else and then use it with default_scope for it and several other classes.


text:
Q: Getting too many result on python browser Friends i want to extract live scores on espncricinfo i try with dryscrape :-
Import dryscrape as d
d.start_xvfb()
br = d.Session()
br.visit('http://www.espncricinfo.com/ci/engine/match/index.html?view=live')
for x in br.xpath('//*[@class = "innings-info-1"]'):
 x
#print 4 results
for y in br.xpath('//*[@class = "innings-info-2"]'):
 y
#print 4 results of 2nd innings
#but when i try combian then print tooo many results
for x in br.xpath('//*[@class = "innings-info-1"]'):
 for y in br.xpath('//*[@class = "innings-info-2"]'):
  x,'\n',y
#need 4+4=8 results but python prints 16 results

Please help me

A: You have double loop. First have 4 elements, second 4 element. So you iterate 4 times by second loop and get 4 + 4 + 4 + 4 = 16. Your code execute the way it should.
if you want to get list of result you can for example do it like this:
x = [x for x in br.xpath('//*[@class = "innings-info-1"]')]
y = [y for y in br.xpath('//*[@class = "innings-info-2"]')]
print(list(zip(x,y))


text:
Q: How to fix Mariadb Galera cluster error "Semaphore wait has lasted > 600 seconds" I am getting following error on one of my node in Galera cluster and after the error, this node goes shutdown and eventually out from the Galera cluster. Someone please help to fix this.
Mutex LOCK_SYS created /home/buildbot/buildbot/build/mariadb-10.5.8/storage/innobase/lock/lock0lock.cc:461, lock var 2
[ERROR] [FATAL] InnoDB: Semaphore wait has lasted > 600 seconds. We intentionally crash the server because it appears to be hung.


text:
Q: PyQt ERROR: Command errored out with exit status Python Question: I would like to install PyQt-fit.
I upgrade the pip and the supertools wheel
version pip: 20.0.2 and 1.0.1 for supertools.
I don't know what is going on.
C:\Users\Flor>pip install supertools
Requirement already satisfied: supertools in c:\users\flor\appdata\local\programs\python\python37-32\lib\site-packages (1.0.1)

ERROR:
C:\Users\Flor>python373 -m pip install --user PyQt-Fit
Collecting PyQt-Fit
  Using cached PyQt-Fit-1.4.0.tar.gz (104 kB)
Collecting distribute>=0.6
  Using cached distribute-0.7.3.zip (145 kB)
    ERROR: Command errored out with exit status 1:
     command: 'C:\Users\Flor\AppData\Local\Programs\Python\Python37-32\python373.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Flor\\AppData\\Local\\Temp\\pip-install-3jhprspf\\distribute\\setup.py'"'"'; __file__='"'"'C:\\Users\\Flor\\AppData\\Local\\Temp\\pip-install-3jhprspf\\distribute\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\Flor\AppData\Local\Temp\pip-install-3jhprspf\distribute\pip-egg-info'
         cwd: C:\Users\Flor\AppData\Local\Temp\pip-install-3jhprspf\distribute\
    Complete output (15 lines):
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\Users\Flor\AppData\Local\Temp\pip-install-3jhprspf\distribute\setuptools\__init__.py", line 2, in <module>
        from setuptools.extension import Extension, Library
      File "C:\Users\Flor\AppData\Local\Temp\pip-install-3jhprspf\distribute\setuptools\extension.py", line 5, in <module>
        from setuptools.dist import _get_unpatched
      File "C:\Users\Flor\AppData\Local\Temp\pip-install-3jhprspf\distribute\setuptools\dist.py", line 7, in <module>
        from setuptools.command.install import install
      File "C:\Users\Flor\AppData\Local\Temp\pip-install-3jhprspf\distribute\setuptools\command\__init__.py", line 8, in <module>
        from setuptools.command import install_scripts
      File "C:\Users\Flor\AppData\Local\Temp\pip-install-3jhprspf\distribute\setuptools\command\install_scripts.py", line 3, in <module>
        from pkg_resources import Distribution, PathMetadata, ensure_directory
      File "C:\Users\Flor\AppData\Local\Temp\pip-install-3jhprspf\distribute\pkg_resources.py", line 1518, in <module>
        register_loader_type(importlib_bootstrap.SourceFileLoader, DefaultProvider)
    AttributeError: module 'importlib._bootstrap' has no attribute 'SourceFileLoader'
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.


text:
Q: NFC tag - why use AAR and LaunchApp rather than URL intent with Android? Given that you can launch an installed android app using an NFC tag with a URL on it, using, e.g.:

<category android:name="android.intent.category.DEFAULT"/>
<data android:scheme="https"
          android:host="http://myurl.com"
          android:pathPrefix="/something" />

And that you can make that shorter using a url shortening service, or your own domain, and that redirects to the play store, why would you use an AAR on a tag? (Also, I believe the AAR intent wont pass data to the app).
I'm looking to make a tag that supports multiple OS, with as few bytes as possible - if I create a website that has links to each phone's store, what advantage is there to including an AAR or LaunchApp record on the tag?

A:
why would you use an AAR on a tag?

Because your (original, pre-edit) proposed URL would cause the tag to always go to the Play Store. An AAR is designed to only go to the Play Store if there are no apps on the device that can handle the primary NFC record. See my answer to my own question for more on this.
Your approach of using http://myurl.com/something should work fine, so long as:

*

*The tag is only supposed to be valid for your app

*Nothing else on the device advertises support for that specific host and path prefix


text:
Q: Is the set of rational numbers between $0$ and $1$ invariant under some ergodic transformation As the question suggests, I am trying to find an ergodic transformation on $[0,1]$ (equipped with the Borel algebra and the Lebesgue measure) that leaves $\mathbb{Q}\cap[0,1]$ invariant. Any thought is appreciated.

A: Consider
$$f(x)=\begin{cases}x&\text{if }x\in\Bbb Q+\sqrt 2\Bbb Z\\x+\sqrt 2\bmod 1&\text{otherwise}\end{cases} $$


text:
Q: Extract a random element from a list (and remove it), learning monads Im learning monads in Haskell with the haskell wikibook and my own newbie experiments
As my first step, i've copypasted the parts of the book related to monads to my own PDF using the great HaTeX library (by Daniel Díaz) while lightly reading such hard text (hard because of its content).
Below is my first attempt to practice what i learned: 7 versions of a function that takes a list and returns a random element from that list
Now my main question is, should i be using monad Transformers for the "remove the element" part? i've read they are used to mix monads,
 and i know i will be using the State monad and the List monad
Other than that, any comments on my code will be gratefully recieved (the style ones the most, as monads are about writing with style? :P)
import System.Random
import Control.Monad.Trans.State
import Control.Monad

------------------------ PRIMER INTENTO DE RANDOMNESS ------------------------
extractR' :: [a] -> a
extractR' xs = xs !! randomPos
  where
    n         = length xs
    randomPos = fst pareja
    pareja    = randomR (0,n-1) stdGen
    stdGen    = mkStdGen 0

-- extractR' siempre devuelve la misma cosa, al llamarla sobre la misma
-- lista   (por tanto NO SIRVE, NO ES ALEATORIO)
-- EJ:
-- *Deck> extractR' [1..100]
-- 46
-- (0.00 secs, 0 bytes)
-- *Deck> extractR' [1..100]
-- 46
-- (0.02 secs, 0 bytes)
-- *Deck> extractR' [1..100]
-- 46
-- (0.00 secs, 0 bytes)

------------------------ SEGUNDO INTENTO DE RANDOMNESS ------------------------
stdGen = mkStdGen 0

extractR'' :: StdGen -> [a] -> (a, StdGen)
extractR'' gen xs = (xs !! randPos , newGen)
  where
    n = length xs
    (randPos, newGen) = randomR (0,n-1) gen

-- esta version permite arrastrar el RNGenerator, pero es incomodisima de usar:

-- *Deck> extractR'' stdGen [1..100]
-- (46,40014 40692)
-- (0.00 secs, 0 bytes)
-- *Deck> let x = snd (extractR'' stdGen [1..100]) in extractR'' x [1..100]
-- (56,1601120196 1655838864)
-- (0.00 secs, 0 bytes)

------------------------ TERCER INTENTO DE RANDOMNESS -------------------------
extractR''' :: [a] -> State StdGen a
extractR''' xs = state sol
  where
    n   = length xs
    sol = \s -> ( xs !! (randPos s) ,  newGen s)
    randPos st = fst $ randomR (0,n-1) st
    newGen st  = snd $ randomR (0,n-1) st

-- extractR''' xs =
--   state ( \s ->
--     ( xs !! (fst $ randomR (0, (length xs)-1) s )
--     ,
--     snd $ randomR (0, (length xs)-1) s ) )

-- pruebas en pantalla:

-- *Main> runState (extractR ['a'..'z']) (mkStdGen 0)
-- ('d',40014 40692)
-- (0.00 secs, 0 bytes)
-- *Main> runState (extractR ['a'..'z']) (mkStdGen 0)
-- ('d',40014 40692)
-- (0.00 secs, 0 bytes)
-- *Main> runState (extractR ['a'..'z']) (mkStdGen 7854)
-- ('n',314309970 40692)
-- (0.00 secs, 0 bytes)

-- works well, but the code is bad (non-monadic)
-- but we are in the State monad, so the following works:

extractR2 :: [a] -> State StdGen (a,a)
extractR2 xs = liftM2 (,) (extractR''' xs) (extractR''' xs)

------------------------ CUARTO INTENTO DE RANDOMNESS -------------------------
extractR'''' :: [a] -> State StdGen a
extractR'''' xs = pr1 >>= f
  where
    n   = length xs
    pr1 = state $ randomR (0,n-1)
    f   = \k -> state ( \s -> (xs !! k , s) )

-- monadic code, se actualiza 1 vez el StdGen

------------------------ QUINTO INTENTO DE RANDOMNESS -------------------------
extractR_ :: [a] -> State StdGen a
extractR_ xs = pr1 >>= f
  where
    n   = length xs
    pr1 = state $ randomR (0,n-1)
    f   = \k -> state ( \s -> (xs !! k , g s) )
    g   = \stdG -> snd $ next stdG

-- monadic code, se actualiza 2 veces el StdGen

------------------------ SEXTO INTENTO DE RANDOMNESS --------------------------
extractR_' :: [a] -> State StdGen a
extractR_' xs =
  do
    generator <- get              -- get = state $ \st -> (st,st)
    let n = length xs
    let (k, newGen) = randomR (0,n-1) generator
    put newGen
    return (xs!!k)

-- traduccion del codigo:
extractR_'' xs =
  get >>=
    \generator -> let n=length xs in
      ( let (k, newGen)=randomR (0,n-1) generator in
        (put newGen >> return (xs!!k) ) )

-- *Main> :t extractR_''
-- extractR_'' :: (RandomGen t, Monad m) => [b] -> StateT t m b
-- *Main> :t extractR_
-- extractR_ :: [a] -> State StdGen a

-- ======o     o======
--    ___________
--   |___________|    -------------------------------------------------------------------------------
--    |\  /\  /\|     ------------------------        VERSION FINAL          ------------------------
--    |_\/__\/__|     -------------------------------------------------------------------------------
--   |___________|

 --    ??????????????????? (dont know which to choose)

By the way im doing this to finish my Maths degree, and after that i'll be looking to earn my livings through Haskell :D (am i asking for a miracle?)

A:
should i be using monad Transformers for the "remove the element" part? i've read they are used to mix monads, and i know i will be using the State monad and the List monad

But you are not using the list monad! You are just using lists. To say you are using the list monad would mean you are using (>>=) or return specialized to lists (or similar Monad-polymorphic functions specialized to lists), which you are not doing. So I think it makes perfect sense to use State, and not use any transformers.

Other than that, any comments on my code will be gratefully recieved (the style ones the most, as monads are about writing with style? :P)

I like your fourth attempt the best, which as a reminder was this one:
extractR'''' :: [a] -> State StdGen a
extractR'''' xs = pr1 >>= f
  where
    n   = length xs
    pr1 = state $ randomR (0,n-1)
    f   = \k -> state ( \s -> (xs !! k , s) )

The only tweak I would make is that I find your f a bit too complicated. Since you are not modifying the state at all, you need not use State-specific functions; one could write
    f   = \k -> return (xs !! k)

instead. And then one can apply a monad law, namely:
m >>= (\x -> return (f x)) = fmap f m

The final implementation I would want to see is thus:
extractR :: [a] -> State StdGen a
extractR xs = fmap (xs!!) pr1
  where
    n   = length xs
    pr1 = state $ randomR (0,n-1)

(One can of course spell fmap in several other ways, that in this case differ primarily in aesthetics, like (<$>), liftA, or liftM.)

A: You may want to take a look to the MonadRandom package.
import Control.Monad.Random

extractR :: MonadRandom m => [a] -> m a
extractR xs = (xs !!) <$> getRandomR (0, length xs - 1)

The MonadRandom constraint is satisfied by IO and RandT g m, which is essentially a StateT StdGen-based monad, usable in pure code.
Also, the library defines uniform, which is equivalent to your extractR (albeit its implementation is rather complex).


text:
Q: How do I stop having carriage returns added to my file output in Python? I'm trying to parse a BMP file, do some changes and then reassemble a new BMP using Python.
The carriage return seems to be a huge problem.  When I open the bitmap file using Notepad++ and search for "\r', the character does not exist.  I read the file in Python (readData = fileIn.read()) and try searching using readData.find('\r') it returns -1.  Searching for "\n" works fine.  All is good for now.
When I try to write this exact same block of text into a new BMP using fileOut.write(readData) and I use Notepad++ to search for "\r", I am able to find it (twice, each corresponding to the preexisting "\n" characters).
Is there a way to write this block of data to a new BMP without "\r" being added automatically?  I've tried applying .strip() and .replace('\r','') to the string before writing it to the new file.

A: You're probably opening the file as text (the default) when you want to open it as binary.
open("example.bmp", "rb") # to [r]ead as [b]inary
open("example.bmp", "wb") # to [w]rite as [b]inary

From the documentation:

The default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading. Thus, when opening a binary file, you should append 'b' to the mode value to open the file in binary mode, which will improve portability.

A: You are opening the file in text mode, while you need binary mode. Find more about open() here:
http://docs.python.org/library/functions.html


text:
Q: dict values pass into a function I have below dictionary
a={
'set1': {'fileName': 'filename1',
'moduleName': 'modulename1',
'connection1.name': 'connection1',
'connection.test':'connectiontest1',
'connection2.name': 'connection2',
'connection.test':'connectiontest2',
'queue1.name': 'queue1',
'queue1.test':'queuetest1',
'topic1.name':'topic1',
'topic1.test':'topic1test',
'topic2.name':'topic2',
'topic2.test':'topic2test',
'ServerName': 'serverone',
'DeploymentName': 'deployment1'
},

'set2':{'fileName': 'filename2',
'moduleName': 'modulename2',
'connection1.name': 'connection1',
'connection.test':'connectiontest1',
'queue1.name': 'queue1',
'queue1.test':'queuetest1',
'topic1.name':'topic1',
'topic1.test':'topic1test',
'topic2.name':'topic2',
'topic2.test':'topic2test',
'ServerName': 'servertwo',
'DeploymentName': 'deployment2'
}}

in each set, I need to pass it to a function to create a server from the above dictionary.
def create_server_config(fileName,moduleName,connection,connectiontest,topic,topictest,queue,queuetest,servername,deploymentname):

    create_queue(queue,queuetest)

    create_topic(topic,topictest)

    create_connection(connection,connectiontest)

In this I want to pass each set into a function as an argument So that it will create a server for each set, the problem here is queue,topic,connection has multiple increment values in each set. so anyone helps me with how to pass it to a function. for example, if I want to create a queue then under create_server_config function , need to pass all the queue and queuetest related to set1 dict.

A: I have a few questions for you. Based on that, the answer might change.
Below code assumes the following:

*

*In Set1 & Set2, there are two connection.test keys. This may be a typo. I am assuming the first one is connection1.test and second one is connection2.test

*connection1.name, queue1.name, and topic1.name will ALWAYS be present in each set

*If topic2.name exists but connection2.name and queue2.name does not exist, then it is OK to pass connection1.name and queue1.name values to create server config.

*Similarly, if any combination of connection2.name, connection2.test, queue2.name, queue2.test, topic2.name, topic2.test exists but the others do not exist, then the value from xxx1.name or xxx1.test will be used in its place where xxx is connection or queue or topic.
This code will call the create server config function for each value of the dict:
a={
    'set1':{'fileName': 'filename1',
            'moduleName': 'modulename1',
            'connection1.name': 'connection1',
            'connection1.test':'connectiontest1',
            'connection2.name': 'connection2',
            'connection2.test':'connectiontest2',
            'queue1.name': 'queue1',
            'queue1.test':'queuetest1',
            'topic1.name':'topic1',
            'topic1.test':'topic1test',
            'topic2.name':'topic2',
            'topic2.test':'topic2test',
            'ServerName': 'serverone',
            'DeploymentName': 'deployment1'
           },

    'set2':{'fileName': 'filename2',
            'moduleName': 'modulename2',
            'connection1.name': 'connection1',
            'connection1.test':'connectiontest1',
            'queue1.name': 'queue1',
            'queue1.test':'queuetest1',
            'topic1.name':'topic1',
            'topic1.test':'topic1test',
            'topic2.name':'topic2',
            'topic2.test':'topic2test',
            'ServerName': 'servertwo',
            'DeploymentName': 'deployment2'
           }
  }
for s,setkey in a.items():
    fileName       = setkey['fileName']
    moduleName     = setkey['moduleName']
    connection     = setkey['connection1.name']
    connectiontest = setkey['connection1.test']
    topic          = setkey['topic1.name']
    topictest      = setkey['topic1.test']
    queue          = setkey['queue1.name']
    queuetest      = setkey['queue1.test']
    servername     = setkey['ServerName']
    deploymentname = setkey['DeploymentName']

    print (fileName,moduleName,                     \
                         connection,connectiontest, \
                         topic,topictest,queue,     \
                         queuetest,servername,deploymentname)

    create_server_config(fileName,moduleName,       \
                         connection,connectiontest, \
                         topic,topictest,queue,     \
                         queuetest,servername,deploymentname)

    flag = False

    if 'connection2.name' in setkey:
        flag = True
        connection     = setkey['connection2.name']

    if 'connection2.test' in setkey:
        flag = True
        connectiontest = setkey['connection2.test']

    if 'queue2.name'      in setkey:
        flag = True
        queue          = setkey['queue2.name']

    if 'queue2.test'      in setkey:
        flag = True
        queuetest      = setkey['queue2.test']

    if 'topic2.name'      in setkey:
        flag = True
        topic          = setkey['topic2.name']

    if 'topic2.test'      in setkey:
        flag = True
        topictest      = setkey['topic2.test']

    if flag:
        print (fileName,moduleName,                 \
                         connection,connectiontest, \
                         topic,topictest,queue,     \
                         queuetest,servername,deploymentname)

        create_server_config(fileName,moduleName,   \
                         connection,connectiontest, \
                         topic,topictest,queue,     \
                         queuetest,servername,deploymentname)


text:
Q: An amusing idiom about forgetfulness? There is an idiom in Indian languages about forgetfullness.

A shepherd keeps a baby lamb under his armpit and searches for it the whole village

Is there an equivalent and amusing idiom in English.?
I knowhis memory is like a sieve

A: There are the idioms:

*

*It goes in one ear and comes out the other (meaning you immediately forget what you hear)

*He's having a senior moment (meaning someone is having a lapse in memory, perhaps due to old age or like someone older)

*He's got a brain like swiss cheese (meaning full of holes)

The only equivalent I can think of that is similar to your lengthy Indian saying is a common comedic trope of someone searching for their spectacles which are on sitting on top of their head.


text:
Q: C# - Program execution flow yield/pause/resume Could you tell me please if there is a way in C# to pause and resume the program execution flow as I would like to do below?
Or do you have an idea how to save/load the current thread call stack?
I am looking for a solution that does not creates new thread at all.
public class MyClass : InterruptableClass
{
    int x;

    public void Fn1()
    {
        x = 1;
        this.Interrupt();
        x = 2;
    }
}

static class Program
{
    static void Main()
    {
        MyClass c = new MyClass();

        c.Fn1();
        // Now c.x is 1

        if (c.IsInterrupted)
        {
            c.ResumeExecution();
            // Now c.x is 2
        }
    }
}

Unfortunately I cannot save / reload the call stack (StackTrace/StackFrame).

A: You should look into threads and thread synchronization using Events or Locks, depending on which is appropriate for your scenario.
You can tell a thread to wait for other threads or to wait until some event happens using these mechanisms, so that while it is actually waiting it will most likely (depending on OS) be context switched out, so other threads having work to do, can actually get on with work.

A: You may want to take a look at await keyword that will be introduced in the next version of C#.
If you need the solution now, consider using TPL continuations (Task.ContinueWith method).


text:
Q: Leaflet + Turf strange squareGrid behaviour After a week of tests, and researches I've decided to "give up" and ask you guys for some help.
What I'm trying to accomplish is fairly easy.

*

*Take the world map and split it in 4 quadrants (done)

*Take each quadrant, and using turf calculate how many squares of N units are contained.

Everything works fine with the 2 first quadrants: A (red), B (green)

In fact, if I then try to fill the first two quadrants with squares using turf the result is correct:

The problem is that when trying to replicate the same logic on the squares below, turf returns 0 squares...
The code used to create the 4 quadrants with Leaflet is the following:
const quadrantA = L.rectangle(L.latLngBounds(L.latLng(90, -180), L.latLng(0, 0)), { weight: 1, fillColor: 'red', color: 'red' });
const quadrantB = L.rectangle(L.latLngBounds(L.latLng(90, 0), L.latLng(0, +180)), { weight: 1, fillColor: 'green', color: 'green' });
const quadrantC = L.rectangle(L.latLngBounds(L.latLng(0, -180), L.latLng(-90, 0)), { weight: 1, fillColor: 'blue', color: 'blue' });
const quadrantD = L.rectangle(L.latLngBounds(L.latLng(0, 0), L.latLng(-90, 180)), { weight: 1, fillColor: 'yellow', color: 'yellow' });

quadrantA.addTo(this.map);
quadrantB.addTo(this.map);
quadrantC.addTo(this.map);
quadrantD.addTo(this.map);

Meanwhile the code used to calculate the squares in each quadrant with turf is the following:
const QGrid_A = turf.squareGrid(turf.bbox(quadrantA.toGeoJSON()), 500, { units: 'kilometers' });
const QGrid_B = turf.squareGrid(turf.bbox(quadrantB.toGeoJSON()), 500, { units: 'kilometers' });
const QGrid_C = turf.squareGrid(turf.bbox(quadrantC.toGeoJSON()), 500, { units: 'kilometers' });
const QGrid_D = turf.squareGrid(turf.bbox(quadrantD.toGeoJSON()), 500, { units: 'kilometers' });

Problem is, that the "second round" of calculations returns always 0 features for the quadrants C and D.
QGrid_A features: 800
QGrid_B features: 800
QGrid_C features: 0
QGrid_D features: 0
I've also read about that Leaflet reverses the standard GeoJSON coordinates positions, by using [LAT,LON] instead of [LON,LAT], so I've also tried to reverse the result of the Leaflet generated GeoJSONs by doing a reverse on the coordinates array, but still nothing.
I wonder where am I wrong here? Is it a problem of "looped" coordinates? Is it a problem due to a falsy conversion between Leaflet and Turf? Is it me dumb? Please help me guys.

A: My solution
At the end of the day, I've adopted another strategy. Pretty simple tbh.
I've created a polygon which is the "area to map". This polygon then is split in several sub-squares polygons. Each square then can be used as an individual "tile".
Using @turf/square-grid and @turf/bbox was to achieve this was pretty easy,
the code for this is all incapsulated in 2 functions:
export interface ISplitAreaInSubareasConf {
    squareCellSide?: number;
    units?: `meters` | `kilometers`;
}

private splitAreaToMapInSubAreas(areaToMap: Polygon, opts?: ISplitAreaInSubareasConf): BBox[] {
    const units = opts && opts.units ? opts.units : this.SQUARE_UNIT;
    const side = opts && opts.squareCellSide ? opts.squareCellSide : this.SQUARE_CELL_SIDE_IN_KM;

    const grid = turfSquareGrid.default(this.getAreaToMapBBox(areaToMap), side, {units, mask: areaToMap});

    return grid.features.map(feat => this.getAreaToMapBBox(feat.geometry));
}

private getAreaToMapBBox(areaToMap: Polygon) {
    return bbox.default(areaToMap);
}


text:
Q: How can I generate a fake coverage report for a Typescript/angularjs project with an artificial 0% coverage value? I'm dealing with some legacy code that is being ported to newer frameworks. We're not going to bother to start unit testing the legacy code, because as we port it we also revise the business specification.
However, for the sake of statistical accuracy, I would like to include the 0% coverage that we have in our legacy code into our full coverage report (that includes other non-legacy modules using different languages and frameworks).
Given that this is an angularjs project and due to complications given by the architecture (usage of requirejs, global variable, being split into multiple apps) I have already given up setting an actual Karma test environment, my question is:
what is the least painful way to generate a fake coverage report from the existing code that simply marks every line as not covered, yielding a 0% coverage report?
I need something in a standard format (lcov?) that can be uploaded to coverage report websites like codacy/codecov/codeclimate etc.


text:
Q: How do I have to use the Field type when writing a mysql storage engine? I am working on a storage engine for MySQL. But I am already struggling with simply parsing data. For example there is a method with the following signature:
int ha_engine::update_row(const uchar *old_data, uchar *new_data);

So the data is stored in the old_data and new_data arrays. However to get the data out of this array, one should use the Field class to access the data in these rows.
Now the problem is, that I have no idea how to do that. For example this code:
longlong val = table_share->field[0]->val_int();

will not work, or I don't know from which row I will get the first column. So how should one do that??
Thanks in adcance for any help!

A: You can use the field type information to determine the kind of variable to hold the data and also which function to use to fetch the data.
In my database applications, the type of the field is always known, as the program creates the tables and populates them.
I have a hierarchy of classes derived from a Field class:
class Field
{
  public:
    virtual std::string  get_field_name(void) const = 0;
    virtual std::string  get_value_as_string(void) const = 0;
    virtual void         load_from_mysql_record(const MySQLRecord& r) = 0;
};

class Field_Integer : public Field
{
  public:
    int m_value;
    std::string get_value_as_string(void) const
    {
        std::ostringstream oss;
        oss << m_value;
        return oss.str();
    }
};

class Field_String : public Field
{
  public:
    std::string m_value;
    std::string get_value_as_string(void) const
    {
        return m_value;
    }
};

Each field leaf class would use the get_field_name function to fetch the data from the MySQL record.  Alternatively, a method could be created in the Field class to fetch data in a record by field index.


text:
Q: Inline text change not updating on ajax request (but changes on DB) I'm using a script I found for changing a line of text on the go (you click on it and an input shows). It works fine without doing anything to the database but when I add my code for an update, it will update the DB but won't refresh the text after it submits. I'm totally lost now since I've been at it for hours, maybe I'm missing something very basic.
My JS:
$.ajaxSetup({
    url: '/ajax/nombreruta.php',
    type: 'POST',
    async: false,
    timeout: 500
});

$('.editable').inlineEdit({
    value: $.ajax({ data: { 'action': 'get' } }).responseText,
    buttons: '',
    cancelOnBlur: true,
    save: function(event, data) {
        var html = $.ajax({
            data: { 'action': 'save', 'value': data.value }
        }).responseText;

        //alert("id: " + this.id );

        return html === 'OK' ? true : false;
    }
});

nombreruta.php:
<?php session_start();

$action = isset($_POST) && $_POST['action'] ? $_POST['action'] : 'get';
$value  = isset($_POST) && $_POST['value'] ? $_POST['value'] : '';

include $_SERVER['DOCUMENT_ROOT'] ."/util-funciones.php";//for my db functions

$cnx=conectar();
$sel="select * from ruta where id_ruta='".$_SESSION['ruta']."'";

$field=mysql_query($sel, $cnx);
if($row=mysql_fetch_object($field)){
$data = $row->nombre;
}

switch ($action) {

// retrieve data
case 'get':
    echo $data;
    break;

// save data
case 'save':
    if ($value != '') {

        $sel="update ruta set nombre='".$value."' where id_ruta=".$_SESSION['ruta'];
        mysql_query($sel,$cnx) or die(mysql_error());

        $_SESSION['data'] = $value;

        echo "OK";
    } else {
        echo "ERROR: no se han recibido valores.";
    }
    break;

// no action
default:
    echo "ERROR: no se ha especificado accion.";
    break;
}

Firebug shows me that after I update my text it returns OK and after I refresh the site it will show the updated text but not before. I started thinking this approach is too much hassle but after so much hours I feel like I'm one step from my solution...
EDIT:
I'm using this plugin: http://yelotofu.com/2009/08/jquery-inline-edit-tutorial/
And my html is just
 Text

A: Your code works fine for me....
Here's the demo app I put together (asp.net, but basically the same minus the database).
Just to be clear: Press Enter to save. Click off to cancel (since you removed the buttons).
HTML

    Test 1

C#
public void ProcessRequest(HttpContext context)
{
    //Custom Object to Get and Format my Connection String from the URL
    QueryStringObjects QSO = new QueryStringObjects(context.Request, "InlineAjaxTest");

    //Look for any GET or POST params named 'action'
    switch (context.Request.Params["action"])
    {
        //If 'action' = 'save' then....
        case "save":
            //Open a connection to my database (This is a custom Database object)
            using (DataBrokerSql SQL = GetDataBroker(QSO.Connstring))
            {
                //Create a SQL parameter for the value of the text box
                DbParameter[] Params = {
                    new SqlParameter("@val", context.Request.Params["value"])
                };
                //Execute an Insert or Update
                SQL.ExecSQL(@"UPDATE
                                    Test_InlineAJAX
                                SET
                                    Value = @val
                                IF @@ROWCOUNT=0
                                    INSERT INTO
                                    Test_InlineAJAX
                                    VALUES
                                    (@val)", Params);

            }
            //Return OK to the browser
            context.Response.Write("OK");
            break;
        default:
            //Open a connection to my database
            using (DataBrokerSql SQL = GetDataBroker(QSO.Connstring))
            {
                //Get Value from my table (there's only one row so no need to filter)
                object obj = SQL.GetScalar("Select Value From Test_InlineAJAX");
                //If my value is null return "" if not return the value of the object
                context.Response.Write(obj != null ? obj.ToString() : "");
            }
            break;
    }
}

SQL
CREATE TABLE [dbo].[Test_InlineAJAX](
    [Value] [varchar](255) NULL
) ON [PRIMARY]

Not sure what else to tell you, but maybe something here will give you an idea...


text:
Q: UISaveVideoAtPathToSavedPhotosAlbum doesn't report error when disk is full When trying to save a video to the camera roll/photo album using
UISaveVideoAtPathToSavedPhotosAlbum

and the disk storage is full, there is no error in the call to the completion callback method
- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;

The only indication of the disk being full and the copy didn't work is that the video isn't there in the Camera roll afterwards.
Just wanted to check if someone else has got this to actually work or if this is a bug.


text:
Q: How to set background color of the plot and color for gridlines? Here is my code:
import plotly.graph_objects as go

fig = go.Figure()
fig.add_trace(go.Bar(
    name='Group 1',
    x=['Var 1', 'Var 2', 'Var 3'], y=[3, 6, 4],
    error_y=dict(type='data', array=[1, 0.5, 1.5]),
    width=0.15
))
fig.add_trace(go.Bar(
    name='Group 2',
    x=['Var 1', 'Var 2', 'Var 3'], y=[4, 7, 3],
    error_y=dict(type='data', array=[0.5, 1, 2]),
    width=0.15
))
fig.update_layout(barmode='group')
fig.show()

output:

I read this but code from seems depreciated and does not works.
Question: How to set background color of the plot and color for grid lines?

A: This should help
import plotly.graph_objects as go
from plotly.graph_objects import Layout

# Set layout with background color you want (rgba values)
# This one is for white background
layout = Layout(plot_bgcolor='rgba(0,0,0,0)')

# Use that layout here
fig = go.Figure(layout=layout)
fig.add_trace(go.Bar(
    name='Group 1',
    x=['Var 1', 'Var 2', 'Var 3'], y=[3, 6, 4],
    error_y=dict(type='data', array=[1, 0.5, 1.5]),
    width=0.15
))
fig.add_trace(go.Bar(
    name='Group 2',
    x=['Var 1', 'Var 2', 'Var 3'], y=[4, 7, 3],
    error_y=dict(type='data', array=[0.5, 1, 2]),
    width=0.15
))
fig.update_layout(barmode='group')

# Change grid color and axis colors
fig.update_xaxes(showline=True, linewidth=2, linecolor='black', gridcolor='Red')
fig.update_yaxes(showline=True, linewidth=2, linecolor='black', gridcolor='Red')
fig.show()

Sources:

*

*Grid line customization

*Background Customization