text:
Q: C# Игральный кубик с неравномерной вероятностью Имеется игральный кубик с N количеством граней, сейчас вполне хватит 6. Кубик является не вполне честным, так как шанс выпадения граней неравномерный. Тем не менее, при броске гарантированно выпадает одна из граней.
Шансы выпадения граней этого кубика:

*

*10%

*15%

*40%

*5%

*10%

*20%

Примерная структура игрального кубика:
public struct Dice
{
    /// <summary>
    /// Edges of a <see cref="Dice"/>
    /// </summary>
    public Dictionary<int, double> Edges { get; private set; }

    public Dice(Dictionary<int, double> edges)
    {
        this.Edges = edges;
    }

    public int Roll()
    {
        // some code
        return default;
    }
}

Как можно реализовать бросок такого кубика, а затем вернуть номер выпавшей грани?

A: Как альтернатива, более шустрый и тупой вариант (но в общем случае неудобный и не везде применимый) это создать массив с нужным количеством тех или иных вариантов и выбирать уже из него рандомом по его размеру:
public int Roll()
{
    Random random = new Random();

    var dist = new []{1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 4, 5, 5, 6, 6, 6, 6};
    return dist[random.Next(dist.Length)];
}

* edges здесь не учитывается

A: public int Roll()
{
  Random random = new Random();
  double r = random.NextDouble();
  double p = 0;
  foreach(int key in edges.Keys)
  {
    if (p <= r && r < p + edges[key])
      return key;
    p = p + edges[key];
  }
  return -1;
}

A: Не успел до ответа @Александра Муксимова. По сути, мой ответ содержит те же идеи, что и у автора принятого ответа.

Реализация проста. Необходимо представить в голове колесо рулетки, где каждый сектор - это граница кубика, а его размер - это вероятность выпадения грани кубика. Т.е. процесс бросания кубика превращается в процесс вращения рулетки. Вот, как это можно представить:

Необходимо этот процесс вращения аппроксимировать на прямую длиной от 0 до 1. Т.е. необходимо разбить прямую на "секторы", где длина сектора вычисляется по формуле:
L(сектора i) = (1 / 100) * P(вероятность выпадения сектора i в процентах).

Реализация алгоритма представлена ниже. Не делал проверок на правильность указанных значений в edges, поскольку хотел показать основную идею, а дописать ее будет несложно.
private static void Main(string[] args)
{
    var edges = new Dictionary<int, double>
    {
        {1, 10},
        {2, 15},
        {3, 40},
        {4, 5},
        {5, 10},
        {6, 20}
    };

    var dice = new Dice(edges);

    var rollCount = 100;
    var actualProbabilities = edges.Select(p => p.Key).ToDictionary(p => p, p => 0);
    for (var i = 0; i < rollCount; i++)
    {
        var edge = dice.Roll();
        actualProbabilities[edge]++;

        Console.WriteLine($"Roll #{i}: Edge {edge}");
    }

    foreach (var p in actualProbabilities)
    {
        Console.WriteLine($"Edge #{p.Key} has actual probability {p.Value * 1.0d / rollCount}");
    }

    Console.ReadLine();
}

public class Dice
{
    private readonly Roulette _roulette;

    public Dice(Dictionary<int, double> edges)
    {
        _roulette = CreateRoulette(edges);
    }

    public int Roll()
    {
        var sector = _roulette.Roll();
        return sector.Id;
    }

    private static Roulette CreateRoulette(Dictionary<int, double> edges)
    {
        var sectors = new List<Sector>();

        const double onePercentLength = 1.0d / 100;
        double sectorFrom = 0;
        foreach (var edge in edges)
        {
            var sectorTo = sectorFrom + edge.Value * onePercentLength;
            var sector = new Sector(edge.Key, sectorFrom, sectorTo);
            sectors.Add(sector);

            sectorFrom = sectorTo;
        }

        var roulette = new Roulette(sectors);
        return roulette;
    }
}

public class Sector
{
    public double From { get; }
    public double To { get; }
    public int Id { get; }

    public Sector(int id, double from, double to)
    {
        Id = id;
        From = from;
        To = to;
    }
}

public class Roulette
{
    private static readonly Random _random = new Random();
    private readonly List<Sector> _sectors;

    public Roulette(List<Sector> sectors)
    {
        _sectors = sectors;
    }

    public Sector Roll()
    {
        var r = _random.NextDouble();

        foreach (var sector in _sectors)
        {
            if (IsValueInSector(r, sector))
            {
                return sector;
            }
        }

        return null;
    }

    private static bool IsValueInSector(double value, Sector sector)
    {
        return value >= sector.From && value < sector.To;
    }
}

Протестировать, поиграться можно тут

A: Для датчика с равномерным распределением случайных чисел на отрезке [A,B], вероятность попадания в некоторый отрезок [a,b], принадлежащий [A,B] (a>A и b<B) пропорциональна длине этого отрезка (b-a)/(B-A). Следовательно Ваша задача разбить интервал распределения случайной величины вашего датчика на множество не пересекающихся отрезков, с длиной пропорциональной заданной вероятности.
Для того создаем в Вашем классе генератор случайных чисел:
public class Dice
{
    //...
    Random rnd;
    //...
}

Поскольку у Вас шансы выпадения граней заданы в процентах, то дабы не заморачиваться будем генерировать целые случайные числа в интервале 1,100. Тогда Ваша искомая функция будет иметь вид:
public int Roll()
{
    int p = rnd.Next(1, 101); // правая граница Random не входит в интервал

    if (p <= 10) return 1;
    if (p > 10 && p <= 25) return 2;
    if (p > 25 && p <= 65) return 3;
    if (p > 65 && p <= 70) return 4;
    if (p > 70 && p <= 80) return 5;
    if (p > 80) return 6;
    throw new Exception("Вот сейчас совсем неожиданно было");
}

То же самое, только с использованием синтаксиса C# 9.0 (.NET 5)
public int Roll() => rnd.Next(1, 101) switch
{
    > 80 => 6,
    > 70 => 5,
    > 65 => 4,
    > 25 => 3,
    > 10 => 2,
    _ => 1
};

A: А мне больше всего нравится простота и "дубовость" ответа Vladimir Gamalyan.
Я решил развить его идею до следующего кода:
private int[] dist = new[] {
                  //(цифра кубика, возможность выпадения)
   Enumerable.Repeat(1, 10),
   Enumerable.Repeat(2, 15),
   Enumerable.Repeat(3, 40),
   Enumerable.Repeat(4, 5 ),
   Enumerable.Repeat(5, 10),
   Enumerable.Repeat(6, 20)
}
.SelectMany(a => a).ToArray();

private Random random = new Random();

public int Roll() => dist[random.Next(dist.Length)];

