text:
Q: js promise - how to end "then" execution if a condition is fulfilled and continue to next then if not I have a promise with 1 .then() method which I would like to divide in smaller pieces (because it is to long...).
it looks similar to this (simplified) example:
const myPromise = new Promise((resolve, reject) => {
  setTimeout(function() {
    resolve(false);
  }, 500);
});

myPromise
  .then(value => {
    if (value) {
      // do something
      console.log('value: ' + value)
      console.log('do something');
    } else {
      // do something else only if value=true
      // this is really long.............
      console.log('value: ' + value)
      console.log('do something else');
    }
  });

to simplify I thought of doing something like this:
const myPromise = new Promise((resolve, reject) => {
  setTimeout(function() {
    resolve(false);
  }, 500);
});

myPromise
  .then(value => {
    if (value) {
      // do something
      console.log('value: ' + value)
      console.log('do something');
      // stop "then" execution (next "then" should not run) -> HOW TO DO THIS?
    } else {
      // continue processing in next then
      return value
    }
  })
  .then(value => {
    // do something else only if value=false
    console.log('value: ' + value)
    console.log('do something else');
  })

what I am unable to figure out is how to get // stop "then" execution (next "then" should not run) -> HOW TO DO THIS? to work...

A: You can "stop" then chains by returning a rejected promise, this why it will "jump" to catch phase.

const myPromise = new Promise((resolve, reject) => {
  setTimeout(function() {
    resolve(true);
  }, 500);
});

myPromise
  .then(value => {
    if (value) {
      // do something
      console.log('value: ' + value);
      console.log('do something');
      // stop "then" execution (next "then" should not run) -> HOW TO DO THIS?
      return Promise.reject();
    } else {
      // continue processing in next then
      return value;
    }
  })
  .then(value => {
    // do something else only if value=false
    console.log('value: ' + value);
    console.log('do something else');
  });


text:
Q: Java URL constructor allows spaces I'm confused with why this is valid and not throwing an exception:
final URL u = new URL("https:// google . c o m foo bar")

Isn't this an invalid URL?

A: Yes.  java.net.URL is a very old class which was part of Java 1.0.  It does little to no checking of the syntax of its String argument.
Later, the java.net.URI class was added, which does all of the proper checks.  And a valid URI can be converted to a URL with the toURL() method.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Calling a method of the MainActivity from another class? I want to call a method of MainActivity from another class. The method is:
 public void setDate() {
    final Calendar c = Calendar.getInstance();
    int year = c.get(Calendar.YEAR);
    int month = c.get(Calendar.MONTH);
    int day = c.get(Calendar.DAY_OF_MONTH);

    Toast.makeText(this, "I am in on resume", Toast.LENGTH_LONG).show();

    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    date = sharedPreferences.getString("DATE_OF_JOURNEY", null);
    if (date == null) {
        sharedPreferences.edit().putString("DATE_OF_JOURNEY", day + "/" + month + "/" + year).apply();
        date = day + "/" + month + "/" + year;
    }

    date_text.setText(date);
}

The other class is used as a datePicker. The dateset method is calling the above method of the MainActivity.
 public void onDateSet(DatePicker view, int year, int month, int day) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());

    Toast.makeText(getContext(),"The date is: " + year + month + day ,Toast.LENGTH_LONG).show();

    sharedPreferences.edit().putString("DATE_OF_JOURNEY", day + "/" + month+"/"+ year).apply();
    mainActivity.setDate();
    // Do something with the date chosen by the user
}

Basically, I want to get SharedPreferences value written by DatePickerFragment class to the MainActivity.
Edit 1: MainActivity:
package com.example.shiza.cube26;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;
import java.util.prefs.PreferenceChangeEvent;

public class MainActivity extends AppCompatActivity {

    Toolbar toolbar;
    TextView date_text;
    String date;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        String url = "https://cube26-1337.0x10.info/stations";

