text:
Q: How do I make sure a call to another program has finished before I continue with the program? I am writing a program which uses a loop to run several Prism (a graphing program) scripts, exporting PNGs. However, I am having some difficulty with how Prism runs, and I have a couple of suspicions about what might be causing the problem, listed here:

*

*Prism is not finished doing everything it needs to do before I call it again

*I am using the wrong sort of pipeline to the command line, although I have also tried subprocess.popen() and os.system()

*For whatever reason the command I send to command line is waiting on the program for something

Some strange behaviour that I have encountered is that when I run the program, the Prism startup 'label' shows up on the screen but doesn't go away after a few seconds, indicating to me that Prism has started but is being prevented from running by my code (the particular code I think is causing this is shown below). Additionally, the window I create becomes unresponsive so I have to close the program. However, after I close it, Prism runs the script and I get the exported PNGs from one of the scripts (also indicating that the program might be preventing Prism from running).
A little bit of the code in question is:
    os.popen(create_full_prism_path(create_script_name(f)).replace('/', '\\'))
    while (not(path.exists(root.output_path + "\\" + f + ".TV.png"))):
        pass

Where
create_full_prism_path(create_script_name(f)).replace('/', '\\')
is the command being sent to the command line - I have tested printing and running this command after everything has run, and it works just fine.
while (not(path.exists(root.output_path + "\\" + f + ".TV.png"))):
        pass

is the while loop I am using to check that before I go through the loop again, Prism has actually created the PNG I am asking for.
I have tried workarounds to this problem but I can't seem to find a solution, does anyone know how this problem can be solved?


text:
Q: How to define multiple functions in single function declaration? In Fortran you can do something like this:
#:for DTYPE, NAME in [('real','ssygvd'), ('dble', 'dsygvd'), ('cmplx', 'chegvd')]

  subroutine ${DTYPE}$_something_${NAME}$(args)
  [some commands]
  end subroutine ${DTYPE}$_something_${NAME}$

Can something like this be done in Python?
I want to write a function like this for float, int and str.
def get_int_tuple(value):
   try:
       values = [int(i) for i in value.split(',')]
       assert len(values) in range(1,4)
   except (ValueError, AssertionError):
       raise argparse.ArgumentTypeError(
           'Provide a CSV list of 1 up to 3 integers'
       )

   # return our value as is if there is only one
   if len(values) == 1:
       return tuple(np.array(values))

   # if there are three - return a range
   return tuple(np.arange(*values))

Which I will then pass to the parser:
parser.add_argument(
    "--kernel",
    type=get_str_tuple,
    help="SVM kernel. Options: 'linear', 'poly', 'rbf' (default=rbf)"
)

parser.add_argument(
    '--c',
    type=get_float_tuple,
    help="C (hyper)parameter of 'rbf' kernel (default=0.05)."
)

parser.add_argument(
    '--degree',
    type=get_int_tuple,
    help="Degree of the 'poly' kernel. (default=3)."
)

A: The types themselves are first-class objects, so you can pass them as arguments to a single function.
First, define a function that defines the common function, closing over the desired type.
def make_type(type_, type_name):
    def get_tuple(value):
       try:
           values = [type_(i) for i in value.split(',')]
           assert len(values) in range(1,4)
       except (ValueError, AssertionError):
           raise argparse.ArgumentTypeError(
               f'Provide a CSV list of 1 or 3 {type_name}'
           )

       # return our value as is if there is only one
       if len(values) == 1:
           return tuple(np.array(values))

       # if there are three - return a range
       return tuple(np.arange(*values))
    return get_tuple

