text:
Q: How do I make an image push up another image within a  tag I am just starting HTML and some basic CSS, Im here trying to make a Rocketship push up another image with some simple  tags,
Ive tried everything.
I have right now,

<marquee behavior="scroll" direction="up">

</marquee>

I have tried some CSS which is in my stylesheet.css right now, and here is that code.
image {
    position: relative;
    width: 100px;
    height: 100px;
    border: 1px solid red;
}
.imageOne {
    z-index: 0;
}
.imageTwo {
    z-index: 1;
}

and at this point, i dont even know if im using z-index in the right context. If its hard to see my vision, Im bascially trying to push and image up with another image under it. or create that kind of visual, i dont know if i have to edit the pixel and align them up.  The rocket seems to be being in the center but the src="images.png" is on the side but its under the  tag...
Sorry if this is dumb and simple but I couldnt find anything.
As Requested in comments; https://jsfiddle.net/7ohrpk42/

A: Updated Solution:

img {
 margin-left: auto;
 margin-right: auto;
 display: block;
}
<DOCTYPE HTML!>

    <title>The Most Best Worst Websites</title>

      <marquee behavior="scroll" direction="up">

      </marquee>

Your questions a little unclear without a jsFiddle, but I think you are trying to do something like this:

img {
  position: relative;
  width: 100px;
  height: 100px;
  border: 1px solid red;
}

.imageOne {
  margin: none;
}

.imageTwo {
  margin: none;
}

  <marquee behavior="scroll" direction="up">

  </marquee>

A: What you're trying to achieve can be done by setting the "f&*k you" image as the background of the marquee and background size to 'cover'. Like this:
marquee{
  background: url('https://i.postimg.cc/g2ZJTkHk/images.png') no-repeat;
  background-size: cover;
}

I updated your fiddle https://jsfiddle.net/0vd79j2h/

A: <marquee> is Deprecated
It is strongly recommended that <marquee> be avoided -- it's deprecated and on its way to becoming obsolete. We can still customize HTML elements to behave and appear as a <marquee> with CSS animation (or even with JavaScript/jQuery although it wouldn't be as efficient as CSS). The following demo uses CSS animation only, and the only images are actually fonts (like emoticons)

Demo

.marquee {
  width: 30%;
  height: 50vh;
  /* Required on Parent */
  overflow: hidden;
  font: 400 15vh/1.5 Consolas;
  background: rgba(0, 0, 0, 1);
  padding-left: 15px;
  margin: 20px auto;
}

.marquee b,
.marquee i {
  /* Required on Child*/
  white-space: nowrap;
  display: table-cell;
  vertical-align: baseline;
  /* Infinite Loops */
  animation: climb 2s linear infinite;
  animation-fill-mode: forwards;
  /* Set to 0s in order to have a point of reference */
  animation-delay: 0s;
}

.marquee i {
  animation: fall 2s linear infinite;
}

/* Required for complex CSS animation */

/* Bottom to top / Left to right */

@keyframes climb {
  0% {
    transform: translate(-200%, 300%);
  }
  100% {
    transform: translate(300%, -300%);
  }
}

/* Top to bottom / Right to left */

@keyframes fall {
  0% {
    transform: translate(200%, -20%);
  }
  100% {
    transform: translate(-300%, 300%);
  }
}

  ✨


text:
Q: Spring Batch Data Migration I am working on a project where the data from old database is to be migrated and/or merged with the new database after processing.  I have more than 500 tables in the old db.  The master data (Ids) in both the database are not matching with each other, so I decided to create mapping tables where old and new Ids will be kept, which will be used in later stage of migration.
So I decided to use Spring Batch for the same. However soon I realized that I cannot compare the data from old and new database, because the data can be read from single data source at a time.
My questions is, is there any way to do this with spring batch? Is there any another better way to migrate the data.
My scenario is as follows.
Old DB
Table Name – bank
bankId  bankName
1           IDBI
2           HDFC
3           SBI

New DB
Table Name – bank
bankId  bankName
1           SBI
2           Bank Of India
3           IDBI
4           HDFC

Required Output
Table Name – migrate_bank
oldBankId   newBankId
1           3
2           4
3           1

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to set Kendo Grid's total count manually? i am trying to set total count value of Grid  manually on delete event.When delete button pressed, delete event is catched by javascript , pass value that will be delete. At last, i would like to decrease total count of grid.Problem is, i am able to decrease count but i dont know how to set new count to grid's Datasource as total value.
   @(Html.Kendo().Grid<Model>()
   .Name("grid")
    .Events(e=>e.Remove("customDelete"))

JS
    e.preventDefault();

    var grid = $("#grid").data("kendoGrid").dataSource;
    var count = grid.total();
    alert(count); // actual count

    var countNew=  grid.total() - 1  //new count after delete  ;
    alert(countNew);
    //...  need to set grid's total count as countNew

    $('.k-pager-info').html(1 + " - " + countNew+  " of " + countNew+ " items");
    var data = e.model["ID"]; // Getting IDvalue of column
    ...// Deleting process

A: I agree with @PeturSubev, if you delete the row it should automatically be decremented. If for some sort of reason -that I cannot understand- you need to set it to some value, the solution is implement a custom total function in the schema.model. Something like:
var countNew = undefined;
var dataSource = new kendo.data.DataSource({
    transport: {
        /* transport configuration */
    }
    schema: {
        total: function (d) {
             return countNew || d.length;
        }
    }
});

// Compute newCount with as you want
var countNew =  grid.total() - 1  // new count after delete  ;


text:
Q: Core Date One-To-One Sorting I have a core data model that has two entities, Bid and Result.
I want them sorted initially in a section where the bid has no result i.e. the relationship from Bid to Result is nil, then I want this sub sorted by date.
Ideally I would have two sections:

*

*Bids with no Result sorted by date

*Bids with a result sorted by date

Due to the relationship being potentially nil I see very erratic results. Using two NSSortDescriptors first sorting on the relationship and then on the date will work for a few entries then seems to randomly blow up.
E.g.
 NSSortDescriptor *sectionSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"result" ascending:YES];
 NSSortDescriptor *dateSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:NO];

How should I sort entities by a relationship that could potentially be nil?

A: A nil should evaluate to zero and non-nil to non-zero so you can sort on nils. I think the problem maybe elsewhere.
I would suggest trying to sort just with the nils and see if that works. That at least will tell you where the problem is.


text:
Q: How to iterate over two lists and recycle the second one until the first one is over Basically I have these 2 lists
listone = ['a', 'b', 'c', 'd', 'e', 'f', 'j']
listtwo = ['1', '2', '3']

And I want to iterate over both of the lists synchronously and whenever the shortest list ends (listtwo in this case) is restarts again until listone is finished.
Example:
a 1
b 2
c 3
d 1
e 2
f 3
j 1

Like this.

A: you can use itertools.cycle:
from itertools import cycle

for i, j in zip(listone, cycle(listtwo)):
    print(i, j)

output:
a 1
b 2
c 3
d 1
e 2
f 3
j 1

A: Without itertools.cycle() or creating secondary list:
listone = ['a', 'b', 'c', 'd', 'e', 'f', 'j']
listtwo = ['1', '2', '3']
N = len(listtwo)

for index, elem in enumerate(listone):
    elem2 = listtwo[index % N]
    print(elem, elem2)

A: from math import ceil
listone = ['a', 'b', 'c', 'd', 'e', 'f', 'j']
listtwo = ['1', '2', '3']
listtwo_augmented = listtwo * ceil(len(listone)/len(listtwo))
for e1, e2 in zip(listone, listtwo_augmented):
    print(e1, e2)

A: Add-on to accepted answer,
In case of unknown list length.
from itertools import cycle

A = [1,2,3,4,5,6,7,8,9]
B = ["A","B","C"]

zip_list = list(zip(A, cycle(B)) if len(A) > len(B) else zip(cycle(A), B))

for i, j in zip_list :
    print(i, j)

1 A
2 B
3 C
4 A
5 B
6 C
7 A
8 B
9 C

[Program finished]


text:
Q: Using AppCompat v21 or lower in Eclipse I updated  appcompat-v7 SDK to API 23. But i cannot reference it as a library in Eclipse if my project is set to API 21.
There is a solution with Android Studio in this link Using AppCompat v22 or lower .
Is there any solution in Eclipse?
Thank you.


text:
Q: How to use ShinyApp to choose 3 specific factor variables among all for creating plot according to them with "ggplot2" package? I am new to shiny package,I want to create an app for my Data which choose 3 specific variables among 4 variables and create the plot according to them.My data is:
month <-
as.factor(c("sep","oct","nov","nov","oct","oct","oct","nov","sep","oct"))
cost <- as.numeric(sample(1000:10000,10,replace=F))
Type <- as.factor(c("T1","T1","T3","T1","T2","T3","T1","T3","T2","T2"))
class <- as.factor(c("R","Q","R","R","R","Q","Q","Q","R","R"))
sex <- as.factor(c("M","F","F","F","M","F","F","M","M","F"))

f <- data.frame(month , cost , Type , class , sex)
f

f1 <- as.data.frame(aggregate(f[c("cost")],
                          by=f[c("month","Type","class","sex")],
                          FUN="mean"))
f1$percent <- f1$cost/sum(f1$cost)

f1

As you can see my data has 4 factor variable,I want the user to choose 3 of them and plot according to the 3 chosen variables.It is important that which variable is chosen for x_axis and which is chosen for fill parameter and which one for facet_grid's argument.
what I want to do in an interactive way:
library(ggplot2)

ggplot(f1 , aes(x=month ))+
geom_bar(stat="identity",aes(y=percent , fill=Type) ,colour="black",
  position = position_dodge())+
scale_y_continuous(labels = scales::percent)+
labs(x="month" , y="cost percentage")+
facet_grid(sex ~ class)+
theme(strip.text.x = element_text(size=8),
    strip.text.y = element_text(size=5, face="bold"),
    strip.background = element_rect(colour="red", fill="#CCCCFF"))+
labs(x="month" , y="percentage" )

What I have tried:
library(shiny)
library(ggplot2)
ui <- fluidPage(

titlePanel("Report"),
sidebarLayout(
sidebarPanel(

  selectInput("variable1", "Variable1:",
              choices = c("month","Type","class","sex")),

  selectInput("variable2", "Variable2:",
              choices = c("month","Type","class","sex")),

  selectInput("variable3", "Variable3:",
              choices = c("month","Type","class","sex")),

  ),

  mainPanel(
  plotOutput("disPlot")

      )
     )
    )

 server <- function(input, output) {
 var1 <- reactive({
 switch (input$variable1,
        "month"=month,
        "Type"=Type,
        "class"=class,
        "sex"=sex
   )
  })

 var2 <- reactive({
 switch (input$variable2,
        "month"=month,
        "Type"=Type,
        "class"=class,
        "sex"=sex
    )
  })

 var3 <- reactive({
 switch (input$variable3,
        "month"=month,
        "Type"=Type,
        "class"=class,
        "sex"=sex
   )
  })

 output$disPlot <- renderPlot({
 variable1 <- var1()
 variable2 <- var2()
 variable3 <- var3()
   ggplot(f1 , aes(x=variable1 ))+
    geom_bar(stat="identity",aes(y=percent , fill=variable2)
    ,colour="black", position = position_dodge())+
    scale_y_continuous(labels = scales::percent)+
    labs(x="variable1" , y="cost percentage")+
    facet_grid(. ~ variable3)+
    theme(strip.text.x = element_text(size=8),
        strip.text.y = element_text(size=5, face="bold"),
        strip.background = element_rect(colour="red", fill="#CCCCFF"))+
    labs(x="variable1" , y="percentage" )

      })

   }
   shinyApp(ui,server)

