text:
Q: delayed_job - NameError - uninitilized constant I have this custom job which is located in /lib/jobs/MessageNotificationJob.rb
class MessageNotificationJob < Struct.new(:user_id, :message_id)

  def perform

        @user = User.find(user_id)
        @message = Message.find(message_id)
    if !message.reciever_open
        MessagesMailer.message_notification(@user, @message ).deliver

    end

  end
end

I call it from a method in the MessagesController with
Delayed::Job.enqueue(MessageNotificationJob.new(@user.id, @msg.id))

In my application.rb I have
config.autoload_paths += Dir["#{config.root}/lib/**/"]

But I get the error
 NameError - uninitialized constant MessagesController::MessageNotificationJob:

How do I fix this? I've tried several variations, with this as the latest one as a solution to a similar question. I am missing something?

A: I haven't used the latest DelayedJob, but it looks an awful like the delayed job doesn't have the MessageNotificationJob class loaded when it runs.  Try the following:
# file: config/initializers/custom.rb
require 'message_notification_job'

See also this wiki entry -- I think newer versions of DJ improved the error message (rather than silently failing), but the underlying cause is the same.


text:
Q: ASP.NET Core 3 API routing So I've created an API project using .NET Core 3 and inside the project I've created a Controller like so:
[Route("api/account")]
[ApiController]
public class AccountController : ControllerBase
{
   public IActionResult Hello()
   {
      return Ok("Hello");
   }
}

In my Startup.cs I have:
public class Startup
{
   public IConfiguration Configuration { get; }

   public Startup(IConfiguration configuration)
   {
      Configuration = configuration;
   }

   public void ConfigureServices(IServiceCollection services)
   {
      services.AddControllers();
   }

   public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
   {
      app.UseRouting();
      app.UseEndpoints(endpoints =>
      {
         endpoints.MapControllers();
      });
    }
}

From what I understand, the line services.AddControllers(); picks up every controller in my api project. I remember in asp.net to add controllers you would have to call this line:
services.AddTransient<AccountController>();
You would have to namely add each controller, is there no way to do this in .NET Core 3?

A: If you want that certain endpoints should not be hit, MVC provide provision to use attribute [NonAction]:
[NonAction]
public IActionResult Index()

The end points for which the attribute is used, would not be hit in the API call.

A: If you don't want to expose an action method(end point) to client, you can make the method as "private" or as Imran suggested, you can decorate the method with "[NonAction]" attribute.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Пропорциональное масштабирование окна Здравствуйте. Собственно сабж.
Как вариант реализации:
private void Window_SizeChanged_1(object sender, SizeChangedEventArgs e)
{
     this.Height = this.Width;
}

