text:
Q: What data type(s) can bind to DataGridViewComboBoxColumn? A DataGridViewComboBoxColumn allows the value to be one of the members of a list.
I can't figure out what value type this can bind to when binding a DataGridView to a custom class. e.g. if I set DataPropertyName to "MyProperty" what type(s) may MyClass.MyProperty use for getter/setter?

A: It could be any type as soon as it's convertible from string (have a proper TypeConverter. This also heavily depends on how you set the DisplayMember and ValueMember properties. The weird thing is when you want to bind to a property of custom class type and just display some property of that class. In such a case, setting just DisplayMember does not work and you need to expose some artificial self pointing property of the class in order to bind it as ValueMember. I think all that design originates from the old days when you would want to display obj.Name but bind obj.Id. Anyway, here is a small sample showing what I mean:
using System;
using System.Linq;
using System.Windows.Forms;

namespace Samples
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            var categories = Enumerable.Range(1, 10).Select(n => new Category { Name = "Category" + n }).ToList();
            var products = Enumerable.Range(1, 50).Select(n => new Product { Name = "Product" + n, Category = categories[(n - 1) % categories.Count] }).ToList();
            var form = new Form();
            var dg = new DataGridView { Dock = DockStyle.Fill, Parent = form, AutoGenerateColumns = false };
            dg.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "Name" });
            var categoryColumn = new DataGridViewComboBoxColumn { DisplayStyleForCurrentCellOnly = true };
            // data part
            categoryColumn.DataPropertyName = "Category"; // bind to Product.Category property
            // list part
            categoryColumn.DisplayMember = "Name"; // bind to Category.Name property
            categoryColumn.ValueMember = "Self"; // w/o this it doesn't work
            categoryColumn.DataSource = categories;
            dg.Columns.Add(categoryColumn);
            dg.DataSource = products;
            Application.Run(form);
        }
    }
    public class Category
    {
        public string Name { get; set; }
        public Category Self { get { return this; } }
    }
    public class Product
    {
        public string Name { get; set; }
        public Category Category { get; set; }
    }
}


text:
Q: How to sort list by Persian alphabet? How can I read testArrray in ul li and sort this list?
lis.sort(function(a,b)) has English/Arabic/and alphabet support, not Persian alphabet support. Help me please. Thank you

var alphabets = ["ا", "ب", "پ", "ت", "ث", "ج", "چ", "ح", "خ", "د", "ذ", "ر", "ز", "ژ", "س", "ش", "ص", "ض", "ط", "ظ", "ع", "غ", "ف", "ق",
  "ک", "گ", "ل", "م", "ن", "و", "ه", "ی", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"
];
var testArrray = ["ی", "گ", "ژ", "پ"];

var aChar;
var bChar;

function OrderFunc() {
  testArrray.sort(function(a, b) {
    return CharCompare(a, b, 0);
  });
  document.getElementById("result").innerHTML = testArrray;;
}

function CharCompare(a, b, index) {
  if (index == a.length || index == b.length)
    return 0;

  aChar = alphabets.indexOf(a.toUpperCase().charAt(index));
  bChar = alphabets.indexOf(b.toUpperCase().charAt(index));

  if (aChar != bChar)
    return aChar - bChar
  else
    return CharCompare(a, b, index + 1)
}

ی

پ

گ

ژ

A: To sort a list alphabetically in Persion, I used this code with <meta charset="utf-8"> and its result was perfect:
const myList = ["ی","گ","پ", "ژ"];
const collator = new Intl.Collator('fa');
const sortedLetters = myList.sort(collator.compare);
console.log(sortedLetters);

The Intl.Collator objects enable language sensitive string comparison.
For other languages, you can replace fa:
ar — Arabic
bg — Bulgarian
ca — Catalan
zh-Hans — Chinese, Han (Simplified variant)
cs — Czech
da — Danish
de — German
el — Modern Greek (1453 and later)
en — English
es — Spanish
fi — Finnish ,....

for more information please visit https://dev.to/aumayeung/comparing-non-english-strings-with-javascript-collators-57bf
and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator

A: I never tested it and really cannot do it because I have no idea what letter comes before or after in arabic but I can point you to the right direction. You will need to use localeCompare in a way similiar to this:
arr.sort((x,y)=>x.localeCompare(y, 'ar-ma'))

ar-ma being Arabian Morocco language code which you should change to the language code of your needs.

A: I had same problem And I wrote this function , It works well for me ..
so I decided to share it here for you :

// costome order of english and persian letters
var persianAlphabets = [" ", "آ", "ا", "ب", "پ", "ت", "ث", "ج", "چ", "ح", "خ", "د", "ذ", "ر", "ز", "ژ", "س", "ش", "ص", "ض", "ط", "ظ", "ع", "غ", "ف", "ق", "ک", "گ", "ل", "م", "ن", "و", "ه", "ی", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];

// function for sorting an array of persian words
function customSort(x, y) {
  var i = 0;
  var maxLen = Math.min(x.length, y.length);

  function increseIndex() {
    if (persianAlphabets.indexOf(x[i]) == persianAlphabets.indexOf(y[i]) &&
      i <= maxLen) {
      i++;
      increseIndex();
    } else return
  }
  increseIndex();

  if (persianAlphabets.indexOf(x[i]) <
    persianAlphabets.indexOf(y[i])) {
    return -1;
  }
  if (persianAlphabets.indexOf(x[i]) >
    persianAlphabets.indexOf(y[i])) {
    return 1;
  }
  return 0;
}

// sample array for testing
var testArrray = [
  "بابا",
  "آبادان",
  "آب",
  "احمد آقا",
  "احد محمدی",
  "احد مرادی",
  "یونس",
  "مادر 1",
  "آبادانی",
  "ش س",
  "شگیرا",
  "یدالله",
  "مادر 2",
  "سلام"
];

// applying the sorting function
testArrray.sort(customSort);

// testing resoults
console.log(testArrray);

A: String#localeCompare is supposed to be locale-aware and compare strings appropriately, so:
function OrderFunc() {
  // Get the list
  const ul = document.querySelector(".myul");
  // Get its items as an array
  const lis = [...ul.querySelectorAll("li")];
  // Sort the array with localeCompare
  lis.sort((a, b) => a.textContent.localeCompare(b.textContent));
  // Move each of them to the end of the list; this
  // puts them back in order
  for (const li of lis) {
    ul.appendChild(li);
  }
}

Live Example:

function OrderFunc() {
    // Get the list
    const ul = document.querySelector(".myul");
    // Get its items as an array
    const lis = [...ul.querySelectorAll("li")];
    // Sort the array with localeCompare
    lis.sort((a, b) => a.textContent.localeCompare(b.textContent));
    // Move each of them to the end of the list; this
    // puts them back in order
    for (const li of lis) {
        ul.appendChild(li);
    }
}
OrderFunc();

ی

پ

گ

ژ

You may need to pass some options to localeCompare, see the ECMAScript® Internationalization API Specification for more on that.

In a comment you asked:

What will i do first Persian and Second English Words?

If you're asking how to sort Persian words above English ones in the list, I think you'll probably have to detect what script the text is written in. You're supposed to be able to do that with a JavaScript regular expression, but the feature (Unicode property excapes) is new and not well-supported yet. You can use the XRegExp library to do it, though:
// This checks to see if the FULL string is in Arabic script; you'll
// probably have to adjust it to fix your use case
const rexArabic = XRegExp("^\\p{Arabic}+$");
function OrderFunc() {
    // Get the list
    const ul = document.querySelector(".myul");
    // Get its items as an array
    const lis = [...ul.querySelectorAll("li")];
    // Sort the array with localeCompare
    lis.sort(({textContent: a}, {textContent: b}) => {
        const aArabicScript = rexArabic.test(a);
        const bArabicScript = rexArabic.test(b);
        if (aArabicScript && !bArabicScript) {
            // `a` is in Arabic script, `b` isn't; `a` should be first
            return -1;
        }
        if (!aArabicScript && bArabicScript) {
            // `b` is in Arabic script, `a` isn't; `b` should be first
            return 1;
        }
        // They're in the same script
        return a.localeCompare(b);
    });
    // Move each of them to the end of the list; this
    // puts them back in order
    for (const li of lis) {
        ul.appendChild(li);
    }
}

Live Example:

// This checks to see if the FULL string is in Arabic script; you'll
// probably have to adjust it to fix your use case
const rexArabic = XRegExp("^\\p{Arabic}+$");
function OrderFunc() {
    // Get the list
    const ul = document.querySelector(".myul");
    // Get its items as an array
    const lis = [...ul.querySelectorAll("li")];
    // Sort the array with localeCompare
    lis.sort(({textContent: a}, {textContent: b}) => {
        const aArabicScript = rexArabic.test(a);
        const bArabicScript = rexArabic.test(b);
        if (aArabicScript && !bArabicScript) {
            // `a` is in Arabic script, `b` isn't; `a` should be first
            return -1;
        }
        if (!aArabicScript && bArabicScript) {
            // `b` is in Arabic script, `a` isn't; `b` should be first
            return 1;
        }
        // They're in the same script
        return a.localeCompare(b);
    });
    // Move each of them to the end of the list; this
    // puts them back in order
    for (const li of lis) {
        ul.appendChild(li);
    }
}
OrderFunc();

ی

پ

Some English

گ

More English

ژ