Как следствие: код простой, дубовый, легко читается, легко правится, и, вероятно, самый быстро работающий из всех предложенных. (хотя нет, код aepot на C#9 работает быстрее)
Кроме того - возможность выпадения пишется БУКВАЛЬНОЙ ТОЧНОЙ ЦИФРОЙ. А не относительной. Т.е. если возможность 25 - то это 25, а не > 10 && < 35.
Еще из плюсов кода - можно развить возможность выпадения и до сотой процента легким движением руки:
Enumerable.Repeat(1, 1.11 * 100), //1,11%
Enumerable.Repeat(2, 15   * 100), //15%

У этого кода я вижу только один недостаток - при большой точности будет занято "много" места в оперативке. Но т.к. задача этого не предполагает изначально - то и особо недостатком можно это и не считать.


text:
Q: How to reorder bars in a histogram in R? I have a bargraph that is generated using the following code.
ggplot(data = df, aes(y = y_variable, fill = fact_variable)) + geom_bar(stat='count') + ggtitle("Graph")

This generates the following plot: (Titles and axes have been cropped due to sensitivity of information)

I want the plot however to be ordered in descending order of count. How do i do that? Ideally it should look like this but with the fill variable in the previous plot:

NOTE: y_variable and fact_variable are factor variables.
All examples on stackoverflow currently show the reorder() method as the solution, however that is for a bargraph that has a x variable plotted on the x-axis. I have a bargraph that has count in the x-axis.
How do i order it on this basis?

A: Try this one
ggplot(df, aes(y = reorder(y_variable, -perc), fill  = fact_variable)) + geom_bar(stat='count') + ggtitle("Graph")

A: @Adishwar it is generally recommended to use geom_col() if you work with totals. This avoids you having to set stat in geom_bar().
Since there is no reproducible example in terms of data, I have grossly simplified your data frame emulating your variable names. (The error you get is because perc is not known in your case, aka "object not found").
I then use geom_col() and reorder for the ordered barchart.
Your example does not specify where you got the fill colours from.
You can set them manually dependent on your needs. I use the out-of-the-box colours ...
If you do not want a label to show, set it to NULL (which removes it).
# setting up the test data with 2 categories and counts
df <- tribble(
  ~y_variable, ~fact_variable, ~count
  ,"Government" , "fact1"     , 100
  ,"Government" , "fact2"     , 200
  ,"Government" , "fact3"     , 500
  ,"Nonprofit"  , "fact1"     , 75
  ,"Nonprofit"  , "fact2"     , 200
  ,"Nonprofit"  , "fact3"     , 100
  ,"Other"      , "fact1"     , 300
  ,"Other"      , "fact2"     , 50
  ,"Other"      , "fact3"     , 80
)

# "standard barchart on counts (totals) using geom_col()
ggplot(data = df, aes(x = count, y = y_variable, fill = fact_variable)) +
  geom_col() +

# this is to set the title, labels, etc ---------------------------
  labs(title = "your title here", fill = "possible fill title"
       ,x = "my counts or NULL", y = NULL) +
  theme_minimal()

For the ordered version, use reorder(variable, ordervariable).
Make sure to assign the right variable names.
ggplot(data = df, aes(x = count, y = reorder(y_variable, count), fill = fact_variable)) +
  geom_col() +
  labs(title = "your title here", fill = "possible fill title"
       ,x = "my counts or NULL", y = NULL) +
  theme_minimal()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mobile form zooms in I have a mobile loginform, nothing too special.
But when I click on an input field, my mobile device zooms in. But since i am using this snippet:
  <meta name="viewport" content="width=device-width, initial-scale=1">

I cannot zoom out anymore.
Is there a way to either prevent it from zooming in or to zoom out again once the user has pressed 'enter/return'?
Greetings,
Chris.

A: Is not this what you want? Modify meta as (tested on iPhone and iPad):
      <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />

A: Try
`<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">`

Know More About Viewport


text:
Q: Django links to other other apps Maybe this question has been answered before in one way or another. But I need to ask because I tried to answer it myself I googled it for days but I couldn't figure it out.
I have an app called reception in my Django project.
I figured out everything but this.
I have the link in the html directing to the right urlpattern.

<tab1>Reception</tab1>

urlpatterns = [...,  path('go_to_reception', views.reception, name='go_to_reception'), ...]

And the view is like this
def reception(request):
    return render(request, 'reception.html')

now instead of reception.html I want the link to go the reception page. The app page. What do I need to write there. I have tried everything that came to my mind but nothing worked.
the reception is as follows:
http://127.0.0.1:8000/admin/reception/
So how do I point to this.
Please help!
Thanks

A: So im just going to write the solution that we discussed in the chat:
{% url "admin:app_list" app_label="reception" %}
documentation

A: Look, this help you? i solve a similar problem in this way
url.py
path('gotoreception', views.reception, name="go_to_reception"),

html
<a href="{% url 'go_to_reception' slug=slug %}"

model
slug = models.SlugField(max_length=255, unique=True)

view
def home(request, slug):
context = {'yourdata':yourdata}
    return render(request,'index.html', context)

On the template tag url you need use the name of your path, you can use a slug if you store the field on your db
3º option but not recommended, you can add the value if you have on a variable but is not a good practice
I recommend you this 2 resources:

*

*https://docs.djangoproject.com/en/2.1/ref/utils/

*https://docs.djangoproject.com/en/2.1/ref/templates/builtins/

hardcoded way

can you test this?
urls
urlpatterns = [...,  path('reception/', views.reception, name='go_to_reception'), ...]

html
and on the link

is the hardcoded way but in the future you can have troubles or relative urls, 404 on internal pages

A: Thank you for your answer Matthew,
After your latest comment, I have changed my code to the following:

<tab1>Reception</tab1>

and in url.py its:
path('reception/', include('reception.urls', namespace='reception-urls')),

in reception.urls.py
app_name = "reception"

and the message now says:
django.urls.exceptions.NoReverseMatch: Reverse for 'go_to_reception' not found. 'go_to_reception' is not a valid view function or pattern name.
I am sorry for going back and forth like this, but I honestly can't make it work.

A: have you got a view called go_to_rececption in your reception.views or a url named go_to_reception in your reception.urls?.
and no worries just trying to help!!!


text:
Q: Angular Expression is shared while sharing in addthis not expression value Here is my angular controller:
     var myApp = angular.module('myApp', []);
  myApp.controller('GreetingController', ['$scope', '$sce',     function      ($scope, $sce) {
  $scope.greeting = 'my test goes here';
  $scope.url = "http://google.com";
  var shartthis = "

";
  $scope.shartthishtml = $sce.trustAsHtml(shartthis);
   } ]);

and this is my HTML page :

{{greeting}}

Sharethis button is displaying but when share something it display Angular syntax not its value.

no any console error

A: myApp.controller('GreetingController', ['$scope', '$sce',     function      ($scope, $sce) {
  $scope.greeting = 'my test goes here';
  $scope.url = "http://google.com";
  var shartthis = "

";
  $scope.shartthishtml = $sce.trustAsHtml(shartthis);
   } ]);

{{greeting}}


text:
Q: Specify a non-standard temporary directory for open() method in Ubuntu Is there a way to specify a path to use as a temporary directory for the open() method (while using open-uri)?
I am using Ubuntu 12.04 and Ruby 2.0.0 with RVM - it uses the standard system temp dir (/tmp). As I am downloading large files, it takes a while before the file gets pulled off the web and moved into the target directory; also, I do not want to fill the /tmp filesystem up.
I know there are other methods of downloading files, some allowing to write data in chunks, I am just asking about the standard open method with open-uri.
The code I use is:
['ftp://example1.com/a.gz', 'ftp://example2.com/b', 'example3.com/somefile'].
  each do |uri|
  thread = Thread.new do
    3.times do
      File.open(uri.split(/\//)[-1], "wb") do |file|
          file.write open(uri).read
      end
    end
  end

  threads << thread
end

(the point of all this is I am to make a script pulling large files out of arbitrary sites as a way of saturating the network link in order to check the throughput).

A: Looking at the OpenURI source code we can see that it uses Tempfile:
[...]
io = Tempfile.new('open-uri')
[...]

Tempfile in order to choose the temporary directory uses Dir.tmpdir, which in turn uses the system temporary directory or a directory specified by the environment variable TMPDIR (between others). So we can write something like this:
require 'open-uri'
require 'fileutils'

d = "#{Dir.home}/.tmp"
Dir.mkdir d
ENV["TMPDIR"] = d
p open("http://www.google.com")
ENV.delete("TMPDIR")
FileUtils.rm_rf d

In a single command (please ensure that $HOME/.tmpdoes not exist and is not used):
ruby -ropen-uri -rfileutils -e 'd = "#{Dir.home}/.tmp"; Dir.mkdir d; ENV["TMPDIR"] = d; p open("http://www.google.com"); ENV.delete("TMPDIR"); FileUtils.rm_rf d'

It should print something like
#<Tempfile:$HOME/.tmp/open-uri20131115-16887-nag9pr>

P.S. I'm using Ruby 2.1.0 preview, so maybe you have to look at #{ruby directory}/lib/ruby/2.0.0/open-uri.rb source in order to understand how OpenURI manages the temporary file (but it should be very similar)

A: the question is unclear are you asking about the open method of File class?
If so just specify the directory
File.open("/your/path/to/new-tmp/#{uri.split(/\//)[-1]}","wb")

The open method of open-uri just reads out into a StringIO using open(uri,&:read) returns a String neither one of these are stored in temp.
require 'open-uri'
open("http://www.google.com/").class
#=> StringIO
open("http://www.google.com/", &:read).class
#=> String


text:
Q: Type 'string | string[]' is not assignable to type 'string' Создал интерфейс:
interface SearchData {
   user_ip : string
}

И далее заполняю его данными:
var config : SearchData = {
    user_ip: req.headers['x-forwarded-for']
}

Но это вызывает ошибку

Type 'string | string[]' is not assignable to type 'string'.
    Type 'string[]' is not assignable to type 'string'.

Поскольку заголовок x-forwarded-for может содержать не один, а несколько IP-адресов. Переписал это так:
var config : SearchData = {
    user_ip: req.headers['x-forwarded-for'].hasOwnProperty('length') ? req.headers['x-forwarded-for'][0] : req.headers['x-forwarded-for'],
}

Но ошибка не пропала. Как правильно задать значение, чтобы компилятор TypeScript понимал, что в итоге всё равно в свойство задаётся строка?

A: Array.isArray(req.headers['x-forwarded-for']) ? req.headers['x-forwarded-for'][0] : req.headers['x-forwarded-for'];

A: Можно так:
(String)((typeof req.headers["x-forwarded-for"] == "string") ? req.headers["x-forwarded-for"] : req.headers["x-forwarded-for"][0])

Вообще вот великолепное чтиво об проверке типов:
https://basarat.gitbooks.io/typescript/docs/types/typeGuard.html

A: req.headers.get('x-forwarded-for')
https://angular.io/api/common/http/HttpHeaders
get() - Returns the first header value that matches a given name.


text:
Q: I want to see what processes do most of disk writes in Mac OS X I run Mac OS X 10.8.2 and I want to find out what processes do most of disk writes. Ideally, I would like to see a complete report for a period of say 10 hours, with sorted data showing top performers.
I know that essentially in Linux something as simple as running iotop -o -a can give me something like this:

Any ideas/solutions for Mac OS X?


text:
Q: SIGALRM alarm only skips getchar once I'm just using the function alarm to skip the getchar, but something is not going well because it only skips once, and I want it indefinitely.
Example:
#include <signal.h>

int duration = 2;

main() {
     cicleProgram();
}

void cicleProgram(){

  while(opcion != 'q' && opcion != 'Q'){

    signal(SIGALRM, (void*)cicleProgram);
    alarm(duration);

    opcion = getchar();
  }
}

What am I doing wrong?

A: You're using cicleProgram() as your signal handler (despite it having the wrong type — it should take an int argument).  That means you never return from the signal handler until you type q or Q, and the system is probably blocking the signal until the first signal handler returns.  So, you never get the second signal — it is blocked.
Use a separate signal handler function.  See also What is the difference between sigaction() and signal()? and use sigaction() in preference to signal().
And use int main(void) — with at least the return type.  Even the old (C99) version of the standard requires that, let alone the current (C11) standard.  We've progressed to the 21st Century; don't code in 20th Century C!
See also How to avoid using printf() in a signal handler? for information on what you can do in a signal handler.

Could I add some control in that "while" in order to evaluate the signal alarm and avoid the deadlock?

There are multiple problems with the original code, and not all possible problems were diagnosed.  An additional problem was that if the alarm fired, there was nothing to set the alarm again, so the program falls into waiting until you type a character.
Here's some experimental code you play with:
#include <assert.h>
#include <signal.h>
#include <stdio.h>
#include <unistd.h>

static int duration = 2;
static volatile sig_atomic_t alarm_fired = 0;

static void alarm_handler(int signum)
{
    //signal(SIGALRM, alarm_handler);
    write(STDOUT_FILENO, "Signalled!\n", 11);
    alarm_fired = signum;
    alarm(duration);
}

static void cicleProgram(void)
{
    int opcion = 0;
    while (opcion != 'q' && opcion != 'Q')
    {
        signal(SIGALRM, alarm_handler);
        alarm(duration);
        if ((opcion = getchar()) == EOF)
            clearerr(stdin);
        if (alarm_fired)
        {
            alarm_fired = 0;
            printf("Alarm!\n");
        }
        printf("c = %d\n", opcion);
    }
}

static void actionProgram(void)
{
    struct sigaction sa = { 0 };
    sa.sa_handler = alarm_handler;
    sa.sa_flags = 0;
    sigfillset(&sa.sa_mask);
    sigaction(SIGALRM, &sa, 0);

    int opcion = 0;
    while (opcion != 'q' && opcion != 'Q')
    {
        alarm(duration);
        if ((opcion = getchar()) == EOF)
            clearerr(stdin);
        if (alarm_fired)
        {
            alarm_fired = 0;
            printf("Alarm!\n");
        }
        printf("c = %d\n", opcion);
    }
}

int main(void)
{
    printf("Using signal (q to quit):\n");
    cicleProgram();
    printf("Using sigaction (q to quit):\n");
    actionProgram();
    return 0;
}

There are two active functions, each with a loop.  The first is based on your original cicleProgram() but the function has been revamped; it is no longer the signal handler.  I am running on Mac OS X (BSD-based), and these systems do not require you to reset the signal() handler in the signal handler function.  The second function, actionProgram(), uses sigaction() instead of signal().  It probably isn't necessary, but it gives you something to look at.  The absence of SA_RESTART in the sa.sa_flags element means that the read() system call reports that it was interrupted each time the signal goes off.  The code in the signal_handler() doesn't use disallowed function calls.
Example output (program name al97):
$ ./al97
Using signal (q to quit):
Signalled!
Signalled!
Signalled!
Signalled!
WonderfulSignalled!

Alarm!
c = 87
c = 111
c = 110
c = 100
c = 101
c = 114
c = 102
c = 117
c = 108
c = 10
Signalled!
Signalled!
q
Alarm!
c = 113
Using sigaction (q to quit):
c = 10
Signalled!
Alarm!
c = -1
Signalled!
Alarm!
c = -1
Signalled!
Alarm!
c = -1
Signalled!
Alarm!
c = -1
ASignalled!
Alarm!
c = -1
lso workingSignalled!
Alarm!
c = -1

c = 65
c = 108
c = 115
c = 111
c = 32
c = 119
c = 111
c = 114
c = 107
c = 105
c = 110
c = 103
c = 10
qSignalled!
Alarm!
c = -1

c = 113
$

There were some quite long pauses in the run, but you can experiment on your machine.  You may need to reinclude the signal() in the alarm_handler() function for cicleProgram() and use a different handler (that doesn't use signal(), as now) for actionProgram().


text:
Q: Is there a way to determine the project based on the node expanded(not necessarily selected) in a Project in Eclipse? I have added a javascript library to my project programatically. I add different versions of library based on user preference during project creation.
I am able to achieve this but I am not able to retain the project information once the library creation is finished.
This is needed because you might have more than one project in your workspace with different library versions, so it becomes crucial to know which is the project in question when a user expands the tree node under javascript resources, where I add my library. If the user selects a project then expands the tree node I can get the Project info through
PlatformUI.getWorkbench().getActiveWorkbenchWindow()
                    .getSelectionService();

but if the user just expands the tree node without selection of project, how can I know which project does that belong to ?...
Any help in this regard will be highly appreciated.
Thanks in advance !

A: If they expand the node, not the project then I assume you have a reference to the node that was expanded which will be type IResource on that instance you can call .getProject() which returns the project the selection is contained in. If that does not apply, what type of object reference do you have on the node expansion?


text: Q: Why do t statistics decrease (standard error for cofficient increases) when multicollinearity exists? Can anybody show how the t statistic decreases when multicollinearity exists? It is easy to prove using the F test, but I don't know how to prove it using the t test.


text:
Q: C# WinForms TabStrip control: no accelerator I am using a tab strip control on a WinForms form. I make use of keyboard accelerators as much as possible. When I set the Text property of a TabPage to e.g. &Documents, the text on the tab is literally &Documents instead of the letter D being underlined.
The help about TabStrip and TabPage doesn't cover this topic. The property ShowKeyboardCues is read-only. Google is helpless.
Can anyone give me a hint how to show accelerators?

A: Neither of these controls supports that functionality. It is possible to simulate it, but it is a long and complicated task that I would not recommend because it is non-standard functionality. As a result it is unlikely that anyone would expect it to occur. On the other hand, changing tabs using Ctrl+Tab is standard behaviour so is already automatically supported.
If you did want to do this, you would need to:

*

*Subclass the Control

*Override the painting and draw the text on the tab yourself

*Get a preview of the keydown event and use that to determine if the key combination you wanted was pressed

*Select the correct tab programmatically based on the keypress that you have intercepted

As I say, I would not recommend this because it is not normal behaviour for that control and because the complexity means that it is likely to be buggy. But it is possible...

A: How can I set up keyboard shortcuts for a Windows Forms TabControl? gives tips on setting up keyboard shortcuts for it.. In terms of showing an accelerator though, you'll have to draw them yourself
Set the tabControl's DrawMode to OwnerDrawFixed then do some code to draw the tabs, for example (I had to try hard to make it this ugly)
    private void tabControl1_DrawItem(object sender, DrawItemEventArgs e)
    {
        //Change appearance of tabcontrol
        Brush backBrush = Brushes.Red;
        Brush foreBrush = Brushes.Blue;
        e.Graphics.FillRectangle(backBrush, e.Bounds);

        Rectangle r = e.Bounds;
        r = new Rectangle(r.X, r.Y + 3, r.Width, r.Height - 3);
        e.Graphics.DrawString("my label", e.Font, foreBrush, r);
        var sz = e.Graphics.MeasureString("my ", e.Font);
        e.Graphics.DrawString("_", Font, foreBrush, r.X + sz.Width - 2, r.Y + 2);
    }

Joking aside, setting up some ugly colors does help you see where the bounds of the drawing area are etc. I'm sure you'll tart it up..


text:
Q: Sequelize: create is not a function when model is generated from migration I created this model from sequelize CLI
models/society.js
'use strict';
module.exports = (sequelize, DataTypes) => {
  const Society = sequelize.define('Society', {
    code: DataTypes.STRING,
    name: DataTypes.STRING,
    description: DataTypes.STRING
  }, {});
  Society.associate = function(models) {
    // associations can be defined here
  };
  return Society;
};

Then this is my index.js file for configurations
'use strict'

const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const api = require('./routes')

app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json())
app.use('/api', api)

const port = process.env.PORT || 3000

app.listen(port, ()=>{
    console.log(`API REST running on http://localhost:${port}`)
})

The part of routes is this
routes/index.js
'use strict'

const express = require('express')
const api = express.Router()

const SocietyCtrl = require('../controllers/society')
api.post('/society', SocietyCtrl.createSociety)

module.exports = api

And finally it's just the controller
controllers/society.js
'use strict'

const Society = require('../models/society')

function createSociety(req, res){
    console.log('POST /api/society/')
    Society.create(req.body).then(created =>{
        res.status(200).send({society: created})
    })
}

module.exports = {
    createSociety
}

The problem comes when I try to make POST, I get this following error:
Society.create is not a function
Can you tell me what I'm doing wrong?

A: This problem is not related to migration, however to solve this problem you have to do two steps:
1) Add new file in models directory called index.js which contain the following code

NOTE: make sure to edit sequelize config (with your environment) which starts in line 9 and ends in line 13 in file below (models/index.js)

'use strict';

const Sequelize = require('sequelize');
const fs = require('fs');
const path = require('path');
const basename = path.basename(__filename);

const db = {};

const sequelize = new Sequelize('database', 'username', 'password', {
  host: 'localhost',
  port: 3066,
  dialect: /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */
});

fs.readdirSync(__dirname).filter(file => {
  return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
}).forEach(file => {
  const model = sequelize['import'](path.join(__dirname, file));
  db[model.name] = model;
});

Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

module.exports = db;

2) in controllers/society.js file do the following

*

*replace const Society = require('../models/society'); with const db = require('../models/index'); or const db = require('../models');

*replace Society.create with db.Society.create
like this:
'use strict'

const db = require('../models');

function createSociety(req, res){
    console.log('POST /api/society/');
    db.Society.create(req.body).then(created =>{
        res.status(200).send({society: created})
    });
}

module.exports = {
    createSociety
}

To learn more I recommend you to check a github repository called express-example which developed by official sequelize team

A: Thanks Amjed!
But I didn't need to add index.js to models directory because sequelize already did.
However all I needed to do was:
'use strict'

const db = require('../models/index')
const Society = db.Society

And then it worked like it was supposed to.


text:
Q: new line instead of white space when using \n I'm new to Flask, so I trying to display data from my dict in HTML.
next_data = '1111111\n222222'
data = {'next_data': next_data}
return render_template("data.html", data=data)

and this is my HTML page

{{data['next_data']}}

{{data['name'}}

the result I'm getting is a string with whitespace instead of \n but my goal is that it should display '222222' on a new line. Any tips?
Expected output = 111111
                  222222

A: As described in this answer, use
 instead of \n, because the string is treated as HTML, not as a Python string.
next_data = '1111111\n222222'.replace('\n', '
')


text:
Q: Cannot read property 'toastr' of undefined I have been trying to implement express-toastr into my express js form and use it to send the express-validator error messages as toast notifications, however when I place the required div #{req.toastr.render()} inside my index.pug file I receive the error Cannot read property 'toastr' of undefined when attempting to load the page.
Full error:
        TypeError: /home/bob/project/views/index.pug:34
    32|         h1(class="section__title") Title1
    33|         div(class="centerBlock")
> 34|           div #{req.toastr.render()}
    35|             .col-xs-12
    36|               form(action='', method='post', id='form')
    37|                 .row

Cannot read property 'toastr' of undefined
    at eval (eval at wrap (/home/bob/project/node_modules/pug-runtime/wrap.js:6:10), <anonymous>:117:61)
    at template (eval at wrap (/home/bob/project/node_modules/pug-runtime/wrap.js:6:10), <anonymous>:245:131)
    at Object.exports.renderFile (/home/bob/project/node_modules/pug/lib/index.js:428:38)
    at Object.exports.renderFile (/home/bob/project/node_modules/pug/lib/index.js:418:21)
    at View.exports.__express [as engine] (/home/bob/project/node_modules/pug/lib/index.js:465:11)
    at View.render (/home/bob/project/node_modules/express/lib/view.js:135:8)
    at tryRender (/home/bob/project/node_modules/express/lib/application.js:640:10)
    at Function.render (/home/bob/project/node_modules/express/lib/application.js:592:3)
    at ServerResponse.render (/home/bob/project/node_modules/express/lib/response.js:1008:7)
    at /home/bob/project/routes/index.js:19:7
    at Layer.handle [as handle_request] (/home/bob/project/node_modules/express/lib/router/layer.js:95:5)
    at next (/home/bob/project/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/home/bob/project/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/home/bob/project/node_modules/express/lib/router/layer.js:95:5)
    at /home/bob/project/node_modules/express/lib/router/index.js:281:22
    at Function.process_params (/home/bob/project/node_modules/express/lib/router/index.js:335:12)

My layout.pug is as follows:
link(rel="stylesheet" href="/css/toastr.css")
script(src="/js/jquery.js")
script(src="/js/toastr.js")

and my app.js:
var cookieParser = require('cookie-parser');
var session = require('express-session');
var flash = require('connect-flash');
var toastr = require('express-toastr');

var index = require('./routes/index');

var app = express();
app.use(cookieParser('secret'));
app.use(session({
    secret: 'secret',
    saveUninitialized: true,
    resave: true
}));
app.use(flash());
app.use(toastr());

app.use('/js', express.static(__dirname +
'/node_modules/jquery/dist')); // redirect JS jQuery + toastr.js is in this folder
app.use('/css', express.static(__dirname +
'/node_modules/bootstrap/dist/css')); // redirect CSS bootstrap;

index.js:
router.get('/', function(req, res, next) {
res.render('index', { title: 'Project' });
});

router.post('/', function(req, res){

var errors = req.getValidationResult();

if (errors){
    for (error in errors){
      req.toastr.error(error.msg)
    }
    res.redirect(req.get('referer'));
    return;
  }
})

I am relatively new to nodejs but I have been managing thus far, however I have tried and tried and cannot figure out why this will not work. Apologies if I am missing something extremely simple.
Cheers,
Kyle.

A: The issue is you don't pass the req object to view render function.
Change your get method of index.js to following:
router.get('/', function(req, res, next) {
    res.render('index', {
        title: 'Project',
        req: req });
});

More usage document could be found here.


text:
Q: how to use puppeteer to goto web page then press Control P to print the page? How to press control + P on a web page that is automated by puppeteer?
This code loads the web page.  But using await page.keyboard.down('Control') to press the  Control key has no effect.
(async () =>
{
  const browser = await puppeteer.launch({ headless: false });
  const page = await browser.newPage();
  await page.goto(`https://google.com`);

  await page.waitForSelector('input');
  await page.focus("input");

 // this works
  await page.keyboard.down('Shift');
  await page.keyboard.press('KeyP');
  await page.keyboard.up('Shift');

// this has no effect.
  await page.keyboard.down('Control');
  await page.keyboard.press('KeyP');
  await page.keyboard.up('Control');

})();

What I would like to do is navigate to a PDF file. Have the browser open the PDF. Then press Control P and automate the print dialog to the extent that the code selects the printer to print to and presses the Enter key.

A: running puppeteer in kiosk mode enables the window.print( ) dialog to be automatically responded to.
const puppeteer = require('puppeteer');

(async () =>
{
  const browser = await puppeteer.launch(
    {
      headless: false,
      "args": [ "--kiosk-printing" ]
    });

  const page = await browser.newPage();
  await page.goto(`file:///C:/Users/srich/Downloads/packing-list.pdf`);

  await page.evaluate(() => { window.print(); });
  await page.waitForTimeout(2000) ;

  await browser.close( ) ;
})();


text:
Q: AVAudioPlayer Interruption issue I have a problem with AVAudioPlayer Interruption.
And I'm not talking about the interruption during the incoming call. I can handle this situation very well. Call -> Interruption start -> End of call -> Interruption finish.
The problem is with the camera on the device. The situation is:
My player app is playing on background. I want to make a photo. I open the camera and make a photo. No interruption at all! But if I want to capture some video the interruption starts and the player becomes silent. At the same moment interruption finishes! (I have checked it on two devices with the help of NSLog - and I find it very weird) But the player doesn't continue playing the song because video camera is still ON. I close camera and NOW I expect the interruption to finish, but it was finished earlier and the player remain silent.
The question is: How to handle this situation?


text:
Q: Using various format specifiers of c in c++ As in c we can use various format specifiers like

*

*%nd where n is a number, to print the number with a total of atleast n space covered

*%0nd same as above, except pre-padding with 0's   " %05d ",3 => 00003

*%.nf to set precision of n after decimal

*etc ....

So is there any way to use these with std::cout ?
I got some negative feedback in a recent course (c++ for c programmers) in coursera, for using printf instead of cout because i wanted to some formatting :(

A: C++ streams don't use format-specifiers like C's printf()-type functions; they use manipulators.
For example:
#include <iostream>
#include <iomanip>

int main()
{
    std::cout << std::fixed << std::setprecision(6) << 42.0 << std::endl;
}

Output:
42.000000

See it run!

A: The usual solution in C++ is to defined manipulators which state
what your trying to format, rather than to hack physical values
directly at the point of output.  (One possible exception is the
width, where std::setw may be useful directly.)  Thus, for
example, when actually outputting something, you won't specify
zero padding, or fixed, with 2 decimals, but something like:
std::cout << temperature(2) << theTemporature;

where temperature would be something like:
class temperature
{
    int myMinWidth;
public:
    temperature( int minWidth )
        : myMinWidth( minWidth )
    {
    }
    friend std::ostream& operator<<( std::ostream& dest, temperature const& manip )
    {
        dest.setf( std::ios_base::fixed, std::ios_base::floatfield );
        dest.precision( 2 );
        dest.width( myMinWidth );
        return dest;
    }
};

For the list of format modifications available, see the
specification of std::ios_base, and the fields of
std::ios_base::fmtflags.
If you're doing a lot of output, you might want to modify this
to restore the original format flags at the end of the full
expression.  (All of the format information except the width is
sticky, so forcing fixed format here leaves you with fixed
format for the rest of the program, which isn't necessarily what
you want.)  I use the following as base class for all of my
manipulators:
class StateSavingManip
{
public:
    void operator()( std::ios& stream ) const;
protected:
    StateSavingManip() : myStream( nullptr ) {}
    ~StateSavingManip();
private:
    virtual void setState( std::ios& stream ) const = 0;
private:
    mutable std::ios* myStream;
    mutable std::ios::fmtflags mySavedFlags;
    mutable int mySavedPrec;
    mutable char mySavedFill;
};

implementation:
namespace {
int getXAlloc() ;
int ourXAlloc = getXAlloc() + 1 ;

int
getXAlloc()
{
    if ( ourXAlloc == 0 ) {
        ourXAlloc = std::ios::xalloc() + 1 ;
        assert( ourXAlloc != 0 ) ;
    }
    return ourXAlloc - 1 ;
}
}

StateSavingManip::~StateSavingManip()
{
    if ( myStream != nullptr ) {
        myStream->flags( mySavedFlags ) ;
        myStream->precision( mySavedPrec ) ;
        myStream->fill( mySavedFill ) ;
        myStream->pword( getXAlloc() ) = NULL ;
    }
}

void
StateSavingManip::operator()(
    std::ios&           stream ) const
{
    void*&              backptr = stream.pword( getXAlloc() ) ;
    if ( backptr == nullptr ) {
        backptr      = const_cast< StateSavingManip* >( this ) ;
        myStream     = &stream ;
        mySavedFlags = stream.flags() ;
        mySavedPrec  = stream.precision() ;
        mySavedFill  = stream.fill() ;
    }
    setState( stream ) ;
}

Note the use of the pword field to ensure that only the first
temporary manipulator restores the format; the destructors will
be called in the reverse order of construction, but the order of
construction will typically not be specified if you have more
than one such manipulator in an expression.
Finally: not everything is possible using this technique: if you
want to systematically append a degree sign to the temperature,
there's no way of doing so.  In this case, you need to define
a class Temperature, and overload the << operator for it; this
allows everything imaginable (much more than you could ever
achieve with printf style formatting).

A: C++ stream manipulators (iomanip) were specifically designed to support all of the standard c format specifiers operations, just with an entirely different interface. E.g. setfill and setw for the width and fill part of %02d.
Of course if you really need format strings (e.g. because it makes i18n easier for you), then you should have a look at boost::format, and if you have C++11 then you can easily write  small variadic template wrapper around it, to make the format call look more like printf.
Whatever you do, please try to not use printf. It is not typesafe, and not extendible for  output operations on user defined types.

A: For %nd %0nd, C++ equivalents are std::setw() and std::setfill().
#include <iostream>     // std::cout, std::endl
#include <iomanip>      // std::setfill, std::setw

int main () {
  std::cout << std::setfill ('x') << std::setw (10);
  std::cout << 77 << std::endl;
  return 0;
}

Output: xxxxxxxx77
%.nf can be replaced by std::setprecision and std::fixed,
#include <iostream>     // std::cout, std::fixed, std::scientific

int main () {
    double a = 3.1415926534;
    double b = 2006.0;
    double c = 1.0e-10;

    std::cout.precision(5);

    std::cout << "fixed:\n" << std::fixed;
    std::cout << a << '\n' << b << '\n' << c << '\n';
    return 0;
}

Output:
fixed:
3.14159
2006.00000
0.00000

A: There are stream manipulators, if you need them. But I think you want to know this thing: cout is smarter than printf().
Say you have:
int x = 34;
cout<<x;

Now the compiler will call:
ostream& operator<<(ostream& stream, int arg);

for you. And this function will print the output in console( since in your case stream is cout). The standard library supplies overloads for this << operator for all fundamental datatype available.


text:
Q: Spring boot maven plugin: mvn clean package does not layered jar file automatically I got trouble with spring-boot-maven-plugin build process. I just want to build
excutable "layered" jar file for optimizing docker image. As document said this build process will produce layered jar by default https://docs.spring.io/spring-boot/docs/current/maven-plugin/reference/htmlsingle/. Here is apart of my pom.xml file
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <layers>
                    <enabled>true</enabled>
                </layers>
            </configuration>
        </plugin>
    </plugins>
</build>

I used spring boot 2.5.5, maven 3.6.3
Some steps produce:

mvn clean package
jar -tf target/[excutableJarFile].jar

This filesystem of excutableJarFile is just BOOT-INF, META-INF and org although it should be

*

*dependencies

*spring-boot-loader

*snapshot-dependencies

*application

A: Enabling the layering feature of the Spring Boot Maven plugin does not change the layout of the generated jar file. It does enable the generation of a layers.idx file that describes how the application is layered, as described in the Spring Boot documentation.
You can use the layertools mode of the generated jar to extract the contents of the jar into a layered structure. See the Dockerfile example in the documentation for more information on how this works.


text:
Q: Linear Gradient not working in Firefox 11 canonical for Ubuntu This is my css
    * {
    background: linear-gradient(to right, blue, white);
    }

and my html is just essential tags (no divs ,no nothing)
<!DOCTYPE html>
<html>

<head>
<meta http-equiv="refresh" content="10">
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<title>Corruption in India</title>

<body>
</body>
</html>

But its just not appearing

A: Firefox 11 doesn't support the new gradient syntax. The notation to use for older versions is:
background: -moz-linear-gradient(left, blue, white);

You would use both (and the rest of the prefixes) to cover all bases of course.


text:
Q: Prevent resize of UIViewController when changing orientation The Maps app has a "custom" behaviour and doesn't resize the bottom menu when in landscape orientation.
What's the best way to achieve the same effect, short of resizing the view manually on every orientation change?
See attached images to get a better understanding.

A: This is done using size classes.
The easiest way to do it is to use the size classes right from your storyboard.
Right next to constraints and size related options from the size inspector you have this little + sign.
Hit it to define a different behavior for each size class.
See here for more, including how to use size classes from your code.


text:
Q: How to get the Map view zoomlevel with solo abject in robotium for android implementing apk file only I am working on robotium to test an android apk file.this apk file implementing robotium testcases .in mapview one button is inbuild buttons zoom in and zoom out buttons I would like to get the map view zoom level of certain stage. I don't know how to get with that by using solo in robotium.

A: use  solo.clickOnButton(0) its working fine in this function repeat multiple times


text:
Q: This result is a forward only result set, calling rewind() after moving forward is not supported i want to iterate à table to view tables data 2 time (in listbox and dropdown boutton), when i use one foreach for 1 inout it's ok, but when i use 2 foreach for 2 inputs i hade the bellow error i searched, i found that i must use $resultSet->buffer(); whn i replace it it my table the same eror stay:
File:
C:\xampp\htdocs\gestion-commercial-03\vendor\zendframework\zend-db\src\Adapter\Driver\Pdo\Result.php:182
Message:
This result is a forward only result set, calling rewind() after moving forward is not supported
Stack trace:
#0 C:\xampp\htdocs\gestion-commercial-03\vendor\zendframework\zend-db\src\ResultSet\AbstractResultSet.php(241): Zend\Db\Adapter\Driver\Pdo\Result->rewind()
#1 C:\xampp\htdocs\gestion-commercial-03\module\Documentachat\view\documentachat\documentachat\index.phtml(138): Zend\Db\ResultSet\AbstractResultSet->rewind()
#2 C:\xampp\htdocs\gestion-commercial-03\vendor\zendframework\zend-view\src\Renderer\PhpRenderer.php(506): include('C:\\xampp\\htdocs...')
#3 C:\xampp\htdocs\gestion-commercial-03\vendor\zendframework\zend-view\src\View.php(207): Zend\View\Renderer\PhpRenderer->render(NULL)
#4 C:\xampp\htdocs\gestion-commercial-03\vendor\zendframework\zend-view\src\View.php(236): Zend\View\View->render(Object(Zend\View\Model\ViewModel))
#5 C:\xampp\htdocs\gestion-commercial-03\vendor\zendframework\zend-view\src\View.php(200): Zend\View\View->renderChildren(Object(Zend\View\Model\ViewModel))
#6 C:\xampp\htdocs\gestion-commercial-03\vendor\zendframework\zend-mvc\src\View\Http\DefaultRenderingStrategy.php(105): Zend\View\View->render(Object(Zend\View\Model\ViewModel))
#7 [internal function]: Zend\Mvc\View\Http\DefaultRenderingStrategy->render(Object(Zend\Mvc\MvcEvent))
#8 C:\xampp\htdocs\gestion-commercial-03\vendor\zendframework\zend-eventmanager\src\EventManager.php(490): call_user_func(Array, Object(Zend\Mvc\MvcEvent))
#9 C:\xampp\htdocs\gestion-commercial-03\vendor\zendframework\zend-eventmanager\src\EventManager.php(248): Zend\EventManager\EventManager->triggerListeners('render', Object(Zend\Mvc\MvcEvent))
#10 C:\xampp\htdocs\gestion-commercial-03\vendor\zendframework\zend-mvc\src\Application.php(384): Zend\EventManager\EventManager->triggerEvent(Object(Zend\Mvc\MvcEvent))
#11 C:\xampp\htdocs\gestion-commercial-03\vendor\zendframework\zend-mvc\src\Application.php(356): Zend\Mvc\Application->completeRequest(Object(Zend\Mvc\MvcEvent))
#12 C:\xampp\htdocs\gestion-commercial-03\public\index.php(29): Zend\Mvc\Application->run()
#13 {main}

Table :
<?php
///=======================DocumentachatTable factory=========================
namespace Documentachat\Model;

use Zend\Db\ResultSet\ResultSet;
use Zend\Db\Sql\Expression;
use Zend\Db\Sql\Select;
use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Where;
use Zend\Db\TableGateway\TableGateway;
use Zend\Paginator\Adapter\DbSelect;
use Zend\Paginator\Paginator;

class DocumentachatTable
{
    protected $tableGateway;
    private $lastinserted;

    public function __construct(TableGateway $tableGateway)
    {
        $this->tableGateway = $tableGateway;
    }

    public function fetchAll($paginated = false)
    {

        if ($paginated) {

            // create a new Select object for the table album
            $select = new Select('achat__document');
            // create a new result set based on the Album entity
            $resultSetPrototype = new ResultSet();
            $resultSetPrototype->setArrayObjectPrototype(new Documentachat());
            // create a new pagination adapter object
            $paginatorAdapter = new DbSelect(
            // our configured select object
                $select,
                // the adapter to run it against
                $this->tableGateway->getAdapter(),
                // the result set to hydrate
        $resultSetPrototype->buffer();
                $resultSetPrototype
            );
            $select->where(array('achat__document.deleted' => 1));
            $paginator = new Paginator($paginatorAdapter);

            return $paginator;
        }

        $select = $this->tableGateway->getSql()->select();
        $select->where(array('achat__document.deleted' => 1));
        $results = $this->tableGateway->selectWith($select);
        return $results;

    }

    public function lastInserted()
    {
        return $this->lastinserted;
    }

    public function getDocument($id)
    {
        $id = (int)$id;
        $rowset = $this->tableGateway->select(array('id' => $id));
        $row = $rowset->current();
        if (!$row) {
            throw new \Exception("Could not find row $id");
        }
        return $row;
    }

    public function getLastCount($idType)
    {
        $idType = (int)$idType;
        $select = $this->tableGateway->getSql()->select();

        $select->where->equalTo('id_type', $idType);
        $select->order('count desc');

        $rowset = $this->tableGateway->selectWith($select);
        $row = $rowset->current();
        if (!$row) {
            return 0;
        }
        return $row;
    }

    public function saveDocument(Documentachat $document)
    {
        $data = array(
            'reference' => $document->reference,
            'id_type' => $document->idType,
            'id_fournisseur' => $document->idFournisseur,
            'address' => $document->address,
            'deleted' => 1,
            'date_doc' => $document->dateDoc
        );

        $id = (int)$document->id;
        if ($id == 0) {
            $data['count'] = $this->getLastCount($document->idType)->count + 1;
            $this->tableGateway->insert($data);
            $this->lastinserted = $this->tableGateway->getLastInsertValue();
        } else {
            if ($this->getDocument($id)) {
                $this->tableGateway->update($data, array('id' => $id));
            } else {
                throw new \Exception('Documentachat id does not exist');
            }
        }
    }

    public function deleteDocument($id)
    {
        $data = array(
            'deleted' => 0,
        );
        $this->tableGateway->update($data, array('id' => $id));
    }

    public function searchDocument($query)
    {
        $select = $this->tableGateway->getSql()->select();
        $select->where(array('achat__document.deleted' => 1));
        $select->where->like('achat__document.reference', '%' . $query . '%');
        $results = $this->tableGateway->selectWith($select);
        return $results;
    }

View:
<?php

$title = 'Documentachat';
$this->headTitle($title);
?>

                     Date début
                    <input type="date" id="dateMinI" class="form-control" name="dateMinI">

                     Date fin
                    <input type="date" id="dateMaxI" class="form-control" name="dateMaxI" >

                     N° Document
                    <input type="text" id="Reference" class="form-control" name="Reference" value autocomplete="off">

                     Fournisseur
                    <input type="text" id="fournisseur" class="form-control" name="fournisseur" >

                     Document Type

                    <select id="doctype" class="form-control" name="doctype">
                        <option value="">---</option>

                        <?php foreach ($this->docTypes as $item) : ?>
                            <option value=<?php echo $item->id; ?> >   <?php echo $item->label; ?> </option>
                        <?php endforeach;
                          ?>

                    </select>

                        <button type="button" id="sendid" class="btn btn-primary btn-block">

                            OK
                        </button>

                <button type="button" data-toggle="modal" data-target="#transformerModal" id="transformer"
                        class="btn btn-sm btn-default">

                    Transformer
                </button>

                    <button type="button " class="btn btn-primary  btn-sm dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                        Ajouter
                    </button>

                                DEVIS

                                BON DE COMMANDE

                                BON DE LIVRAISON

                                BON DE RETOUR

                                FACTURE INTERNE

                                FACTURE A COMPTABILISER

                                FACTURE COMPTABILISEE

                                FACTURE DE RETOUR

                                AVOIR FINANCIER

                    <button class="btn btn-primary dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
                        Ajouter

                    </button>

                        <?php

                        foreach ($this->docTypes as $item)  { ?>

<a href="<?= $this->url('documentachat', array('action'=>'add', 'id' => $item->id));?>"><?= $item->label?>

                        <?php } ?>
                        <?php  ?>

module.config.php
<?php

return array(
    'controllers' => array(
        'invokables' => array(
            'Documentachat\Controller\Documentachat' => 'Documentachat\Controller\DocumentachatController',
            'Documentachat\Controller\Parametreachat' => 'Documentachat\Controller\ParametreachatController',
            'Documentachat\Controller\DocArticle' => 'Documentachat\Controller\DocArticleController',
        ),
    ),

    'router' => array(
        'routes' => array(
            'documentachat' => array(
                'type'    => 'segment',
                'options' => array(
                    'route'    => '/documentachat[/:action][/:id]',
                    'constraints' => array(
                        'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                        'id'     => '[0-9]+',
                    ),
                    'defaults' => array(
                        'controller' => 'Documentachat\Controller\Documentachat',
                        'action'     => 'index',
                    ),
                ),
            ),

            'parametreachat' => array(
                'type'    => 'segment',
                'options' => array(
                    'route'    => '/parametreachat[/:action][/:id]',
                    'constraints' => array(
                        'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                        'id'     => '[0-9]+',
                    ),
                    'defaults' => array(
                        'controller' => 'Documentachat\Controller\Parametreachat',
                        'action'     => 'index',
                    ),
                ),
            ),

            'docarticle' => array(
                'type'    => 'segment',
                'options' => array(
                    'route'    => '/docarticle[/:action][/:id]',
                    'constraints' => array(
                        'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                        'id'     => '[0-9]+',
                    ),
                    'defaults' => array(
                        'controller' => 'Documentachat\Controller\DocArticle',
                        'action'     => 'index',
                    ),
                ),
            ),

        ),
    ),

    'view_manager' => array(
        'template_path_stack' => array(
            'documentachat' => __DIR__ . '/../view',
        ),
    ),
);


text:
Q: How to insert into mysql with Boolean condition I have this statement that I wanna execute:
INSERT INTO kitchenitems (kno, `date`, added_Date, added_By)
VALUES (5,'2016-04-01', now(), 2);

but before it executes i wanna check whether "kno" has "5" or not. If not it should execute. If has it should not execute. Thanks in advance.

A: You can do something like this:
    INSERT INTO kitchenitems (`kno`, `date`, `added_Date`,`added_By`)
    SELECT kno,date,added_Date,added_By
    FROM (SELECT '5' as kno, '2016-04-01' as date, NOW() as added_Date, '2' as added_By) a
    WHERE NOT EXISTS (SELECT 1 FROM kitchenitems b WHERE a.kno = b.kno);

However, if you want unique values of kno, you should ensure that at server-side.

A: Hi there I think that can easealy be done with stored procedure... I would suggest you to read this article HERE I think that's the answer on your solution.
Here is SQL Fiddle to see how that works on your problem...
here is your stored procedure
CREATE PROCEDURE addItem
(IN inkno INT, IN inddate DATETIME, IN inadded_Date DATETIME, IN inadded_By INT)
BEGIN
    DECLARE SomeId int;
    DECLARE CheckExists int;
    SET CheckExists = 0;

    SELECT count(*) INTO CheckExists from kitchenitems WHERE kno = inkno;

    IF (CheckExists > 0) THEN
        SELECT kno INTO SomeId FROM kitchenitems WHERE kno = inkno;
    ELSE
        INSERT INTO kitchenitems (kno,ddate,added_Date,added_By)
        VALUES (inkno, inddate,inadded_Date, inadded_By);
    END IF;

END/


text:
Q: Minimum value of length of tangent of the ellipse $x^2/a^2 + y^2/b^2 = 1$, intercepted between the co-ordinate axes I have taken a parameter $(a \cos c, b \sin c)$ where $c$ is the eccentric angle and the tangent passing through this point cuts the x-axis at the point $(a \cos c, 0)$ and y-axis at $(0,b \sin c)$.
After this I have calculated the the length using Pythagoras theorem. But I couldn't get the minimum value.

A: Length of tangent intercepted:
$\sqrt { \frac {a^2}{ {cos}^2 t}+ \frac {b^2 }{{sin}^2t}}$
= $\sqrt { a^2 {sec}^2 t+ b^2 {cosec}^2t}$
= $\sqrt { a^2{tan}^2t+a^2+ b^2 {cot}^2t+b^2}$
Using AM-GM inequality:
$\frac {a^2{tan}^2t+b^2 {cot}^2t} 2 \ge \sqrt {a^2{tan}^2t.b^2 {cot}^2t}$
So ${a^2{tan}^2t+b^2 {cot}^2t}  \ge 2ab $
Therefore required minimum value is $a+b$


text:
Q: Sparklyr: List contents of directory in R using invoke methods Unable to find a sparklyr built in for listing the contents of a directory via Spark, I am attempting to use invoke:
sc <- spark_connect(master = "yarn", config=config)
path <- 'gs:// ***path to bucket on google cloud*** '
spath <- sparklyr::invoke_new(sc, 'org.apache.hadoop.fs.Path', path)
fs <- sparklyr::invoke(spath, 'getFileSystem')
list <- sparklyr:: invoke(fs, 'listLocatedStatus')

Error: java.lang.Exception: No matched method found for class org.apache.hadoop.fs.Path.getFileSystem
    at sparklyr.Invoke.invoke(invoke.scala:134)
    at sparklyr.StreamHandler.handleMethodCall(stream.scala:123)
    at sparklyr.StreamHandler.read(stream.scala:66) ...

Note: Are there guidelines for reproducible examples with distributed code? I don't know how to make an example others could follow, given I am running against a particular Spark environment.

A: getFileSystem method takes org.apache.hadoop.conf.Configuration object as the first argument:

public FileSystem getFileSystem(Configuration conf)
                     throws IOException

Return the FileSystem that owns this Path.
Parameters:
conf - the configuration to use when resolving the FileSystem

So the code to retrieve FileSystem instance should looks more or less like this:
# Retrieve Spark's Hadoop configuration
hconf <- sc %>% spark_context() %>% invoke("hadoopConfiguration")
fs <- sparklyr::invoke(spath, 'getFileSystem', hconf)

Additionally listLocatedStatus takes either Path

public org.apache.hadoop.fs.RemoteIterator<LocatedFileStatus> listLocatedStatus(Path f)
                                                                     throws FileNotFoundException,
                                                                            IOException

or Path and PathFilter (note that this implementation is protected):

public org.apache.hadoop.fs.RemoteIterator<LocatedFileStatus> listLocatedStatus(Path f)
                                                                    throws FileNotFoundException,
                                                                            IOException

So if you want to structure your code as shown above you'll have to provide at least a path
sparklyr:: invoke(fs, "listLocatedStatus", spath)

In practice it might be easier to just get FileSystem directly:
fs <- invoke_static(sc, "org.apache.hadoop.fs.FileSystem", "get",  hconf)

and use globStatus
lls <- invoke(fs, "globStatus", spath)

where spath is a path with wildcard, like:
sparklyr::invoke_new(sc, 'org.apache.hadoop.fs.Path', "/some/path/*")

The result will be an R list, which can be easily iterated:
lls  %>%
    purrr::map(function(x) invoke(x, "getPath") %>% invoke("toString"))

Credits:
The answer to How can one list all csv files in an HDFS location within the Spark Scala shell? by @jaime
Notes:

*

*In general, if you interact with non-trivial Java API, it makes much more sense to write your code in Java or Scala, and provide a minimal R interface.

*For interactions with specific file object store it might be easier to use a dedicated package. For Google Cloud Storage you can take a look at googleCloudStorageR.


text:
Q: IBOutlet not working when trying to adjust subviews So my outlets are as follows, and yes they are connected in my .xib file:
IBOutlet UIButton *savedReadings;
IBOutlet UIButton *beginReading;

Here's my .m file:
 if ([[ UIScreen mainScreen] bounds].size.height == 568){

        _background.hidden = NO;
        _background2.hidden = YES;
        _PalmFrame.hidden = YES;

    }else{

        [beginReading setFrame:CGRectMake(beginReading.frame.origin.x, beginReading.frame.origin.y-1500, beginReading.frame.size.width, beginReading.frame.size.height)];
        [savedReadings setFrame:CGRectMake(savedReadings.frame.origin.x, savedReadings.frame.origin.y-1500, savedReadings.frame.size.width, savedReadings.frame.size.height)];
        _background2.hidden = NO;
        _background.hidden = YES;
        _PalmFrame.hidden = NO;
}

for some reason every time I try to make an adjustment to the y-axis placement of the button it doesn't budge. Any ideas?

A: As a primary step check these things

*

*Check your lines  executed or not..

*Verify your outlets correctly configured or not most of the times that happens!!!
If above two steps correctly done then go to your storyboard or interface builder and remove savedReadings, beginReading buttons auto layouts, you will get expected output.


text:
Q: How to find client ip address instead of server ip address in asp.net c#? I used below code for getting IP address, but it is giving server IP address.
 public static string LocalIPAddress()
        {
            IPHostEntry host;
            string localIP = "";
            host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    localIP = ip.ToString();
                    break;
                }
            }

        return localIP;
    }

From website
    "http://whatismyipaddress.com/" I found my IP address is:
203.100.79.91

But code is providing me some different IP :
172.24.0.123

How can I get user IP instead of server ?
Please suggest.
Thanks


text:
Q: Evenly distribute points on a circle I need to distribute points evenly on a circumference of a circle, and I'm out of my wits. The result is not exactly circular but rather spiraly, especially with larger numbers of points. I've researched it vigorously but still can't figure out where I could make a mistake.

  window.onload = function() {
      var num = 15;

      var angle = (2 * Math.PI)/(num+1); var count = 0;
      var demo = document.getElementById("demo");

      function Dot() {
          this.angle = angle * count;
          count++;
          this.x = Math.cos(this.angle) * 200;
          this.y = Math.sin(this.angle) * 200;
      }

      Dot.prototype.create = function() {
          var dot = document.createElement("div");
          dot.style.top = this.y + 100 + "px";
          dot.style.left = this.x + 200 + "px";
          dot.className = "dot";
          demo.appendChild(dot);
      }

      for (var i = 0; i < num; i++) {
          var d = new Dot();
          d.create();
      }
  }
  .dot {
      height: 20px;
      width: 20px;
      border-radius: 50%;
      background: blue;
      position: relative;
      text-align: center;
  }
    <!DOCTYPE html>

      <title>Metcalfe's Law Demo</title>
      <link rel="stylesheet" href="style.css">

A: The main mistake is bloody simple - just change the style position: relative to position: absolute:

window.onload = function() {
      var num = 12;

      var angle = (2 * Math.PI)/(num); var count = 0;
      var demo = document.getElementById("demo");
      console.log(angle)

      function Dot() {
          this.angle = angle * count;
          count++;
          console.log(this.angle,count)
          this.x = Math.cos(this.angle) * 200;
          this.y = Math.sin(this.angle) * 200;
      }

      Dot.prototype.create = function() {
          var dot = document.createElement("div");
          dot.style.top = this.y + 200 + "px";
          dot.style.left = this.x + 200 + "px";
          dot.className = "dot";
          demo.appendChild(dot);
      }

      for (var i = 0; i < num; i++) {
          var d = new Dot();
          d.create();
      }
  }
.dot {
      height: 20px;
      width: 20px;
      border-radius: 50%;
      background: blue;
      position: absolute;
      text-align: center;
  }
<!DOCTYPE html>

      <title>Metcalfe's Law Demo</title>
      <link rel="stylesheet" href="style.css">


text:
Q: Excel Network days formula using multiple Holiday conditions I am working on a vacation dashboard where I want I am trying to calculate the number of working days between two days using networkdays but I have different holidays list for different set of people.
I have two Holiday list one according to Indian calendar and one according to US calendar. My excel sheet looks something like this.
** Excel Screen shot**

I have put a table reference for each of these small tables.In column A I have name of the employees which might be an Indian Employee or an US employee. The employee will enter the details of there vacation type, start and end date till column D and the Column E will then calculate the Number of days leaves taken using the start and the end date.
=NETWORKDAYS(vaca[[#This Row],[Start Date]],vaca[[#This Row],[End Date]],Holidays[Holidays])
I have a list of Holidays separately for both the US and Indian Calender (column K& L)and the different employee list both Indian and US in column I.
I now want to calculate the number of days in column E such that when it sees the name of the employee in column A it calculates in on the basis of the US and UK holiday calender and the employee name.
For example
if the Name of the employee in column A fall is in the employee_india table the the network days should take Holiday India calendar and if the name of the employee in column A is in employee US then use US holiday calendar. i have used multiple IF statements and a true and false condition but nothing works.
please suggest the solution for the same


text:
Q: Email charset. HTML emails. PHP mail() I'm trying to send email using mail() PHP function.
Text is cyrillic, and when I receive the message I've something like this:
Н�! �цио� �альный
Other words are correct.
Here's the my headers:
$header = '';
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html; charset=UTF-8\r\n";
$header .= "From: \"Example.com\" <no-reply@example.com>\r\n";
$subject = '=?UTF-8?B?' . base64_encode($this->_data['subject']) . '?=';//works fine, but when I'm trying to use it for content, I'm receiving encoded text
@mail($this->_data['to'], $subject, $this->_html, $header);


text:
Q: NavigatorIOS error: undefined is not an object (evaluating routerArg.component) Super, super basic React Native installation here; trying to add a simple NavigatorIOS instance to my application. I've populated NavigatorIOS with an initialRoute parameter, and set the component of that to another component, but I'm getting the error in the title at runtime. Here's an image of what I'm seeing.

App.js
/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow
 */

import React, {Component} from 'react';
import FontAwesome5 from 'react-native-vector-icons/FontAwesome5';
import {Platform, StyleSheet, Text, View, NavigatorIOS, TabBarIOS} from 'react-native';
import {HomePage} from './app/pages/Home';

const instructions = Platform.select({
  ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu'
});

type Props = {};
export default class App extends Component<Props> {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.instructions}>{instructions}</Text>
          <NavigatorIOS
              intitialRoute={{
                  component: HomePage,
                  title: 'Home'
              }}/>
      </View>
    );
  }
}

Home.js
import React, {Component} from "react";
import {View} from "react-native";

export class HomePage extends Component<{}> {

    constructor(props, context) {
        super(props, context);
    }

    _onForward = () => {
        this.props.navigator.push({
            title: 'Scene foo',
        });
    };

    render() {
        return (
          <View>
          </View>
        );
    }
}

Why am I seeing this? Running Xcode-10 beta, with the latest release of React Native, on macOS 10.14 Mojave.

A: This is due to the typo here
<NavigatorIOS
   intitialRoute ={{ // <== here
     component: HomePage,
     title: 'Home'
}}/>

Replace intitialRoute with initialRoute


text:
Q: TeamCity CppUnit plugin prints extra '\n' I have integrated TeamCity with Cppunit using their plugin.
I'm trying to get rid of the '\n' that's being appended after each test. I tried commenting out details.append("\n"); from teamcity_cppunit.cpp, but that didn't do the trick. And I didn't find anywhere else that '\n' is being appended.
Basically I want to get this :
16>  Description: Executing Unit Tests...
16>  Running 4 test cases...
16>  CoreTechUnitTests::CLogExtractorTestCase::CreateLogExtractorTest... [0.2503s]
16>  CoreTechUnitTests::CLogExtractorTestCase::CreateOutputFolderTest... [0.0057s]
16>  CoreTechUnitTests::CLogExtractorTestCase::WriteLogFileTest... [0.0050s]
16>  CoreTechUnitTests::CLogExtractorTestCase::LastRunUnitTest... [0.0001s]
16>  Total test execution took 0.2612s
16>
16>  OK (4)

As opposed to this :
9>  CoreTechUnitTests::CMcMd5TestCase::MD5Test...CoreTechUnitTests::CMcMd5TestCase::MD5Test [0.0001s] : OK
9>
9>  CoreTechUnitTests::CByteBufferTest::TestBuffer...CoreTechUnitTests::CByteBufferTest::TestBuffer [0.0003s] : OK
9>
9>  CoreTechUnitTests::CETWLogConsumerTestCase::CreateETWReaderTests...CoreTechUnitTests::CETWLogConsumerTestCase::CreateETWReaderTests [0.0106s] : OK
9>
9>  CoreTechUnitTests::CETWLogConsumerTestCase::ExtractEventSystemTimeTests...CoreTechUnitTests::CETWLogConsumerTestCase::ExtractEventSystemTimeTests [0.0001s] : OK

I was wondering if anyone knows where that '\n' is being appended.

A: It looks like there is an endl written to the output stream in teamcity_messages.cpp at line 71:
*m_out << endl;

Another place to look is in teamcity_boost.cpp at line 153:
out << endl;

See if removing one of these does the trick.


text:
Q: C++: using fstream, maps, and output I am trying to open a text file, and from this, read each line, and map each word occurrence to the line number it is on. Then, I want to print the map.
Here is my code:
#include <map>
#include <set>
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main(){

std::map<string, set<int>> myMap;
ifstream myFile;
string myLine ="";
int lineNum = 0;
stringstream myStream;
string myWord ="";
set<int> mySet;

myFile.open("myTextFile.txt");
if(myFile.is_open()){
    while (!myFile.eof()){
        getline(myFile, myLine);
        myStream.str(myLine);
        ++lineNum;
        while (!mySStream.eof())
        {
            myStream >> myWord;
            myMap[myWord].insert(lineNum);

        }
        myStream.clear();
   }
}
myFile.close();
// at this point, I expect everything to have been mapped
// mapping each word occurrence to a line
//I now want to print the map but out does not work, and I need to use an iterator
//I have tried this:
map<string, set<int>>::iterator iter;
for (iter = myMap.begin(); iter != myMap.end(); ++iter)
{
    cout << "Key: " << iter->first << endl << "Values:" << endl;
    set<int>::iterator setIter;
    for ( setIter = iter->second.begin(); setIter != iter->second.end(); ++setIter)
        cout << " " << *setIter<< endl;
}
return 0;

}

I have no output. Why not?
Secondly, is everything being properly mapped?

A: I haven't been able to test it as I am not at my development machine. This should work if I understand what you are trying to do.
Basically, instead of checking the EOF bit, I moved the getlines into the while loops. std::getline will exit the loop after it has read the entire file!
#include <map>
#include <set>
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>

using namespace std;
int main(){
std::map<string, set<int>> myMap;
ifstream myFile;
string myLine ="";
int lineNum = 0;
stringstream myStream;
string myWord ="";
set<int> mySet;

myFile.open("myTextFile.txt");

if(myFile.is_open()){
    while (getline(myFile, myLine)){
        myStream.str(myLine);
        ++lineNum;
        while (myStream >> myWord)
        {
            myMap[myWord].insert(lineNum);
        }
        myStream.clear();
   }
    myFile.close();
}
else
{
    std::cout << "Unable to open file!" << std::endl;
}

map<string, set<int>>::iterator iter;
for (iter = myMap.begin(); iter != myMap.end(); ++iter)
{
    cout << "Key: " << iter->first << endl << "Values:" << endl;
    set<int>::iterator setIter;
    for (setIter = iter->second.begin(); setIter != iter->second.end(); ++setIter)
    {
        cout << " " << *setIter<< endl;
    }
}
return 0;

}


text:
Q: Cannot Open Shared File Error in Netbeans | JavaFx FXML Application I keep getting this Error whenever I compile my code:
Failed to load plugin /path/zulu/lib/libavplugin.so': libavcodec.so.55: cannot open shared object file: No such file or directory.

However there is a file named libavplugin.so in lib folder. I am currently using Netbeans and the category of my project is javafx and the project is javafx with FXML Application.
Initially I was not able to create a javafx project with FXML Application as I was getting an Error of
 "Failed to automatically set up a JavaFX Platform".

So, I downloaded an open JDK from zulu and set up a non default JAVA platform. Now I am able create projects but code is not compiling.
I have looked over many stack overflow questions and I have also tried doing sudo ldconfig. Nothing is working for me.
Any help will be much appreciated. Thanks in Advance.


text:
Q: jQuery dialog won't close (with .load data) On my page (let's call it page A) I have a jQuery dialog with the id customOrderEdit. Within the dialog I load another page (let's call it page B) using $("#customOrderEdit").load("/url/to/page.php").
Now I want to close the dialog using a custom button, but it won't close. I've tried so many things (found on google, stackoverflow, etc.) but none of them seem to work. It doesn't matter if the code to close the dialog are on page A or B, as long as it closes I'm happy.
Code I tried on page A:
$("body").on('click', '.cancelUpdateOrder', function(){
    console.log("Test"); //it displays the test console log, but it doesn't close
    $("#customOrderEdit).dialog( "close" );
    return false;
});

Code I tried on page B:
$(".cancelUpdateOrder").on('click', function(){
        $('#customOrderEdit').dialog('close');
        return false;
});

I've also tried to call the click function differently:

*

*$(".cancelUpdateOrder").click(function(){ }});

*$(".cancelUpdateOrder").live('click', function(){ }});

*$(".cancelUpdateOrder").on('click', function(){ }});.

And the closing part:

*

*$(".ui-dialog").dialog( "close" );

*window.parent.$('#customOrderEdit').dialog('close');

*$('#customOrderEdit', window.parent).dialog("close");
And probably some more I can't remember.
Does anyone know what I'm doing wrong and can provide me the right code?

A: The class selector can return a list of objects, then you can try to iterate with them using each:
$('.cancelUpdateOrder').each( function () {
    $(this).on('click', function () {
        $('#customOrderEdit').dialog('close');
        return false;
    })
});

If doesn't work, you can try to put a console.log to track if you are reaching the right elements.
Hope it helps

A: I had this problem and commented out the jquery.js included in the file being loaded (file B) even though it was the exact same jquery.js file that had been included in the calling file (file A).  The following example will NOT work unless you comment out the

    <button id="btnAddClient" name="btnAddClient">Add</button>

test.js
$( document ).ready(function() {

    $("#contentsContainer").on('click', '#btnAddClient', function () {
        var dlg = $("
").dialog({
            title: 'Add New Client',
            modal: true,
            autoOpen: false,
            width: 720,
            height: 420,
            buttons: {
                Save: function () {
                    $.post("../php/test.php");
                    $('#btnAddClientDlg').dialog('destroy').remove();

                },
                Close: function () {
                    $('#btnAddClientDlg').dialog('close');
                }
            }
        });
        dlg.load("../php/test.php");
        dlg.dialog('open');
    });
});

