text:
Q: Как в  сделать белый кружочек? Вот макет

Вот то что получается

Интересует кастомизация зеленых кружочков.
Вот html
<line x1="15" y1="497" x2="15" y2="497" class="ct-point"></line>

Вот CSS
.static_chart .ct-point {
    stroke-width: 20px;
    stroke: #8fbf6e;
}

Как в зеленый кружочек добавить белый фон? Я не могу залезть в html, так как этот svg код генерирует плагин графиков. Как это можно решить только средствами CSS?

A: У неких сущностей в SVG  есть marker и он может быть разный но в моём примере я применил один и тот же маркер для начала и конца и так же для средних точек
смотрим пример

<svg viewBox="0 0 640 200">
  <defs>
    <marker id="dot" viewBox="-1 -1 11 12" refX="5" refY="5" markerWidth="10" markerHeight="10">
      <circle cx="4.5" cy="5" r="5" fill="#fff" stroke="red" stroke-width="1" />
    </marker>
  </defs>
  <polyline points="20,180 100,150 150,100 250,120 300,180" fill="none" stroke="#000" stroke-width="2" marker-start="url(#dot)" marker-mid="url(#dot)" marker-end="url(#dot)" />
</svg>

A: Немного теории для лучшего понимания решения:
Маркер может быть применен к <line>, <polyline>, <polygon>,<path>, <rect> то есть к любому элементу SVG, который имеет линии.
Начальный маркер marker-start="url(#mark)" прикрепляется к началу линии, конечный маркер marker-end="url(#mark)" к концу линии, marker-mid="url(#mark)" в точках излома линий.
Таких маркеров будет ровно столько, сколько раз линия меняет своё направление.
Подробнее о параметрах, настройках, регулировках и применении маркеров здесь.
О возможных анимациях маркеров можно прочитать тут.
Вот этот элемент - маркер будет использован для создания кругов в точках излома графика.
В качестве маркера может быть использована любая фигура SVG. В этом примере это окружность, которая имеет внутри область, закрашенную белым цветом,  с линией окружности соответствующего зеленого цвета.
<circle cx="10" cy="10" r="5" fill="#fff" stroke="#75C65D" stroke-width="2" />
Серая, координатная сетка создана с помощью pattern
Для облегчения понимания кода, читайте комментарии в коде:

<svg  xmlns="http://www.w3.org/2000/svg"  xmlns:xlink="http://www.w3.org/1999/xlink"
         width="520" height="320" viewBox="0 0 520 320" >
<defs>
  <pattern id="patt"
             x="0" y="0" width="100" height="30"
             patternUnits="userSpaceOnUse" >

            <g fill="none" stroke="#CACACA" fill-opacity="0.7">
             <rect x="0" y="0" width="100" height="30" />
            </g>
      </pattern>
      <marker id="mark" viewBox="0 0 22 24" refX="10" refY="10" markerWidth="20" markerHeight="20">
      <circle cx="10" cy="10" r="5" fill="#fff" stroke="#75C65D" stroke-width="2" />
    </marker>
</defs>

             <!-- Бледно-зелёный фон -->
<path fill="#F2F9F1" d="M22 264v-59l78-57 100-51 100 20 97 31 101-31v147z" />
                           <!-- сетка -->
<rect fill="url(#patt)" x="20" width="500" height="270" fill="none" stroke="grey" />
                   <!-- Линия графика -->
<polyline fill="none" stroke="green" stroke-width="2" points="20,210 100,150 200,100 300,120 400,150 500,120"  marker-end="url(#mark)" marker-start="url(#mark)" marker-mid="url(#mark)"  />
</svg>

В качестве бонуса, примеры анимации графика
          <!-- Анимация роста линии графика  -->
     <animate id="an" attributeName="stroke-dasharray" begin="svg1.click;an.end+1.5s"
         dur="4s" values="0,523;523,0" fill="freeze" />

<!-- https://ru.stackoverflow.com/q/1302705/28748 -->
<svg id="svg1"  xmlns="http://www.w3.org/2000/svg"  xmlns:xlink="http://www.w3.org/1999/xlink"
         width="520" height="320" viewBox="0 0 520 320" >
<defs>
             <!--Определение паттерна сетки -->
  <pattern id="patt"
             x="0" y="0" width="100" height="30"
             patternUnits="userSpaceOnUse" >

            <g fill="none" stroke="#CACACA" fill-opacity="0.7">
             <rect x="0" y="0" width="100" height="30" />
            </g>
      </pattern>
             <!--Определение формы маркера -->
      <marker id="mark" viewBox="0 0 22 24" refX="10" refY="10" markerWidth="20" markerHeight="20">
      <circle cx="10" cy="10" r="5" fill="#fff" stroke="#75C65D" stroke-width="2" />
    </marker>
</defs>

             <!-- Бледно-зелёный фон -->
<path fill="#F2F9F1" d="M22 264v-59l78-57 100-51 100 20 97 31 101-31v147z" />
                           <!-- сетка -->
<rect fill="url(#patt)" x="20" width="500" height="270" fill="none" stroke="grey" />
                   <!-- Линия графика -->

 <polyline fill="none" stroke="green" stroke-width="4" stroke-dasharray="0,523" points="20,210 100,150 200,100 300,120 400,150 500,120">
              <!-- Анимация роста линии графика  -->
     <animate id="an" attributeName="stroke-dasharray" begin="svg1.click;an.end+1.5s" dur="4s" values="0,523;523,0" fill="freeze" />
</polyline>

<polyline fill="none" stroke="green" stroke-width="2" stroke-dasharray="0,523" points="20,210 100,150 200,100 300,120 400,150 500,120"  marker-end="url(#mark)" marker-start="url(#mark)" marker-mid="url(#mark)"/>

   <text x="50%" text-anchor="middle" y="22" font-size="24px" fill="green">Click me </text>

</svg>

Анимация рисования соединительных линий и маркеров
Используется анимация маски, которая прорезает маскирующую полосу, показывая тем самым линию графика с маркерами:

<svg id="svg1"  xmlns="http://www.w3.org/2000/svg"  xmlns:xlink="http://www.w3.org/1999/xlink"
         width="520" height="320" viewBox="0 0 520 320" >
<defs>
             <!--Определение паттерна сетки -->
  <pattern id="patt"
             x="0" y="0" width="100" height="30"
             patternUnits="userSpaceOnUse" >

            <g fill="none" stroke="#CACACA" fill-opacity="0.7">
             <rect x="0" y="0" width="100" height="30" />
            </g>
      </pattern>
             <!--Определение формы маркера -->
      <marker id="mark" viewBox="0 0 22 24" refX="10" refY="10" markerWidth="20" markerHeight="20">
      <circle cx="10" cy="10" r="5" fill="#fff" stroke="#75C65D" stroke-width="2" />
    </marker>
              <!-- Анимированная маска -->
    <mask id="mask">
       <rect width="100%" height="100%" fill="white"/>
       <polyline fill="none" stroke="black" stroke-width="20" stroke-dashoffset="542" stroke-dasharray="542"  points="12,215 100,150 200,100 300,120 400,150 510,118">
     <animate id="an" attributeName="stroke-dashoffset" begin="svg1.click;an.end+1.5s" dur="5s" values="523;0" repeatCount="1" fill="freeze" />
    </mask>
</defs>

             <!-- Бледно-зелёный фон -->
<path fill="#F2F9F1" d="M10 264v-49l90-67 100-51 100 20 97 31 114-35v151z" />
                           <!-- сетка -->
<rect fill="url(#patt)" x="20" width="500" height="270" fill="none" stroke="grey" />

 <!-- Линия графика -->

<polyline fill="none" stroke="green" stroke-width="2"   points="20,210 100,150 200,100 300,120 400,150 500,120"  marker-end="url(#mark)" marker-start="url(#mark)" marker-mid="url(#mark)"/>

</polyline>
                   <!-- Маскирующая полоса того же цвета, как фон  -->
                     <!-- которая прорезается маской и показывается полоса графика stroke="green" -->
    <polyline fill="none" stroke="#F2F9F1"  mask="url(#mask)" stroke-width="20" points="11,216 100,150 200,100 300,120 400,150 509,117"/>
    </polyline>
        <text x="50%" text-anchor="middle" y="22" font-size="24px" fill="green">Click me </text>
</svg>

A: Удалось сделать только через Javascript. Пришлось белые кружочки с зеленой рамочкой разместить над зелеными точками графика.
Но на IPhone это не сработало ((((


text:
Q: Android Extract String from Okhttp onResponse Function I would like to get String value from onResponse function in OkHttp3 using Android Studio, which is

final String title_name = jsonarray_news_extract_Data(jsonStr, index)

in below codes.
I've tried insert String variable "a" in argument, but it said

Variable is accessed within inner class. Needs to be declared final

so that I declared as final then it said

Cannot Assign a Value to Final Variable

I tried to put
a = title_name;

after removed Handler method but still not work.
If you have any idea please help me out.
Thank you
public void news_From_API_Title(String url_news, final int index, final TextView textView, String a){

    OkHttpClient client = new OkHttpClient();

    Request request = new Request.Builder()
            .url(url_news)
            .build();

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(@NotNull Call call, @NotNull IOException e) {}

        @Override
        public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
            final String jsonStr = Objects.requireNonNull(response.body()).string();
            final String title_name = jsonarray_news_extract_Data(jsonStr, index);

            Handler mainHandler = new Handler(Looper.getMainLooper());
            mainHandler.post(new Runnable() {
                @Override
                public void run() {

                    a = title_name;
                }
            });
        }
    });

}

private String jsonarray_news_extract_Data(String jsonString_News, int index){
    try {
        JSONObject jsonObject = new JSONObject(jsonString_News);
        JSONArray jsonArray = jsonObject.getJSONArray("Data");
        return jsonArray.getJSONObject(index).getString("title");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}

A: You can use a custom interface like this:
interface ApiCallback{
    void onOkHttpResponse(String data);
    void onOkHttpFailure(Exception exception);
}

Then you pass not a String but an instance of ApiCallback into the method which is actually doing the call:
public void news_From_API_Title(String url_news, final int index, final TextView textView, ApiCallback callback){

    OkHttpClient client = new OkHttpClient();

    Request request = new Request.Builder()
            .url(url_news)
            .build();

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(@NotNull Call call, @NotNull IOException e) {
            callback.onOkHttpFailure(e);
        }

        @Override
        public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
            final String jsonStr = Objects.requireNonNull(response.body()).string();
            final String title_name = jsonarray_news_extract_Data(jsonStr, index);

            Handler mainHandler = new Handler(Looper.getMainLooper());
            mainHandler.post(new Runnable() {
                @Override
                public void run() {
                    callback.onOkHttpResponse(title_name);
                }
            });
        }
    });

}