My first problem is : how can I delete the selected variable1 from inputselect() of variable2,that any of the variables has been chosen for variable1 does not appear in selectinput() of variable2 and any of them that has been chosen for variable2 does not appear in the list of selectinput() for variable3.In other words,the 3 variables should not be equal at all.They have to be different.
The second one:I am a little confused about the usage of reactive() function and if I used it correctly,what is the correct form of ui and server for my purpose?
Any help or solution would be greatly appreciated.If any more information about my question is needed,I'll be answering.


text:
Q: getElemenstByTag returning null inside facebook page plugin iframe Is there any Error in the code ? or How should I get desired output ?
My aim is to do this
document.getElementById('iframe1').contentWindow.document.getElementsByTagName("IMG").style = "filter:invert(100%);";

The Entire Code is given Below
<iframe onload="frameload()" lazy="true" sandbox="allow-same-origin allow-scripts block-popups allow-forms" class='viewport-iframe' id='iframe1' src="https://www.facebook.com/plugins/page.php?href=https%3A%2F%2Fwww.facebook.com%2FTroll.Malayalam%2Fposts%2F&tabs=timeline&width=340&height=500&small_header=true&adapt_container_width=true&colorscheme=&hide_cover=false&show_facepile=false&appId" scrolling="no" frameborder="0" allowfullscreen="true" allow="autoplay; clipboard-write; encrypted-media; picture-in-picture; web-share" frameborder="0" allowFullScreen="true" webkitallowfullscreen="true" mozallowfullscreen="true">

A: If you are getting iframe successfully than change your code like this. Add your attributes in iframe tag


text:
Q: how to add child window controls to CWindowImpl How do I add simple child window controls (e.g. a button) to a CWindowImpl?
I've looked at CWindowImpl and CDialogImpl. With CDialogImpl, it appears that you just create a dialog template resource and use it, very simple. I would like to do something similar with CWindowImpl, but there doesn't seem to be a way to do it. Must I add the controls manually and position them programmatically?
Some context on what I'm trying to do: I'm trying to create a plug-in for foobar2000, a Windows audio player. I would like to create a "UI element" plugin, and in the sample code that I've looked at, a "UI element" is created via CWindowImpl. How do I add buttons to this CWindowImpl? I've tried using a CDialogImpl instead, but this gives me a "pop-up" dialog, which is not what I'm looking for.
Thanks very much in advance!

A: With any window, including CDialogImpl, you can add child controls by creating a new window of control class and specifying your parent window handle as a parent for new control. Additionally, SetParent API is here to re-parent any window.


text:
Q: Flutter|Updating a ListView everyone!
I have a HomeScreen, with this code:
return SafeArea(
          child: Scaffold(
            body: Stack(
              children: [
                Padding(
                  padding: const EdgeInsets.only(left: 8, right: 8),
                  child: Column(children: [
                    ActiveTaskInfo(
                      task: tasks.first,
                    ),
                    const TextWidget(),
                    Expanded(child: TasksList()),
                    const SizedBox(height: 80),
                  ]),
                ),
                BottomBarClass(),
              ],
            ),
        ),
    );

TasksList() - ListView.
BottomBarClass() - It is a container with a button inside.
If you return the code itself to the main HomeScreen file, everything works, but if you put it in a separate class and when you add a new item to the list (through the button) nothing happens, but if you press Hot Reload, then the new item in the list is displayed.
Code BottomBarClass():
Positioned(
        bottom: 0, left: 0,
        child: ClipRRect(
          borderRadius: const BorderRadius.only(topRight: Radius.circular(30), topLeft: Radius.circular(30)),
          child: Container(
            height: 80, width: MediaQuery.of(context).size.width,
            color: const Color(0xff070417),
            child: Row(mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                Icon(Icons.watch_later, color: Colors.white.withOpacity(0.4)),
                IconButton(icon: Icon(Icons.add, color: Colors.white.withOpacity(0.4),), iconSize: 32, onPressed: () async {
                  bool result = await Navigator.push(context, MaterialPageRoute(builder: (context) {
                    return TaskAdding();
                  }));
                  if (result == true) {
                    setState(() {
                    });
                  }
                }),
                Icon(Icons.pie_chart_rounded, color: Colors.white.withOpacity(0.4), size: 24,),
              ],),
          ),
        ));

Вот пример GIF: https://gifyu.com/image/Spp1O
TaskAdding():
import 'package:flutter/material.dart';

import '../expansions/task_tags_decorations.dart';
import '../expansions/tasks_data.dart';

class TaskAdding extends StatefulWidget {
  const TaskAdding({Key? key}) : super(key: key);

  @override
  State<TaskAdding> createState() => _TaskAddingState();
}

class _TaskAddingState extends State<TaskAdding> {
  late String _addField;
  late Widget _selectedValue;
  late bool _active;
  late int _selectedIndex;

  @override
  void initState() {
    _addField = 'Empty';
    _active = false;
    _selectedValue = tasks[0].icon;
    _selectedIndex = 0;
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Add'), backgroundColor: Colors.pink),
      body: Column(children: [
        Text('Add Task', style: TextStyle(color: Colors.white, fontSize: 24),),
        TextField(onChanged: (String value) {
          _addField = value;
        }),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            DropdownButton<Widget>(
              value: _selectedValue,
              onChanged: (newValue) {
                setState(() {
                  _selectedValue = newValue!;
                });
              },
              items: dropdownItems,
            ),
            ElevatedButton(
                onPressed: () {
                  setState(() {
                    tasks.addAll({
                      TaskData(
                        taskName: _addField,
                        tagOne: _active
                            ? tasks[0].tagOne
                            : tasks[1].tagOne,
                        tagTwo: tagTwoContainer[_selectedIndex],
                        icon: _selectedValue,
                        taskTime: '00:32:10',
                      )
                    });
                    decorations.addAll({
                      TaskTagsDecorations(
                          iconColor: const Color(0xff7012CF))
                    });
                  });
                  Navigator.of(context).pop(true);
                },
                child: const Text('Add')),
          ],
        ),
        Center(
          child: ListTile(
            title: _active
                ? Center(
              child: tasks[0].tagOne,
            )
                : Center(child: tasks[1].tagOne),
            selected: _active,
            onTap: () {
              setState(() {
                _active = !_active;
              });
            },
          ),
        ),
        SizedBox(
          height: 52,
          child: ListView.builder(
              shrinkWrap: true,
              scrollDirection: Axis.horizontal,
              itemCount: tagTwoContainer.length,
              itemBuilder: (context, index) {
                var tagTwoList = tasks[index].tagTwo;
                return SizedBox(
                  height: MediaQuery.of(context).size.height, width: 160,
                  child: ListTile(
                    visualDensity: VisualDensity.compact,
                    selected: index == _selectedIndex,
                    selectedTileColor: Colors.indigo.withOpacity(0.6),
                    title: Align(
                      alignment: Alignment.topCenter,
                        child: tagTwoList),
                    onTap: () {
                      setState(() {
                        _selectedIndex = index;
                      });
                    },
                  ),
                );
              }),
        ),
      ],),
    );
  }
  List<DropdownMenuItem<Widget>> get dropdownItems {
    List<DropdownMenuItem<Widget>> menuItems = [
      DropdownMenuItem(
        child: const Icon(Icons.free_breakfast),
        value: iconCircle[0],
      ),
      DropdownMenuItem(
          child: const Icon(Icons.grade_outlined), value: iconCircle[1]),
      DropdownMenuItem(child: const Icon(Icons.gamepad), value: iconCircle[2]),
      DropdownMenuItem(
          child: const Icon(Icons.face_rounded), value: iconCircle[3]),
    ];
    return menuItems;
  }
}

A: You question is not clear. Try to add TasksList()

A: My solution:
 Navigator.push(context,
                    MaterialPageRoute(builder: (context) {
                      return HomeScreen();
                    }));


text:
Q: Событие submit и обработчик события Можно ли при появлении события сабмит на форме, использовать собственный обработчик чтобы произвести валидацию? Прочитал на форумах - вроде как должно отрабатывать. В итоге отрабатывает частично - если форма заполнена верно и произошел сабмит, то вызовется обработчик, который я передал в виде колбэк. Если же форма заполнена неверно и засабмичена, то мой обработчик не вызовется и браузер отработает по своему. Т.е. никаких вариантов добраться до валидации вручную.
Пробовал сие на г**нокоде, который привожу ниже. Как быть, если я всё таки хочу провести валидацию по событию сабмит на форме?

<!DOCTYPE html>
<html>
    <head>

    </head>
    <body>
        <form id="form" action="#" method="POST">
            <input type="number" min="10">
            <button type="submit"></button>
        </form>
        <script>
            var somefun = function () {
                console.log('happend');
            };
            var elementForm = document.querySelector('#form');
            elementForm.addEventListener('submit', somefun);
        </script>
    </body>
</html>

A:
Можно ли при появлении события submit на форме использовать собственный обработчик, чтобы произвести валидацию?

var elementForm = document.querySelector('#form');
// Нужно поймать событие "e"
elementForm.addEventListener('submit', function(e) {
  e.preventDefault(); // Остановить форму от посылки на сервер
  //------------------------------------------------------------
  // Your validation goes here
  console.log('happened');
});
<form id="form" action="#" method="POST">
  <input type="number" min="10">
  <button type="submit">Submit</button>
</form>

A: Добавьте в <form> атрибут onsubmit = "return formValidation()", а в функции используйте return true; для отправки формы на сервер или return false; для отмены.

function formValidation() {
  alert("Валидация формы");
  return false;
}
<form id="form" action="#" method="POST" onsubmit="return formValidation()">
  <input type="number" min="10">
  <button type="submit">Submit</button>
</form>

A: Для отключения проверки браузером можно воспользоваться атрибутом novalidate на форме

var somefun = function() {
  console.log('happend');
};
var elementForm = document.querySelector('#form');
elementForm.addEventListener('submit', somefun);
<form id="form" action="#" method="POST" novalidate>
  <input type="number" min="10">
  <button type="submit">btn</button>
</form>


text:
Q: What are some standard methods for solving functional equations? I have searched the internet for methods on solving functional equations, unfortunately, most of them consist mainly of substituting values for the variables or on guessing solutions. I think those methods sound like either an impossible task due to the infinite number of possible substitutions or a leap of faith due also to the infinite number of guesses there can be.