test.php
<!DOCTYPE html>

<?php
    echo "hello";
?>


text:
Q: Formula to determine USPS Postal Zone based on ZIP code I'm looking to make the sorting of hundreds of envelopes by USPS postal zones easier. The difficulty is in having to manually sort them for each of the 8 US zones, based on the origin ZIP code: 91352.
http://postcalc.usps.gov/ZoneCharts/
I have a spreadsheet of contacts that includes a ZIP column. I've set up a separate sheet of all of the USPS ZoneCharts site based on "913", and combined the four sections into one (two columns total). I then used the LEFT and RIGHT functions to get the first three and last three numbers of the first column and put them into their own columns (now three columns total):

ZIP_BEG  ZIP_END  Zone
005      098      8
100      212      8
214      268      8
270      342      8
344      344      8
346      347      8
349      349      8
350      352      7
354      359      7
360      361      8
362      362      7
363      364      8
365      366      7
...etc.
Would I use the VLOOKUP function from the sheet of contacts to search each ZIP (using the LEFT function to use only the first three numbers of each ZIP value) and then check whether that value is both greater than the ZIP_BEG value and less than the ZIP_END value?
Whatever row it matches, it would return the Zone value. I'm putting this as a column after the ZIP column in the first sheet.

A: Splitting out every possible zip code seems viable but might be 'overkill' (though might be useful to detect errors). I'm assuming that a code not in the range mentioned is (a) not valid but (b) does not require to be flagged in any way, so for example 099 will either never arise in practice (unless the tables are updated) or can 'safely' be treated as 098.
This is to make it possible to consider only one value for each band (before a change in Zone), conveniently your ZIP_BEG ones, in conjunction with an inexact VLOOKUP. The syntax for VLOOKUP is:
VLOOKUP(lookup_value,table_array,col_index_num,range_lookup)
where the fourth parameter (range_lookup) is optional. Forgetting it or setting it to TRUE (or 1) by mistake has caused much grief but may be very suitable here.
To quote:

If TRUE or omitted, an exact or approximate match is returned. If an exact match is not found, the next largest value that is less than lookup_value is returned.
  The values in the first column of table_array must be placed in ascending sort order; otherwise, VLOOKUP may not give the correct value.

(It does a binary search, so needs to know which direction is more and which less).Your values should already be in the required order, so a formula such as:
=VLOOKUP(A2,ZIPUP,2)

somewhere in the same workbook should be sufficient, where the value to be looked up (first three digits of destination Zip) is assumed to be in A2 and ZIPUP is the name of a workbook-scoped range of ZIP_BEG in one column and Zone in the matching rows in the column immediately to the right of that.
Given the initial assumptions, the entire ZIP-BEG list is not required (108 'ranges') as, using only the limits, 74 are sufficient (and should be quicker).
If not aggregating the bands in that way, beware of formatting as 005 is not the same as 5 and that distinction is relevant to =VLOOKUP. You have used =LEFT and =RIGHT to extract your lists and these text functions return strings, though here I would prefer number formatting myself. (I split the ranges with Text to Columns.)


text:
Q: changing interface in an asynctask (the right way) I'm trying to change the process data retrieved into a list view. The data is recieved properly. but i'm failing to make up the list view the right way.
Here is my asynctask class
class GetFriendsInfo extends AsyncTask<String, String, String>{