A: Crowder gave the correct answer. But if you want to take matter in your own hands,  you can apply your custom sorting function which sorts by comparing indexes in the reference array.
var alphabets = ["ا", "ب", "پ", "ت", "ث", "ج","چ","ح","خ","د","ذ","ر","ز","ژ","س","ش","ص","ض","ط","ظ","ع","غ","ف","ق","ک","گ","ل","م","ن","و","ه","ی","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];

var testArrray = ["ی","گ","ژ","پ"];
testArrray.sort(customSort(alphabets));
function customSort(alphabets){
    return function (x,y) {
      if (alphabets.indexOf(x) < alphabets.indexOf(y)) {
        return -1;
      }
      if (alphabets.indexOf(x) > alphabets.indexOf(y)) {
        return 1;
      }
      return 0;
  }
}
console.log(testArrray);

A:

function OrderFunc() {
    // Get the list
    const ul = document.querySelector(".myul");
    // Get its items as an array
    const lis = [...ul.querySelectorAll("li")];
    // Sort the array with localeCompare
    lis.sort((a, b) => a.textContent.localeCompare(b.textContent));
    // Move each of them to the end of the list; this
    // puts them back in order
    for (const li of lis) {
        ul.appendChild(li);
    }
}
OrderFunc();

ی

پ

گ

ژ

A: This is my best working solution:

function PersianSort(words,target) {
    var els = $(words).get();
    els.sort(function(el1, el2){
        return $(el1).text().trim().localeCompare($(el2).text().trim())
    });
    $(target).append(els)
}
ul.container li {
   padding:5px;
}

<button onclick="PersianSort('.container li','.container')" type="button" value="1">Sort</button>

هستی

گلی

Reza

چکامه

Amir

ویدا

ژاله

Ramin

پوران

یگانه

آناهیتا

آلاله

A: I tested the code below and it worked for me.
I hope this could help other people who are looking for a good and fast solution.
    const result = [ {code: 1, title: 'کارن'},
                     {code: 2, title: 'پیروز'},
                     {code: 3, title: 'ایران'}]
    const sortedResult = result.sort((a,b)=> {
          return a.title.localeCompare(b.title, 'fa')
    )}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Observable with Timer for specifc value Not sure about the title of my question but hopefully I can explain what I am trying to do.
I want to have a Timer to inject a value into a sequence but when a specific value is observed.
I want the Timer to be cancelled when any other value is entered into the sequence.
public enum State
{
    Connected,
    Disconnected,
    DisconnectedRetryTimeout
}

var stateSubject = new Subject<State>();

var connectionStream = stateSubject.AsObservable();

var disconnectTimer =
    Observable.Return(State.DisconnectedRetryTimeout)
        .Delay(TimeSpan.FromSeconds(30))
        .Concat(Observable.Never<State>());

var disconnectSignal =
    disconnectedTimer
        .TakeUntil(connectionStream.Where(s => s == State.Connected))
        .Repeat();

var statusObservable =
    Observable.Merge(connectionStream, disconnectSignal)
        .DistinctUntilChanged();

So when nothing is in the stream (i.e. new) no timer.
When Connected|DisconnectedRetryTimeout is add no timer.
When Disconnected is add I want the timer to start
If Connected is on the stream before the timer fires I want the timer cancelled
The Timer should  only fire once, until Disconnected is received again.
Pretty new to RX and ran out of ideas on this one.
Any help much appreciated.

A: If I understand the problem correctly: We start with a state stream that will emit either Connected or Disconnected messages. We want to enrich this with DisconnectedRetryTimeout message that appears if a Disconnected message sits on the stream for 30 seconds without a Connected message appearing.
One way to do this has the following idea:
Project the Connected/Disconnected stream into the DisconnectedRetryTimeout stream as follows:

*

*First strip duplicates with DistinctUntilChanged as we only want the first Disconnected message of a batch to start a timer.

*If Disconnected is received, project this event as a stream that emits DisconnectedRetryTimeout after 30 seconds

*If Connected is received, just project an infinite and empty stream (Observable.Never)

*With the above, we end up with a stream of streams, so now we use Switch which flattens this by always taking the most recent stream. So if Connect appears whilst the timer is in flight, the Never stream will replace the timer stream.

Now we can merge this with the original de-duped stream. Note that we publish the de-duped stream because we will be subscribing to it twice - if we don't do this, and the source is cold then we can run into problems. See more about that here.
var stateSubject = new Subject<State>();

var state = stateSubject.DistinctUntilChanged().Publish().RefCount();

var disconnectTimer = state
    .Select(x => x == State.Disconnected
        ? Observable.Timer(TimeSpan.FromSeconds(30))
            .Select(_ => State.DisconnectedRetryTimeout)
        : Observable.Never<State>())
    .Switch();

var statusObservable =
    state.Merge(disconnectTimer);

EDIT: Simpler Version
You can do this all in one go and drop the publish step and merge - by using StartWith we can push the Disconnected events through the timer stream, and with Observable.Return we can push the Connected through replacing the empty Never stream:
var statusObservable = stateSubject
    .DistinctUntilChanged()
    .Select(x => x == State.Disconnected
        ? Observable.Timer(TimeSpan.FromSeconds(5))
                    .Select(_ => State.DisconnectedRetryTimeout)
                    .StartWith(State.Disconnected)
        : Observable.Return(State.Connected))
    .Switch();


text:
Q: Find $\frac{d}{dx}\left(\frac{f}{g}\right)(x)$ when $x = 2 $

known : $\dfrac{df(x)}{dx} = 3$ when $x = 2$.
$\dfrac{dg(x)}{dx} = 4$ when $x = 2$.
$\dfrac{d}{dx}(f(x)\cdot g(x)) = 11$ when $x = 2$.
$d\left(f^2(x) + g^2(x)\right) = 20$ when $x = 2$. Find $\frac{d}{dx}\left(\frac{f}{g}\right)(x)$ when $x = 2 $

$f'(2) = 3$
$g'(2) = 4$
$(f(2)\cdot g(2))'=11$
$\left(f(2)^2 + g(2)^2\right)' = 20$
Find $\frac{d}{dx}\left(\frac{f}{g}\right)(x)$ when $x = 2 $
$y = \frac{f(x)}{g(x)} \rightarrow y' = \frac{f'(x) \cdot g(x) - g'(x)\cdot f(x)}{{g(x)}^2}$
$\left(\dfrac{f(2)}{g(2)}\right)' =\dfrac{ f'(2)g(2) - g'(2)f(2)}{g(2)^2}$
$\left(f(2)^2 + g(2)^2\right)' = 20$
$2f(2)' + 2g(2)' = 20$
But how to find $g(x)$ and $f(x)$? please help me, thanks in advanced

A: $\frac{d}{dx} \frac{f(x)}{g(x)} = \frac{f'(x)g(x)-g'(x)f(x)}{(g(x))^2}$
Now let's find the unknown. For $\left(f(x)\cdot g(x)\right)'$
$$(f(x)\cdot g(x))' = f'(x)g(x)+g'(x)f(x)$$
Plug $x=2$
$$f'(2)g(2)+g'(2)f(2)=11\\
4f(2)+3g(2) = 11 \text{ ... (1)}$$
For $\left( (f(x))^2 +(g(x))^2 \right)$
$$\begin{aligned}
\left((f(x))^2+(g(x))^2\right)'&=2f(x)f'(x)+2g(x)g'(x)
\end{aligned}$$
Plug $x=2$
$$2f(x)f'(x)+2g(x)g'(x)=20\\
3f(2)+4g(2)=10 \text{ ... (2)}$$
Solve for $(1) \text{ and }(2)$
$$f(2) = 2 \text{ and } g(2) = 1$$
Ergo
$$\frac{f'(2)g(2)-g'(2)f(2)}{(g(2))^2}=\frac{3-8}{1}=-5$$

A: We are given that

*

*$f'(2)=3$

*$g'(2)=4$

*$[f(x)g(x))]'_{x=2}=f'(2)g(2)+f(2)g'(2)=11\implies 4f(2)+3g(2)=11$

*$[f(x)^2+g(x)^2]'_{x=2}=2f(2)f'(2)+2g(2)g'(2)=20\implies3f(2)+4g(2)=10$.
Solving simultaneously yields $f(2)=2$ and $g(2)=1$. Thus \begin{align}\left[\frac{f(x)}{g(x)}\right]'_{x=2}&=\frac{f'(2)g(2)-f(2)g'(2)}{g(2)^2}=\frac{3\cdot1-2\cdot4}{1^2}=-5.\end{align}


text:
Q: Conditionally order results in the one response So I have a mongo collection with an array of chapters inside it.
What I want to do is do a find, sorted by date - but push all the documents that have only 1 chapter to the end of the list.
Note: I don't want to sort by chapters count - only push the 1 chapter documents to the end of the cursor.
Now I could do 2 finds:
cursor1 = collection.find({'chapters.1':{$exists: true}})
//iterate over it
cursor2 = collection.find({'chapters.1':{$exists: false}})
//iterate over it

The problem is - I'm doing pagination. Currently without the seperation is:
(sorry for pseudocode - translating from PHP)
cursor = collection.find()
cursor.sort({created: -1})
cursor.skip($page * $page_size)
cursor.limit($page_size);

When trying the above solution to separate - it creates quite a nasty code
Do I have a choice? Any magic "push 1 chapters to the end" to push into the find itself?

A: It sounds like you want to "weight" things with only one array element so that you can "sort" the results on that weight. This effectively would be "chapters longer than 1" with a 0 score, and "chapters with length 1" with a 1 score, and ascending sort on that weight score so the 1 lengths are at the end of the list.
To do this you use something that can modify the document, such as .aggregate(). Where we are basically going to inspect each document and calculate the weight:
collection.aggregate([
    { "$project": {
        "someField": 1,
        "chapters": 1,
        "created": 1,
        "weight": {
            "$cond": [
                { "$lte": [ { "$size": "$chapters" }, 1 ] },
                1,
                0
            ]
        }
    }},
    { "$sort": { "weight": 1, "created": -1 } },
    { "$skip": numToSkip },
    { "$limit": numToLimit }
])

That means that all the documents with a chapters that only have one or less items in the array will be "sorted" to the bottom of the results.
Read about $project as you must explicitly name each field you want in the results. Or you can alter the document to contain the original document under a single result field and project using $$ROOT.
For a better approach to forward paging see, Calculate skip value for given record for sorted paging and impelement the principles there if you can.


text:
Q: Second order nonhomogenous ODE with Dirichlet boundary condition I would like to know a hint for this problem. Brezis describes it as it can be "solved explicitly by a very simple calculation". The problem is:
Given $f\in C^1([a,b])$, find a function $u$ satisfying:
\begin{equation}\tag{1}
-u''+u=f, \text{   on  }[a,b],
\end{equation}
and
$$u(a)=u(b)=0.\tag{2}$$
Thanks Umberto P. I found the solution for (1) is:
$$u(t)=c_1(t)e^t+c_2(t)e^{-t}, \text{   where}$$
$$ c_1'(t)=-\frac{f(t)}{2e^{t}}, \text { and  } $$
$$c_2'(t)=\frac{f(t)}{2e^{-t}} .$$
So functions $c_1$ and $c_2$ are determined modulo one constant. However, taking $a=0$ and $b=1$ and writing the boundary condition (2) results in a system that I can't solve.