How could one for example solve:
$$f(1+x)=1+f(x)^2$$
I have tried many different ideas on this, from trying guesses to applying integrals, to eliminating the $1$ by calculating $f(2+x)$ and subtracting equations, then trying to simplify the answer through sums or products, but nothing seems to work.

I think this is a rather interesting subject because $f(x)=f(x-1)^2$ has a solution that is very easy to find but somehow adding a $1$ makes it a much harder problem. Are there ways to solve this equation or even a polynomial functional equation?

A: As for iterating polynomials, there are two general forms of polynomials that we currently know how to iterate. They are polynomials of the form
$$P(x)=a(x-b)^d+b$$
and
$$T(x)=\cos(k\arccos(x))$$
and yes, I know the second one doesn't look like a polynomial, but for integer values of $k$, it is a polynomial where the inverse cosine is defined, and can be extended to other values (accurately, for our purposes) using the hyperbolic cosine function. For more info, see Chebyshev Polynomials.
The iteration formulas for each of these is given by
$$P^n(x)=a^{\frac{b^n-1}{b-1}}(x-b)^{d^n}+b$$
and
$$T^n(x)=\cos(k^n\arccos(x))$$
In case you were wondering how this applies to your problem of finding $f$ given that
$$f(1+n)=(Q\circ f)(n)$$
where $Q$ is a polynomial, here's how: if you assign a value for $f(0)$, say $y_0$, then you can say that
$$f(n)=(Q^n\circ f)(0)=Q^n(y_0)$$
which allows you to find $f:\mathbb Z\to\mathbb Z$.


text:
Q: ActionView::Template::Error (no implicit conversion from nil to integer) - awesome_nested_set I'm using awesome_nested_set to implement nested pattern in select tag. When there is no record in the database form is loading successfully, but after adding first category as base category whose parent_id is null this error is showing up
ActionView::Template::Error (no implicit conversion from nil to integer)

I've used view helper to implement this, my select tag looks like this
<%= f.select :parent_id, nested_set_options(Category, @category) {|i, level| "#{'-' * level} #{i.name}" } %>

Please help, how to get rid of this error, I'm using awesome nested set to implement this!

A: You need to use this:
<%= f.select :parent_id, nested_set_options(Category, @category) {|i| "#{'-' * i.level} #{i.name}" } %>

You have a serious error in your block. As documented on the gem's page, the block passed to the nested_set_options only accepts a single argument i which is the category itself. level is a method of i which you can get using i.level.