Then use make_type to create the necessary argument for the type argument to `add_argument.
parser.add_argument(
    "--kernel",
    type=make_type(str, "strings"),
    help="SVM kernel. Options: 'linear', 'poly', 'rbf' (default=rbf)"
)

parser.add_argument(
    '--c',
    type=make_type(float, "floating-point values"),
    help="C (hyper)parameter of 'rbf' kernel (default=0.05)."
)

parser.add_argument(
    '--degree',
    type=make_tuple(int, "integers"),
    help="Degree of the 'poly' kernel. (default=3)."
)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How append the fields data from backend into JSON file in Typo3 How can I write into existing JSON-file the data from backend-Formular in Typo3 directly?
And how can I later delete some data from JSON, when I delete them from the backend in Typo3?
All JSON enterings have a time stamp.
Thank you in advance!

A: as JSON, is not a linear file Format but rather a Serialized object. its not possible to append data to it.
what you have to to is:
1) read the json file
2) use json_decode() to get an stdObject or array
3) manipulate that data Object/array the way you want.
4) use json_encode() to convert it back to a string..
5) write it back to a file.
// Load The Data
$pathToYourFile = 'paht/somefile.json';
$dataString = file_get_contents($pathToYourFile);
$jsonDataArray = json_decode($dataString, true); // fetch Data as ArrayM
///Maniuplate the data like you want

$jsonDataArray['someValue'] = 'updated Value';

// write it back

$dataString = json_encode($jsonDataArray);
file_put_contents($dataString);


text:
Q: How do arrays in Excel translate into R? I'm trying to transition from using Excel to R, since I've heard it's more efficient especially when it comes to a lot of data; so, I'm pretty new to this all. I'm currently working on figuring out how to have two criterias in sheet 2 to link back to sheet 1, and have it retrieve the average, 25th percentile, 50th percentile, and 75th percentile.
For example, in sheet 2, column B I have a job title "Chief Executive Officer". In sheet 2, column C, I have an asset cut

So, for cell I5 in sheet 2 to be calculated, the formula will go to sheet 1 and look at column E and column AB to make sure it matches sheet 1, column B and C. Then it should take all those values that match in sheet 1, column G and calculate an average.
My current formulas work for excel, but it takes 6 hours to save a change.
I currently have the excel file turned into a csv file.
Here's how it looks in excel form (salaries are $ values, but are "x" for confidentiality reasons):
sheet 1
sheet 2

A: As stated in comments, it's hard to guess what you want to achieve and ask based on the information you provided. However, from the screenshots you linked I suppose you have one spreadsheet with registers on base salary and cut of each employee and you want to compute some statistics for base salary grouped by cut and job title.
The data spreadsheet can be imported in R quite easily. I suggest using the "Import Dataset" button in RStudio, which will generate for you the code to import an Excel spreadsheet.
There are several ways to do the computations you need in R. Probably, the simpler one is to use aggregate function with something like:
aggregate(base_salary, by=list(job_title, cut), mean)

That will compute the whole I column (average) in your spreadsheet. For columns J to L (quartiles):
aggregate(base_salary, by=list(job_title, cut), quantile, probs=c(.25,.5,.75))


text:
Q: Disable wordpress reordering functions in backend screen element Does anyone know how to disable WordPress reorder button? I mean the up and down arrow (located in the upper right corner of the image attached below), and not the collapse button. So the box will stay at the default original position. Fyi, I'm using the classic editor plugin.

It will be nice if this can be solved without a plugin :)

A: You have to add the following CSS to an admin.css file (name it whatever you like but it has to be a css file that applies to the admin.
You need the following in that file:
.order-lower-indicator,
.order-higher-indicator{
    display:none;
}

To enqueue a stylesheet properly in the admin:
https://developer.wordpress.org/reference/hooks/admin_enqueue_scripts/
It's the same basic process as enqueuing for the front end but you're just applying a different action: do_action( 'admin_enqueue_scripts', string $hook_suffix );


text:
Q: Query not running. There is # in mysql password I am running a mysqldump command from mac terminal. There is # in the password. Getting -bash: !3: event not found error in the terminal.
The command: mysql -uUNAME -pPASSWORD#PASS -e "SELECT * from TABLE_NAME" DB_NAME | sed 's/\t/","/g;s/^/"/;s/$/"/' > /Users/Desktop/name.csv
Need help! Thanks in advance.

A: You must escape special chars with backslash like
The command:
mysql -uUNAME -pPASSWORD\#PASS -e "SELECT * from TABLE_NAME" DB_NAME | sed 's/\t/","/g;s/^/"/;s/$/"/' > /Users/Desktop/name.csv


text:
Q: Single codebase for applications that target AWS as well as Azure for pass services such as service bus, blob, SQS/SNS etc I am having multiple applications which are deployed in Microsoft Azure. These applications are using various libraries from Microsoft for interacting with services such as Azure Servicebus (Topic & Queue), Blob, etc. There is a new requirement that these applications should run on AWS as well on Azure. Since service bus, blob are very specific to Azure. They are not available in AWS. AWS has equivalent services such as SNS/SQS, S3 bucket etc. AWS has different SDK's/libraries for interacting with there services.
This is a problem since I will have to maintain two different versions of the applications one for Azure and another for AWS. This is difficult to maintain and I want to avoid.
Is there any framework/pattern/approach which abstracts vendor-specific details to service bus or blob and work both with AWS & Azure using a single code base

A: Dockerize as much as posible and create a core project where all your Azure and AWS nuget packages are installed then create an abstract layer to use methods within your core project that connects to Azure or AWS services.
You can create this Core layer with both packages for Azure and AWS and depending on current configuration (or cloud being deployed) use methods in azure package or AWS package.

A: There are 2-3 ways if you want to target Azure, Aws or any other cloud using a single code base

*

*Libraries such as Simple.Bus targets Azure Service bus and RabbitMQ. But they are limited to message brokers. For storage, you may need to find another library that targets both environments.

*More appropriate solution is Dapr (Distributed application portable runtime) which not only facilitates microservice service-based development but also helpful in developing cloud-agnostic code. It has various building blocks such as State management and Pubish and Subscribe which can target Azure, AWS using a single code base. By replacing an appropriate component, You can switch from one cloud to another cloud without code change.

*If none of the above solution is not working for you for some reason, you may need to implement your own facade layer to target multiple clouds.


text:
Q: How do I return a selected value from a complicated dropdownlist in MVC? My dropdownlist works like a treeview.  Since, I cant seem to figure out if Html.DropDownListFor does this, I am having to do it the old fashioned way.  Here is my code.
View:

Controller:

How do I get the selected value (LocationId) back to my controller?  id="locSelection" in the view, brought in as object selection in the controller.  Thank you:)

A: *

*First of all it's not a old fashioned way it's the bootstrap way of replicating dropdown

*Second of all it's not a drop down element...
Since this contains only ul and li tags and those are not of input type you cannot post back the values...
Also another problem in the code is you are setting the ID locSelection on multiple elements and that too in a loop .. So you will have a whole lot of elements with the same ID which is a Big NO. The Id's must be unique else it's a nightmare when we start using Jquery on these elements...
Solution -- Use Jquery

*

*Remove the Id's

*Add a class to all the anchor tags eg: locSelection

*Maintain a hidden input field inside your form. We will use this hidden input field to post back the data on form submit.
<input type='hidden' name='locSelection' id='locSelection' />

*

*Now bind a click event to the anchor tag inside the li and inside this event put that Clicked anchor tag text value into the hidden input.

$('.locSelection').on('click',function(){
  $('#locSelection').val($(this).text());
});


text:
Q: Android 2.3 WebView goBackOrForward not working I have a WebView in my app, and based on various conditions I wish to go back to some element in the history. The obtained index is valid, although the WebView doesn't do anything (no onpagestarted) in 2.3. It works in 4.1+.
private Integer getBackIndex(){
    WebBackForwardList list = webView.copyBackForwardList();
    Integer backi = null;
    for(int i=list.getSize()-1;i>=0;--i){
        String url = list.getItemAtIndex(i).getUrl();
        //select the appropriate index and set to backi
    }

    return backi;
}

private void goBack(){
    Integer backi = getBackIndex();
    Assert.assertNotNull(backi);
    WebBackForwardList list = webView.copyBackForwardList();
    Log.d("web","going "+String.valueOf(backi-list.getCurrentIndex()));
    webView.goBackOrForward(backi-list.getCurrentIndex());
}

The log confirms that we're going back 2 indices, although nothing happens on my gingerbread device. Does this have to do anything with webView settings, or is this a bug?


text:
Q: storing different languages in sql table Using SQL server management, creating tables for a glossary for example where you will need different translations for different words .. i am storing 15 different languages such as french, italian, spanish .. but when storing these in a table theyre are outputted fine, but when creating a table valued function they dont output correctly. my return is a simple select and for Bulgarian it just outputs question marks
Is there any way to help sql management to read these languages better?
appreciate the help

ALTER FUNCTION [dbo].SelectExportObject ( @TITLE NVARCHAR(MAX) )
RETURNS @Result TABLE
(
  BG                NVARCHAR(MAX) ,
  CS                NVARCHAR(MAX) ,
  DE                NVARCHAR(MAX) ,
  EL                NVARCHAR(MAX) ,
  EN                NVARCHAR(MAX) ,
  ES                NVARCHAR(MAX) ,
  ET                NVARCHAR(MAX) ,
  FI                NVARCHAR(MAX) ,
  FR                NVARCHAR(MAX) ,
  GA                NVARCHAR(MAX) ,
  HU                NVARCHAR(MAX) ,
  IT                NVARCHAR(MAX) ,
  LT                NVARCHAR(MAX)
 )

AS
BEGIN

    DECLARE @BG VARCHAR(MAX)
    DECLARE @CS VARCHAR(MAX)
    DECLARE @DE VARCHAR(MAX)
    DECLARE @EL VARCHAR(MAX)
    DECLARE @EN VARCHAR(MAX)
    DECLARE @ES VARCHAR(MAX)
    DECLARE @ET VARCHAR(MAX)
    DECLARE @FI VARCHAR(MAX)
    DECLARE @FR VARCHAR(MAX)
    DECLARE @GA VARCHAR(MAX)
    DECLARE @HU VARCHAR(MAX)
    DECLARE @IT VARCHAR(MAX)
    DECLARE @LT VARCHAR(MAX)

    select  @BG = c.BG,
           @CS = c.CS,
           @DE = c.DE,
           @EL = c.EL,
           @EN = c.EN,
           @ES = c.ES,
           @ET = c.ET,
           @FI = c.FI,
           @FR = c.FR,
           @GA = c.GA,
           @HU = c.HU,
           @IT = c.IT,
           @LT = c.LT
    from tblTEST c where c.title = @Title

    /* Populate the values of @Str1 and @Str2 how ever you need to */

 INSERT INTO @Result (BG,CS,DE,EL,EN,ES,ET,FI,FR,GA,HU,IT,LT)
 VALUES (@BG,@CS,@DE,@EL,@EN,@ES,@ET,@FI,@FR,@GA,@HU,@IT,@LT)

    RETURN;
END

A: There's really no need for this to be a multi line table-value function, it'll perform much worse than an inline table-value function.
The problem you have is that you have declared your variables as a varchar, not an nvarchar, however, if we change it to a inline table-value function, then the problem doesn't even exist (as those variables disappear):
ALTER FUNCTION [dbo].SelectExportObject ( @Title nvarchar(MAX) )
RETURNS TABLE
AS

    SELECT t.BG,
           t.CS,
           t.DE,
           t.EL,
           t.EN,
           t.ES,
           t.ET,
           t.FI,
           t.FR,
           t.GA,
           t.HU,
           t.IT,
           t.LT
    FROM tblTEST t
    WHERE t.title = @Title;

GO


text:
Q: Dropdown list allow multi-select in sharepoint I have a trouble that : I have to implement a webpart contain a Field that look up into other list. But the requirement that it must allow multi-value, and multi-select as a dropdown-list.
Pls, help me :(

A: The data side is easy enough, use a multilookup field.
In a web part, the UI is standard .net/javascript and can be pretty much anything you have a consistent set of rules for. That is your real problem - if your client won't accept any of the standard methods of multiselect (checkboxlist, ctrl-click in a listbox or moving items between listboxes), get them to explain the details of how they want the dropdown to work.


text:
Q: Braintree drop in UI generate new nonce I've integrated the braintree drop in UI in my project and have added paypal, google pay and visa payments. Everything works fine, payments are submitting to the API etc. But if I use submit a payment which fails using the values from - https://developers.braintreepayments.com/reference/general/testing/php#transaction-amounts. The nonce has then been used, amending my basket price and submitting again fails as the nonce has already been used. I've looked through the documentation and all I can find about nonces is that it can only be used once (https://developers.braintreepayments.com/guides/payment-method-nonces) and nothing around refreshing or requesting a new nonce. Ideally I'd like to avoid having to force the user to enter the payment details again.
Is there another way of automatically requesting a new nonce?


text:
Q: Sql Server Stored Procedure with conditional Where Clause I have a combobox that sets the value of @NULLFather' and '@NULLMother. When the combobox is ticked the WHERE clause of stored procedure checks for the values of @NULLFather' and '@NULLMother and based on that gives a result. But I can't get it to work. Here is the code. I have also tried the case condition but still no success.
USE myStudentDB
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[ManualSearchStudents]
-- Add the parameters for the stored procedure here

@NullFather int = 1,
@NullMother int = 1

AS
BEGIN
 SET NOCOUNT ON;

 -- Insert statements for procedure here

 SELECT StudentName, FatherName, MotherName
 FROM StudentTable
 WHERE  IF(NULLFather > 0) THEN FatherName IS NULL
  AND   IF(NullMother > 0) THEN MotherName IS NULL
 ORDER BY StudentTable.StudentID DESC
END

A: I implemented a different solution:
First call the stored procedure and save it to a dataTable . Generate the sql statement string from the combobox. Apply the new sql string to the dataTable. Problem solved. Applied this and it works great. Here is the code:
    private DataTable StudentDataExtract()
   {
         DataTable ds = new DataTable();

        try
        {

            string sqlSelect = "SearchStudents";
            EntityConnection scontext = new EntityConnection();
            SqlConnection c = new SqlConnection(scontext.Database.Connection.ConnectionString);
            SqlCommand cmd = new SqlCommand(sqlSelect, c); //c.con is the connection string
            cmd.CommandType = CommandType.StoredProcedure;

            c.Open();

            SqlDataAdapter da = new SqlDataAdapter(cmd);
            SqlCommandBuilder commandBuilder = new SqlCommandBuilder(da);

            da.Fill(ds);

            c.Close();

            if (GetFilter != "")
            {
                ds = ManualFilter(ds);
            }
            else
            {
                string dataOrder = "SID DESC";
                DataView dv = ds.DefaultView;
                dv.Sort = dataOrder;
                ds = dv.ToTable();
            }

            return ds;

        }
        catch (SqlException e)

        {
            return ds;
        }
    }

    private DataTable ManualFilter(DataTable OldDataTable)
    {
        DataTable NewDataTable = new DataTable();
        try
        {
            NewDataTable = OldDataTable.Select(GetFilter, dataOrder).CopyToDataTable();
            return NewDataTable;
        }
        catch (SqlException)
        {
            return NewDataTable;
        }
        catch(Exception)
        {
            return NewDataTable;
        }
    }

    private string getfilter = "";
    public string GetFilter
    {
        get
        {
            IEnumerable<String> selectedData = combolist.Where(d => d.IsSelected).Select(d => d.myTableValue);
            string singleString = string.Join(" OR ", selectedData.ToArray());
            return singleString;
        }
        set
        {
            getfilter = value; OnPropertyChanged("GetFilter"); OnPropertyChanged("GetStudentData");
        }

    }

    public DataTable GetStudentData
    {
        get
        {
            return this.StudentDataExtract();
        }

    }

   public class ComboSet : ViewModelBase
    {
        private bool isSelected;
        public bool IsSelected
        {
            get { return isSelected; }
            set { isSelected = value; OnPropertyChanged("IsSelected"); OnPropertyChanged("GetFilter"); }
        }

        private string mydataproperty;

        public string myDataProperty
        {
            get { return mydataproperty; }
            set { mydataproperty = value; }
        }

        private string mytablevalue;

        public string myTableValue
        {
            get { return mytablevalue; }
            set { mytablevalue = value; }
        }

    }

    private ObservableCollection<ComboSet> combolist;

    public ObservableCollection<ComboSet> ComboList
    {
        get { return combolist; }
        set { combolist = value; }
    }


text:
Q: Kubernetes NodePort / Load Balancer / Ingress on a Multi-Master Setup: Is it necessary? I'm fairly new to this but I'm setting up a multi-master, high availability Kubernetes cluster of at least 3 masters and a variable number of nodes. I'm trying to do this WITHOUT the use of kube-spray or any other tools, in order to learn the true ins-and-outs. I feel I have most of it down except one bit:
My understanding is:

*

*A NodePort allocates a port to a specific service

*A Load Balancer is an external resource that allows for external access

*An Ingress Controller allows you to configure specific paths to services and ports.

Some points about my cluster:

*

*The pods I deploy can run on any machine in the cluster and don't need to be externally accessible.

*My masters are also worker nodes and can run pods

*etcd runs on each master

My question is, do I need a NodePort/LB/Ingress Controller? I'm trying to understand why I would need any of the above. If a master is joined to an existing cluster alongside another master, the pods are distributed between them, right? Isn't that all I need? Please help me to understand as I feel I'm missing a key concept.

A: First of all NodePort, LoadBalancer and Ingress has nothing to do with the setting up kubernetes cluster. These three are tools to expose your apps to the outside world so that you can access those apps from outside the kubernetes cluster.
There are two parts here:

*

*Setting up the highly available kubernetes cluster with three masters. I have written a blog on it, how to setup a multi-master kubernetes cluster, it will give you brief idea about how to setup multi master cluster in kubernetes.

https://velotio.com/blog/2018/6/15/kubernetes-high-availability-kubeadm

*Now once you have your kubernetes cluster ready, you can start deploying your applications on it (pods,services etc.). Those application you deploy might needs to be exposed to outside world, for example a website hosted on your kubernetes cluster and needs to be accessed from internet. Then these NodePort, Loadbalancer or Ingress comes into the picture. The difference between NodePort, LoadBalancer and Ingress and when to use what? is explained very well in this article here.

https://medium.com/google-cloud/kubernetes-nodeport-vs-loadbalancer-vs-ingress-when-should-i-use-what-922f010849e0

Hope this gives you some clarity.
EDIT: This edit is for kubeadm config file for 1.13(see comments)
apiVersion: kubeadm.k8s.io/v1beta1
kind: ClusterConfiguration
kubernetesVersion: stable
apiServer:
  certSANs:
  - "VIRTUAL IP"
controlPlaneEndpoint: "VIRTUAL IP"
etcd:
    external:
        endpoints:
        - https://ETCD_0_IP:2379
        - https://ETCD_1_IP:2379
        - https://ETCD_2_IP:2379
        caFile: /etc/kubernetes/pki/etcd/ca.crt
        certFile: /etc/kubernetes/pki/apiserver-etcd-client.crt
        keyFile: /etc/kubernetes/pki/apiserver-etcd-client.key


text:
Q: Render 404 page when route is incorrect or param is missing in url. React/Redux Below is my url : -
http://local.abc.com/pages/red/4
red and 4 is param , if it is unavailable or url is improper i want to redirect to 404 page.
for this i have added below route in routes.jsx
1 ] Routes.jsx
import React from 'react'
import { Route, IndexRoute } from 'react-router'
import App from 'layout/app'
import Home from 'pages/home'
import Wagers from 'containers/wagersContainer'
import NotFound from 'pages/notFound'

const ROUTES = (
  <Route path='/' component={App}>
    <IndexRoute component={Home} />
    <Route path="/wagers(/:trackCode)(/:raceNum)" component={Wagers} />
    <Route path="*" component={NotFound}/>
  </Route>
)
export default ROUTES

In this file I have added notfound component route.
Below is my app.jsx
2 ] App.jsx
import React from 'react'
import Navbar from 'layout/navbar'
import Footer from 'layout/footer'
import LoginPopup from 'common/popups/loginPopup'
import { Router, browserHistory, useRouterHistory } from 'react-router'

export default class App extends React.Component {

componentDidMount() {
    let emptyArr = [null, "undefined", '']
    console.log(this.props.children.params)
    if(this.props.children.params && !_.every(_.values(this.props.children.params))) {
        browserHistory.push('/notFound');
    }
}

render() {
    return (

            <Navbar />

                {this.props.children}

            <LoginPopup />

    )
}

}
This is main root component.
and below is my index.jsx
3 ] Index.jsx
require('./main.js');

import React, { PropTypes, Component } from 'react'
import ReactDOM from 'react-dom'
import { Router, browserHistory, useRouterHistory } from 'react-router'
import { Provider } from 'react-redux'
import configureStore from './store/configureStore'

import ROUTES from './routes';
let store = configureStore();

ReactDOM.render(
   <Provider store={store}>
       <Router history={browserHistory} routes={ROUTES} />
   </Provider>,
   document.getElementById('app')

);
When i write wrong url like http://local.abc.com/randommmm
Then it is rendring 404 page but if i miss some params then it is not returning 404.what should i do to handle notfound url.


text:
Q: Sort Django Rest API Endpoint Response by Date Let's say I have a response from a endpoint. I am using Django Rest Framework. Let's say this is what is returning from endpoint.
[
  {
    Name: "q4",
    Date: "2020-09-30T18:00:52+03:00",
    Url: "/test/test",
  },
  {
    Name: "q2",
    Date: "2020-10-01T13:32:21+03:00",
    Url: "/test",
  },
  {
    Name: "q1",
    Date: "2020-09-30T17:42:06+03:00",
    Url: "/xyz",
  },
  {
    Name: "q3",
    Date: "2020-09-30T13:04:23+03:00",
    Url: "...",
  },
  {
    Name: "q5",
    Date: "2020-10-01T13:04:45+03:00",
    Url: "...",
  },
]

How am I going to change ordering of response by respecting to date and time like this?
[
  {
    Name: "q3",
    Date: "2020-09-30T13:04:23+03:00",
    Url: "...",
  },
  {
    Name: "q1",
    Date: "2020-09-30T17:42:06+03:00",
    Url: "/xyz",
  },
  {
    Name: "q4",
    Date: "2020-09-30T18:00:52+03:00",
    Url: "/test/test",
  },
  {
    Name: "q5",
    Date: "2020-10-01T13:04:45+03:00",
    Url: "...",
  },
  {
    Name: "q2",
    Date: "2020-10-01T13:32:21+03:00",
    Url: "/test",
  }
]

A: Use order_by in the queryset to order the results:
Model.objects.order_by('creation_time')

Check the Queryset API reference for more details


text:
Q: Having fill issues with shapes in p5.js when using bezier() and curve() functions I'm having issues figuring out how to fill concave shapes when using the bezier() or curve() functions in the p5.js library. Not sure if there's another function I can use to get the same result without fill issues or what exactly I'm doing wrong here. I attached a picture of what the output looks like in the full program, along with snippets of the two objects I'm having issues with.
I've tried adding a fourth side to close the shape that way, but it doesn't seem to fix anything and from what I understand isn't necessary when CLOSE is passed to endShape()
Picture of Full Output (at time of posting)
Full Code (Note: code has been modified and a temporary fix has been implemented since posting the question)
Arm

function setup()
{
    createCanvas(200, 350); //modified for snippet
}

function draw() {
    let x = -270;//added for snippet
    let y = -450;//added for snippet
    let r,g,b = 200;//added for snippet

    strokeWeight(6);
    fill(r-40,g-40,b-40);

    beginShape(); // FIXME: Fix fill issue
    curve(x-150, y+490,x+340, y+470,x+420, y+775,x+420, y+680);
    bezier(x+337, y+520,x+370, y+550,x+370, y+680,x+380, y+775);
    bezier(x+380, y+775,x+370, y+680,x+370, y+550,x+337, y+520);
    bezier(x+380, y+775,x+390, y+780,x+410, y+780,x+420, y+775);
    endShape(CLOSE);
}
<script src="https://github.com/processing/p5.js/releases/download/v1.4.2/p5.min.js"></script>

Hand Cup

function setup()
{
    createCanvas(150, 80); // modified for snippet
}

function draw() {
     let x = -300;  // Added for snippet
     let y = -750; // Added for snippet
     let r,g,b = 200; // added for snippet

    strokeWeight(6);
    fill(r-40,g-40,b-40);

    strokeWeight(6);
    beginShape(); // FIXME: Fix fill issue
    bezier(x+420, y+775,x+430, y+790,x+430, y+780,x+440, y+820);
    bezier(x+380, y+775,x+370, y+790,x+370, y+780,x+360, y+820);
    bezier(x+440, y+820,x+410, y+830,x+390, y+830,x+360, y+820);
    endShape(CLOSE);
}
<script src="https://github.com/processing/p5.js/releases/download/v1.4.2/p5.min.js"></script>


text:
Q: XPages tracelog - output of JavaScript print() statement is not logged or shown In the .../IBM/Lotus/Notes/Data/workspace/logs directory I have seen some tracelog files written in XML, but I can't see the output of JavaScript print() statements in any of them.
I have already tried the XPagesLogFileReader Application from openntf.org: there are no tracelog files found at all. Console log files are shown.
How and where can I get and see current tracelog file entries? At the moment,I`m testing the examples of "Mastering XPages" Book.. there are lots of JavaScript print() statements.
Thank you in advance.

