Q: How to drill down data in one single click in excel? I have a year progress table, and one of the columns include (+) Sign, what I want is when I click on (+)
the rows from number 8 till 15 will drill down the data (Show Data) and the (+) sign in this case will be (-) Sign and, re click on (-) sign to drill up data (Hide data) and the (-) comes (+) again. I want this formula to be applicable in each row of entire table. Note: The problem with my code is only done for one row but i want for all , so is  there any simple eay to make for all rows.
The Table when rows is Hidden
The Table when rows is Appeared

Trying Code

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

If Not Intersect(Target, Range("O:O")) Is Nothing And Target.Cells.CountLarge = 1 Then

If Range("A8:R15").EntireRow.Hidden = True Then

    Range("A8:R15").EntireRow.Hidden = False

Else
    Range("A8:R15").EntireRow.Hidden = True
End If
End If
End Sub

Update
Screenshot after using the correct Code

A: I's use the double-click event here: otherwise it's a bit awkward needing to click out of the cell and back again to reverse the hide/unhide.
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
    Dim rng As Range
    'exit if not in monitored column
    If Intersect(Target, Me.Range("O:O")) Is Nothing Then Exit Sub
    'check for +/-
    If Target.Value = "+" Or Target.Value = "-" Then
        Set rng = Target.Offset(1, 0).Resize(8).EntireRow
        rng.Hidden = Not rng.Hidden
        Target.Value = IIf(rng.Hidden, "+", "-") 'reset cell text
        Cancel = True 'don't enter edit mode in the clicked cell
    End If
End Sub