        date_text = (TextView) findViewById(R.id.date);

//        new fetchData().execute(url);

    }

    public void setDate() {
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        Toast.makeText(this, "I am in set date.", Toast.LENGTH_LONG).show();

        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

        date = sharedPreferences.getString("DATE_OF_JOURNEY", null);
        if (date == null) {
            sharedPreferences.edit().putString("DATE_OF_JOURNEY", day + "/" + month + "/" + year).apply();
            date = day + "/" + month + "/" + year;
        }

        date_text.setText(date);
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    public class fetchData extends AsyncTask<String, Void, String> {
        ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar_timer);

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressBar.setVisibility(View.VISIBLE);
        }

        @Override
        protected String doInBackground(String... params) {
            BufferedReader reader = null;
            try {
                URL url = new URL(params[0]);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                StringBuilder sb = new StringBuilder();

                reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

                String line;

                while ((line = reader.readLine()) != null) {
                    sb.append(line + '\n');

                }

                return sb.toString();

            } catch (MalformedURLException e) {
                e.printStackTrace();
                return null;
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            progressBar.setVisibility(View.GONE);

            try {
                JSONObject json = new JSONObject(s);

                JSONArray jsonArray = json.names();

                for (int i = 0; i < jsonArray.length(); i++) {
                    Toast.makeText(getApplicationContext(), jsonArray.getInt(i), Toast.LENGTH_LONG).show();
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
            try {
                JSONArray jsonArray = new JSONArray(s);

                for (int i = 0; i < jsonArray.length(); i++) {
                    Toast.makeText(getApplicationContext(), jsonArray.getString(i), Toast.LENGTH_LONG).show();
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    public void showDatePickerDialog(View v) {

        DatePickerFragment datePickerFragment = new DatePickerFragment();
        datePickerFragment.setDateChangeListener(new DatePickerFragment.DateChangeListener(){
            public void onDateChange(){
                setDate();
            }
        });

        DialogFragment newFragment = new DatePickerFragment();
        newFragment.show(getSupportFragmentManager(), "datePicker");
    }
}

DatePickerFragment:
package com.example.shiza.cube26;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.DialogFragment;
import android.widget.DatePicker;
import android.widget.Toast;

import java.util.Calendar;

/**
 * Created by Shiza on 04/10/2015.
 */
public class DatePickerFragment extends DialogFragment
        implements DatePickerDialog.OnDateSetListener {

    private DateChangeListener mListener;
    public void setDateChangeListener(DateChangeListener listener){
        mListener = listener;
    }

    public interface DateChangeListener{
        public void onDateChange();
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        // Create a new instance of DatePickerDialog and return it
        return new DatePickerDialog(getActivity(), this, year, month, day);
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());

        Toast.makeText(getContext(),"The date is: " + year + month + day ,Toast.LENGTH_LONG).show();

        sharedPreferences.edit().putString("DATE_OF_JOURNEY", day + "/" + month+"/"+ year).apply();
        if(mListener!=null){
            mListener.onDateChange();
        }
        // Do something with the date chosen by the user
    }
}

A: there are couple of ways:

*

*If MainActivity is present and context!=null then call on object's reference. (not so good way if you want GC to free RAM)

*Make function static and call MainActivity.staticFunction(); (discouraged for various reasons)

*Best way is to make a controller class and init its object when required. call object.function();

A: you can use interface as callback mechanism here.
I am using name OtherClass for class which is having datepicker dialog for following example:
define an interface in the other class like this:
public interface DateChangeListener{
  public void onDateChange();
}

and add method for attaching listener in same class
private DateChangeListener mListener;
public void setDateChangeListener(DateChangeListener listener){
   mListener = listener;
}

now inside your onDateSet of same class call
if(mListener!=null){
     mListener.onDateChange();
}

on in your main activity implement DateChangeListener interface before calling for datepicker dialog like this
   otherclassInstance.setDateChangeListener(new OtherClass.DateChangeListener(){
       @override
       public void onDateChange(){
           setDate();
       }
    });

this way whenever onDateSet method will get called in OtherClass, onDateSet method of main activity will also get called.

Edit
Change showDatePickerDialog method like this:
public void showDatePickerDialog(View v) {
    DatePickerFragment datePickerFragment = new DatePickerFragment();
    datePickerFragment.setDateChangeListener(new DatePickerFragment.DateChangeListener(){
        public void onDateChange(){
            setDate();
        }
    });

    datePickerFragment .show(getSupportFragmentManager(), "datePicker");
}

A: Write this in your fragment from which you want to call
private MainActivity mainActivity() {
    return (MainActivity) getActivity();
}

And with,
mainActivity().setDate();
You can call main activity public method inside your fragment


text:
Q: Mercurial.Net pullCommand using authorization I am trying to pull code changes from Mercurial using Mercurial.NET library. I get an authorization exception and do not obtain any results, below is the code.
Repository repository = new Repository(@"D:\sandeep\work\20Dec2016");

PullCommand pullcommand = new PullCommand();
repository.Pull(pullcommand);

This is my code, is there a way, I can specify my credentials (username and password) for authentication in order to pull the recent changes?

A: I could achieve the result with the below code and help from Lasse V. Karlsen
Repository repository = new Repository(@"D:\sandeep\Work\20Dec2016");
pullCommand.WithConfigurationOverride("auth", "x.prefix", "*");
pullCommand.WithConfigurationOverride("auth", "x.username", "ssk");
pullCommand.WithConfigurationOverride("auth", "x.password", "ssk");
repository.Pull(pullCommand);


text:
Q: Can't use data from redux-form inside my component I have a simple redux-form on the first page of my project and a button to the next page where I want to display the data from the form.
import React from 'react';
import { connect } from 'react-redux';

class UsersList extends React.Component {
    componentDidMount() {
        console.log(this.props.form.contact.values)
        // this displays the data
    }

    render(){
        let { firstName, lastName } = this.props.form.contact.values;
        // this doesn't display the data
        return (

{firstName}

{lastName}

        );
    };
};

function mapStateToProps(state) {
    return {
        form: state.form
    };
};

export default connect(mapStateToProps, null)(UsersList);

This is the component where I'm trying to display the data submitted through the form. As you can see in the comments, when I do "console.log(this.props.form.contact.values)" in the componentDidMount method, it works just fine, and I can see the info in the log, but when I try to use it to actually display stuff in the p tags, I get "Cannot read property 'values' of undefined" error.
I don't know it this is relevant, but when console.logging, I get the data in an object. I also tried to map over it inside the return, still without success.
Any help is appreciated!

A: This is normal because when you change route, the @@redux-form/DESTROY action will be called emptying all the data from your form and apparently from your form reducer, so this
function mapStateToProps(state) {
    return {
        form: state.form
    };
};

will result to undefined. If you need to persist the form values, you need to tell your form not to destroy itself in unmount.
reduxForm({
  destroyOnUnmount: false
})(...)


text:
Q: Converting coordinates in $\mathbb{R}^2$ to a point in $\mathbb{C}$ (and back again) I have a list of control points for a BezierFunction. I want to apply a function taking input a complex number to these points and then plot the BezierFunction of the resulting points. I'm looking for a way to convert a list of points in the form $\{a,b\}$ to the form $a+bi$. After applying my function and obtaining the resulting list of points in this complex number form I would like to convert this back to a list of points in the original form.

A: n = 10000;
x = RandomReal[{-1, 1}, {n, 2}];
ToComplex[x_] := x.{1, I};

(*to complex numbers*)
z = ToComplex[x];
(*to real vectors*)
y = ReIm[z];

As to answer to MarcoB's comment: Of course applying Complex does work but it is slower (be a factor of almosr 20) because it is not vectorized:
n = 1000000;
x = RandomReal[{-1, 1}, {n, 2}];
z1 = ToComplex[x]; // AbsoluteTiming // First
z2 = Complex @@@ x; // AbsoluteTiming // First
z1 == z2

0.022322
0.424101
True


text:
Q: Run same function parallelly with different items in the list in Python I have the below code and I want to get the sum of each list in the nested listed parallelly using multi-processing or threading or any other  method in Python 3.x. How do I approach this? All the sub lists or atleast 2 sub lists should run the addition function at the same time.
Thanks in advance!
nested_list = [[2,3,4], [4,5,6], [7,8,9], [10,11,12]]

def addition(list):
  tot = sum(list)
  return tot

for list in nested_list:
  tot = addition(list)
  print (tot)

A: You don't need threads, because your task is CPU bound.
from multiprocessing import Pool

with Pool(5) as p:
    print(p.map(addition, nested_list))

Other way
import concurrent

with concurrent.futures.ProcessPoolExecutor() as executor:
     print(executor.map(addition, nested_list))

A: Give a woman or a man a fish and you feed her or him for a day. Teach woman or man to fish and you feed her or him for a lifetime.
Check this article. It's awesome!
The case is not of a complicated matter, so you'll be ready to solve this and similar problems after 10-15 minutes of reading and trying.
Note! You wouldn't want to look toward multithreading in a case of CPU-bound task (such as yours). In this case, in case of Python, only multiprocessing will introduce parallelism.
Good luck!

A: multiprocessing module can be used for process based parallel programming.
from multiprocessing import Pool

nested_list = [[2,3,4], [4,5,6], [7,8,9], [10,11,12]]
with Pool(5) as p:
    print(p.map(sum, nested_list))


text:
Q: Accessing Nested Class Member Function in CPP In case of nested class, how do I access the "Inner" or "Child" class's member function?.
For example, the code, where I created "obj1". Now how do I access the "childPrint()" with"obj1"?
example_code:
#include<iostream>
using namespace std;

/////////////////////////////////////////////////
class Parent
{
public:
    void print()
    {
        cout<<"this is from Parent"<<endl;
    }
    class Child
    {
    public:
        void childPrint()
        {
            cout<<"this is from Child"<<endl;
        }
    };
};

int main()
{
    Parent obj1;
    obj1.print();

    Parent::Child obj2;
    obj2.childPrint();

    obj1.Child::childPrint();///ERROR

    return 0;
}

A:
Now how do I access the "childPrint()" with"obj1"?

You can't.
obj1 is of type Parent, which doesn't contain any method called childPrint. An instance of Parent doesn't automatically contain an instance of Child (I think Java does something like this), they are still seperate classes. You can only call this method on an instance of Child.

A: obj1.Child::childPrint();
In this particular line, you need to understand that childPrint() is an instance member function of class Child. So, only an instance of class Child can call childPrint() function.
If childPrint() function is a static member function(class function) of class Child then it is possible to call it without creating any instance and no error will be shown in Parent::Child::childPrint();.

A: If you have a static method, then you can call it with:
/////////////////////////////////////////////////
class Parent
{
public:
...
    class Child
    {
    public:
    static void childPrint() { cout<<"this is from Child"<<endl; };
    }
}

...

Parent::Child::childPrint();

These are separate classes without any automatic instanciation of child classes and vice versa.


text:
Q: Cannot apply bootstrap styling to an ASP:Button within Sharepoint I am trying to apply Bootstrap's CSS styles to an ASP:Button and am currently experiencing some CSS conflicts from Sharepoint's corev15.css stylesheet for the button input type:
input[type="button"], input[type="reset"], input[type="submit"], button {
    min-width: 6em;
    padding: 7px 10px;
    border: 1px solid rgb(171, 171, 171);
    background-color: rgb(253, 253, 253);
    margin-left: 10px;
    font-family: "Segoe UI","Segoe",Tahoma,Helvetica,Arial,sans-serif;
    font-size: 11px;
    color: rgb(68, 68, 68);
}

From what I can tell Bootstrap applies these styles at a lower level (btn btn-primary btn-sm in my case) so the input[type="button"] styles being applied curtosy Sharepoint are taking precedence.
Any ideas on how to prevent this from occuring for my application without potential repurcussions elsewhere via editing Sharepoint's CSS?
I suspect what's needed is some custom CSS within a stylesheet that's rendered after my core bootstrap styles such as bootstrap3-custom.css, but I'm not sure what code would fix this specific issue.

A: my recommendation is to inspect the button with ie dev toolbar or firebug and check the rendered html for css classes or inline styles.
if css classes exist, use them, otherwise use the button type to a copy of those styles in a separate stylesheet.
use !important if required.
its important to know that there is stylesheet priority, and markup matching priority, so later load stylesheets with more specific assignments will prevail. !important should force anything without further concerns, but use with caution, dont make it a standard


text:
Q: Does JPQL support the use of a boolean result in another expression? I am trying to write a query to back a search API. Specifically for a flag searchDrafts - if the flag is true I have to get rows with status DRAFT and else I have to get all rows that have any status other than DRAFT.
In regular SQL, the below query works fine:
SELECT id, status
FROM records
where ((status = 'DRAFT') = :searchDrafts);

However, a similar thing in JPQL doesn't work:
SELECT r
FROM Records r
WHERE ((r.status = 'DRAFT') = :searchDrafts);

It gives the error:
unexpected AST node: = near line 1, column nn
Is there any way in JPQL to use the value of a boolean result in another expression?
The alternative would be doing it the longer way, but its a bit verbose. This works fine in JPQL:
SELECT id, status
FROM records
where (:searchDrafts=true AND (status = 'DRAFT'))
or (:searchDrafts=false AND (status != 'DRAFT'));

A: JPQL grammar from Jakarta Persistence 3.0 specification doesn't allow that. (I had 3.0 by hand, but I don't expect that earlier ones differ.) Boolean comparison corresponds to this production rule:
comparison_expression ::=
    ...
    boolean_expression {= | <>} {boolean_expression | all_or_any_expression} |
    ...

Then comparison_expression is only ever encountered as a part of conditional_expression production rules:
conditional_expression ::= conditional_term | conditional_expression OR conditional_term
conditional_term ::= conditional_factor | conditional_term AND conditional_factor
conditional_factor ::= [NOT] conditional_primary
conditional_primary ::= simple_cond_expression | (conditional_expression)
simple_cond_expression ::=
    comparison_expression |
    ...

And conditional_expression is what goes directly in WHEN, WHERE, HAVING and ON clauses. This means that comparison_expression cannot be a boolean_expression.
Apart from your solution with AND, this one seems to work too:
SELECT r
FROM Records r
WHERE CASE WHEN r.status = 'DRAFT' THEN TRUE ELSE FALSE END = :searchDrafts;

It's quite ugly, but it does convert a conditional_expression into a boolean_expression.
In practice you'd better have two different queries: one for "=" and the other for "<>".
Overall, it feels like an omission in the JPA standard.


text:
Q: How to get rid of no carparks found for no such campus I have two models: Campus and Carpark. Data on carpark information is stored in json files in a database.
models.py
from django.db import models

class Campus(models.Model):
  campus_id = models.AutoField(primary_key=True)
  name = models.CharField(max_length=100)
  def __str__(self):
    return self.name

class Carpark(models.Model):
  carpark_id = models.AutoField(primary_key=True)
  name = models.CharField(max_length=100)
  spaces = models.IntegerField()
  campus_id = models.ForeignKey()
  disabled_spaces = models.IntegerField()
  def __str__(self):
    return self.name

views.py
from django.shortcuts import render
from django.http import HttpResponse
from parkatdcu.models import Campus, Carpark
import requests

def index(request):
  context = {}
  return render(request, "parkatdcu/index.html", context)

def carparks(request):
  context = {}
  Base_URL = 'http://jfoster.pythonanywhere.com/carparks/'
  campus_name = request.GET['campus']
  try:
    campus = Campus.objects.get(name__iexact=campus_name)
  except Campus.DoesNotExist:
    print('No such campus')
    return render(request,"parkatdcu/carparks.html",context)
  carparks = Carpark.objects.filter(campus_id=campus)
  carpark_info= []
  for carpark in carparks:
    URL = Base_URL + carpark.name
    r = requests.get(URL).json()
    if 'spaces_available' in r:
      spaces_available = r['spaces_available']
    else:
      spaces_available = 'not available'
    carpark_info.append({
                         'name': carpark.name,

           'spaces': carpark.spaces,
                         'disabled_spaces': carpark.disabled_spaces,
                         'spaces_available': spaces_available
                         }
                        )
context['campus'] = campus_name
context['carparks'] = carpark_info
return render(request,"parkatdcu/carparks.html",context)

carparks.html
{% if campus %}

{{ campus }}

{% else %}

No such campus

{% endif %}
{% if carparks %}

{% for carpark in carparks %}

{{carpark.name}}: {{carpark.spaces}} spaces, {{carpark.disabled_spaces}} spaces for people with
disabilities

Spaces available:  {{ carpark.spaces_available }}

{% endfor %}
{% else%}

No carparks found

{% endif %}

When I type the name of a campus into the search box that is not stored in the Django database, it says both 'No such campus' and 'No carparks found'. How do I only print 'No such campus' for a campus that does not exist?

A: You should only need to remove above lines
{% if campus %}

{{ campus }}

{% else %}

No such campus

{% endif %}

{% if carparks %}

    {% for carpark in carparks %}

{{carpark.name}}: {{carpark.spaces}} spaces, {{carpark.disabled_spaces}} spaces for people with
disabilities

Spaces available:  {{ carpark.spaces_available }}

    {% endfor %}

{% else%}                    <--- REMOVE THIS LINE

No carparks found
 <--- REMOVE THIS LINE

                    <--- MOVE THIS LINE INSIDE {% endif %}
{% endif %}

A: have a look at the code below, it should only show No such campus message for a campus not in the database.

{% if campus %} {{ campus }} {% else %} No such campus {% endif %}

{% if campus %} {# HERE -- i just wrapped the block with if statement #}

  {% if carparks %}

      {% for carpark in carparks %}

{{carpark.name}}: {{carpark.spaces}} spaces, {{carpark.disabled_spaces}} spaces for people with disabilities
Spaces available:  {{ carpark.spaces_available }}

      {% endfor %}

  {% else%}

No carparks found

  {% endif %}

{% endif %}


text:
Q: WPF application touch response on Win8 tablet I have a WPF application written for desktop. When I run the application on a non-touch win8 pc, the tab change, combobox drop down etc work fine. The same application on a Win8 tab is behaving differently. The tab changes after a delay. The response of the UI is slower comparitively. I tried implementing this piece on code in my MainWindow constructor from this MSDN link. But the application crashes when I open child windows.
I am running the application on a Windows 8 pro tablet with Intel Atom. So it's not WinRT and allows desktop apps to run.


text:
Q: Formatting a string to be a constant length in Python Lets say I have a few string titles:
title0 = 'USA'
title1 = 'Canada'

And I want to append a list of '#' characters to the front and back of these titles to give them a constant length so they look like:
######## USA ########
####### Canada ######

With 1 space buffering the start and end of the text.  Obviously I can't always get a symmetric number of symbols around the word.  Is there a way to do this with built in Python string formatting?

A: Python's str.format() has a few options that should get you what you want. You can read more about them here. This should give you what you wanted.
title0 = '{:#^{width}}'.format(' USA ', width=19)
title1 = '{:#^{width}}'.format(' Canada ', width=19)

Or using a similar syntax for the new f-strings/formatted string literals:
width = 19
country = 'USA'
title0 = f'{country:#^{width}}'


text:
Q: Whats wrong in using the words Whilst and Due to? I remember reading in an English style guide (The Scott Foresman Handbook for Writers) that the words whilst and due to were quite redundant and not to be used. The author did not seem to like them as whilst was just another word for while and due to was a rough form of saying because.
However, I've found myself using the due to quite often. For instance, I'm writing a long sentence that can have two becauses. In that case I end up using due to in place of the second because. For example:

For a sincere and talented writer, all barriers to entry are finally removed because of the e-publishing phenomena, and that was only possible due to the Internet revolution pioneered by Tim Berners Lee in the early nineties.

What can I use in place of second because if I don't want to use due to?
Also, I personally find it more elegant to say "Whilst" instead of "While". But is that the perception of most modern readers or not?

A: "For a sincere and talented writer, all barriers to entry are finally removed because of the e-publishing phenomena, and that was only possible due to the Internet revolution pioneered by Tim Berners Lee in the early nineties" sounds OK to me (bear in mind that I am not a native speaker though).
Moreover, if, as you asked, wanted to know what can you use in place of second because if you don't want to use due to, I would suggest thanks to ;
" For a sincere and talented writer, all barriers to entry are finally removed because of the e-publishing phenomena thanks to Internet revolution pioneered by Tim Berners Lee in the early nineties"

A: There are plenty of good reasons not to use "whilst":

*

*It is identical to "while" in meaning, but because it's a rarer word, it distracts your reader.

*It has never been the norm. Dickens never uses it, and even Shakespeare uses it sparingly.

*Many style guides, including the BBC, the Guardian, the Economist, and the Canadian Hansard, advise simply to replace it with "while".

*It sounds pompous and affected.

"Due to" is fine the way you use it: it might be a bit of a writer's disease to avoid duplicating formulations, but if you can do it without jumping through hoops, it does make your prose sound more elegant, and "due to" is clear and understandable.


text:
Q: How to disable submit button on submit for many forms - generic function to any form I'm not an expert in jQuery - and I know this is easy - but I cannot find the solution for this.
I have a page with 10 alerts (cancel, confirm, resend..) - with 10 forms and 10 submit buttons.
How I can disable the submit button on submit form with a generic function ?
I know how I can disable 1 form.
$('form#id').submit(function(){
  $(this).find(':input[type=submit]').prop('disabled', true);
});

but with this I need to write 10x - a function for each form...
$('.form').submit(function(){
  $(this).find(':input[type=submit]').prop('disabled', true);
});

I try this but, didn't work..
I need a function to works for any form..
All forms are like this:
            <form id="cancelform" action="cancel.asp">
            <input type="hidden" name="codec" id="codec" value="121">
                <button type="button" class="btn btn-danger bk-rd-off" data-dismiss="modal"> NO</button>
                <button type="submit" class="btn btn-success bg-success-800 bk-rd-off"> YES</button>
            </form>

A: You don't even need jQuery for this, feel free to use vanilla JS:
document.querySelectorAll('form input[type="submit"]')
  .forEach(input => input.disabled = true);

Or if you want to disable form submission and not just the buttons, you can do something similar to preventDefault on every submit event:
document.querySelectorAll('form').forEach((form) => {
  form.addEventListener('submit', e => e.preventDefault());
});

A: Select all the forms, then onSubmit, use the event.target to get a reference to just that single form that is being submitted, find it's submit button, and disable it. Should work for 1 form, or 100 forms....
Example JS Fiddle
$('form').submit(function(event){
  // disable future submits
    $(event.target).find('[type="submit"]').prop('disabled', true);
});

Depending on your needs, you might also include an event.preventDefault();

A: You're scoping adding the disabled prop to the $(this) selector which is the current form being submitted. If you want to disable all submit buttons you can use a global query selector on your submit callback:
$('.form').submit(function() {
  $('input[type=submit]').prop('disabled',true);
});

A: I'm not sure why you're trying to use find when you can just do this:

$('input[type=submit]').prop('disabled', true);

<input type="submit"/>
<input type="submit"/>
<input type="submit"/>


text:
Q: Pass GUID to parameter in SSRS How i can pass simple GUID value to a parameter @Param1 in SSRS. I have report with couple of parameters and i need to pass GUID to one of my parameters

A: SSRS doesn't understand uniqueidentifiers - it just assumes they are strings.  Just set the value of the parameter to be equal to the GUID you want to pass (preferably in lower case).


text:
Q: Clarification on a statement of a theorem If $f(x)$ be continuous over $(0,1]$ then $f$ is uniformly continuous if and only if $\lim_{x \to 0^+} f(x)$ exists.
I have a question about this statement, I am unclear on whether if it is saying that $f$ is uniformly continuous only over $(0,1]$ or is it everywhere, where $f$ is defined? Thanks!!!

A: Only over $(0,1]$; since you don't know anything about the function elsewhere, that's the only place you know it's uniformly continuous.


text:
Q: union of two select queries with different fields I have two tables empmaster and allocation. I used union to do sql operation in order to get results from two tables. empmaster has empid and other empdetails. Table allocation contains empid from empmaster as foriegn key another field called per_alloc. I need to retrieve empdetails which satisfies:

*

*empmaster.empid not in allocation.empid.

*empmaster.empid in allocation.empid and allocation.per_alloc < 100.
MySQL query I used is:
  select distinct(tbl_empmaster.emp_fname)
  from tbl_empmaster
  where tbl_empmaster.emp_id not in(select tbl_allocation.emp_id
                                    from tbl_allocation)
  union
  select distinct(tbl_empmaster.emp_fname)
  from tbl_empmaster
   where tbl_empmaster.emp_id in(select tbl_allocation.emp_id
                                 from tbl_allocation
                                 group by emp_id
                                 having sum(per_alloc) < 100)

This only retrieves empdetails, say  tbl_empmaster.emp_fname, I need to retrieve sum(per_alloc) from select tbl_allocation!!! When I tried it gives lot of errors, Can any one show me the correct way, please?

A: Try this:
SELECT DISTINCT em.emp_fname, 0 alloc
FROM tbl_empmaster em
WHERE em.emp_id NOT IN(SELECT emp_id FROM tbl_allocation)
UNION
SELECT DISTINCT em.emp_fname, SUM(a.per_alloc) alloc
FROM tbl_empmaster em
INNER JOIN tbl_allocation a ON em.emp_id = a.emp_id
GROUP BY a.emp_id
HAVING SUM(a.per_alloc)<100

A: Ok, from what I have understood of your problem, I see two problems.

*

*There is the unecessary grouping in the subquery of the second select statement. It should be ok to just write select tbl_allocation.emp_id from tbl_allocation where tbl_allocation.per_alloc<100)*

*And the answer to your question.change the second select statement to the following, and it should work:select A.emp_fname, B.per_alloc from tbl_empmaster A join tbl_allocation B using(emp_id) where A.emp_id in(select C.emp_id from tbl_allocation C where C.per_alloc<100))
**Assuming that emp_id is the primary key*


text:
Q: How to unwind to the right view controller if current one is presented AND pushed? I have a viewcontroller, let's say A, that is reached by three other view controllers, let's say B, C and D.
B presents UIViewController A modally.
C and D are part of a UINavigationController and thus, push view controller A.
If all of them had modal segues, I could just do a switch(presentingViewController) to determine who is the viewcontroller I should unwind to. The problem is that since two of them are in a navigation stack (B and C), they will never be a presentingViewController.
How do I solve this conundrum?

A: Check if a navigation controller exists in A. If it does you'd pop, if it doesn't you'd dismiss.


text:
Q: No contribution on Spoop2 development / stable release Why was Sqoop2 deprecated? I can see this alert message in Cloudera:

Note: Sqoop 2 is deprecated. Cloudera recommends you use Sqoop 1.

Also, they mentioned that the 1.99.x version is not stable and not intended to be used for production releases.

Latest stable release is 1.4.7 (download, documentation). Latest cut of Sqoop2 is 1.99.7 (download, documentation). Note that 1.99.7 is not compatible with 1.4.7 and not feature complete, it is not intended for production deployment.

Does anyone know the reason behind these issues?
I'm seeing the potential on sqoop-on-spark to implement for one of our projects but it has a dependency of sqoop2 and it's concepts (connection and links).


text:
Q: Converting char array to integer c programming The Problem: The user enters a time in 24 hour format. The Array has different times listed also in 24 hour format. I would like to compare the number entered by the user to the time that is closest to the time entered by the user. Whatever number is closest to the time entered by the user is to be displayed on the screen. I've been working overnight at my company job and trying to understand the programming behind this. Can anyone help me? By the way, I just began this C Programming class. If you see anything that looks like C# code, it's because I haven't learned enough yet. Here's what I have so far:
#include <stdio.h>
#include <stdlib.h>

int main(void) {

    int hours, mins; //24 hour time to be entered by user

    int bestTime = scanf("%d:,%d", &hours, &mins);  //best time for user departure

    char* depart [8] = {"8:00", "9:43", "11:19", "12:47", "14:00", "15:45", "19:00", "\0"}; //times available for departure

    int counter; //count number of times to loop
    printf("Please Enter The Best Time For Your Flight In 24 Hour Format.\n");
    scanf("%d:,%d", &hours, &mins);

    for(counter = 0; counter <  ; counter++){
        if(bestTime < depart[counter]){
            bestTime = depart[counter];
        }
    }

    return bestTime;
}

A: You can make a function that converts a string of format "hh:mm" into minutes from "00:00". And then use that to do all the comparisons.
One implementation of the function can be
unsigned int str_to_mins(const char* t) {
    return (unsigned int) (
        ((t[0] - '0') * 10 + (t[1] - '0')) * 60
        + (t[3] - '0') *10 + (t[4] - '0')
    );
}

Call this function on all your strings. They will give you unsigned integers. Use that to find the number closest to the one entered. (Convert your input to also this format in similar way).
Just to be clear scan your input as
char input[10];
scanf("%s", input);

A:
The idea:

*

*After getting the time from the user, convert everything to minutes.

*Get every element of your departure array, convert it to integers using atoi().

*Convert to minutes the departure times and put them inside an array of integers.

*Now compare the total number of minutes entered by the user with every total you have in your array. That's simple; you compare the
  absolute values of the subtraction of the departure total from the
  input total. The lowest absolute value is your closest. For that, I
  wrote a function that returns the index of the closest element inside
  the array.

*I display the equivalent closest value from your initial departure array of strings.

*NB: I assume you have 7 departure times.

 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>

int findClosest(int * , int);

int main(void) {

    int hours,mins,total; //24 hour time to be entered by user
    char computationHours[3],computationMins[3];
    int computationHoursInt,computationMinsInt,computationTotal;

    int bestTime; //best time for user departure
    int index;
    char * depart[8] = {
        "8:00",
        "9:43",
        "11:19",
        "12:47",
        "14:00",
        "15:45",
        "19:00",
        "\0"
    }; //times available for departure
    int departures[7];
    int counter; //count number of times to loop
    printf("Please Enter The Best Time For Your Flight In 24 Hour Format.\n");
    scanf("%d:%d",  & hours,  & mins);
    total = (hours * 60) + mins;
    for (counter = 0; counter < 7; counter++) {

        if (strlen(depart[counter]) == 4) {
            //Like 8:00
            strncpy(computationHours, depart[counter], 2);
            strncpy(computationMins, depart[counter] + 2, 2);
            computationHoursInt = atoi(computationHours);
            computationMinsInt = atoi(computationMins);
            computationTotal = (computationHoursInt * 60) + computationMinsInt;
        } else {
            //Like 19:00
            strncpy(computationHours, depart[counter], 2);
            strncpy(computationMins, depart[counter] + 3, 2);
            computationHoursInt = atoi(computationHours);
            computationMinsInt = atoi(computationMins);
        }
        computationTotal = (computationHoursInt * 60) + computationMinsInt;
        departures[counter] = computationTotal;
    }

    index = findClosest(departures, total);
    printf("Closest timing is: %s", depart[index]);
    return 0;
}

int findClosest(int values[], int n) {
    int dist = abs(values[0] - n),closest;
    int size = 7;
    for (int i = 1; i < size; ++i) {
        if (abs(values[i] - n) < dist) {
            dist = abs(values[i] - n);
            closest = i;
        }
    }
    return closest;
}


text:
Q: Solving problems regarding $L(x)=\int_1^x\frac{dt}{t},\quad x>0$ and the inverse function $E(x)$ The problem
Without using $L(x)=\ln(x)$ and given $$L(x)=\int_1^x\frac{dt}{t},\quad x>0$$
a) Prove that
i) $L(xy)=L(x)+L(y),x,y>0$
ii) $L(1/x)=-L(x)$
b) Prove that $L(2)<1$
c) Prove that $L(3)>1$
d) Prove that $L$ is increasing
The number $e$ is $L(e)=1$ and $2<e<3$.
Let $E$ be the inverse function to $L$, with $D_E=\Bbb{R}$ and $V_E=(0,\infty)$. Dont use $E(x)=e^x$.
e) Prove that $E$ is differentiable, and that $E'(x)=E(x)$
f) Prove that for all $x, y\in\Bbb{R} $
i) $E(x+y)=E(x)E(y)$
ii) $E(-x)=\frac{1}{E(x)}$
g) Let $n\in\Bbb{N}$. Prove that $E(x)^n=E(nx)$, and that $E(n)=e^n$
We can prove that $E(q)=e^q$ for $q\in\Bbb{Q}$. We define $e^x=E(x)$ for $x\in\Bbb{R}$, and consequently $L(x)=ln(x)$.
h) show that for all $x\in\Bbb{R}$ applies
$$\lim_{x\to \infty}\left(1+\frac{x}{n}\right)^n=e^x$$
(Hint: Define the function $f$ like $f(t)=ln(1+xt)$ for $x\neq0$ and inspect $f'(0)$.)
My Work
a) i) $$L(xy)=\int_1^{xy}\frac{dt}{t}=\int_1^{x}\frac{dt}{t}+\int_x^{xy}\frac{dt}{t}=\int_1^{x}\frac{dt}{t}+\int_{\frac{1}{x}*x}^{\frac{1}{x}*{xy}}\frac{x*du}{x*u}=\int_1^{x}\frac{dt}{t}+\int_1^{y}\frac{du}{u}=L(x)+L(y)$$
Using $u=\frac{t}{x}$
ii)$$L(\frac{1}{x})=\int_1^{\frac{1}{x}}\frac{dt}{t}=\int_\frac{1}{1}^{\frac{1}{\frac{1}{x}}}\frac{1}{\frac{1}{u}}\left(\frac{-1}{u^2}\right)du=\int_1^x\frac{-u}{u^2}du=-\int_1^x\frac{1}{u}du=-L(x)$$
using $u=1/t$
b) ?
c) ?
d) $$L'(x)=\left(\int_1^x\frac{dt}{t}\right)'=\frac{1}{x}$$ for all $x>0$ is $L'(x)>0$. $L$ is increasing.
e) $L:(0,\infty)\rightarrow\Bbb{R}$ is continuous and strictly increasing, consequently the inverse function $E(x)$ is continuous and strictly increasing , and therefore differentiable?
$$E(x)=\int_{-\infty}^x e^t dt \quad??$$
and $$E'(x)=\left(\int_{-\infty}^x e^t dt\right)'=e^x$$
or is that using $E(x)=e^x$ and therefore not allowed?