A: This is a second order nonhomogeneous ODE with constant coefficients. You can find the method of solution in most calculus books. Look up e.g. "variation of parameters".


text:
Q: Postgres JDBC driver not returning error line number as shown in PGAdmin Postgres JDBC driver not returning the exact error line number as shown in PGAdmin. When I run the below program :
import java.sql.*;

public class Test {

  public static void main(String[] args) {

    String query = "SELECT table_name, table_type\n" +
      "  FROM information_schema.tabls\n" +
      " WHERE table_schema='public'\n" +
      "   AND table_type in ('BASE TABLE','VIEW') ORDER BY table_type, table_name;";

    try (Connection connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgres", "postgres", "postgres")) {

      System.out.println("Connected to PostgreSQL database!");
      Statement statement = connection.createStatement();
      ResultSet resultSet = statement.executeQuery(query);
      while (resultSet.next()) {
        System.out.printf("%-30.30s  %-30.30s%n", resultSet.getString("table_name"), resultSet.getString("table_type"));
      }

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

I am getting the following error :
 org.postgresql.util.PSQLException: ERROR: relation "information_schema.tabls" does not exist
  Position: 38

But when I run the same query on pgadmin4, I receive the following error :
    ERROR:  relation "information_schema.tabls" does not exist
LINE 2:   FROM information_schema.tabls
               ^
SQL state: 42P01
Character: 38

I want the line number in java program as well. How can I get it?

A: PGAdmin4 is a node.js backend that uses Python driver psycopg2. This driver is nothing more than a wrapper for C driver named libpq, created by the PostgreSQL team.
JDBC driver communicates with database and uses responses received from the server. org.postgresql.core.v3.QueryExecutorImpl#receiveNoticeResponse private method  responsible for parsing server errors and it just creates new org.postgresql.util.ServerErrorMessage instance. So, the response given by the server is equal to the response shown by the JDBC driver.
But as for libpq, messages received from the server, and shown on client-side aren't the same. There is reportErrorPosition method in libpq sources exactly for adding line information. Here is reference for reportErrorPosition sources for PostgreSQL 13.3. Here is place where LINE: x is added to the client error.
Summary
You need to calculate the line number by yourself when using the JDBC driver. Or use C library which does it for you.


text:
Q: Can this be accomplished with CSS?
Can the line behind the text be accomplished with CSS only?

A: Yes.
HTML:

Centered Header Text

CSS:
body {
    background: #ccc;
}

h2 {
    text-align: center;
    display: table;
    width: 100%;
}
h2 > span, h2:before, h2:after {
    display: table-cell;
}
h2:before, h2:after {
    background: url(http://dummyimage.com/2x1/f0f/fff&text=+) repeat-x center;
    width: 50%;
    content: ' ';
}
h2 > span {
    white-space: nowrap;
    padding: 0 9px;
}

JSFiddle
Source

A: Yes it can.
No images, no tables, just two elements and simple CSS.
Here's a fiddle to demonstrate it: http://jsfiddle.net/URrdP/
HTML:

 Text Here

CSS:
div {
    font-size: 45px;
    border: #EEEEEE inset 2px;
    position: relative;
    text-align:center;
    height: 0px;
}
span {
    position: relative;
    top:-0.7em;
    background: #CCCCCC;
}

The key points here are that the outer element has an inset border and zero height and the inner element is positioned half a line upward so it sits on top of the outer element's border.
The other key point is that the inner element has a solid background color, otherwise the border line would show through. This means the technique will only really work successfully when you are placing it on top of a solid background; putting it on top of a gradient or an image may not work so well.
I may not have got the colors or the font sizing perfect for you in my example, but the principle should work perfectly fine for you.
CSS border inset may not be the best way to get a perfect colour match for you; if you need more fine-grained control of the colours you can specify individual colours for border-top and border-bottom.

A: Here's how you could do something similar with no images.
HTML:

Text Here

CSS:
body, span { background: #ccc; }

h1 { text-align: center; border-bottom: 1px solid #333; font-size: 20px; height: 10px; }

JSFiddle http://jsfiddle.net/ChrisLTD/fvetd/

A: Without images version (I'd prefer the display:table version though)
CSS:
body
{background:silver;}

h1
{text-align:center;color:white;font-weight:normal;position:relative;
line-height:1;text-shadow:0 1px black;font-size:34px;font-family:georgia, serif}

h1::before, h1::after
{width:100%;border-bottom:1px white solid;content:' ';
position:absolute;top:50%;left:0;}

h1::after
{margin-top:-1px;border-color:gray}

h1 > span
{background:silver;position:relative;z-index:1;}

HTML:

    Text Here

    On Multiple Lines too

Demo: http://jsbin.com/uqexar/1/edit

A: Since there was no HTML specification, I added in a couple of spans

    TEXT HERE

CSS:
h1 {
    width:300px;
    background:#dcdcdc;
    padding:10px;
    text-align:center;
    color:#333;
}
.wrapper {
    display:block;
    position:relative;
}
.line {
    display:block;
    height:1px;
    background:#cecece;
    border-bottom:1px solid #e3e3e3;
    width:100%;
    position:absolute;
    top:50%;
    z-index:100;
}
.text {
    z-index:200;
    position:relative;
    padding:10px;
    background:#dcdcdc;
    display:inline-block;
}

This means the line will look like you specified with two greys.
http://jsfiddle.net/3q5he/

A: This can be done with a single element:
http://jsfiddle.net/Puigcerber/vLwDf/

Heading

h1 {
    overflow: hidden;
    text-align: center;
}
h1:before,
h1:after {
    background-color: #000;
    content: "";
    display: inline-block;
    height: 1px;
    position: relative;
    vertical-align: middle;
    width: 50%;
}
h1:before {
    right: 0.5em;
    margin-left: -50%;
}
h1:after {
    left: 0.5em;
    margin-right: -50%;
}

Origin: http://www.impressivewebs.com/centered-heading-horizontal-line/#comment-34913


text:
Q: Panel with time fixed effects and a variable with high correlation across individuals I have panel data of countries and I am estimating a Fixed Effects model similar to
$$
y_{ct} = \underbrace{\theta_t}_{\text{Time FE}} + \underbrace{\theta_c}_{\text{Country FE}} + \beta^1x^1_{ct} + \beta^2x^2_{ct} + \varepsilon_{ct}
$$
For every $t$, the variable $x^2_{ct}$ is highly correlated across countries. That is, $x^2_{ct}$ shows high correlation in the cross-sectional dimension. This means that almost all of its variation can be captured by $\theta_t$. Thus, when I fit this model, I get that $\beta^2$ is not significant at all.
However, theory suggest that $x^2_{ct}$ should have a strong causal impact on $y_{ct}$. So the question is: assuming I have controlled for all confounders with $(\theta_t, \theta_c, x^1_{ct})$, is it possible to estimate $\beta^2$ using this setup?
P.S.: for the estimation, I assume two-way clustering in $\varepsilon_{ct}$

A: The significance of a coefficient increases with the variance of the regressor. If $x^{2}_{ct}$ is highly correlated across countries and your data is country level, then you will have low variance. Unsurprisingly, this leads to an insignificant $\beta^2$, whether your have country FE or not. Taking out $\theta_c$ is unlikely to fix this problem.
Of course, if you can control for all relevant country characteristics, then you do not need the country FE. Nevertheless, it is very unlikely that you can.
Especially with cross-country data, regressions without country FE are suspect, because countries themselves can vary across so many dimensions that it is hard to interpret regression coefficients as being causal and it is near impossible to control for all relevant country factors. I would not recommend running a cross-country regression without country FE.


text:
Q: How can I find the full path to a font from its display name on a Mac? I am using the Photoshop's javascript API to find the fonts in a given PSD.
Given a font name returned by the API, I want to find the actual physical font file that font name corresponds to on the disc.
This is all happening in a python program running on OSX so I guess I'm looking for one of:

*

*Some Photoshop javascript

*A Python function

*An OSX API that I can call from python

A: open up a terminal (Applications->Utilities->Terminal) and type this in:
locate InsertFontHere

This will spit out every file that has the name you want.
Warning: there may be alot to wade through.

A: I haven't been able to find anything that does this directly.  I think you'll have to iterate through the various font folders on the system: /System/Library/Fonts, /Library/Fonts, and there can probably be a user-level directory as well ~/Library/Fonts.

A: There must be a method in Cocoa to get a list of fonts, then you would have to use the PyObjC bindings to call it..
Depending on what you need them for, you could probably just use something like the following..
import os
def get_font_list():
    fonts = []
    for font_path in ["/Library/Fonts", os.path.expanduser("~/Library/Fonts")]:
        if os.path.isdir(font_path):
            fonts.extend(
                [os.path.join(font_path, cur_font)
                 for cur_font in os.listdir(font_path)
                ]
            )
    return fonts

A: Unfortunately the only API that isn't deprecated is located in the ApplicationServices framework, which doesn't have a bridge support file, and thus isn't available in the bridge. If you're wanting to use ctypes, you can use ATSFontGetFileReference after looking up the ATSFontRef.
Cocoa doesn't have any native support, at least as of 10.5, for getting the location of a font.

A: I had encountered similar requirements and I ended up by this method:
def get_font_path(font):
    ttf_filename = os.path.basename(font)
    dirs = []
    if sys.platform == "win32":
        # check the windows font repository
        # NOTE: must use uppercase WINDIR, to work around bugs in
        # 1.5.2's os.environ.get()
        windir = os.environ.get("WINDIR")
        if windir:
            dirs.append(os.path.join(windir, "fonts"))
    elif sys.platform in ("linux", "linux2"):
        lindirs = os.environ.get("XDG_DATA_DIRS", "")
        if not lindirs:
            # According to the freedesktop spec, XDG_DATA_DIRS should
            # default to /usr/share
            lindirs = "/usr/share"
        dirs += [
            os.path.join(lindir, "fonts") for lindir in lindirs.split(":")
        ]
    elif sys.platform == "darwin":
        dirs += [
            "/Library/Fonts",
            "/System/Library/Fonts",
            os.path.expanduser("~/Library/Fonts"),
        ]

    ext = os.path.splitext(ttf_filename)[1]
    first_font_with_a_different_extension = None
    for directory in dirs:
        for walkroot, walkdir, walkfilenames in os.walk(directory):
            for walkfilename in walkfilenames:
                if ext and walkfilename == ttf_filename:
                    return os.path.join(walkroot, walkfilename)
                elif (
                    not ext
                    and os.path.splitext(walkfilename)[0] == ttf_filename
                ):
                    fontpath = os.path.join(walkroot, walkfilename)
                    if os.path.splitext(fontpath)[1] == ".ttf":
                        return fontpath
                    if (
                        not ext
                        and first_font_with_a_different_extension is None
                    ):
                        first_font_with_a_different_extension = fontpath
    if first_font_with_a_different_extension:
        return first_font_with_a_different_extension

Note that the original code is from PIL

A: With matplotlib (pip3 install -U matplotlib):
from matplotlib import font_manager

fontmap = {font.name: font for font in font_manager.fontManager.ttflist}
fontmap.update({font.name: font for font in font_manager.fontManager.afmlist})

print(f'Total fonts: {len(fontmap.keys())}')

for family in sorted(fontmap.keys()):
    font = fontmap[family]
    print(f'{family:<30}: {font.fname}')

Sample output
Total fonts: 312
.Aqua Kana                    : /System/Library/Fonts/AquaKana.ttc
Academy Engraved LET          : /System/Library/Fonts/Supplemental/Academy Engraved LET Fonts.ttf
Al Bayan                      : /System/Library/Fonts/Supplemental/AlBayan.ttc
American Typewriter           : /System/Library/Fonts/Supplemental/AmericanTypewriter.ttc
...
Zapf Dingbats                 : /System/Library/Fonts/ZapfDingbats.ttf
ZapfDingbats                  : /usr/local/lib/python3.9/site-packages/matplotlib/mpl-data/fonts/pdfcorefonts/ZapfDingbats.afm
Zapfino                       : /System/Library/Fonts/Supplemental/Zapfino.ttf

NOTE: The font families from matplotlib do not seem to include all system fonts that are available for example to the PyQt5 library:
from PyQt5.QtGui import QFontDatabase
from PyQt5.QtWidgets import QApplication

app = QApplication([])
print('\n'.join(QFontDatabase().families()))


text:
Q: Save textbox value into JSON using angularJS How to save a textbox value into a JSON file using AngularJS?
For example

  Email (ID)
  <input type="text" size="15" id="email_id" ng-model="email_ID" />
  Contact Number
  <input type="text" size="15" id="C_Num" ng-model="Contact" />

On the click of button, the data residing on textbox should save on JSON file using AngularJS.

A: In order to transform something in JSON string you should have an object. It works with simple variables to but I would not make much difference for what you're trying to accomplish.
Anyway to save your model as a JSON string inside a textarea by clicking a button you should do something like this:
My name: <input type="text" ng-model="myModel.name">
My phone: <input type="text" ng-model="myModel.phone">
<button ng-click="jsonString = angular.toJson(myModel)">Save JSON</button>
<textarea ng-model="jsonString"></textarea>


text:
Q: Программа нажатия кнопки через заданное время Нужна программа, которая будет автоматически вызывать нажатие кнопки "f10" через заданное мною время (не периодически) для реакции другой запущенной программы. Запросы в Google результата не дали.
Как новичку, стало интересно, можно ли написать что-то подобное, например, на C# без больших затрат времени? Есть идеи?
UPD: Насчёт Timer я понял. А как можно вызвать нажатие хоткея в методе?

A: Используй Timer. Создаешь таймер и подписываешься на событие его срабатывания. В обработчике события вызываешь событие нажатой кнопки.


text:
Q: How can i make my Lazyrow to scroll automatically in JetpackCompose? I have a list of items and I populate them in the UI using LazyRow. Now What i want is to scroll the row automatically infinitely. But not getting any clue about it.
item {
                LazyRow {
                    item { Spacer(modifier = Modifier.width(16.dp)) }
                    items(data.categories) { category ->
                        if(category.discount !=null && category.price!=null) {
                            ItemCard(
                                title = category.name,
                                imageUrl = category.image,
                                discount = category.discount,
                                price = category.price,
                                onClick = onCategoryClick
                            )
                        }
                        Spacer(modifier = Modifier.width(16.dp))
                    }
                }
            }

A: what you can do is listening the visible item count in your LazyRow scroll state and remove/append half portion of your list when a specified value passed such as:
val scrollState = rememberLazyListState()

val loadMore = remember {
        derivedStateOf {
            val layoutInfo = scrollState.layoutInfo
            val totalItemsNumber = layoutInfo.totalItemsCount
            val lastVisibleItemIndex = (layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: 0) + 1

            lastVisibleItemIndex > (totalItemsNumber - YOUR_DESIRED_NUMBER)
        }
    }

LaunchedEffect(loadMore) {
  snapshotFlow { loadMore.value }
     .distinctUntilChanged()
     .collect {
         //Remove desired count of items
         //Append the removed items to the end
     }
}

LazyRow(
    state = scrollState
) {
    items.forEach {
         item(key = item.id) { item -> //key is important here
              YourItem(item)
         }
    }
}


text: Q: Why might a PDF in a kernel density plot be "spikey"? I am plotting two kernel density plots where the Y-axis is the density, the X-axis is some attribute of the two data sets. Why might one data set look "spikey"? Is there some significant takeaway or inference that can be drawn about the data?


text:
Q: I made a special store front for a mobile version of my site. How to redirect mobile devices there and also link back to the desktop site? I've setup a special mobile store/store front under a subdomain - www.m.mydomain.com according to this tutorial.
I was going to put this code in the Miscellaneous scripts to make the system detect that a customer is connecting from a mobile device and forward the traffic to www.m.mydomain.com:
I have a special responsive mobile store at m.MYdomain.com - how to make Magento detect mobile devices and forward the traffic to m.Mydomain.com?
But now I'm thinking a better solution might just be through changing the .htaccess file as explained here.
But I don't understand where to put that code into? Also - that post is from 2010. Is there something newer to go with given the development in the mobile devices and tablets?
I also need to place a large button on the mobile site (at www.m.mydomain.com ) that would re-direct customers to the desktop version of the site (www.mydomain.com) if they choose to. What is the best way to do that?
I mean - How can this work? Will it not be stuck in a loop? When the customer clicks the button that will send it to www.mydomain.com, won't the script once again detect that it is a mobile device and transfer the traffic back to www.m.mydomain.com ? I read about doing it with cookies but how exactly? And how would I set that button up?
I am looking for a simple solution as in: take this code and put it here. Change this code here and you are done! :o)
In my example my desktop site is: www.mydomain.com and my mobile is at: www.m.mydomain.com while my desktop store name and store front name is: mydomain.com and my mobile store name and store front name is: mmydomaincom

Updated December 12th:
Please don't tell me to load a different theme. I already have a nice responsive theme! This is not the problem. The reason I want to redirect to my mobile site (located at www.m.mysite.com) is that I have around 50 products on my desktop front page and a lot of things (such as text put on there by the SEO company) that are just taking up space and I don't need to display that clutter on mobile devices. I think that ordering on a mobile device should be fast and easy without unnecessary junk. That said - I am not trying to reinvent the wheel here. I need 2 things.
1. Detect the mobile device and if that is so - load www.m.mysite.com instead of www.mysite.com
2. Add a button for people who for whatever reason (maybe they are connected to a fast wifi connection) decide they want the desktop version instead and make it work when they click it to display www.mysite.com
If you go to www.ebay.com on your mobile phone - it redirects to "m.ebay.com" Same with YouTube, Facebook, Twitter, LinkedIn...So don't tell me this is an old age approach. If these multi-billion dollar companies are doing it - it has some logic behind it....

A: https://stackoverflow.com/questions/3680463/mobile-redirect-using-htaccess
http://wpandsuch.com/redirect-to-a-mobile-site-with-htaccess-and-set-a-cookie-to-break-redirect/
Magento Redirect to mobile website when on Smart Devices
https://github.com/LimeSoda/LimeSoda_MobileRedirect
https://github.com/sebarmeli/JS-Redirection-Mobile-Site
https://github.com/vkathirvel/Magento-Extension-MobileDetect
http://mobiledetect.net/
Multi store magento redirects to main store
https://www.cloudways.com/blog/create-and-configure-multistore-magento-2/
Magento 2 with multiple domain names
This is the best article so far: https://www.forgeonline.co.nz/magento-multistore-website-shopfront/
U need to set Cookie & Flag then it will work out. U can also refer to Magento Default .htaccess which provides already

A: First off, the link you provided is for setting up a multisite/multi store. For example, when you have a multi language site; it detects patterns in the domain name and sets the proper store code if set.
To answer your second question: The .htaccess code of 2010 should still work. Haven't tested it yet, but it's nothing more than checking the user-agent against a regular expression and nothing much has changed since then.
So you could use the second example to set the redirect. However, you want to be able to redirect back to the site, effectively ignoring the .htaccess-rule.
I think your best bet may be to not use the .htaccess-rule, but rather let Magento handle the redirect according to the user agent. See this article on how to set this up.
The second challenge you have then is to make Magento ignore this redirect if someone explicitly chooses the link on one of those mobile devices. I think you can best handle this by tracking down the code in Magento that handles the redirect and create a module that rewrites this code (or if you're lucky there's an event for that). In your module, you can then check if there's a flag in your URL (like ?noredirect or something), and add a flag to the user session so it never will trigger the redirect.
So no, there's not a 'one-line-solution' for what you're trying to achieve, but if you know how-to-Magento, it's not a very difficult task to setup.
But... why use a mobile site in the first place? Why not make your template responsive? Mobile redirects or so 2001...

A: you should add exceptions for the mobile devices. Navigate to the Magento administrative area -> System -> Configuration -> Design -> Themes. Click on the Add Exceptions buttons beside the Templates, Skin and Layout labels.
And for the Matched exceptions add **iPhone|iPod|BlackBerry|Palm|Googlebot-Mobile|Mobile|mobile|mobi|Windows Mobile|Safari Mobile|Android|Opera Mini**

This solution assumes that you have a different custom theme for mobile store

A: <?php

$useragent=$_SERVER['HTTP_USER_AGENT'];

if(preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i',$useragent)||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i',substr($useragent,0,4)))

header('Location: http://detectmobilebrowser.com/mobile');

?>

in header location you specify store url of mobile device


text:
Q: tableview won't update after adding objects to an array I have a tableview inside a popover in my main view which is a web browser. Whenever the user visits a web page I want it to add the page to a list of recently visited websites. I have the code set up to add the URL as a string to the array that is the data source for the table view. The table view only shows the first site visited and won't show anything past that. However I know the sites are being added to the array because the array shows the Sites using NSLog statements after being added. However they still won't show up in the table. Can anyone help me?
EDIT:
 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    // Return the number of rows in the section.
    return [recentlyVisitedUrls count];
}

A: Try
[tableView reloadTable];

after you add the new data.

A: Also make sure you are returning the correct length of your array from – tableView:numberOfRowsInSection:

A: If you wan't animated updating, you can call:
[self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO]
If you need animation, it will be better read: Table View Programming Guide for iOS, you need Batch insert… part.

A: If you have a large table, [tableView reloadData] is probably not ideal. It'll also will reset your view to the beginning of the table, which may or may not be desirable.  You might try something like this:
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_model.recordCount - 1 inSection:0];
[_tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationRight];
[_tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];

BTW, _model is the data delegate class for the table in the example.
Also, make sure the data delegate updates it's total count correctly before you insert, or your app will crash on the insertRowsAtIndexPaths.


text:
Q: Making a phone call not directly To make a phone call, I just click on a button and I'm directly making the phone call. But I want to change that.
What I want, it's when I click on the button, I move to the composer like in this image.
Then, I can confirm ou not the call phone.
Please, can you helpe me ? This is my actual code
    buttonCall.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View view){
                Intent call = new Intent(Intent.ACTION_CALL);
                call.setData(Uri.parse("tel:" 1234567));
                startActivity(call);
        }
    });