Но! При масштабировании окно мигает. Возможно (даже скорее всего) есть какое-то свойтво (флаг пропорционального ресайза) для реализации данной задачи - подскажите, пожалуйста.
P.S. походы по msdn не помогли... =(
A: Давайте реализуем сохранение aspect ratio в виде attached behavior, чтобы не вмешиваться в код окна, а просто навесить его «со стороны».
Код окна при этом будет выглядеть примерно так:
<Window x:Class="WindowAspectRatio.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
        xmlns:local="clr-namespace:WindowAspectRatio"
        Title="MainWindow" Height="350" Width="525">
    <i:Interaction.Behaviors>
        <!-- параметр AspectRatio можно и не указывать -->
        <local:WindowAspectRatioBehavior AspectRatio="3"/>
    </i:Interaction.Behaviors>
    <Grid Background="Azure"/>
</Window>

(для поддержки behaviours нужно подключить сборку System.Windows.Interactivity).
Реализацию поведения (behaviour) отделим от логики. (Логику можно повторно использовать где-то ещё.)
Итак, вот WindowAspectRatioBehavior:
class WindowAspectRatioBehavior : Behavior<Window> // только для целого окна
{
    protected override void OnAttached()
    {
        base.OnAttached();
        // пробуем навеситься сразу...
        var hwnd = TryGetHwndSource(AssociatedObject);
        if (hwnd != null)
            keeper = new AspectRatioKeeper(hwnd, double.IsNaN(AspectRatio) ?
                        default(double?) : AspectRatio);
        else
            AssociatedObject.SourceInitialized += OnSourceInitialized;
        // если у окна ещё нету HWND, подождём, пока появится
    }

    void OnSourceInitialized(object sender, EventArgs e)
    {
        // опять пробуем навеситься
        var hwnd = TryGetHwndSource(AssociatedObject);
        if (hwnd != null)
            keeper = new AspectRatioKeeper(hwnd, double.IsNaN(AspectRatio) ?
                        default(double?) : AspectRatio);
        AssociatedObject.SourceInitialized -= OnSourceInitialized;
    }

    static HwndSource TryGetHwndSource(Window w)
    {
        return (HwndSource)HwndSource.FromVisual(w);
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();
        AssociatedObject.SourceInitialized -= OnSourceInitialized;
        if (keeper != null)
            keeper.Dispose();
        keeper = null;
    }

    public double AspectRatio
    {
        get { return (double)GetValue(AspectRatioProperty); }
        set { SetValue(AspectRatioProperty, value); }
    }

    // обыкновенное dependency property. при изменении значения вызываем
    // функцию OnAspectChanged. По умолчанию NaN, что означает
    // пользоваться aspect ratio, как у окна на момент навешивания
    public static readonly DependencyProperty AspectRatioProperty =
        DependencyProperty.Register(
            "AspectRatio", typeof(double), typeof(WindowAspectRatioBehavior),
            new PropertyMetadata(double.NaN, (o, args) =>
                ((WindowAspectRatioBehavior)o).OnAspectChanged()));

    void OnAspectChanged()
    {
        var ratio = AspectRatio;
        // если мы уже поддерживаем размер, нам нужно его переустановить
        if (keeper != null && !double.IsNaN(ratio))
            keeper.SetAspectRatio(ratio);
    }

    AspectRatioKeeper keeper;
}

Вся логика пересчёта лежит в AspectRatioKeeper'е. Здесь нам придётся спуститься на нижний уровень, к оконной процедуре, и серьёзно поиспользовать P/Invoke.
class AspectRatioKeeper : IDisposable
{
    // хэндл окна, за которым мы следим
    HwndSource hwnd;

    // если forceRatio == null, мы запоминаем начальное состояние и поддерживаем его
    public AspectRatioKeeper(HwndSource hwnd, double? forceRatio)
    {
        this.hwnd = hwnd;
        RECT rect;
        GetWindowRect(hwnd.Handle, out rect);
        _aspectRatio = forceRatio ?? ((double)rect.Height / rect.Width);
        if (forceRatio.HasValue)
            EnsureAspectRatio(rect.Width, rect.Height);
        hwnd.AddHook(DragHook);
    }

    public void SetAspectRatio(double ratio)
    {
        _aspectRatio = ratio;
        RECT rect;
        GetWindowRect(hwnd.Handle, out rect);
        EnsureAspectRatio(rect.Width, rect.Height);
    }

    void EnsureAspectRatio(int w, int h)
    {
        EnsureAspectRatioValue(ref w, ref h, true);
        SetWindowPos(hwnd.Handle, IntPtr.Zero, -1, -1, w, h,
                     SWP.NOACTIVATE | SWP.NOMOVE | SWP.NOSENDCHANGING);
    }

    public void Dispose()
    {
        hwnd.RemoveHook(DragHook);
    }

    // это наш хук, следим за изменениями размеров окна
    IntPtr DragHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    {
        switch ((WM)msg)
        {
        case WM.WINDOWPOSCHANGING:
            {
                // новый размер и позиция окна
                WINDOWPOS pos =
                    (WINDOWPOS)Marshal.PtrToStructure(lParam, typeof(WINDOWPOS));

                if ((pos.flags & (int)SWP.NOMOVE) != 0)
                    return IntPtr.Zero;

                // Здесь была проверка, является ли окно с данным хэндлом
                // действительно WPF-окном. Но она по идее не нужна.

                // если мы ещё не знаем, меняем мы высоту или ширину, определим это
                if (!_adjustingHeight.HasValue)
                {
                    Point p = GetMousePosition();

                    // считаем расстояния позиции мыши от краёв окна
                    double mouseFromLeft = Math.Abs(p.X - pos.x),
                           mouseFromRight = Math.Abs(p.X - pos.x - pos.cx),
                           mouseFromTop = Math.Abs(p.Y - pos.y),
                           mouseFromBottom = Math.Abs(p.Y - pos.y - pos.cy);

                    double diffWidth = Math.Min(mouseFromLeft, mouseFromRight),
                           diffHeight = Math.Min(mouseFromTop, mouseFromBottom);

                    // похоже, мы меняем высоту. или ширину. запомним это.
                    _adjustingHeight = diffHeight < diffWidth;
                }

                EnsureAspectRatioValue(ref pos.cx, ref pos.cy, _adjustingHeight.Value);

                Marshal.StructureToPtr(pos, lParam, true);
                handled = true;
            }
            break;
        case WM.EXITSIZEMOVE:
            // мы закончили перетаскивание, в следующий раз направление придётся
            // определять заново
            _adjustingHeight = null;
            break;
        }

        return IntPtr.Zero;
    }

    // просто пересчёт численного значения высоты и ширины, с учётом их отношения
    // и максимального/минимального системного значений
    void EnsureAspectRatioValue(ref int w, ref int h, bool tryKeepWidth)
    {
        if (tryKeepWidth)
            w = (int)(h / _aspectRatio); // adjusting height to width change
        else
            h = (int)(w * _aspectRatio); // adjusting width to heigth change

        if (w > maxw)
        {
            w = (int)maxw;
            h = (int)(w * _aspectRatio);
        }
        else if (w < minw)
        {
            w = (int)minw;
            h = (int)(w * _aspectRatio);
        }

        if (h > maxh)
        {
            h = (int)maxh;
            w = (int)(h / _aspectRatio);
        }
        else if (h < minh)
        {
            h = (int)minh;
            w = (int)(h / _aspectRatio);
        }
    }

    double _aspectRatio;
    bool? _adjustingHeight = null;
    double minh = SystemParameters.MinimumWindowHeight,
           minw = SystemParameters.MinimumWindowWidth,
           maxh = SystemParameters.MaximumWindowTrackHeight,
           maxw = SystemParameters.MaximumWindowTrackWidth;

    /////////////////////////////////////////////////////////
    // дальше будет просто импорт функция WinAPI и определение структур данных
    // большая часть взята с сайта pinvoke.net

    enum WM
    {
        WINDOWPOSCHANGING = 0x0046,
        EXITSIZEMOVE = 0x0232,
    }

    [Flags]
    enum SWP : uint
    {
        ASYNCWINDOWPOS = 0x4000,
        DEFERERASE = 0x2000,
        DRAWFRAME = 0x0020,
        FRAMECHANGED = 0x0020,
        HIDEWINDOW = 0x0080,
        NOACTIVATE = 0x0010,
        NOCOPYBITS = 0x0100,
        NOMOVE = 0x0002,
        NOOWNERZORDER = 0x0200,
        NOREDRAW = 0x0008,
        NOREPOSITION = 0x0200,
        NOSENDCHANGING = 0x0400,
        NOSIZE = 0x0001,
        NOZORDER = 0x0004,
        SHOWWINDOW = 0x0040
    }

    [StructLayout(LayoutKind.Sequential)]
    internal struct WINDOWPOS
    {
        public IntPtr hwnd;
        public IntPtr hwndInsertAfter;
        public int x;
        public int y;
        public int cx;
        public int cy;
        public int flags;
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct RECT
    {
        public int Left, Top, Right, Bottom;
        public int Height { get { return Bottom - Top; } }
        public int Width { get { return Right - Left; } }
    }

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool GetCursorPos(ref Win32Point pt);

    [DllImport("user32.dll", SetLastError = true)]
    static extern bool GetWindowRect(IntPtr hwnd, out RECT rect);

    [DllImport("user32.dll", SetLastError = true)]
    static extern bool SetWindowPos(
        IntPtr hWnd, IntPtr hWndInsertAfter,
        int X, int Y, int cx, int cy, SWP uFlags);

    [StructLayout(LayoutKind.Sequential)]
    internal struct Win32Point
    {
        public Int32 X;
        public Int32 Y;
    };

    static Point GetMousePosition() // mouse position relative to screen
    {
        Win32Point w32Mouse = new Win32Point();
        GetCursorPos(ref w32Mouse);
        return new Point(w32Mouse.X, w32Mouse.Y);
    }
}

Код во многом основан на этом ответе.


text:
Q: Understanding Modular Multiplication I'm reading a book on Cryptography and in the book it explains:

A modular multiplication is quite natural to define over such a set of
numbers. Let's take the following multiplication, for example:
3 x 2 = 6
With what you learned above, you know that 6 is congruent to 1 modulo
5, and thus the equation can be rewritten as
3 x 2 = 1 mod 5
Quite straightforward isn't it? Note that the previous equation tells
us that 3 is the inverse of 2, and vice versa. So we can also write,
for example:
3^-1 = 2 mod 5

I can understand that 3 x 2 = 6.
And 6 mod 5 = 1 or 6  % 5 == 1.  Therefore 3x2 = 1 mod 5
However what I don't understand is how it suddenly become proof that:
3^-1 = 2 mod 5
I understand that 3^-1 = 1/3....
so if
3^-1 = 2 mod 5
then
1/3 = 2 mod 5
no?  I'm getting confused....
What foundational knowledge do I need to understand and how to connect the dots????
Thank you.

A: Hint: holds $(5k+\color{red}{2})(5l+\color{red}{3})=5n+\color{red}{1}$.


text:
Q: In index, why check if item already has an index? (Qt) Short version
When reimplementing index for a tree model, why would we first check to see if the relevant item already has an index (with hasIndex), returning the root index if it does not? Isn't the whole point to create an index for that item?
Detailed version
Consider the reimplemention of index in PySide's simpletreemodel example (full code is below). My understanding is that the index method is meant to take in the row, column, and parent index of a particular item, and return an index for that item using createIndex. But the index method opens with the following lines:
    if not self.hasIndex(row, column, parent):
        return QtCore.QModelIndex()

I am a bit confused here. If the item does not already have a valid index, why return the root index? How does this method ever create an index in the first place? When I cut out the above lines, I see no deleterious effects in the application.
Since I am trying to simplify the PySide example as much as possible, I want to just remove those two lines. Will this have bad unforeseen consequences?
Relevant code
def index(self, row, column, parent):
    if not self.hasIndex(row, column, parent):
        return QtCore.QModelIndex()
    if not parent.isValid():
        parentItem = self.rootItem
    else:
        parentItem = parent.internalPointer()
    childItem = parentItem.child(row)
    if childItem:
        return self.createIndex(row, column, childItem)
    else:
        return QtCore.QModelIndex()

A: The hasIndex function just performs bounds-checking. If the row or column arguments are less than zero, or outside of the range of the row or column count of the parent index, it will return False; otherwise, it will return True.
Also, in the example implementation, the index method does not return the root-index when hasIndex returns false: it returns an invalid index (the no-argument constructor of QModelIndex always creates an invalid index). The model should always return an invalid index when there is no corresponding item available in the data that is being modelled.


text:
Q: Android development -Unknown Host exception problem I'm developing an Android app that gets a JSON_encoded result from a php middleware script that connects to a MySQL database.  I have given the application Internet permissions.
The problem I'm having is that the program gives an UnknownHostException error the first time it is run.  I have the program on a timer, and subsequent calls to the timer handler function do not return the UnknownHostException error.  Do you have any idea why this would occur?  I have tested the domain and made sure that it connects correctly through a web browser.
Here's a snippet from the code:
    public final void timerAlert(){

    final Handler handler = new Handler();
    final Runnable r = new Runnable()
    {
        public void run() {

            Timer_Method();
            handler.postDelayed(this,1000);
        }

    };
    handler.postDelayed(r, 1000);
}

public void Timer_Method()
{

    //See if this buzzer is being signaled.
    String result = null;
    InputStream is = null;
    StringBuilder sb=null;
    //http post
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("BuzzerID",BuzzerID.toString()));
   Toast.makeText(getBaseContext(), "BuzzerID="+BuzzerID.toString() ,Toast.LENGTH_LONG).show();
    try{
         HttpClient httpclient = new DefaultHttpClient();
         HttpPost httppost = new HttpPost("http://domain/getBuzzStatus.php?BuzzerID="+BuzzerID.toString());
         httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
         HttpResponse response = httpclient.execute(httppost);
         HttpEntity entity = response.getEntity();
         is = entity.getContent();

    }catch(Exception e){
             Log.e("log_tag", "Error in http connection"+e.toString());
           Toast.makeText(getBaseContext(), "Hm, problem here="+e.toString() ,Toast.LENGTH_LONG).show();
         }

Note that domain has something else there in the actual code and that this is just a snippet but is where the first issue occurs.  Also note that I am mixing get and post, something I'd rather not do, but for some reason passing the nameValuePair to the php script doesn't send anything to $_REQUEST.
A snippet from the very simple PHP script:
$sql_string="SELECT Signal FROM BuzzCustomer WHERE idBuzzCustomer=" . $_GET['BuzzerID'];

$sql = mysql_query($sql_string);

while($row=mysql_fetch_assoc($sql))
    $output[]=$row;
print(json_encode($output));

mysql_close();

I switched to $_GET here because I could not get $_REQUEST to work.  Any help would be appreciated.  Thanks in advance!

A: May be their will be no Internet connection in the simulator......Check a url in browser
Instead of
HttpResponse response = httpclient.execute(httppost);
         HttpEntity entity = response.getEntity();
         is = entity.getContent();

Use
ResponseHandler<String>  response = new BasicResponseHandler();
String result = httpclient.execute(httppost,response);

Also put Internet permission in the Manifest

A: Just a guess, but maybe the DNS request takes too long and your HttpClient gives up, but the request is finished and cached so the next time it does not fail?
This With Apache HttpClient, why isn't my connection timeout working? seems to be a question about how to set the timeout for HttpClient.


text:
Q: Misuse of aggregate in SQLite This error occurs in this SQLite query:
select f.rid, c.title, sum(some_expression) as ratio
from doesntmatter
where c.active = 1 or (ratio = 1.0 and c.active = 0
      and c.deactivated in (1, 2, 3, 4, 5)
group by f.rid

This question solves it with having clause:
select f.rid, c.title, sum(some_expression) as ratio
from doesntmatter
where c.active = 1 or (c.active = 0
      and c.deactivated in (1, 2, 3, 4, 5)
group by f.rid
having ratio = 1.0

But in my case this changes the semantics of the expression. Do you know how to achieve the expression that is in the original where clause?

A: Basically, you can't reference an aliased column in a where clause. Take a look at this question to see how to workaround that.
Aditionally, you should add to the group by all non-aggregated columns present in the select statement, in this case, c.id and c.title.
It is difficult to rewrite that query for you because the logic is a bit difficult to understand (because of the wrong group by).
Edit:
After a second thought, you might just need to correct the group by.
select c.id, c.title, sum(some_expression) as ratio
from doesntmatter
where c.active = 1 or (c.active = 0 and c.deactivated in (1, 2, 3, 4, 5))
group by c.id, c.title
having ratio = 1.0

Or maybe:
select f.rid, sum(some_expression) as ratio
from doesntmatter
where c.active = 1 or (c.active = 0 and c.deactivated in (1, 2, 3, 4, 5))
group by f.rid
having ratio = 1.0

I can't help you with the previous part because I don't know the fields nor the data of your tables nor how to interpret them. But selecting fields not present in the group by is a bad idea. Anyway, remember you can always join back to the original tables and get the info you are looking for, not just the fields displayed in the select.


text:
Q: Delete Perspective manually I want to delete perspectives which I have created. But here I don't want to use Eclipse's own page. I want to create my own page and display list of Perspectives and give option to delete it or make it default. I don't want to use default Eclipse page because I don't need "Fast View" and other options for perspectives. That's why I decided to create my own page list only what I need. But I don't know how to get list of perspectives and methods to make it default and delete.
This the page which I am displaying right now in my application:

A: You use the IPerspectiveRegistry to manipulate the perspective registry:
IPerspectiveRegistry perspectiveRegistry = PlatformUI.getWorkbench().getPerspectiveRegistry();

You can get the list of perspectives from the registry with:
IPerspectiveDescriptor [] perspectives = perspectiveRegistry.getPerspectives();

You can delete a perspective by calling the registry method
public void deletePerspective(IPerspectiveDescriptor persp)

but note that the JavaDoc says:

Deletes a perspective. Has no effect if the perspective is defined in
  an extension.


text:
Q: hiding the running program window
*

*I have .mp3 converted as .exe to
make it as self playing its done.

*But a window is appearing while
music is playing.

*I want to hide
that window while music is
playing [only using .bat file code]

*So please help me for the .bat
file code

A: There is no way to hide a window in pure batch, your best alternative is to relaunch yourself (the .bat) with the START command and the /MIN switch, this would run it minimized and not hidden (You would use a special parameter and check %1 to see if you need to relaunch or not)


text:
Q: Plot multiple series where each series have a distinct line type and specific part of each series colored differently using ggplot2 I want to plot multiple series where each series have a distinct line type and specific part of each series colored differently using ggplot2.
I prepared the data and plot it as follows:
# Load melted data frame
df = read.table(text="time,group,variable,value
1,train,preds,-1.01327781066807
2,train,preds,-1.06923407042272
3,train,preds,-1.0738165129006
4,train,preds,-1.0570173408663
5,train,preds,-0.849528539296128
6,train,preds,-1.00956150966228
7,train,preds,-1.05129344633106
8,train,preds,-1.01137384052835
9,train,preds,-0.986500386274102
10,train,preds,-0.782545791298946
11,train,preds,-0.492011449844967
12,train,preds,0.0752350668715425
13,train,preds,0.718851922060212
14,train,preds,0.907488713099219
15,train,preds,0.809418859320128
16,train,preds,0.799428598786513
17,train,preds,0.89455950317809
18,train,preds,0.891727059592248
19,train,preds,0.839506291414727
20,train,preds,0.891986330803872
21,train,preds,0.868653513783531
22,train,preds,0.867573512960701
23,train,preds,0.790999769131768
24,test,preds,0.836612851268108
25,test,preds,0.835266880809444
26,test,preds,0.825396293221058
27,test,preds,0.82669719817616
1,train,actual,-1.06741896705375
2,train,actual,-1.07208489151112
3,train,actual,-1.04309035399799
4,train,actual,-1.11384867929676
5,train,actual,-1.10435803969419
6,train,actual,-1.06534456421351
7,train,actual,-1.04953633499216
8,train,actual,-1.05459775190554
9,train,actual,-0.981186588772681
10,train,actual,-0.96224883216766
11,train,actual,-0.892023497056106
12,train,actual,0.830642326040778
13,train,actual,0.834595424714826
14,train,actual,0.881344777367528
15,train,actual,0.915772459185225
16,train,actual,0.929638947563377
17,train,actual,0.994907176661985
18,train,actual,0.99423350946309
19,train,actual,0.989942263051002
20,train,actual,0.967976146034507
21,train,actual,0.787447328638445
22,train,actual,0.586847009899609
23,train,actual,0.84574152360878
24,test,actual,1.01305250589053
25,test,actual,1.06157202086132
26,test,actual,1.01496086957322
27,test,actual,0.999883908716498", sep=",", stringsAsFactors=F, header=T)

# plot
ggplot(data=df, aes(x=time, y=value)) + geom_line(aes(color=group, linetype=variable))

The result is:

There is a break between train and test part of the series. How can I get them connected? I tried geom_path but couldn't do it.

A: You need to create another data point to connect the line. For example
library(ggplot2)
library(dplyr)

# I get the first record of test data for each variable and assign
# the group variable to train
additional_line <- df %>%
  filter(group == "test") %>%
  group_by(variable) %>%
  filter(time == min(time)) %>%
  ungroup() %>%
  mutate(group = "train")

# Then binded them into the original dataset
df_revised <- bind_rows(df, additional_line)

# Now plot the new data with train line connected to the test line by
# additional train line.
ggplot(data=df_revised, aes(x=time, y=value)) +
  geom_line(aes(color=group, linetype=variable))

# You can draw the original data without additional records if not
# using linetype
ggplot(data=df, aes(x=time, y=value)) +
  geom_line(aes(group = variable, color=group))

# When using linetype in plot this config will cause errors
ggplot(data=df, aes(x=time, y=value)) +
  geom_line(aes(group = variable, color=group, linetype = variable))
#> Error: geom_path: If you are using dotted or dashed lines, colour,
#> size and linetype must be constant over the line


text:
Q: Java Food Diary The goal of this project is to create a Food Diary. This diary should contain breakfast, lunch, dinner and Snacks that you consume during the day. The user should be able to enter their food items and save it as a csv file. The user should be able to keep appending to the file.
This is what I have so far but I'm not sure where to close my scanner:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;

public class App {

    public static void main(String[] args) throws FileNotFoundException {

        PrintWriter pw = new PrintWriter(new File("test.csv"));
        StringBuilder sb = new StringBuilder();
        sb.append("Date");
        sb.append(',');
        sb.append("FoodTime");
        sb.append(',');
        sb.append("FoodItem");
        sb.append(',');
        sb.append("Calories");
        sb.append('\n');

        int exit;
        do {
            Scanner sc = new Scanner(System.in);
            System.out.println("Date : ");
            String Date = sc.next();
            System.out.println("Meal Time: ");
            String FoodTime = sc.next();
            System.out.println("Food Item : ");
            String FoodItem = sc.next();
            System.out.println("Calories : ");
            String Calories = sc.next();
            sb.append(Date);
            sb.append(',');
            sb.append(FoodTime);
            sb.append(',');
            sb.append(FoodItem);
            sb.append(',');
            sb.append(Calories);
            sb.append('\n');
            pw.write(sb.toString());
            System.out.println("Please enter 0 to exit, 1 to continue : ");
            exit = sc.nextInt();
        } while (exit != 0);

        System.out.println("done!");
    }

}

A: You should create the Scanner Object Before the do loop because at every iteration a new object is being created and you should close the Scanner Object after the end of do loop.

A: You are creating a new scanner on every interaction inside your do while.
Try to create a new scanner before the loop and close it after.
Scanner sc = new Scanner(System.in);
do {
        System.out.println("Date : ");
        String Date = sc.next();
        System.out.println("Meal Time: ");
        String FoodTime = sc.next();
        System.out.println("Food Item : ");
        String FoodItem = sc.next();
        System.out.println("Calories : ");
        String Calories = sc.next();
        sb.append(Date);
        sb.append(',');
        sb.append(FoodTime);
        sb.append(',');
        sb.append(FoodItem);
        sb.append(',');
        sb.append(Calories);
        sb.append('\n');
        pw.write(sb.toString());
        System.out.println("Please enter 0 to exit, 1 to continue : ");
        exit = sc.nextInt();
    } while (exit != 0);
sc.close();

A:
I'm not sure where to close my scanner:

To answer your question, you need to close it right before the last line:
pw.close();
sc.close();
System.out.println("done!");

You need to also declare the Scanner outside of the do loop:
int exit;
Scanner sc = new Scanner(System.in);
do {


text:
Q: Проблема с адаптивом слайдера Всем привет , я совсем новичок в js, и вот какая проблема у меня возникла:
При изменении ширины экрана слайды начинают работать неккоректно , это происходит из-за того, что переменная, которой присвоено значение ширины слайдера остается неизменной при уменьшении / увелечении окна браузера, она получает корректное значение только при перезагрузке. Я пробовал отслеживать ширину экрана путем запуска requestAnimationFrame , но присвоив значение (которое обновлялось при уменьшении / увелечении) переменной, она получала значение при старте функции, а точнее Null, затем я начал искать что либо о динамических переменных, но решил что не буду изобретать велосипед и лучше спрошу.

A: Для того, чтобы отслеживать ширину окна браузера можете использовать следующий код:
document.addEventListener('resize' , () => {

  //тут пишете код, который должен регулировать ширину ваших слайдов
})


text:
Q: How is this not constructive? It is duplicate, but very constructive! This question: iPhone development on Windows was closed by a mod for "non constructiveness"
But a question (that looks like a duplicate) is still all open ( How can I develop for iPhone using a Windows development machine? ).
If How can I develop for iPhone using a Windows development machine? is constructive, then iPhone development on Windows is constructive, but a duplicate.
Why was it closed like it was, and should it be changed?

A: It's more because the other question was just as non-constructive as the one you're suggesting is a duplicate of it.
I've closed that question as "Not Constructive" as well.  Both questions have conflicting information (some saying yes, some saying no), as well as being lists of things.
So to answer your question, the other post shouldn't have been open as "Not Constructive" but that's been rectified now.


text:
Q: Android: How publish H264 raw data to live stream server via RTMP I would like live stream video from Drone to Wowza Streaming Engine Server. I got H264 raw data from this callback, And I'm looking a library which supports live stream from H264 raw data or any document about live stream from H264 data.
Thank for any support.

A: DJI released a new version of the SDK 4.0, where it comes with an example of how to decode that raw data into YUV image using FFMpeg.
Folowing that example, you can modify this method
 private void screenShot(byte[] buf, String shotDir) {

      YuvImage yuvImage = new YuvImage(buf,
                 ImageFormat.NV21,
                 DJIVideoStreamDecoder.getInstance().width,
                 DJIVideoStreamDecoder.getInstance().height,
                 null);

 //you can therefore stream it to your Wowza Server

 }

I don't know what are your objectives. However, I'd sugest you to encode that YUV frame to Jpeg, and transmit it throught UDP, like a Peer to Peer application.
Here is a simple way of how to stream live video using UDP. It uses C++, but is simple to understand


text:
Q: Is it possible to create grouping of input cells in IPython Notebook? When I do data analysis on IPython Notebook, I often feel the need to move up or down several adjacent input cells, for better flow of the analysis story.
I'd expected that once I'd create a heading, all cells under that heading would move together if I move the heading. But this is not the case.
Any way I can do this?
Edit: To clarify, I can of course move cells individually, and the keyboard shortcuts are handy; but what I'm looking for is a way to group cells so that I can move (or even delete) them all together.

A: I use a little-known extension, which does exactly what you want (i.e. "once I'd create a heading, all cells under that heading would move together if I move the heading"). It is part of the Calico suite, but can be installed separately.
More specifically, you need to install a Calico Notebook Extension named Document Tools. From the description:

The Calico Document Tools extensions adds section moving, heading numbering, table of contents, and bibliography support.
  Demonstration of use: https://www.youtube.com/watch?v=YbM8rrj-Bms

I don't know whether the instructions of installation given on the wiki page are updated for IPython 3.0 (february 2015), but the source-code on BitBucket actually is.
I cannot install IPython 3.0 for the moment, but I gladly use this extension with IPython 2.x since last summer. It's great, perhaps less versatile than the asif.m's suggestion Collective Cut-Copy-Paste for IPython Notebooks (which, by the way, has not been updated for IPython 3.0), but IMHO faster and more logical.

A: For anyone out there who needs the grouping feature: yes, there's a great extension here: https://github.com/ivanov/nb-cccp
The days of moving one cell at a time is over. Apparently it will be built into the next IPython version.

A: This is not currently possible. There are two relevant issues open on Github:

*

*Group multiple cells together as one unit using shift button #5180

*Allow sections to be collapsed and expanded in the notebook #805

A:
Latest version of Ipython/Jupyter notebook allows selection of multiple cells using shift key which can be useful for batch operations such as copy, paste, delete, etc.


text:
Q: Firebase Have to upload image twice to get it to display I am building a chat app i have a list view setup that loads messages and i have a image picker setup to upload images to firebase and display them in the list view. When i go to upload an image i select the image from a image picker, it gets sucesfuly uploaded to firestore but not displayed and no message object created for it this is the error
2019-02-06 16:32:19.032 3810-5272/com.example.android.debateapp E/StorageException: {  "error": {    "code": 404,    "message": "Not Found.  Could not get object"  }}
java.io.IOException: {  "error": {    "code": 404,    "message": "Not Found.  Could not get object"  }}
    at com.google.firebase.storage.obfuscated.zzj.zza(com.google.firebase:firebase-storage@@16.0.2:455)
    at com.google.firebase.storage.obfuscated.zzj.zza(com.google.firebase:firebase-storage@@16.0.2:3435)
    at com.google.firebase.storage.obfuscated.zzc.zza(com.google.firebase:firebase-storage@@16.0.2:65)
    at com.google.firebase.storage.obfuscated.zzc.zza(com.google.firebase:firebase-storage@@16.0.2:57)
    at com.google.firebase.storage.zzc.run(com.google.firebase:firebase-storage@@16.0.2:68)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
    at java.lang.Thread.run(Thread.java:761)

but if i go an upload the same image right after the image will sucesfuly upload and display
I have it setup so that the image will be uploaded to firebase storage and then be displayed in the realtime database under the messages object as the image url Database
code:
    @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == GALLERY_PICK && resultCode == RESULT_OK) {

        Uri selectedImageUri = data.getData();

        StorageReference photoRef = mChatPhotosStorageReference.child(selectedImageUri.getLastPathSegment());

        photoRef.putFile(selectedImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

            }
        });
        photoRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
            @Override
            public void onSuccess(Uri uri) {

                String downloadUrl = uri.toString();Log.d("tag", downloadUrl);
                FriendlyMessage friendlyMessage = new FriendlyMessage(null, mUsername, downloadUrl);
                mMessagedatabaseReference.push().setValue(friendlyMessage);
            }
        });

full code

A: You're calling getDownloadUrl() before the file is finished uploading.
putFile() is asynchronous, meaning it returns immediately, and your callback is invoked some time later, whenever the upload is done.  Your code is assuming that the upload either completes immediately, or blocks the current thread until the upload is done.  This isn't going to work.
What you should do instead is call getDownloadUrl() inside the callback, when you know the upload is complete.
    photoRef.putFile(selectedImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
            photoRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                @Override
                public void onSuccess(Uri uri) {
                    String downloadUrl = uri.toString();
                    Log.d("tag", downloadUrl);
                    FriendlyMessage friendlyMessage = new FriendlyMessage(null, mUsername, downloadUrl);
            mMessagedatabaseReference.push().setValue(friendlyMessage);
                }
            });
        }
    });