Q: Loading JSON data into pandas data frame and creating custom columns Here is example JSON im working with.
{
    ":@computed_region_amqz_jbr4": "587",
    ":@computed_region_d3gw_znnf": "18",
    ":@computed_region_nmsq_hqvv": "55",
    ":@computed_region_r6rf_p9et": "36",
    ":@computed_region_rayf_jjgk": "295",
    "arrests": "1",
    "county_code": "44",
    "county_code_text": "44",
    "county_name": "Mifflin",
    "fips_county_code": "087",
    "fips_state_code": "42",
    "incident_count": "1",
    "lat_long": {
      "type": "Point",
      "coordinates": [
        -77.620031,
        40.612749
      ]
    }

I have been able to pull out select columns I want except I'm having troubles with "lat_long". So far my code looks like:
# PRINTS OUT SPECIFIED COLUMNS
col_titles = ['county_name', 'incident_count', 'lat_long']
df = df.reindex(columns=col_titles)

However 'lat_long' is added to the data frame as such: {'type': 'Point', 'coordinates': [-75.71107, 4...
I thought once I figured out how properly add the coordinates to the data frame I would then create two seperate columns, one for latitude and one for longitude.
Any help with this matter would be appreciated. Thank you.

A: If I don't misunderstood your requirements then you can try this way with json_normalize. I just added the demo for single json, you can use apply or lambda for multiple datasets.
import pandas as pd
from pandas.io.json import json_normalize
df = {":@computed_region_amqz_jbr4":"587",":@computed_region_d3gw_znnf":"18",":@computed_region_nmsq_hqvv":"55",":@computed_region_r6rf_p9et":"36",":@computed_region_rayf_jjgk":"295","arrests":"1","county_code":"44","county_code_text":"44","county_name":"Mifflin","fips_county_code":"087","fips_state_code":"42","incident_count":"1","lat_long":{"type":"Point","coordinates":[-77.620031,40.612749]}}

df = pd.io.json.json_normalize(df)
df_modified = df[['county_name', 'incident_count', 'lat_long.type']]
df_modified['lat'] = df['lat_long.coordinates'][0][0]
df_modified['lng'] = df['lat_long.coordinates'][0][1]
print(df_modified)

A: Here is how you can do it as well:
df1 = pd.io.json.json_normalize(df)

pd.concat([df1, df1['lat_long.coordinates'].apply(pd.Series) \
  .rename(columns={0: 'lat', 1: 'long'})], axis=1) \
  .drop(columns=['lat_long.coordinates', 'lat_long.type'])


Q: Realizing closed manifolds as Legendrian submanifolds of the standard contact vector space I started learning some basic contact geometry, in particular its flexible side, and I got stuck with the following naive question. Given a closed manifold of dimension $n$, we can always embed it into $\mathbb R^{2n+1}$, say by Whitney embedding theorem. I wonder whether this manifold can always be "approximated" by some loose Legendrian submanifolds there. In other words, I wonder whether every closed $n$-manifold admits a Legendrian embedding into $\mathbb R^{2n+1}$, maybe even with some controlled classical invariants like Maslov class (say, 0) and Thurston-Bennequin number.

A: There are obstructions:  For example, if $N^n\subset\mathbb{R}^{2n+1}$ is a Legendrian submanifold, then $\nu$, the normal bundle of $N^n$, is isomorphic to $\tau\oplus TN$, where $\tau$ is the trivial bundle.  Thus, $\tau\oplus TN\oplus TN$ is isomorphic to $\nu\oplus TN$, which is trivial.  In particular, it follows that the total Stiefel-Whitney and Pontrjagin classes of $TN$ must square to zero.
Since this doesn't happen for, say, $N=\mathbb{CP}^{2}$, it follows that $\mathbb{CP}^2$ cannot be immersed as a Legendrian submanifold of $\mathbb{R}^9$.

A: The obstruction here is in admitting a formal Legendrian embedding, i.e., there must be an embedding $f : N \to \Bbb R^{2n+1}$ which is covered by a 1-parameter family $F_t : TN \to T\Bbb R^{2n+1}$ of bundle monomorphisms such that $F_0 = df$ and $F_1(T_p N) \subset T_{f(p)}\Bbb R^{2n+1}$ is a Legendrian subspace. In particular, one must have the conditions imposed by Robert Bryant's answer.
If this is true, then one can run the proof of Murphy's $h$-principle: every formal Legendrian embedding is homotopic to a $\varepsilon$-Legendrian embedding, and therefore admits a front projection over which it is graphical. We may project to the front, wrinkle by Eliashberg-Mishachev's wrinkled embedding theorem, and then lift it back up. This gives a topological embedding of $N$ in $\Bbb R^{2n+1}$ which is Legendrian everywhere except embedded disjoint $S^{n-2}$'s which correspond to unfurled swallowtail singularities.
If one can now introduce a loose chart, then this may be used to cancel the swallowtail singularities by markings. This can be done by taking a connect sum with a loose topological unknot $S^n \to \Bbb R^{2n+1}$, obtained by spinning a zigzag. This doesn't change the topology of $N$, so we are done.


Q: Values not Populating in COMBOBOX even though it is fired the values from MVC I am Very new to EXTJS.
i am adding a new combo to my html page using EXTJS in xxx.js file and fetching the values from MVC controller with sample information.
while debugging the MVC application it is sending the sample information when i send URL: xxxx/getSite from EXTJS.
but it is not showing the values which are fetching from Controller. i am adding the below code which i am using.
Please let me know my mistake.
My Ext JS Code:
 var siteidStore = new Ext.data.JsonStore({
reader: new Ext.data.JsonReader({
fields: ['SiteName','SiteId']
}),
root: 'Site',
proxy: new Ext.data.HttpProxy({
url: 'Site/getSite',
method: "POST",
type: 'ajax',
reader: 'json'
}),
autoLoad: true
});

var combo = Ext.create('Ext.form.field.ComboBox', {
queryMode: 'local',
store: siteidStore,
fieldLabel: 'Site ID',
name: 'siteid',
displayField: 'SiteName',
valueField: 'SiteId',
triggerAction: 'all',
typeAhead: false,
forceSelection: true,
emptyText: 'Select Site',
hiddenName: 'SiteId',
selectOnFocus: true
});

MY MVC Appln Code from Controller:
publicActionResult getSite()
{
List<Combo> siteid = newList<Combo>();
siteid.Add(newCombo(1, "IND"));
siteid.Add(newCombo(2, "USA"));
siteid.Add(newCombo(3, "UK"));
return Json(new
{
Site = siteid,
}, JsonRequestBehavior.AllowGet);
}

Output of my C# code or Json:
{"Site":[{"SiteName":"IND","SiteId":1},{"SiteName":"USA","SiteId":2},{"SiteName":"UK","SiteId":3}]}

A: may be you forgot
renderTo : Ext.getBody()
inside combobox...


Q: JSON to Tuple operation in IBM Streams Is there a way to convert a JSON string to a SPL tuple type without using JSONtoTuple Operator?
I saw this documentation:
https://developer.ibm.com/streamsdev/docs/introducing-the-json-toolkit/
where they have mentioned a native function for converting tuple to json but not json to tuple.
How do I convert a JSON to Tuple inside a Custom operator?

A: version 1.4+ of the JSON toolkit includes functions that you can call from a custom.
This version must be downloaded from Github, as it is not yet included in the Streams product.
Download the latest version from Github, which is 1.4.4.
Build the toolkit: cd com.ibm.streamsx.json and run ant.
Then you can use the extractJSON function:
public T extractFromJSON(rstring jsonString, T value)
Pass the JSON string you want to parse, and a mutable tuple that will contain the parsed result as parameters.
For example:
composite ExtractFromJSON {
type

 //the target output type. Nested JSON arrays are not supported.
    Nested_t = tuple<rstring name, int32 age, list<rstring> relatives> person, tuple<rstring street, rstring city> address;

graph
    () as Test = Custom() {
        logic
            onProcess : {
                rstring jsonString = '{"person" : {"name" : "John", "age" : 42, "relatives" : ["Jane","Mike"]}, "address" : {"street" : "Allen Street", "city" : "New York City"}}';

                mutable Nested_t nestedTuple = {};
                println( extractFromJSON(jsonString, nestedTuple));
            }
    }
}

This is based on the ExtractFromJSON sample
 that you can find in the repo on Github.
Hope this helps.


Q: set of natural numbers subset of the set of real numbers The natural numbers are said to be a subset of the real numbers but how is this possible since in the set of natural numbers division is not allowed.

A: Real numbers are basically all numbers, decimal, whole, negative, and positive except for imaginary numbers. They include both rational and irrational numbers. A more formal definition is any value that can represent a distance along a line (-ve and positive denoting direction).
Natural numbers are just whole positive numbers. Since whole positive numbers can represent a distance along a line, they are a subset of real numbers.
I really don't understand what division has to do with this.

A: That the set of natural numbers is a subset of the set of real numbers just means that all natural numbers are also real numbers. You may be thinking of the term subfield, which is a subset that is a field with respect to the same operations as the larger set. Since the set of natural numbers has no multiplicative inverses (or additive for that matter), it is indeed not a subfield of the set of real numbers.

A: A set $A$ is said to be a subset of a set $B$ if and only if every member of $A$ is a member of $B$.
Since every natural number is a real number, the set of natural numbers($\Bbb N$) is a subset of the set of real numbers($\Bbb R$). It should be clear from the definition that containment(subset) relationships have nothing to do with the possible binary operations defined on the set.
What you might be thinking of is a group, in which case the set of non-zero real numbers form a group under multiplication but the set of natural numbers do not form a subgroup because you cannot guarantee a multiplicative inverse for every element.

A: You mention that, "in the set of natural numbers, division is not allowed". That's not entirely true. We can do lots of division with natural numbers, e.g., $6\div 2=3$. I think you mean that the set of natural numbers is not "closed under division". That's true. There are lots of division problems involving natural numbers whose solution is not a natural number.
The set of real numbers is closed under division, with the usual provision that we don't divide by $0$. The natural numbers $6$ and $5$ are also real numbers, since the naturals are a subset of the reals. Their quotient, $\frac65$, is another real number, one which is not a natural number. There is no problem here.
Being a subset of the real numbers doesn't mean retaining all of the closure properties of real numbers. It's like this: the prime numbers are a subset of the natural numbers, and even though the natural numbers are closed under addition, the prime numbers are not: $3+5=8$. Here, the sum of two primes equals a natural that is not a prime, just like we saw the quotient of two naturals can equal a real that is not a natural.


Q: question about tree i have question for example i   want to implement   binary tree with array    i want understand what will  indexes for left child and rigth child  ?my array is 0 based  i want implement   searching in tree using array  can anybody help me?

A: left child = parent * 2 + 1
right child = parent * 2 + 2
I imagine this is homework so I will let you figure out the searching algorithm.

A: To implement a binary tree as an array you put the left child for node i at 2*i+1 and the right child at 2*i+2.
So for instance, having 6 nodes here's the indices of the corresponding array
          0
          |
      ---------
      |       |
   ---1--   --2--
   |     |  |    |
   3     4  5    6

A: I think you are looking for a heap. Or at least, you use a tree when an array structure is not enough for your needs so you can try to implement a tree inside an array but it wouldn't make much sense since every node contains references to its children without any need of indices.
But an heap is an array that can also be seen as a binary tree, look it out here. It's a tree in the sense that it organizes data as a tree but without having direct references to the children, they can be inferred from the position.


Q: How to Find the number zero in decimal part where add no value to the number and remove that part I am using the following code to convert cm to the meter.
 public static double? ConvertCmToM(double? cm)
        {
            return cm.Value * 0.01;

        }

When I input the number 8.8 output giving as

0.08800000000000001m

But I want to stop in the index where zero adds no value in the decimal part. In this case I want to display the value as

0.088m

This is already done in major converter websites. when you type the cm to m converter on google those sites will appear. How do they do it?
I took the same sample and put in their sites and this is how they show.
> 0.088m

I cannot blindly substring the value after converting to a string as the zero part will appear in 5th or 6th element.
That also handled in those sites.
This is a double data type. the letter "m" concat at the last minute. How to acehive this?

A: I would use decimal instead of double then:
public static decimal? ConvertCmToM(decimal? cm)
{
    if(cm == null) return null;
    return Decimal.Multiply(cm.Value, 0.01m);
}

static void Main()
{
    Console.Write(ConvertCmToM(8.8m)); // 0.088
}

decimal vs double! - Which one should I use and when?


Q: Retrieving all objects in code upfront for performance reasons How do you folks retrieve all objects in code upfront?
I figure you can increase performance if you bundle all the model calls together?
This makes for a bigger deal, especially if your DB cannot keep everything in memory

def hitDBSeperately {
get X users
  ...code
get Y users... code
get Z users... code
}

Versus:

def hitDBInSingleCall {
get X+Y+Z users
code for X
  code for Y...
}

A: Are you looking for an explanation between the approach where you load in all users at once:
# Loads all users into memory simultaneously
@users = User.all

@users.each do |user|
  # ...
end

Where you could load them individually for a smaller memory footprint?
@user_ids = User.connection.select_values("SELECT id FROM users")

@user_ids.each do |user_id|
  user = User.find(user_id)

  # ...
end

The second approach would be slower since it requires N+1 queries for N users, where the first loads them all with 1 query. However, you need to have sufficient memory for creating model instances for each and every User record at the same time. This is not a function of "DB memory", but of application memory.
For any application with a non-trivial number of users, you should use an approach where you load users either individually or in groups. You can do this using:
@user_ids.in_groups_of(10) do |user_ids|
  User.find_all_by_id(user_ids).each do |user|
    # ...
  end
end

By tuning to use an appropriate grouping factor, you can balance between memory usage and performance.

A: Can you give a snipet of actual ruby on rails code, our pseudo code is a little confusing?
You can avoid the n+1 problem by using eager loading. You can accomplish this by using :includes => tag in your model.find method.
http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html


Q: Division en postgreSQL muestra resultado incorrecto Tengo la consulta que me devuelve el valor de un indice que es el resultado de una operacion entre dos columnas, el resultado lo quiero en decimales y lo muestra asi, lo que sucede es que el resultado no el correcto: aca dejo mi consulta:
SELECT dep.nombre as departamento,
mun.nombre,can.nombre,cas.nombre,
sum(cap.total_mosquitos) as total_mosquitos,
sum(cap.total_anopheles) AS total_anopheles,
sum(cap.casa_positiva) AS casa_positiva,
sum(cap.casa_inspeccionada) AS casa_inspeccionada,
SUM(CASE casa_inspeccionada WHEN 0 THEN null ELSE
(total_mosquitos::float/casa_inspeccionada::float) END) AS indice_casa
FROM pl_captura_anopheles cap
INNER JOIN ctl_caserio cas on (cap.id_caserio =cas.id)
INNER JOIN ctl_canton can on (cas.id_canton = can.id)
INNER JOIN ctl_municipio mun on (can.id_municipio = mun.id)
INNER JOIN ctl_departamento dep on (dep.id=mun.id_departamento)
WHERE (EXTRACT(YEAR FROM cap.fecha)=2018)
GROUP By dep.nombre,mun.nombre,can.nombre,cas.nombre

y el resultado que me muestra:
EN la primera fila se puede observar el resultado incorrecto 110/70 = 3.16?

A: El problema era que me estaba sumando los resultados de division de cada fila, entonces lo que he hecho es sumar primero las columnas y luego ya ese total dividirlo:
(sum(total_mosquitos)::numeric/ sum(casa_inspeccionada)::numeric)as indice


Q: System.out.println - Java In Java, why can't we refer to
System.out.println

as just
out.println

...why can't the System call just be implicit since the System library is universal? Perhaps Groovy solved this one.

A: You can if you import static like
import static java.lang.System.out;

then you can do
public static void main(String[] args) {
    out.println("Hello, World");
}

A: "Universal", as you're using it, means that you don't need to import System. You still need to qualify references to a field in a different class. What if you (as often happens) want a local field named out?
(And Groovy lets you simply use println.)

A: out.println() would then eliminate out as a valid instance name. By referencing System we know that out is not, for example, File out.


Q: tinyMCE 4.0.5 ObjectResizeStart doesn't work I have latest version of tinyMCE I need to use this function:
http://www.tinymce.com/wiki.php/api4:event.tinymce.Editor.ObjectResizeStart
to prevent image resizing when I'm in read mode because in Chrome images and tables can be rezised even when I'm saying  readonly: true.

A: You can disable resizing with
object_resizing : false


Q: Как сделать, чтобы popup не открывался вместе со страницей? мне надо сделать чтобы popup открывался только по нажатию кнопки, а он открывается вместе со страницей, как это можно исправить?

// Pop-up
$(document).ready(function() {
  //Скрыть PopUp при загрузке страницы
  PopUpHide();
  $("#popup1").hide();
});
//Функция отображения PopUp
function PopUpShow() {
  $("#popup1").show();
}
//Функция скрытия PopUp
function PopUpHide() {
  $("#popup1").hide();
}
.product {
  height: 100vh;
  margin-top: 50px;
}

.product-text {
  margin: 0 auto;
  text-align: center;
  font-size: 72px;
  margin-bottom: 50px;
}

.product-itemss {
  display: -ms-grid;
  display: grid;
  -ms-grid-rows: (1fr)[2];
  -ms-grid-columns: (1fr)[2];
  grid-template: repeat(2, 1fr)/repeat(2, 1fr);
  gap: 15px;
}

.product-item {
  height: 390px;
  width: 100%;
  -webkit-box-shadow: 0px 0px 25px 0px rgba(0, 0, 0, 0.2);
  box-shadow: 0px 0px 25px 0px rgba(0, 0, 0, 0.2);
  border-radius: 25px;
}

.product-description {
  font-size: 16px;
  margin: 10px;
  margin-left: 20px;
  margin-bottom: 0;
}

.product-price {
  float: left;
  font-weight: 600;
  font-size: 22px;
  margin: 10px;
  margin-left: 20px;
}

.product-img {
  margin-left: 20px;
}

.product-texti {
  margin: 0;
  padding: 10px;
  padding-left: 20px;
  font-size: 38px;
}

.product-btn {
  float: left;
  margin-top: 10px;
  padding-top: 5px;
  padding-bottom: 7px;
  padding-left: 28px;
  padding-right: 30px;
  background-image: url("/img/btn.png");
  background-repeat: no-repeat;
  font-size: 16px;
}

.product-btn :hover {
  -webkit-transition: 0.5s;
  transition: 0.5s;
  color: #f3f3f3;
  text-shadow: 0px 0px 25px black;
}

.b-popup {
  width: 100%;
  min-height: 100%;
  background-color: rgba(0, 0, 0, 0.2);
  overflow: hidden;
  position: fixed;
  top: 0px;
}

.b-popup-content {
  -webkit-backdrop-filter: blur(10px);
  backdrop-filter: blur(10px);
  margin: 50px auto 0px auto;
  width: 1110px;
  height: 773px;
  padding: 20px;
  background-color: rgba(170, 170, 170, 0.7);
  border-radius: 25px;
  -webkit-box-shadow: 0px 0px 25px rgba(0, 0, 0, 0.5);
  box-shadow: 0px 0px 25px rgba(0, 0, 0, 0.5);
}

.b-popup-content-textm {
  float: left;
  color: #fff;
  font-size: 48px;
}

.b-popup-content-close {
  float: right;
}

.b-popup-content-close :hover {
  border-radius: 10px;
  -webkit-transition: .5s;
  transition: .5s;
  -webkit-box-shadow: 0px 0px 25px rgba(0, 0, 0, 0.5);
  box-shadow: 0px 0px 25px rgba(0, 0, 0, 0.5);
}

.b-popup-form {
  float: left;
}

.b-popup input {
  margin-top: 30px;
  width: 1000px;
  height: 60px;
  border: none;
  border-radius: 25px;
  font-size: 30px;
  padding-left: 30px;
  font-family: 'Grtsk Tera', sans-serif;
}

.b-popup input[type="submit"] {
  padding: 0;
  width: 220px;
  height: 45px;
  font-size: 24px;
}

Цены

Landing page

· От 4 до 12 блоков
· Слайдер, анимации
· Адаптивный дизайн

Цена от 8000₽

          Заказать

Оформление соц.сетей

Вконтакте, Instagram, YouTube, Twitch

Цена от 500₽

          Заказать

Превью для
YouTube канала

Привлекающая картинка для вашего видео

Цена от 400₽

          Заказать

Фирменный
логотип

Современный и красивый логотип

Цена от 500₽

          Заказать

Мы всегда на связи
Пишите нам!

      <form action="#" class="b-popup-form">
        <input type="text" name="example" list="exampleList" placeholder="Меня интересует...">
        <datalist id="exampleList">
                <option value="Сайта под ключ">
                <option value="Дизайн сайта">
                <option value="Дизайн приложения">
                <option value="HTML/CSS верстка">
                <option value="Дизайн для соц.сетей">
                <option value="Превью"></option>
                <option value="Логотип"></option>
            </datalist>
        <input type="text" name="name" placeholder="Ваше имя">
        <input type="text" name="email" placeholder="Ваш email">
        <input type="text" name="description" placeholder="Расскажите о своём проекте">
        <input type="text" name="money" placeholder="Планируемый бюджет">
        <input type="file" name="f">
        <input type="submit" value="Добавить файл">
        <input type="submit" value="Отправить">
      </form>

Прошу прощения, если мой вопрос покажется глупым, пожалуйста не снижайте мне рейтинг.

A: Скрывайте блок изначально при помощи стилей например .pop-up { display: none; }
Функцию отображения/скрытия блока используйте onclick например: Заказать
Тогда функция отображения PopUp будет:
function PopUpShow() {
  $(".pop-up").show();
}

A: Попробуйте так. Немного переделал под универсальный вариант.
Добавляете в элемент data-action="openModal" (либо data-action="closeModal") и data-id="айди_модального_окна" и по щелчку на него(Например, на текст) будет открываться (закрываться) нужная модалка

//Функция отображения PopUp
$('[data-action="openModal"').click(function(){
  modalID = '#'+$(this).data('id');
  $(modalID).show();
})

//Функция скрытия PopUp
$('[data-action="closeModal"').click(function(){
  modalID = '#'+$(this).data('id');
  $(modalID).hide();
})
.product {
  height: 100vh;
  margin-top: 50px;
}

.product-text {
  margin: 0 auto;
  text-align: center;
  font-size: 72px;
  margin-bottom: 50px;
}

.product-itemss {
  display: -ms-grid;
  display: grid;
  -ms-grid-rows: (1fr)[2];
  -ms-grid-columns: (1fr)[2];
  grid-template: repeat(2, 1fr)/repeat(2, 1fr);
  gap: 15px;
}

.product-item {
  height: 390px;
  width: 100%;
  -webkit-box-shadow: 0px 0px 25px 0px rgba(0, 0, 0, 0.2);
  box-shadow: 0px 0px 25px 0px rgba(0, 0, 0, 0.2);
  border-radius: 25px;
}

.product-description {
  font-size: 16px;
  margin: 10px;
  margin-left: 20px;
  margin-bottom: 0;
}

.product-price {
  float: left;
  font-weight: 600;
  font-size: 22px;
  margin: 10px;
  margin-left: 20px;
}

.product-img {
  margin-left: 20px;
}

.product-texti {
  margin: 0;
  padding: 10px;
  padding-left: 20px;
  font-size: 38px;
}

.product-btn {
  float: left;
  margin-top: 10px;
  padding-top: 5px;
  padding-bottom: 7px;
  padding-left: 28px;
  padding-right: 30px;
  background-image: url("/img/btn.png");
  background-repeat: no-repeat;
  font-size: 16px;
}

.product-btn :hover {
  -webkit-transition: 0.5s;
  transition: 0.5s;
  color: #f3f3f3;
  text-shadow: 0px 0px 25px black;
}

.b-popup {
  width: 100%;
  min-height: 100%;
  background-color: rgba(0, 0, 0, 0.2);
  overflow: hidden;
  position: fixed;
  top: 0px;
  display: none;
}

.b-popup-content {
  -webkit-backdrop-filter: blur(10px);
  backdrop-filter: blur(10px);
  margin: 50px auto 0px auto;
  width: 1110px;
  height: 773px;
  padding: 20px;
  background-color: rgba(170, 170, 170, 0.7);
  border-radius: 25px;
  -webkit-box-shadow: 0px 0px 25px rgba(0, 0, 0, 0.5);
  box-shadow: 0px 0px 25px rgba(0, 0, 0, 0.5);
}

.b-popup-content-textm {
  float: left;
  color: #fff;
  font-size: 48px;
}

.b-popup-content-close {
  float: right;
}

.b-popup-content-close :hover {
  border-radius: 10px;
  -webkit-transition: .5s;
  transition: .5s;
  -webkit-box-shadow: 0px 0px 25px rgba(0, 0, 0, 0.5);
  box-shadow: 0px 0px 25px rgba(0, 0, 0, 0.5);
}

.b-popup-form {
  float: left;
}

.b-popup input {
  margin-top: 30px;
  width: 1000px;
  height: 60px;
  border: none;
  border-radius: 25px;
  font-size: 30px;
  padding-left: 30px;
  font-family: 'Grtsk Tera', sans-serif;
}

.b-popup input[type="submit"] {
  padding: 0;
  width: 220px;
  height: 45px;
  font-size: 24px;
}

Цены

Landing page

· От 4 до 12 блоков
· Слайдер, анимации
· Адаптивный дизайн

Цена от 8000₽

          Заказать

Оформление соц.сетей

Вконтакте, Instagram, YouTube, Twitch

Цена от 500₽

          Заказать

Превью для
YouTube канала

Привлекающая картинка для вашего видео

Цена от 400₽

          Заказать

Фирменный
логотип

Современный и красивый логотип

Цена от 500₽

          Заказать

Мы всегда на связи
Пишите нам!

      <form action="#" class="b-popup-form">
        <input type="text" name="example" list="exampleList" placeholder="Меня интересует...">
        <datalist id="exampleList">
                <option value="Сайта под ключ">
                <option value="Дизайн сайта">
                <option value="Дизайн приложения">
                <option value="HTML/CSS верстка">
                <option value="Дизайн для соц.сетей">
                <option value="Превью"></option>
                <option value="Логотип"></option>
            </datalist>
        <input type="text" name="name" placeholder="Ваше имя">
        <input type="text" name="email" placeholder="Ваш email">
        <input type="text" name="description" placeholder="Расскажите о своём проекте">
        <input type="text" name="money" placeholder="Планируемый бюджет">
        <input type="file" name="f">
        <input type="submit" value="Добавить файл">
        <input type="submit" value="Отправить">
      </form>


Q: OpenCV: Why SIFT and SURF detectors crashes? Why do the SIFT and SURF detectors crash?
using namespace std;
using namespace cv;

int main(int argc, char *argv[])
{
  Mat image = imread("TestImage.jpg");

  // Create smart pointer for SIFT feature detector.
  Ptr<FeatureDetector> featureDetector = FeatureDetector::create("SIFT");
  vector<KeyPoint> keypoints;

  // Detect the keypoints
  featureDetector->detect(image, keypoints); // here crash
  // ...
}

The error is Segmentation fault (core dumped). I use OpenCV 2.4.8, gcc 4.9 and Ubuntu. If I use the other types of features it runs normally. What am I missing?

A: Have you tried to call initModule_nonfree()?
#include <opencv2/nonfree/nonfree.hpp>
using namespace std;
using namespace cv;

int main(int argc, char *argv[])
{
  initModule_nonfree();
  Mat image = imread("TestImage.jpg");

  // Create smart pointer for SIFT feature detector.
  Ptr<FeatureDetector> featureDetector = FeatureDetector::create("SIFT");
  vector<KeyPoint> keypoints;

  // Detect the keypoints
  featureDetector->detect(image, keypoints); // here crash
  // ...
}

Also, you didnt check the pointer featureDetector which is probably null (since you have not called initModule).


Q: Answer queries about the number of distinct numbers in a given range The problem
I have an array with N numbers. The numbers may be disctints and may also be unordered. I have to answer Q queries about how many distinct numbers there are between A and B. Where A, B are indices between 0 <= A <= B < array.Length.
I know how to do it O(N) per query by using a HashTable but I'm asking for a more efficient solution.
I tried to improve it with sqrt decomposition and also with a segment tree but I couldn't. I'm not showing any code because I did not find any idea that worked.
I'm looking for someone to give an explanation of a faster solution.
UPDATE
I read you can collect the queries and then answer them all by using a Binary Indexed Tree (BIT). Can someone explain how to do it. Assume I know how a BIT works.

A: For each index i find the previous index prev[i] that has the same value (or -1 if there's no such index). It may be done in O(n) average by going left to right with hash_map, then the answer for range [l;r) of indices is number of elements i in range [l;r) such that their value is less then l (it require some thinking but should be clear)
Now we will solve problem "given range [l;r) and value c find number of elements that are less then c" on array prev. It may be done in O(log^2) using segment tree, if we save in each vertex all the numbers that are in its range(subtree). (On each query we will get O(log n) vertices and do binary search in them)


Q: Is JSF 2.0 View Scope back-button safe? Is the JSF 2.0 View Scope "back button" safe? e.g. if I store a model in View Scope and go from page 1, page 2, page 3, to page 4, modifying the model object along the way (via input fields), and then hit the back button twice to go back to page 2 and make changes (taking me again to page 3), will the model in view scope have only changes that were made when page 2 was originally rendered or will it have later pages' changes?
Oracle ADF had/has something called "process scope" that handles this by tokenizing what is placed into session, so each page has its own copy of the model.

A: To start, the view scope is bound to a particular page/view. Multiple views won't share the same view scoped bean. The view scope starts with an initial GET request and stops when a POST action navigates with a non-null return value.
There are in general the following scenarios, depending on whether the browser is instructed to cache the page or not and the JSF state saving configuration. I'll assume that the navigation between those pages took place by a POST request (as it sounds much like the "Wizard" scenario).
When the back button is pressed:

*

*If browser is instructed to save the page in cache, then browser will load the page from the cache. All previously entered input values will reappear from the browser cache (thus not from the view scoped bean in the server side!). The behavior when you perform a POST request on this page depends further on the javax.faces.STATE_SAVING_METHOD configuration setting:

*

*If set to server (default), then a ViewExpiredException will occur, because the view state is trashed at the server side right after POST navigation from one to other page.

*If set to client, then it will just work, because the entire view state is contained in a hidden input field of the form.

*Or, if browser is instructed to not save the page in cache, then browser will display a browser-default "Page expired" error page. Only when the POST-redirect-GET pattern was applied for navigation, then the browser will send a brand new GET request on the same URL as the redirect URL. All previously entered input values will by default get cleared out (because the view scoped bean is recreated), but if the browser has "autocomplete" turned on (configureable at browser level), then it will possibly autofill the inputs. This is disableable by adding autocomplete="off" attribute to the input components. When you perform a POST request on this page, it will just work regardless of the JSF state saving method.

It's easier to perform the "Wizard" scenario on a single view which contains conditionally rendered steps and offer a back button on the wizard section itself.
See also:

*

*javax.faces.application.ViewExpiredException: View could not be restored

*What scope to use in JSF 2.0 for Wizard pattern?


Q: Measuring electric conductivity My daughter is doing a science experiment on which metal (e.g., copper, silver, aluminum, iron) has maximum electric conductivity. We are assuming we can accomplish this by using different metal, 3 to 6 volt electrical circuits, and a basic digital multimeter.
How we can do it? Do we have to measure resistance of this metal? Or is there a different way. Please guide us.

A: Conductivity is given by $$ \sigma=\frac{l}{AR} $$ where where $l$ is length, $A$ is cross sectional area and $R$ is resistance.
Therefore if you can measure these three things for each metal you can calculate their conductivities.

A: You have to use the equation for resistivity: $$\rho=R\frac{A}{l}$$ where $R$ is resistance, $\rho$ is electrical resistivity, and $a$ is area. So, for all the metals, I would use the same length and area in order to keep $l$ and $a$ constant.
In order to find the resistance, $R$, for the metals, you need to use a potentiometer, or variable resistor, and plot a graph of voltage vs. current in order to determine the resistance of the metals. In order to accomplish this though, you need to have a voltmeter attached parallel to the potentiometer and an ammeter in series with the circuit. Since resistance is voltage divided by current, just divide the voltage by the current on any point on the graph.
Now that you have $l$, $a$, and $R$, you can solve for $\rho$, electrical resistivity. In order to find conductivity, you simply take the inverse of the resistivity, $\rho$, value.

A: Apart from the mathematics already given, and considering more practical issues- you will not see much difference between all the metals you listed by measuring with a cheap multimeter. If you throw in carbon and silicon - then yes you will see a difference.
All the metals you listed will all read zero ohms resistance on a cheap meter. And conductivity is just the reciprocal of resistance often written in units of mhos. So infinite conductivity! (But not really, there is a difference you just can't detect it). You need to either get very long (tens of meters), thin specimens of the metals (coils of insulated metal wire for example) or you need a more sensitive (and expensive) ohmmeter that resolves in milliohms (1/1000's of an ohm).
In any event you'll either need to make all the samples the same so it's not the geometry determining the resistance as noted in the other answers, but rather the resistivity of the particular metal, $\rho$.

A: This adds to the other answers that explain the basic concept behind the measurement.
Consider that the conductivity of all these materials is pretty high.
To give you a starting point, 1 meter of 26 AWG copper wire will be about 0.13 ohms. This is a reasonable value to measure, but does require some care to measure accurately (for example, accurately enough to distinguish copper from silver). Depending on the samples you have available of your different materials you might need to measure even lower resistance values than that.
If you do a naive measurement with a two-probe ohmmeter, the contact resistance between the probes and your samples is likely to disturb the measurement.
In that case, you will want to do a four-wire resistance measurement to prevent the probe wires and contact resistances from being measured as if they are part of your samples.
Another thing to be aware of when interpreting your results is that the resistivity of these metals can depend on how they are alloyed and how they are treated. For example, annealed copper and work-hardened copper will have different resistivity values. This difference could be enough to overwhelm the difference between the materials themselves, for example if you compared a sample of silver wire from a jewelry-maker's supply store with a sample of copper wire intended for electrical use.


Q: Extract jsonb in Postgresql - dictionary and array structure in same jsonb field I am using postgresql and I have this table on dataset, that some columns are jsonb.
SELECT
external_id as cod,
title as name,
objectives
FROM table

So, the result for "objectives" column is like that:
{"blocks":
    [
        {"key":"dek2k",
        "text":"Objetivo Geral",
        "type":"unstyled",
        "depth":0,
        "inlineStyleRanges":
            [
            {"offset":0,"length":14,"style":"fontsize-12pt"},
            {"offset":0,"length":14,"style":"fontfamily-Arial"},
            {"offset":0,"length":14,"style":"fontsize-14"}
            ],
        "entityRanges":[],
        "data":{"text-align":"start"}},
        {"key":"ct1vn",
        "text":"Conhecer e aplicar ferramentas para análise da mídias em sua respectiva relação com a cognição e o design,",
        "type":"unstyled","depth":0,"inlineStyleRanges":
            [
            {"offset":0,"length":216,"style":"color-rgb(0,0,0)"},
            {"offset":0,"length":216,"style":"fontsize-12pt"},
            {"offset":0,"length":216,"style":"fontfamily-Arial"},
            {"offset":0,"length":216,"style":"fontsize-14"}
            ],
        "entityRanges":[],
        "data":{}},
        {"key":"8jshq",
        "text":"","type":"unstyled","depth":0,
        "inlineStyleRanges":[],
        "entityRanges":[],"data":{}},
        {"key":"avq4h",
        "text":"tendo como ênfase os estudos das materialidades dos meios de comunicaçõe e seus aspectos sensoriais.",
        "type":"unstyled",
        "depth":0,
        "inlineStyleRanges":
            [
            {"offset":0,"length":23,"style":"color-rgb(0,0,0)"},
            {"offset":0,"length":23,"style":"fontsize-12pt"},
            {"offset":0,"length":23,"style":"fontfamily-Arial"},
            {"offset":0,"length":23,"style":"fontsize-14"}
            ],
        "entityRanges":[],
        "data":{}}
    ],
"entityMap":{}
}

I want to get in result only what is in "text". Sometimes it has just one "text" value, sometimes it has up to 15 or more.
What i need is a result like this for all rows in table:
 cod      |      name      | objectives
----------+-----------------+----------
 1        | A              | Objetivo Geral Conhecer e aplicar ferramentas para análise da mídias em sua respectiva relação com a cognição e o design, tendo como ênfase os estudos das materialidades dos meios de comunicaçõe e seus aspectos sensoriais.

Any clue?

A: The json functions with string_agg() achieve what you want.
Using WITH ORDINALITY guarantees correct ordering of the text elements.
SELECT t.external_id as cod,
       t.title as name,
       string_agg(a.block->>'text', ' ' ORDER BY rn) as objectives
  FROM "table" t
       CROSS JOIN LATERAL jsonb_array_elements(t.objectives->'blocks')
                           WITH ORDINALITY as a(block, rn)
 GROUP BY t.external_id, t.title;


Q: Upgrade to Ubuntu 13.10 disabled track pad, brightness, sound on Lenovo Z570 I just upgraded to Ubuntu 13.10 using Ubuntu's software update. It seemed to go all right, however after the system restarted and booted up Ubuntu 13.10, it began experiencing several problems. Some of them were due to expected conflicts with the updated OS, however right now I cannot figure out why certain hardware functions are now "broken" and how to fix them.
As far as I can tell, these are the sound (permanently muted), mic (picks up no sound), brightness (set at maximum brightness regardless of using keyboard shortcuts or moving the screen brightness slider) and trackpad (mouse does not move, however plugged-in USB mouse does)
This sounds to me like a driver issue, however I cannot figure out how to re-enable my drivers, re-install them, or whatever I have to do here. This did not happen durring my upgrades from 12.04 to 12.10, or 12.10 to 13.04, so I'm at a total loss as to why this happened this time around.
My computer is a Lenovo Z570, dual-booting Ubuntu and Windows 7 from GRUB 2. Windows is working fine as far as I can tell.

A: For sound, try this:
Sound problems after upgading to 13.04
For the trackpad, I had for some weird reason a missing package, and doing
 sudo apt-get install xserver-xorg-input-synaptics

resolved the issue. Maybe it works for you too?
For the brightness I'm at a loss. I have a somewhat similar problem with the brightness, so hang on :)

A: For screen brightness the following may help you (for me this worked on G510 core i5 4th gen free dos).
Use terminal and give the code:
sudo -H gedit /etc/default/grub

In the line GRUB_CMDLINE_LINUX_DEFAULT add acpi_backlight=vendor after quiet splash. So the line reads as:
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash acpi_backlight=vendor"

Save and without fail update the grub using:
sudo update-grub

Restart.


Q: How to display template parameter type name in natvis? I want to extend a natvis visualizer for a (C++) template class. Is there a way to display a type name of the first template parameter?
It would be great for boost::variant<int,bool> v; v=1; to display 1 (int) or something like that

A: In my opinion the best solution is to use the standard C++17 std::variant. MSVC comes with natvis for this type so that you have a pretty view of the value that is stored.
Here is some natvis code that I just wrote and tested:
  <Type Name="boost::variant<*>">
    <DisplayString Condition="which_==0">{*($T1*)storage_.data_.buf}</DisplayString>
    <DisplayString Condition="which_==1" Optional="true">{*($T2*)storage_.data_.buf}</DisplayString>
    <DisplayString Condition="which_==2" Optional="true">{*($T3*)storage_.data_.buf}</DisplayString>
    <DisplayString Condition="which_==3" Optional="true">{*($T4*)storage_.data_.buf}</DisplayString>
    <DisplayString Condition="which_==4" Optional="true">{*($T5*)storage_.data_.buf}</DisplayString>
    <DisplayString Condition="which_==5" Optional="true">{*($T6*)storage_.data_.buf}</DisplayString>
    <DisplayString Condition="which_==6" Optional="true">{*($T7*)storage_.data_.buf}</DisplayString>
    <Expand>
      <Item Name="which">which_</Item>
      <Item Name="value0" Condition="which_==0">*($T1*)storage_.data_.buf</Item>
      <Item Name="value1" Condition="which_==1" Optional="true">*($T2*)storage_.data_.buf</Item>
      <Item Name="value2" Condition="which_==2" Optional="true">*($T3*)storage_.data_.buf</Item>
      <Item Name="value3" Condition="which_==3" Optional="true">*($T4*)storage_.data_.buf</Item>
      <Item Name="value4" Condition="which_==4" Optional="true">*($T5*)storage_.data_.buf</Item>
      <Item Name="value5" Condition="which_==5" Optional="true">*($T6*)storage_.data_.buf</Item>
      <Item Name="value6" Condition="which_==6" Optional="true">*($T7*)storage_.data_.buf</Item>
    </Expand>
  </Type>

It works for any boost::variant<type_or_types>.
It has a DisplayString that takes the variant's member storage_ and extracts the buffer buf. The address of the buffer is then cast to a pointer to the type that was provided to std::variant. As you can see in my code which_ is zero based, whereas the template parameters are 1 based. I am not interested in the address but in the value, so I am adding a * in front of the value.
I also added an Expand section so that you can expand a variant. This allows me to show which_ and to show the value again - this time the column Type will show the correct type as you can see in my screen capture (for the variant itself the type is displayed as boost::variant<…> and I do not know how to add the type name into the DisplayString).
Please note that the Optional="true" are required because otherwise we would get a parsing error in cases where less than 7 type parameters are passed (as in boost::variant<int,bool>and natvis does not have a $T7.
If you need more template parameters, you can easily extend the code.
If you want the DisplayString to also shows the index (as an explicit value or coded into the name value…), you can easily change it accordingly as in
<DisplayString Condition="which_==0">{{which={which_} value0={*($T1*)storage_.data_.buf}}}</DisplayString>

Last but not least please note that I did not test very much and that I did not look into boost::variant into detail. I saw that storage_ has members suggesting that there is some alignment in place. So it might not be sufficient to just use storage_.data_.buf. It might be necessary to adjust the pointer depending on the alignment being used.

A: If you want to show $T1 as a string, wrap it with ". For example, for
<DisplayString>{*($T1*)storage_.data_.buf} {"$T1"}</DisplayString>
in your case you will see 1 "int"


Q: Percent difference when both negative In an experiment, I was asked to find the percent difference between theoretical and experimental $y$-intercept (which I have). It is known that its formula is
$$\text{Percent Difference} =\frac{|x_t-x_e|}{\frac{1}{2}\left(x_t+x_e\right)}\cdot100\%$$
But what if both values (in my case) of $x_t,\,x_e$ are negative? Does that mean I need to write negative percentage or just take its absolute?

A: It should be $\%=\frac{|x_t-x_e|}{\frac{1}{2}\left(x_t+x_e\right)}$. You dont have to worry about negative values as ${|x_t-x_e|}$ will take care of all possible values + or -  Just plug the values as they are and the difference will be correct.


Q: What should I use in ANSI C to create linked lists? In Java I used LinkedList<T>.
Is there any standard, or maybe some other libraries, to create LinkedLists in C?

A: No, C doesn't have anything like that. If you can use C++, there's std::list.
You'll have to write the structure yourself in C.

A: As others have said, there is no standard library support for linked lists in C.  That means you either get to roll your own (like most people have done at one or more times in their C coding career), or you look at other libraries for support.
For most uses, you will find that an 'intrusive' implementation is appropriate.  You modify your existing structure to include a pointer to the next item in the list (and, if you're doing a doubly linked list, the previous item).
typedef struct TheStruct TheStruct;

struct TheStruct
{
    ...the real data...
    TheStruct *next;
  //TheStruct *prev;
};

Your list now consists of a simple pointer to the head item:
TheStruct *head = 0;

TheStruct *allocated_node = new_TheStruct(value1, value2, ...);

assert(allocated_node->next == 0);

// Insert new allocated node at head of list
allocated_node->next;
head = allocated_node;

You have to worry about threading issues if you've got threads access the same list, and so on and so forth.
Because this code is so simple, this is how it is most frequently handled.  Deleting a node from a list is trickier, but you can write a function to do it.
People have dressed up this basic scheme with macros of varying degrees of complexity so that the code manipulating different types of lists can use the same macros.  The Linux kernel uses a macro-based set of linked lists for managing its linked list data structures.
The alternative to the 'intrusive' implementation (which is so-called because it requires a change to the structure to include the list pointers) is to have some generic list mechanism:
typedef struct GenericList GenericList;
struct GenericList
{
    void        *data;
    GenericList *next;
  //GenericList *prev;
};

Now you have the ability to put (pointers to) unmodified structures into the list.  You lose some type safety; there is nothing to stop you adding random different structure types to a list that should be homogeneous.  You also have to allocate memory for the GenericList structures separately from the pointed at data.

*

*One advantage of this is that a single data item can be on multiple separate lists simultaneously. * One disadvantage of this is that a single data item can accidentally be on multiple lists, or multiple times in a single list, simultaneously.

You also have to make sure you understand the ownership properties for the data, so that the data is released properly (not leaked, not multiply-freed, not accessed after being freed).  Managing the memory for the list itself is child's play by comparison.
With the GenericList mechanism, you will likely have a library of functions that manage the list operations for you.  Again, searching should reveal implementations of such lists.

A: C does not (as yet) provide any standard container structures.  You'll have to roll your own.

A: It doesn't exist by default, but it can be made quite easily.
Basically a linked list is a header pointer that points to 1st element, and an ending file pointing to null.
The elements are actually nodes, containing the object and a pointer to the next node.
So making a basic one is quite easy, though in C it might be painful as no classes, only structs.

A: There are no Lists in the standard C library. A very good C library you can use is PBL - The Program Base Library here. Its interface is Java like. You can download it from here


Q: Domino Rest service API to get Tentative status in Ateendee's calendar Is there any way to find the Tentative status of my meetings as an Attendee from the response of "GET /{db}/api/calendar/events"  or  "GET /{db}/api/calendar/events/meetingId" ?
Some documents say x-lotus-noticetype property with "P" indicates a tentative acceptance. But I am getting a status "A" instead, after tentative accept meeting in both 8.5.3 and 9.0.1 versions of domino.
Use case: To show my(Attendee's) tentatively accepted meetings in Yellow color , in my Web App's calendar.

A: You should look at the JSON transparency property.  When an attendee tentatively accepts a meeting, the property will look like this:
  "transparency": "transparent"

On the other hand, when an attendee accepts a meeting, the property will look like this:
  "transparency": "opaque"

In other words, a transparent event doesn't block busy time; an opaque event does block busy time.  This terminology comes from the iCalendar specification.  See the TRANSP property in iCalendar.


Q: Exchange Information between two windows Im not sure how to explain my problem in short at the title, so forgive me for this. Lets say I opened my website in some random page, and I have a register button. Really simple, but in my case I require the registration form to appear in other tab(or window). Not "RederPartial", nor popup window of some kind, legit new tab. The problem is, I want to be able do detect, from that random page of mine, when the registration completed (ie a new user has been created). How can I pass this information? without reloading the first page

A: There are various ways to make two windows talk with each other (through server, with cookies, using FileSystem API  or Local Storage.
Locale Storage is by far the easiest way to talk between two windows who come from the same domain, but it is not supported in older browsers. Since you need to contact the server anyway to find out when someone has registered, I recommend using the server (Ajax//web sockets).
Here's a somewhat simple AJAX solution which you could use in your random page:
(function(){
    var formOpened = false;
    var registered = false;

    //Change to whatever interaction is needed to open the form
    $('#registerbutton').on('click', function(){
        if (!formOpened){
            formOpened = true;

            //Will try to poll the server every 3 seconds
            (function pollServer(){
                $.ajax({
                    url: "/ajax/pollregistered",
                    type: "GET",
                    success: function(data) {
                        if (data.registered){
                            registered = true;
                            //do other stuff here that is needed after registration
                        }
                    },
                    dataType: "json",
                    complete: setTimeout(function() {if (!registered) pollServer();}, 3000),
                    //will timeout if request takes longer than 2 seconds
                    timeout: 2000,
                })
            })();

            //opens the new tab
            var win = window.open('/registrationform', '_blank');
            win.focus();
        }
    });
})();

You can then use the session key of the visitor in  the  '/ajax/pollregistered' action to write your backend code to check if and when this visitor registered as user to your site.
If you don't mind using the local storage, you could poll the storage instead of the server and have the registration page write to local storage upon registration. This is less stressing for your server, but might not work for users with ancient browsers.
Also worth nothing that this method of opening a new tab is not completely reliable. Technically there is not a sure shot way of opening a new tab with javascript. It depends on browser and the preferences of the user. Opening a new tab might get blocked for users who are using anti popup plugins.
That being said, I strongly recommend revising your design and try finding a way to work with just one window instead. It's probably better for both yourself and your users.


Q: Differentiable extension of an arbitrary function I'm learning multivariate analysis from Analysis on Manifolds written by Munkres. In solving the problems, I have encountered this problem:
In (a), since the support of $\phi$ is in $U$, if $\mathbf{x}\notin K:=\operatorname{supp}\phi$, $\phi(x)=0$. Hence the definition makes sense. But how can I show that this $h$ is of class $C^r$? On $K^c$, $h$ is identically zero, which implies that $h$ is $C^r$ on $K^c$. But on $K$, I don't know how to show that $h$ is of $C^r$.


Q: Adjust border to content I have a simple grid with 2 columns with border and two columns Fiddle
The problem is I want to adjust the border to the content and the content has left padding, so I want to remove that free space.
I tried to use box-sizing: border-box; but it causes no effect

HTML:

    Annual Test Test

    80

SCSS:
.totalContainer {
  display: grid;
  grid-template-columns: 2fr 1fr;
  margin-top: 30px;
  border: 1px solid rgba(72, 82, 93, 0.8);
  border-radius: 12px;
  box-sizing: border-box;

  &__row {
    background-color: #E5E5E5;
  }

  &__space {
    padding: 10px 0 10px 140px;
  }

  &__text {
    font-size: 13px;
  }

  &__result {
    text-align: right;
  }
}

A: Using margin-left instead of padding:
 &__space {
    padding: 10px 0 10px 10px;
    margin-left: 140px;
  }

A: I think you are missing the big picture here.

Making up a block box in CSS we have the:
Content box: The area where your content is displayed, which can be
sized using properties like width and height. Padding box: The padding
sits around the content as white space; its size can be controlled
using padding and related properties.
Border box: The border box wraps
the content and any padding. Its size and style can be controlled
using border and related properties.
Margin box: The margin is the
outermost layer, wrapping the content, padding, and border as
whitespace between this box and other elements. Its size can be
controlled using margin and related properties.

So in short the border includes the padding (it wraps the content as well as the padding), while the margin lays outside of it (pushing the content with border and padding included). I would recomand to check the box model docs.


Q: middleman Invalid byte sequence in UTF-8 I want to edit a webpage for someone who is using middleman.  Anytime I run middleman in the console I get this error:
Traceback (most recent call last):
    68: from /Users/apple/.rvm/gems/ruby-2.6.0/bin/ruby_executable_hooks:24:in `<main>'
    67: from /Users/apple/.rvm/gems/ruby-2.6.0/bin/ruby_executable_hooks:24:in `eval'
    66: from /Users/apple/.rvm/gems/ruby-2.6.0/bin/middleman:23:in `<main>'
    65: from /Users/apple/.rvm/gems/ruby-2.6.0/bin/middleman:23:in `load'
    64: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-cli-4.3.3/bin/middleman:49:in `<top (required)>'
    63: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-cli-4.3.3/bin/middleman:49:in `new'
    62: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/application.rb:283:in `initialize'
    61: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/callback_manager.rb:28:in `block in install_methods!'
    60: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_handler.rb:138:in `block in redefine_method'
    59: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/call_with.rb:76:in `call_with'
    58: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_reference.rb:43:in `send_to'
    57: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/callback_manager.rb:57:in `execute'
    56: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/hamster-3.0.0/lib/hamster/vector.rb:431:in `each'
    55: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/hamster-3.0.0/lib/hamster/vector.rb:1316:in `traverse_depth_first'
    54: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/hamster-3.0.0/lib/hamster/vector.rb:1316:in `each'
    53: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/callback_manager.rb:57:in `block in execute'
    52: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/callback_manager.rb:57:in `instance_exec'
    51: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_handler.rb:138:in `block in redefine_method'
    50: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/call_with.rb:76:in `call_with'
    49: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_reference.rb:43:in `send_to'
    48: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/core_extensions/file_watcher.rb:47:in `before_configuration'
    47: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_handler.rb:138:in `block in redefine_method'
    46: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/call_with.rb:76:in `call_with'
    45: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_reference.rb:43:in `send_to'
    44: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/sources.rb:241:in `poll_once!'
    43: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/sources.rb:241:in `reduce'
    42: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/sources.rb:241:in `each'
    41: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/sources.rb:241:in `block in poll_once!'
    40: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_handler.rb:138:in `block in redefine_method'
    39: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/call_with.rb:76:in `call_with'
    38: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_reference.rb:43:in `send_to'
    37: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/sources/source_watcher.rb:212:in `poll_once!'
    36: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_handler.rb:138:in `block in redefine_method'
    35: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/call_with.rb:76:in `call_with'
    34: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_reference.rb:43:in `send_to'
    33: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/sources/source_watcher.rb:288:in `update'
    32: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/callback_manager.rb:28:in `block in install_methods!'
    31: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_handler.rb:138:in `block in redefine_method'
    30: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/call_with.rb:76:in `call_with'
    29: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_reference.rb:43:in `send_to'
    28: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/callback_manager.rb:57:in `execute'
    27: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/hamster-3.0.0/lib/hamster/vector.rb:431:in `each'
    26: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/hamster-3.0.0/lib/hamster/vector.rb:1316:in `traverse_depth_first'
    25: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/hamster-3.0.0/lib/hamster/vector.rb:1316:in `each'
    24: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/callback_manager.rb:57:in `block in execute'
    23: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/callback_manager.rb:57:in `instance_exec'
    22: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_handler.rb:138:in `block in redefine_method'
    21: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/call_with.rb:76:in `call_with'
    20: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_reference.rb:43:in `send_to'
    19: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/sources.rb:351:in `did_change'
    18: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_handler.rb:138:in `block in redefine_method'
    17: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/call_with.rb:76:in `call_with'
    16: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_reference.rb:43:in `send_to'
    15: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/sources.rb:361:in `run_callbacks'
    14: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/hamster-3.0.0/lib/hamster/vector.rb:431:in `each'
    13: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/hamster-3.0.0/lib/hamster/vector.rb:1316:in `traverse_depth_first'
    12: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/hamster-3.0.0/lib/hamster/vector.rb:1316:in `each'
    11: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/sources.rb:368:in `block in run_callbacks'
    10: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_handler.rb:138:in `block in redefine_method'
     9: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/call_with.rb:76:in `call_with'
     8: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_reference.rb:43:in `send_to'
     7: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/core_extensions/data.rb:89:in `update_files'
     6: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/core_extensions/data.rb:89:in `each'
     5: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_handler.rb:138:in `block in redefine_method'
     4: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/call_with.rb:76:in `call_with'
     3: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_reference.rb:43:in `send_to'
     2: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/core_extensions/data.rb:108:in `touch_file'
     1: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/util/data.rb:60:in `parse'
/Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/util/data.rb:60:in `match': invalid byte sequence in UTF-8 (ArgumentError)

Is there a way to find out what is causing this error?  I didn't build this website, I just cloned the repository but I don't know where to start.
I've looked this up earlier and found people with a similar problem that said that it had something to do with the font files.  Even when I removed those I still have this error. If anyone could help me out I would appreciate it.  Thanks in advance.


Q: Create Shape drawable with stroke color, corner and solid drawable I Want to create a shape: solid is a Bitmap (repeat tiles), and stroke is a color. I use LayerList:
    <layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:id="@+id/additional_image"
        android:drawable="@drawable/bg_detail_loop"
        >
    </item>
    <item android:id="@+id/rounded_corners"
        android:drawable="@drawable/shape_box_dlg">
    </item>
</layer-list>

File bg_detail_loop.xml:
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:filter="true"
    android:gravity="center"
    android:tileMode="repeat"
    android:src="@drawable/tile_detail"
    />

File shape_box_dlg.xml:
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <stroke
        android:width="2dip"
        android:color="#EE6A1F" />
    <gradient android:angle="270" />
    <corners android:radius="6dp" />
</shape>

But, in the corner, the background Bitmap not clip. I want rounded the corner. Anyone help me? Thanks


Q: Select data from different sheets in LibreOffice Calc I have three sheets 1,2 and 3. There are three columns on sheet 2 and 3: name (A), surname (B), age(C). How can I select men whose age is >=30 from sheet 2 and 3, order them by age and show the result on sheet 1 (also 3 columns)? I mean something equivalent to SELECT name,surname,age FROM sheet2,sheet3 WHERE age=>30 ORDER BY age and show result on sheet 1.

A: While Excel will support some SQL, Calc does not.  Staying within Calc, to get the results on sheet 1 will take multiple steps:
Highlight your entire table on sheet 2, including the header row.  Select Data→Filter→Standard Filter and in the popup window select field name Age, condition >= and value 30.  Copy and paste the resulting filtered table (including header row, if needed) to sheet 1.
Repeat that procedure on sheet 3, copy and pasting the results (this time excluding the header row) to sheet 1 below your first copy-paste.
Now, highlight your entire table on sheet 1, including the header row, and choose Data→Sort and sort by age.
If you need to do this frequently, it might be worthwhile to look into connecting a Base file to the Calc files so you can treat the data in the spreadsheet as database tables.  While this would be fairly complicated, I believe it would be less work than figuring out macro code to do the filter/copy/filter/copy/sort procedure.


Q: Troubleshooting Samba server connection issue I have a Samba server (smbd version 4.3.11) running on Ubuntu.
I cannot connect to it from other computers on my LAN (I tried an OS X 10.12 box and a Windows 7 box)
However, I can telnet to port 139 from my OS X box and see the connection in the smbd logs.  And I can connect to samba locally on the Ubuntu box.
Any ideas on further troubleshooting?
More details on what I have done so far:
The Ubuntu server is at 192.168.1.11
The OS X client box is at 192.168.1.107
I set the log level on smbd to level 3.
I run the following command on the Ubuntu server:
smbclient -L 192.168.1.11 -U%

This successfully returns the expected shares on the server and prints a large number of log lines to the smbd logs.
I run the following command on the OS X box:
smbutil view '//192.168.1.11'

I get the following error:
smbutil: server connection failed: No such file or directory

No log lines printed on the server.
Any attempt to connect to the server using the connect to server UI in OS X Finder fails.  Same with the map network drive UI in Windows 7.  No smbd log entries are posted for any of these.
I run the following command on the Ubuntu server:
echo hello | telnet 192.168.1.11 139

This appears in the smbd logs:
==> /var/log/samba/log.192.168.1.11 <==
[2017/07/09 03:45:41.892842,  3] ../source3/smbd/oplock.c:1310(init_oplocks)
  init_oplocks: initializing messages.
[2017/07/09 03:45:41.892955,  0] ../source3/smbd/process.c:339(read_packet_remainder)
  read_fd_with_timeout failed for client 192.168.1.11 read error = NT_STATUS_END_OF_FILE.
[2017/07/09 03:45:41.893288,  3] ../source3/smbd/server_exit.c:252(exit_server_common)
  Server exit (failed to receive smb request)

==> /var/log/samba/log.smbd <==
[2017/07/09 03:45:41.892646,  3] ../source3/lib/access.c:338(allow_access)
  Allowed connection from 192.168.1.11 (192.168.1.11)

I run the identical command on OS X, and the following appears in the logs:
==> /var/log/samba/log.192.168.1.107 <==
[2017/07/09 03:47:47.151012,  3] ../source3/smbd/oplock.c:1310(init_oplocks)
  init_oplocks: initializing messages.
[2017/07/09 03:47:47.151336,  3] ../source3/smbd/server_exit.c:252(exit_server_common)
  Server exit (failed to receive smb request)

==> /var/log/samba/log.smbd <==
[2017/07/09 03:47:47.150839,  3] ../source3/lib/access.c:338(allow_access)
  Allowed connection from 192.168.1.107 (192.168.1.107)

So, it appears the OS X box can connect to the smbd port and smbd is listening.  And smbd does appear to be properly serving requests locally, but refuses to respond to any valid remote requests.  I am at a loss...

A: Does the Samba Shared Directory have the correct permissions?
A common issue with Samba is that the Shared Folder itself does not have the correct permissions. When you make your Shared Directory you should make it without Sudo. If you don't do that you will have to adjust ownership and permissions after the fact. Note Samba still does the smb sharing functions but the permissions need to be correct.


Q: zshell passing argument to function I put this in my zshrc:
function picofl() {
        openocd -f interface/picoprobe.cfg -f target/rp2040.cfg  -c 'program "$1" reset exit'
}

Then I run: picofl myblink.elf but it errors with unexpected argument. What am I doing wrong?


Q: What does it mean "to channel" somebody?
The director Bryan Singer clearly enjoys playing with these oversize, puppetlike meanies and finds queasy comedy in their threat, especially when Jack, Isabelle and some others, including a knight, Elmont (Ewan McGregor channeling Errol Flynn), nearly become finger food.

Source: "This Jack stays near the stalk", THE GLOBAL EDITION OF THE NEW YORK TIMES, THURSDAY, MARCH 7, 2013
What does it mean "to channel" somebody? Does it mean to imitate?

A: In this context channel means to act like another person.

to invoke the style or characteristics of another person

You might see it in more fantastic settings being used to describe allowing the spirit or ghost of a deceased person to speak or act through the first individual's body.
In this case the excerpt is using it in a much more common metaphorical way.


Q: Custom Sinatra route I'm looking to make a custom route for my Sinatra blog project which shows the user the last entered post in the database.
get "/most-recent-job" do
  Job.last

Can anyone help? I can't find info in my curriculum for such a request.

A: The Sinatra documentation on routes is pretty thorough. Assuming you're just trying to call a class method of Jobs::last, and that the method returns something stringifyable, then:
get '/most-recent-job' do
  Jobs.last
end

should get it done. If that's insufficient for your use case, you'll have to expand your question to include code and output showing what Jobs.last is supposed to return, whatever errors you're getting from the route currently, and what you think the route's output ought to look like if you're expecting a MIME type other than text/plain.


Q: Layers in Hexagonal Architecture I'm reading a lot about hexagonal architecture, but in all the examples that i'm looking, all folders and class ubication are different, and this looks a bit confusing to me.

I've done a simple spring boot application with below folder structure. Adapter folder contains implementation of repository interface and the rest controller.
In domain folder, I've model, which is a simple POJO, ports, that are interfaces of service class which contains all the business logic of Product, and the interface of repository which exposes the methods to be implemented in repository.
In another folder I've service implementation, and as i told before, with the business logic of product.
Is this a correct way to implement an hexagonal architecture for a simple use case? If not, why? Where i should put every class and why? This is what it's not clear...
Much appreciate!

A: You are totally free to organise your code however you wish. This is unrelated to hexagonal architecture.
With that being said, if you want to use hexagonal architecture efficiently, you should probably follow a domain-driven design, that is to say, you should organise your code based on domain/business logic, and not based on technical similarities.
For example, instead of having the following structure:
controller
    product
    cart
    customer
service
    product
    cart
    customer
repository
    product
    cart
    customer

DDD recommends the following structure:
product
    controller
    service
    repository
cart
    controller
    service
    repository
customer
    controller
    service
    repository

Once you've done this, if it helps, you could wrap these in three packages for the differents parts of the hexagonal architecture: user side, business logic and server side. This is something I've done in the past; it helps me keep the different layers clear.
userside
    product
        controller
    cart
        controller
    customer
        controller
businesslogic
    product
        service
    cart
        service
    customer
        service
serverside
    product
        service
    cart
        repository
    customer
        repository

Again, the structure of your packages is not the most important concept. The hexagonal architecture focuses on three principles:

*

*Explicitly separate user side, business logic, and server side layers. A clear package structure helps, but you can separate these layers in other ways.

*Dependencies go from user side and server side layers to the business logic. This is done by defining interfaces and adapters in the business logic (see below). The goal is that code in the user side and server side may be changed without impacting the business logic layer. For example, if you wish to change your repository from a MySQL implementation to a PostgreSQL implementation (in the server side layer), this change should not impact your business logic: the new implementation need only comply with the interface in the business logic.

*Dependency injection: the business logic defines interfaces (commonly called "ports") and transformers ("adapters") with which the user side and server side layers must comply for communication.

It's a very DDD oriented architecture; the idea is that the business logic remain as close to the domain as possible, and unadulterated by technical requirements.

A: Hexagonal architecture doesn't say snything about how to organize the hexagon code (business logic). You can implement however you want to.
Take a look at these articles:
https://jmgarridopaz.github.io/content/articles.html


Q: Tensorflow input pipeline for distributed training I am trying to figure out how to setup my input pipeline for tensorflow in distributed training. It's not clear whether the readers will read from a single process and send the data to all workers or each server will start it's own input pipeline? How do we ensure that every worker has a different input going to it?

A: I will give an example of how I do it:
import tensorflow as tf
batch_size = 50
task_index = 2
num_workers = 10
input_pattern = "gs://backet/dir/part-00*"

get all names of files in the bucket that correspond to input_pattern
files_names = tf.train.match_filenames_once(
                input_pattern, name = "myFiles")

select names for worker task_index. tf.strided_slice is like slice for lists: a[::,task_index] (select every task_indexth file for worker task_index)
to_process = tf.strided_slice(files_names, [task_index],
                 [999999999], strides=[num_workers])
filename_queue = tf.train.string_input_producer(to_process,
                     shuffle=True, #shufle files
                     num_epochs=num_epochs)

reader = tf.TextLineReader()
_ , value = reader.read(filename_queue)
col1,col2 = tf.decode_csv(value,
        record_defaults=[[1],[1]], field_delim="\t")

train_inputs, train_labels = tf.train.shuffle_batch([col1,[col2]],
        batch_size=batch_size,
        capacity=50*batch_size,
        num_threads=10,
        min_after_dequeue = 10*batch_size,
        allow_smaller_final_batch = True)

loss = f(...,train_inputs, train_labels)
optimizer = ...

with tf.train.MonitoredTrainingSession(...) as mon_sess:
    coord = tf.train.Coordinator()
    with coord.stop_on_exception():
        _ = tf.train.start_queue_runners(sess = mon_sess, coord=coord)
        while not coord.should_stop() and not mon_sess.should_stop():
            optimizer.run()

I'm not sure my method is the best way to implement input pipeline in case of distributed TensorFlow implementation because each worker reads names of all files in the bucket

Good lecture about input pipeline in TensorFlow: http://web.stanford.edu/class/cs20si/lectures/notes_09.pdf


Q: How to find integer solutions to $M^2=5N^2+2N+1$? My number theory is terrible so I don't know what "class" of problem this secretly is.  I'm looking for all positive integer solutions to the equation:

$M^2=5N^2+2N+1$

That is, I want positive integer $M$ and $N$ to make the above true.  I've got the obvious solution ($N=0$, $M=1$) but I don't know how to go about getting more solutions.  It has been suggested to me that there should be infinitely many solutions, and I would like to find them all.
I could transform it to look like Pell's equation by completing the square on the right, but it won't have integer coefficients (or you could multiply it through by the denominators, but then it wouldn't look like Pell's equation), so I don't think that helps much.
I don't know enough number theory to guess at other things, but I'm happy to read something on this topic.

A: One possibility is to rewrite  as $$M^2=(2N)^2+(N+1)^2. $$ So you are looking at the Pythagorean  triples of the form $(N+1,2N,M) $.
Edit: Along the lines of Erick's complaint, I want to make this into a full answer, so let's talk about Pythagorean triples and how this turns into an acceptably fast algorithm.
A primitive Pythagorean triple is a triple $(r^2-s^2, 2rs, r^2+s^2)$ where $r$ and $s$ are coprime positive integers, not both odd, and $r>s$.  It turns out that every Pythagorean triple -- a triple of positive integers $(a,b,c)$ where $a^2+b^2=c^2$ -- is a positive integer multiple of a primitive Pythagorean triple.
If $(N+1, 2N, M)$ is a Pythagorean triple, then there are positive integers $r$, $s$, and $k$ as above where $N+1=k(r^2-s^2)$ and $2N=2krs$.  Since $2N=2((N+1)-1)$, this means $2krs=2(k(r^2-s^2)-1)$, so $krs=kr^2-ks^2-1$, so $k(rs-r^2+s^2)=-1$.  Since $k$ is a positive integer, this means $k=1$, so that's one degree removed.
So we're looking at positive integers $r$ and $s$ where $rs-r^2+s^2=-1$, or rearranged, $s^2+rs-r^2+1=0$.  So it must be that $s=\frac{1}{2}\left(-r+\sqrt{r^2+4(r^2-1)}\right)=\frac{1}{2}\left(-r+\sqrt{5r^2-4}\right)$.
Note that it's $+$, not $\pm$, in the above, since $s$ needs to be positive. Thus, given $r$, we can find $s$.
So the algorithm is now this.  For each positive integer $r$, find $s$ in the above.  If it's a positive integer, then $N=rs$, and you've found a solution $N$.  Every $N$ is of this form, so this enumerates all of them, in order.
Additionally, if some number $N$ is a solution, this algorithm will find it in $O(\sqrt{N})$ time.
It can be sped up by enumerating solutions to the Pell-like equation $5r^2-4=t^2$ (that is, finding $r$ which make $s$ rational), which can be done very quickly through a recurrence (I believe) but I don't actually know how to do it.  If you can do that, about half of those $r$ should make $s$ an integer, as opposed to merely rational, and you've got a really fast algorithm.

A: For these equations we use the standard approach.
For a private quadratic form:  $$Y^2=aX^2+bX+1$$
Using solutions of Pell's equation:  $$p^2-as^2=1$$
Solutions can be expressed through them is quite simple.
$$Y=p^2+bps+as^2$$
$$X=2ps+bs^2$$
$p,s$ - these numbers can have any sign.
Finding solutions of equations Pell - standard procedure.

A: as it says above, you may manipulate the original problem into:
$$(n+1)^2 + (2n)^2 = (y)^2$$
the sum of two squares equaling a square is a Pythagorean type equation
so parametrize as follows:
$p^2 - q^2=n+1 \tag{1}$
$2pq=2n \tag{2}$
and
$p^2 + q^2 = y^2  \tag{3}$
thus $n = pq$ and $y=\sqrt{p^2+q^2}$
put this $n$ back into (1), we have
$$pq + 1 = p^2 - q^2$$
$$1 = p^2 - pq -q^2$$
completing the square of the first and second terms:
$$1 = (p-q/2)^2 - q^2/4 - q^2$$
$$1 = (p-q/2)^2 - (5/4)q^2$$
$$4 = (2p - q)^2 - 5q^2$$
let $r = 2p - q$, this implies that $p=\frac{r+q}{2}$,
thus $n=pq=\frac{(r+q)q}{2}$
thus $y=\sqrt{\left(\frac{r+q}{2}\right)^2 + q^2}$
the equation above is now
$$r^2 - 5q^2 = 4$$
which is a pell type equation
it's fair I think to represent the solution of the problem in terms of the solutions of a pell type equation, which by the way are infinite in number:
In this way, the solution set is $$(n,y) = \left(\frac{(r+q)q}{2}, \sqrt{\left(\frac{r+q}{2}\right)^2 + q^2}\right)$$
such that $(r,q)$ belongs in the solution set of $r^2 - 5q^2 = 4$.
Here are some examples:
$\underline{(r,q)\to(n,y^2)}$
$(3,1)\to(2,5)$
$(7,3)\to(15,34)$
$(18,8)\to(104,233)$
and so on...

A: A quick way to find some solutions is the following:
You probably know you can get the square numbers by calculating $1+3+5+7+9+...$
In the same way, you can get the numbers $5N^2+2N+1$ by calculating
$$1+7+17+27+37+47+57...$$
So, one add per number, which you can do with pencil and paper.
You might need a calculator to check which numbers are squares.
You can also get values for negative $N$ with $1+3+13+23+33+43+53+...$


Q: Django Design Pattern - request.user in Model I run into this pattern all the time and I'm wondering if there's a better way to handle it.  Lots of my models contemplate the idea of 'creator' - in other words, I want to make sure the user who created the object is saved as the creator.  As such, my models almost always include
creator = models.ForeignKey(User)

There doesn't seem to be a way of defaulting this user to the user who created it (request.user).  As such I find myself building model forms and adding creator as a HiddenInput()
class MyModelForm(ModelForm):
    class Meta:
        model = MyModelForm
        fields = ['name', 'creator']
        widgets = {
            'creator': HiddenInput()
        }

and then binding the form in the view with initial
form = MyModelForm(initial={'creator': request.user})

and checking on POST to make sure no one dickered with the form (full view):
def create(request):
    form = MyModelForm(initial={'creator': request.user})
    if request.method ==  'POST':
        if int(request.POST['creator']) != int(request.user.id):
            return render(request,'500.html', {'message':'form tampering detected'})
        form = FeedGroupForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('index'))
    return render(request, 'mymodelformpage.html',{'form':form})

I'm fine with this but it seems like an anti-pattern.  It strikes me that there ought to be a way to default the creator in the model.
creator = models.ForeignKey(User, default=request.user)

Or do it in a post_save perhaps?

A: No, this is not the right way. The correct way is to exclude the creator field from the form, then set it on save:
if form.is_valid:
    obj = form.save(commit=False)
    obj.creator = request.user
    obj.save()
    ... redirect ...


Q: Running Android Studio Volley in different API levels The app I made ran on different API levels but the volley library only works API level 26.
I was puzzled when I can't login in the app using my phone (android 9) but a later model works just fine. I found out that I can only login in Android 8 phones (API level 26). I tested multiple virtual devices with different API levels and API level 26 let's me login and the rest just doesn't work. I was wondering how can I make volley library work on API level 26 and higher.
Edit: It was a big mistake for me but I now enabled the log for errors and I found these.
(Using http://)

(Using https://)

plugins {
    id 'com.android.application'
}

android {
    compileSdk 31

    defaultConfig {
        applicationId "com.example.studentplanner"
        minSdk 26
        targetSdk 31
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    buildFeatures {

        viewBinding true

    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    namespace 'com.example.studentplanner'
}

dependencies {

    implementation 'androidx.appcompat:appcompat:1.4.2'
    implementation 'com.google.android.material:material:1.6.1'
    implementation 'com.github.xabaras:RecyclerViewSwipeDecorator:1.3'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    implementation 'com.android.volley:volley:1.2.1'
    implementation 'com.google.code.gson:gson:2.9.1'

    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'androidx.recyclerview:recyclerview:1.1.0-alpha04'
    implementation 'com.google.android.material:material:1.1.0'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}

A: Add this line in your application tag
<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        ...
        android:usesCleartextTraffic="true"
        ...>
        ...
    </application>
</manifest>


Q: WooCommerce product categories are not displayed properly in menu I got this strange behavior in Wordpress, I have about 90 product categories/subcategories.
All the related functions are working fine, except when I go to Appearance -> Menu and try to add product categories to my menu.
The thing is that only two pages of product categories are viewed with many missing categories.
please see the attached screenshot.

I am using Woocommerce v3.3.4
Server info:

A: Go to the ‘Tools’ tab inside the WooCommerce > System Status of your WordPress administration panel. Here you first use the ‘Recount terms’ button and after that use the ‘Clear transients’ button. This will force the system to recount all the products the next time a category is loaded.

A: File Manager >> public_html >> wp-admin >> includes >> nav-menu.php
search for paginate there is two it will be the one in line 692 (it was for me).
// Paginate browsing for large numbers of objects.
    $per_page = 50;
Change 50 to your needs
Also add to child theme functions.php


Q: GDAL polygonize only certain raster values I want to polygonize a raster file with GDAL. I only want to rasterize cells with a value of 0. Is it possible to specify that within the polygonize function or do I have to modify my raster before hand?

A: No, it's not possible directly in the function. You can either a) reclassify the raster first (probably fastest and easiest), or 2) convert to vector then delete all non-zero polygons, or 3) create a mask, and pass that to gdal_polygonize using -mask (see manual.)


Q: EJS not rendering on placing image url I am trying to add image using EJS, the page on the browser doesn't render as I want.
Here is the image of the browser
ejs code for this rendering page is
<% layout('layout/boilerplate') -%>
   <% for (let camps of allCamps){%>

                <img class="img-fluid" src="<%= camps.image[0].url %>">

<%= camps.title %>

<%= camps.description %>

                      <%= camps.location%>

                  <a class="btn btn-primary" href="/campgrounds/<%=camps._id%>">View <%=camps.title%>

 <% }%>


Q: Add SSH Connection with pem key to Apache Airflow connection Is there a way to add an ssh connection to Apache Airflow from the UI either via connections or vairables tab that allow connection using a pem key and not a username and password.

A: DISCLAIMER: Following answer is purely speculative

*

*I think key_file param of SSHHook is meant for this purpose

*And the idiomatic way to supply it is to pass it's name via extra args in Airflow Connection entry (web UI)

*

*Of course when neither key_file nor credentials are provided, then SSHHook falls back to identityfile to initialize paramiko client.

*Also have a look how SFTPHook is handling this


Q: Facing problem with material mat-select dropdown position issue Facing problem with material mat-select dropdown position issue. Dropdown position is keep on changing on select of item. How to keep position as fixed. Can you someone support please.


Q: Issue while using webservice to call some java application method which is using resource file Issue while using webservice to call some java application method which is using resource file
I have created one java application which contains following directory structure in my src folder of java..
Src/
  Transcriber.java
  config.xml
  digits.gram
  transcriber.manifest

I have successfully created web-service of this java application with .aar file and putting into axis2 service folder
I am packaging this whole in Transcriber.aar file with the following structure
Transcriber\edu\cmu\sphinx\demo\transcriber

and in that all 4 file above I listed.
I have two method in above Transcriber.java class.. 1st method is just processing without any of other file use like (e.g. config.xml,digits.gram and transcriber.manifest). and its working fine and I can call easily that method from android.
but my second method uses the other files also(e.g. config.xml,digits.gram and transcriber.manifest) to process some logic I want.
But some how I'm getting error when I call the second method and its give me error while I'm calling this 2nd method from android device .
My Error is as follows:
  at java.lang.Thread.run(Thread.java:662)
Caused by: Property exception component:'jsgfGrammar' property:'grammarLocation'
 - Can't locate resource:/edu/cmu/sphinx/demo/transcriber
edu.cmu.sphinx.util.props.InternalConfigurationException: Can't locate resource:
/edu/cmu/sphinx/demo/transcriber

its give me error that some how it cant locate the grammar file digits.gram which is i use to add via the config.xml file with this code in config.xml
<component name="jsgfGrammar" type="edu.cmu.sphinx.jsgf.JSGFGrammar">
        <property name="dictionary" value="dictionary"/>
        <property name="grammarLocation"
             value="resource:/edu/cmu/sphinx/demo/transcriber"/>
        <property name="grammarName" value="digits"/>
    <property name="logMath" value="logMath"/>
    </component>

Why I'm Having this kind of error?enter code here
My CODE WHERE I HAVE FIRST GET THE CONFIG.XML AND THEN CONFIG.XML GET ANOTHER RESOURCE FILE....its successfully finds the config.xml but then the code in config.xml cant locate other resource file
package edu.cmu.sphinx.demo.transcriber;

import edu.cmu.sphinx.frontend.util.AudioFileDataSource;
import edu.cmu.sphinx.recognizer.Recognizer;
import edu.cmu.sphinx.result.Result;
import edu.cmu.sphinx.util.props.ConfigurationManager;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

/** A simple example that shows how to transcribe a continuous audio file that has multiple utterances in it. */
public class TranscribeSimpleGrammar {

        private static final String PATH = "file:///D:\\Sound\\";

        @SuppressWarnings({ "null", "null" })
        public String recognize_wave(String wavePath) throws MalformedURLException{

              URL audioURL;

              //  if (args.length > 0) {
                //    audioURL = new File(args[0]).toURI().toURL();
              //  } else {
                    //audioURL = TranscribeSimpleGrammar.class.getResource("hello.wav");
                        //audioURL = new URL(PATH + "turn-on-light-kitchen-male.wav");
                        //audioURL = new URL(PATH + "turn-down-tv-volume-female.wav");
                       // audioURL = new URL(PATH + wavePath);
              audioURL = new URL(wavePath);
              //audioURL = new URL(PATH + "turn-down-dining-room-music-player-volume-male.wav");

               // }

                URL configURL = TranscribeSimpleGrammar.class.getResource("config.xml");

                ConfigurationManager cm = new ConfigurationManager(configURL);
                Recognizer recognizer = (Recognizer) cm.lookup("recognizer");

                /* allocate the resource necessary for the recognizer */
                recognizer.allocate();

                // configure the audio input for the recognizer
                AudioFileDataSource dataSource = (AudioFileDataSource) cm.lookup("audioFileDataSource");
                dataSource.setAudioFile(audioURL, null);

                // Loop until last utterance in the audio file has been decoded, in which case the recognizer will return null.
                Result result;
                while ((result = recognizer.recognize())!= null) {

                        String resultText = result.getBestResultNoFiller();
                        System.out.println(resultText);
                }

            return result.getBestResultNoFiller();
        }

        public String get_wav_byte(byte[] wavbite,String path){

            String result1="null";

            try
            {
                File dstFile = new File(path);
                FileOutputStream out = new FileOutputStream(dstFile);
                out.write(wavbite, 0, wavbite.length);

                out.close();

            }
            catch (IOException e)
            {
              System.out.println("IOException : " + e);
            }

            try {
                result1=recognize_wave(path);
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

         return result1;

     }

}

A: Have you ever tried to change
<property name="grammarLocation" value="resource:/edu/cmu/sphinx/demo/transcriber"/>

to
<property name="grammarLocation" value="resource:edu/cmu/sphinx/demo/transcriber"/>

(meaning just removing the leading slash before edu)?
Class.getResource() and ClassLoader.getResource() do interpret the provided name differently: while Class.getResource( "/edu/cmu/sphinx/demo/transcriber/transcriber.manifest" ) would find the resource, you have to use ClassLoader.getResource() with the argument "edu/cmu/sphinx/demo/transcriber/transcriber.manifest" to find the same resource. As you do not know which method is used by the library code you call to load the other resources, you should give it a try.