Now you can use an implementation of ApiCallback as follows:
String url_news = "https://some.web.address/news";
int index = 7;
TextView textView;
news_From_API_Title(url_news, index, textView, new apiCallback(){
    @Override
    public void onOkHttpResponse(String data){
        // do something with data here
        Log.d("TEST", "data = " + data);
    }

    @Override
    onOkHttpFailure(Exception exception){
        // exception handling
    }
});

Please note that it may be better from an architecture point of view if you don't pass the TextView as parameter into the method but instead set the text in onOkHttpResponse():
// TextView will be initialized before calling news_From_API_Title()
// either make TextView a field (then use "private")
// or declare it locally (then use "final")
private TextView textView;

// ... other code ...

String url_news = "https://some.web.address/news";
int index = 7;

// method will only take parameters which are not related to the UI
// since it's desirable to avoid tight coupling of networking and UI components
news_From_API_Title(url_news, index, new apiCallback(){
    @Override
    public void onOkHttpResponse(String data){
        // do something with data here
        // e.g. show data in TextView
        textView.setText(data);
    }

    @Override
    onOkHttpFailure(Exception exception){
        // exception handling
    }
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to display data from HealthKit and internet in WidgetKit I'm developing a widget app that coins multiple functional widgets. The problem is fetching data. I want to fetch data from HealthKit to display step counts and fetch weather data.
I'm using just one Widget object. I show different widgets by changing the View objects in them according to the widget type which is a String property.
I can fetch data from EventKit for calendar events, but reminders, health information, and internet fetching is not working on my code. So where am I doing wrong?
My widget provider is looking like that:
func getTimeline(for configuration: WidgetConfigurationIntentIntent, in context: Context, completion: @escaping (Timeline<Entry>) -> Void) {
    if let widget = lookUpWidget(for: configuration) {
        let currentDate = Date()
        let midnight = Calendar.current.startOfDay(for: currentDate)
        let nextMinute = Calendar.current.date(byAdding: .minute, value: 1, to: midnight)!

        let type = widget.type
        switch type {
        case "Quotes":
            let entry = MainEntry(date: Date(), type: widget.type!, backgroundImageData: widget.backgroundImage, backgroundHexColor: widget.backgroundHexColor, themeHexColor: widget.themeHexColor, fontName: widget.fontName, text: widget.text)
            let timeline = Timeline(entries: [entry], policy: .after(nextMinute))
                completion(timeline)
        case "Daily Forecast":
            let entry = MainEntry(date: Date(), type: widget.type!, weatherInfo: loadWeatherInfo(), backgroundImageData: widget.backgroundImage, backgroundHexColor: widget.backgroundHexColor, themeHexColor: widget.themeHexColor, fontName: widget.fontName)
            let timeline = Timeline(entries: [entry], policy: .after(nextMinute))
                completion(timeline)
        case "Calendar":
            let entry = MainEntry(date: Date(), type: widget.type!, backgroundImageData: widget.backgroundImage, backgroundHexColor: widget.backgroundHexColor, themeHexColor: widget.themeHexColor, fontName: widget.fontName, calendarEventTitles: loadCalendarEventTitles())
            let timeline = Timeline(entries: [entry], policy: .after(nextMinute))
                completion(timeline)
        case "Countdown":
            let entry = MainEntry(date: Date(), type: widget.type!, backgroundImageData: widget.backgroundImage, backgroundHexColor: widget.backgroundHexColor, themeHexColor: widget.themeHexColor, fontName: widget.fontName, text: widget.text, countdownDate: widget.countdownDate)
            let timeline = Timeline(entries: [entry], policy: .after(nextMinute))
                completion(timeline)
        case "Reminders":
            let entry = MainEntry(date: Date(), type: widget.type!, backgroundImageData: widget.backgroundImage, backgroundHexColor: widget.backgroundHexColor, themeHexColor: widget.themeHexColor, fontName: widget.fontName, reminderTitles: loadReminderTitles())
            let timeline = Timeline(entries: [entry], policy: .after(nextMinute))
                completion(timeline)
        case "Battery":
            let entry = MainEntry(date: Date(), type: widget.type!, batteryLevel: Int(loadBatteryLevel()), backgroundImageData: widget.backgroundImage, backgroundHexColor: widget.backgroundHexColor, themeHexColor: widget.themeHexColor, fontName: widget.fontName)
            let timeline = Timeline(entries: [entry], policy: .after(nextMinute))
                completion(timeline)
        case "Clock":
            let entry = MainEntry(date: Date(), type: widget.type!, backgroundImageData: widget.backgroundImage, backgroundHexColor: widget.backgroundHexColor, themeHexColor: widget.themeHexColor, fontName: widget.fontName)
            let timeline = Timeline(entries: [entry], policy: .after(nextMinute))
                completion(timeline)
        case "Steps":
            let entry = MainEntry(date: Date(), type: widget.type!, backgroundImageData: widget.backgroundImage, backgroundHexColor: widget.backgroundHexColor, themeHexColor: widget.themeHexColor, fontName: widget.fontName, stepCount: loadStepCount())
            let timeline = Timeline(entries: [entry], policy: .after(nextMinute))
                completion(timeline)
        case "Photos":
            let entry = MainEntry(date: Date(), type: widget.type!, backgroundImageData: widget.backgroundImage, backgroundHexColor: widget.backgroundHexColor, fontName: widget.fontName)
            let timeline = Timeline(entries: [entry], policy: .after(nextMinute))
                completion(timeline)
        default:
            let entry = MainEntry(date: Date(), type: "Nothing")
            let timeline = Timeline(entries: [entry], policy: .atEnd)
            completion(timeline)
        }
    } else {
        let entry = MainEntry(date: Date(), type: "Nothing")
        let timeline = Timeline(entries: [entry], policy: .atEnd)
        completion(timeline)
    }
}


text:
Q: Render a view based on the conditional statement in Spring I am kind of new to Spring. I am trying to render a view based on the the value returned from DBDAOImplementation class using a conditional if statement inside processController. I am trying to return successuseraddstatus jsp file for success scenarios and faileduseraddstatus jsp file for failed scenarios.
ProcessController.java:
@RequestMapping(value = "/adduserstatus", method = RequestMethod.POST)
public String addStudent(@ModelAttribute("SpringWeb")Process process,ModelMap model) {

    model.addAttribute("fname", process.getFname());
    model.addAttribute("lname", process.getLname());
    model.addAttribute("email", process.getEmail());
    model.addAttribute("phone", process.getPhone());

    ApplicationContext context =
         new ClassPathXmlApplicationContext("Beans.xml");

    DBDAOImp dbd =
         (DBDAOImp)context.getBean("JDBCTemplate");

    dbd.createuser(process.getFname(), process.getLname(), process.getEmail(), process.getPhone());

    if (true){ //This is where I am having trouble
        return "successuseraddstatus";
    }
    return "faileduseraddstatus";
}

DBDAOImplementation.java:
@Override
public Boolean createuser(String fname, String lname, String email, String phone) {

    isExists(email);

    if (isExists==false){

        String SQL = "insert into USERS (user_id,f_name,l_name,creation_date,email,phone) values (seq_users.nextval,?,?,sysdate,?,?)";

        jdbcTemplateObject.update( SQL, fname,lname,email,phone);
        System.out.println("Created Record");
        return true;
    } else {
        return false;
    }
}

A: Below if condition works. But I am not too sure if this is the right approach.
ProcessController.java:
@RequestMapping(value = "/adduserstatus", method = RequestMethod.POST)
public String addStudent(@ModelAttribute("SpringWeb")Process process,ModelMap model) {
    model.addAttribute("fname", process.getFname());
    model.addAttribute("lname", process.getLname());
    model.addAttribute("email", process.getEmail());
    model.addAttribute("phone", process.getPhone());

     DBDAOImp dbd =
         (DBDAOImp)context.getBean("JDBCTemplate");

     if (dbd.createuser(process.getFname(), process.getLname(), process.getEmail(), process.getPhone())){
      return "useraddstatus";
      } else {
          return "faileduseraddstatus";
      }
}


text:
Q: Hello, jquery doesn't change attribute value I'm learning web development and I try to use jquery for a chat system. When i click to the submit button the content of input will be sent to a log file and I want clear that imput field. My jquery script works in writing the text on the file but doesn't reset the attribute value of the input. I'm getting crazy and I really don't have any idea what to do
Here is the html code
<form name="message" action="#" class="message" method="post">
            <input name="usermsg" type="text" id="usermsg" size="43%" value="">
            <input name="submitmsg" type="button"  id="submitmsg" value="Send">
</form>

Here the js
<script type = "text/javascript" src ="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">

        $("#submitmsg").click(function(){
            var clientmsg = $("#usermsg").val();
            $.post("update_log.php", {text : clientmsg});
            $("#usermsg").attr("value", "");
            return false;
        });

</script>

A: This can help:
$("#usermsg").val('');


text:
Q: Constructor for class must explicitly initialize the base class I've got:
//all classes are in different files
namespace Tree {
    class Node {
        NodeType type;
    protected:
        std::string nodename;
        Node(Node::NodeType _type) : type(_type) {}
    };
}

class Parent : public virtual Tree::Node {
protected:
    Parent() : Node(Node::UNDEFINED) {}
};

class Child: public virtual Tree::Node {
protected:
    Child() : Node(Node::UNDEFINED) {}
};

namespace Tree {
    class Element :
             public Parent,
             public Child,
             public virtual Node {

    protected:
        Element() : Node(Node::ELEMENT) {}
    };
}

class SpecificElement: public Tree::Element {
public:
    SpecificElement(const std::string name) {
        nodename = name;
    }
};

In the constructor of SpecificElement appears the error:

Constructor for 'SpecificElement' must explicitly initialize the base
  class 'Tree::Node' which does not have a default contructor

Isn't Node supposed to be initialized through Element?, why the compiler ask me for explicitly initialize there?
I don't know if this has anything to do with the builders being protected. Or if it is for the namespaces, although, I don't think so, since the code compiled, until I introduced the class SpecificElement.
I would call the constructor of Node in SpecificElement, but I have many more classes that inherit from this, and in all asks me to initialize explicitly Node, and I can not do that by design.
EDIT:
thanks to @r-sahu, I solved it as follow
namespace Tree {
    class Node {
    protected:
        std::string nodename;
        NodeType type; //changed to protected

        Node(Node::NodeType _type) : type(_type) {}
        Node() : Node(UNDEFINED) {} //default constructor
    };
}

namespace Tree {
    class Element :
             public Parent,
             public Child,
             public virtual Node {

    protected:
        Element() { //change the init constructor list
            type = Node::ELEMENT; //change type inside constructor
        }
    };
}

A:
Isn't Node supposed to be initialized through Element?, why the compiler ask me for explicitly initialize there?

No.
That happens only when you create an instance of Element, not a sub-class of Element. This has to do with virtual inheritance.
Classes that are virtually inherited must be initialized correctly in the constructor of the most derived class. Hence, you must use:
SpecificElement(const std::string name) : Tree::Node(Node::ELEMENT) {
    nodename = name;
}

With that in place, when you construct an instance of SpecificElement, the Tree::Node sub-object is initialized only once, from the constructo of SpecificElement. The Tree::Node(Node::Element) part in the constructor of Element is ignored at runtime.
The justification for this behavior can be found in the standard in Section 12.6.2 Initializing bases and members/10.1


text:
Q: printing table in format without using a library, SQLite 3 python I want to print data from my database in a better format, this is for a game  I made. This is the code:
def read_all_tables(self):
        self.cursor.execute('SELECT Name, Gender, Age, Score, Date, Time FROM Link JOIN Scores ON  Score_ID = Scores.ID JOIN Player ON Player_ID = Player.id ORDER BY Score DESC')
        Data = self.cursor.fetchall()
        for Row in Data:
            print()
            for record in range(len(Row)):
               print(Row[record], end=" ")

The output is:
HAMMAD MALE 18 900 07/01/18 13:07:02
HAMMAD MALE 18 850 07/01/18 13:30:11
INDERVEER MALE 18 750 07/01/18 13:35:46
HAMMAD MALE 18 500 07/01/18 13:08:29
HAMMAD MALE 18 400 07/01/18 14:07:29
PARSA MALE 18 300 07/01/18 13:36:58
HADIA FEMALE 19 300 07/01/18 14:09:37
MANAAL FEMALE 18 100 07/01/18 13:51:40
MICHAL MALE 18 0 07/01/18 13:42:41
HAMMAD MALE 18 0 07/01/18 13:44:04
HADIA FEMALE 19 0 07/01/18 13:45:51
MANAAL FEMALE 18 0 07/01/18 13:53:02
JACK WEIRD 21 0 07/01/18 13:53:49
HAMMAD MALE 18 0 07/01/18 13:54:44
HAMMAD MALE 18 0 07/01/18 13:56:08
MANAAL FEMALE 18 0 07/01/18 13:57:39
PARSA MALE 18 0 07/01/18 13:58:25
HAMMAD MALE 18 0 07/01/18 13:59:08
HAMMAD MALE 18 0 07/01/18 14:10:37

How can I align them and have a column heading? I would like not to use any library.

A: Use the string formatting capability:
formatted_row = '{:<10} {:<6} {:>6} {:>6} {:<9} {:<9}'
print(formatted_row.format("Name", "Gender", "Age", "Score", "Date", "Time"))
for Row in Data:
    print(formatted_row.format(*Row))

Output:
Name       Gender    Age  Score Date      Time
HAMMAD     MALE       18    900 07/01/18  13:07:02
HAMMAD     MALE       18    850 07/01/18  13:30:11
INDERVEER  MALE       18    750 07/01/18  13:35:46
HAMMAD     MALE       18    500 07/01/18  13:08:29
HAMMAD     MALE       18    400 07/01/18  14:07:29
PARSA      MALE       18    300 07/01/18  13:36:58
HADIA      FEMALE     19    300 07/01/18  14:09:37
MANAAL     FEMALE     18    100 07/01/18  13:51:40
...

Note
In this approach, we hard-code the width of the columns. In order to dynamically adjust the columns width, we will have to do a good deal more works. I hope this will work for you.
Update
In order to dynamically adjust the widths, we need to pass through the data twice: The first time to determine the maximum width for each column, and the second to print.
# Determine the longest width for each column
header = ("Name", "Gender", "Age", "Score", "Date", "Time")
widths = [len(cell) for cell in header]
for row in Data:
    for i, cell in enumerate(row):
        widths[i] = max(len(str(cell)), widths[i])

# Construct formatted row like before
formatted_row = ' '.join('{:%d}' % width for width in widths)

print('DEBUG: widths={!r}'.format(widths))
print('DEBUG: formatted_row={!r}'.format(formatted_row))

print(formatted_row.format(*header))
for row in Data:
    print(formatted_row.format(*row))

Output:
DEBUG: widths=[9, 6, 3, 5, 8, 8]
DEBUG: formatted_row='{:9} {:6} {:3} {:5} {:8} {:8}'
Name      Gender Age Score Date     Time
HAMMAD    MALE    18   900 07/01/18 13:07:02
HAMMAD    MALE    18   850 07/01/18 13:30:11
INDERVEER MALE    18   750 07/01/18 13:35:46
...

Once you are happy with the result, you can delete the DEBUG lines. They are there to show how the code works.

A: For the heading, just select the text you want, like
select 'Name    Gender    Age  ...';

To format the data, use the printf() function (see https://sqlite.org/lang_corefunc.html#printf), like
select printf('%-20s %-6s  %2d ....', Name, Gender, Age, ...) from ...;

(Adjust as necessary.)


text:
Q: How can I navigation to other screens in Jetpack Compose? My code is below.
RootNavGraph.kt
@Composable
fun RootNavGraph(navController: NavHostController = rememberNavController()) {
    NavHost(
        navController = navController,
        route = rootRoute,
        startDestination = authGraphRoutePattern
    ) {
        authGraph(
            navigateToHome = {
                navController.popBackStack()
                navController.navigateToAppBarGraph()
            }
            authOtherScreen { navController.popBackStack() }
        }
        appBarGraph()
        supplementSearchScreen()
    }
}

SupplementSearch.kt
const val supplementSearchRoute = "supplement_search_route"

fun NavController.navigateToSupplementSearch(navOptions: NavOptions? = null) {
    this.navigate(supplementSearchRoute, navOptions)
}

fun NavGraphBuilder.supplementSearchScreen() {
    composable(route = supplementSearchRoute) {
        SupplementSearchRoute()
    }
}

authGraph() is for different login.
appBarGraph() is for bottom navigation menus.
As far as I read this Navigation document, I can place screens in NavHost like this
SomeAScreen()
AGraph()
BGraph()
SomeBScreen()
SomeCScreen()
SomeDScreen()
CGraph()

But I get NPE when I call like this:
@Composable
fun AddSupplementItem(
    addSupplement: Vitamin.AddSupplement
) {
    val isClicked = remember { mutableStateOf(false) }

    Column(
        modifier = Modifier
            .width(97.dp)
            .clickable {
                isClicked.value = !isClicked.value
            },
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        AsyncImage(
            model = addSupplement.imageUrl,
            modifier = Modifier
                .fillMaxWidth()
                .padding(5.dp)
                .aspectRatio(1.46f)
                .clip(RoundedCornerShape(16.dp)),
            contentDescription = addSupplement.name,
            contentScale = ContentScale.Crop
        )
        Text(
            text = addSupplement.name,
            fontSize = 13.sp,
            color = Color.Gray
        )
    }

    if (isClicked.value) {
        val navController = rememberNavController()
        navController.navigateToSupplementSearch() // NullPointException
    }
}

It seems like SupplementSearchScreen is not registered to the graph.
Should I keep passing navcontroller from NavHost to that Screen?
NavHost(...){
    // otherGraphs()
    supplementSearchScreen(navController)
}

But it didn't work.
And also,
// the parent composable function is
fun SupplementGrid(vitaminList: List<Vitamin>) {
     // list of vitamin item. and also use AddSupplement()
}
// And also it has parent composable function
@Composable
fun SupplementLayout(feedType: FeedType, supplements: List<Vitamin>) {
    // call SupplementGrid()
}

// and finally,
@Composable
fun NutritionScreen(
    // it uses LazyColumn and one of item is SupplementLayout()
)

How can I solve this issue??


text:
Q: E-mail Communication How to get total email conversation with single common identifier in all email messages using java. javaMail API and JMS is giving sender and receiver message id which is different. I need the common identifer which will specify the communication thread.

A: There is no such thing.  If you're trying to correlate messages into a "thread" or "conversation", see this.


text:
Q: How to get the selected checkbox corresponding value I have a dynamic form with corresponding check box with each row.
<?php
  $q2 = mysql_query("SELECT * from plan ORDER BY id ASC");
  while($result=mysql_fetch_array($q2))
   {
?>

 <?php echo $result['plan_name'];?>
 <? echo '$';echo $result['price'];?>
 <input type="hidden" name="id[]" id="id" value="  <?php echo $result['id'];?>">
 <input type="checkbox" name="check_list[]" value="<? echo $result['price'];?>">

<?php  } ?>

Plan    Price   Choose
PHP       $3     []
.Net      $2     []
C#        $6     []
Java      $2     []
C++       $10    []
ROR       $2     []

User can select the multiple options. At last will show the total of the selected plans. For total I redirected that page to total.php page. There I did the total of
the selected plans. On total.php Page I want to get the corresponding Id value or the Plan Name of the selected plans. I just get the id the Last Column but not for
the selected columns. Then after that from total.php page user will fill his/her the details and submit the details along with the selected plans and price. How can I retrieve the id of the selected checkbox Value to show the plans.

A: You approach is wrong:
<input type="checkbox" name="check_list[]" value="<? echo $result['price'];?>">

As only checked checkboxes get sent to the server, you will not be able to identify the checked box by its ID; if only the third is checked, its key in the array will be 0. And as you are using the monetary value as its value, you will not be able to identify the checked box by the value as the values of different boxes can be the same.
In short: You will not be able to identify the checked boxes when the form is sent in.
To correct that you need to make or the name (key on the server) or the value unique so that you can link it to your database.
An easy way to do that for the ID, would be to set the ID in the loop:
<input type="checkbox" name="check_list[<?php echo $result['id'];?>]" value="<? echo $result['price'];?>">
                                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^ set the key manually

Now you can loop over $_POST['check_list'] and the key in that foreach loop will contain the ID of the item in the database:
foreach ($_POST['check_list'] as $key => $value) {
  //                             ^^^^ the key
  ...

You could of course use the value in the same way.


text:
Q: How Do I find the user for an extended event? For a "simple" Request On a MSSQL Server I get a Column filled with Xmls:
SELECT CONVERT(XML, event_data) As event_data_xml
    FROM sys.fn_xe_file_target_read_file('Test*.xel', NULL, NULL, NULL)

The result:

one of these in details:
<event name="login" package="sqlserver" timestamp="2020-07-17T10:09:20.922Z">
  <data name="is_cached">
    <value>true</value>
  </data>
  <data name="is_recovered">
    <value>false</value>
  </data>
  <data name="is_dac">
    <value>false</value>
  </data>
  <data name="database_id">
    <value>1</value>
  </data>
  <data name="packet_size">
    <value>4096</value>
  </data>
  <data name="options">
    <value>2000002838f4010000000000</value>
  </data>
  <data name="options_text">
    <value />
  </data>
  <data name="database_name">
    <value />
  </data>
  <action name="attach_activity_id" package="package0">
    <value>093CAB81-B0B7-46CF-A807-F32D0469235A-2</value>
  </action>
</event>

In these details I do not get any hint, which user invoked this event. So:
How Do If find out by SQL Code which user invoked this event?
Thanks for help!

A: When setting up your extended event you should expand the event (by clicking on it) and in the Global fields tab check nt_username and/or username and any of the other fields that might be interesting. (I.e.: client_hostname, client_app_name)

you should do this for all selected events in your case based on your screenshot, login and logout.
In T-SQL:
-- Drop the existing Login event
ALTER EVENT SESSION [Test_Event] ON SERVER
DROP EVENT sqlserver.login

-- Drop the existing logout event
ALTER EVENT SESSION [Test_Event] ON SERVER
DROP EVENT sqlserver.logout

-- Add a new login event with properties : nt_username and username
ALTER EVENT SESSION [Test_Event] ON SERVER
ADD EVENT sqlserver.login(
    ACTION(sqlserver.nt_username,sqlserver.username))

-- Add a new logout event with properties : nt_username and username
ALTER EVENT SESSION [Test_Event] ON SERVER
ADD EVENT sqlserver.logout(
    ACTION(sqlserver.nt_username,sqlserver.username))

New events will then contain the selected fields:
<event name="login" package="sqlserver" timestamp="2020-07-27T05:59:26.931Z">
  <data name="is_cached">
    <value>true</value>
  </data>
  <data name="is_recovered">
    <value>false</value>
  </data>
  <data name="is_dac">
    <value>false</value>
  </data>
  <data name="database_id">
    <value>1</value>
  </data>
  <data name="packet_size">
    <value>8000</value>
  </data>
  <data name="options">
    <value>2000002838f4010000000000</value>
  </data>
  <data name="options_text">
    <value />
  </data>
  <data name="database_name">
    <value />
  </data>
  <!--Newly selected global fields-->
  <action name="username" package="sqlserver">
    <value>Domain\Username</value>
  </action>
  <action name="nt_username" package="sqlserver">
    <value>Domain\Username</value>
  </action>
</event>


text:
Q: Issue with controller validators generated with OpenApi Generator So I have used OpenApi Generator to generate java classes (controller interfaces and response class). But because I set flag user-optional to true, every parameter which is not required in request is wrapped as Optional, but if I add constrains to min and max value my parameters looks like following: @Min(1) @Max(10) Optional<Long> value, and obviously my java app is not happy because there is no such validator which will validate Optional.
My snippet of generator file looks like that:
/test:
  get:
    tags:
      - test
    summary: Make it work already
    parameters:
      - name: id
        in: query
        required: true
        schema:
          type: string
      - name: range
        in: query
        required: false
        schema:
          type: integer
          format: int64
          minimum: 1
          maximum: 10
          .
          .
          . etc

And second parameter looks like that @Min(1) @Max(10) @RequestParam(value="range", required = false) Optional<Long> value
Is there way to tell OpenApi to put validators inside of Optional?


text:
Q: How to call Rails console on server, if it uses Mina? Before implementation Mina on server, I called it with:
rails console

now I get:
-bash: rails: command not found

How can I call it now?

A: Try this out
mina console

Visit
typing 'rails console' doesn't start?
or
visit https://github.com/mina-deploy/mina/issues/279
for issue in MINA

A: I'd the same problem and got:
bash: bundle: command not found
-----> Loading rbenv

rbenv is loading after the command was executed.
So, I've created new task to ruan rails console and load rbenv before it.
task :environment do
  invoke :'rbenv:load'
end

task rc: :environment do
  invoke :'console'
end

mina rc to launch rails console


text:
Q: Integration testing in grails using netbeans I am using netbeans as the ide to develop grails web applications and am facing problems in integration testing.i created an integration test for a domain class ProgressData as ProgressDataIntegration in netbeans and it generated a code full of errors
package main
import static org.junit.Assert.*
import org.junit.*

class ProgressDataIntegrationTests{

@Before
void setUp() {
    // Setup logic here
}

@After
void tearDown() {
    // Tear down logic here
}

@Test
void testSomething() {
    fail "Implement me"
}
}

need help on how to remove these errors

A: Whenever you create a grails domain class an integration test will also be created for you containing the code you posted.  By default the test fails, as a prompt to write some tests for your new domain class, i.e. The line:
fail "Implement me"

If you remove this line your test will pass, but it also fails to actually test anything.


text:
Q: Pandas dataframe change values in a column based on conditions I have a large Dataframe below:
The data used as the example here 'education_val.csv' can be found here https://github.com/ENLK/Py-Projects-/blob/master/education_val.csv
import pandas as pd

edu = pd.read_csv('education_val.csv')
del edu['Unnamed: 0']
edu.head(10)

ID  Year    Education
22445   1991    higher education
29925   1991    No qualifications
76165   1991    No qualifications
223725  1991    Other
280165  1991    intermediate qualifications
333205  1991    No qualifications
387605  1991    higher education
541285  1991    No qualifications
541965  1991    No qualifications
599765  1991    No qualifications

The values in the column Education are:
edu.Education.value_counts()

intermediate qualifications 153705
higher education    67020
No qualifications   55842
Other   36915

I want to replace the values in the column Education in the following ways:

*

*If an ID has the value higher education in a year in the column Education then all future years for that ID will also have higher education in the Education column.

*If an ID has the value intermediate qualifications in a year, then all future years for that ID will have intermediate qualifications in the corresponding Education column. However, if the value higher education occurs in any of the subsequent years for this ID, then higher education replaces intermediate qualifications in the subsequent years, regardless if Other or No qualifications occur.
For example in the DataFrame below, ID 22445 has  the valuehigher education in the year 1991, all subsequent values of Education for 22445 should be replaced with higher education in the later years, up to the year 2017.
edu.loc[edu['ID'] == 22445]

ID  Year    Education
22445   1991    higher education
22445   1992    higher education
22445   1993    higher education
22445   1994    higher education
22445   1995    higher education
22445   1996    intermediate qualifications
22445   1997    intermediate qualifications
22445   1998    Other
22445   1999    No qualifications
22445   2000    intermediate qualifications
22445   2001    intermediate qualifications
22445   2002    intermediate qualifications
22445   2003    intermediate qualifications
22445   2004    intermediate qualifications
22445   2005    intermediate qualifications
22445   2006    intermediate qualifications
22445   2007    intermediate qualifications
22445   2008    intermediate qualifications
22445   2010    intermediate qualifications
22445   2011    intermediate qualifications
22445   2012    intermediate qualifications
22445   2013    intermediate qualifications
22445   2014    intermediate qualifications
22445   2015    intermediate qualifications
22445   2016    intermediate qualifications
22445   2017    intermediate qualifications

Similarly, ID 1587125 in the Dataframe below has the value intermediate qualifications in the year 1991, and changes to higher education in 1993. All subsequent values in the column Education in the future years (from 1993 onwards) for 1587125 should be higher education.
edu.loc[edu['ID'] == 1587125]

ID  Year    Education
1587125 1991    intermediate qualifications
1587125 1992    intermediate qualifications
1587125 1993    higher education
1587125 1994    higher education
1587125 1995    higher education
1587125 1996    higher education
1587125 1997    higher education
1587125 1998    higher education
1587125 1999    higher education
1587125 2000    higher education
1587125 2001    higher education
1587125 2002    higher education
1587125 2003    higher education
1587125 2004    Other
1587125 2005    No qualifications
1587125 2006    intermediate qualifications
1587125 2007    intermediate qualifications
1587125 2008    intermediate qualifications
1587125 2010    intermediate qualifications
1587125 2011    higher education
1587125 2012    higher education
1587125 2013    higher education
1587125 2014    higher education
1587125 2015    higher education
1587125 2016    higher education
1587125 2017    higher education

There are 12,057 unique ID in the data and the column Year spans from 1991 to 2017. How does one change the values of Education for all 12, 057 according to the above conditions? I'm not sure how to do this in a uniform way for all unique IDs. The sample data used as the example here is attached in the Github link above. Many thanks in advance.

A: You can do it using the categorical data like this:
df = pd.read_csv('https://raw.githubusercontent.com/ENLK/Py-Projects-/master/education_val.csv')

eddtype = pd.CategoricalDtype(['No qualifications',
                               'Other',
                               'intermediate qualifications',
                               'higher education'],
                               ordered=True)
df['EducationCat'] = df['Education'].str.strip().astype(eddtype)

df['EduMax'] = df.sort_values('Year').groupby('ID')['EducationCat']\
                 .transform(lambda x: eddtype.categories[x.cat.codes.cummax()] )

It is broken it up explicitly so you can see the data manipulations I am using.

*

*Create a Education categorical dtype with order

*Next, change dtype of Education column to use that categorical
dtype (EducationCat)

*Use the codes of the categorical to preform cummax calculation

*With indexing to return the category defined by the cummax calculation (EduMax)

Outputs:
df[df['ID'] == 1587125]

            ID  Year                    Education                 EducationCat                       EduMax
18      1587125  1991  intermediate qualifications  intermediate qualifications  intermediate qualifications
12075   1587125  1992  intermediate qualifications  intermediate qualifications  intermediate qualifications
24132   1587125  1993             higher education             higher education             higher education
36189   1587125  1994             higher education             higher education             higher education
48246   1587125  1995             higher education             higher education             higher education
60303   1587125  1996             higher education             higher education             higher education
72360   1587125  1997             higher education             higher education             higher education
84417   1587125  1998             higher education             higher education             higher education
96474   1587125  1999             higher education             higher education             higher education
108531  1587125  2000             higher education             higher education             higher education
120588  1587125  2001             higher education             higher education             higher education
132645  1587125  2002             higher education             higher education             higher education
144702  1587125  2003             higher education             higher education             higher education
156759  1587125  2004                        Other                        Other             higher education
168816  1587125  2005            No qualifications            No qualifications             higher education
180873  1587125  2006  intermediate qualifications  intermediate qualifications             higher education
192930  1587125  2007  intermediate qualifications  intermediate qualifications             higher education
204987  1587125  2008  intermediate qualifications  intermediate qualifications             higher education
217044  1587125  2010  intermediate qualifications  intermediate qualifications             higher education
229101  1587125  2011             higher education             higher education             higher education
241158  1587125  2012             higher education             higher education             higher education
253215  1587125  2013             higher education             higher education             higher education
265272  1587125  2014             higher education             higher education             higher education
277329  1587125  2015             higher education             higher education             higher education
289386  1587125  2016             higher education             higher education             higher education
301443  1587125  2017             higher education             higher education             higher education

A: There clearly is an order in the level of education. Your problem can be restated as a "rolling max" problem: what is the highest level of education a person has as of a certain year?
Try this:
# A dictionary mapping each label to a rank
mappings = {e: i for i, e in enumerate(['No qualifications', 'Other', 'intermediate qualifications', 'higher education'])}

# Convert the label to its rank
edu['Education'] = edu['Education'].map(mappings)

# The gist of the solution: an expanding max level of education per person
tmp = edu.sort_values('Year').groupby('ID')['Education'].expanding().max()

# The first index level in tmp is the ID, the second level is the original index
# We only need the original index, hence the droplevel
# We also convert the rank back to the label (swapping keys and values in the mappings dictionary)
tmp = tmp.droplevel(0).map({v: k for k, v in mappings.items()})

edu['Education'] = tmp

Test:
edu[edu['ID'] == 1587125]

    ID  Year                    Education
1587125  1991  intermediate qualifications
1587125  1992  intermediate qualifications
1587125  1993             higher education
1587125  1994             higher education
1587125  1995             higher education
1587125  1996             higher education
1587125  1997             higher education
1587125  1998             higher education
1587125  1999             higher education
1587125  2000             higher education
1587125  2001             higher education
1587125  2002             higher education
1587125  2003             higher education
1587125  2004             higher education
1587125  2005             higher education
1587125  2006             higher education
1587125  2007             higher education
1587125  2008             higher education
1587125  2010             higher education
1587125  2011             higher education
1587125  2012             higher education
1587125  2013             higher education
1587125  2014             higher education
1587125  2015             higher education
1587125  2016             higher education
1587125  2017             higher education

A: You could iterate through the IDs, then through the years. The DataFrame is ordered chronologically, so if a person has 'higher education' or 'intermediate qualifications' in a cell, you can save this knowledge and apply it to subsequent cells:
edu = edu.set_index('ID')
ids = edu.index.unique()

for id in ids:
    # booleans to keep track of education statuses we've seen
    higher_ed = False
    inter_qual = False

    rows = edu.loc[id]
    for _, row in rows:
        # check for intermediate qualifications
        if inter_qual:
            row['Education'] = 'intermediate qualifications'
        elif row['Education'] = 'intermediate qualifications':
            inter_qual = True

        # check for higher education
        if higher_ed:
            row['Education'] = 'higher education'
        elif row['Education'] = 'higher education':
            higher_ed = True

It doesn't matter that we're potentially overwriting each status more than once — if a person has both 'intermediate qualifications' and 'higher education', we only need to be sure that 'higher education' is set last.
I would normally not suggest using a for loop to process a DataFrame — but each cell value might rely on values above it, and the Dataframe isn't so large as to make this infeasible.


text:
Q: How to convert a string to small capitals in PHP? I am trying to convert a strint composed of "standard" upper and lower case letters to small capitals, in PHP. There is no information about small caps in the php.net docs.
Small capitals are, in my understanding, this thing :

Hᴇʟʟᴏ ᴛʜᴇʀᴇ

(generated with this site : https://fsymbols.com/generators/smallcaps/)
For instance, here is the small cap version of a t : http://www.fileformat.info/info/unicode/char/1d1b/index.htm
I searched the web for a longtime and found nothin in PHP. I know that CSS let you do that by using
font-variant: small-caps;

But I need to do this on the server side for what I do. Is this possible in PHP ?
EDIT: To complete my question, I am trying to generate plain text. So no HTML, images or CSS is possible in my case.
EDIT 2: On the website linked, a Javascript function is used to convert the text
Here is the code :
function encool() {
    var _0xce74x20 = location[_0x804c[82]],
        _0xce74x21;
    if (_0xce74x20[_0x804c[84]](_0x804c[83]) == -1 && _0xce74x20[_0x804c[84]](_0x804c[85]) == -1 && _0xce74x20[_0x804c[84]](_0x804c[86]) == -1 && _0xce74x20[_0x804c[84]](_0x804c[87]) == -1 && _0xce74x20[_0x804c[84]](_0x804c[88]) == -1) {
        _0xce74x21 = document[_0x804c[91]][_0x804c[90]][_0x804c[89]]
    } else {
        _0xce74x21 = change(decomposeAString(document[_0x804c[91]][_0x804c[90]][_0x804c[89]]))
    };
    document[_0x804c[91]][_0x804c[92]][_0x804c[89]] = _0xce74x21
}

Pretty sure he is using a character mapping. I will look into that and post the solution if I find it.

A: So you want to convert a text containing lower and upper letters into small capitals using UNICODE.
For that you need a mapping table, that maps each character to its small capitals pendant in UNICODE. Use mb_convert_encoding() for the conversion in PHP.
See this example from the PHP documentation on how to use a custom mapping table.

A: Map each character and then loop over your string.
<?php
//Initialize the map
$map = array(
    "A"=>"ᴀ",
    "B"=>"ʙ",
    "C"=>"ᴄ",
    "D"=>"ᴅ"
    //etc
    );

function convertToSmall($string,$map){
    //Our string to return
    $return = "";
    //You can replace length + the for loop for an explode + foreach
    $length = strlen($string);
    for($i = 0; $i<$length; $i++){
        //set our input character
        $input = strtoupper($string[$i]);
        //check if its in the map
        if(isset($map[$input])){
            $input = $map[$input];
        }
        //write to our output
        $return .= $input;

    }

    return $return;

}

print_r(convertToSmall("aa bc da",$map));

Output of this:
ᴀᴀ ʙᴄ ᴅᴀ
3v4l link

A: Ok here is the solution I came up with, but it is not very complete because even if it fits my needs. I needed this to convert small text (category names) so it is ok for me.
function convertToSmallCaps($string) {
    // standar capitals
    $caps = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
    // small capitals
    $smallCaps = array('ᴀ', 'ʙ', 'ᴄ', 'ᴅ', 'ᴇ', 'ꜰ', 'ɢ', 'ʜ', 'ɪ', 'ᴊ', 'ᴋ', 'ʟ', 'ᴍ', 'ɴ', 'ᴏ', 'ᴘ', 'ǫ', 'ʀ', 's', 'ᴛ', 'ᴜ', 'ᴠ', 'ᴡ', 'x', 'ʏ', 'ᴢ');

    // remove all chars except [a-z] and - (replacing dashes with spaces)
    $sanitized_string = str_replace('-',' ',sanitize_title($string));

    // convert to uppercase
    $sanitized_string = mb_strtoupper($string);

    $length = strlen($sanitized_string);
    $output_string='';
    for($i = 0; $i<$length; $i++){
        $char = $sanitized_string[$i];
        // If the letter exsist in small capitals
        $letter_position = array_search($char,$caps);
        if(is_numeric($letter_position) && isset($smallCaps[$letter_position])) {
            // We append it to the ouput string
            $output_string.=$smallCaps[$letter_position];

        } else {
            // or else we append the original char to the output string
            $output_string.=$char;
        }
    }
    // return the converted string
    return $output_string;
}

It basically maps all chars in the string from caps to small caps
Problems :

*

*it is wordpress dependent. I used the sanitize_title function from wordpress, which "slugifies" the string (removing all chars except [a-z] and -)

*If your text has a lot of diacritics or is a composed of numbers and non latin chars, or longer than a category name, the result may be a bit weird

*some of the letters (the x or s or q) are not actual small caps (because they don't exist, I guess ?) so the result can be confusing on some display.

I will try to improve this in the future if my need change


text:
Q: One of the computers on my home network does not get a local IP My ethernet-connected ubuntu box and my wirelessly connected lap both have 192.168... addresses. I just plugged a second ubuntu box into the router, but it gets an 84.210... address. I can ssh to it from the others, but not to any of them from it. What's going on?

A: It seems like your second Ubuntu box has received an external IP address for some (uncertain to me) reasons. And in this case it's not surprising that ssh to your other PCs doesn't work - without port forwarding set up on the router it can't reach the machines which are in the local subnet.
Unfortunately, some important details are missing, especially this: did it work previously in the same configuration?

*

*If no, try to plug your "second box" into another port on your router and then reboot the box.

*If yes: first try to reboot the router and the "second box"; if this doesn't help, try to remember any changes that were made since the last time it worked.

Hope this helps.


text:
Q: checkbox doesnot change value accoding to data , all dates showing same value for checkbox react js when i change the date using input date filed the checkbox value has to change respect to the date but here every date is showing the same value for check box
i have given the entire working code i have tryed in the codesandbox

  <input type="date" onChange={this.dateHandler} />

 {this.state.items.map((personData) => {
                return (
                  <>
                    {" "}

{personData.mainModule}

                            {personData.sub_module.map((subModule, key) => {
                              return (

                                    {" "}
                                    {subModule.subModuleName}

                                  <input
                                    type="checkbox"
                                    data-id={subModule.id}
                                    onChange={(e) =>
                                      this.handleCheckClick(e, "items", key)
                                    }
                                    defaultChecked={
                                      subModule.completed && subModule
                                    }

                                  />

                              );
                            })}

                  </>
                );
              })}

entire working code
https://codesandbox.io/s/snowy-firefly-rs78v?file=/src/App.js

A: Thank you for sharing such a complete reproduction!
I'm not sure how the logic should work here in detail--I assume that when clicking the checkbox, the post request saves data to the server, which then gets re-requested later. When it's re-requested, it should have the correct value in the completed field for sub_modules.
I can spot one issue relating to this behaviour:
prevState[index].completed = e.target.checked;

The prevState is an array of personData. Hence with prevState[index] you are finding a personData item. If I understood correctly, you want to find a sub_module.
This could be done like so
prevState[<personDataIndex>].sub_module[<subModuleIndex>].completed

In your render function you are looping in this fashion
this.state.items.map((personData) => (
   // ...
   {personData.sub_modules.map((subModule, key) => (
       // ...
       <input onChange={(e) => this.handle(e, "items", key)} />
       // ...
   ))}
))

Attempt to provide index values for both of the arrays you are looping
this.state.items.map((personData, i) => (
   personData.sub_modules.map((subModule, j) => (
       <input onChange={(e) => this.handleCheckClick(e, "items", i, j)} />
   ))
))

And then in the handleCheckClick handler set completed like so
prevState[i].sub_module[j].completed = e.target.checked

Also consider using checked instead of defaultChecked because the input is controlled
<input type="checkbox" checked={subModule.checked} />

Another issue with your example was that you were not passing the date when you requested the data, but someone else or you yourself already fixed this issue.


text:
Q: Fetching data from multiple api in django rest framwork First I don't know I'm asking a good question or not. I'm trying to integrate Paytm Payment in my django rest framework. There are many api from paytm like Initiate transaction , fetch all payment, send OTP etc, like in the image below

Im able to initiate transaction but not all payments are available, Inorder to do that I have to call the Fetch Payment Options API. But I don't know how to do that because I'm already calling Initiate transaction API in the view with parameters but I don't know how to call other api with different parameters in the same view. Like when I initiate transaction, the API gets fired and frontend shows the paytm page. So these api should be called on frontend?. I actually don't know how to ask this question properly. I need help


text:
Q: Implicit using subject in rspec example doesn't work I'm going to test the model concern get_uniq_id method.
app/models/concerns/id_generation.rb
module IdGeneration
  extend ActiveSupport::Concern

  module ClassMethods
    def get_uniq_id
      id = ''
      loop {
        id = generate_id
        break unless Ticket.find_by_token(id)
      }
      id
    end

    def generate_id
      id = []
      "%s-%d-%s-%d-%s".split('-').each{|v| id << (v.eql?('%s') ? generate_characters : generate_digits)}
      id.join('-')
    end

    def generate_digits(quantity = 3)
      (0..9).to_a.shuffle[0, quantity].join
    end

    def generate_characters(quantity = 3)
      ('A'..'Z').to_a.shuffle[0, quantity].join
    end
  end
end

spec/concerns/id_generation_spec.rb
require 'spec_helper'
describe IdGeneration do
  class Dummy
    include IdGeneration::ClassMethods
  end
  subject { Dummy.new }
  it { should get_uniq_id.match(/[A-Z]{2}-[0-9]{2}-[A-Z]{2}-[0-9]{2}-[A-Z]{2}/) }
end

It throws up the error:
 Failure/Error: it { should get_uniq_id.match(/[A-Z]{2}-[0-9]{2}-[A-Z]{2}-[0-9]{2}-[A-Z]{2}/) }
 NameError:
   undefined local variable or method `get_uniq_id' for #<RSpec::ExampleGroups::IdGeneration:0x00000001808c38>

If I specify the subject explicitly it { should subject.get_uniq_id.match(/[A-Z]{2}-[0-9]{2}-[A-Z]{2}-[0-9]{2}-[A-Z]{2}/) }. It works.
Do I need specify the subject explicitly?

A: The way you're calling the method - yes. The method needs to be called on object. In this case, the get_uniq_id will be executed in context of currently running test, and this is why the error pops up.
The shortcut you can use might be like:
it { should respond_to :get_uniq_id }

Which will perform test similar to subject.respond_to?(:get_uniq_id). The method call however, needs explicit receiver.
You can update your test in order to use it as in your example, if you modify it slightly:
require 'spec_helper'
describe IdGeneration do
  class Dummy
    include IdGeneration::ClassMethods
  end
  subject { Dummy.new }

  def get_uniq_id
    subject.get_uniq_id
  end

  it { should get_uniq_id.match(/[A-Z]{2}-[0-9]{2}-[A-Z]{2}-[0-9]{2}-[A-Z]{2}/) }
end

Or, to bind the output to subject:
require 'spec_helper'
describe IdGeneration do
  class Dummy
    include IdGeneration::ClassMethods
  end

  let(:dummy) { Dummy.new }
  subject     { dummy }

  describe "#get_uniq_id" do
    subject { dummy.get_uniq_id }

    it { should match(/[A-Z]{2}-[0-9]{2}-[A-Z]{2}-[0-9]{2}-[A-Z]{2}/) }
  end
end


text:
Q: Powershell parameter : string in path I want to launch a .ps1 from Windows Command Prompt. My Powershell script has a path parameter. Here's my command line to launch the .ps1
powershell Set-ExecutionPolicy Unrestricted -scope process ; C:\\MyPowerShell.ps1 -Path \"C:\\Test for my script\test1.txt"
In MyPowerShell.ps1, if I Write-Host Path, I get : C:\Test. It cuts my string when the first space appears.
How can I get my full path ?
Thx.

A: Option 2:
Don't escape the path, and instead remove the quotes from what is passed in.
    $path2file = $path2file.replace('"',"").replace("'","")

This will allow anyone to put quotes around the path (an accepted practice norm) and your application strips the quotes and has the whole path in one variable.  If the path is not quoted, then this lines has no effect.
Where it will fail is if a quote (single or double) is included in the actual file path.

A: I've put ' : -Path '\"C:\\Test for my script\test1.txt"' and it works.
Thx :)


text:
Q: Creating Media Service Credentials I'm trying to set up the Azure Media Service. I created the media service from Azure but I don't know where can obtain the account key.

client = new CloudMediaContext(new MediaServicesCredentials(accountName, accountKey));

I'm following this tutorial: Integrating applications with Azure Active Directory
But after get the secret key in step 4 in "To add application credentials, or permissions to access web APIs" doesn't works.

A:
client = new CloudMediaContext(new MediaServicesCredentials(accountName, accountKey));

Azure Media Services announces support for AAD and deprecation of ACS authentication.

Because Azure Active Directory provides powerful role-based access control features and support for more fine-grained access to resources in your account compared to the ACS token authentication model ("account keys"), we strongly recommend that you update your code and migrate from ACS to AAD-based authentication by June 22, 2018.
Also, a key reason for the rapid migration is the upcoming announced deprecation of the ACS key based authentication system.

User Authentication with AAD in Media Services
A native application would first acquire an access token from Azure Active Directory and then use that access token to make all REST API calls.
The following examples show how a daemon application may use AAD web application credentials to authenticate requests with the REST service.

For a REST API request to succeed, the calling user must be a "Contributor" or "Owner" of the Azure Media Services account it is trying to access.
Users of the .NET client SDK for Media Services must upgrade to the latest version on Nuget (windowsazure.mediaservices version 4.1.0.1 or greater) to use AAD authentication for communicating with REST requests.
You could use the following code to connect to the Media Services account.
class Program
    {
        // Read values from the App.config file.
        private static readonly string _AADTenantDomain =
            ConfigurationManager.AppSettings["AMSAADTenantDomain"];
        private static readonly string _RESTAPIEndpoint =
            ConfigurationManager.AppSettings["AMSRESTAPIEndpoint"];
        private static readonly string _AMSClientId =
            ConfigurationManager.AppSettings["AMSClientId"];
        private static readonly string _AMSClientSecret =
            ConfigurationManager.AppSettings["AMSClientSecret"];

        private static CloudMediaContext _context = null;

        static void Main(string[] args)
        {
        try
        {
            AzureAdTokenCredentials tokenCredentials =
                new AzureAdTokenCredentials(_AADTenantDomain,
                    new AzureAdClientSymmetricKey(_AMSClientId, _AMSClientSecret),
                    AzureEnvironments.AzureCloudEnvironment);

            var tokenProvider = new AzureAdTokenProvider(tokenCredentials);

            _context = new CloudMediaContext(new Uri(_RESTAPIEndpoint), tokenProvider);

            // Add calls to methods defined in this section.
            // Make sure to update the file name and path to where you have your media file.
            IAsset inputAsset =
            UploadFile(@"C:\VideoFiles\BigBuckBunny.mp4", AssetCreationOptions.None);

            IAsset encodedAsset =
            EncodeToAdaptiveBitrateMP4s(inputAsset, AssetCreationOptions.None);

            PublishAssetGetURLs(encodedAsset);
        }
        catch (Exception exception)
        {
            // Parse the XML error message in the Media Services response and create a new
            // exception with its content.
            exception = MediaServicesExceptionParser.Parse(exception);

            Console.Error.WriteLine(exception.Message);
        }
        finally
        {
            Console.ReadLine();
        }
        }

NOTE: Applications will also need to update their references to include a new assembly "Microsoft.WindowsAzure.MediaServices.Client.Common.Authentication.dll" and add references to that namespace as well as reference to the "Microsoft.IdentityModel.Clients.ActiveDirectory" assembly to get access to the ITokenProvider interface.
Click API access and choose "
Connect to Azure Media Services API with user authentication".

This includes the API endpoint that you need to call, along with the ClientID, Domain, and Resource.

For more details about how to connect to Media Services with Azure AD, you could refer to this article.


text:
Q: Find and Replace *.txt file generator? web based? I want to know how or what would be the best way to achieve the following.
I work with a large eCommerce company and we have to constantly replace images with new images and then clear the cache using a pre-made template. I'll show a small example of the template it's a *.txt file template that I use for refreshing content on "Akamai edge control"
There is about 100 different lines in the text file each a little different but they all contain to sets of generic variables.
http://www.mysite.com/file/folder/blah/xxxxxx/_something_else here/zzzzzz/image250
http://www.mysite.com/file/folder/blah/xxxxxx/_something_else here/zzzzzz/image500
http://www.mysite.com/file/folder/blah/xxxxxx/_something_else here/zzzzzz/image800
http://www.mysite.com/file/folder/blah/xxxxxx/_something_else here/zzzzzz/image1000

That is just an example of what it looks like in the text file. The thing we do is open the file with Notepad and press Ctrl+h and the replace box pops up. I put in a number could be i.e. "123456" to replace the xxxxxx but I then have to go back to the number and manually change it to "123000" mind you we are only making changes to the xxxxxx and the zzzzzz. They are just place holders. So my end result would be like this...
Ps. on the zzzzzz it always ends with "000"
http://www.mysite.com/file/folder/blah/123456/_something_else here/123000/image250
http://www.mysite.com/file/folder/blah/123456/_something_else here/123000/image500
http://www.mysite.com/file/folder/blah/123456/_something_else here/123000/image800
http://www.mysite.com/file/folder/blah/123456/_something_else here/123000/image1000

My main question is... is there already some sort of program that can run this process a bit more automatically by just selecting my template file and pasting in my only "123456" and getting all the lines the change while adding the zzzzzz with the zero's also.
I'm trying to eliminate a ton of work and make the process more efficient. My example of "123456" could also be up to "1234567". Maybe even pasting in more then one number separated with commas kind of like "123456,123457,123458" then it runs sample process generating a block of text for each number like it was found and replaced manually.
Ideally I would like to just have a web based form like the image to perform the task, unless there is another way without installing software on over 1000 computers. Hope this make sense. Thanks in advance for any input.

A: Given a file with full list of UNC paths or FTP paths and credentials for each target file location/server, it would be possible to write a program to read your templates, allow you to input your numbers, and to contact each server in turn and write the new versions.
Given the nature of the beast, the lil' program would have to have logging and crash resistance and probably an interface allowing the operation to be repeated on a subset of machines.
You could also probably continue to update your files manually (PSPAD.EXE has find and replace in files), upload them to a central file server and have each of the web servers download the files irrespective of if they've changed or not - a simple batch file executed by each server's scheduler could do that, of course you'd have to configure each server.
Mark ia.uk.com

A: I am guessing from the phrasing of the question that you are not inclined to see a 'server admin' solution, such as the command line tool sed.
A server administrator would perform this task in this way.  From the folder where your template.txt file is, they would run these two commands:
sed -i 's/xxxxxx/123456/' template.txt
sed -i 's/zzzzzz/123000/' template.txt
Explanation:
 sed - stream the file through this tool and work one line at a time
 -i  - make the changes in place, so save them back to the file they came from
 s/.../... - substitute this for that
Assumptions I am making:
'Ctrl+h' means you are using a Windows machine to download the template, make the changes, and upload the new template.
'for refreshing content on' means that this template is already on a web server, and you have access to that web server.
'large eCommerce company' I am assuming this is a linux web server, and therefore the sed tool is already installed as part of any modern linux operating system.
'Ideally I would like to just have a web based form like the image to perform the task, unless there is another way without installing software on over 1000 computers.' I am assuming you do not have permission from your supervisor to hire a freelance developer to make a single web page with the one number field and a launch button, which would then run the above commands dynamically and perform your ideal solution.
Information I dont know:
Is your template file in one central location, or is it on these 1000 computers?
What is making the image changes?


text:
Q: Select all columns, but replace some with expression in Google BigQuery? Similar to Select All Columns Except Some in Google BigQuery? - we want to SELECT * from the table, but instead of excluding some columns, we want to replace them with some expression. For example, given table with columns: name, start_date, amount, end_date, comment, we want to convert start and end from STRING to DATE. It is possible to write
SELECT
  * EXCEPT(start_date, end_date),
  CAST(start_date AS DATE) start_date,
  CAST(end_date AS DATE) end_date

But this would change order of columns moving start and end to the end.

A: I would go further and say  - you can chain EXCEPT and REPLACE in same SELECT
It is not that obvious from documentation, so I thought it valuable
For example
SELECT * EXCEPT(end_date) REPLACE(
  CAST(start_date AS DATE) AS start_date)
FROM T

This will remove end_date from output end replace original start_date with casted to date start_date

A: In addition to SELECT * EXCEPT, Google BigQuery also supports SELECT * REPLACE clause in Standard SQL dialect. Documentation can be found here: https://cloud.google.com/bigquery/sql-reference/query-syntax#select-list
Your example will become:
SELECT * REPLACE(
  CAST(start_date AS DATE) AS start_date,
  CAST(end_date AS DATE) AS end_date)
FROM T


text:
Q: WCF hosting issues Hi I wonder if someone can help me, I've been banging my head against the wall trying to solve this but no luck yet :( I have a WCF hosted on IIS6 on a remote server on our internal network, http://systemservices/ServiceManagerServices.svc. I can access the service in my browser, however when trying to send a request using WcfTestClient, i get the following error:
> Error: Cannot obtain Metadata from
> http://systemservices/ServiceManagerServices.svc If this is a Windows
> (R) Communication Foundation service to which you have access, please
> check that you have enabled metadata publishing at the specified
> address.  For help enabling metadata publishing, please refer to the
> MSDN documentation at
> http://go.microsoft.com/fwlink/?LinkId=65455.WS-Metadata Exchange
> Error    URI: http://systemservices/ServiceManagerServices.svc
> Metadata contains a reference that cannot be resolved:
> 'http://systemservices/ServiceManagerServices.svc'.    There was no
> endpoint listening at http://systemservices/ServiceManagerServices.svc
> that could accept the message. This is often caused by an incorrect
> address or SOAP action. See InnerException, if present, for more
> details.    Unable to connect to the remote server    No connection
> could be made because the target machine actively refused it
> 172.16.25.221:80HTTP GET Error    URI: http://systemservices/ServiceManagerServices.svc    There was an error
> downloading 'http://systemservices/ServiceManagerServices.svc'.
> Unable to connect to the remote server    No connection could be made
> because the target machine actively refused it 172.16.25.221:80

I have tried changing my web.config to so many different values it is untrue, however nothing! Any ideas would be really welcome!!!
This is my web.config
<?xml version="1.0"?>
<configuration>
    <configSections>
        <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
            <section name="ServiceManager.Services.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
        </sectionGroup>
    </configSections>
    <system.web>
        <customErrors mode="Off"/>
        <compilation debug="true" targetFramework="4.0" />
    </system.web>
    <system.serviceModel>
        <services>
            <service name="ServiceManager.Services.ServiceManagerServices" behaviorConfiguration="WCFServiceBehavior">
                <endpoint address="" binding="wsHttpBinding" contract="ServiceManager.Services.IServiceManagerServices" />
                <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
            </service>
        </services>
        <behaviors>
            <serviceBehaviors>
                <behavior name="WCFServiceBehavior">
                    <serviceMetadata httpGetEnabled="True"/>
                    <serviceDebug includeExceptionDetailInFaults="True" />
                </behavior>
            </serviceBehaviors>
        </behaviors>
    </system.serviceModel>
    <system.webServer>
        <modules runAllManagedModulesForAllRequests="true"/>
    </system.webServer>
</configuration>

A: Since you can't connect, it could be an access restriction, but this message can show when you've been kicked back for other issues, so this could be a missing referenced binary, or use of an invalid DataContract or something similar.
Firstly, turn on some diagnostics:
<system.diagnostics>
  <sources>
    <source name="System.ServiceModel" switchValue="Warning, ActivityTracing" propagateActivity="true">
      <listeners>
        <add type="System.Diagnostics.DefaultTraceListener" name="Default">
          <filter type="" />
        </add>
        <add name="ServiceModelTraceListener">
          <filter type="" />
        </add>
      </listeners>
    </source>
  </sources>
  <sharedListeners>
    <add initializeData="path\to\trace.svclog"
      type="System.Diagnostics.XmlWriterTraceListener, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
    name="ServiceModelTraceListener" traceOutputOptions="Timestamp">
    <filter type="" />
  </add>
</sharedListeners>

Now run the service, get the error and using SvcTraceTool (just go to Program Files\Microsoft SDKs and do a search for svc) open up the output log. This will give you more of an overview of the process, at which point it goes wrong and point to more details of the exception - sometimes just telling you to look in the Event Log for the specific exception.

A:
Unable to connect to the remote server    No connection could be made
  because the target machine actively refused it 172.16.25.221:80

I would say it is a firewall issue, not a web.config issue. Can you telnet to that address on port 80 and get a response?


text:
Q: angularjs $http call won't recognize headers I'm trying to hit an endpoint that works fine in Chrome's rest client. But for whatever reason, the browser gives me back the same unhelpful error no matter what I do. Here's the $http call:
         return $http({
            method: 'GET',
            url: calls.filters,
            headers: {
             accept: calls.acceptValue,
             Authorization: calls.token
            }
         }).then(function (response) {
            return response.data;
         });

I've tested and made sure that the calls obj is coming through, and all the values are there. But when I look at what's actually being sent when I do it this way, the headers look like this:
   {
       accept: "application/json",
       Authorization:  "tokenstuffF82arSJxkQ"
   }

If I cut/paste that into the rest client, I get an error back that I'm sending malformed request. So in a desperate attempt to appease the $http gods, I created a headers var, as a string and dropped that into the headers: {} part of the call. I did it with single-quotes (ie 'accept:') and without (ie accept:), I did with & without curly braces. Not that I expected it to work, but scraping the bottom of the barrel on ideas at this point.
No matter what I do, though, I still get the same "Error, All requests must have Authorization header" error, even though the Authorization is in there! I have CORS enabled, plus I know the endpoint hittage works otherwise, since basically the same setup is how I'm logging in. How on earth do I get this to work, and what am I missing!?
Thanks in advance!

A: Check your dev tools for the Authorization header or event better check the request from a fiddler and compare the request you making from the rest client. i'm sure there would be something minor left out and that's eating your day.


text:
Q: Updating Moya/RxSwift breaking my network calls Updating my iOS app from Moya 8 to 11 and I have the following function in a network utility class which is called to get data from a server and map it for use in other classes:
func getServerData(endpoint: MyMoyaService) -> Observable<Any> {
    let provider = RxMoyaProvider<MyMoyaService>()
    return provider.request(endpoint)
        .filterSuccessfulStatusAndRedirectCodes()
        .mapJSON()
        .flatMap { response -> Observable<Any> in
            return Observable(…)
        }
}

With the updates, RxMoyaProvider was replaced with MoyaProvider and instead you're supposed to use .rx to use the RxSwift extensions. This now returns a Single instead of an Observable so in order to avoid compiler errors I also needed to insert asObservable()
func getServerData(endpoint: MyMoyaService) -> Observable<Any> {
    let provider = MoyaProvider<MyMoyaService>()
    return provider.rx.request(endpoint)
        .asObservable()
        .filterSuccessfulStatusAndRedirectCodes()
        .mapJSON()
        .flatMap { response -> Observable<Any> in
            return Observable(…)
        }
}

But the flatMap portion is not being called at all and my network calls don't work anymore. If I do this without RxSwift, just switching on the result, it works OK (but that doesn't fit with my current setup) so I know that the network call and the updates to the custom TargetType service are done correctly.

*

*How do I get this working again, (ideally without completely changing the entire setup, and

*(for extra credit) how do I take full advantage of the updated setup with Single instead of Observable (since I assume that by using asObservable I'm just missing out on useful features / cleaner code)

A: Seems the issue is retaining the MoyaProvider object… If I move the provider outside of the function and store it as a property in the class, then everything works properly.
class MyClass {
     let provider = MoyaProvider<MyMoyaService>()
     func getServerData(endpoint: MyMoyaService) -> Observable<Any> {
        return provider.rx.request(endpoint)
           .asObservable()
           .filterSuccessfulStatusAndRedirectCodes()
           .mapJSON()
           .flatMap { response -> Observable<Any> in
               return Observable(…)
           }
   }
}

From the providers documentation:

Always remember to retain your providers, as they will get deallocated if you fail to do so.

I suppose at some point they updated how these providers get deallocated?


text:
Q: Is there any finished tutorial on how to develop and package unity web apps? I want to create unity web-app for my new website.So,is there any up to the mark tutorial.I've read Ubuntu's official tutorial on this topic but that is not even complete.I've developed the code but don't know how to package the code

A: Actually packaging a webapp isn't really different from packaging any other application. Take a look at resources in this answer and especially at existing integrations, e.g. LinkedIn, Feedly and (shameless plug) This Is My Jam.
Basically, you need debian/ directory with at least the following files (see the guide for details):

*

*control with basic description for package manager (see example) Three keys are important for webapps in particular: XB-Ubuntu-Webapps-Includes, XB-Ubuntu-Webapps-Name and XB-Ubuntu-Webapps-Domain.

*compat

*copyright

*install specifies which files should be installed where

*rules

*changelog specifies the resulting version of the package and must follow a very specific format; can be managed using e.g. dch command

You can generate these files using e.g. dh_make command or just copy the debian directory from other webapps project and change package names, filenames, and domains.
Once you have the files in place, you should be able to generate package using e.g. dpkg-buildpackage command (from the dpkg-dev package). The resulting package is generated in the parent directory.
If you are using version control such as Git or Bazaar, take a look at git-buildpackage or bzr-builddeb respectively (both available in Ubuntu repository). I've found especially the git dch command useful for maintaining the changelog. There's a nice HowTo on packaging with Git and uploading to PPA.

A: I'd take a look at this link: http://developer.ubuntu.com/resources/technologies/webapps/ seeing it's the official guide.


text:
Q: Variable 'Button' never assigned (Java using android studio) First: Apologies if this question has been asked several times already. I just couldn't find a fix.
Compiler in android studio returns "1 error":
Button button_go2activity findViewById(R.id.button_go2activity);

Error code: variable 'button_go2activity' never assigned

This is confusing to me. I also have another button, which I assigned the same (and which works fine).  I also tried to add the variable 'button' in the strings.xml (although it works with the other button without that declaration).
Please see the code attached.
Many thanks for your help.
Best,
Constantin
package paperpad.app;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    //private Button button;              //button because otherwise not declared???
    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button_openHelp = findViewById(R.id.button_openHelp);    //connect button "open help" to xml
        button_openHelp.setOnClickListener(new View.OnClickListener() {     //find button
            @Override
            public void onClick(View view) {                  //activity when button "open help" is clicked
                Intent openHelp = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com"));      //link to paperPad youtube channel
                startActivity(openHelp);
            }
        });

        Button button_go2activity findViewById(R.id.button_go2activity);
        button_go2activity.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                openActivity_loadPicture();                 //activity defined below
            }
        });
    }
    public void openActivity_loadPicture() {
        Intent intent = new Intent(this, loadpicture.class);
        startActivity(intent);

    }
}

A: In your code you are missing the = assignment operator. The line that defines button_go2activity should look like:
Button button_go2activity = findViewById(R.id.button_go2activity);


text:
Q: Cannot install nor cancel mongodb installation I've tried running the setup with and without selecting 'install mongo compass' option, but still I'm neither able to install it nor cancel the installation.
This setup dialogue then freezes without any progress for more than 20-30mins. This is literally just what happens after downloading the setup from their website(https://www.mongodb.com/try/download/community?tck=docs_server) in msi format and starting the install. I'm not sure what I'm doing wrong.
I've selected "complete" setup type then "Install MongoD as a Service MongoDB as a service" and
"Run the service as Network Service user (Default)"


text:
Q: How to add background-size in css based on image size? I am working on a project where the user will be able to select or upload an image and it will be displayed inside of these circles. The images are dynamically being added as background-images. The problem comes in when I am trying to set the background-size. If the image is larger than the circles, I would like it to have a background-size cover, so it scales down. If the image is smaller than the circle, I don't want it to scale up or anything so setting no background size achieves this effect.
Any ideas on how I could achieve this?
The main html looks like this:

    /div>

css:
.module-list-home .content .image-boundary-photo {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
  text-align: center;
  background-repeat: no-repeat;
  background-position: center;
}

Here is the codepen of my example. http://codepen.io/johnsonjpj/pen/zKyGZp?editors=1100
The third image should have a background-size: cover; because it is bigger while the others should stay the way they are.

A: You might get some mileage out of the background-size setting "contain".
I've added it inline to your pen, for a view, here: http://codepen.io/cam5/pen/vXvNOq?editors=1100
It upsizes when they are too small, so might not be entirely what you're after. But querying image's size is very likely going to involve some javascript.  This is a CSS-only approach.

From MDN:

contain
A keyword that scales the image as large as possible and maintains image aspect ratio (image doesn't get squished). Image is letterboxed within the container. When the image and container have different dimensions, the empty areas (either top/bottom of left/right) are filled with the background-color.  The image is automatically centered unless over-ridden by another property such as background-position.

A: Have you tried setting the property background-size: contain; in the .module-list-home .content .image-boundary-photo class?
To solve the problem of small images also getting too large using background-size: contain; use the size as in percentage. e.g.
set the property background-size:60%; in the .module-list-home .content .image-boundary-photo class instead of contain and i think your problem will be solved.
Hope this helps.
[Edit]
Also wrote solution with jquery dynamically checking image size and adjusting.
Here is the jquery solution: http://codepen.io/Nasir_T/pen/ZpVbJo . Make sure your page has the jquery.min linked.

A: Try this
$('.img-responsive').each(function(key, el) {
    var img = new Image;
    img.src = $(el).css('background-image').match(/^url\("?(.+?)"?\)$/)[1];
    if ($(el).width() <= img.width || $(el).height() <= img.height)
        $(el).css('background-size', 'cover');
})

here is a working example


text:
Q: Combine 3 MySQL queries to make 1 query I'm trying to build a search function into my site. If I want to search if a photo's title, text or tag contains the word 'black' I have these 3 queries:
SELECT id
FROM photos
WHERE title LIKE '%black%'
AND status = 'A'

SELECT id
FROM photos
WHERE text LIKE '%black%'
AND status = 'A'

SELECT DISTINCT(photos.id)
FROM photos, photo_tags, tags
WHERE tags.tag LIKE '%black%'
AND photo_tags.keyid = tags.id
AND photos.id = photo_tags.catid
AND photos.status = 'A'

Is it possible to combine all of this into 1 query? I know I can join the first 2 however combining it with the third seems too complex for me. I've tried joining with OR but I don't think I'm doing it right.
Additionally I would like it so that there are no duplicate results, so if a photo has the title 'black' and the tag 'black' it would only show up once.
BTW the tables look something like this, the keyid relates to the tag.id and the catid relates to the photos.id
photos

+----+-----------+-----------------+
| id | title     | text            |
+----+-----------------------------+
|  1 | blue pic  | black and blue  |
|  2 | red pic   | red and green   |
|  3 | green pic | green and white |
|  4 | white pic | white and black |
|  5 | black pic | black and gold  |
+----+-----------+-----------------+

tags

+----+-------+
| id | tag   |
+----+-------+
|  1 | blue  |
|  2 | table |
|  3 | chair |
|  4 | red   |
|  5 | black |
+----+-------+

photo_tags

+-------+-------+
| keyid | catid |
+-------+-------+
|  1    | 1     |
|  2    | 1     |
|  3    | 2     |
|  4    | 2     |
|  5    | 5     |
+-------+-------+

A: It seems you should join the tables and then filter by the text you're looking for in both tables:
SELECT DISTINCT p.id FROM photos p
JOIN photo_tags pt ON pt.cat_id = p.id
JOIN tags t ON pt.key_id = t.id
WHERE (p.title LIKE '%black%' OR t.tag LIKE '%black%') AND p.status = 'A'

A: First statement could be your answer. Not sure if you are looking for below output:-

ysql> SELECT DISTINCT(photos.id) FROM photos, photo_tags, tags WHERE tags.tag L
IKE '%black%'AND photos.title LIKE '%black%' AND photo_tags.keyid = tags.id AND
photos.id = photo_tags.catid;
+------+
| id   |
+------+
|    5 |
+------+
1 row in set (0.05 sec)

mysql> SELECT id
    -> FROM photos
    -> WHERE title LIKE '%black%' ;
+------+
| id   |
+------+
|    5 |
+------+
1 row in set (0.08 sec)

mysql> SELECT id
    -> FROM photos
    -> WHERE text LIKE '%black%';
+------+
| id   |
+------+
|    1 |
|    4 |
|    5 |
+------+
3 rows in set (0.00 sec)

mysql> SELECT DISTINCT(photos.id)
    -> FROM photos, photo_tags, tags
    -> WHERE tags.tag LIKE '%black%'
    -> AND photo_tags.keyid = tags.id
    -> AND photos.id = photo_tags.catid ;
+------+
| id   |
+------+
|    5 |
+------+
1 row in set (0.05 sec)

mysql> SELECT DISTINCT(photos.id) FROM photos, photo_tags, tags WHERE tags.tag L
IKE '%black%'AND photos.title LIKE '%black%' AND photo_tags.keyid = tags.id AND
photos.id = photo_tags.catid;
+------+
| id   |
+------+
|    5 |
+------+
1 row in set (0.05 sec)


text:
Q: For Loop is not looping untill the given range in robot framework sleep till Rest api
  FOR    ${i}    IN RANGE    20
    Sleep    5s till rest api is available
    ${result} = Check Rest Api
    Exit For Loop If    ${result} == True
    Log to Console  try again in 5 sec
  END

I am using For loop to sleep for some time until the api is available and exit from loop once it has got the response. For this I had stored the result of the keyword in a varibale and gave exit from loop when result becomes true. But, whats happening is first it waits for 5 seconds and checks the result and fails. After failing once it is not iterating and fails at checking the result itself.
Here when it goes through the second line in for loop ( ${result} = Check Rest Api ). The sleep time is not sufficient and it fails at that statement itself. What I am expecting is the loop should continue until it gets the response.


text:
Q: Hide Bootstrap popover after a delay I already check out this answer: Auto hide bootstrap popover, but it does not seem to cover my exact scenario.
I initialize my popovers in the window load function like this:
$(window).load(function(){
  $('#fileArea').popover({
    selector: '[rel=popover]'
  });
});

The trigger is a table row element. Normally when a user clicks a row, an item gets added to a queue. Rather than binding or unbinding a bunch of stuff, I set up two separate click handlers. One to handle table rows that do NOT have rel="popover" (and after executing the code, I then add the rel attribute!) and one to handle table rows that indeed have rel="popover"
This is all working dandy; the separate listeners successfully distinguish between the two types of clicks. Here's the code for showing a popup on elements with the valid rel attribute:
$('#fileArea').on('click', 'tbody [rel=popover]', function(e) {
  var $this = $(this);
  $this.popover({container: '#fileArea', placement: 'top auto', content:"This file has already been added to the queue."});
  setTimeout(function() {$this.popover('hide')},3000);
});

So, the popovers are already "initialized" (sort of... using the selector parameter with the #fileArea as the actual listener), and then when the popover method is called, the parameters being passed in create a successful popover. The setTimeout also works!
But then I discovered that if the user clicks AGAIN, the popover will not appear. I suspect it has to do with passing in parameters rather than just calling the void method or passing the string 'show'. Unfortunately, I need to pass parameters rather than use the data- attributes to store the content.
From console, if I select the row and then call $el.popover('show') on it, the popover appears again.
My current thinking is that I need to figure out if the row already has a popover configured on it (not just initialized, but configured). However, I don't know how to find that out in order to create a conditional. The faked code would look something like this:
$('#fileArea').on('click', 'tbody [rel=popover]', function(e) {
  var $this = $(this);
  if(/* popover is configured */) {
    $this.popover('show');
  } else {
  $this.popover({container: '#fileArea', placement: 'top auto', content:"This file has already been added to the queue."});
  }
  setTimeout(function() {$this.popover('hide')},3000);
});

Anybody have ideas for detecting if a popover is configured? Any alternative ways of accomplishing my goal?

A: Set a .data() value on the element when you initialize the popover:
$('#fileArea').on('click', 'tbody [rel=popover]', function(e) {
  var $this = $(this);
  if($this.data("popoverInitialized")) {
    $this.popover('show');
  } else {
    $this.popover({container: '#fileArea', placement: 'top auto', content:"This file has already been added to the queue."});
    $this.data("popoverInitialized", true);
  }
  setTimeout(function() {$this.popover('hide')},3000);
});

Or, instead of hiding the popover, destroy it:
$('#fileArea').on('click', 'tbody [rel=popover]', function(e) {
  var $this = $(this);
  $this.popover({container: '#fileArea', placement: 'top auto', content:"This file has already been added to the queue."});
  setTimeout(function() {$this.popover('destroy')},3000);
});

Or, show the popover every time:
$('#fileArea').on('click', 'tbody [rel=popover]', function(e) {
  var $this = $(this);
  $this.popover({container: '#fileArea', placement: 'top auto', content:"This file has already been added to the queue."});
  $this.popover('show');
  setTimeout(function() {$this.popover('hide')},3000);
});