text:
Q: Change tab by click on a button angular material i am getting error ERROR "Cannot find name 'maxNumberOfTabs' "
** My problem** i tried to navigate angular tabs with next and previous button in which i am getting error Cannot find name 'maxNumberOfTabs'
This is ts file
import {DomSanitizer} from '@angular/platform-browser';
import {MatIconRegistry} from '@angular/material/icon';
import { Router, ActivatedRoute } from '@angular/router';
import { Question, questionService } from 'src/app/services/question.service';
import { MatTabChangeEvent } from '@angular/material/tabs';

@Component({
  selector: 'app-logicaltest',
  templateUrl: './logicaltest.component.html',
  styleUrls: ['./logicaltest.component.scss']
})
export class LogicaltestComponent implements OnInit {

  constructor( tabChangeEvent: MatTabChangeEvent) {

  }
  ngOnInit() {
  //   setTimeout(() => {
  //     this.router.navigate(['']);
  // }, 120000);

  }
  selectedIndex: number = 0;
  nextStep() {
    if (this.selectedIndex != maxNumberOfTabs) {
     // console.log('in html page',row.Id);

      this.selectedIndex = this.selectedIndex + 1;
  }
    console.log(this.selectedIndex);
  }

  previousStep() {

    if (this.selectedIndex != 0) {
      this.selectedIndex = this.selectedIndex - 1;
    }
    console.log(this.selectedIndex);
  }
 }