A: Use Intent.ACTION_DIAL or Intent.ACTION_VIEW instead of Intent.ACTION_CALL.
From Intent:

ACTION_VIEW tel:123 -- Display the phone dialer with the given number filled in.
ACTION_DIAL tel:123 -- Display the phone dialer with the given number filled in.

A: I guess you want to show the dialpad with the phone no.
Use this in onClick
Intent dial = new Intent();
dial.setAction("android.intent.action.DIAL");
dial.setData(Uri.parse("tel:"+number));
startActivity(dial);

A: Use this :
Intent call = new Intent(Intent.ACTION_DIAL);


text:
Q: Can I import a parameter defined file in Symfony? For a specific situation, my Symfony2 project has different versions of configuration files. A concrete simple example would be the security file :
security_db.yml
security_ldap.yml

I would like the used file to be defined in the parameters.ini file.
This is what I tried to add in the config.yml:
imports:
- { resource: "security_%authentification%.yml" }

While having the authentification parameter defined in my parameters.ini file but I always have the same error :
The file "security_%authentification%.yml" does not exist

A: I believe one way to do this is to use your Extension class to load the proper config based on what is defined in your parameters.ini ... This is untested ...
src/MyAwesomeBundle/DependencyInjection/MyAwesomeExtension.php
class MyAwesomeExtension extends Extension
{