text:
Q: Can't get data from Bosch IoT API this is my first question to this great community, so please have mercy.
I currently have following problem:
I want to recieve data from Bosch IoT API, but even following their documentation (https://bosch-iot-insights.com/static-contents/docu/html/Java.html >> Synchronous query execution - Example) didnt help me.
My code looks exactly the same as theirs:
        String resourceUrl = "https://bosch-iot-insights.com/mongodb-query-service/v2/my-project";

        String username = "my-user";
        String password = "my-pw";
        String authorizationCredentials = generateAuthorizationToken( username, password );

        String payload = new String(Files.readAllBytes(Paths.get("C:/Users/my-name/Desktop/payload.json")));
        String contentType = "application/json";

        WebResource service = Client.create().resource( resourceUrl );
        ClientResponse response = service.header( "Authorization", authorizationCredentials )
                .header( "Content-Type", contentType )
                .post( ClientResponse.class, payload );

        System.out.println( response );

        if ( response.getStatus() == 200 ) {
            System.out.println( parseJson( response.getEntity( String.class ) ) );
        }

I've also tried some solutions with C# and PHP, but they all had the same output: 403 Forbidden
When I am opening the project URL I can normally log in, but then I get obviously a 405 Method not allowed - Error, because there is no GET-Method.
I even contacted them and asked for help, but with my credentials they were getting following result:
POST https://bosch-iot-insights.com/mongodb-query-service/v2/my-project/execute-aggregation-query returned a response status of 200 OK
[
  {
    "key": value
  }
]

I know what the Status Code 403 means, but even Bosch can't help me in this problem, because for them everything looked fine..
I'd appreciate and be very grateful if someone could help me or give me some ideas why this error is being produced.
(For more information feel free to ask!)


text:
Q: How can I make my laptop boot automatically from the hard drive without having to press F10 each time? I followed the instructions in this answer to How do I boot my Samsung laptop from a CD/DVD?
Once I installed Windows I found that I have to press F10 to select the hard drive every single time to make it boot into Windows. I tried re-enabling Secure Boot but then I am unable to find the hard drive in the bootable devices list.
What should I do?

my labtop is sumsang core i3
i mean that when i wanted to change my windows i can not find cd-rom in the list of F10
i saw the Instructions of this link
How do I boot my Samsung laptop from a CD/DVD?
i Succeeded to do that and i changed my windows
but then i can not go to windows automatically
I had to press F10 to select hard drive
and i can go to windows
i want To what it was before so I make secure boot (enabled)
but I can't find hard drive on the list of F10.
maybe i Erred in doing my new windows
If i changed my windows again i can go to windows automatically or not
please i wait your advice and Instructions

A: there are two ways you can get your computer to boot from CD/DVD
1: Change the first boot device from BIOS

*

*Turn on the PC

*Press F2 at the Samsung Logo

Make sure you don't change anything else unless you know what you are doing

*You would see BIOS Setup Utitlity

*Navigate to Boot

*Go to Boot Device Priority and press enter

*You would see a list of Bootable Devices

*Using F5/F6 to change values, makeCD/DVD the first boot device

*Press enter and F10 to save and exit

You should be able to boot the computer using CD/DVD now

Make sure you don't change anything else unless you know what you are doing

2: Access one time boot menu
Try Esc or F4 to access One Time Boot menu in samsung computers


text:
Q: Python: how to write data to an already open excel file (no path specified)? I'm trying to write data to an excel file that is already open and saved with a specific filename. I need to do this without specifying a file path.
What I have below is not writing anything to the spreadsheet.
import pandas as pd
df = pd.DataFrame({data1, data2, data3})
writer = pd.ExcelWriter("*open_excel_filename*.xlsx")
df.to_excel(writer,"Sheet1",startrow=1,startcol=1)


text:
Q: Call System.IDisposable.Dispose on object 'emailForm' before all references to it are out of scope I have the following function:
    private void emailVideoButton_Click(object sender, EventArgs e)
    {
        VideoEMailForm emailForm = new VideoEMailForm();
        emailForm.ShowDialog();
    }

Which gives me the following warning:

Warning   1   CA2000 : Microsoft.Reliability : In method
  'VideoPlayerControl.emailVideoButton_Click(object, EventArgs)', call
  System.IDisposable.Dispose on object 'emailForm' before all references
  to it are out of scope.

I read this link http://msdn.microsoft.com/en-us/library/ms182289(v=vs.80).aspx and gathered that I needed to call .Dispose like so:
    private void emailVideoButton_Click(object sender, EventArgs e)
    {
        VideoEMailForm emailForm = new VideoEMailForm();
        emailForm.ShowDialog();
        emailForm.Dispose();
    }

But then I get the following warning:

Warning   1   CA2000 : Microsoft.Reliability : In method
  'VideoPlayerControl.emailVideoButton_Click(object, EventArgs)', object
  'emailForm' is not disposed along all exception paths. Call
  System.IDisposable.Dispose on object 'emailForm' before all references
  to it are out of scope.

Can anyone help me to get rid of this warning?

A: You need the using statement, which will call Dispose() in a finally block to make sure it gets disposed even if an exception is thrown.

A: What the compiler is trying to say is that if an exception is thrown in emailForm.ShowDialog(), Dispose() will not get called.
Use a using statement to ensure that it will get called either way.
private void emailVideoButton_Click(object sender, EventArgs e)
{
    using (VideoEMailForm emailForm = new VideoEMailForm())
    {
        emailForm.ShowDialog();
    }
}

This is equivalent to this code:
private void emailVideoButton_Click(object sender, EventArgs e)
{
    VideoEMailForm emailForm = null;
    try
    {
        emailForm = new VideoEMailForm();
        emailForm.ShowDialog();
    }
    finally
    {
        if (emailForm != null)
        {
            ((IDisposable)emailForm).Dispose();
        }
    }
}


text:
Q: SQL Server 2012 patching failure - The language of SQL Server instance MSSQLSERVER does not match the language expected by the SQL Server update I've picked up the support for a SQL Server 2012 instance on a server at our German site and need to apply SQLServer2012SP4-KB4018073-x64-ENU.
The patching is failing with the installer showing error

The language of SQL Server instance MSSQLSERVER does not match the language expected by the SQL Server update. The installed SQL Server product language is German (Germany) and the expected SQL Server language is English (United States).

The server properties general tab (in SSMS) shows Language German (Germany), but the SERVERPOPERTY('LCID') shows 1033 (US_English). The registry entry shows 1031 (German) as the install language (https://www.sqlserverscience.com/basics/localization/language-used-sql-server-binaries/#comment-191)

Trying to use the German patch file SQLServer2012SP4-KB4018073-x64-DEU results in

This SQL Server setup media does not support the language of the OS, or does not have the SQL Server English-language version installation files. Use the matching language-specific SQL Server media; or install both the language specific MUI and change the format and system locales through the regional settings in the control panel

Any pointers as to a way forward so I can apply the patch?
Attempted patching after first suggested fix

A: The cause of the error is that you are applying an English update on a SQL Server installed in German language. Or maybe there might be some specific problem with SQL Server and the German Language.
@Massimiliano Buschi is right, the solution should be this. However you said in your case is not working.
Use PowerShell to:

*

*Check your current language: Get-WinUserLanguageList

*Set the language you want: Set-WinUserLanguageList -LanguageList en-US

*Reboot and try to install

Still doesn't work? Let's try to change these 3 parameters:

*

*User interface settings: In Control Panel, open Region and Language. On the Languages tab, for Language used in menus and dialogs, select a value from the list. Click Apply to confirm the change and OK to close the window.

*User locale: In Control Panel, open Regional and Language Options. On the Regional Options tab, for Select an item to display its settings, select a value from the list. Click Apply to confirm the change and OK to close the window.

*System locale: In Control Panel, open Regional and Language Options. On the Advanced tab, for Select a language that matches the version of the non-Unicode programs you want to use, select a value from the list. Click Apply to confirm the change and OK to close the window.

Still doesn't work? We need to use the hammer :(

*

*Delete or Rename the %ProgramFiles%\Microsoft SQL Server\110 folder (110 for SQL Server 2012, 120 for SQL Server 2014and so on)

*Try again.

A: This is an easy one. Albeit if you work in a Swiss-German organisation like I do and have to install German SQL Server instances on Windows Servers, which have been set up to use the location Switzerland which results in a Swiss-German keyboard layout and date-time settings.
The solution depends on the version of the OS installed...
Windows Server 2016
On a Window Server 2016 with the Location set to Switzerland the language bar might look like this:

Trying to install a German Service Pack will fail, even though the Deutsch (Schweiz) setting is available. Starting the SQLServer2016SP2-KB4052908-x64-DEU.exe (SQL Server 2016 Service Pack 2 German) results in:

Solution
To circumvent this issue, add the language German - German and set to default.
1. Open Language and Region Settings

Click on the Add Language icon ...
2. Add Language
...and start typing German.

3. Select German - German
Select the German (Germany) (or Deutsch (Deutschland)) option...

4. Set Default
...and when back in the Language and Region Settings select the Set Default button:

6. Language and Region Settings
Your settings should now look a bit like this with German (Germany) (or Deutsch (Deutschland)) at the top.

6. Run Setup Again
If I run the setup for Service Pack 2 now, then I am presented with:

...and eventually this:

Disclaimer:
All pictures taken today on a Windows Server 2019 (German) running SQL Server 2016 (German)

Details for older operating systems to follow...

A: Please try to go to Control Panel, Regional Settings and change the "Format" language.  close , re-open it and change format back to yours. Retry the setup of the patch


text:
Q: X86 - Function is undefined I am new at assembly and am trying to wrap my head around function calling in x86. I am provided the following code:
read_integer:

push ebp
mov ebp, esp

sub esp, 8
mov dword [ebp-4], '0'
mov dword [ebp-8], 0

push ebx
push ecx
push edx

.read_loop:
mov eax, 10
mul dword [ebp-8]
add eax, [ebp-4]
sub eax, '0'
mov [ebp-8], eax

mov eax, 3
mov ebx, 0
lea ecx, [ebp-4]
mov edx, 1
int 0x80

cmp dword [ebp-4], 10
jne .read_loop

ret

I can call the read_integer function using call read_integer. However when I try to do the same for .read_loop using call .read_loop I get the error :

.read_loop is not defined.

What am I doing wrong?

A: the dot in .read_loop means that the label is local.
It is only visible inside the same "scope" made of 2 global labels.
global_label_1:
    code
.local_label
    code
    jne .local_label  <=== no ambiguity, the label is locally defined, jumps to the label above
global_label_2:
   code
.local_label    <=== same name but different scope
   code

It's useful because the code can be copied/pasted several times in different procedures without naming conflicts.
In your case, removing the leading dot will solved it: you want it global.
read_loop:
mov eax, 10
...
call read_loop

EDIT: some assemblers also allow to access the inner label like this: call read_integer.read_loop

A: .read_loop is not meant to be called. It's a label local to read_integer marking the start of a loop.
If you take a look at the end of read_integer you see:
cmp dword [ebp-4], 10
jne .read_loop

Which will jump back to .read_loop as long as [ebp-4] doesn't equal 10. This is similar to if you had written the following in C:
do {
  // Whatever
} while (*(ebp-4) != 10);

To be able to jump somewhere you need to specify where to jump. Hardcoding the location would be really inconvenient, so you use labels and let the assembler figure out which address that label corresponds to.
But you might only want some labels to be visible within a certain scope (e.g. within read_integer). Perhaps you want to be able to use that same label name in some other function, or perhaps you just want to make it clear to whoever is reading the code that the label is local to the function. So some assemblers provide syntax for making a label local, as described by @Jean-FrançoisFabre.
Some assemblers go one step further and allow "anonymous" labels, such as:
1:
    jmp 2f   ; f for forwards
    ; Whatever
    jmp 1b   ; b for backwards
2:

Or:
-:
    jp +  ; this is Z80 assembly, so jp isn't a typo
    ; Whatever
    jp -
+:


text:
Q: Blob MIME type incorrect for JPEG image I'm trying to fetch a local jpg image and convert to blob. The expected MIME type for the blob is "image/jpeg" but my logs are showing it is "text/html". Please let me know if I should add additional parameters to the code below to ensure it returns a blob in the correct type:
const image = fetch('../images/image.jpg')
        .then((res) => res.blob())
        .then(async(myBlob) => {
            console.log(myBlob);
            //Do stuff with myblob... should be in "image/jpeg" type but showing as "text/html"
        });


text:
Q: boto3 s3 download file, key arg seems redundant to filename I'm trying to understand why there needs to be two arguments here:

*

*key which is basically the filename

*path argument, the path of the file

Isn't it redundant to still pass the key?
Can't we just pass the bucket and the filename?

A: key in S3 could be a long string, like /my-prefix/YYYY/MM/DD/UUID.txt. It can, and usually will, contain things like slash characters. So it makes sense to have to specify the local filename argument separately, because you may not want to save the file in the same path that it is saved in S3, and you also may not want to save it using the same name that was used in S3.

A: You can download the file to the Filename which has different name than the Key from where you are downloading, e.g. Key = 'hello.txt', Filename = '/tmp/MylocalCopyOfTheHello.txt'


text:
Q: How to use netcdf in tensorflow I have two netcdf files (temperature, Humidity) and I would like to use them in a neural network to predict whether it will snow or not. The netcdfs have the format time* lat * lon*value I have a dataframe with the binary result (snow/no snow) for all times.
I have read the blog:
https://www.noahbrenowitz.com/post/loading_netcdfs/
on how to import netcdf in tensorflow but I am confused on how to use them as predictors in tensorflow with my response variable which will be a simple array.
Any idea?
if everything was in a dataframe it would look sth like (as features I created artificial data):
#Split data to test/train
labels=df['Snow']
features = df.iloc[:,2:10]
X=features
y=np.ravel(labels)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)
scaler = StandardScaler().fit(X_train)
X_train = scaler.transform(X_train)
X_test = scaler.transform(X_test)

model = Sequential()
model.add(Dense(6, activation='relu', input_shape=(8,)))
model.add(Dense(6, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy',
optimizer='sgd',
metrics=['accuracy'])
model.fit(X_train, y_train,epochs=8, batch_size=1, verbose=1)

y_pred = model.predict(X_test)
score = model.evaluate(X_test, y_test,verbose=1)


text:
Q: Login with Node.js I want to do a POST action with node.js with a command line application.
The goal is to login to http://hbeta.net
(I want to create a application that post the username and the password automaticly)
thanks ;)

A: If the website supports posting data to the login and receiving a login cookie/token back, you can use the following code:
var cloudscraper = require('cloudscraper');

cloudscraper.post('http://hbeta.net/', {
    username: 'username',
    password: 'password'
}, function(error, response, body) {
    if (error) {
        console.log("an error has occured");
    } else {
        console.log(body, response);
    }
});

This code will simply send a POST method to http://hbeta.net/ while bypassing their CloudFlare DDOS protection and send a username and password along with the request.


text:
Q: Is it possible to pass a sub-query for the Default Value when adding a new column to a table? ALTER TABLE TABLENAME
ADD New_Col3 INT NOT NULL
CONSTRAINT CONSTRAINT_1 DEFAULT {DEFAULT_VALUE}

If i am adding a new column that is not null to an existing table, is there away i can pass a t-sql sub query to provide the column's default value? Or i can only update the new column with query result value in a separate statement?
The sub-query is like below
 SELECT ID FROM dbo.Category WHERE CategoryName = N'Default Category'

A: I think you could clarify for us a bit more about what you're doing. I'm confused. This is all that I can think of...

DECLARE @sqlstring varchar(max)=''
    ,@defaultValue varchar(10)='8'

SET @sqlstring=
'ALTER TABLE TABLENAME ADD New_Col8 INT NOT NULL
CONSTRAINT CONSTRAINT_8 DEFAULT (' + (SELECT TOP 1 CAST(number as varchar(2)) FROM
                                master..spt_values WHERE number=@defaultValue)  + ')'

PRINT @sqlstring
EXEC (@sqlstring)


text:
Q: Setting error messages to English not working For some reason I cannot change the language of the error messages from PostgreSQL. I have tried to set the language inside the script for creating the schema in at the first line:
SET lc_messages TO 'en_US.UTF-8';

and I also did this, setting LC_MESSAGES to English but it didn't help. Yes, I restarted the service after changing the value.

Nothing seems to work. I am still getting my messages in German.
What else can I try?

A: if you have permission for access to $datadir\postgresql.conf, you change lc_messages parameter to 'English_United States.1252'.
After you must reload configuration.
My config settings is here;

#These settings are initialized by initdb, but they can be changed.
lc_messages = 'English_United States.1252'            # locale for system error message strings
lc_monetary = 'English_United States.1252'         # locale for monetary formatting
lc_numeric = 'English_United States.1252'          # locale for number formatting
lc_time = 'English_United States.1252'             # locale for time formatting
# default configuration for text search
default_text_search_config = 'pg_catalog.english'

A: Have you tried the following command?
initdb --locale=en_US --lc_messages=en_US

for details, please refer to http://www.postgresql.org/docs/9.0/static/locale.html


text:
Q: Developer name as client name in iTunes store We have launched an app for a client under our own company name as the developer on the App store. Our client has now asked us to change the name of the developer listed to be shown as theirs.
I've read that this can be done - BUT would this change only apply to the single client app or to ALL apps produced by us?
We are happy to agree to a change, as long as it only effects their app and not our other clients.
I understand that we have to contact Apple about this.


text:
Q: Настроить кодировку UTF-8 для git на windows7 Всех приветствую.
Помогите пожалуйста разобраться с настройкой гит для windows7.

*

*Версия git version 2.28.0.windows.1

*Терминал mintty 3.2.0

Никак не могу решить проблему вывода текста на русском языке, когда выполняю git diff и git log, в консоли отображается нечитаемый текст.

git log

Что делал (НЕ ПОМОГЛО):

*

*устанавливал кодировку в терминале mintty ru_RU.UTF-8

*настройки гит
core.quotepath=off
i18n.filesencoding=utf-8
gui.encoding=utf-8
core.pager=iconv.exe -f cp1251 -t utf-8 | less

*в переменные среды добавлял LC_ALL=ru_RU.UTF-8, LESSCHARSET=UTF-8
Команды ниже корректно отображают русские символы
less README.md

diff README.md 1.txt

gitk

A: Удалось решить вопрос (спасибо @AlexeyTen за помощь).
Чтобы корректно отображались русские символы в cmd, необходимо установить новую переменную в переменные среды через "Свойства системы"  (системные или пользователя)
LC_ALL=ru_RU.UTF-8

после этого командная строка windows7, git diff и git log должны показывать русские символы корректно.
Только почему-то утилита git bash название файлов не корректно читает.
Для гит установил такие настройки:
gui.encoding=utf-8
это заставляет gitk отображать русские символы корректно


text:
Q: iOS 10 play a Smart Playlist on iPhone Have a Smart Playlist "ALL" made of multiple simple playlists ; that was created with iTunes on a Mac. All the music comes from CDs and is locally on the Mac, and on iPhone (via sync).
After a Sync, on the iPhone (6+, latest iOS 10) the Smart Playlist "ALL" appears in Music that I'd like to play, but there's just a menu
(in "Downloaded Music")

*

*Download

*Remove

*Add to Playlist (what is that?)

Download? What is it going to Download? All the Music being already locally on the iPhone in the Library.
Must be missing something obvious, I just want to play "ALL", how can i do that?
Edit May 2017
The question was not so clear.It was actually a bug (smart playlists not syncing in iOS 10), and this answer fixed it for me. Basically

*

*go to Library in iTunes (Mac/PC side, not "My Device")

*right-click and "Duplicate" all problematic playlists

*delete the old ones, rename the duplicated ones to their old name (if you cannot stand the "1" added to the renamed playlist)

*go to your "Device" and sync the "Entire Library"

A: It seems we are talking here about possibility of creating/transferring Smart Playlists from iTunes for Mac to iPhone.
There was such a possibility back in the days, it flawlessly worked with old iPod Nano in the old iTunes, according to the apple discussions. You could configure complicated filters based on given starts for the tracks, genres, years, etc. and to generate the Smart Playlists, which allowed to play the same music with the specific order on your devices.
I checked my settings (the latest iOS and OS Sierra) - and I still have the smart playlists, so Apple haven't removed the possibility of using them. Smart playlists are present in their documentation as well. So it means it should work out of the box.
You have to make sure, you turned on the music and playlists synchronization in your iTunes:

*

*Select the Music tab in the left panel of iTunes.

*Click Sync Music at the top of the iTunes screen in order to sync music to your iPhone.

*Click the button next to Entire Music Library to sync all your iTunes music to your iPhone (Please, note, this only works if your phone's storage is bigger than your library. If it isn't, you'll get some of your music but not all of it.)

*Click the button next to Selected playlists, artists, albums, and genres to specify which music is downloaded to your iPhone. Sync playlists by checking the boxes in the Playlist section or all music by specific artists by checking the boxes in the Artists section. Sync all music in a particular genre or from a given album by clicking the boxes in the Genres and Albums sections.


text: Q: Log the log4net logs in file if the database is down Is there way to configure the log4net is such a way that, if the database is down or could not able to connect to database exceptions should log into file(only if the database is having problem). Currently i am able to write for both database and file.


text:
Q: How do I iterate through data in a panda data frame? I have created a 5 day moving average for 5 years worth of data. How do I iterate through this to show if the moving average is rising or falling for every single day. My code is simply giving me 1 integer answer rather than a rising (+1) or falling(-1) answer for every day. Thank you!
import pandas as pd

df = pd.read_csv('file:///C:/Users/James Brodie/Desktop/USDJPY.csv', header=1, index_col=0)
ma5 = df['PX_LAST'].rolling(window=5).mean()
ma8 = df['PX_LAST'].rolling(window=8).mean()
ma21 = df['PX_LAST'].rolling(window=21).mean()

ma5x = []
for i in ma5:
    if i > i-1:
        ma5x = 1
    elif i < i-1:
        ma5x = -1
    else:
        ma5x = 0

print(ma5x)

Thank you!

A: ma5 = [5,2,2,3,3,2,5]
ma5x = []
lastItem = ma5[0]
for currItem in ma5[1:]:
    if currItem > lastItem:
        ma5x.append(1)
    elif currItem < lastItem:
        ma5x.append(-1)
    else:
        ma5x.append(0)
    lastItem = currItem
print(ma5x)

gives:
[-1, 0, 1, 0, -1, 1]

The elements of a list are best represented in pandas as a Series object (put own index of choice for rows replacing list(range(len(ma5x))) with anything you need):
print('-----------')
import pandas as pd
pd_ma5x = pd.Series(ma5x, index=list(range(len(ma5x))))
print(pd_ma5x)

gives:
-----------
0   -1
1    0
2    1
3    0
4   -1
5    1
dtype: int64

Using own index be aware that pd_ma5x size is one less than that of ma5


text:
Q: My flutter stream and firebase real time database reads all documents every time a new document comes I use firebase real time database in my messaging flutter app and I read that the firebase cached documents and read only the new one but I note that it's not true and every time I write a message the stream reads all documents and firestore also calculates it and the cost is increasing so what should I do and is there any wrong in my code?
this is my code
    class MessagesStream extends StatelessWidget {
    final ScrollController _scrollController;
    MessagesStream(this._scrollController);

    @override
    Widget build(BuildContext context) {
FirebaseFirestore _firestore = FirebaseFirestore.instance;
return StreamBuilder<QuerySnapshot>(
  stream: _firestore
      .collection('messages')
      .orderBy('Timestamp')
      .limitToLast(50)
      .snapshots(),
  builder: (context, snapshot) {
    if (!snapshot.hasData) {
      return Center(
        child: CircularProgressIndicator(
          backgroundColor: Colors.lightBlueAccent,
        ),
      );
    }
    final messages = snapshot.data.docs;
    List<MessageBubble> messageBubbleList = [];
    for (var message in messages) {
      final messageText = message.get('text');
      final messageSender = message.get('sender');
      final senderUid = message.get('uid');
      final senderType = message.get('type');
      final senderImage = message.get('imageUrl');
      final currentUser =
          Provider.of<LoggedUser>(context, listen: false).loggedUser.uid;
      final messageBubble = MessageBubble(
        senderUid: senderUid,
        senderType: senderType,
        sender: messageSender,
        text: messageText,
        senderImage: senderImage,
        isMe: currentUser == senderUid,
      );
      messageBubbleList.add(messageBubble);
    }

    return Expanded(
      child: ListView.builder(
        controller: _scrollController,
        itemCount: messageBubbleList.length,
        padding: EdgeInsets.symmetric(horizontal: 10.0, vertical: 20.0),
        itemBuilder: (context, index) {
          return messageBubbleList[index];
        },
      ),
    );
  },
);
   }
   }


text:
Q: Multiple target with different display name for different language
Possible Duplicate:
XCode - Multiple targets, Multiple internationalized names?

When you create a new project with Xcode 4.2+, there is an InfoPlist.strings, you can specific different app display name for different language. For example:
InfoPlist.strings (English) - "CFBundleDisplayName" = "English Name";
InfoPlist.strings (Chinese) - "CFBundleDisplayName" = "中文";

This works fine for single target. How to display different display name for multiple target?


text:
Q: Using SVGs in Kivy I am trying to import an SVG into Kivy to create an interactive component in the page. I have succeeded in getting it on the page but am having trouble doing anything meaningful with it. I can't seem to move it where I want, size it, or change any properties. It won't fit nicely in any layout either. I was wondering if anybody who's used SVGs in Kivy before could give me some pointers. At the moment I have it set up using the class below:
class SvgWidget(FloatLayout):
    def __init__(self, **kwargs):
        super(SvgWidget, self).__init__()
        filename = 'Z:/Brendan/NIC4/CochleaGraphic.svg'
        with self.canvas:
            svg = Svg(filename)

I then use this class as a child widget in my kv lang string. I have tried almost every kivy layout and just can't figure it out. I just want to fit it into my page in a meaningful way. Please help.
Thanks!


text:
Q: Qt: checkbox single click not working I'm playing around with QtQuick in Qt 5.9 and I encountered a strange issue.
When I created two Tumblers and a CheckBox in QML everything was working fine.
But when I created an event handler for a id: secondTumbler which manipulates testCheckBox.checked status the CheckBox started to act in a strange way.
When I launch the app and firstly scroll around any tumbler and then click the CheckBox it will not check. The second click will eventually check it but that is a strange behavior.
The only thing I wrote is the below code in the main.qml:
import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 2.2

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    Tumbler {
        id: firstTumbler
        model: 10
        anchors.left: parent.left
    }

    Tumbler {
        id: secondTumbler
        model: 10
        anchors.right: parent.right

        onCurrentIndexChanged: {
                testCheckBox.checked = false
        }
    }

    CheckBox {
        id: testCheckBox
        anchors.left: firstTumbler.right

        onCheckedChanged: {
            if(testCheckBox.checked == true)
            {
                secondTumbler.currentIndex = firstTumbler.currentIndex
            }
        }
    }
}

What am I missing?

A: The issue is that javascript runs asynchronously. So, signals and slots dont work as they do in C++.  They fire along with the other code, not sequentially. This makes them an unrealiable Intermediary for logical processing since the order that events can happen can vary.
Instead,
Use property bindings for this one by setting a property  such as currentIndex  to another property created using  property var <my property> and  currentIndex: <my property>
Then you can change the value of currentIndex by setting <my property> without disrupting the flow of things.
    Tumbler {
            id: firstTumbler
            model: 10
            anchors.left: parent.left
        }

       /* Edit in response to comment #1
        */

     property bool followFirst: testCheckbox.checked

       /* end of Edit in response to comment #1 */

        Tumbler {
            id: secondTumbler
            model: 10

            /* modify the property of currentIndex  by changing this variable which will be bound to the currentIndex property */
            property var m_index: 0

            anchors.right: parent.right

           /* conditional assignment for currentIndex -- do not set currentIndex directly or this will disappear..
  instead set secondTumbler.m_index */
            currentIndex: testCheckBox.checked === true ?    firstTumbler.currentIndex : m_index

            /* ensures that changing the currentIndex does not change the     actual property, but instead changes m_index which will be bound to that property */
            onCurrentIndexChanged: {
                   m_index = currentIndex;

                  /* Edit in response to comment #1
                  */

                   if (followFirst) { testCheckBox.checked = false }

                  /* end of Edit in response to comment #1 */
            }
        }

this will allow the chckbox to change state along with the tumbler without running into state conflicts arising from the current index changing.


text:
Q: Manipulation of Input checkbox Is there anyone who can help me how can for this logic using jQuery?
I have two checkboxes in my form. Once I click the first checkbox, the second checkbox will also check and vice versa. I hope you can help me. Thank you!

A: Assuming the first checkbox has an ID of checkbox1 and the second is checkbox2, do this:
$('#checkbox1').bind('click', function() {
  $("#checkbox2").prop("checked", true);
});
$('#checkbox2').bind('click', function() {
  $("#checkbox1").prop("checked", true);
});

A: Technically this works for n checkboxes. Assign a class that links the checkboxes. When one changes state find the rest and set them to be the same.
http://jsfiddle.net/bumqH/
<input class="pair" type="checkbox" />
<input class="pair" type="checkbox" />

$('.pair').change( function() {
    $('.pair').not($(this)).prop('checked', $(this).prop('checked'));
});

A: You can (un)check both checkboxes to the state of the clicked one: http://jsfiddle.net/DVMPm/. This piece of code works for any amount, not necessarily two.
$(":checkbox").click(function() {
    $(":checkbox").prop("checked", this.checked);
});


text:
Q: What does fun keyword do in Coq? I am struggling to understand the meaning of keyword 'fun' in Coq.
There are types all and function forallb:
Inductive all (X : Type) (P : X -> Prop) : list X -> Prop :=
  | all_nil : all X P []
  | all_cons : forall (x:X) (l: list X) , P x -> all X P l -> all X P (x::l).

Fixpoint forallb {X : Type} (test : X -> bool) (l : list X) : bool :=
 match l with
| [] => true
| x :: l' => andb (test x) (forallb test l')
end.