A: If you are running on a domino server the console output is saved to:
C:\ Domino Dir \data\IBM_TECHNICAL_SUPPORT\  and then the latest "console.log" file.
However the easiest way by far is to simply leave the server console open and just view that as it is printing.
if you are using the local web preview server heres a link to take a look at:
http://www.juliusbuss.de/web/youatnotes/blog-jb.nsf/dx/see-ssjs-print-statements-in-local-web-preview.htm


text:
Q: Excel text data import Step 3 select columns via keyboard on Mac I am experiencing the following issue in Microsoft Excel for Mac 2016. When using the From Text data import function and clicking through the first two steps (selecting "Delimited" and defining delimiter), Step 3 allows for changing the column data format. By default, column 1 is selected and I can click to select any other column that fits into the window, as shown in the screenshot below. However, it seems that it is not possible to select columns that are to the right of those visible in the window. In my example below, there are about four more columns to the right. Scrolling and arrow-keys seem to not work in the Mac version.
Is there a keyboard shortcut, or some other workaround, that I am missing?

A: Perform a two-finger touch (not a complete tap), more like a contact. A slider bar will appear at the bottom of the columns. Now is your chance to grab it with one-finger click. If you begin with the pointer in the bottom part of the columns, it is much easier to grab the slider as it should be under the pointer. This probably works on other such windows.


text:
Q: Freescale t4240qds: Serial Rapidio API I am trying to develope a protocol stack.As for now i have build the kernel and enabled the Rapidio interfaces in t4240 board. Where can i get the Serial Rapidio API for freescale t4240qds board?

A: You need to download the Linux SDK for QorIQ processors. Version 1.7 is the current release as of this writing. Its avalable here. You will need a freescale.com account if you don't have one already, which is free.


text:
Q: percent match within the same table Below I have an MySQL database where "id" is just an id for each row. "question" shows the id of the question. There are four questions, 11, 12, 13 and 14. For every question the user has four answer options (1,2,3 and 4) which is stored in the "answer" column. The "user" column indicates what user who answered. In this example we have user 10, 11 and 12
id      question    answer      user
1           11          2       10
2           12          2       10
3           13          3       10
4           14          4       10
5           11          2       11
6           12          2       11
7           13          4       11
8           14          1       11
9           11          2       12
10          12          2       12
11          13          1       12
12          14          1       12

Let's say that user 10 is the reference user which means that I want to know how well user 10 matches with the others. Using SQL and/or php code how can I match the answers of the users such that I get the matches in percent with the highest percent shown first. So in this example I'm looking for something like.
        user     percent
1       11       50%
2       12       75%

I'm not sure if this is possible all the way with only SQL. Maybe a bit of php is needed to convert the count to % for instance.