    public function load(array $configs, ContainerBuilder $container)
    {
       // boiler plate code here ... this probably already exists in your class.
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.xml');

        // your personalized loader goes here ...
        $myloader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));

        $auth = $container->getParameter('authentication');
        if (isset($auth)) {
            $myloader->load('security_' . $auth . '.yml');
        }
    }

}


text:
Q: How to access Configuration file in Class library from webpage as well as webform I have several projects some of which are web applications and some are windows applications.
I wanted to globalize my settings, something like Connection Strings because all the projects use the same connection string.
So I followed this example How to share custom application configuration settings across projects in .NET
my XML file is in the  class library and that is referenced in each project. The windows project are working fine with the file path which is something like this in the client project:
<configuration>
      <appSettings file="F:\Classes\ConnectionStringFile.xml">

      </appSettings>

    </configuration>

I also want to be able to use this xml file from a web project. however, the web project would not accept the path to this file as shown earlier.
What is the best approach or say, best solution to have this connection string file shared amongst web projects as well as windows projects. What do i pass in

something like <appSettings file ="~/classLibrary/ConnectionStringFile.xml" ???`

A: The solution we use is to store shared settings in a custom folder beneath the CommonApplicationData folder (e.g. C:\ProgramData on Windows7):
var commonAppData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
var settingsFilePath = Path.Combine(commonAppData, "MyProgram\\Settings.xml");

A: file= accepts relative paths, and *.config files are excluded from ASP.NET and IIS static file rules, so it is safe to drop any *.config file into an ASP.NET site.  Just put it next to the web.config file (root of the web app), mylibrary.config, and file="mylibrary.config".


text:
Q: Exporting and importing subscriptions to SharePoint-hosted reports that were created in SQL Server Reporting Services I came across this question in related questions which basically asks the same thing.
Is there a way of exporting and importing subscriptions to SharePoint-hosted reports that were created in SQL Server Reporting Services?
Scenario: During report re-deployments, reports are deleted and re-created, and the associated subscriptions are deleted (orphaned?). Is there a way (automated - either by a custom tool or via SharePoint/SSRS APIs) that I can export out the subscriptions before deleting the associated report and import back the subscriptions after the report has been redeployed?

A: Something to try...
When a SSRS subscription is create a job gets created under SQL Server Agent\Jobs. The job name looks like a guid so it's not easy to tell one subscription from another. But you can right click on the job and the "Script Job as" options are available.
I'm sure someone with more T-SQL could come up with a neat little script that does everything for you. But that would be a whole new question. :)
Note: I know this for sure with SSRS 2005 I would image 2008 is similar.


text:
Q: Nginx rule to redirect user to a /404 url if the current url ends with index.php I am looking for an NGINX rule for my website.
If the user lands on my website with a URL having index.php at the end I want to redirect them to a /404 URL with a 404 status code.
for eg
http://example.com/index.php => http://example.com/404
http://example.com/abcd/index.php => http://example.com/404
http://example.com/abcd/dcba/index.php => http://example.com/404
so far I have this but this doesn't work.
location ~ index\.php$ {
        return 404 https://$host/404;
    }


text:
Q: Oracle - OCI query timeout Is there any way to set a timeout on Oracle OCI calls (OCIStmtExecute for example) ?
Thanks

A: There is no way provided by OCI itself.
You can create a Timer and issue an OCIBreak() on timeout.
OCIBreak() is thread safe and signal safe.

A: Timeouts can be set on oracle server side, but not through any OCI APIs.

A: PHP's OCI module can do it according to this comment:
http://www.php.net/manual/en/function.oci-connect.php#84144


text:
Q: Calling php function from /var/www/folder (as www-user), which is located in a file in /var (or any folder) (with root permissions?) I wrote a script which "walks" through /var/www/xyz and scans folders and more. The folders are all 'user-bound', so the permissions for a single folder there are set to the specific user.
Running this script as root (for example in /root, 'php myscript.php') returns the expected results.
Now I want to transfer the results to the browser: in /var/www/newfolder I created a file index.php, just pasted the script into the file and tried it (in the browser) and of course failed. It just shows me a little part of the results (showing the user-specific folder names, when does not get deeper). Pretty sure it's a permission thing, being the www-user.
Phew, so the question is: is there a possibility to put a file with a function (for example) into /var, and allow a www user in the browser to ONLY CALL THAT function? If yes, any useful links or tips? (I googled really hard and a long time now, but what I found was worth nothing)
OR
Call a function in my /var/www/newfolder/ which has enough permission to scan the user-folders? (I guess that is critical regarding safety)

A: You are correct to be concerned about security. You can use the setuid bit to create an executable that runs as the owner of the executable instead of the user that called the executable. If the executable is owned by root then it would run as root (be sure not to give write privileges to anyone but root). Use group permissions if you want to limit who can run the executable.
Use chmod o+s <path to script> to turn on the setuid bit. (chmod 4750 <path to script> to allow the owner group to read and execute a file as the file's owner but allowing other users no access.).
An approach that does not require your script to run as root would be to set up the group owner and permissions of the folders that you want to scan so that the www-user can read the contents of the folder. Using the setgid bit on the folders will cause all files and folders created within these folders to inherit the group ownership.
Use chmod g+s <path to folder> to turn on the setgid bit. To set your /var/www/ folder (and subfolders) to group www-user and allow users in this group to access all the folders use (as root):
chgrp -R www-user /var/www/
chmod -R g+srX /var/www/


text:
Q: Join de 2 tablas por coincidencia aproximada (uniendo por el máximo valor que sea menor o igual) Lo que quiero lograr es lo mismo que un =BUSCARV(val;matriz;col;VERDADERO) con coincidencias aproximadas (VERDADERO en el último parámetro), pero en PowerQuery (M).
Explico de nuevo y en detalle:
Tengo 2 tablas, Tabla1 que es la principal y a la que quiero agregarle una categoría traída de la Tabla2 (join).

Quiero generar una nueva tabla, la cual debería mantener los mismos valores de Tabla1, con una columna extra, la Categoría de Tabla2.
Resultado esperado:

En este ejemplo, el join para las 2 primeras filas coinciden perfecto, pero las últimas 2 toman el caso máximo donde
Tabla1[Valor] >= Tabla2[ValorDesde]
Condiciones: quiero hacer esto con PowerQuery (exclusivamente), ambas tablas pueden cambiar y al ejecutar el query quiero regenerar la tabla de resultados. Las categorías son un parámetro que yo no defino, por lo cual no me sirve hacer una columna personalizada con un if para cada condición ni nada similar. Las categorías son únicas, no hay valores duplicados y ya vienen ordenados de menor a mayor.
Lo que intenté hasta ahora (código abajo) fue generar una columna personalizada con el primer valor de Tabla2[ValorDesde] que cumple la condición, para luego hacer el join. Sin embargo, estoy uniendo los valores de la Tabla2 por duplicado, y esto es claramente innecesario. Sé que cuando tenga muchos datos lo va a convertir en un cuello de botella.
Ejemplo mínimo (estoy generando las tablas manualmente para que puedan copiar y pegar en PowerQuery y reutilizar este mismo código):
let //Orígenes de datos
    Tabla1 = Table.FromRows({{"Uno", 1}, {"Dos",2}, {"Tres", 3.33}, {"Cuatro", 4.12345678}}, type table[Nombre=text, Valor=number]),
    Tabla2 = Table.FromRows({{0, "Inicial"}, {1, "Nuevo"}, {2, "Intermedio"}, {4, "Avanzado"}}, type table[ValorDesde=number, Categoría=text]),

    //Obtengo el valor que tiene que usar en el join (columna accesoria)
    ColParaJoin = Table.AddColumn(Tabla1, "ValorDesde",
        (fila) =>
            List.Max(
                List.Select(Tabla2[ValorDesde], (valorDesde) => valorDesde <= fila[Valor])
            )
        , type number
    ),

    //JOIN
    LeftOuterJoin = Table.NestedJoin( ColParaJoin, {"ValorDesde"}, Tabla2, {"ValorDesde"}, "ColParaJoin", JoinKind.LeftOuter),
    ExpandCateg = Table.ExpandTableColumn(LeftOuterJoin, "ColParaJoin", {"Categoría"}, {"Categoría"}),

    //Elimino la columna accesoria
    ElimValorDesde = Table.RemoveColumns(ExpandCateg,{"ValorDesde"})
in
    ElimValorDesde

Logro el resultado esperado, pero...
Pregunta: ¿hay alguna forma más eficiente de hacer el join con el máximo valor que sea menor o igual y obtener la última columna? ¿Se puede hacer sin estar uniendo 2 veces?

A: Aqui es como hacer todo en Powerquery.
https://www.myonlinetraininghub.com/power-query-approximate-match-vlookup#:~:text=Step%201%3A%20Load%20both%20the,tab%20%3E%20From%20Table%2FRange.&text=Step%204%3A%20Add%20a%20Conditional,from%20the%20Bonus%20Rate%20table.
Hacer un join

Expandir

Insertar Columna

Ordenar

Copiar Categoria Abajo

Eliminar Null

Codigo:
let
    Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"Nombre", type
text}, {"Valor", type number}}),
    #"Merged Queries" = Table.NestedJoin(#"Changed Type", {"Valor"}, Table2,
{"ValorDesde"}, "Table2", JoinKind.FullOuter),
#"Expanded Table2" = Table.ExpandTableColumn(#"Merged Queries", "Table2",
{"ValorDesde", "Categoria"}, {"ValorDesde", "Categoria"}),
    #"Added Conditional Column" = Table.AddColumn(#"Expanded Table2",
"Custom", each if [Valor] = null then [ValorDesde] else [Valor]),
    #"Sorted Rows" = Table.Sort(#"Added Conditional Column",{{"Custom",
Order.Ascending}}),
    #"Filled Down" = Table.FillDown(#"Sorted Rows",{"Categoria"}),
    #"Filtered Rows" = Table.SelectRows(#"Filled Down", each [Nombre] <> null
and [Nombre] <> "")
in
    #"Filtered Rows"


text:
Q: Почему оператор присвоения не копирует объект? Почему при первом выполнении строки z = *this, z.val копирует значение this->val
Но при втором z.val становится равна 0.
В результате b.val = 6.
#include <iostream>

using namespace std;

class integer2
{
private:
    int val;
public:
    integer2(int v0)
    {
        val = v0;
    }
    integer2& operator+(int s)
    {
        integer2 z(0);
        z = *this;
        z.val = z.val + s;
        return z;
    }

    int getVal()
    {
        return val;
    }
 };

int main()
{
    integer2 a(5), b(0);
    b = a + 5 + 6;
    return 0;
}

A: Локальные переменные, созданные на стеке, уничтожаются при выходе из области видимости (в данном случае это выход из метода).
Таким образом, возвращая integer2& вы указываете на объект integer2 z( 0 );, которого уже не существует - это UB.

В соответствии со стандартами C и C++, если выполнение программы приводит к переполнению знаковой целой переменной, или к любому из сотен других «неопределённых действий» (undefined behaviour, UB), то результат выполнения программы может быть любым: она может запостить на Твиттер непристойности, может отформатировать вам диск…
  (с) хабра-пост

Правильный оператор+ в вашем случаи:
integer2 operator+( const int num )
{
    integer2 temp( *this );
    temp.val += num;
    return temp;
}

A: Ответ rikimaru2013 объясняет, почему так делать нельзя, я же попытаюсь объяснить что вообще произошло.
Первый оператор + отрабатывает условно-нормально - есть UB, но результат соответствует ожиданиям. Но он вернул ссылку на переменную, которой больше нет, и тот факт, что там до сих пор находится 10 - это заслуга исключительно современных ОС, где никакие прерывания не "портят" пользовательский стек. Кстати, если процесс получит в этот момент сигнал - значение "10" наверняка затрется.
Теперь выполняется оператор + второй раз. Вызывается он условно так:
temp1.operator + (6)

где temp1 - это ссылка на уничтоженную локальную переменную z. Посмотрим выполнение построчно:
    integer2 z(0);
    z = *this;
    z.val = z.val + s;
    return z;

Первая строка создает новую переменную z, проинициализировав ее нулем. Но где она создается? Она создается на том же самом месте, что и прошлая переменная z, а значит, this сейчас указывает на локальную переменную z! Поэтому значение 10 в первой строчке затирается нулем.
Во второй строчке этот ноль присваивается самому себе, в третьей - к нему добавляется 6, и в четвертой строчке ссылка на локальную переменную опять возвращается.
В итоге в b обычно попадает 6.


text:
Q: Oracle - Joining a inline table or table on the fly I have a problem where a validation Code is stored in my table along with other data. Unfortunately the description is stored in a table where  I dont have access to. I do know the values
Example

12, 14, and 22- Description for them is available in an excel. I have no permissions to create a table to store the data and I need to run them every day as a reporting work.

*

*12- Missing Work

*14 - Absent

*22 - Incomplete

Question: how do I write a query where I can create a dummy table(inline? On the fly?) with the values in excel and join to my table so that results looks like this

Note:

*

*I cant create a perm table - no permissions. Its a read only Db for me

*I want to give 12,MissingWork, 14, Absent as part of my query

Any thoughts. I tried searching. I think I am not using the right terminology and hence not finding results.

A: You can do that by joining a subquery that SELECTs each code description pair FROM dual and uses UNION ALL to combine their results into one set.
SELECT t1.date,
       t1.task,
       t1.code,
       x.description
       FROM table1 t1
            LEFT JOIN (SELECT 12 code,
                              'Missing Work' description
                              FROM dual
                       UNION ALL
                       SELECT 14 code,
                              'Absent' description
                              FROM dual
                       ...) x
                      ON x.code = t1.code;

A: As you know those codes and descriptions, a simple option is to create a CTE; in the following example, it is called excel. Another CTE in this example represents your "real" table1 (I could have created it in my database, but CTE is good enough to show what to do).
SQL> with excel (code, description) as
  2    (select 12, 'Missing Work' from dual union all
  3     select 14, 'Absent'       from dual union all
  4     select 22, 'Incomplete'   from dual
  5    ),
  6    table1 (c_date, task, code) as
  7    (select date '2019-05-30', 'Homework', 12 from dual union all
  8     select date '2019-05-31', 'Labwork' , 14 from dual union all
  9     select date '2019-05-30', 'Other'   , 22 from dual
 10    )
 11  select t.c_date, t.task, t.code, e.description
 12  from table1 t join excel e on e.code = t.code;

C_DATE     TASK           CODE DESCRIPTION
---------- -------- ---------- ------------
05/30/2019 Homework         12 Missing Work
05/31/2019 Labwork          14 Absent
05/30/2019 Other            22 Incomplete

SQL>

A: You can use something called Common Table Expressions (CTE)
WITH Code_lookup AS (
  SELECT 12 Code, 'Missing Work' Description FROM DUAL UNION ALL
  SELECT 14, 'Absent' FROM DUAL UNION ALL
  SELECT 22, 'Incomplete' FROM DUAL)
SELECT <your columns list>
  FROM <your table>
  JOIN Code_lookup USING (Code)

A: Perhaps use a common table expression with a union:
with descr (code, description) as (
    select 12, 'Missing Work' from dual union
    select 14, 'Absent' from dual union
    select 22, 'Incomplete' from dual
)
select table1.date, table1.task, table1.code, descr.description
from table1
left join descr on table1.code = descr.code

A: In Oracle there is a DECODE function that would be suitable.

select code,
       DECODE(code, 12, 'Missing work',
                    14, 'Absent'
                    22, 'Incomplete',
                    'UNKNOWN Code) as Description
from table;

The first argument is the field to decode, followed by pairs of values for the mapping, and a final value which is the decoded value when there is no match.
You code use a CTE and distinct to turn it into a proper table if that's what's needed.  Then you would have the decode in a single place and wouldn't have to inline it everywhere.


text:
Q: Path of the image for "EMAIL" share in phonegap I have implemented slide function for images and now need to set current page as body of the Email and share it in phonegap. i'm able to send the email but not with the image,  can i set the first image as current page and set the path? please help me to give the right path for the Sliding image.
here's my java intent code
private void doSendIntent(String subject, String text) {
    Intent sendIntent = new Intent(android.content.Intent.ACTION_SEND);

    sendIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
    sendIntent.putExtra(android.content.Intent.EXTRA_TEXT, text);
    this.cordova.startActivityForResult(this, sendIntent, 0);
    File path = new File(Environment.getExternalStorageDirectory()+"file_path");
    sendIntent.putExtra(android.content.Intent.EXTRA_STREAM,Uri.fromFile(new File(path.getAbsolutePath())));
}

Had implemented image swipe in javascript.

     <button class="button" id="Email" onclick="share()">Hello</button>

  <button class="button" id="Email" onclick="share()">Hello</button>

A: Try this
sendIntent.putExtra(android.content.Intent.EXTRA_STREAM,Uri.fromFile(new File(Environment.getExternalStorageDirectory().getPath()+filepath.jpg)));


text:
Q: Geocortex Essentials I am currently using Geocortex Essentials REST elements and I am in the process of adding a new map service. I've entered in my url to the map service's in ArcGIS Server, but can't see my newly created map service in the dropdown list. Any ideas or hints as to why my map service isn't appearing?

A: Once you configure Geocortex Essentials using post installation manager (to work with ArcGIS Server) , open Geocortex Essentials Manager. And in Map - click on Add Map Service.
Here you can enter keyword to search your map service which is published in ArcGIS Server. You can limit your search within your ArcGIS Server portal. Here you can get list of all map services published and then you can add them directly to Geocortex Essentials.


text:
Q: CloudStorageAccount.Parse(connString) says CloudStorageAccount.cs not found In my WebAPI controller I am trying to post to my Azure Blob Storage. I am trying to connect in the following manner:
string blobConnectionString = ConfigurationManager.ConnectionStrings["AzureStorageAccount"].ConnectionString;
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(blobConnectionString);
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference("testContainer");

However just doing this returns a 500 and walking through this line by line in the debugger after

CloudStorageAccount.Parse(blobConnectionString)

it returns a Source Not Found error in Visual Studio where it says:

CloudStorageAccount.cs not found, You need to find
  CloudStorageAccount.cs to view the source for the current call stack
  frame.

Is this a issue with me missing a file or is this a issue with my connection string? My web config is:
<connectionStrings>
<add name="AzureStorageAccount" connectionString="DefaultEndpointsProtocol=https;AccountName=somecustomname;AccountKey=accesskey" />
</connectionStrings>

A: The problem was me debugging using F11 (Step Into) rather than F10 (Step Over).


text:
Q: Shell searching for a line Hello I have simple file called myfile.txt ,in there there are only 3 lines :
   192.168.20.30
   text123
   192.168.1.1

I am trying to grep all IPs in the form number.number.1 I tried with this regex
grep [0-9]*\.[0-9]*\.[1] myfile.txt

but it prints the 3 lines,any ideas why,it is supposed to print 192.168.1.1 only

A: Without the single quotes the shell removes the backslashes from the pattern, it looks as [0-9]*.[0-9]*.[1] and it matches 0+ digits, then any char, again 0+ digits, again any char and then 1.
You must use quotes:
grep '[0-9]*\.[0-9]*\.1' myfile.txt

See the online demo. You may see that echo [0-9]*\.[0-9]*\.[1] prints [0-9]*.[0-9]*.[1] and echo '[0-9]*\.[0-9]*\.1' prints [0-9]*\.[0-9]*\.1.
Note that you may use -E option with grep and use + quantifier (1 or more occurrences): grep -E '[0-9]+\.[0-9]+\.1' (at least, with GNU grep).


text:
Q: Question about closure of the product of two sets Let $A$ be a subset of the topological space $X$ and let $B$ be a subset of the topological space $Y$. Show that in the space $X \times Y$, $\overline{(A \times B)} = \bar{A} \times \bar{B}$.
Can someone explain the proof in detail?  The book I have kind of skims through the proof and I don't really get it.

A: $(\subseteq)$: The product of closed sets $\overline{A} \times \overline{B}$ is closed. For every closed $C$ that contains $\overline{A} \times \overline{B}$, $A \times B \subseteq C$ so $\overline{A \times B} \subseteq \overline{\overline{A} \times \overline{B}} = \overline{A} \times \overline{B}$.
$(\supseteq)$: Choose any $(a,b) \in \overline{A} \times \overline{B}$. Notice that for every open neighborhood $W \subseteq X \times Y$ that contains $(a, b)$, $U \times V \subseteq W$ (by the definition of the product topology) for some open neighborhood $U$ of $a$ and some open neighborhood $V$ of $b$. By the definition of closure points, $U$ intersects $A$ at some $a'$. Similarly, define $b' \in V \cap B$. Hence, $(a', b') \in W \cap (A \times B)$.
To summarize, every open neighborhood $W \subseteq X \times Y$ that contains $(a,b)$ must intersect $A \times B$, therefore $(a,b) \in \overline{A\times B}$.

A: A set in $X\times Y$ is open iff it is the union of sets of type $U\times V$ with $U,V$ open.
Therefore, if $(x,y)\notin\overline{A\times B}$, there is $U\times V$ containing it and disjoint to $A\times B$.
As $(U\cap A)\times (V\cap B)\subseteq (U\times V)\cap (A\times B)$, one of the sets $U\cap A$ or $V\cap B$ is empty, i.e. $x\notin \overline A$ or $y\notin \overline B$.
This shows $\overline A\times\overline B \subseteq \overline{A\times B}$.
The converse is not much different.


text:
Q: Is it possible to prove that a relation is a function or not by using derivative? There several ways to prove if a mathematical formula is a function or not :
First: To find 2 or more $X$'s that have the same $Y$ assigned to them .
Second: To assume that we put $(x_1,y_1)$ and $(x_2,y_2)$ into the formula and then come to the conclusion that $y_1=y_2$ .
But I've heard that there's even a third way which is using derivative to determine if a relation is a function or not . Honestly I cannot use the 2 provided ways efficiently in a reasonable time , when things get complicated as bellow :

*

*Determine if bellow formulas are function or not :

*

*$F(X-2)=|X|-1$

*$F(|X|-1)=2X+1$

*$F(|X|-1)=2X^2 +1$

*$F(2X^2 +1)=|X|-1$

*$Y!=X$

*$Y= X + [X]$

*For what amount of a , the below is representing a function ?
$$(Y-X^2)( (X-2)^2 + (Y+a) ) = 0$$
Many thanks
Mohammad from Iran


text:
Q: How should I fire Javascript blur event after click event that causes the blur? I have run into this problem a few times and I'm not happy with the solutions I've used before.
I have an input box with a blur event that validates the content of it and a button which will fill the input box on click. The problem is clicking the button fires the input blur event and then the button click event so content inserted by the button is not what is validated.
See http://jsfiddle.net/jakecr/dL3K3/
I know this is the correct behavior but I can't think of a clean way to get around the problem.

A: This might also help:
Set a timer that delays the blur event action before it fires the button click event.
// Namespace for timer var setTimer = { timer: null }

    $('input,select').blur(function () {
        setTimer.timer = setTimeout(function () {
           functionCall();
        }, 1000);
    });

    $('input,select').focus(function () {
        setTimer.timer = setTimeout(function () {
            functionCall();
        }, 1000);
    });

    $("#btn").click(function () {
        clearTimeout(setTimer.timer);
        functionCall();
    });

A: We had a similar problem at work. what we figured out in the end
was that the mousedown event will fire before the blur event
allowing you to set the content before the validation or even  cancel the validation
process completely using a flag.
check this fiddle I made using your example-
http://jsfiddle.net/dL3K3/31/
$(function(){
    var flag = true;
    $('input').blur(function(){
        if(!$(this).val() && flag){
            alert("Grrr, It's empty");
        }
    });

    $('button').mousedown(function(){
        flag = false;
    });
    $('button').mouseup(function(){
        flag = true;
        $('input').val('content').focus();
    });

});

-Edit-
As @mclin Suggested, using the mousedown event and preventDefault will prevent blur behavior.
And you can just leave the original click event intact -
http://jsfiddle.net/dL3K3/364/
$(function(){
    $('input').blur(function(){
        if(!$(this).val()){
            alert("Grrr, It's empty");
        }
    });

    $('button').mousedown(function(e){
        e.preventDefault();
    });
    $('button').click(function(){
        $('input').val('content');
    });

});

This solution might be a bit cleaner and better for most cases just note that if you use it you'll preventDefault and blur of any other element the focus is currently on but for most use cases that shouldn't be an issue.

A: I have a better solution than Yoni Jah's:
call preventDefault on the button's mousedown event. The onBlur never happens so you're free to do whatever in the click event.
This is better because it doesn't change the click behavior by making things happen on mouse down instead of mouse up, which can be unexpected.

A: Separate the input validation logic to it's own function which is called both by the blur event automatically and then by the click event after you've modified the value in the input box.  True your validation logic would be called twice, but I'm not seeing a way around that without making a lot more changes.
Example using jQuery:
$('input').blur(function() {
    validate(this);
});

$('submit').click(function() {
   //modify the input element
   validate(inputElement);
});

var validate = function(obj) {
   // validate the object
}

A: Sometimes it is useful to get a child object on mouseup, but the parent wants to hide its children on blur. We can cancel the hiding of the children elements, then wait until our mouseup occurs, then force the blur to occur when we are ready
js
var cancelHide = false;

$('.my-input').blur(function() {
    if (!cancelHide) {
        $('.my-item').hide();
    }
});

$('.my-input').click(function() {
    $('.my-item').show();
});

$('.my-item').mousedown(function() {
    cancelHide = true;
});

$('.my-item').mouseup(function() {
    var text = $(this).text();
    alert(text);
    cancelHide = false;
    $('.my-input').blur();
});

html
<input type="text" class="my-input"/>

Hello

Lovely

World

css
.my-item {
    display:none;
}

https://jsfiddle.net/tic84/on421rxg/
Clicking the list items will only alert on mouseup, despite the parent trying to hide them on blur

A: The trick is not to use blur and click events, because they are always performed in order of blur first, click second. Instead you should check when the element having focus has changed, because that happens only after the click.
I think I have an elegant solution for this one:
var alreadyValidated = 'true';

setInterval(function(){
    if(document.activeElement.id != 'validation-field-id'){
        if(alreadyValidated=='false'){
            alreadyValidated = 'true';
            validate(document.activeElement);
        }
    }
    else {
        alreadyValidated = 'false';
    }
}, 200);

These days all modern browsers support document.activeElement.


text:
Q: How to override the `is` operator
Possible Duplicate:
python: class override "is" behavior

I am trying to override the is operator, so that I could do something like
if tom is writer:
   print 'tom is writing'
elif tom is programmer:
   print 'tom is programming'

Is this possible in python?

A: As far as I know, you can't override 'is' because it tests whether two objects are the same object by comparing their memory addresses (i.e. pointer comparison). You probably want to override '==' by implementing tom's __eq__ method.

A: The Python way to test for the type of an object is to use isinstance, as in isinstance(tom,Writer).
But whenever you start to write code that reads like your example, think about using polymorphism instead.  Here is a simple class hierarchy that does what you want, without a single call to isinstance:
class Worker(object):
    def __init__(self, name):
        self.name = name

    def is_doing(self):
        return "working"

class Writer(Worker):
    def is_doing(self):
        return "writing"

class Programmer(Worker):
    def is_doing(self):
        return "programming"

workers = [
    Writer("Tom"),
    Programmer("Dick"),
    ]

for w in workers:
    print "%s is %s" % (w.name, w.is_doing())

Prints:
Tom is writing
Dick is programming

Now you can just add new subclasses to Worker and implement is_doing, and you don't have to maintain some table of type-to-activity values.
This pattern of polymorphism is traditional O-O, but in Python, you aren't even restricted to subclasses of Worker - any object that implements is_doing and has a name attribute will work:
class Fish(object):
    def __init__(self, n):
        self.name = n
    def is_doing(self):
        return "swimming"

workers.append(Fish("Wanda"))

for w in workers:
    print "%s is %s" % (w.name, w.is_doing())

will print:
Tom is writing
Dick is programming
Wanda is swimming


text:
Q: Difference between {% include '' %} and {{ include('') }} in Twig It's possible to include a file in two different ways:
{% include 'fic.html.twig' %}
{{ include('fic.html.twig') }}

What is the difference between the two methods?
Source:

*

*http://twig.sensiolabs.org/doc/tags/include.html

*http://twig.sensiolabs.org/doc/functions/include.html

A: From Twig's changelog:
* 1.12.0-RC1 (2012-12-29)

 * added an include function (does the same as the include tag but in a more flexible way)

A: Tags are less flexible than functions, for example:

*

*If you want to store contents of a file in a variable if you want to repeat it twice:
{% set content = include('test.twig') %}
Instead of:
{% set content %}
{% include 'test.twig' %}
{% endset %}

*If you want to add filters:
{{ include('alert.twig') | upper }}
Its tag equivalent:
{% set temp %}
{% include 'alert.twig' %}
{% endset %}
{{ temp | upper }}

You see, {{ include }} instead of {% include %} will not change the world, but remove some complexity when you need to do tricky stuffs using Twig.
Also, according to the documentation, it is recommended to use {{ include() }} to fit with best practices:
{{ }} is used to print the result of an expression evaluation;
{% %} is used to execute statements.

A: I think it's the same functionality, but while {% include '' %} is a tag, the {{ include('') }} is a function. Maybe if you want to overwrite the function it can be easier than a tag.

A: From Symfony 2.8 (LTS)  documentation

2.3 The include() function is available since Symfony 2.3. Prior, the {% include %} tag was used.


text:
Q: C# - Get RSA encryption progress How can I get RSA encryption progress? I want to display it in progress bar.
Thanks for help.
    using System.Security.Cryptography;
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(4096);

//I want to get percentage process of this function, because it takes a lot of time.
byte[] encrypted = RSA.Encrypt(Encoding.Default.GetBytes("some text", true));

A: Using a 16k-bit key I can do 1000 Encrypt calls in 2893ms (so ~3ms per), this doesn't seem slow enough to need a progress bar.
Decrypt, on the other hand, was 458,554ms for 1000 calls (so ~460ms per).  But half a second still doesn't really seem to warrant a progress bar.  And not very many people have 16k-bit RSA keys (since they take hours to generate)
Some other quick numbers (time per 1000 calls, in ms):
Keysize | Encrypt | Decrypt
--------|---------|--------
  16384 |    2893 | 458554
   4096 |     216 |  14636
   3584 |     182 |  13259
   3072 |     149 |   8370
   2560 |     127 |   4680
   2048 |      94 |   2083
   1536 |      86 |   1236
   1024 |      71 |    473
    512 |      64 |    150

So the best you could do is the fake progress bar of sending text messages... you do some heuristics for how long you think it will take, and artifically move the progress bar, then do an "eep" moment at 80% when it isn't actually done.
Since the guidance is to only use asymmetric operations to bootstrap symmetric operations (as already suggested in the comments), you can probably get away with using a progress bar on the symmetric operations only, if they're being slow enough for you to warrant it.  If you want to throw in a fudge factor for the asymmetric operation, it wouldn't hurt.

A: Check this blog post: https://www.codeproject.com/Articles/10877/Public-Key-RSA-Encryption-in-C-NET
You can make each iteration of your for loop increase your progress bar.
For more specific help post your code and let us know where you are stuck.


text:
Q: Empty file when saving as PNG I've got a method which takes an input image, does some things to the image, then saves it to another file. At its most basic it resizes the image, but it can do a few more complicated things like converting to greyscale, quantizing etc, but for the case of this question I'm only attempting to resize the image and not performing any of the other actions.
It looks something like:
public void SaveImage(string src, string dest, int width, int height, ImageFormat format, bool deleteOriginal, bool quantize, bool convertToGreyscale) {
    // Open the source file
    Bitmap source = (Bitmap)Image.FromFile(src);

    // Check dimensions
    if (source.Width < width)
        throw new Exception();
    if (source.Height < height)
        throw new Exception();

    // Output image
    Bitmap output = new Bitmap(width, height);
    using (Graphics g = Graphics.FromImage(output)) {
        // Resize the image to new dimensions
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
        g.DrawImage(source, 0, 0, width, height);
    }

    // Convert to greyscale if supposed to
    if (convertToGreyscale) {
        output = this.ConvertToGreyscale(output);
    }

    // Save the image
    if (quantize) {
        OctreeQuantizer quantizer = new OctreeQuantizer(255, 8);
        using (var quantized = quantizer.Quantize(output)) {
            quantized.Save(dest, format);
        }
    }
    else {
        output.Save(dest, format);
    }

    // Close all the images
    output.Dispose();
    source.Dispose();

    // Delete the original
    if (deleteOriginal) {
        File.Delete(src);
    }
}

Then to use it I'd call something like: imageService.SaveImage("c:\image.png", "c:\output.png", 300, 300, ImageFormat.Png, false, false, false);
That should open up the "image.png" file, resize in to 300×300, then save it to "output.png" as a PNG file. But it's not working—the file that gets created is in the correct location but has a file size of zero and contains no image at all.
This also only seems to happen when I pass in the parameter ImageFormat.Png; if I pass ImageFormat.Jpeg, then it works fine and creates the image file perfectly.
I'm wondering if there's some sort of delay occurring between creating the image and somewhere else in the code attempting to access the image that's been created (not in the above code) which locks up the file and so it's never written to? Could that be the case?
Any ideas what else could be going on?
Cheers
Edits:

*

*remove redundant cast pointed out by Lloyd

A: There are some historical issues with saving bitmaps as png.
Using System.Windows.Media.Imaging.PngBitmapEncoder can resolve this
See  System.Windows.Media.Imaging.PngBitmapEncoder
And How to: Encode and Decode a PNG Image for a sample.

A: Using the Save() parameter with a Stream instead of a filename will allow you to ensure the file is flushed to disk before the objects are disposed.
However, I'd strongly suggest using a server-safe image-processing library here, as you're playing with fire.


text:
Q: Loss over pixels During backpropagation, will these cases have different effect:-

*

*sum up loss over all pixels then backpropagate.

*average loss over all pixels then backpropagate

*backpropagate individuallyover all pixels.

My main doubts in regarding the numerical value but the effect all these would be having.

A: The difference between no 1 and 2 is basically : since sum will result in bigger than mean, the magnitude of gradients from sum operation will be bigger, but direction will be same.
Here's a little demonstration, lets first declare necessary variables:
x = torch.tensor([4,1,3,7],dtype=torch.float32,requires_grad=True)
target = torch.tensor([4,2,5,4],dtype=torch.float32)

Now lets compute gradient for x using L2 loss with sum:
loss = ((x-target)**2).sum()
loss.backward()
print(x.grad)

This outputs: tensor([ 0., -2., -4.,  6.])
Now using mean: (after resetting x grad)
loss = ((x-target)**2).mean()
loss.backward()
print(x.grad)

And this outputs: tensor([ 0.0000, -0.5000, -1.0000,  1.5000])
Notice how later gradients are exactly 1/4th of that of sum, that's because the tensors here contain 4 elements.
About third option, if I understand you correctly, that's not possible. You can not backpropagate before aggregating individual pixel errors to a scalar, using sum, mean or anything else.


text:
Q: Keeping validation errors after redirect from partial back to the same page that has the partial So I'm trying to get the errors from my form that is rendered as a partial inside my root_path. After I attempt to post it, and it fails (or succeeds), I want to redirect back to the root_path. However, redirect_to decides to not save any information for the validation.
Wondering how to do this.
class PostsController < ApplicationController
  def new
    @post = Post.new
  end

  def create
    @nom = current_user.noms.build(params[:nom])
    if @nom.save
      flash[:success] = "Nom created!"
      redirect_to root_path
    else
      flash[:error] = @nom.errors
      redirect_to root_path
  end

In my Home/Index, I render the partial for the form of the post.
= form_for [current_user, @post] do |f|
  = f.text_field :name
  = f.select :category
  = f.text_area :description
  = f.submit "Post", class: "btn btn-primary"

  - @post.errors.full_messages.each do |msg|
    %p
      = msg

It should be keeping the errors at the bottom of the form after it redirects to the root_path.
I'd also like to keep the information that was there after the validation failed.

A: You should not use redirect in this case, instead use render:
class PostsController < ApplicationController
  #..

  def create
    @nom = current_user.noms.build(params[:nom])
    if @nom.save
      flash[:success] = "Nom created!"
      redirect_to root_path
    else
      flash[:error] = @nom.errors
      render :template => "controller/index"
    end
  end

Replace controller/index with names of you controller and action
Also check this question

A: This seemed to work for me
format.html { redirect_to :back, flash: {:errors => "Document "+@requested_doc.errors.messages[:document][0] }}

I don't know if this could cause any other exception issues.

A: You can not use redirect_to for showing the error messages of an object because while redirecting it discards your object which does have linked with the error_messages & took a new object to redirect the path.
So in that case, you only have to use render.
respond_to do |format|
        format.html {
          flash[:error] = @account.errors.full_messages.join(', ')
          render "edit", :id => @account._id, sid: @account.site._id
        }
end


text:
Q: Email в интернет с  Open Server или Denwer Можно ли как-то отправить письмо с Openserver или Denwer используя ф-ию mail()?
A: Привет!
Вам надо поставить mail сервер (например sendmail (в Denwer стоит заглушка)), затем в файле php.ini прописать соот. настройки [mail]
A: Вы заглядывали в настройки OpenServer? Там закладка "Почта", выбираете или складировать в локальную папку, или отправлять через удаленный SMTP сервер. И Mail servser ставить не надо. Да и вообще, мануал на русском языке, где всё подробно описано. К тому же, форум есть.  А про Денвер пора забыть. Уже больше года наблюдаю:
Регистрация требуется в связи с будущим выходом Денвера-4.

Проект заглох, а OpenServer регулярно обновляется (последний раз - 19 августа 2012), не такой глючный, настроек и возможностей на хороший порядок выше.