    String id = "";
    String fullName = "";
    String birthday = "";

    protected void onPreExecute() {
        super.onPreExecute();
        pd_GetData = new ProgressDialog(MainActivity.this);
        pd_GetData.setMessage("Getting friend data");
        pd_GetData.setIndeterminate(false);
        pd_GetData.setCancelable(true);
        pd_GetData.show();
    }

    @Override
    protected String doInBackground(String... params) {

        JSONArray friendArray;

        List<NameValuePair> param = new ArrayList<NameValuePair>();
        param.add(new BasicNameValuePair("user_id", id));
        param.add(new BasicNameValuePair("user_id", fullName));
        param.add(new BasicNameValuePair("user_id", birthday));

        JSONObject jsonObject = jsonParser.makeHttpRequest(url_get_birthdays,"GET", param);

        try{
            int success = jsonObject.getInt(TAG_SUCCESS);

            if (success == 1){
                Log.d("PHP Server [GET]", "Retrieved user data");

                String jsonString = jsonObject.getString("message");
                friendArray = new JSONArray(jsonString);

                String[] names = new String[friendArray.length()];
                String[] birthdays = new String[friendArray.length()];
                String[] ids = new String[friendArray.length()];

                for(int i=0; i<friendArray.length(); i++) {
                    JSONObject friend = friendArray.getJSONObject(i);
                    String friend_id = friend.getString("id");
                    ids[i] = friend_id;
                    String friend_name = friend.getString("fullName");
                    names[i] = friend_name;
                    String friend_birthday = friend.getString("birthday");
                    birthdays[i] = friend_birthday;
                }

                Log.i("friend:", Arrays.toString(ids) + " " + Arrays.toString(names) + " " + Arrays.toString(birthdays));

               List<HashMap<String, String>> birthday = new ArrayList<HashMap<String, String>>();

                for (int i=0;i<names.length;i++){
                    HashMap<String, String> hm = new HashMap<String, String>();
                    hm.put("names", names[i]);
                    hm.put("ids", ids[i]);
                    hm.put("birthdays", birthdays[i]);
                    birthday.add(hm);
                }

                String[] from = {"names", "ids", "birthdays"};
                int[] to = {R.id.text1, R.id.im_ProfilePic, R.id.text2};

                SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, birthday, R.layout.listitem_birthday, from, to);
                HorizontalListView featuredList = (HorizontalListView) findViewById(R.id.lv_Birthdays);
                featuredList.setAdapter(adapter);

            }else{
                Log.d("PHP Server [GET]", "Failed retrieve user data");
            }
        }catch (JSONException e){
            e.printStackTrace();
        }catch (RuntimeException e){
            e.printStackTrace();
        }