A: Finally i got your desired output
Try this:
SELECT * ,round(count(*)/(SELECT count(*) FROM `list` where user=10)*100) as
 pecentage FROM `list` as l where l.answer=(SELECT m.answer FROM `list` as m
 where m.user=10 and l.question=m.question) group by (l.user) order by pecentage

It will produce out put as

and you can add l.user!=10 in where condition if you don't want user 10 value.


text:
Q: Make a dependent target with an Xcode 6 template In Xcode 5, the Dependencies key along with an array of integers will indicate to create a dependency from another created target to the current target.
     <key>Dependencies</key>
        <array>
            <integer>1</integer>
        </array>

This indicates make the 1st target a dependency on the current (0th) one:

However in Xcode 6, the second target does not even get generated and the following gets logged to the console:
9/23/14 3:26:58.520 PM Xcode[14870]: Invalid target dependency for template from /Users/paulb/Library/Developer/Xcode/Templates/Project Templates/Application/TestApplication.xctemplate

From the debugger, it looks like Xcode 6 is expecting a string instead of an integer. Replacing the integer with a string will get rid of the console error and both targets get generated. However, the dependency does not get generated even if the string is the name of the target:

What needs to be done in a template to get Xcode 6 to create a target dependency?
Full .xctemplate here

A: Xcode 6 expects a string instead of a integer value for the Dependencies array. The string refers to the value of the new TargetIdentifer key.
For example, the zeroth (depending) target is changed from:
     <key>Dependencies</key>
        <array>
            <integer>1</integer>
        </array>

to
     <key>Dependencies</key>
        <array>
            <string>mylib</string>
        </array>

and the first (dependent) target has the following new key:
     <key>TargetIdentifier</key>
        <string>mylib</string>


text: Q: Extend background on two of three monitors I have three monitors (two with the same size) and I'd like to set the same extended background for the two monitors with the same size and I'd like to set another background on the different sized desktop. How can I manage to do that? I've been trying for half an hour but I can only set a different background for each monitor or extend the backgrounds through all the screens (which is the worst choice ever since the third monitor is in vertical and sized 900x1440 (width x height).


text:
Q: There is need to use beforeEach + browser.get while testing with Protractor + AngularJS within MEAN.js? I just began to use protractor in angularJS. I was facing an error:
I App Already Bootstrapped with this Element 'document' while changing ui-route states among my tests, and tried some workaround like browser.ignoreSynchronization = true, but it messed up. Although I recently noticed in angular-seed the tests using: beforeEach(function() { browser.get(''); });
This way didn't crash my tests, but I know that as the tests grow up it will affect the performance/execution time. Looking in AngularJS docs I didn't find details about it.
Thanks!


text:
Q: jQuery zoom function fails after several zoom ins and outs I am using the jQuery Zoomable maps Plugin for a WordPress site with two types of maps and legends. Under maintenance mode right now as it is not open to the public as of yet. I love its zoom in and out functionality. I even added a trigger to the legend to make links in the legend trigger zoom ins and outs on the maps which works with this extra code:
jQuery(document).ready(function ($) {
    $('#area-one-button').click(function() {
     $('#area-one').click();
    });
    });
But I have been having issues. After several zoom ins and outs sometimes zooming no longer works until I refresh the page or wait for a few minutes. When I click the zoom out button in the legend  I can no longer click on zoomable fields on the map as it somehow does not know I zoomed out. That is the issue. But how to solve this?
Link to all code files is here: http://javascript.pastebin.com/qpEHcDts (could only add one link)

A: With the help of a JavaScript developer I have managed to optimize the code based on the jQuery plugin as found here: http://www.gethifi.com/blog/a-jquery-plugin-for-zoomable-interactive-maps  somewhat. Here is the code in legend.js used to make certain areas clickable and to improve zoomability without delays.
jQuery(document).ready(function ($) {
    $('#1-coast-button').click(function() {
    $('#1-coast').click();
        });
    $('#island-1-button').click(function() {
     $('#island-1').click();
    });
    $('#water-button').click(function() {
     $('#water').click();
    });
    $('#2-coast-button').click(function() {
     $('#2-coast').click();
    });
    });

The basic code loaded on one map page itself is rather large, but here is one of the pop-ups loaded by code on one .html map page:

Royal X Resort

Text

Maps do load better now and customer is pretty satisfied.


text:
Q: ServiceStack REST service custom path error I am having trouble configuring my ServiceStack REST service to work on my production IIS 7.5 box.  It works fine running localhost, and it also works fine if I deploy in the root of "Default Web Site" -  /EmployeeSvc.  I have a virtual directory structure under Default Web Site for organizational purposes (note custom path in web.config).  I can browse successfully to the default.htm at this location, but when I try to execute the built-in /hello example I receive:
Server Error 404 - File or directory not found.
The resource you are looking for might have been removed, had its name changed, or is temporarily unavailable.
Like I said, the built-in /hello example works perfectly from localhost and from a root iis folder under default web site, but not from within a directory structure.  What am I doing wrong with the location-path?
Thanks in advance!  Here is web.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>

  <location path="Employees-NoAuth/WebServices/EmployeeSvc">
        <system.web>
          <httpHandlers>
            <add path="*" type="ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory, ServiceStack" verb="*" />
          </httpHandlers>
        </system.web>

        <!-- Required for IIS 7.0 -->
        <system.webServer>
          <modules runAllManagedModulesForAllRequests="true"/>
          <validation validateIntegratedModeConfiguration="false" />
          <handlers>
            <add path="*" name="ServiceStack.Factory" type="ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory, ServiceStack" preCondition="integratedMode" resourceType="Unspecified" allowPathInfo="true" verb="*" />
          </handlers>
        </system.webServer>
  </location>

  <system.web>
    <customErrors mode="RemoteOnly"/>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>

</configuration>

A: I'd try the following:
 1. Remove location node from web.config. Move SS configuration out of it.
 2. Register base URL path in your class derived from AppHostBase:
public override void Configure(Container container)
{
    this.SetConfig(new EndpointHostConfig { ServiceStackHandlerFactoryPath = "base/path" });
}


text:
Q: GRUB2 is unable to detect a fresh Fedora intstallation I have recently installed Fedora 30 using the default installation process, using a media drive to first try out a live version of the system and then installing to a drive. I have Ubuntu and Windows 10 installed since before on the system. My computer has three physical drives with a number of partitions across them. The problem is that Grub does not display the new Fedora installation at all.
I've tried a number of things to remedy this problem:

*

*In my BIOS settings the "UEFI BIOS boot option #1" is set to Fedora. This changes nothing, as Grub is started by default when I start up my machine.

*I've tried (after rebooting) using os-prober followed by update-grub. os-prober does not detect Fedora so it is not added to the list of boot options.

*Using "bootinfoscript" I've collected data on my partitions and confirmed that the Fedora installation is indeed there. Dump of its output here.

*Attempted using Grub-install to install grub on the physical drive (/dev/sdc)

*Tried simpler things such as making sure the drive was mounted and running update-grub after that, to no avail.
I'm aware my partitions and system is a bit of a mess, it's a result of me lacking knowledge on the topic and adding two more physical drives over the course of some years, while also adding more installs of operating systems.
My suspicion is that the issue might be related to UEFI, because I've noticed that my Ubuntu installation seems to boot in legacy BIOS mode, and it seems the Fedora installation has EFI files associated with it.
I feel like my knowledge on the topic is lacking and I'm not sure where to go from here. I would be happy to make sweeping changes to the setup I have currently. I'm also OK to not use Ubuntu anymore, as it is installed on an older and slow HDD. Windows 10 and Fedora is all I need going forward.

A: I found this line in the bootinfoscript output:
/dev/sdb7    *    308,977,664   310,026,239     1,048,576  ef EFI (FAT-12/16/32)

This is a EFI System type. But. It is on a MBR/dos labeled disk.
The bootinfoscript is very informative. You really have some boot loaders a bit everywhere. It should be fixable.
How exactly do you boot now, and what do you want for the futute?
Because with three separate Disks, and two OSs, and legacy and uefi bios and an existing dual boot: many possibilities. Even for the simple 1=win, 2=linux 3=data solution.
You should be able to start linux from any grub command line with the correct images and root. As from uefi shell.
If you UEFI boot into grub or uefi shell, and then start a kernel with a initrd from the same EFI-sp, you can have a busybox root=/dev/ram0 system without any real partition, just the 1 GB EFI system partition. What else you put on your three disks is...additional.
The hierarchy is:
BIOS legacy or uefi
   BOOTORDER (internal ones, external ones, uefi shell...)
      MENU bootloader  (or COMMAND uefi shell)

A uefi shell with scripts, and a bootloader with manual command line are very similar.

If everything is working (ie a correct uefi bios, no bad surprises), me personally would want it like this:
BIOS legacy (not used): boot windows from disk1, as before, via MBR
BIOS UEFI: three (or more) boot entries: for grub on disk2, one future on disk3, maybe plus a systemd-boot; and option "Uefi Shell" boot.
Bootloader MENU on disk2 (Linux disk): with one ore more entries for linux on same disk. This grub should also be able to boot windows on the dos disk1, and maybe chain-load disk3.
You can really build up a full circuit with all this. I hope you see the outline of what I mean. If not maybe try pen and paper. For me it is a bit too "far away".