And theorem:
Theorem all_spec: forall (X:Type) (test : X -> bool) (l: list X),
    forallb test l = true <-> all X (fun x => test x = true) l.

I understand the left part but confused on what fun is doing on the right side of the <->.

A: Isn't it simply like a lambda, i.e., isn't here fun x => ... simply like \x -> ... in Haskell?
There is another interesting peculiarity of that fun ... in your code. The type of the result of that function in your code must be proposition (Prop), not boolean. The expression test x = true must be of that type, so we conclude that = in coq denotes propositions about equality, not the boolean binary operation (which is known as == in Haskell; we don't see this from your example, but perhaps coq's notation is similar).
So, although the idea of this fun ... is just a lambda, it is a bit unusual from Haskell's point of view, because here it introduces a function operating on type-level (the result type is Prop), not value-level (only the latter must be possible--or at least the usual usage--for \ x-> ... in Haskell). coq's Prop is on the same level as * in Haskell, isn't it?
And all X P in this code is like a type constructor (well, a parameterized family of type constructors) in Haskell, but a dependent one, of type [X] -> * (in Haskell's notation). all_nil and all_cons are like data constructors for this new type.


text:
Q: How to prevent html div from expanding when text size is changed So, I have a navigation bar.  I want each link text to grow and bold when on hover.  I have achieved this using css, but now whenever teh mouse hovers over the link the text size grows,b ut so does the div to accomodate that text. Any ideas on how to fix this.  Here is the jsfiddle link:
jsfiddle
CODE:
    <!DOCTYPE html>

Home

Our Team

Gallery

Community

FIRST

#navigation{
    background-color:black;
    width:98%;
    font-family:calibri;
    padding:1%;
    margin-left:0px;
    position:absolute;
    top:0;
    left:0;
    display:block;
}
#nav{
    list-style-type:none;
}
ul#nav li{
    float:left;
    padding:0 6%;
}
.navlink{
    display:block;
    background-color:black;
    text-decoration:none;
    color:white;
}
.navlink:hover{
    font-weight:bold;
    font-size:14pt;
}