A: b)$$L(2)=\int_1^2\frac{dt}{t}$$
Note that for $t>1$, $0<\frac1t<1$. So if we imagine the average "height" of the function between $(1,2)$ is $0<h<1$ then the integral is equal to this height multiplied by the width, which is $1$. And so:
$$0<L(2)<1$$


text:
Q: Creating multiple files with the names saved in text Say, I have a list.txt contained the names:
Book Summary to Complete
Jargon to Collect
Open Problem to Solve
Wordlist to Filter
...
etc

*

*How can I create files with its names saved in list.txt?

*For more usage, say the list.txt is updated period, how can I create the rest of files as soon as list.txt updated?

Thanks

A:
How can I create files with its names saved in list.txt?

You can either loop through the output of cat
 cat "list.txt" | while read LINE; do
     touch "./${LINE}"
 done

or make read read from file descriptor other than standard input
 while read -u 4 LINE; do
     touch "./${LINE}"
 done 4<list.txt

There might be lots of solutions though.
Just remember to enclose your variable references in double quotes and curly braces as long as the value of your variable may contain spaces.

For more usage, say the list.txt is updated period, how can I create the rest of files as soon as list.txt updated?

Basically this can be achieved by something monstrous like checking for changes in file in an infinite loop, but I doubt this is what you want.
Can you be more descriptive?
How and where do you want to use your list.txt file?