text:
Q: How can I make parts of a SwiftUI transition crossfade, but other to not crossfade I have a view, with several subview (in my sample the label one and two). When I tap on one of them, I would like to transition to a view, where everything else, but that original view that I tapped on is still visible. (In my real world app it's different, but for the sake of a simple sample it's like that now).
Also in this sample the view is on the exact same position in both states, which is only to make the problem more visible.
So my problem now is that while i transition, SwiftUI implicitly uses a .transition(.opacity). Which is partly what I want, as it nicely fades out the view that I want to disappear, but it also crossfaces the view that is meant to matched-geometry-effect. And that crossfade produces this little (but noticeable) flicker.
How can I combine the animations (fade-out/in the views that should appear/disappear, but only move without any crossfade the view that should only move.
It's not noticeable if the views moved while crossfading, but if the view is not moving, one can notice it.
I have a very simple demo project setup to demonstrate my problem.
struct ContentView: View {

    @State var myToggleVar = true
    @Namespace private var animation

    var body: some View {

        Group {
            if myToggleVar {

                ZStack {
                    VStack {

                        Label("One", systemImage: "folder.fill")
                            .font(.system(size: 24, weight: .bold))
                            .frame(height: 80)
                            .onTapGesture {
                                withAnimation(.easeInOut(duration: 1)) {
                                    myToggleVar.toggle()
                                }
                            }
                            .matchedGeometryEffect(id: "one", in: animation)

                        Label("Two", systemImage: "folder.fill")
                            .font(.system(size: 24, weight: .bold))
                            .frame(height: 80)

                        Spacer()
                    }

                    Text("Tap on one, look carefully at the folder-icon. You will see a slight flicker due to the .opacity transition")
                        .multilineTextAlignment(.center)
                        .padding()
                }
                .frame(maxWidth: .infinity)
            } else {
                VStack {

                    Label("One", systemImage: "folder.fill")
                        .font(.system(size: 24, weight: .bold))
                        .frame(height: 80)
                        .onTapGesture {
                            withAnimation(.easeInOut(duration: 1)) {
                                myToggleVar.toggle()
                            }
                        }
                        .matchedGeometryEffect(id: "one", in: animation)

                    Spacer()
                }
            }
        }
    }
}


text:
Q: UIViewController doesn't adjust content insets when shown by another UIViewController (within a UINavigationController) I have a navigation controller whose root is a view controller (call it First). This First view controller has a button that, when pressed, shows another view controller (call it Second). This Second view controller has a single UITextView that covers the whole view.
In the storyboard, the sample text in the UITextView correctly starts below (but not underneath) the title bar. In other words, its content insets are set correctly.
However, when I run the app and I tap on the First view controller's button in order to show the Second view controller, the text is underneath the title bar. The text view's content insets are zero.
Why isn't the text view's top content inset automatically adjusted to account for the title bar?
I've created a "minimum" app that shows the problem: https://github.com/redcurry/TestContentInsets.
Note: I'm using Xamarin, but I imagine the same problem happens in iOS (I haven't tested it).

A: In the second View Controller please uncheck the "Adjust ScrollView Insets" check box.

A: You might be looking for this
Your view is starting from under the navigationController.
You just need to set this.


text:
Q: Laravel 5.8 null csrf_token() when used in api controller I'm working on Laravel 5.8 and php 7.1.3. using csrf_token() return value in controller function but not return any value in controllers/api controller. how to used csrf_token in api controller function.
Api controller :- Http/Controllers/Api/TestConroller.php
class TestConroller extends Controller
{
    public function __construct()
    {

    }

    public function getToken(Request $request){

        echo csrf_token();
    }
}

Routes:- routes/api.php
Route::get('getToken', 'Api\TestConroller@getToken');

url:-
http://localhost/laravel/api/getToken

if csrf token() not work in api controller then how to used token for verification in api.