this is html code
    <mat-icon>arrow_back_ios</mat-icon>
  </button>
  <button (click)="nextStep()">
      <mat-icon>arrow_forward_ios</mat-icon>
  </button>
    <mat-tab-group [selectedIndex]="selectedIndex">
      <mat-tab *ngFor="let number of [0,1,2,3,4];let i=index; ">
        <ng-template mat-tab-label>
        </ng-template>
        content{{number}}
      </mat-tab>


text:
Q: GraphQL mutation on id field I have a GraphQL schema called Car Manufacturer which has two fields, id and name. What I am trying to accomplish via GraphiQL is to insert several data into the schema but I need to mutate both the mentioned fields.
Is there a way to insert a desired value on the id field?

A: Why you want to modify the id? For using them as indexes? Like id: 1, id: 2 an so on? If is that so, you should have something like globalIdField from graphql-relay in my opinion. Not mutate these ids yourself.
For example:
import { GraphQLObjectType, GraphQLFloat } from 'graphql';
import { globalIdField } from 'graphql-relay';

export default new GraphQLObjectType({
  name: 'Car anufacturer',
  description: 'desc',
  fields: () => ({
    id: globalIdField('CarManufacturer'),
    title: {
      type: GraphQLString,
      resolve: async obj => obj.title,
    },
  }),
});

This way you will have unique ids and you can turn these ids on an ObjectIdfor use with MongoDB for example.
If you want to change this values for whatever other reason, you have to create Mutations just like @arian said
I hope that I helped you someway :)


text:
Q: I'm trying to get info from sheet 2 onto sheet 1 I've got a complexed workbook that im trying to take info from one of the sheets and put into a new sheet by using the IF function or VLOOKUP but i cant seem to get it to work.
Example:
Sheet 1:
I have empty cells from B14:B47 and empty cells in C14:C47
Sheet 2:
I have Names in cells from C13:C84 all in alphabetical order, (none are the same).
Empty cells in H13:H84
The sheet is to show how many hours people will be working in that area
I want to input an amount of hours into a cell on sheet 2 inbetween the H13:H84 and for sheet 1 to pick up the amount of hours and place it into C14:C47, at he top as a list (there wont be a full list) and for the matching names on their rows in sheet 2 to be picked up and placed into B14:B47, aswell at the top of the list.
So to clarify:
Joe Bloggs is in C14 on sheet 2
he has worked 8 hours and i will input this into the cell next to his name H14,
I want sheet 1 to pick up that his name has a number next to it and place his name in a B14 on sheet 1 and his hours in C14 on sheet 1 and anybody else in this bracket and range.
I hope this makes sense as ive been at this hours. :-)

A: You want to copy Sheet2(C:C) to Sheet1(B:B) and Sheet2(H:H) to Sheet1(C:C) ?
It´s not clear, as @sr28 said, if you want to ignore empty cells...
If you want just to copy, use:
Sub copyData()

Dim Count As Integer

Count = Worksheets("Sheet2").Range("C2").End(xlDown).Row  'find last row from column C on sheet2
ActiveWorkbook.Sheets("Sheet2").Activate

For i = 1 To Count
    Sheet1.Cells(i, 2) = Sheet2.Cells(i, 3)
    Sheet1.Cells(i, 3) = Sheet2.Cells(i, 8)
Next i

End Sub

If you want to ignore blank cells on Sheet2.H, you can use:
Sub copyDataNoEmpty()

Dim Count As Integer
Dim j As Integer

Count = Worksheets("Sheet2").Range("C2").End(xlDown).Row

j = 1
For i = 1 To Count
    If Sheet2.Cells(i, 8) <> Empty Then
        Sheet1.Cells(j, 2) = Sheet2.Cells(i, 3)
        Sheet1.Cells(j, 3) = Sheet2.Cells(i, 8)
        j = j + 1
    End If
Next i

End Sub


text:
Q: Convert a pandas series to Integer, ignoring NaN I have an expression which seems to convert my floats to ints
df_maa_lu.loc[df_maa_lu["APPROVAL_YEAR"].notnull()]["APPROVAL_YEAR"].apply(lambda x: int(x))

returns:

When I try and assign these values back it isn't working:
df_maa_lu.loc[df_maa_lu["APPROVAL_YEAR"].notnull()]["APPROVAL_YEAR"] = df_maa_lu.loc[df_maa_lu["APPROVAL_YEAR"].notnull()]["APPROVAL_YEAR"].apply(lambda x: int(x))

Returns this warning:

C:\ProgramData\Anaconda3\envs\ariel\lib\site-packages\ipykernel_launcher.py:1:
SettingWithCopyWarning:  A value is trying to be set on a copy of a
slice from a DataFrame. Try using .loc[row_indexer,col_indexer] =
value instead
See the caveats in the documentation:
http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
"""Entry point for launching an IPython kernel.

And my original dataframe still has floats in it:

I tried this, but it doesn't like the "NaN" values.
df_maa_lu.loc[:,  "APPROVAL_YEAR"] = df_maa_lu.loc[:,  "LU_APPROVED_DT"].dt.year.apply(lambda x: int(x))

All I want to do is assignment on the non NaN values to int.


text:
Q: Inequality between Dirichlet and Neumann eigenvalue for Sturm Liouville problem Consider the following Sturm Liouville problem on an interval $[a,b]$
$$\frac{\mathrm{d}}{\mathrm{d} x}\left[p(x) \frac{\mathrm{d} y}{\mathrm{d} x}\right]+q(x) y=-\lambda w(x) y$$
for given coefficient function $p(x),q(x),w(x)>0$. Here we can assume they are smooth. One can consider two sets eigenvalues
$$0<\lambda_{1}^D<\lambda_{2}^D<\lambda_{3}^D<\cdots<\lambda_{n}^D<\cdots \rightarrow \infty$$
$$\lambda_{1}^N<\lambda_{2}^N<\lambda_{3}^N<\cdots<\lambda_{n}^N<\cdots \rightarrow \infty$$
where $\lambda_i^D$ are Dirichlet boundary condition and $\lambda_i^N$ are Neumann boundary condition. It is quite easy to show $\lambda_i^N\leq \lambda_i^D$ by the variational characterizations of the eigenvalues. However, it seems that under some condition of $p,q,w$, we will have
$$\lambda_{i+1}^N\leq \lambda_i^D$$
I encounter this when reading some papers, and it says this is well known. Does anyone know a good reference for this type of inequality? Who first found this? Do you have a simple proof?
PS. I googled a little bit and found many works on eigenvalue inequality of this type for Laplacian operator on dimension greater than 1. I am just interested in one dimension and here the operator is more general than Laplacian.


text:
Q: Outlook Web Access - 3 Pane view using browsers other than Internet Explorer Why doesn't Outlook Web Access display the 3 pane view when using browsers like Firefox, Chrome or Safari?
Specifics: When you access Outlook for the web(specifically Outlook 2003) using Internet Explorer you get the 3 pane view that looks pretty similar to the Outlook Desktop version. i.e. Folder/button on the left, the email summary list in the middle and the the email body on the right hand side. When you browse the same site in other browsers like Firefox, Chrome or Safari they show a 2 pane view. i.e. The folder view on the left and then the summary view on the right. You then have to click on each email summary to display the detail. The problem is that its one extra click to get to the email body.
Is there a way to get other browsers to show the 3 panes by tricking them in some way, or is this one of Microsoft's non standard apis that only works in IE or there is just some configuration that we haven't set right?

A: What you are looking at (when you use a non IE browser) is OWA Lite.
OWA Lite misses out on:

*

*Spelling Checker

*Reading Pane

*Notifications and Reminders

*Weekly Calendar Views

*Windows SharePoint Services and Windows File Share Integration

*HTML Message Format

*Right-Click Menu

*Drag and Drop

*Explicit Logon

*Type-down Search

*Resource Mailbox Management

*Color Scheme Appearance

*Voicemail Options

However! You can circumvent this if you install the IE Tab Addon for FireFox:
https://addons.mozilla.org/en-US/firefox/addon/1419
More detailed info from:
http://blog.fpweb.net/outlook-web-access-with-exchange-2007-%E2%80%93-get-the-full-feature-set/

A: Which version of Exchange is it? 2003? 2007?
IE is the only browser I know of that can display OWA "Premium" - which is the full-on interface you're used to.
Other browsers are restricted to the "Lite" view, which is what you're seeing. I believe there may be a FireFox plugin to fix this, but I'm not sure.
Irony being that OWA 2003 didn't used to work in IE7 and 8 (is this still the case?) so FF was your only option!
Just to clarify: This behaviour is normal. There's no configuration you've missed, and yes, it's likely some IE API they're using.


text:
Q: Convert JSON Data into Dictionary I am try to convert this JSON data into Dictionary, but I don't know how the data will be structured in this JSON. I think my code for detect JSON struct thats wrong.
JSON Response
[
    {
        "userId": 1,
        "id": 1,
        "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
        "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
    },
    {
        "userId": 2,
        "id": 2,
        "title": "et ea vero quia laudantium autem",
        "body": "delectus reiciendis molestiae occaecati non minima eveniet qui voluptatibus\naccusamus in eum beatae sit\nvel qui neque voluptates ut commodi qui incidunt\nut animi commodi"
    }
]

Thats my code :
enum postResult {

    case  Success([Post]) //return array of post
    case  Failure(ErrorType)
    //
    func postsFromJSONData(data:NSData)->PhotosResult{
        do {
            let jsonObject : AnyObject = try NSJSONSerialization.JSONObjectWithData(data,options:[])
            guard let jsonDictionary = jsonObject as? [NSObject:AnyObject],
            postsArray = ["userId"] as? [[String:AnyObject]] else {
                return.Failure(InvalidError.InvalidJSONData)
            }

            var finalPosts = [post]()
            return.Success(finalPosts)
        }
        catch let error {
            return.Failure(error)
        }
    }
}

A: Your response is Array not Dictionary, so you need to access object from Array also your userId key contains number as value not Array/Dictionary.
let jsonObject = tryNSJSONSerialization.JSONObjectWithData(data,options:[]) as! [[String: AnyObject]]
if jsonObject.count > 0 {
    if let userId = jsonObject[0]["userId"] as? Int {
         print(userId)
    }
}


text:
Q: How and where are instructions cached? If i were to run a binary executable program, do all of the instructions have to be stored in the instruction cache? Is the instruction cache a location in one of the L1, L2, or L3 CPU caches or is it a different entity? I am not very clear on what physically happens when i run an executable and any sort of clarity would be greatly appreciated.

A: The instructions are stored permanently in the binary executable file on your mass storage device. When the program is executed, the contents of the executable file are loaded into primary memory (RAM). Generally speaking, all traffic between the CPU and RAM goes through a cache; so do the instructions contained by the executable.
A cache may contain instructions, data, or both. In the case of Intel CPUs, there are two L1 caches: L1d for data and L1i for instructions; L2 and L3 are shared. The following image illustrates this quite clearly:

Image source
That is the short answer. If you wish to learn more, there is plenty of good material around. Ulrich Drepper's What every programmer should know about memory is a great read for one.

A: Your executable on disk is logically memory-mapped into the virtual address space of a new process.
As usually with virtual memory, touching a 4k pages of the executable may trigger a page fault if the data isn't actually in DRAM (hard page fault) or if it is but the HW page tables haven't "wired" that page.  Soft page faults might still happen on each repeated runs because OSes are typically "lazy" about wiring up page tables, even when file data is in the kernel's pagecache.
(x86 uses 4kiB virtual memory pages.  It's a common page size but some other ISA do or can use other page sizes like 8k or 16k.)
The kernel may optimize by making sure at least the page containing the process entry point is loaded from disk and wired up before entering user-space.  Otherwise it will just page-fault right away back to the kernel.  e.g. very early Linux, like 0.11, worked this way, as a get-it-working step in development before making it good.

When data is in DRAM, execution works by the CPU doing code-fetch through L1i / L2 / L3 cache.  This is exactly like data loads, but goes through L1 I-cache instead of L1 D-cache, assuming a machine with split L1 caches.  Outer levels of cache (assuming they exist) are almost always unified.  Modern x86 CPUs and other high-end chips like POWER do typically have 3 levels of cache, usually L1i/d and L2 are per-core private, with a large shared L3.  Otherwise you might have just private L1i/L1d and shared L2, or in a single-core system maybe just 1 or 2 levels of cache.
These caches have a line size of 64 bytes on most CPUs (including all x86 CPUs since P4 / Core 2 or so).  Cache misses don't fault, the core just has to wait for the line to arrive.  If there's any out-of-order execution still not done, it can still be happening while a code-cache miss is in flight.  But otherwise the CPU is stuck with nothing at all to do.
(TLB misses are also a thing.  Most ISAs have hardware page-walk that makes it transparent to software, but an iTLB miss can similarly stall instruction fetch leaving the CPU without any queued up work to do.  So i-cache / i-TLB misses are even worse than data-cache / d-TLB misses where miss-under-miss / hit-under-miss, and out-of-order execution, can let some useful work continue.)

In modern x86 CPUs, decoded instructions are cached in a small, very fast "uop cache", as well as caching the machine-code bytes in L1i cache.
Pentium 4 didn't have an L1i cache, only a trace cache, but that didn't work out very well.  And it didn't have the transistor or power budget for enough decoders to build traces fast on trace-cache misses.  This was one of several major downsides of the NetBurst microarchitecture.


text:
Q: how to use multiple ng-click with one single boolean? AngularJS pretty new to angularJS so this question might be dumb!
I have 7  including in it the 7 days of the week.
The idea is that each time the user clicks on one days, thanks to a ng-show a table with some data for that day will appear.
I have an issue with the "buttons" (for buttons I mean the  with the clickable text inside) , I use ng-click and ng-class so when you click on a day, the text will get bigger and colored, so you know what day you selected!
ng-class="{'activeSelection': isActive}" ng-click="isActive = !isActive"

.activeSelection {
transform: scale(1.2);
color: #fff;

}
so if there was only one day, this would work great, but what happens is when I click on a day, ALL of the other days get applied the "activeSelection" class.
I understand that this happens because the BOOL isActive it's the same for every day, so when I click on a day and it gets "true", all days get the same so all days get big and colored!
How can I solve this? Initially I thought to make for each day a different BOOL like this:
isActive, isActive2, isActive3, isActive4..

but there are some problems, first, when I click on another day after I clicked on one already, I want the previous day to lose the class, so only one day is big at a time! So if new day is clicked, the previous day returns small size like the others!
For the tables, I'll use a ng-show with a bool that we get when a day is clicked, so if monday is clicked, the monday table will show, but if we click wednesday, the monday table disappears, and the wednesday one appears.
What's the best approach to this? thank you

A: You can do one thing on click of each day, pass some param to function and update $scope. try below example
<button ng-click="changeDay(1)"> Day 1</button>
<button ng-click="changeDay(2)"> Day 2</button>
<button ng-click="changeDay(3)"> Day 3</button>

1 Selection

2 Selection

3 Selection

Controller
$scope.day =0;
$scope.changeDay = (day)=>{
    $scope.day =day;
}


text:
Q: Operations with tag select in PHP How about, I try to perform a simple operation (addition, subtraction or multiplication).
99 + 5 = 104
Form
<select> + <input> = result

Between input tags, there is no problem, the problem is when I have a list of numbers to select from the BD.
In the BD the following data are available. As you can see, the discounts do not match your ID.
Id discount
1   100
2   99
3   98
4   96
5   95

If I want to perform an operation, at the time of listing the discounts, the label
<option value = "<? PHP echo ''. $ row ['id'];?>"> <? PHP echo ''. $ row ['discount'];?> </ option>

The operation is done with the id and not with the discount.
An example of a sum, we select the discount with 99, then insert the amount of 5 the correct result = 104.
The problem is that at the time of the operation instead of 99 it takes the value of its ID = 2, consequently 2 + 5 = 7.
My question at the time of performing the operation as I can take the discount value instead of Id.

  <form name='f1' action="" method=POST>
  Num 1:
  <select name="cveDiscount" class="form-control ">
    <?PHP

    if ($resultado = $mysqli->query("SELECT id,discount FROM discount  order by id desc", MYSQLI_USE_RESULT)) {

      while ($row = mysqli_fetch_array($resultado)){
        ?>

          <option value="<?PHP echo ''.$row['id'];?>"><?PHP echo ''.$row['discount'];?></option>

        <?PHP
      }
    }
    ?>
    <option value="#" selected>Select discount</option>
  </select>

  Num 2:
  <input type=text name='amount'/>

  <input type=button value="   =   " onclick="fadd()">

  <input type=text name='resul'/>

</form>

A: You can use:

selectedOptions: ...contains a list of the  elements contained within the  element that are currently selected. The list of selected options is an HTMLCollection object with one entry per currently selected option.

Hence, you can change from:
n1=document.f1.cveDiscount.value;

to:
n1 = document.f1.cveDiscount.selectedOptions[0].textContent;

In any case I'd suggest to use .addEventListener() at dom ready instead to inline event handler.
The snippet:

document.addEventListener('DOMContentLoaded', function(e) {
   document.querySelector('[type=button]').addEventListener('click', function(e) {
        n1 = document.f1.cveDiscount.selectedOptions[0].textContent;
        n2 = document.f1.amount.value;
        res = document.f1.resul.value;
        res = parseInt(n1) + parseInt(n2);
        document.f1.resul.value = res;
    })
})
<form name='f1' action="" method=POST>
    Num 1:
    <select name="cveDiscount" class="form-control ">
        <option value="1">100</option>
        <option value="2">99</option>
        <option value="3">98</option>
        <option value="4">96</option>
        <option value="5">95</option>
        <option value="#" selected>Select discount</option>
    </select>
    Num 2:
    <input type=text name='amount'/>
    <input type=button value="   =   ">
    <input type=text name='resul'/>
</form>

A: Just change value inside option with discount
<option value="<?PHP echo ''.$row['discount'];?>"><?PHP echo ''.$row['discount'];?></option>

In this way you can easly pass the discount as value instead of its id

A: Changing your javascript a bit will also let you use the text from the select tag options, if you need to keep those id values in there for whatever reason:
var sel = document.f1.cveDiscount;
var n1 = sel.options[sel.selectedIndex].text;

This will return the expected results.

A: Currently you're showing the value of Discount in UI but you're actually passing id as the value for the addition.
Just retrieve discount from query and put it as value in your option tag as follows:
<select name="cveDiscount" class="form-control ">
    <?PHP

    if ($resultado = $mysqli->query("SELECT discount FROM discount  order by id desc", MYSQLI_USE_RESULT)) {

      while ($row = mysqli_fetch_array($resultado)){
        ?>

          <option value="<?PHP echo ''.$row['discount'];?>"><?PHP echo ''.$row['discount'];?></option>

        <?PHP
      }
    }
    ?>
    <option value="#" selected>Select discount</option>
  </select>


text:
Q: How to simulate HTML5 Drag and Drop in Selenium Webdriver in JavaScript I need the javascript (nodejs) version of the following code (Python) using WebdriverIO:
from selenium import webdriver

with open("drag_and_drop_helper.js") as f:
js = f.read()

driver.execute_script(js + "$('#one').simulateDragDrop({ dropTarget: '#bin'});")

Here are the complete Python and Ruby implementations for further reference.

A: With a working webdriver you can use:
driver.actions().dragAndDrop(driver.findElement(webdriver.By.id('none')),driver.findElement(webdriver.By.id('bin'))).perform();


text:
Q: mysterious error 1064 I am trying to inserting a string into MySQL db - it contains regular expressions containing quotes,asterisks,backslashes etc - the following isn't working - any thoughts how to correct it? I have also tried htmlentities with no joy based on other answers.
qa_db_query_sub('INSERT INTO `^islamiqa_topics` (title, description, regexp) VALUES ($, $, $)', $title, $description, mysql_real_escape_string($regexp));

This is the error I get:
Database query error 1064
You have an error in your SQL syntax;
check the manual that corresponds to your
MySQL server version for the right syntax to use near 'regexp)
VALUES ('7/7', '3rd of March 1924 was the day the Ottoman' at line 1

INSERT INTO `qa_islamiqa_topics` (title, description, regexp) VALUES ('7/7', '3rd of March 1924 was the day the Ottoman Caliphate was formally abolished in Turkey by Mustafa Kemal Atataurk.', '7/7(/2005)?|7(th)? july 2005|july 7.* 2005')

A: You can base64_encode() the string before adding to database.
qa_db_query_sub('INSERT INTO `islamiqa_topics` (`title`, `description`, `regexp`) VALUES ($, $, $)', $title, $description, base64_encode($regexp));

Also, @Del found out that regexp is a reserved word, so you cannot use it as a table column name. You may also try to use regexp (add quotes)


text:
Q: Flash Player Cache problem I made a flash video jukebox, so it reads a dynamic playlist of F4V files for hours.
Everything works well but after about 45 min the sound stops and after 2 hours the flash player plug in crashes.
It seems like the cache is not accepting more F4V videos and then crashes. If I auto-refresh the browser every 2 hours it works but I would like to avoid having to refresh the browser and just clear the flash player cache if that's where the F4V go?
I can't find any info about where the F4V files go when you play them!
Edit
Frame 1 gives the variable vidReference the value of the video file name:
VidReference = trackToPlay;
Frame 2 does the playing:

var nc:NetConnection = new NetConnection();
    nc.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
    nc.connect(null);
var ns:NetStream = new NetStream(nc);
ns.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
const buffer_time:Number = 2;
ns.bufferTime = buffer_time;
ns.client = this;
ns.play(VidReference);
var vid:Video = new Video();
vid.attachNetStream(ns);
addChild(vid);
vid_frame.addChild(vid);
This is the function that detects when video is done playing, still on frame 2:

function netStatusHandler(event:NetStatusEvent):void
{
  switch (event.info.code)
{
 case "NetStream.Play.StreamNotFound": newTrack();
break;
case "NetStream.Play.Stop": newTrack();
break;
}
}
And the function newTrack() is just giving the variable trackToPlay a value (the file name of the next video). And then says to gotoAndPlay frame 1, so it kind of reinitializing the player. The objects are re declared in frame 2, is that the problem here?
David

A: sounds like it's running out of memory. are you clearing out the old f4v's so that you're never just continuously requesting memory?
try profiling it, or use something like http://jpauclair.net/flashpreloadprofiler/
for help tracking memory problems, check out http://divillysausages.com/blog/tracking_memory_leaks_in_as3 (shameless self promotion)

A: Its not a cache issue. Cache is allocated space on your hard drive  so if that is not full you will not have an issue.
It sounds move like you are not garbage collecting and not reusing the video object properly.
Post some code so we can fix it


text:
Q: SQL Server could not find stored procedure 'show' I can't use the most basic procedure, show, as it throws an error:

Msg 2812, Level 16, State 62, Line 1
  Could not find stored procedure 'show'.

I used:
SHOW DATABASES

Please help me find answers to this issue.

A: To list all Databases in SQL Server,
Select * from sys.databases

To exclude in-built DBs,
Select * from sys.databases WHERE name NOT IN ('master', 'tempdb', 'model', 'msdb');

A: Try to refresh local Cache which is under the Intellisense.


text:
Q: Please if someone help me to find the winning Probability you are playing a chess match against a skilled opponent .for a given game ,there is a 75% chance the game will end in a draw.of the game that do not end in a draw,there is a 2/3 chance you will win,and a 1/3 chance you will lose.the first player to win 2 games in a row is declared the winner of the chess match.what is the probability you will win the match?

A: Firstly let us find out your winning probability.
$\frac{1}{4}$ of games end in a draw in which you win $\frac{2}{3}$ of them hence your winning probability is $\frac{1}{4}\cdot\frac{2}{3} = \frac{1}{6}$
Similarly the opponents probability of winning is $\frac{1}{12}$
We can break down  your probability of winning overall, i.e having 2 consecutive wins before your opponent on the three states the game can be in depending on the last result.
Let $\{ D,L,W\}$ be the states that indicate respectively the last game was a draw, a loss or a win.
Firstly our transition probabilities are as follows:
$D\to D \frac{3}{4}, D\to W\frac{1}{6}, D\to L \frac{1}{12}$
$L\to D\frac{3}{4}, L\to W \frac{1}{6}$
$W \to D \frac{3}{4}, W \to L \frac{1}{12}$
Hence:
$\mathbb{P}_D[\text{You win the match}] := \mathbb{P}[\text{You win the match} | \text{Most recent game was draw}] = \frac{3}{4}\mathbb{P}_D[\text{You win the match}] +\frac{1}{6}\mathbb{P}_W[\text{You win the match}] + \frac{1}{12}\mathbb{P}_L[\text{You win the match}]$
For shorthand let the event of you winning the match be $S$.
We have:
$\mathbb{P}_D[S] = \frac{3}{4}\mathbb{P}_D[S] +\frac{1}{6}\mathbb{P}_W[S] + \frac{1}{12}\mathbb{P}_L[S]$
$\mathbb{P}_W[S] = \frac{3}{4}\mathbb{P}_D[S] +\frac{1}{6}\cdot 1 + \frac{1}{12}\mathbb{P}_L[S]$
$\mathbb{P}_L[S] = \frac{3}{4}\mathbb{P}_D[S] +\frac{1}{6}\mathbb{P}_W[S] + \frac{1}{12}\cdot 0 $
Solving these equations yields: $\mathbb{P}_D[S] = \frac{26}{33} $
Notice that the most recent game being a draw is identical to the state when the game starts so your probability of winning is $\frac{26}{33}$

A: It is easy to see that the probabilities that you win, lose, and draw one game are
$\frac16,\; \frac1{12},\;$  and $\;\frac34$ respectively
Let there be $3\,$ states, s (start=level), a (ahead by one ) and b (behind by one)
We seek the probability that you ultimately win starting from s
Note that from any stage you can draw and return to s with $Pr = 3/4$.
Tracking your movement from state to state from s to victory,
$s = 3s/4 + a/6 + b/12\quad$ [I]
Similarly, $a = 3s/4 + 1/6 +b/12\quad$ [II]
(Note that the second term , a win from a completes a win for you)
$b =  3s/4 + a/6\quad$ [III]
solving these $3$ linear equations gives us $P(\,you\; win) = s = \frac{26}{33}$


text:
Q: How do I to resolve unmet dependencies to uninstall and reinstall package I have tried several askubuntu threads but yet to no avail none have all met qualifications.
I installed allvideodownloader, and found a better version an earlier version; I downloaded from software-center, so there should not have been a related programs version problem and I got this error:
The following packages have unmet dependencies:
 allvideodownloader : Depends: allvideodownloader-bin (= 2.6.0-0ubuntu1)
 apache2.2-bin : Depends: libaprutil1-ldap but it is not going to be installed
E: Error, pkgProblemResolver::Resolve generated breaks, this may be caused by held packages.

I have tried the usual suspects, in synaptic, software-center and aptitude.
 apt-get autoremove --purge allvideodownloader
Package allvideodownloader is not installed, so not removed
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded

 apt-get remove --auto-remove allvideodownloader-bin
Package allvideodownloader is not installed, so not removed
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded

 apt-get remove --auto-remove allvideodownloader-bin
E Unable to locate package allvideoinstaller-bin

 sudo apt-get install allvideoinstaller-bin
E Unable to locate package allvideoinstaller-bin

This is what I believe to be so; allvideodownloader changed the versions on several packages at install and didn't change them back at uninstall. These packages are somehow not reverse compatible using usual means.
I am having a headache I am growing used to from staring at this problem and that wont help matters. I've tried manner of install , purge and repair of broken packages
Please advise me on a repair.
thx,
DL

A: You just have to install dependencies, all of them at once, once you figure them all out. From that alone I see you need to sudo aptitude install allvideodownloader-bin libaprutil1-ldap allvideodownloder and if that errors it will show more dependencies and you just add those to your command and try again.


text:
Q: MySQL - Union in a filtering subquery I'm able to run the following:
SELECT * FROM t1 WHERE t1.id NOT IN (SELECT id FROM t2);

As well as:
SELECT * FROM (SELECT id FROM t2 UNION SELECT id FROM t3);

But MySQL complains when I attempt to run the following:
SELECT * FROM t1 WHERE t1.id NOT IN (SELECT id FROM t2 UNION SELECT id FROM t3);

The error is "unexpected 'SELECT'" for the third select.
Is something wrong with my syntax? Is this not possible? I'm open to rewriting using EXISTS if that's the only way.

A: They are not mistakes on your query:
SQL Fiddle
MySQL 5.6 Schema Setup:
create table t1 ( id int );
create table t2 ( id int );
create table t3 ( id int );

insert into t1 values (1);
insert into t2 values (2);
insert into t3 values (3);

Query 1:
SELECT * FROM t1 WHERE t1.id NOT IN
(SELECT id FROM t2 UNION SELECT id FROM t3)

Results:
| id |
|----|
|  1 |


text:
Q: How to edit a protected cell range on Google Sheets with scripts I have created a tracker to capture time automatically in the next cell when a cell is edited. And the time should be protected from being edited manually (through protected range). I have the below script but don't know how can I implement it on the sheet in which user's cannot edit the protected range but the script should.
function onEdit() {
    var s = SpreadsheetApp.getActiveSheet();
    if( s.getName() == "Sheet1" ) { //checks that we're on the correct sheet
        var r = s.getActiveCell();
        if( r.getColumn() == 3 ) { //checks the column
            var nextCell = r.offset(0, 1);
            //if( nextCell.getValue() !== '' ) //is empty?
            nextCell.setValue(new Date());
        }

        if( r.getColumn() == 5 ) { //checks the column
            var nextCell = r.offset(0, 1);
            //if( nextCell.getValue() !== '' ) //is empty?
            nextCell.setValue(new Date());
        }
    }
}

I want the script to run on the protected range when end user edits a cell before the protected range

The script works fine for me. But does not works for user's who don't have access to edit the protected range.


text:
Q: Does vector know to reserve first when initializing by a pair of iterators? Consider the following code.
struct MyData{
    MyData(const BYTE* pData, size_t uSize)
        : bucket_(pData, pData + uSize)
    {}
    std::vector<BYTE> bucket_;
};

Does my bucket_ do the reserve first when initializing from a pair of iterators?  Something like vec.reserve(std::distance(begIter, endIter)).
Or it just simply perform a serious of push_back or back_inserter_iterator::operator= ?
If it does not, I may need to initialize it with uSize of 0 then do the memcpy_s in constructor block.

A:
Does my bucket_ do the reserve first when initializing from a pair of iterators?

Yes, it does in effect.
Standard draft:

Complexity: Makes only N calls to the copy constructor of T (where N is the distance between first and last) and no reallocations if iterators first and last are of forward, bidirectional, or random access categories. It makes order N calls to the copy constructor of T and order log(N) reallocations if they are just input iterators.

(Pointers are random access iterators)

A: Yes, it's guaranteed that there will be no reallocations, because pointers are RandomAccessIterators. vector.cons/9

template <class InputIterator>
vector(InputIterator first, InputIterator last, const Allocator& = Allocator());

Effects: Constructs a vector equal to the range [first, last), using the specified allocator.
Complexity: Makes only N calls to the copy constructor of T (where N is the distance between first and last) and no
  reallocations if iterators first and last are of forward,
  bidirectional, or random access categories. It makes order N calls
  to the copy constructor of T and order log(N) reallocations if
  they are just input iterators.


text:
Q: OpenSSH server wont install on azure Windows 10 VM I'm trying to install OpenSSH-Server on multiple Windows 10 VM from Azure.
I added some rules on network security group (directly on portal.azure) : I allowed inbound traffic for port 22 and same for outbound.
After that I tried to install openSSH-server using the windows 10 interface, but it doesn't work (no error message, just jumping back into the app list).
I tried to add the rules to the firewall and retried to install openSSH-server, no success.
I also tried to install it using powershell but without success.
There is something I must be missing, here is the guide I followed for installing OpenSSH-server: https://learn.microsoft.com/en-us/windows-server/administration/openssh/openssh_install_firstuse
And here is the guide I followed for opening ports:
https://learn.microsoft.com/en-us/azure/virtual-machines/windows/nsg-quickstart-portal

A: Ok so I finally find out what was blocking the installation, the Windows update service was deactivated, by activating it I was able to install OpenSSH-Server, all good now !


text:
Q: Regex match only URL's that dont contain special characters I have a list of URL's like so.
https://www.website.com/foo
https://www.website.com/foo/bar
https://www.website.com/foo?query=

And I want to have some Regex that only matches with https://www.website.com/foo
I have been trying something like (?=.{23}).+(?!\?) because I know the first part of the url will always be the same so I just want to not match if there are more than one / in the trailing path or if it has special characters like ? or =. I guess I'm not understanding why the negative lookahead isn't actually filtering out matches with those characters.

A: Is that what you want?
^https://[^/]+/[^/?]+$

Demo & explanation


text:
Q: How can I put data from csv file to array using jquery? I want it to be the same file every time rather than having to input a filename or choosing a file when the page opens.  My code below requires me to choose a file, I would like it to just put the data in an array each time the page is refreshed.
$(document).ready(function () {
    $("#filename").change(function (e) {
        var reader = new FileReader();

        reader.onload = function (e) {

            var csvVal = e.target.result.split("\n"); //lines
            var csvValue = csvVal[0].split(","); //each word
            var word = "";
            var allText = "";

            for (var n = 0; n < csvVal.length - 1; n++) {
                for (var i = -1; i < csvValue.length; i++) {

                    var word = (n + 1) + " " + csvVal[n] + " " + "<br>";
                }
                var allText = allText + word;

                $("#cardData").html(allText);
            }
        };
        reader.readAsText(e.target.files.item(0));
        return false;
    });

Any help would be appreciated, thanks!


text:
Q: Linq to entities is not generating a where clause This is a weird one, never seen anything like it before. I have an old project I haven't touched in a while and its setup using Linq to Entities with code-first. Every entity I attempt to select data from works, but the SQL being generated doesn't contain a where clause. (I can see what's generated in SQL Profiler) So the application is basically selecting all rows from the tables and then filtering on the server which is not good. My project is .Net Core 2.2 using Microsoft.EntityFrameworkCore assembly version 2.2.6.0
I feel like it may be a misconfiguration of something but I don't see anything wrong. Anyone seen anything like this before?
Whatever this issue is it also presents me with this exception when trying to save a Country entity; which makes no sense because the CountryId is the primary key in the code-first setup below and I'm definitely not assigning it.
Cannot insert explicit value for identity column in table 'Country' when IDENTITY_INSERT is set to OFF.

I've tried different variations of selections and none of them generate a where clause.
var country = await _taxContext.Countries
    .FirstOrDefaultAsync(a => a.TwoLetterISOCode.Equals(country.jurisCode, StringComparison.OrdinalIgnoreCase))
    .ConfigureAwait(false);

-- generates this sql
SELECT [a].[CountryId], [a].[Name], [a].[TwoLetterISOCode]
FROM [dbo].[Country] AS [a]

var exists = await _taxContext.Countries
    .AnyAsync(a => a.TwoLetterISOCode.Equals(country.jurisCode, StringComparison.OrdinalIgnoreCase))
    .ConfigureAwait(false);

-- generates this sql
SELECT [a].[TwoLetterISOCode]
FROM [dbo].[Country] AS [a]

This is my Country entity POCO
public class Country
{
    public byte CountryId { get; private set; }
    public string Name { get; set; }
    public string TwoLetterISOCode { get; set; }

    public ICollection<Nexus> Nexi { get; set; }
}

My configuration for Country
class CountryConfiguration : IEntityTypeConfiguration<Country>
{
    public void Configure(EntityTypeBuilder<Country> builder)
    {
        builder.ToTable(nameof(Country), "dbo");

        builder.HasKey(ci => ci.CountryId);

        builder.Property(ci => ci.Name)
            .HasColumnType("nvarchar(75)");

        builder.Property(ci => ci.TwoLetterISOCode)
            .HasColumnType("char(2)");

        builder.HasMany(ci => ci.Nexi)
            .WithOne(ci => ci.Country);
    }
}

and my DbContext
public class TaxContext : DbContext
{
    public TaxContext(DbContextOptions<TaxContext> options) : base(options)
    {
    }

    public DbSet<Region> Regions { get; set; }
    public DbSet<Country> Countries { get; set; }
    public DbSet<Nexus> Nexi { get; set; }
    public DbSet<TaxRate> FallbackRates { get; set; }
    public DbSet<CircuitBreakerLog> CircuitBreakerLogs { get; set; }
    public DbSet<AppLog> AppLogs { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder
            .ApplyConfiguration(new NexusConfiguration())
            .ApplyConfiguration(new RegionConfiguration())
            .ApplyConfiguration(new CountryConfiguration())
            .ApplyConfiguration(new TaxRateConfiguration())
            .ApplyConfiguration(new CircuitBreakerLogConfiguration())
            .ApplyConfiguration(new AppLogConfiguration());
    }
}

Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<TaxContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}

A: You should see warnings in your output that EF is evaluating your query locally. This is because of your string comparison. While I will support using string.Equals, it won't support the overload you used. EF doesn't know how to deal with the StringComparison.OrdinalIgnoreCase since it relies on the database collation for casing, accents etc. The solution is to use the simple overload or a basic ==:
.FirstOrDefaultAsync(a => a.TwoLetterISOCode.Equals(country.jurisCode))

Or
.FirstOrDefaultAsync(a => a.TwoLetterISOCode == country.jurisCode)


text:
Q: Have javascript print error for invalid Captcha I have a PHP script that will process the Google Recaptcha, how can I send an error back to javascript to print an error like it does for the other fields when user does not interact with the Captcha?
PHP Script:
<?php
function validateRecaptcha($secret, $clientResponse, $clientIp)
{
    $data = http_build_query([
        "secret"   => $secret,
        "response" => $clientResponse,
        "remoteip" => $clientIp,
    ]);

    $options = [
        "http" => [
            "header" =>
                "Content-Type: application/x-www-form-urlencoded\r\n".
                "Content-Length: ".strlen($data)."\r\n",
            "method"  => "POST",
            "content" => $data,
        ],
    ];

    $response = file_get_contents(
        "https://www.google.com/recaptcha/api/siteverify",
        false,
        stream_context_create($options)
    );

    if($response === false)
    {
        return false;
    }
    else if(($arr = json_decode($response, true)) === null)
    {
        return false;
    }
    else
    {
        return $arr["success"];
    }
}

$errors         = array();      // array to hold validation errors
$data             = array();         // array to pass back data

// validate the variables ======================================================
    // if any of these variables don't exist, add an error to our $errors array

    if (empty($_POST['firstName']))
        $errors['firstName'] = 'First Name is required.';

    if (empty($_POST['lastName']))
        $errors['lastName'] = 'Last Name is required.';

    if (empty($_POST['companyName']))
        $errors['companyName'] = 'Company Name is required.';

    if (empty($_POST['companyAddress']))
        $errors['companyAddress'] = 'Company Address is required.';

    if (empty($_POST['city']))
        $errors['city'] = 'City is required.';

    if (empty($_POST['state']))
        $errors['state'] = 'State is required.';

    if (empty($_POST['emailAddress']))
        $errors['emailAddress'] = 'Email Address is required.';

    if (empty($_POST['comment']))
        $errors['comment'] = 'Comment is required.';

    if (empty($_POST['g-recaptcha-response']))
        $errors['captcha'] = 'Captcha is required.';

// return a response ===========================================================

    // if there are any errors in our errors array, return a success boolean of false

    if(empty($errors))
    {
        if(!validateRecaptcha($secret, $_POST['g-recaptcha-response'], $_SERVER["REMOTE_ADDR"]))
        {
            $errors['captcha'] = 'Captcha is required.';
        }
    }

    if ( ! empty($errors)) {

        // if there are items in our errors array, return those errors
        $data['success'] = false;
        $data['errors']  = $errors;
    } else {

        // if there are no errors process our form, then return a message

        // DO ALL YOUR FORM PROCESSING HERE
        // THIS CAN BE WHATEVER YOU WANT TO DO (LOGIN, SAVE, UPDATE, WHATEVER)

        // show a message of success and provide a true success variable
        $data['success'] = true;
        $data['message'] = 'Success!';
    }

    // return all our data to an AJAX call
    echo json_encode($data);

Javascript:
// Start
$(document).ready(function() {

    // process the form
    $('form').submit(function(event) {

        $('.form-group').removeClass('has-error'); // remove the error class
        $('.help-block').remove(); // remove the error text

        // get the form data
        // there are many ways to get this data using jQuery (you can use the class or id also)
        var formData = {
            'firstName'                 : $('input[name=firstName]').val(),
            'lastName'              : $('input[name=lastName]').val(),
            'companyName'               : $('input[name=companyName]').val(),
            'companyAddress'                : $('input[name=companyAddress]').val(),
            'city'              : $('input[name=city]').val(),
            'state'                 : $('input[name=state]').val(),
            'emailAddress'          : $('input[name=emailAddress]').val(),
            'comment'   : $('input[name=comment]').val(),
        };

        // process the form
        $.ajax({
            type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
            url         : 'formMaster.php', // the url where we want to POST
            data        : formData, // our data object
            dataType    : 'json', // what type of data do we expect back from the server
            encode      : true
        })
            // using the done promise callback
            .done(function(data) {

                // log data to the console so we can see
                console.log(data);

                // here we will handle errors and validation messages
                if ( ! data.success) {

                    // handle errors for name ---------------
                    if (data.errors.firstName) {
                        $('#firstName-group').addClass('has-error'); // add the error class to show red input
                        $('#firstName-group').append('
' + data.errors.firstName + '
'); // add the actual error message under our input
                    }

                    // handle errors for name ---------------
                    if (data.errors.lastName) {
                        $('#lastName-group').addClass('has-error'); // add the error class to show red input
                        $('#lastName-group').append('
' + data.errors.lastName + '
'); // add the actual error message under our input
                    }

                    // handle errors for name ---------------
                    if (data.errors.companyName) {
                        $('#companyName-group').addClass('has-error'); // add the error class to show red input
                        $('#companyName-group').append('
' + data.errors.companyName + '
'); // add the actual error message under our input
                    }

                    // handle errors for Company Address ---------------
                    if (data.errors.companyAddress) {
                        $('#companyAddress-group').addClass('has-error'); // add the error class to show red input
                        $('#companyAddress-group').append('
' + data.errors.companyAddress + '
'); // add the actual error message under our input
                    }

                    // handle errors for Company Address ---------------
                    if (data.errors.city) {
                        $('#city-group').addClass('has-error'); // add the error class to show red input
                        $('#city-group').append('
' + data.errors.city + '
'); // add the actual error message under our input
                    }

                    // handle errors for Company Address ---------------
                    if (data.errors.state) {
                        $('#state-group').addClass('has-error'); // add the error class to show red input
                        $('#state-group').append('
' + data.errors.state + '
'); // add the actual error message under our input
                    }

                    // handle errors for Email Address ---------------
                    if (data.errors.emailAddress) {
                        $('#emailAddress-group').addClass('has-error'); // add the error class to show red input
                        $('#emailAddress-group').append('
' + data.errors.emailAddress + '
'); // add the actual error message under our input
                    }

                    // handle errors for superhero alias ---------------
                    if (data.errors.comment) {
                        $('#comment-group').addClass('has-error'); // add the error class to show red input
                        $('#comment-group').append('
' + data.errors.comment + '
'); // add the actual error message under our input
                    }

                    // handle errors for recaptcha ---------------
                    if (data.errors.recaptcha) {
                        $('#recaptcha-group').addClass('has-error'); // add the error class to show red input
                        $('#recaptcha-group').append('
' + data.errors.recaptcha + '
'); // add the actual error message under our input
                    }

                } else {

                    // ALL GOOD! just show the success message!
                    $('form').append('
' + data.message + '
');

                    // usually after form submission, you'll want to redirect
                    // window.location = '/thank-you'; // redirect a user to another page

                }
            })

            // using the fail promise callback
            .fail(function(data) {

                // show any errors
                // best to remove for production
                console.log(data);
            });

        // stop the form from submitting the normal way and refreshing the page
        event.preventDefault();
    });

});

HTML:
<!doctype html>

    <title>Form Master</title>
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">

Contact Form

    <form name="form" id="form" action="formMaster.php" method="POST">

            First Name
            <input type="text" class="form-control" name="firstName" placeholder="Henry Pym">

            Last Name:
            <input type="text" class="form-control" name="lastName" placeholder="Henry Pym">

            Company Name:
            <input type="text" class="form-control" name="companyName" placeholder="Henry Pym">

            Company Address:
            <input type="text" class="form-control" name="companyAddress" placeholder="Henry Pym">

            City:
            <input type="text" class="form-control" name="city" placeholder="Henry Pym">

      State
      <select id="statea" name="state" class="form-control">
        <option selected>Choose...</option>
        <option>...</option>
      </select>

            Email Address:
            <input type="text" class="form-control" name="emailAddress" placeholder="rudd@avengers.com">

            Comment:
            <input type="text" class="form-control" name="comment" placeholder="Ant Man">

        <button type="submit" class="btn btn-success">Submit </button>

    </form>

But when the form is submitted other fields are highlighted with their errors except for the recaptcha section. What am I doing wrong? What needs to be done to have an error print for the recaptcha as well?

A: The form won't highlight the other errors plus the ReCaptcha errors because you're telling it to only check the ReCaptcha response if there are no other errors:
if(empty($errors))
{
    if(!validateRecaptcha($secret, $_POST['g-recaptcha-response'], $_SERVER["REMOTE_ADDR"]))
    {
        $errors['captcha'] = 'Captcha is required.';
    }
}

Instead just do:
if(!validateRecaptcha($secret, $_POST['g-recaptcha-response'], $_SERVER["REMOTE_ADDR"]))
{
    $errors['captcha'] = 'Captcha is required.';
}


text:
Q: AOSP , Error while building android Source code on Mac I am building Android source code on MacOS 10.12.6.
Android Version is 7.1.1, I have faced few issues and till now i am able to resolve all of it.
Right now I am facing issue with "lunch" command following is the error :-
-bash: Saving: command not found
-bash: ...saving: command not found
-bash: ...completed.: command not found

** Don't have a product spec for: 'aosp_arm'
** Do you have the right repo manifest?

Any leads will be appreciated.
Regards.

A: I had faced this error because the folder name (where i downloaded AOSP code) was having space "MY AOSP" after changing it to "MY_AOSP" issue got fixed.


text:
Q: Transmission line I'm currently testing a design, and using two small wires to connect an oscillator with a frequency counter (both are small circuits I have build).
So here is a question, when designing RF and connecting different circuits, when is something to be considered a transmission line?
I mean, when do I have to think about transmission line impedance matching (and to start worrying about reflection and ect.).

A: As a rule, a transmission line isn't required if the length of the connection is under 1/10 of a wavelength.
A low-impedance source can generally drive a high-impedance load without any problems. Loss of signal results if they are the other way round, and a buffer stage is usually the answer.
Impedances should be matched when using transmission lines.

A: Every line is a transmission line, however different situations require different level of rigour.
At low frequencies - from DC to few hundred MHz, short transmission lines have only very small inductance and capacitance and can be usually ignored because they don't contribute much to input of output impedance of what they are connecting. The situation with them is similar to the case when the stages are connected directly. Once you start moving into GHz range, impedance of the line becomes significant and you have to treat it as separate stage of your device and match it. When the line is long, like in the case of cable, impedance also goes up and becomes significant, and you have to match it.
At high power levels reflected wave can destroy previous stage and you have to care about matching even at low frequencies. For example if you try to transmit 100W with disconnected antenna, you are likely going to fry your power amplifier (unless it has protection against such situation).
Example: short PCB trace is going to have say 10 nH inductance, which at 10 MHz would give it reactance 0.63 ohm (open circuit), shunt capacitance 1 pF, or capacitive reactance 15783 ohm (high impedance), and resistance under 1 ohm - all values insignificant if the input and output impedance of the stages is 50 ohm. At 2 GHz it would be reactance 125 ohm and shunt capacitance 79.6 ohm - significant values that would require redesign into transmission line.

A: An interconnection should be considered a transmission line if reflections are detrimental to your application. As Leon Heller says, 1/10th wavelength is a good rule-of-thumb.
However, all this depends on the nature of the signal (1/10th of what wavelength?). With sine waves, the wavelength in the cable will be about $\frac{2 X 10^8}{f}$ where f is the frequency, but will vary according to the cable type. The effect of reflections on sine waves is to cause standing waves, so the amplitude will vary along the length of the cable but will always be sinusoidal. With square waves the situation is complicated by harmonics. Although the square-wave may have a low fundamental frequency, the harmonics introduced by the edges will be significant. The effect of reflections in this case is undershoot, overshoot or ringing depending on where the mismatches are (if both $R_S$ & $R_L$ are lower than $Z_0$ for example, you will get ringing).
So do you need to match the source? No. As long as the load is perfectly matched, the wavefront will travel down the transmission line and be fully absorbed by the load. Consider a digital system with 3.3V logic for example. If you terminated both source and load you would only get 1.65V swing at the load. Terminating only at the load is termed parallel termination.
There is also a technique known as series termination in which the source is terminated but the load is left open circuit. In this case, a half-amplitude edge propagates down the line and is reflected back to the source, lifting the voltage to full amplitude as it returns until it is absorbed by the source termination. Along the line, you would see a 'stepped' signal except right at the load where you would see a clean waveform.


text:
Q: Como traer datos de una tabla que no coinciden con otra en rango de fechas Amablemente solicito ayuda con una consulta MySQL, hace un tiempo hice una aplicación de reservación de salas y actualmente el cliente me solicitó colocar la opción de búsqueda de salas libres en determinado lapso de tiempo, es decir, ingresar dos campos para la hora inicial y la hora final y mostrar las salas que tenían disponibles ese tiempo.
Estas son mis dos tablas:

Las tablas tienen más campos de los visibles, pero estos son los que se necesitan para la consulta.
Cuando quiero saber qué reservaciones hay en un lapso de tiempo específico ("2019-04-23 12:01:00" y "2019-04-23 13:59:00" para el ejemplo) hago esta consulta:
SELECT reservas.id, reservas.id_sala, salas.nombre
FROM reservas
LEFT JOIN salas ON reservas.id_sala = salas.id
WHERE
((desde <= "2019-04-23 12:01:00" AND hasta >= "2019-04-23 13:59:00")
OR desde BETWEEN "2019-04-23 12:01:00" AND "2019-04-23 13:59:00"
OR hasta BETWEEN "2019-04-23 12:01:00" AND "2019-04-23 13:59:00")

(A los campos 'desde' les sumo un minuto y a los campos 'hasta' les resto uno, esto con el fin de que no devuelva una reserva que termine justo donde comienza una o que comience donde termine otra).
En teoría necesito justo lo contrario, obtener las salas que no estén ocupadas (reservadas) en ese preciso rango de tiempo.
He intentado con IS NULL, NOT IN y NOT EXISTS pero no lo he logrado
Esta consulta me trae las salas que se encuentran reservadas en el lapso de tiempo especificado:
SELECT salas.id, salas.nombre FROM salas
LEFT OUTER JOIN reservas
ON salas.id = reservas.id_sala
WHERE
((desde <= "2019-04-23 12:01:00" AND hasta >= "2019-04-23 13:59:00")
OR desde BETWEEN "2019-04-23 12:01:00" AND "2019-04-23 13:59:00"
OR hasta BETWEEN "2019-04-23 12:01:00" AND "2019-04-23 13:59:00")

Agradezco mucho su colaboración

A: En principio, para saber que salas estarían ocupadas en el período indicado puedes hacer:
SELECT R.id_sala
       FROM reservas R
       WHERE R.desde <= '2019-04-23 13:59:00' AND
             R.hasta >= '2019-04-23 12:01:00'

Luego, podríamos negar esta consulta para saber cuales estarían libres:
SELECT salas.id, salas.nombre
       FROM salas
       WHERE salas.id NOT IN ( SELECT R.id_sala
                                      FROM reservas R
                                           WHERE R.desde <= '2019-04-23 13:59:00' AND
                                                 R.hasta >= '2019-04-23 12:01:00'
                             )

Para una explicación más general de como funcionan las relaciones entre los intervalos de reservas y el intervalo solicitado, puedes ver: ¿Como verificar si dos intervalos de datos tienen elementos compartidos?