text:
Q: How to retrieve data from eloquent laravel I have a relationship between 4 tables where the kontraks table is directly related to the skkos and vendors table.
But here I have a relationship between the skkos table and the units table. How to relate between skkos table and unit table? so i can retrieve unit->name from table units

{
  id: 1,
  periode: "TW III",
  nomor_kontrak: "nomor kontrak",
  tanggal_awal: "2021-12-04",
  tanggal_akhir: "2021-12-04",
  uraian_komitmen: "uraian",
  nilai_kontrak: 100000,
  created_at: "2021-12-04T12:33:32.000000Z",
  updated_at: "2021-12-04T12:33:32.000000Z",
      skko: {
          id: 1,
          unit_id: 1,
          kategori_id: 17,
          nomor_skko: "001/OPR/UID-LPG/2021/M",
          nomor_prk: "2021.PRK.PEG.UID.01.01",
          periode: "TW I",
          uraian_kegiatan: "Pemeliharaan Kesehatan",
          nilai_rekomendasi: 1374595806,
          nilai_penetapan: 1374595806,
          revisi: "0",
          tanggal: "2021-01-26",
          created_at: "2021-12-01T15:15:44.000000Z",
          updated_at: "2021-12-01T15:15:44.000000Z"
          },
     vendor: {
          id: 1,
          name: "Apotek Kimia Farma",
          created_at: "-000001-11-30T00:00:00.000000Z",
          updated_at: "-000001-11-30T00:00:00.000000Z"
          }
}

My eloquent relation:
$kontrak =  Kontrakao::with('skko','vendor')
            ->orderBy('id','DESC')
            ->get();

A: You need to eager load the relation. Try:
$kontrak =  Kontrakao::with('skko.unit','vendor')
               ->orderBy('id','DESC')
               ->get();

A: I have solved this with modify my model Kontrakao add this "->with('unit')" on skko method:
public function skko()
    {
        return $this->belongsTo(Skko::class)->with('unit');
    }