A: Add a max-height: 30px; to #navigation.
In general, if you are looking for something that transform shape/size aesthetically, it's easier to work with min/max width in pixels, rather then %.

A: To fix the horizontal pushing:
Instead of using padding to space the items apart, one solution is to use width and text-align: center; so that the items don't push the other items after them.
To fix the vertical pushing:
One solution is to specify a line-height equal to the largest font-size (which would be your :hover size)

#navigation{
    background-color:black;
    width:98%;
    font-family:calibri;
    padding:1%;
    margin-left:0px;
    position:absolute;
    top:0;
    left:0;
    display:block;
}
#nav{
    list-style-type:none;
}
ul#nav li{
    float:left;
    width: 15%;
    text-align: center;
}
.navlink{
    display:block;
    background-color:black;
    text-decoration:none;
    color:white;
    line-height:14pt;
}
.navlink:hover{
    font-weight:bold;
    font-size:14pt;
}
<!DOCTYPE html>

Home

Our Team

Gallery

Community

FIRST


text:
Q: else statement is ignored in react when i am trying to perform this task to change password, everything works fine if the response is 200 and it also gives me the pop up window, but if its not it dosent perform the else statement,it like no else. completely ignored.
here is the code
const submitForm = () => {

    let form_data = new FormData();
    form_data.append('old_password', formValues.oldpass);
    form_data.append('new_password', formValues.newpass);
    try {
        axios.put(baseUrl + '/change-password/', form_data,
            {
                headers: {
                    'Authorization': `Token ${token}`
                }
            }

        ).then((response) => {
            const Swal = require('sweetalert2');
            console.log(response.data);
            if (response.status === 200) {

                Swal.fire(
                    'Great!',
                    'Password updated successfully',
                    'success'
                )
            }
            else {
                alert('error ', 'password has not been changed !!');
            }

        });
    } catch (error) {
        console.log(error);

    }
};