        return null;
    }

    protected void onPostExecute(JSONArray result) {
        // dismiss the dialog once done

        pd_GetData.dismiss();
    }
}

I know that i shouldn't create the listview in the doInBackground. But i don't have a clue how i should do it.

A: set your adapter in onPostExecute() method.
class GetFriendsInfo extends AsyncTask<String, String, String>{

String id = "";
String fullName = "";
String birthday = "";
List<HashMap<String, String>> birthday;

protected void onPreExecute() {
    super.onPreExecute();
    pd_GetData = new ProgressDialog(MainActivity.this);
    pd_GetData.setMessage("Getting friend data");
    pd_GetData.setIndeterminate(false);
    pd_GetData.setCancelable(true);
    pd_GetData.show();
}

@Override
protected String doInBackground(String... params) {

    JSONArray friendArray;

    List<NameValuePair> param = new ArrayList<NameValuePair>();
    param.add(new BasicNameValuePair("user_id", id));
    param.add(new BasicNameValuePair("user_id", fullName));
    param.add(new BasicNameValuePair("user_id", birthday));

    JSONObject jsonObject = jsonParser.makeHttpRequest(url_get_birthdays,"GET", param);

    try{
        int success = jsonObject.getInt(TAG_SUCCESS);

        if (success == 1){
            Log.d("PHP Server [GET]", "Retrieved user data");

            String jsonString = jsonObject.getString("message");
            friendArray = new JSONArray(jsonString);

            String[] names = new String[friendArray.length()];
            String[] birthdays = new String[friendArray.length()];
            String[] ids = new String[friendArray.length()];

            for(int i=0; i<friendArray.length(); i++) {
                JSONObject friend = friendArray.getJSONObject(i);
                String friend_id = friend.getString("id");
                ids[i] = friend_id;
                String friend_name = friend.getString("fullName");
                names[i] = friend_name;
                String friend_birthday = friend.getString("birthday");
                birthdays[i] = friend_birthday;
            }

            Log.i("friend:", Arrays.toString(ids) + " " + Arrays.toString(names) + " " + Arrays.toString(birthdays));

            birthday = new ArrayList<HashMap<String, String>>();

            for (int i=0;i<names.length;i++){
                HashMap<String, String> hm = new HashMap<String, String>();
                hm.put("names", names[i]);
                hm.put("ids", ids[i]);
                hm.put("birthdays", birthdays[i]);
                birthday.add(hm);
            }

        }else{
            Log.d("PHP Server [GET]", "Failed retrieve user data");
        }
    }catch (JSONException e){
        e.printStackTrace();
    }catch (RuntimeException e){
        e.printStackTrace();
    }

    return null;
}

protected void onPostExecute(JSONArray result) {
    // dismiss the dialog once done

    String[] from = {"names", "ids", "birthdays"};
            int[] to = {R.id.text1, R.id.im_ProfilePic, R.id.text2};

            SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, birthday,   R.layout.listitem_birthday, from, to);
            HorizontalListView featuredList = (HorizontalListView) findViewById(R.id.lv_Birthdays);
            featuredList.setAdapter(adapter);