So in view i can call it with this:
{{$row->skko->unit->name}}


text:
Q: Calculate Median for a group based on lag and lead values in R I have a complex ask, hence would appreciate your patience.
For each datapoint, I would like to first capture the values from lag and lead columns, and then identify those values in the series for my dataset, and compute the median value using the captured values for each group.

Group,Date,Month,Sales,lag,lead
Group1,42005,1,2503,0,2
Group1,42036,2,3734,0,2
Group1,42064,3,6631,2,3
Group1,42095,4,8606,0,0
Group1,42125,5,1889,0,2
Group1,42156,6,4819,1,2
Group1,42186,7,3294,1,0
Group1,42217,8,38999,2,0
Group1,42248,9,28372,1,0
Group1,42278,10,25396,4,1
Group1,42309,11,21093,1,0
Group2,42339,1,9263,0,3
Group2,42005,2,6660,1,3
Group2,42036,3,28595,2,2
Group2,42064,4,123,2,0
Group2,42095,5,11855,3,3
Group2,42125,6,15845,4,3
Group2,42156,7,32331,2,2
Group2,42186,8,3188,1,1
Group2,42217,9,38161,4,0

For example, if we look at Month 6 for Group1, the Sales value is 4819, the lag and lead value is 1, and 2 respectively.
I would like to first capture the lag and lead values, and then vlookup in the series. For 4819, for lag(value=1), i would like to go till one datapoint above 4819, (which is 1889, a.k.a 4819->1889, similarly for lead(value=2), i would like to go till two datapoints below 4891, which are 3294 and 38999. So now capture points for 4819 datapoint, is 1899,4819,3294 and 38999, hence now i would like to take the median of this, and store it in my output. THis exercise i want to do for each group.
Similarly, for Group 2, Month 4, i would like to take capture previous 2 lag datapoints with reference to 123( lead is zero, hence it will not be captured), and take median of the the total 3 values.
I tried the same for one particular case with an ifelse condition, to see how it works.
df$output <- ifelse(lag==0 & lead==1, median(Sales,lead(Sales,1)),0)
The result was very surprising. R took the median of all the values for the column. Another problem is even if it had worked, i would have to write multiple ifelse conditions, hence looking for a simpler solution.
Not sure how to do the approach the problem and do the exercise for each group in R.
Below is the output i am trying to achieve.
Group,Date,Month,Sales,lag,lead,Output
Group1,42005,1,2503,0,2,3734
Group1,42036,2,3734,0,2,6631
Group1,42064,3,6631,2,3,4276.5
Group1,42095,4,8606,0,0,8606
Group1,42125,5,1889,0,2,3294
Group1,42156,6,4819,1,2,4056.5
Group1,42186,7,3294,1,0,4056.5
Group1,42217,8,38999,2,0,4819
Group1,42248,9,28372,1,0,33685.5
Group1,42278,10,25396,4,1,23244.5
Group1,42309,11,21093,1,0,23244.5
Group2,42339,1,9263,0,3,7961.5
Group2,42005,2,6660,1,3,9263
Group2,42036,3,28595,2,2,9263
Group2,42064,4,123,2,0,6660
Group2,42095,5,11855,3,3,11855
Group2,42125,6,15845,4,3,13850
Group2,42156,7,32331,2,2,15845
Group2,42186,8,3188,1,1,32331
Group2,42217,9,38161,4,0,15845

Any leads would be highly appreciated.
I am missing something. please guide me how to solve this problem. If there is any function that i needs to use, please help me with the same.
Thanks,

A: df$Output <- sapply(seq(nrow(df)), # For each row (number) in df
                    function(i)
                      # take the median of Sales from
                      # current row - current lag value
                      # to
                      # current row + current lead value
                      with(df, median(Sales[(i - lag[i]):(i + lead[i])])))

Data Used:
df <- data.table::fread("
Group,Date,Month,Sales,lag,lead
Group1,42005,1,2503,0,2
Group1,42036,2,3734,0,2
Group1,42064,3,6631,2,3
Group1,42095,4,8606,0,0
Group1,42125,5,1889,0,2
Group1,42156,6,4819,1,2
Group1,42186,7,3294,1,0
Group1,42217,8,38999,2,0
Group1,42248,9,28372,1,0
Group1,42278,10,25396,4,1
Group1,42309,11,21093,1,0
Group2,42339,1,9263,0,3
Group2,42005,2,6660,1,3
Group2,42036,3,28595,2,2
Group2,42064,4,123,2,0
Group2,42095,5,11855,3,3
Group2,42125,6,15845,4,3
Group2,42156,7,32331,2,2
Group2,42186,8,3188,1,1
Group2,42217,9,38161,4,0
")

dout <- fread("
Group,Date,Month,Sales,lag,lead,Output
Group1,42005,1,2503,0,2,3734
Group1,42036,2,3734,0,2,6631
Group1,42064,3,6631,2,3,4276.5
Group1,42095,4,8606,0,0,8606
Group1,42125,5,1889,0,2,3294
Group1,42156,6,4819,1,2,4056.5
Group1,42186,7,3294,1,0,4056.5
Group1,42217,8,38999,2,0,4819
Group1,42248,9,28372,1,0,33685.5
Group1,42278,10,25396,4,1,23244.5
Group1,42309,11,21093,1,0,23244.5
Group2,42339,1,9263,0,3,7961.5
Group2,42005,2,6660,1,3,9263
Group2,42036,3,28595,2,2,9263
Group2,42064,4,123,2,0,6660
Group2,42095,5,11855,3,3,11855
Group2,42125,6,15845,4,3,13850
Group2,42156,7,32331,2,2,15845
Group2,42186,8,3188,1,1,32331
Group2,42217,9,38161,4,0,15845
")
all.equal(df$Output, dout$Output)
# [1] TRUE

A: setDT(df)[,i:=sequence(.N)][,med:=as.numeric(median(df$Sales[c((i-lag):(i+lead))])),by=i][,i:=NULL][]
     Group  Date Month Sales lag lead     med
 1: Group1 42005     1  2503   0    2  3734.0
 2: Group1 42036     2  3734   0    2  6631.0
 3: Group1 42064     3  6631   2    3  4276.5
 4: Group1 42095     4  8606   0    0  8606.0
 5: Group1 42125     5  1889   0    2  3294.0
 6: Group1 42156     6  4819   1    2  4056.5
 7: Group1 42186     7  3294   1    0  4056.5
 8: Group1 42217     8 38999   2    0  4819.0
 9: Group1 42248     9 28372   1    0 33685.5
10: Group1 42278    10 25396   4    1 23244.5
11: Group1 42309    11 21093   1    0 23244.5
12: Group2 42339     1  9263   0    3  7961.5
13: Group2 42005     2  6660   1    3  9263.0
14: Group2 42036     3 28595   2    2  9263.0
15: Group2 42064     4   123   2    0  6660.0
16: Group2 42095     5 11855   3    3 11855.0
17: Group2 42125     6 15845   4    3 13850.0
18: Group2 42156     7 32331   2    2 15845.0
19: Group2 42186     8  3188   1    1 32331.0
20: Group2 42217     9 38161   4    0 15845.0


text:
Q: Nested form doesn't show up on page I'm trying to build a nested form, but I can't get it to work. I'm using rails 5.2, devise and wicked wizard.
I have tried to use the cocoon gem, but without luck. The problem is, that the nested form doesn't show up on the page, it's just a blank section on the page.
This is what I have tried so far with the cocoon gem installed, and I have added //= require cocoon to application.js.
I have a user table and a services table. The service table is the nested form.
This is how I created the services table
class Services < ActiveRecord::Migration[5.2]
  def change
    create_table :services do |t|
      t.string :name
      t.text :description
      t.integer :duration
      t.integer :price
      t.timestamps
  end
end
end

I have added a foreign key to the services table like this
AddUserReferenceToServices
class AddUserReferenceToServices < ActiveRecord::Migration[5.2]
  def change
    add_reference :services, :user, foreign_key: true
  end
end

I have created these relations
user.rb
class User < ApplicationRecord
    has_many :services
    accepts_nested_attributes_for :services, reject_if: :all_blank, allow_destroy: true
end

service.rb
class Service < ApplicationRecord
    belongs_to :user
end

I have added values to the user params
def user_params

  params.require(:user).permit(clinic_images: [], profession_ids: [], speciality_ids: [], services_attributes: [:id, :description, :name, :duration, :price, :_destroy])

end

main_form.html.erb

    <%= simple_form_for @user, url: wizard_path, method: :put do |f| %>

Professioner

            <%= f.association :professions, input_html: { id: 'professions-select', class: 'js-example-basic-multiple' } %>

Mangler der en profession på listen? Så skriv til os på info@betterwing.dk

        <%= f.simple_fields_for :services do |t| %>
        <%= render 'services/services_fields', :f => t %>
        <% end %>

      <%= link_to_add_association 'add services', f, :services, :partial => 'services/services_fields' %>

services/_services_fields.html.erb
<%= f.input_field :name, required: true, autofocus: true, autocomplete: "Navn på behandling", placeholder: "Navn på behandling" %>
<%= f.input_field :description, required: true, rows: '1', autofocus: true, autocomplete: "Beskrivelse af behandling", placeholder: "Beskrivelse af behandling"%>
<%= f.input_field :duration, required: true, rows: '1', autofocus: true, autocomplete: "Tid", placeholder: "Tid"%>
<%= f.input_field :price, required: true, rows: '1', autofocus: true, autocomplete: "Pris", placeholder: "Pris"%>

<%= link_to_remove_association 'x', f %>

registration_steps_controller.rb
class RegistrationStepsController < ApplicationController

    include Wicked::Wizard
    steps :company_general, :company_images, :practitioners_general, :practitioners_professions, :practitioners_educations

    def new
      @user.services.new
    end

    def show
   @user = current_user
   render_wizard
    end

    def update
      @user = current_user
      # Change @user.attributes(user_params) by @user.update_attributes(user_params)
      @user.update_attributes(user_params)
      render_wizard @user
    end

private
    def user_params

      params.require(:user).permit(clinic_images: [], profession_ids: [], speciality_ids: [], services_attributes: [:id, :description, :name, :duration, :price, :_destroy])

    end

end

A: You need to instantiate the object, in controller action
@user.services.new

or if this partial is only used in new form not shared with edit form, you can try this
<%= f.simple_fields_for @user.services.new do |t| %>

Give it a try!


text:
Q: Lower volume of AVAudioPlayer sound I have a background song that I use on an infinite loop while my app is in use.
Except that the sound/volume is too high... I'd like it to be played at half the volume... This is how I load the music:
//background music for in-game loop
backgroundLoop = [[NSBundle mainBundle] pathForResource:@"Background" ofType:@"wav"];
GameMusic = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:backgroundLoop] error:NULL];
GameMusic.delegate = self;          //need <...> in .h
GameMusic.numberOfLoops = -1;       //play infinite loop

I've tried a few things, but nothing affects the volume of the track. I've tried this:
GameMusic.volume = 0.5f;

and:
[GameMusic setVolume: 0.5f];

but it doesn't change the volume and still plays at the same max volume...
The strange thing is, if I set the volume to 0.0 ([GameMusic setVolume: 0.5f];) it doesn't play at all because I'm guessing it's setting volume to zero... but why does 0.1f or 0.5f not adjust the volume when it's a linear scale from 0-1?
How can I lower the volume of the sound? It's far too loud.
Also, I tried editing the actual sounds in Garageband, but they won't export any sounds under a second long so it's not feasible to adjust them manually.
Thanks.
Update
A Wiki, shows the following file formats are supported:
- AAC (MPEG-4 Advanced Audio Coding)
 - ALAC (Apple Lossless)
 - AMR (Adaptive Multi-rate)
 - HE-AAC (MPEG-4 High Efficiency AAC)
 - iLBC (internet Low Bit Rate Codec)
 - Linear PCM (uncompressed, linear pulse code modulation)
 - MP3 (MPEG-1 audio layer 3)
 - µ-law and a-law
Unfortunately, I changed my .wav to a .mp3 and it still isn't working :(

A: It's finally working. The volume is adjusted by using lower linear values such as 0.01f and 0.08f.
I changed my file type to mp3 as wav isn't supported:
    backgroundLoop = [[NSBundle mainBundle] pathForResource:@"Background" ofType:@"mp3"];

and then set the volume of the loaded audio:
    GameMusic.volume = 0.01f

and 0.01f cuts the volume in half (approximately by my ears), but may be different depending on what track is used, if it's normalised or what file format it's encoded in.
I hope this helps.

A: I suspect that it is working but, because the sound is so loud to start with, you are not perceiving the difference (because of the logarithmic nature of the decibel scale of intensities). Try a much smaller number, such as 0.05, perhaps.

A: I was getting errors in Swift 3.0 using this syntax.  I resolved it by trial and error.  Use the following to adjust the volumes:
nameOfFile.volume = 1.0
Drop the "f".  Anything above 1.0 will increase the volume, below will decrease.  Hope this helps.  Cheers.


text:
Q: Making section Responsive I am trying to make my section responsive by making the (trending item) appear 2 instead of 1 in the mobile width. I am planning to have like 20 items making it long and the website not that attractive. I would love help in making them 2. Thanks.

.trending
{
    width: 100%;
    padding-top: 105px;
    padding-bottom: 50px;
}
.trending_container
{
    margin-top: 90px;
}
.trending_item
{
    margin-bottom: 55px;
}
.trending_image
{
    width: 82px;
    height: 76px;
    float: left;
}
.trending_image img
{
    width: 100%;
}
.trending_content
{
    padding-left: 94px;
}
.trending_title
{
    margin-top: -5px;
}
.trending_title a
{
    font-size: 14px;
    font-weight: 700;
    color: #2d2c2c;
    -webkit-transition: all 200ms ease;
    -moz-transition: all 200ms ease;
    -ms-transition: all 200ms ease;
    -o-transition: all 200ms ease;
    transition: all 200ms ease;
}
.trending_title a:hover
{
    color: #fa9e1b;
}
.trending_price
{
    font-size: 14px;
    font-weight: 700;
    color: #fa9e1b;
}
.trending_location
{
    font-size: 14px;
    font-weight: 400;
    color: #929191;
    text-transform: uppercase;
    margin-top: 2px;
}

.clearfix::before, .clearfix::after
{
    content: "";
    display: table;
}
.clearfix::after
{
    clear: both;
}
.clearfix
{
    zoom: 1;
}

@media only screen and (max-width: 575px)
{
  .trending_title a
{
  font-size: 14px;
}
.trending_price
{
  font-size: 12px;
}
.trending_location
{
  font-size: 12px;
}
.offers_image_container
{
  height: calc((100vw - 30px) / 0.974);
}
.trending_item
{
  margin-bottom: 30px;
}
.trending {
position: static;}

}

Activities

What to do in
            Nairobi

 Enquire for any of the activities and a tour guide will be designated to ensure smooth travelling and execution
              of all activities done to perfection.

Shopping at Maasai Market

From $182

madrid, spain

Nairobi National Park Game Drive

From $182

madrid, spain

queen hotel

From $182

madrid, spain

mars hotel

From $182

madrid, spain

grand hotel

From $182

madrid, spain

mars hotel

From $182

madrid, spain

queen hotel

From $182

madrid, spain

mars hotel

From $182

madrid, spain

A: If you want your items to be on 2 columns instead of 1 for mobile, you must add:

*

*col-xs-6 for Bootstrap 3 (minimum col will be always col-xs-x)

*col-6 for Bootstrap 4 (minimum col will be always col-x)

Bootstrap 3:

.trending
{
    width: 100%;
    padding-top: 105px;
    padding-bottom: 50px;
}
.trending_container
{
    margin-top: 90px;
}
.trending_item
{
    margin-bottom: 55px;
}
.trending_image
{
    width: 82px;
    height: 76px;
    float: left;
}
.trending_image img
{
    width: 100%;
}
.trending_content
{
    padding-left: 94px;
}
.trending_title
{
    margin-top: -5px;
}
.trending_title a
{
    font-size: 14px;
    font-weight: 700;
    color: #2d2c2c;
    -webkit-transition: all 200ms ease;
    -moz-transition: all 200ms ease;
    -ms-transition: all 200ms ease;
    -o-transition: all 200ms ease;
    transition: all 200ms ease;
}
.trending_title a:hover
{
    color: #fa9e1b;
}
.trending_price
{
    font-size: 14px;
    font-weight: 700;
    color: #fa9e1b;
}
.trending_location
{
    font-size: 14px;
    font-weight: 400;
    color: #929191;
    text-transform: uppercase;
    margin-top: 2px;
}

.clearfix::before, .clearfix::after
{
    content: "";
    display: table;
}
.clearfix::after
{
    clear: both;
}
.clearfix
{
    zoom: 1;
}

@media only screen and (max-width: 575px)
{
  .trending_title a
{
  font-size: 14px;
}
.trending_price
{
  font-size: 12px;
}
.trending_location
{
  font-size: 12px;
}
.offers_image_container
{
  height: calc((100vw - 30px) / 0.974);
}
.trending_item
{
  margin-bottom: 30px;
}
.trending {
position: static;}

}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.0/css/bootstrap.css" integrity="sha512-qwBwa3tCXzwsUi4qaXeRMWS/CEeG5iNVpZz98o83NwoDdpbm1ss00GaALwCmXEnr6pQoVm49JaNMKuWvuoHKJA==" crossorigin="anonymous" />

Activities

What to do in
            Nairobi

 Enquire for any of the activities and a tour guide will be designated to ensure smooth travelling and execution
              of all activities done to perfection.

Shopping at Maasai Market

From $182

madrid, spain

Nairobi National Park Game Drive

From $182

madrid, spain

queen hotel

From $182

madrid, spain

mars hotel

From $182

madrid, spain

grand hotel

From $182

madrid, spain

mars hotel

From $182

madrid, spain

queen hotel

From $182

madrid, spain

mars hotel

From $182

madrid, spain

Bootsrap 4:

.trending
{
    width: 100%;
    padding-top: 105px;
    padding-bottom: 50px;
}
.trending_container
{
    margin-top: 90px;
}
.trending_item
{
    margin-bottom: 55px;
}
.trending_image
{
    width: 82px;
    height: 76px;
    float: left;
}
.trending_image img
{
    width: 100%;
}
.trending_content
{
    padding-left: 94px;
}
.trending_title
{
    margin-top: -5px;
}
.trending_title a
{
    font-size: 14px;
    font-weight: 700;
    color: #2d2c2c;
    -webkit-transition: all 200ms ease;
    -moz-transition: all 200ms ease;
    -ms-transition: all 200ms ease;
    -o-transition: all 200ms ease;
    transition: all 200ms ease;
}
.trending_title a:hover
{
    color: #fa9e1b;
}
.trending_price
{
    font-size: 14px;
    font-weight: 700;
    color: #fa9e1b;
}
.trending_location
{
    font-size: 14px;
    font-weight: 400;
    color: #929191;
    text-transform: uppercase;
    margin-top: 2px;
}

.clearfix::before, .clearfix::after
{
    content: "";
    display: table;
}
.clearfix::after
{
    clear: both;
}
.clearfix
{
    zoom: 1;
}

@media only screen and (max-width: 575px)
{
  .trending_title a
{
  font-size: 14px;
}
.trending_price
{
  font-size: 12px;
}
.trending_location
{
  font-size: 12px;
}
.offers_image_container
{
  height: calc((100vw - 30px) / 0.974);
}
.trending_item
{
  margin-bottom: 30px;
}
.trending {
position: static;}

}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">

Activities

What to do in
            Nairobi

 Enquire for any of the activities and a tour guide will be designated to ensure smooth travelling and execution
              of all activities done to perfection.

Shopping at Maasai Market

From $182

madrid, spain

Nairobi National Park Game Drive

From $182

madrid, spain

queen hotel

From $182

madrid, spain

mars hotel

From $182

madrid, spain

grand hotel

From $182

madrid, spain

mars hotel

From $182

madrid, spain

queen hotel

From $182

madrid, spain

mars hotel

From $182

madrid, spain


text:
Q: How to start ActiveMQ messageListener after deploying my application using spring? How to start ActiveMQ messageListener after deploying my application using spring?
my xml file is given below,

        -->

<bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">
    <property name="targetConnectionFactory" ref="activeMQConnectionFactory"/>
</bean>

<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
    <property name="connectionFactory" ref="connectionFactory"/>
</bean>

<bean id="messageListener" class="com.job.SampleMessageListener">
    <property name="jobResponseBean" ref="jobResponseBean"/>
    <property name="startupMessageHandlerBean" ref="startupMessageHandlerBean"/>
</bean>

<bean id="listenerContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
    <property name="concurrentConsumers" value="${consumer.count}"/>
    <property name="connectionFactory" ref="connectionFactory"/>
    <property name="destinationName" value="general"/>
    <property name="messageListener" ref="messageListener"/>

enter code here
</bean>

<bean id="generalQueue" class="org.apache.activemq.command.ActiveMQQueue">
    <constructor-arg value="general"/>
</bean>

A: Spring should start the listenerContainer automatic when its starting/started. So if you have setup all the configuration correctly, it should happen out of the box.


text:
Q: Write TIFF file in python from String I need a way to easily write a compressed TIFF file from a String in python. I already look at the Python Imaging Library PIL But I need to write a very specific TIFF format and PIL only supports uncompressed at the moment. I need to write a LZW compressed, striped TIFF with just one simple line of text in it. I would rather not have to write something from scratch, but if I do I do.

A: I have just used WinPython to write a TIFF file with LZW compression:
from PIL import Image, TiffImagePlugin

[...]

TiffImagePlugin.WRITE_LIBTIFF = True
im.save(filename, compression = "tiff_lzw")
TiffImagePlugin.WRITE_LIBTIFF = False

(See this WinPython ticket).
(Edit 2014-05-13: Fixed my READ_LIBTIFF/WRITE_LIBTIFF confusion).
(Edit 2015-02-23: Updated the WinPython link).

A: I've used this code in the past, so I can say that it works. This script is from 1997, and PIL has yet to implement compressed TIFF writing.
#
# use "tiffcp" to write compressed TIFF files.
#
# fredrik lundh (may 13, 1997)
#

import os, tempfile

# install standard driver
import Image, TiffImagePlugin

LZW      = "lzw"
ZIP      = "zip"
JPEG     = "jpeg"
PACKBITS = "packbits"
G3       = "g3"
G4       = "g4"

def _save(im, fp, filename):

    # check compression mode
    try:
    compression = im.encoderinfo["compression"]
    except KeyError:
    # use standard driver
    TiffImagePlugin._save(im, fp, filename)
    else:
    # compress via temporary file
    if compression not in (LZW, ZIP, JPEG, PACKBITS, G3, G4):
        raise IOError, "unknown compression mode"
    file = tempfile.mktemp()
    im.save(file, "TIFF")
    os.system("tiffcp -c %s %s %s" % (compression, file, filename))
    try: os.unlink(file)
    except: pass

Image.register_save(TiffImagePlugin.TiffImageFile.format, _save)

if __name__ == "__main__":
    # test
    im = Image.open("/usr/iv/tip/images/lenna.ppm")
    im = im.point(lambda v: v >= 128 and 255, "1")
    im.save("lenna.tif", compression=G4)

This code (afaict) just adds the ability to write compressed TIFFs using the standard PIL library, so if you've written your text to a PIL Image object, it should be really easy to implement.


text:
Q: mysql: How to extract multiple tables from one and group by in each, then combine to one result? My table looks like this:
+------+------+------+
| prov | amnt | type |
+------+------+------+
| on   |   10 | 1    |
| on   |   10 | 1    |
| on   |   12 | 2    |
| ab   |   10 | 1    |
| ab   |   12 | 2    |
| ab   |   12 | 2    |
| qc   |   12 | 2    |
| qc   |   13 | 3    |
| qc   |   13 | 3    |
+------+------+------+

I would like to return a table in which for each prov there is a summary grouped by type with the sum and count of each type like so:
+------+-------+------+------+
| prov | total | type | count|
+------+-------+------+------+
| on   |    20 | 1    |     2|
| on   |    12 | 2    |     2|
| ab   |    10 | 1    |     1|
| ab   |    24 | 2    |     2|
| qc   |    12 | 2    |     1|
| qc   |    26 | 3    |     2|
+------+-------+------+------+

Basically if I do three queries with manual input for each province I will get the data in three different tables with three different queries.
SELECT prov, SUM(fine) AS total, code, COUNT(code) AS COUNT
FROM table
WHERE prov = 'on'
GROUP BY code;

   +------+-------+------+------+
   | prov | total | type | count|
   +------+-------+------+------+
   | on   |    20 | 1    |     2|
   | on   |    12 | 2    |     2|
   +------+-------+------+------+

A: Maybe you can use a sql aggregate like:
SELECT *, COUNT(*) FROM tablename GROUP BY prov, type;

For more information about the group-by-functions: see here.

A: Add prov to group by:
SELECT prov, SUM(fine) AS total, code, COUNT(code) AS COUNT
FROM table
GROUP BY prov, code;

A: You need to group by prov and type. Here is what you need:
select
`prov`, sum(`amnt`) as `total`, count(*) as `count`, `type`
group by `prov`, `type`;

A: change your query to be:
SELECT prov, SUM(amnt) AS total, type, COUNT(type) AS COUNT
FROM table
GROUP BY prov, code;


text:
Q: clickhouse-client import file not found I'm trying to import the example data from the link but when I run the below command it can't find the csv file, Error: -bash: full_dataset .csv: No such file or directory and installed with clickhouse docker.

Where do I need to keep the "full_dataset.csv" file?

A: You need to either supply entire path or move the CSV file to clickhouse bin folder where the clickhouse-client resides.

A: I solved this problem by moving the "full_dataset.csv" file to the "root" directory.

A: you need to download the csv dataset from the link and then only execute the code on the clickhouse documentation page, this is indicated https://recipenlg.cs.put.poznan.pl/dataset


text:
Q: Print simple message in pdf invoice of Magento2 using echo? I have created a Default invoice of Magento2 under the (sales order) option, see the screenshot: https://prnt.sc/tje4zn
This is the file path for invoice pdf of Magento2: /vendor/magento/module-sales/Model/Order/Pdf/AbstractPdf.php and below is the file code,
I want to echo simple text message in the end of the file like
<?php echo "NOTE: This is not a GST invoice. This is a packing slip only.";  ?>

Please help me with how I can achieve and add this message to pdf invoice format in the last as I have also mentioned in the screenshot above.
Many Thanks in Advance.

A: You can do so this with code,
Assuming you have a custom Vendor_Invoice module: Change the path specific and module name as per yours. Put following content into the Vendor/Invoice/etc/di.xml,
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\Sales\Model\Order\Pdf\Invoice" type="Vendor\Invoice\Model\Order\Pdf\InvoicePdf"/>
</config>

Now you can create Vendor\Invoice\Model\Order\Pdf\InvoicePdf.php file & add the below code,
<?php

namespace Vendor\Invoice\Model\Order\Pdf;

use \Magento\Sales\Model\Order\Pdf\Invoice;

class InvoicePdf extends Invoice
{
    /**
     * We only need to override the getPdf of Invoice,
     *  most of this method is copied directly from parent class
     *
     * @param array $invoices
     * @return \Zend_Pdf
     */
    public function getPdf($invoices = []) {
        $this->_beforeGetPdf();
        $this->_initRenderer('invoice');

        $pdf = new \Zend_Pdf();
        $this->_setPdf($pdf);
        $style = new \Zend_Pdf_Style();
        $this->_setFontBold($style, 10);

        foreach ($invoices as $invoice) {
            if ($invoice->getStoreId()) {
                $this->_localeResolver->emulate($invoice->getStoreId());
                $this->_storeManager->setCurrentStore($invoice->getStoreId());
            }
            $page = $this->newPage();
            $order = $invoice->getOrder();
            /* Add image */
            $this->insertLogo($page, $invoice->getStore());
            /* Add address */
            $this->insertAddress($page, $invoice->getStore());
            /* Add head */
            $this->insertOrder(
                $page,
                $order,
                $this->_scopeConfig->isSetFlag(
                    self::XML_PATH_SALES_PDF_INVOICE_PUT_ORDER_ID,
                    \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
                    $order->getStoreId()
                )
            );
            /* Add document text and number */
            $this->insertDocumentNumber($page, __('Invoice # ') . $invoice->getIncrementId());
            /* Add table */
            $this->_drawHeader($page);
            /* Add body */
            foreach ($invoice->getAllItems() as $item) {
                if ($item->getOrderItem()->getParentItem()) {
                    continue;
                }
                /* Draw item */
                $this->_drawItem($item, $page, $order);
                $page = end($pdf->pages);
            }
            /* Add totals */
            $this->insertTotals($page, $invoice);
            if ($invoice->getStoreId()) {
                $this->_localeResolver->revert();
            }
            // draw custom notice
            $this->drawNotice($page);
        }
        $this->_afterGetPdf();
        return $pdf;
    }

    /**
     * draw notice below content
     *
     * @param \Zend_Pdf_Page $page
     */
    protected function drawNotice(\Zend_Pdf_Page $page) {
        $iFontSize = 10;     // font size
        $iColumnWidth = 520; // whole page width
        $iWidthBorder = 260; // half page width
        $sNotice = "NOTE: This is not a GST invoice. This is a packing slip only."; // your message
        $iXCoordinateText = 30;
        $sEncoding = 'UTF-8';
        $this->y -= 10; // move down on page
        try {
            $oFont = $this->_setFontRegular($page, $iFontSize);
            $iXCoordinateText = $this->getAlignCenter($sNotice, $iXCoordinateText, $iColumnWidth, $oFont, $iFontSize);  // center text coordinate
            $page->setLineColor(new \Zend_Pdf_Color_Rgb(1, 0, 0));                                             // red lines
            $iXCoordinateBorder = $iXCoordinateText - 10;                                                               // border is wider than text
            // draw top border
            $page->drawLine($iXCoordinateBorder, $this->y, $iXCoordinateBorder + $iWidthBorder, $this->y);
            // draw text
            $this->y -= 15;                                                                                // further down
            $page->drawText($sNotice, $iXCoordinateText, $this->y, $sEncoding);
            $this->y -= 10; // further down
            // draw bottom border
            $page->drawLine($iXCoordinateBorder, $this->y, $iXCoordinateBorder + $iWidthBorder, $this->y);
            // draw left border
            $page->drawLine($iXCoordinateBorder, $this->y, $iXCoordinateBorder, $this->y + 25 /* back to first line */);
            // draw right border
            $page->drawLine($iXCoordinateBorder + $iWidthBorder, $this->y, $iXCoordinateBorder + $iWidthBorder, $this->y + 25 /* back to first line */);
            $this->y -= 10;
        } catch (\Exception $exception) {
            // handle
        }
    }

    /**
     * Draw header for item table
     *
     * @param \Zend_Pdf_Page $page
     * @return void
     */
    protected function _drawHeader(\Zend_Pdf_Page $page)
    {
        /* Add table head */
        $this->_setFontRegular($page, 10);
        $page->setFillColor(new \Zend_Pdf_Color_Rgb(0.93, 0.92, 0.92));
        $page->setLineColor(new \Zend_Pdf_Color_GrayScale(0.5));
        $page->setLineWidth(0.5);
        $page->drawRectangle(25, $this->y, 570, $this->y - 15);
        $this->y -= 10;
        $page->setFillColor(new \Zend_Pdf_Color_Rgb(0, 0, 0));

        //columns headers
        $lines[0][] = ['text' => __('Products'), 'feed' => 35];

        $lines[0][] = ['text' => __('SKU'), 'feed' => 290, 'align' => 'right'];

        // custom column
        $lines[0][] = ['text' => __('HSN'), 'feed' => 290, 'align' => 'right'];

        $lines[0][] = ['text' => __('Qty'), 'feed' => 435, 'align' => 'right'];

        $lines[0][] = ['text' => __('Price'), 'feed' => 360, 'align' => 'right'];

        $lines[0][] = ['text' => __('Tax'), 'feed' => 495, 'align' => 'right'];

        $lines[0][] = ['text' => __('Subtotal'), 'feed' => 565, 'align' => 'right'];

        $lineBlock = ['lines' => $lines, 'height' => 5];

        $this->drawLineBlocks($page, [$lineBlock], ['table_header' => true]);
        $page->setFillColor(new \Zend_Pdf_Color_GrayScale(0));
        $this->y -= 20;
    }
}

Hope this will helps, and please let me know if there is any issues...


text:
Q: deploying azure function app that uses a system assigned managed identity We have an azure function app that uses a system assigned managed identity to access resources.
I have not found a way to use this system assigned identity when deploying the function app via devops.
e.g.

*

*deploy the function app.

*enable the system assigned identity.

*grant function app access to key vault with the system assigned managed identity.

is this a case where the system assigned identity simply does not work and i need to create one manually ?

A: First of all, if you want to deploy the function app via DevOps using managed identity created by the azure function, the answer is no.
See here:
https://learn.microsoft.com/en-us/azure/devops/pipelines/library/connect-to-azure?view=azure-devops#create-an-azure-resource-manager-service-connection-to-a-vm-with-a-managed-service-identity

You are required to use a self-hosted agent on an Azure VM in order to
use managed service identity.

Follow the steps above if you want to use manage identity to integrate with DevOps.
A system-assigned managed identity is enabled directly on an Azure service instance. When the identity is enabled in your azure function app service instance, Azure creates an identity for the azure function app instance in the Azure AD tenant that's trusted by the subscription of the instance. After the identity is created, the credentials are provisioned onto the azure function app instance.
You can find it in Enterprise applications of AAD.

This application has nothing to do with the credentials required to deploy azure functions from DevOps.
The managed identity you create with the 'enable' button is mainly used to manage the access rights of the azure function app instance to other service instances in azure.


text:
Q: Thread 1: signal SIGABRT Xcode practice Xcode is not throwing any errors until I build the app in the simulator. As soon as the simulator launches it triggers the SIGABRT error. Here's my code:
import UIKit

class ViewController: UIViewController, UITableViewDelegate {

    var cellContent = ["example"]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    func numberOfRowsInSection(section: Int) -> Int {

        return cellContent.count

    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")

        cell.textLabel?.text = cellContent[indexPath.row]

        return cell

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}


text:
Q: Integrability with respect to different measures i'm doing an integration exercise and i'm new to the subject and i'm kind of struggling it is as follow

We consider the application $g$ : $\mathbb{R}\rightarrow \mathbb{R}$ defined by $g(x)=\frac{1}{x} if x >0$ and $ g(x)=0 $ otherwise.
We note $\lambda$ the Lebesgue measure on ($\mathbb{R}, \mathcal{B(\mathbb{R})}$ and $\mu$ the image measure of the Lebesgue measure by $g$, defined by $\mu(A)=\lambda(g^-1(A))$ for $A \in \mathcal{B(\mathbb{R})}$. We remind that for all function $h$ : $\mathcal{B(\mathbb{R})} \rightarrow ([0,\infty],\mathcal{B([0,\infty])})$ measruable
\begin{align} \int_{\mathbb{R}} hd\mu=\int_{\mathbb{R}} h \circ g d\lambda
\end{align}
We note $\nu= \sum\limits_{n\in\mathbb{N}}\delta_n$ the counting measure over $\mathbb{N}$. For $\alpha \in \mathbb{R}$, let $f_{\alpha}(x)=x^{-\alpha} 1_{[1,\infty[}(x), x\in \mathbb{R}.$

I first have to show that $f$ is measurable but since it is not continuous (i believe) i have to go back to the definition but i'm kind of stuck.
Then we have to give a necessary and sufficient condition over $\alpha$ under which $f_{\alpha}$ is integrable

a) with respect to $ \lambda$, $\mu$ and $ \nu$.

Any hints or helping hand would be greatly appreciated thank you !

A: $f_\alpha$ is not continuous, but it is continuous for $x<1$ and for $x>1$. This suffices to prove that the function is measurable (as for any measurable $A$ we have $B=A\cap[1,\infty)$, $C=A\cap(-\infty,1)$ are measureable and thus $f_\alpha^{-1}(A)=f_\alpha^{-1}(B)\cup f_\alpha^{-1}(C)$ is measurable).
Now when is $f_\alpha$ integrable? For $\lambda$ we know that this is the case if and only if $\alpha>1$ (if $\alpha<1$ you get $\int_1^\infty x^{-\alpha} = (\alpha-1)(1 - \lim_{x\to\infty} x^{1-\alpha}) = \alpha$, if $\alpha < 1$ we get the same, but the limit does not exists, for $\alpha=1$ we get $\lim_{x\to\infty}\log(x)$, which also does not exist.
For $\mu$ we want $f\circ g$ to be integrable by $\lambda$, that is $x^\alpha 1_{[1,\infty)}(1/x)=x^\alpha 1_{(0,1]}(x)$. So when is
$$ \int_0^1 x^\alpha\,\mathrm d\lambda$$
finite? We know this is the case if and only if $\alpha >-1$ (similar reasoning to $\lambda$ case).
Then for $\nu$ you want to have that $\int_\mathbb R f_\alpha\,\mathrm d\nu = \sum_{n\in\mathbb N} f_\alpha(n)$ is finite. So when is
$$ \sum_{n=1}^\infty n^{-\alpha} $$
finite? We know again that this is exactly the case iff $\alpha>1$.


text:
Q: I found this code for conditional buttons but I don't understand the on_number(self, obj, value) code I'm very new to kivy. So I found this code online, and I don't understand the section for on_number. I know that if I remove it, the number would be updated but it won't repeat the process for creating a widget. Could someone please explain how the function for on_number works and what the three variables refer to?
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import NumericProperty
from kivy.lang import Builder

Builder.load_string('''
<SubWidget1>:
    Label:
        text: 'number is bigger than 3'
    Button:
        text: 'click here to decrease'
        on_press: root.parent.number -= 1

<SubWidget2>:
    Label:
        text: 'number is smaller than 3'
    Button:
        text: 'click here to increase'
        on_press: root.parent.number += 1

<MyWidget>
    number: 0
''')

class SubWidget1(BoxLayout):
    pass

class SubWidget2(BoxLayout):
    pass

class MyWidget(BoxLayout):
    number = NumericProperty()

    def __init__(self, *args):
        super(MyWidget, self).__init__(*args)
        self.widget = None
        self._create_widget()

    def _create_widget(self):
        print(self.number)
        if self.widget is not None:
            self.remove_widget(self.widget)
        if self.number > 3:
            self.widget = SubWidget1()
        else:
            self.widget = SubWidget2()
        self.add_widget(self.widget)

    def on_number(self, obj, value):
        self._create_widget()

class MyApp(App):
    def build(self):
        return MyWidget()

if __name__ == '__main__':
    MyApp().run()

A: All Kivy properties will automatically call a method of their class based on the property name when they change. This method is on_propertyname, and is passed two arguments: the object whose property just changed, and the new value of the property.


text:
Q: ListView in Fragment not showing any Items ANDROID I'm trying to use a ListView in my Fragment which is displayed by a TabViewer2. The listadapter I used is the ArrayAdapter<String>. Unfourtunately the ListVIew does not show any Items. However the TextViews above and below the List are displayed properly.
fragment_log.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    tools:context=".ui.main.LogFragment">
    <TextView android:text="LOGGING"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <ListView
        android:id="@+id/list_view"
        android:layout_width="wrap_content"
        android:layout_height="100dp"
        android:divider="#000"
        android:dividerHeight="4dp"
        android:foreground="@color/colorPrimary"
        />

    <TextView
        android:text="DD"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout >

LogFragment.kt

class LogFragment : Fragment() {

    companion object {
        fun newInstance() = LogFragment()
    }

    private lateinit var viewModel: MainViewModel
    private lateinit var listAdapter : ArrayAdapter<String>
    private lateinit var binding : FragmentLogBinding
    private var list = arrayOf("test1", "test2", "test3")

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        return inflater.inflate(R.layout.fragment_log, container, false)

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding = FragmentLogBinding.inflate(layoutInflater)
        listAdapter = ArrayAdapter(activity as Context, android.R.layout.simple_list_item_1, list)
        binding.listView.adapter = listAdapter

        viewModel = ViewModelProvider(this).get(MainViewModel::class.java)
        viewModel.getLogList().observe(viewLifecycleOwner, Observer {
            listAdapter.clear()
            listAdapter.addAll(it)
        })

        Toast.makeText(context, "done", Toast.LENGTH_SHORT).show()

    }

}


text:
Q: Modify each td of dataTable with certain class $('#table').DataTable().cells('.currency').data().each(function(value, index) {
        console.log(value);
    });

This code print the value of each td with class currency.
The value is a string that contains a currency (2434 for example). I want to format it into the correct value -> 2.434,00.
So, I can get the value, format it, but I don't know how to replace the old currency with the new.
$(this).val() or $(this).html() does not work.

A: $('#table > tr > td').hasClass('.currency').each(function(value, index) {
        console.log(value);
        $(this).text(formattedValue);
    });

You may have to loop in this way.


text:
Q: How to schedule a build in Jenkins on alternate Saturday I want to schedule a Jenkins job which will back up my database on alternate Saturday I am using this expression  but I am confused how to find out alternate Saturdays in a month
* * * * 6