please help i am new to react and i`ve had this issue for days.

A: Axios throws the response if the status code is something else than 2xx. Which means that if you get e.g. 4xx or 5xx the then clause is not run. Instead you need a catch clause that will handle this case.
.then((response) => {
    const Swal = require('sweetalert2');
    console.log(response.data);
    Swal.fire('Great!', 'Password updated successfully', 'success')
}).catch((response) => {
    alert('error ', 'password has not been changed !!');
    console.log(error);
});

In this case you can remove try-catch as it won't catch any errors.
Optionally you can await the result of the axios call to have the current catch clause catch the error. Then you'll also need the function to be async.
const submitForm = async () => {
    let form_data = new FormData();
    form_data.append('old_password', formValues.oldpass);
    form_data.append('new_password', formValues.newpass);
    try {
        await axios.put(baseUrl + '/change-password/', form_data,
            {
                headers: {
                    'Authorization': `Token ${token}`
                }
            }
        ).then((response) => {
            const Swal = require('sweetalert2');
            console.log(response.data);
            Swal.fire('Great!', 'Password updated successfully', 'success')
        });
    } catch (error) {
        console.log(error);
        alert('error ', 'password has not been changed !!');
    }
};

https://axios-http.com/docs/handling_errors


text:
Q: UILongPressGestureRecognizer not working after archiving application When testing in iPad, I can successfully call the method attached to UILongPressGestureRecognizer in UILabel.
After I have archived the application for Enterprise deployment, UILongPressGestureRecognizer does not work anymore.
I have already added the following codes aside from manually ticking User Interaction Enabled:
In .h file:
@interface BGMSetMenuViewController : UIViewController <UIGestureRecognizerDelegate>

In .m file:
- (void)viewDidLoad
{
    [super viewDidLoad];

    itemPriceLabel.userInteractionEnabled = YES;
    itemNameLabel.userInteractionEnabled = YES;

    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressSetMenuPrice:)];
    longPress.delegate = self;
    [itemPriceLabel addGestureRecognizer:longPress];
}

#pragma mark - UILongPressGestureRecognizerDelegate

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
  return YES;
}

- (void)longPressSetMenuPrice:(UILongPressGestureRecognizer*)gesture
{
  if (gesture.state == UIGestureRecognizerStateEnded) {

    BGMPasscodeViewController *passcodeVC = [[BGMPasscodeViewController alloc] initWithNibName:@"BGMPasscodeViewController" bundle:nil];
    self.providesPresentationContextTransitionStyle = YES;
    self.definesPresentationContext = YES;
    [passcodeVC setModalPresentationStyle:UIModalPresentationOverCurrentContext];
    [self presentViewController:passcodeVC animated:YES completion:nil];

  }
}

Anybody here who have the same experience?
Please note that this was working in Xcode 7 and iOS 9.
Now, I'm using Xcode 8 and testing in iOS 10.0.2 and it doesn't work anymore.

A: Try below code:set YES to label userIntractionEnabled also in storyboard
- (void)viewDidLoad {
[super viewDidLoad];
labelTouch.userInteractionEnabled = YES;
[self labelLongPressed:labelTouch];}

- (void)labelLongPressed:(UILabel *)label{
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]
                                     initWithTarget:self action:@selector(handleLongPress:)];
longPress.minimumPressDuration = 2; //seconds
longPress.delegate = self;
[label addGestureRecognizer:longPress];}

-(void) handleLongPress : (UITapGestureRecognizer *)sender{
  UIButton *button = (UIButton *)sender.view;
   NSLog(@"longpress");}


text:
Q: How to monitor remote Linux machines and retrieve installed software in Perl? I have a couple of Perl scripts that allow me to monitor remote Windows machinses through WMI. Right now I can check CPU usage, Memory usage, Disk usage and Installed Software. But what if I want to do the same job on a remote Linux machine? Ofcourse there's no WMI so I guess I shall use something similar. I have read on another old StackOverflow question that Linux exposes informations through /proc and /sys but can I query them from a remote computer? And how can I do that exactly in Perl? Is there a dedicated module?
EDIT: Just to clarify, the script MUST be agent-free.

A: Check these :
http://www.net-snmp.org/docs/mibs/host.html
http://www.oidview.com/mibs/0/RFC1213-MIB.html
This will give you memory / disk usage :
snmptable -v1 -c public localhost hrStorageTable
snmptable -v1 -c public localhost .1.3.6.1.2.1.25.2.3

This will give you processor utilisation :
snmptable -v1 -c public localhost hrProcessorTable
snmptable -v1 -c public localhost .1.3.6.1.2.1.25.3.3

Interface Status :
snmptable -v1 -c public localhost ifTable
snmptable -v1 -c public localhost .1.3.6.1.2.1.2.2

If you use rpm-based linux, this will give you installed software :
snmptable -v1 -c public localhost hrSWInstalledTable
snmptable -v1 -c public localhost .1.3.6.1.2.1.25.6.3

You can make this work for .deb flavours of linux :
http://community.zenoss.org/blogs/zenossblog/2009/02/18/tip-of-the-month-snmp-software-inventory-for-debian-and-ubuntu-machines
Sample output of `snmptable -v1 -c public localhost hrProcessorTable`

        hrProcessorFrwID hrProcessorLoad
 SNMPv2-SMI::zeroDotZero              54
 SNMPv2-SMI::zeroDotZero              22

On the box you are querying, does public have read access to .1.3.6.1.2.1.25  ?
You may need to add something like this to your /etc/snmp/snmpd.conf
com2sec monitor  default         monitor

group monitorGroup v1      monitor
group monitorGroup v2c     monitor

view hardware included .1.3.6.1.2.1.25
view hardware included .1.3.6.1.2.1.2

access monitorGroup ""      any       noauth    exact  hardware    none    none

The restart snmpd
Then specify -c monitor in the commands above instead of -c public

A: I don't think so, perhaps you can use Net::SSH to access these files, but I think it would make more sense if you install snmp agent and use Net::SNMP for the purpose.
Monitoring installed software may get trickier, will depend on the linux distribution and will probably be easiest over ssh.
EDIT: Ignore the snmp part, since you want to be agent-free.


text:
Q: Complie Boost.Python code error: library not found for -lpython3.6m I have an example code of Boost.Python
#include <boost/python.hpp>

char const* greet()
{
    return "hello, world";
}

BOOST_PYTHON_MODULE(hello_ext)
        {
                using namespace boost::python;
                def("greet", greet);
        }

And I compiled it with specifying Python3
g++ -o hello_ext.so -O2 hello.cpp -std=c++11 -fPIC -shared \
-Wall -Wextra `python3.6m-config --includes --libs` \
-lboost_python3

But I got the error
ld: library not found for -lpython3.6m
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Python: Python3.6 on /Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6
Boost.Python: Installed using brew install boost-python --with-python3
The output of python3.6m-config --includes --libs is
-I/Library/Frameworks/Python.framework/Versions/3.6/include/python3.6m -I/Library/Frameworks/Python.framework/Versions/3.6/include/python3.6m
-lpython3.6m -ldl -framework CoreFoundation

How can I compile my code by specifying python3 and boost.python3?

A: Check the directory provided by python3.6m-config --ldflags, make sure libpython3.6m.dylib is there. If so, add the options for the above command to your compiler invocation.
If it's not there, you need to build Python with --enable-shared.


text:
Q: How to Create ManyToMany Through Model without Keys in Django? I have 3 tables:
Table A
Table B
Table C
Table A has a foreign key to Table B.  Table C has a foreign key to Table B.  So B acts as an intermediary through table, but it does not have any foreign keys to A or C itself, so I cannot declare a ManyToManyField from A to C in the conventional way, but I would like to do so in order to use prefetch_related when grabbing C records from A.  Is there a way to do this?


text:
Q: How to run stash in Github Desktop? How do you run stash in GitHub Desktop on Windows?
The feature is available in Sourcetree but I'm unable to find it in GitHub Desktop.

A: Now, with the Github Desktop 2.0 version, Rebase, and Stash features are available. More info can be found here

A: GitHub Desktop for Windows doesn't support stash. The only stash-like feature it has is that it will allow you to switch branches if you have uncommited changes. Source
Update: GitHub Desktop V2.0.0 now supports stash (Issue 6107). Now when switching branches, you'll be prompted to either leave your changes on the current branch (stash) or bring your changes over to the other branch.

A: For those who are using Android Studio, no need for Github Desktop version in switching between branches, just switch from the Android Studio itself

select the branch you want to switch to > Rebase onto

PS: The Android Studio notify you with Rebase failed error (if you
  have created files in the branch you are on) and you will have to
  remove them by clicking on View themRetry then select them all and
  delete with the red - sign button, then do a Rebase onto again.

A: I realize this question is a bit old, and Andrew is correct, but I would like to point out that GitHub Desktop does at least provide a shortcut to a command prompt via Repository>Open in Command Prompt which you can then use to execute git stash through the traditional git CLI commands.  Still, frustrating that GitHub Desktop doesn't provide a clean way to do this via their GUI, forcing you to fallback to git CLI tools for stashing.
UPDATE!:  Github Desktop apparently updated and can now stash by switching to another branch with uncommitted changes.  You will automatically be asked if you want to leave your changes on the current branch(stash) or bring them to the other branch:
Then when going back to the branch later, the you can restore from the stash, or discard them:


text:
Q: At which point of destructor call the object ceases to exist? When a destructor of an object is called, at which point does the object cease to exist?
Does it happen in the moment when its called? or after it finishes deleting the memory of the object's members inside the function?
I'm mainly asking it in order to understand if it's legal to call an object's function inside its destructor or not

A:
At which point of destructor call the object ceases to exist?

The lifetime of the object is ended by the call to its destructor. Within the destructor body, the sub-objects are still alive and member functions may be called. After the destructor body, the sub objects are destroyed.

if it's legal to call an object's function inside its destructor or not

It is legal.
Note however that calling a virtual function works differently than one might expect.

A: We can say that the memory is freed after the destructor function itself has finished executing. See C++ destructor: when the memory gets freed?
However, if not strictly necessary for the deallocation of objects, avoid adding additional logic inside the destructor.


text:
Q: mysql special characters in password I was having trouble with a mysql account, and I eventually narrowed it down to the user's password, which contained the substring '\Y'.
If I create a user with that password, I can't log in with it:
mysql> create user 'test'@'localhost' identified by '\Y';
Query OK, 0 rows affected (0.00 sec)

mysql> exit
Bye

$ mysql -u test -p
Enter password:
ERROR 1045 (28000): Access denied for user 'test'@'localhost' (using password: YES)

This happens on two different machines and two different mysql versions.
mysql  Ver 14.14 Distrib 5.5.37, for debian-linux-gnu (x86_64) using readline 6.3
mysql  Ver 14.14 Distrib 5.6.19, for osx10.9 (x86_64) using  EditLine wrapper

Any clues why this is happening?

A: The sequence '\Y' when you created the user is simply 'Y'. So that user's password is "Y".
In MySQL string literals, only certain backslash-codes have any special meaning. "\n" for example is a newline. When you put a backslash before most characters, it has no special meaning, it's just the same literal character. So a "\Y" is simply "Y".
If you want a literal backslash as part of the password, you need to escape the backslash.  So to create a password that is the two characters "\Y" you need to:
mysql> create user 'test'@'localhost' identified by '\\Y';

Then when you type the password, use one backslash. Backslash has no meaning at all when typing passwords interactively, so there is no need to escape it.


text:
Q: argv error when integrating MWFeedParser I am trying desperately to integrate MWFeedParser in my application. My application uses storyboards, and one UIviewController should show the table view with the RSS. I copied all the files from the MWfeedParser to my project by drag and drop. I then added them to the compile source section and made sure that they where compatible to ARC. Then in my stroyboard I dragged a UITableViewController and set it to RootViewController class.
The result:
as soon as the app launches I get this error:

I get the error even if there is no UITableViewcontroller in the storyboard linked to that class. Any ideas?


text:
Q: How can I override internal style or button in Firebase? I would like override the Google Login button showed in Firebase UI for Android.
In FirebaseUI-Android/auth/src/main/res/values/styles.xml there is
 <style name="FirebaseUI.Button.AccountChooser.GoogleButton">
    <item name="android:drawableLeft">@drawable/logo_googleg_color_18dp</item>
    <item name="android:background">@drawable/idp_button_background_google</item>
    <item name="android:textColor">#757575</item>
  </style>

and in FirebaseUI-Android/auth/src/main/res/layout/idp_button_google.xml is:
 <Button
   xmlns:android="http://schemas.android.com/apk/res/android"
   style="@style/FirebaseUI.Button.AccountChooser.GoogleButton"
   android:text="@string/sign_in_with_google"
   android:id="@+id/google_button"
 />

I would like to change the background color of GoogleButton in my app, I was thinking to override the style or change by code the background in some way.
Any suggestion?
https://github.com/firebase/FirebaseUI-Android


text:
Q: Java or C# to linux based mysql database I'm creating a system for one of my university projects.
Basically, what i'm trying to do is to query a MySQL database stored on a linux web server. I am creating two interfaces, one to register using the a php webpage. The php one is simple enough, and I know what I am doing in regards to that.
The problem I am having is my c# or java (depends which is easiest to do this) application running on my machine, I want either of these applications to query the mySQL server to retrieve data. I know the java or .connectors is not a viable option, so is this possible.
Maybe be running a php script using my application and then parsing the results. Is this possible, and if so any information will be glady accepted.
Thanks

A: Considering the security implications that directly querying MySQL within a standalone application, it's highly unpractical to do such a thing. Anything that can be downloaded can theoretically be decompiled. I highly suggest you use your C# application to WebRequest a PHP script that can complete your queries and echo the results. Then you can use your C# app to interpret this data. It's also much more secure to have specific scripts that do specific things, instead of allowing you to directly enter a query, you instead Web Request your script associated to such a query.
Hope this helps.


text:
Q: Permitting cleartext HTTP traffic from Android App in very limited circumstances I have read Android 8: Cleartext HTTP traffic not permitted, but none of the answers appear to allow me to do what I want.
I have an Android application where another client can identify itself with a certificate.  The application wants to verify that certificate.  Part of verifying the certificate is fetching the certificate revocation list (CRL) from the certificate issuer.  The distribution point(s) for the CRL is(are) listed in the certificate, and is inevitably an HTTP URL (the CRL itself is signed by the issuer so there is no security issue, and if it was an HTTPS URL, one would want to verify the certificate protecting the CRL distribution point, and check if it had been revoked ...)
Possible solutions, and why they don't work for me:

*

*Don't worry about it - let the TLS library worry about validating the certificate.  Unfortunately, there is no direct TLS connection between the two clients; it is all mediated through a server (which is connected to by TLS).

*Create network_security_config.xml which lists the domains to which HTTP is allowed.  Sadly, I don't know the URLs when I build the application - it depends on what the CA decides to put in their certificates.

*Put android:usesCleartextTraffic="true" in the manifest.  This means that any traffic can be HTTP, and I would rather avoid that if possible.  (As an example, communication with the server absolutely must be HTTPS, and I would like an error if I do HTTP by accident.)

Is there any way for the code to say "this connection is allowed to be HTTP" (but default to HTTPS only)?

A: If you're using OkHttp, you can construct a client as such:
OkHttpClient client = new OkHttpClient.Builder()
.connectionSpecs(Arrays.asList(ConnectionSpec.MODERN_TLS, ConnectionSpec.COMPATIBLE_TLS))
.build();

This will only allow connections through HTTPS. So then, you can use your third option (android:usesCleartextTraffic="true") and when you make a cleartext connection through this client, it will fail.
Finally, you can create a standard OkHttp client:
OkHttpClient client = new OkHttpClient.Builder().build()

when you want to use the cleartext connection.
EDIT: Using HttpUrlConnection, you can simply check if the returned connection is a HttpsUrlConnection, like:
try {
    URL my_url = new URL(path);
    HttpUrlConnection urlConnection = (HttpURLConnection) my_url.openConnection();
    if(!(urlConnection instanceof HttpsURLConnection)) {
        // cleartext connection, throw error
        throw new NotHttpsException();
    }
    // the connection is secure, do normal stuff here
    urlConnection.setRequestMethod("POST");
    urlConnection.setConnectTimeout(1500);
    urlConnection.setReadTimeout(1500);
    result = IOUtil.readFully(urlConnection.getInputStream());
} catch(Exception e) {
    e.printStackTrace()
} finally {
    if(urlConnection != null) urlConnection.disconnect();
}

A: The documentation on NetworkSecurityPolicy.isCleartextTrafficPermitted() says

This flag is honored on a best effort basis because it's impossible to prevent all cleartext traffic from Android applications given the level of access provided to them. For example, there's no expectation that the Socket API will honor this flag because it cannot determine whether its traffic is in cleartext.

So maybe this is an option for you: fetch the CRL using a Socket. There is a post by Daniel Nugent describing how to set up a simple TCP client

A: Tha app has a TLS connection with the server.
You can ask the server to hand off those CRL urls to you (It is handing off the certificate in the first place right?).
It could even do it before hand and provide the Certificate together with the CRLs.
In this way you get the CRLs without loosing the https lock nor having to make exceptions.


text:
Q: Iterate Over Pandas DataFrame and Store Results I have a DataFrame which looks like this:
columns = ['C24H31O8', 'C23H27O9', 'C22H23O10', 'C21H19O11', 'C20H15O12','C19H11O13']

values= [[   0.,   37.,   74.,  111.,  148.,  185.],
         [ -37.,    0.,   37.,   74.,  111.,  148.],
         [ -74.,  -37.,    0.,   37.,   74.,  111.],
         [-111.,  -74.,  -37.,    0.,   37.,   74.],
         [-148., -111.,  -74.,  -37.,    0.,   37.],
         [-185., -148., -111.,  -74.,  -37.,    0.]]

You can easily recreate my dataframe by using
df = pd.DataFrame(data=values, index=columns)

I want to iterate over my dataframe as follows:
While iterating, in row C24H31O8 you find 37 in column number 1. Now, go to row number 1 and iterate again. If you again find number 37 - in this case you find 37 in the third column - go to the third row and again search for 37 etc.
My desired output should be a chain:
37 : C24H31O9 --> C23H27O9 --> C22H23O10 --> C21H19O11 ...

(do something for every value)

A: This should work, if I understand the question correctly:
columns= pd.Index(['C24H31O8', 'C23H27O9', 'C22H23O10', 'C21H19O11', 'C20H15O12','C19H11O13'],dtype='object')

values=np.array([[   0.,   37.,   74.,  111.,  148.,  185.],
               [ -37.,    0.,   37.,   74.,  111.,  148.],
               [ -74.,  -37.,    0.,   37.,   74.,  111.],
               [-111.,  -74.,  -37.,    0.,   37.,   74.],
               [-148., -111.,  -74.,  -37.,    0.,   37.],
               [-185., -148., -111.,  -74.,  -37.,    0.]])

df = pd.DataFrame(values, columns)

def build_string(df, i):
    row = 0
    chain = df.index[0]
    while True:
        try:
            row = df.iloc[row][df.iloc[row] == i].index[0]
            chain += f"--> {df.index[row]}"
        except IndexError:
            break
    return chain

Output:
>>> build_string(df, 37)
'C24H31O8--> C23H27O9--> C22H23O10--> C21H19O11--> C20H15O12--> C19H11O13'

or
>>> {int(i): build_string(df, i) for i in df.iloc[0] if i > 0}
{37: 'C24H31O8--> C23H27O9--> C22H23O10--> C21H19O11--> C20H15O12--> C19H11O13',
 74: 'C24H31O8--> C22H23O10--> C20H15O12',
 111: 'C24H31O8--> C21H19O11',
 148: 'C24H31O8--> C20H15O12',
 185: 'C24H31O8--> C19H11O13'}

A: IIUC:
df = pd.DataFrame(values, columns = columns)
s = df.where(df>0).stack()
out_dict = s.index.get_level_values(1).groupby(s)

Output (out_dict):
{37.0: Index(['C23H27O9', 'C22H23O10', 'C21H19O11', 'C20H15O12', 'C19H11O13'], dtype='object'),
 74.0: Index(['C22H23O10', 'C21H19O11', 'C20H15O12', 'C19H11O13'], dtype='object'),
 111.0: Index(['C21H19O11', 'C20H15O12', 'C19H11O13'], dtype='object'),
 148.0: Index(['C20H15O12', 'C19H11O13'], dtype='object'),
 185.0: Index(['C19H11O13'], dtype='object')}


text:
Q: How to get the row of the matched statement? I am grabbing a feed from API and and here I want to get the row that starts with ,,[[,2 . Please help me how can I do that ?

A: The RegExp that I came up with in PHP is:
$s = ',,[[,2thesecretoflife';
$r = preg_match('/^,,\\[\\[,2/', $s);

if ($r) {
  echo 'works';
}

Basically, you have to double escape the [s to get them to be interpreted properly. I'm sure that whatever language you are using would be similar.


text:
Q: Como filtrar uma lista de forma assíncrona usando LINQ? Exemplo de código sem o uso do async:
var products = db.Products.Where(_ => _.UserId == currentUserId);

Como faço para tornar essa consulta assíncrona levando em conta que o Where do Linq não suporta o uso do await?

A: O método Where constrói um objeto que representa uma query a ser executada, sendo que nenhuma query foi executada ainda. Por isso não faz sentido que o método Where seja executado assincronamente.
O que você deve estar procurando é a execução assíncrona do método que executa de fato a query. Diz-se que estes métodos materializam a query. Um exemplo é o método ToList, que transforma o objeto que representa a query em uma lista de objetos materializados.
O método ToList possui uma versão que pode ser chamada assincronamente: ToListAsync, que permite o uso da palavra chave async o que fará a materialização dos objetos de forma assíncrona.
// criando objeto que representa uma query, mas que não executa a mesma
var productsQuery = db.Products.Where(_ => _.UserId == currentUserId);

// materializando a query, ou seja, obtendo os resultados, de forma assíncrona
var products = await productsQuery.ToListAsync();

A título de informação suplementar, também é possível fazer isso na hora de salvar os dados. O método SaveChanges possui também um alter-ego assíncrono SaveChangesAsync:
// salvando as alterações feitas no context
db.SaveChangesAsync();

A: O truque está na hora de compôr a lista:
var products = await db.Products.Where(_ => _.UserId == currentUserId).ToListAsync();

Veja todos os métodos assíncronos por este link aqui.


text:
Q: browserify 'require' placement Usually all dependencies are required in the head of the file.
var Backbone = require('backbone');
var $ = require('jquery');

I wonder if it is correct to require in code body. Example:
template: require('./home.tpl.hbs'),
module.exports = Backbone.View.extend({

template: require('./home.tpl.hbs'),

render: function () {
...
        return this;
    }
});

A: It's going to work, but require function is taken from nodejs world (CommonJS modules) and you can read about best practices in its usage here. So my point is that you need to add local variable at the beggining of the file and then use it wherever you want.


text:
Q: Peskin & Schroeder's QFT book page 161 I am trouble with below derivation in Peskin & Schroeder's QFT book on page 161. At the bottom of this page,
$$
\begin{aligned}
\operatorname{tr}\left[\not p^{\prime} \gamma^{\mu} \not k \gamma^{\nu} \not p \gamma_{\nu} \not k \gamma_{\mu}\right] &=\operatorname{tr}\left[\left(-2 \not p^{\prime}\right) \not k(-2 \not p) \not k\right] \\
&=\operatorname{tr}\left[4 \not p^{\prime} \not k(2 p \cdot k- \not k \not p)\right] \\
&=8 p \cdot k \operatorname{tr}\left[\not p^{\prime}  \not k\right] \\
&=32(p \cdot k)\left(p^{\prime} \cdot k\right) .
\end{aligned}
$$
I am really troubled for the last step derivation, I thought the last coefficient should be 8, not 32, the reason is that
$$
\begin{aligned}
\operatorname{tr}[\not p^{\prime} \not k]&=\operatorname{tr}[p^{\prime}_{\mu}\gamma^{\mu}k_{\nu}\gamma^{\nu}]\\
&=\operatorname{tr}[p^{\prime}_{\mu}k_{\nu}(2g^{\mu \nu}-\gamma^{\nu}\gamma^{\mu})]\\
&=\operatorname{tr}[2p^{\prime}\cdot k-\not k \not p^{\prime}] \\
&=2p^{\prime}\cdot k - \operatorname{tr}[\not p^{\prime} \not k]
\end{aligned}
$$
so we can see that $$\operatorname{tr}[\not p^{\prime} \not k]=p^{\prime}\cdot k,$$ so in the last line, the coefficient should be still 8. Would you have some comment on this?

A: Your second calculation is wrong. Basically because you have to be a little bit more careful what you are taking the trace of! You use the anti-commutation relations for the Dirac matrices, which is commonly written down like
$$
\{\gamma^\mu, \gamma^\nu\} = 2 g^{\mu\nu},
$$
which is actually a bit sloppy. There is a $\mathbb I$ missing. You can easily see this observing that on the left there are matrices (which are entries of a 4-vector) and on the right there is only an entry of a tensor so there must be the identity.
Hence you end up with
$$
\text{tr}(\gamma^\mu \gamma^\nu) = \text{tr}(\{\gamma^\mu, \gamma^\nu\} - \gamma^\mu \gamma^\nu) = \text{tr}(2g^{\mu\nu}\mathbb I) -\text{tr}(\gamma^\mu\gamma^\nu)
$$
$$
\implies\text{tr}(\gamma^\mu\gamma^\nu) = \frac{2}{2} \text{tr}(g^{\mu\nu} \mathbb I)=4g^{\mu\nu}
$$
See also chapter 3.2 in "An Introduction to Quantum Field Theory" by M. Peskin and D.Schröder. (In my edition it is page 40)


text:
Q: how to make origin marker to bounce in directionsDisplay without using suppressmarkers:true? I have developed a route for 2 places using Google Maps Api .... Now I need that the origin marker A should be bounced but i don't want to make suppressMarker value to true ... I also don't want to add custom markers... Is there any way to make the default marker rendered by directionsDisplay itself to be bounced?

A: You can change standart markers with letters to any other markers from google-chart service.
Let me show you how add some text on the marker:
    directionsDisplay = new google.maps.DirectionsRenderer({
         markerOptions: { icon: "https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=SomeText|FF0000|000000" }
    }),

or, you can take any other idea about change marker's look from there: https://developers.google.com/chart/image/docs/gallery/dynamic_icons?hl=fr&csw=1#plain_pin


text:
Q: Apply function to variable size list in R I have a list of files that group together by day (example list below) and want to read each one into a dataframe and bind them together. I'm currently stuck finding a way to avoid the "manual" my_files reference as the my_files list could sometimes have more than two days and this would break. Any ideas?
my_files <- list(c("file1_day0.txt", "file2_day0.txt"), c("file3_day3.txt", "file4_day3.txt"))

df <- rbind(lapply(my_files[[1]], create_activation_df) %>%
                purrr::reduce(dplyr::left_join, by = c("date",
                                                       "experiment")),
              lapply(my_files[[2]], create_activation_df) %>%
                purrr::reduce(dplyr::left_join, by = c("date",
                                                       "experiment")))

A: Another layer of lapply is what you need. This is obviously untested with no reproducible example shared, but it should get the point across:
df <- bind_rows(
  lapply(my_files, \(x) {
    lapply(x, create_activation_df) %>%
      purrr::reduce(dplyr::left_join, by = c("date", "experiment"))
  }
)


text:
Q: Why does su fail with "authentication error"? I tried to su to root so I could install lights, but I get an authentication error when I try:
user@host:~$ su
Password:
su: Authentication failure

A: Use sudo your_command in place of su. ie
sudo apt-get install "program to install"

A: The root account is disabled by default in Ubuntu, so there is no root password, that's why su fails with an authentication error.
Use sudo to become root:
sudo -i

A: If su doesn't work, I do this (in bash):
user@host:~$ sudo bash
root@host:~# su
root@host:/home/user#

Voila! You are now root!
A shortcut for this would be sudo su. In this case given that you are a member of /etc/sudoers with all privileges, then you would only need your user's password.

A: You are getting Authentication failure because you are trying to become root which is disabled by default in all versions of Ubuntu. This can be easily circumvented in two ways:

*

*Enabling the root account. This can be achieved by setting up a password.

*Instead of su use sudo -i or better yet, append to any command sudo in the way of:
sudo apt-get update
[sudo] password for braiam:

I wouldn't recommend enabling root, since it could raise a security concern, for example, if you use any service exposed to the web.

A: Open root with sudo -s and when it's in this mode type:

passwd

Then, choose password. This password will be for su command.