      pd_GetData.dismiss();
  }
}

A: This should give you the idea. Read the inline comments:
class GetFriendsInfo extends AsyncTask<Void, Void, JSONObject> {
    private String url;
    public GetFriendsInfo(String url_get_birthdays) {
        this.url = url_get_birthdays;
    }
    @Override
    protected JSONObject doInBackground(Void... params) {
        // Make your network call and get your JSONObject
        JSONObject jsonObject = jsonParser.makeHttpRequest(url_get_birthdays,"GET", param);

        return jsonObject;
    }

    @Override
    protected void onPostExecute(JSONObject jsonObject) {
        // Here you get your jsonObject on the main thread. You can  parse it and update your UI
        // Convert your jsonObject to what you want and then show the dialog

String[] from = {"names", "ids", "birthdays"};
        int[] to = {R.id.text1, R.id.im_ProfilePic, R.id.text2};

        SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, birthday,   R.layout.listitem_birthday, from, to);
        HorizontalListView featuredList = (HorizontalListView) findViewById(R.id.lv_Birthdays);
        featuredList.setAdapter(adapter);

    }
}

A: As UI operation can not be done in doinbackground. So first make birthday list global in asyntask.
List<HashMap<String, String>> birthday = new ArrayList<HashMap<String, String>>(); // make it Global.