A: Csrf token only works in web.php  not in api.php .Api's are stateless
if you check kernal.php
 protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Laravel\Jetstream\Http\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \App\Http\Middleware\HandleInertiaRequests::class,
        ],

        'api' => [
            'throttle:api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];

web middleware uses session .So For testing purpose if you comment below middleware
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,

then it will return null on web.php

A: if you want to use in api.php just add these 2 lines in kernel.php
\Illuminate\Session\Middleware\StartSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,

in
'api' => [
            'throttle:api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

section


text:
Q: increment numbers in a file that match a given pattern by a fixed amount I have a script that searches PDFs for certain errors and logs instances of them in a file with the corresponding page number. (Using Pdfgrep, in case you're interested.) The PDFs are for sections of a book and so aren't always numbered in print starting from 1. For each error in the log I want to show number that's actually printed on the page, called the folio, for ease of reference, rather than the PDF page number I currently have.
Not all lines in the log are errors. Here is some sample output:
Searches run on vol1.pdf, 01-06-2016

S01 SPACED SEMICOLON
77:  ences                                      Unit for Italian Studies: ; Dir C. KENNEDY      SUMMERS, P. M., Tropical Veterinary Science
143:BRAC Business School: ; Head Dr MD               BISWAS                                      Internet: www.diu.ac.bd
143:BRAC Development Institute: ; Dir Prof.        Dir for Student Welfare: GOUTAM KUMAR         Private control
261:Basic Institute of Biosciences: ; tel. (12)      College of Business Administration: Ir MARIA  Academic year: February to December
261:Basic Institute of Exact Sciences: ; tel.                                                      atinguetá
261:Basic Institute of Human Sciences: ; tel.        Committee on Ethics: Dr RODRIGO RICCI         Vice-Rector: MARILZA VIEIRA CUNHA RUDGE
299:Documentation sur les Traditions et les                                                        Interpreters (ASTI): ; Dir Dr ETIENNE ZÉ
328:              Political Science:            CRESPI, B. J.                         ing: ; tel. (604) 291-5240; f. 1987; Dir Dr R.

The file in the example starts at p81, captured in the script as $folio. For all lines that start with a number between 2 and 4 digits long followed by a colon I want to replace that number with N+($folio -1).
I had thought to use a loop like this to go through the log line by line.
while read line
    do
        # magic here

    done < $log

I'm fairly new to command line stuff. My first thought was to use grep ^[0-9]{2, 4} and somehow save that to a variable too then calculate, but while googling it seems maybe sed or awk might be more useful? I've found lots of answers that are for incrementing numbers by 1 etc. but nothing quite like this, and I'm unsure how to proceed. I'd be extremely grateful for any suggestions.
The $folio value differs every time so I'm collecting that via user input along with the $log filename to work on.
The headers (e.g. S01 SPACED SEMICOLON) need to remain intact.

A: My Perl is a  bit clumsy but:
perl -nle 's/^(\d{2,4}):/$1+82 . ":"/e && print' log

159:  ences                                      Unit for Italian Studies: ; Dir C. KENNEDY      SUMMERS, P. M., Tropical Veterinary Science
225:BRAC Business School: ; Head Dr MD               BISWAS                                      Internet: www.diu.ac.bd
225:BRAC Development Institute: ; Dir Prof.        Dir for Student Welfare: GOUTAM KUMAR         Private control
343:Basic Institute of Biosciences: ; tel. (12)      College of Business Administration: Ir MARIA  Academic year: February to December
343:Basic Institute of Exact Sciences: ; tel.                                                      atinguetá
343:Basic Institute of Human Sciences: ; tel.        Committee on Ethics: Dr RODRIGO RICCI         Vice-Rector: MARILZA VIEIRA CUNHA RUDGE
381:Documentation sur les Traditions et les                                                        Interpreters (ASTI): ; Dir Dr ETIENNE ZÉ
410:              Political Science:            CRESPI, B. J.

That says... "Process the file "log" and if you find a line that starts with 2-4 digits and a colon, calculate a replacement line. That line must have the number you found plus 82 and a colon. If you find any like that, print them"
It's kind of hard to explain, but anything in (...) on the left gets numbered and is available for use as $n on the right side. So the 2-4 digits we find become available as $1 in the replacement.
The bit that is doing the magic is the e which means "execute some more Perl to calculate the replacement string".
If you want the other lines (i.e. the headers and lines that don't start with numbers) to pass through intact as well, change the && into ;. And, in fact, as @123 kindly points out in the comments, if you want that, you can go with:
perl -pe 's/^(\d{2,4}):/$1+82 . ":"/e' log

Searches run on vol1.pdf, 01-06-2016

S01 SPACED SEMICOLON
159:  ences                                      Unit for Italian Studies: ; Dir C. KENNEDY      SUMMERS, P. M., Tropical Veterinary Science
225:BRAC Business School: ; Head Dr MD               BISWAS                                      Internet: www.diu.ac.bd
225:BRAC Development Institute: ; Dir Prof.        Dir for Student Welfare: GOUTAM KUMAR         Private control
343:Basic Institute of Biosciences: ; tel. (12)      College of Business Administration: Ir MARIA  Academic year: February to December
343:Basic Institute of Exact Sciences: ; tel.                                                      atinguetá
343:Basic Institute of Human Sciences: ; tel.        Committee on Ethics: Dr RODRIGO RICCI         Vice-Rector: MARILZA VIEIRA CUNHA RUDGE
381:Documentation sur les Traditions et les                                                        Interpreters (ASTI): ; Dir Dr ETIENNE ZÉ
410:              Political Science:            CRESPI, B. J.

A: An awk solution might look like this:
#!/bin/bash

# The awk script below relies on features of POSIX awk that are not present
# in legacy awk and are not enabled by default in some other awks (e.g.
# older GNU awk).  POSIX_AWK identifies a POSIX-compliant awk to use.
POSIX_AWK='/usr/bin/awk --posix'

# ...

folio=7

# ...

$POSIX_AWK -F ':' -v offset=$(($folio - 1)) '
/^[0-9]{2,4}:.*/  { sub(/[0-9]*/, $1 + offset) }
                  { print }
' $1

The awk program is embedded in the shell script.  Arithmetic expansion is used to compute the line number offset, which is then pre-assigned to an awk variable via a -v option (bash does this part when it expands the awk command line).  The -F ':' option tells awk to use the colon as a field separator; this is used as a convenience for extracting the leading number from numbered lines.  The program reads each line of the file specified by $log, substitutes the adjusted line number in lines that have a line number, and in every case prints the possibly-modified line to the standard output.


text:
Q: How would I monitor I/O on multiple circuits at the same time? I've got a device that communicates over a 8 wire cable. I'd like to examine the signals going into and out of the device without having to test each line individually with my multimeter. Is there a device better suited for this task?
I was imagining some kind of multi-channel multimeter that could monitor more than one circuit at a time, but even then I'm not sure I need that much detail (though if an affordable one existed < $150 I might consider it). Even a simple array of LEDs that lit when a given wire was active would almost be enough. Ideally something in between these two examples would be best.
Short of building something myself, is there some off-the-shelf tool/device that could serve this purpose?

A: Use eight comparators -- you can get 4/package using two LM339's -- and run the reference voltage (whatever you consider the level for a lead to be "active") to the + lead of each comparator.  The reference can be provided by a resistor divider, as shown in the schematic below (resistors R2 and R3).
Run each of the leads in your cable to the - leads of each comparator.  Connect the outputs to the cathode end of 8 LED's.  The anodes should be connected to +5 via resistors (shown as R1 in the schematic) chosen to limit the current to 6 mA (which is the minimum the LM339 can sink).
The reason for connecting the comparator "upside down" (reference to +, input to -) is so the comparator will ground the output (turn on the LED) when the input is > reference.
This scheme works whether the signals are analog or digital, as long as the reference voltage is chosen appropriately.

All eight channels can probably be built for two or three dollars.

A: It sounds like you want a Logic Analyzer. There are many available quite cheaply, such as the Saleae Logic (and illegitimate clones thereof).


text:
Q: Regexp for excluding line containing string from rest of the regexp I have bunch of strings like:
object field: TMemo
  Left = 6
  Top = 23
  Width = 390
  Height = 156
  Anchors = [akLeft, akTop, akRight, akBottom]
  ScrollBars = ssVertical
  TabOrder = 1
  OnChange = fieldChange
  OnKeyUp = fieldKeyUp
  AddMenu = True
  RightClickMoveCaret = True
  RightEdge = 0
end

Or
object btn: TButton
  Left = 5
  Top = 3
  Width = 89
  Height = 21
  Caption = 'Button'
  TabOrder = 0
  TabStop = False
  OnClick = btnClick
end

I want to select all text except name of object (in this case field and btn) and every line that starts with [space][space]On.
I can select everything without name of field using regexp like this:
(object)|(: .*)|(end)|(  .*)

But I'm not able deselect lines starting with "On".
Can you help me join my regexp with this regexp excluding this lines I want from selection?:
(^(?:(?!  On).)*$)

A: You could use a negative lookahead (?!  On)(  .*) for the last alternation to check what is on the right is not 2 spaces followed by On:
(object)|(: .*)|(end)|(?!  On)(  .*)

Regex demo
Since your matches are at the start and the end of the stirng, a more precise match might be using  anchors ^ and $:
^(object)|(: .*)$|^(end)$|^(?!  On)(  .*)

Regex demo
Note that you can also get the matches without using capturing groups:
^object|: .*$|^end$|^(?!  On)  .*

A: Try this regex (maybe)
^(?!On.*$).*


text:
Q: Replication stops with GTID_NEXT error after creation/drop of memory table in mysql5.6 We have recently upgraded to mysql5.6.25 from mysql5.5.x/mysql5.1.x on our mysql-cluster.
Below is a brief snapshot of our architecture.

Since we have upgraded and enabled gtid-mode we have been intermittently getting slave errors similar to :
Last_SQL_Error: Error 'When @@SESSION.GTID_NEXT is set to a GTID, you must explicitly set it to a different value after a COMMIT or ROLLBACK. Please check GTID_NEXT variable manual page for detailed explanation. Current @@SESSION.GTID_NEXT is 'd7e8990d-3a9e-11e5-8bc7-22000aa63d47:1466'.' on query. Default database: 'adplatform'. Query: 'create table X_new like X'
Our observations are as below..

*

*These slave errors are resolved simply by restarting the slave.

*Such errors are always with Create/Drop of tables which have Memory Storage Engine.

*Errors on Complete-Slave(B) show up continuously at a fixed minute (39th) of the hour and have been repeating since we have upgraded, almost a week.

*Errors on Complete-Slave as well as Partial slave are observed whenever its master is restarted.

*Cluster-1 and Cluster-2 have centos machines and Cluster-3 have ubuntu-machines. Slaves on centos machines also fail with the same error whenever its master(C/D) is restarted, but slave on ubuntu machines do not fail!!.

We have temporarily been able to live with this issue by setting up an action-script on our monitoring system which fires on slave error alert on any machine.
A look into gtid_next section in replication-options doc of mysql tells following

Prior to MySQL 5.6.20, when GTIDs were enabled but gtid_next was not
  AUTOMATIC, DROP TABLE did not work correctly when used on a
  combination of nontemporary tables with temporary tables, or of
  temporary tables using transactional storage engines with temporary
  tables using nontransactional storage engines. In MySQL 5.6.20 and
  later, DROP TABLE or DROP TEMPORARY TABLE fails with an explicit error
  when used with either of these combinations of tables. (Bug #17620053)

This seems related to my issue but still doesn't not explain my scenario.
Any hints/direction to solve the issue would be greatly appreciated...
EDIT :
I managed to find a similar recently reported bug in mysql(#77729), description of which is as follows :
https://bugs.mysql.com/bug.php?id=77729

When you have table with Engine MEMORY working on replication master,
  mysqld injects "DELETE" statement in binary logs on first access query
  to this table. This insures consistency of data on replicating slaves.
If replication is GTID ROW based, this inserted "DELETE" breaks
  replication.  Logged event is in STATEMENT format and do not generate
  correct SET GTID_NEXT statements in binary log.

Unfortunately, the status of this bug is marked as Can't Repeat...

A: I encountered a similar problem that generated the same error. On a master instance I dropped a database.
On a slave there was a file left over <tablename>.exp (I forget what purpose this serves).
The slave replication died with

last_Error: Error 'DROP DATABASE failed; some tables may have been
dropped but the database directory remains. The GTID has not been
added to GTID_EXECUTED and the statement was not written to the binary
log. Fix this as follows: (1) remove all files from the database
directory ./db_to_drop/; (2) SET
GTID_NEXT='c62b6474-84e6-11e8-bf49-00164ef9ea6c:73066506'; (3) DROP
DATABASE db_to_drop.' on query. Default database: 'db_to_drop'.
Query: 'drop database db_to_drop'

I removed the file, ran the SET and restarted replication:

SET GTID_NEXT='c62b6474-84e6-11e8-bf49-00164ef9ea6c:73066506';
start slave; ERROR 1837 (HY000): When @@SESSION.GTID_NEXT is set to a
GTID, you must explicitly set it to a different value after a COMMIT
or ROLLBACK. Please check GTID_NEXT variable manual page for detailed
explanation. Current @@SESSION.GTID_NEXT is
'c62b6474-84e6-11e8-bf49-00164ef9ea6c:73066506'.

And this, from following the suggestion. Since it's only a development cluster, I wasn't worried about losing it entirely, so I punted and tried setting it to the next GTID.
SET GTID_NEXT='c62b6474-84e6-11e8-bf49-00164ef9ea6c:73066507';
(i.e. + 1). Restarted replication and things got back to normal.


text:
Q: PHP Form - download to zip I have the following form:
<form action="download.php" method="get">
<input type="checkbox" name="file1" /> File1

<input type="checkbox" name="file2" /> File2

<input type="checkbox" name="file3" /> File3

<input type="checkbox" name="file4" /> File4

<input type="checkbox" name="file5" /> File5

<input type="submit" name="mysubmit" value="Download!">
</form>

I cant then GET the ticked value:
<?php echo $_GET["file1"]; ?>

Gives the result: on
However want I want to be able to do is select those options, and each option relates to a PHP file, on Submit each file is combiled into a ZIP
Any help appreciated.

A: *

*You can use isset($_FILES['file1']) to check if file1 is uploaded

*Loop from file1 to file5

*Save files from temporary paths to permanent ones

*Zip them using http://php.net/manual/en/book.zip.php & http://php.net/manual/en/ref.zip.php

*Optional: Delete the uploaded files (using unlink)

*Force download the zip file to the browser. See this: http://php.net/manual/en/function.header.php
It's quite simple. Enjoy!

A: First, add a value field to your form fields and change them to an array:
<form action="download.php" method="get">
<input type="checkbox" name="file[0]" value="1" /> File1

<input type="checkbox" name="file[1]" value="1" /> File2

<input type="checkbox" name="file[2]" value="1" /> File3

<input type="checkbox" name="file[3]" value="1" /> File4

<input type="checkbox" name="file[4]" value="1" /> File5

<input type="submit" name="mysubmit" value="Download!">
</form>

Next, in download.php:
if (!empty($_POST['file'])) {
    // open zip
    $zip_path = '/path/to/created/download.zip';
    $zip = new ZipArchive();
    if ($zip->open($zip_path, ZIPARCHIVE::CREATE) !== TRUE) {
        die ("An error occurred creating your ZIP file.");
    }
    // checkbox values dont matter because only checked boxes show up in POST data
    foreach ($_POST['file'] as $key => $val) {
        // generate filename to add to zip
        $filename = '/path/to/php/file' . $key . '.php';
        $zip->addFile($filename) or die ("ERROR: Could not add the file $filename");
    }
    $zip->close();

    //===============
    // force download
    //===============
// assume you have a full path to file stored in $zip_path
if (!is_file($zip_path)) {
  die('The file appears to be invalid.');
}

$zip_path = str_replace('\\', '/', realpath($zip_path));
$filesize = filesize($zip_path);
$filename = substr(strrchr('/'.$zip_path, '/'), 1);
$extension = strtolower(substr(strrchr($zip_path, '.'), 1));

// use this unless you want to find the mime type based on extension
$mime = array('application/octet-stream');

header('Content-Type: '.$mime);
header('Content-Disposition: attachment; filename="'.$filename.'"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.sprintf('%d', $filesize));
header('Expires: 0');

// check for IE only headers
if (isset($_SERVER['HTTP_USER_AGENT']) && (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false))) {
  header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  header('Pragma: public');
} else {
  header('Pragma: no-cache');
}

$handle = fopen($filepath, 'rb');
fpassthru($handle);
fclose($handle);

} // close $_POST check


text:
Q: How to insantiate a class after rotating the device I have a fragment which runs camera in it. and then in the main activity, I instantiate the class by passing the context to it
      Camera_play fragment1 = new Camera_play(this);

I have other fragments which play images and videos.
I rotate the device after 10 seconds to landscape mode and I need all the fragments to keep playing .
          Timer timer = new Timer();
          TimerTask action = new TimerTask() {

             public void run()
             {

                 runOnUiThread(new Runnable() {

                      public void run(){
                 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                      }

                 });
                      }

            };

            timer.schedule(action, 10000);

I handle the objects as follows :
   if(savedInstanceState == null)
     {
      frg1 = new Camera_play(this);
      frg2 = new play_video();
     android.support.v4.app.FragmentManager manager= getSupportFragmentManager();
     transaction=manager.beginTransaction();
     transaction.add(R.id.video, frg1,"frag1");
      transaction.add(R.id.camera, frg2,"frag2");
      transaction.commit();
     }
  else
   {
      **frg1 = new Camera_play(this);** ?????
      frg2 = (play_video) getSupportFragmentManager().findFragmentByTag("frag2");
   }

This works fine for the video but the app crashes for the video stating the instantation failed and the class msut have an empty constructor.
How do I make the camera to continue playing after I rotate the device?


text:
Q: Запуск виртуальной машины в vmware workstation после удаления Docker Установил Docker на машину с vmware workstation, из-за чего полетела вложенная виртуализация во втором. При попытке запустит машину получается следующая ошибка:
VMware Workstation does not support nested virtualization on this host.
Module 'HV' power on failed.
Failed to start the virtual machine.

Как всё исправить?


text:
Q: How to use drag in angularjs? http://jsfiddle.net/HB7LU/19316/
I have done a coding of drag .i could not able to drag the text.Once check the above fiddle.CAn anyone solve the problem

Hello U can drag me


text:
Q: What happens when Apple revokes a certificate? Regarding the fact that in iOS distribution model, each App should be signed by a certificate issued by Apple (either developer license, enterprise license, appstore, etc.), I wonder what happens when this certificate gets voided (e.g. because of legal issues) by Apple?

*

*Does the signed app stop working as soon as the certificate is
voided?

*Does the signed Apps stop working as soon as the user connects to internet?

*Does the signed Apps continue working, but cannot be updated?

*Does ... ???

Any Ideas?

A: The signed app remains signed and continues to work. But you will not be able to use the certificate to sign new apps.


text:
Q: Authorization and Windsor I'm trying to implement my custom authorize attribute like:
 public class MyCustomAuth : AuthorizeAttribute
{
    private readonly IUserService _userService;

    public MyCustomAuth(IUserService userService)
    {
        _userService= userService;
    }
... continued
 }

I am using Castle Windsor for automatically resolve the dependency.
When I try to use it as an attribute of an action method obviously I am asked to pass the parameter or I need to have a parameter-less constructor that should resolve in some way it's dependency.
I tried to inject the dependency with a property but Windsor is not injecting it.
The only option I see now would be to instantiate manually the concrete object dependency loosing the benefit of Windsor.
How would you solve this problem?

A: You cannot use DI with attributes - they're metadata;
public class MyCustomAuth : AuthorizeAttribute
{
    public void OnAuthorization(...)
    {
         IUserService userService = ServiceLocator.Current.GetInstance<IUserService>();
    }
}

Learn about Windsor/ServiceLocator here.
See similar question here.

A: You can use a custom ControllerActionInvoker and inject property dependencies (you can't do constructor injection because the framework handles instantiation of attributes).  You can see a blog post I just did on this technique.

A: You did not supply any castle code or configuration examples.  Therefore, I am assuming you are new to castle and unfimilar with the registration process.
First of all, any object you want to act upon must come from Castle Windsor via a registered type.  With that said, you are going down the wrong path by trying to use castle windsor with attributes - because attributes are not referenced in code, but instead are reflected upon.  Therefore, there is not a place for IoC (Castle Windsor in this case) to create the object.
I say this, because what you are trying to accomplish has already been done via different means.  First of all, put your dependency injection on your controllers.
public class PostController
{
  private IUserService _userService;
  public PostController (IUserService userService)
  {
    _userService = userService;
  }

  // other logic

}

For Castle to work, you have register all types.  So, you have to register IUserService, and what services implement that interface, within Castle Windsor.  You can do this via a manual process in your global.asax with container.AddComponentWithLifeStyle; or the more preferred method is to use a configuration file.
Using a configuration file, your IUserService would look something like this:
<?xml version="1.0" encoding="utf-8" ?>
<castle>
    <components>
        <!--lifestyle="singleton|thread|transient|pooled|webrequest|custom"-->

        <component
            id="UserService"
            service="MyMvcProject.IUserService, MyMvcProject"
            type="MyMvcProject.UserService, MyMvcProject"
            lifestyle="transient">
        </component>
    </components>
</castle>

MyMvcProject is the name of your project and make sure to use the exact namespace and fully qualified name of the interface, and type.  Please give code samples of your actual namespaces, else we cannot help you any further.
Before that will work, you will need to modify your app.config or web.config to register the searchGroup for Castle Windsor:
<configSections>

    <section name="castle"
        type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor"/>

</configSections>

<castle configSource="castle.config"/>

Now that you are all registered and setup, it is time to tell your MVC application to "Use Castle Windsor to create each instance of my Controllers."  Doing this means that Castle Windsor, being an Inversion-of-Control (aka IoC) container, will inspect the dependencies of your controller and see that it depends on IUserService and implement an instance of UserService.  Castle will look into its configuration of registered types and see that you have registered a service for IUserService.  And, it will see in your configuration file that you want to implement the concrete class of UserService that implements IUserService.  So, the IoC container will return UserService when a dependency on IUserService is requested.
But before that can happen, you have to tell your MVC application to use your configuired IoC container.  You do this by registering a new ControllerFactory.  To do that, see my answer over at this question:
Why is Castle Windsor trying to resolve my 'Content' and 'Scripts' folder as a controller?
And notice the global.asax part of how to register that code.  It works quite well!
Now, when all of that is said and done, you want to authorize a user.  Use the normal [Authorize] that implements Forms Authentication, and use your _userService to grab any user details of the signed in user.


text:
Q: Get an users playlist with Spotify API (how to add access token in http request angular 2?) I'm doing this course in udemy about building 12 different angular 2 apps, and one of them works with Spotify Web API and I'm adding more features to it;
I've learn how to work with simple GET request like
searchMusic(str:string, type='artist'){
    this.searchUrl = 'https://api.spotify.com/v1/search?query='+str+'&offset=0&limit=20&type='+type+'&market=US';
    return this._http.get(this.searchUrl)
        .map(res => res.json());
}

That function requires no auth key
But to get a playlist I need to pass an auth key to the request, otherwise I get an error instead of a Json formatted playlist
How do you append the auth key to the request to get rid of the error?
Thanks!

A: you can try this code
import this file
import { Http, Response, Headers, RequestOptions } from '@angular/http';

   searchMusic(str:string, type='artist'){
        let headers = new Headers({ 'Content-Type': 'application/json' },{'Authorization:'add_your_token_here'}); // ... Set content type to JSON
        let options = new RequestOptions({ headers: headers }); // Create a request option
        this.searchUrl = 'https://api.spotify.com/v1/search?query='+str+'&offset=0&limit=20&type='+type+'&market=US';
        return this._http.get(this.searchUrl, options)
            .map(res => res.json());
         }

for more information check these links
https://scotch.io/tutorials/angular-2-http-requests-with-observables
https://angular.io/docs/ts/latest/guide/server-communication.html#!#override-default-request-options
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';

@Injectable()
export class PfService {
  constructor(private http: Http) {}

  getProfile() {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    let authToken = localStorage.getItem('auth_token');
    headers.append('Authorization', `Bearer ${authToken}`);

    return this.http
      .get('/profile', { headers })
      .map(res => res.json());
  }
}

try this if above not work
i hope this will help

A: You may find it helpful if other answers wouldn't work...
import {Injectable} from '@angular/core';
import {Http, Headers} from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()

export class SearchService {
  private searchUrl: string;

  constructor (private _http: Http) {

  }

  searchMusic(str:string, type='artist'){
      let headers = new Headers();
      let authToken = 'Your OAuth Token Goes Here';
      headers.append('Authorization', 'Bearer '+authToken);
      this.searchUrl = 'https://api.spotify.com/v1/search?q='+str+'&offset=0&limit=20&type='+type+'&market=US';
      return this._http.get(this.searchUrl, { headers })
        .map(res => res.json());
  }
}

You can also generate OAuth Token from below link:
https://developer.spotify.com/web-api/console/get-search-item/


text:
Q: Order records in table by other table column I have 3 tables: articles, people and person_mentions.
Article model has_many :people, through: person_mentions and so on.
In person_mentions table I have 3 columns article_id, person_id and mention_order. mention_order is an integer.
I need to find all people, who mentioned in article and order them by mention_order, but when I run
@article.people.order(mention_order: :asc)

I get an error

column people.mention_order does not exist

So, I need to make a query from people table with mention_order from person_mentions in it.
Thanks for any help!

A: Could you try:
@article.people.order("person_mentions.mention_order asc")


text:
Q: Asking user to input a category to import file How can I ask a user to give input, so that I can import a random word from the list?
I have multiple lists ( for eg. people, place, animal, thing) so I want the user to input one of these categories to import a random word from these categories.
I can make one list but can't understand for multiple lists
My code for 1 list
import random
from words import word_list

def get_word():
    word = random.choice(word_list)
    return word.upper()

A: You can use the raw_input function. For example,
category=raw_input('Select a category (people, place, animal, thing):')
word = random.choice(category)

A: category = input("Enter category: ")

This will set the category Variable to the user input.
How youre gonna filter for a specific category will depend on the syntax of your words-library

A: You can use input() to get input from the user. Then you can simply use a if/else statement to return a word from the selected category. Similar to this:
import random

people = ['ada', 'frank']
animals = ['elephant', 'giraffe']
places = ['new york', 'tokyo']
things = ['phone', 'computer']

def get_word():
    category = input('please enter a category:\n')
    if category == 'people':
        return random.choice(people).upper()
    elif category == 'places':
        return random.choice(places).upper()
    elif category == 'animals':
        return random.choice(animals).upper()
    elif category == 'things':
        return random.choice(things).upper()

word = get_word()
print(word)


text:
Q: Magento 2 How to get all products from a non anchor parent category and its subcategories I want to display all products from a non anchor parent category and its subcategories. My categories are non anchor.
http://i.prntscr.com/NOZYKxj4Sh2S2tw1yHjyLQ.png

A: Magento's architecture is set in such a way that, the categories having the attribute code is_anchor value set to 0, will not display products in that particular category. In order to display the products, either you have to change the display setting of all non anchor categories to yes, or update the database table entries.
You can do this from the Admin => CATALOG => Catagories => Display Setting and set Anchor to Yes or make the following changes in the database table entries.
1) Get the attribute_id from eav_attribute table where the attribute_code is is_anchor. In my case, it is 54.
2) Update the value field from the table catalog_category_entity_int to 1,  where the attribute_id is the one which you got from the previous query.
3) Run the reindex
Now check your categories.


text:
Q: Best Practices to handle authentication flow in react native I have react native app and i am implementing auth flow using Context API
the nature of the app is when user open it won't request to login or signup and user can explore the app screens however when user add items to cart and about to checkout then will be requested to sign-in/sign-up to continue.
let's assume these are the screens
Home-> shop -> cart

so when user in the cart will be asked to login, after login user value in context provider will be updated and they continue from same screen the user logged in (which in this case is cart screen)
However, when provider value updated all screens re-render again and redirect to initial route which home screen.
how can i handle this scenario which not re-render all screen again.
In my app i am passing the navigation stuck as a children to context provider as follow:
<AuthProvider>
   <Routes />
</AuthProvider>

and here is the code of context provider:
authProvider.js:
 export const AuthContext = createContext();
    export const AuthProvider = ({ children }) => {

     const [user, setUser] = useState(null);
     const value = useMemo(
            () => ({ user, setUser }),
            [user]);

     return (
            <AuthContext.Provider
                    value={{
                             value,
                             login: async (email, password) => {
                              //here i am validating the login details and update user state
                              // if login successful
                                  setUser(/*some data related to user */)
                                 //when i set user data here it re-render all screens again
                              // if login failed
                                  setUser(null)
                               }
                           }}>
                   {children}
            </AuthContext.Provider >

and the following the Routes.js which i am passing it as children to the above code:
const Routes = () => {

 const { value } = useContext(AuthContext);

// validate token with backend
useEffect(() => {
        setTimeout(async () => {
            const Token = await AsyncStorage.getItem('Token');
            if (Token === null) {
                value.setUser(null)
            } else {
                await axios.get(URL, {
                    headers: { 'x-auth-token': Token },
                }).then(async (res) => {
                    const {data} = res;
                    value.setUser(data)

                }).catch(async (err) => {
                    if (err.response) {
                            await AsyncStorage.removeItem('Token');
                            value.setUser(null)
                    }
                });
            }
        }, 1000)

    }, []);

 return (
        <>
            <NavigationContainer>
                 //this is the stuck where i have the three screen mentioned above (home, shop, cart)
               <AppStuckScreen  />
            </NavigationContainer>
        </>

    )
}

export default Routes;

In cart screen i am checking the user values stored in context provider if null then open the login form.
I hope someone can help me on how to handle this situation where not to re-render all component again when updating user value in Context provider.

A: Why don't you keep the current screen in the Context? So after a successful login, you just navigate to that screen.


text:
Q: setting hudson build trigger to check for svn changes i have set Poll SCM with different options
but none of them seems to work
i tried
* * * * *
5 * * * *
*/10 * * * *

it doesn't seem to try to build
and changes were committed to the svn
any idea what i'm doing wrong ?
do i have to set a post commit hook ?
shouldn't this work ?
thanks


text:
Q: "Didn't return an HttpResponse object. It returned None instead" on POST request I'm trying to pass a selection from a dropdown form into views as a POST request, then using this selection to query some data from django. I'm then using these queries to try and follow this approach to map django models data to highcharts. The problem is I'm getting a "the view properties.views.property_list didn't return an HttpResponse object. It returned None instead" error when I submit the form. I've looked through similar questions on SO but none of the solutions seem to work/be applicable to my case. Perhaps my form is invalid, though I'm not sure what's causing that to be the case. Below is the code that I've written:
views.py
def property_list(request):

if request.user.is_authenticated():
    current_user_groups = Group.objects.filter(id__in=request.user.groups.all())
    current_user_properties = Property.objects.filter(groups__in=current_user_groups)
    current_user_meters = Meter.objects.filter(meter_id__in=current_user_properties)
    property_meter_data = MeterData.objects.filter(meter__in=current_user_meters)

    class AccountSelectForm(forms.Form):
        accounts = forms.ModelChoiceField(queryset=current_user_meters)
        accounts.widget.attrs.update({'class' : 'dropdown-content'})

    form = AccountSelectForm()

    if request.method == "POST":
        if form.is_valid():
            selection = form.cleaned_data['accounts']

            current_user_groups = Group.objects.filter(id__in=request.user.groups.all())
            current_user_properties = Property.objects.filter(groups__in=current_user_groups)
            current_user_meters = Meter.objects.filter(meter_id__in=current_user_properties)

            selected_meters = Meter.objects.filter(name=selection)
            selected_meter_data = MeterData.objects.filter(name=selection)

            usage_data = {'usage': [], 'dates': []}

            for meter in selected_meter_data:
                usage_data['usage'].append(meter.usage)
                usage_data['dates'].append(meter.usage)

            # data passing for usage chart

            usage_xAxis = {"title": {"text": 'Date'}, "categories": usage_data['dates']}
            usage_yAxis = {"title": {"text": 'Usage'}, "categories": usage_data['usage']}
            usage_series = [
                {"data": usage_data['usage']},
            ]

            return HttpResponseRedirect('properties/property-selected.html', {
                'form': form,
                'usage_xAxis': usage_xAxis,
                'usage_yAxis': usage_yAxis,
                'usage_series': usage_series,
                'current_user_meters': current_user_meters,
                'selection': selection,
                'selectected_meters': selected_meters,
                'selected_meter_data': selected_meter_data,
            })

    else:

        current_user_groups = Group.objects.filter(id__in=request.user.groups.all())
        current_user_properties = Property.objects.filter(groups__in=current_user_groups)
        current_user_meters = Meter.objects.filter(meter_id__in=current_user_properties)
        property_meter_data = MeterData.objects.filter(meter__in=current_user_meters)

        return render(request, 'Properties/properties.html',{
        'form': form,
        'current_user_groups': current_user_groups,
        'current_user_properties': current_user_properties,
        'current_user_meters': current_user_meters,
        'property_meter_data': property_meter_data
    })

else:

    # If the usre isn't authenticated, the user is redirected to the Sign-n Page

    return render(request, 'SignIn/SignInPage.html')

template.html
<!-- Query based content for dropdown menu -->
<form method="POST" action="" id="property-select">
    {% csrf_token %}
    {{ form.accounts }}
    <input type="submit" value="Submit" class="submit-button" style="margin-top:30px;"/>
</form>

A: If method=='POST' and your form is invalid, nothing is returned.


text:
Q: registering a user and saving it using struts2 and hibernate I am trying to register a new employee here. The problem is that the values are not getting inserted in the database . Though save() does the work of saving the values right ?
I am attaching my code here.
package net.admin.module.controller;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Transaction;
import org.hibernate.classic.Session;

import net.admin.module.model.Employee;
import net.admin.module.util.HibernateUtil;

public class EmployeeManager extends HibernateUtil {

    public Employee add(Employee employee) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        session.save(employee);
        session.getTransaction().commit();
        return employee;
    }
    public Employee delete(int id) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        Employee employee = (Employee) session.load(Employee.class, id);
        if(null != employee) {
            session.delete(employee);
        }
        session.getTransaction().commit();
        return employee;
    }

        public List<Employee> list() {

        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        List<Employee> employee = null;
        try {

            employee = (List<Employee>)session.createQuery("from Employee").list();

        } catch (HibernateException e) {
            e.printStackTrace();
            session.getTransaction().rollback();
        }
        session.getTransaction().commit();
        return employee;
    }
    }

This one is my EmployeeManager.java class. It is my controller.
package net.admin.module.view;

import java.util.List;
import net.admin.module.controller.EmployeeManager;
import net.admin.module.model.Employee;
import com.opensymphony.xwork2.ActionSupport;

public class EmployeeAction extends ActionSupport {

    private static final long serialVersionUID = 9149826260758390091L;
    private Employee employee;
    private List<Employee> employeeList;
    private int id;

    private EmployeeManager employeeManager;

    public EmployeeAction() {
        employeeManager = new EmployeeManager();
    }

    public String execute() {
        this.employeeList = employeeManager.list();
        System.out.println("execute called");
        return SUCCESS;
    }

    public String add() {
        System.out.println(getEmployee());
        try {
            employeeManager.add(getEmployee());
        } catch (Exception e) {
            e.printStackTrace();
        }
        this.employeeList = employeeManager.list();
        return SUCCESS;
    }

    public String delete() {
        employeeManager.delete(getId());
        return SUCCESS;
    }

    public Employee getEmployee() {
        return employee;
    }

    public List<Employee> getEmployeeList() {
        return employeeList;
    }

    public void setEmployee(Employee employee) {
        this.employee = employee;
    }

    public void setEmployeeList(List<Employee> employeeList) {
        this.employeeList = employeeList;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}

This one is my EmployeeAction.java class. This is my action class.
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>

    <title>Employee Manager</title>

Employee Manager

<s:actionerror/>

<s:form action="add" method="post">
    <s:textfield name="employee.id" label="Id" />
    <s:textfield name="employee.firstName" label="Firstname"/>
    <s:textfield name="employee.lastName" label="Lastname"/>
    <s:textfield name="employee.email" label="Email"/>
    <s:textfield name="employee.phoneNo" label="Phone No."/>
    <s:textfield name="employee.presentAddress" label="Present Address"/>
    <s:textfield name="employee.permanentAddress" label="Permanent Address" />
    <s:textfield name="employee.passportNo" label="Passport No." />
    <s:textfield name="employee.panCardNo" label="Pan Card No." />
    <s:textfield name="employee.designation" label="Designation"/>
    <s:textfield name="employee.age" label="Age" />
    <s:textfield name="employee.gender" label="Gender" />
    <s:textfield name="employee.dob" label="Dob" />
    <s:textfield name="employee.status" label="Status" />
    <s:textfield name="employee.createdOn" label="Created On" />
    <s:textfield name="employee.updatedOn" label="Updated On" />
    <s:textfield name="employee.role" label="Role" />
    <s:textfield name="employee.joiningDate" label="Joining Date" />
    <s:submit value="Add Employee" align="center"/>
</s:form>

Employee

    Id
    FirstaName
    LastName
    Email
    Phone No.
    Present Address
    Permanent Address
    Passport No.
    Pan Card No.
    Designation
    Age
    Gender
    Dob
    Status
    Created On
    Updated On
    Role
    Joining Date
    Delete

<s:iterator value="employeeList" var="employee">

        <s:property value="id"/>
        <s:property value="firstName"/>
        <s:property value="lastName"/>
        <s:property value="emailId"/>
        <s:property value="phoneNo"/>
        <s:property value="presentAddress"/>
        <s:property value="permanentAddress"/>
        <s:property value="passportNo"/>
        <s:property value="panCardNo"/>
        <s:property value="designation"/>
        <s:property value="age"/>
        <s:property value="gender"/>
        <s:property value="dob"/>
        <s:property value="status"/>
        <s:property value="createdOn"/>
        <s:property value="updatedOn"/>
        <s:property value="role"/>
        <s:property value="joiningDate"/>
        <a href="delete?id=<s:property value="id"/>">delete

</s:iterator>

This is my jsp - index.jsp . Im forwarding it here.
I can see the inserted values in the jsp page but it does not get inserted in the database.


text:
Q: Gmail push notifications stop when IMPORTANT or CATEGORY_PERSONAL are excluded I am using the Gmail push notifications to determine when an email has been assigned to a custom label.  It seems that custom labels are not supported by labelIds so I am using 'exclude' to exclude built-in labels.  This works fine for most of the built-in labels but if I include 'IMPORTANT' OR 'CATEGORY_PERSONAL' in labelIds then push notifications stop completely.
For example:
Push messages are sent:
service.Users.Watch(new WatchRequest()
{
    TopicName = "projects/tutorial-test-1348/topics/my-new-topic",
    LabelFilterAction = "exclude",
    LabelIds = new string[] { "TRASH",  "SPAM", "DRAFT", "SENT", "STARRED", "INBOX", "CHAT", "UNREAD", "CATEGORY_FORUMS", "CATEGORY_SOCIAL", "CATEGORY_PROMOTIONS"}
}, "me").Execute();

Push messages are not sent
service.Users.Watch(new WatchRequest()
{
    TopicName = "projects/tutorial-test-1348/topics/my-new-topic",
    LabelFilterAction = "exclude",
    LabelIds = new string[] { "IMPORTANT", "TRASH",  "SPAM", "DRAFT", "SENT", "STARRED", "INBOX", "CHAT", "UNREAD", "CATEGORY_FORUMS", "CATEGORY_SOCIAL", "CATEGORY_PROMOTIONS"}
}, "me").Execute();