move the below part from doinbackground to
protected void onPostExecute(JSONArray result) {
        // dismiss the dialog once done

        pd_GetData.dismiss();

    String[] from = {"names", "ids", "birthdays"};
                int[] to = {R.id.text1, R.id.im_ProfilePic, R.id.text2};

                SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, birthday, R.layout.listitem_birthday, from, to);
                HorizontalListView featuredList = (HorizontalListView) findViewById(R.id.lv_Birthdays);
                featuredList.setAdapter(adapter);
    }

If you have still nay query please let me know.


text:
Q: Django admin redirect to parent after object delete As of Django 1.7 it is possible to override an Admin Model's response_delete method to force it to redirect to a custom URL after deletion.
class MyAdmin(admin.ModelAdmin):

    def response_delete(self, request, obj_display, obj_id):
        return HttpResponseRedirect("my_url")

I need to take this a step further and redirect to the parent of the deleted object, which seems like it should be a fairly common use case.
However due to deletion of the object there is no obj available to get the parent ID from.
The hacky solution I found was to pass the parent ID in the Unicode representation of the child object (obj_display), then parse the string to find it:
obj_display = '1 (Product 123)'

integers = re.findall(r'\d+', obj_display)
product_id = int(integers[1])

product_id = 123

However, this seems like an inelegant solution. For example, if the unicode method of the object changed the redirect could break. Is there a better way?
Edit
by 'parent' and 'child' I mean the deleted ('child') object had a foreign key to another object (its 'parent')

A: If you want to retain the ability to use rest of delete_view, I recommend overwriting both delete_view and response_delete like this:
class MyModelAdmin(admin.ModelAdmin):
    deleted_fk = None

    def delete_view(self, request, object_id, extra_context=None):
        self.deleted_fk = MyModel.objects.get(id=object_id).fk
        return super(MyModelAdmin, self).delete_view(request, object_id, extra_context)

    def response_delete(self, request, obj_display, obj_id):
        return redirect('url to deleted_fk')

A: You can overwrite this method delete_view (there you can get the parent of the object, before delete it) and instead of doing this return self.response_delete(request, obj_display, obj_id), just do the redirect to the parent admin page.


text:
Q: Error:(40, 0) Could not find method implementation() for arguments [directory 'libs'] I am trying to run my android studio since 2 days and at last it is showing error 400 and my build.gradle file looks like this
buildscript {
repositories {
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:2.1.2'
}
}

allprojects {
repositories {
    jcenter()
}
}
apply plugin: 'com.android.application'

android {
compileSdkVersion 25
buildToolsVersion '25.0.1'
defaultConfig {
    applicationId "com.armenhovhannisyan.backpaper.backpaper"
    minSdkVersion 25
    targetSdkVersion 25
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner                      "android.support.test.runner.AndroidJUnitRunner"
    vectorDrawables.useSupportLibrary = true
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
    }
}
productFlavors {
}
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
androidTestImplementation('com.android.support.test.espresso:espresso-    core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.0.0-beta1'
testImplementation 'junit:junit:4.12'
implementation 'com.android.support:design:25.0.0-beta1'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.android.support:support-annotations:25.3.1'
}

after updating and making some changes to my gradle.properties file it looks like this
# Project-wide Gradle settings.

# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.

# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html

# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1536m

# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details,  visit
 #        http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decou    pled_projects
# org.gradle.parallel=true
distributionUrl=http\://services.gradle.org/distributions/gradle-2.2.1-    all.zip

A: It should be compile and not implementation and for android specific tests it's androidTestCompile. It should look like this
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile'com.android.support:design:25.0.0-beta1'
compile'com.android.support.constraint:constraint-layout:1.0.2'


text:
Q: representations of Higgs bundles I am trying to understand what is a Higgs bundle as defined in this paper by Gukov and Pei.  They say it is a pair $(E, \Phi)$

*

*$E$ is a holomorphic principal $G^\mathbb{C}$ bundle

*$\Phi \in H^0(\Sigma, \mathrm{ad}(E) \otimes K )$
Can anyone explain to me a little about this sheaf $\mathrm{ad}(E) \otimes K$ ?
In light of comments, I've now learned $K$ is the canonical bundle of $\Sigma$. Can we just say $\Phi$ is a "matrix of $E$-valued 1-forms over $\Sigma$ transforming in the adjoint representations of $G$"?


text:
Q: Language C : BOOL FUNCTION with error: expected '=', ',', ';', 'asm' or '__attribute__' before 'isThereSpace' bool isThereSpace (EvernotaStruct *nota){
bool y = false;
for(x = 0; x < NUMBER_STRUCTS; x++){
    if(shmptr[x].time == 0){
        strcpy(shmptr[x].nome_nota, nota.nome_nota);
        strcpy(shmptr[x].text, nota.text);
        strcpy(shmptr[x].autor, nota.autor);
        shmptr[x].time = nota.time;
        printf(">>Nota inserida com sucesso\n");
        y = true;
    }
}
return y;

}

I keep getting that error on console, I am doing everything right I guess :s
Thanks!

A: If this is strict C, there is no 'bool' keyword.