text:
Q: Laravel route without prefix name I'm trying to utilize the Laravel landing page route. For example Laravel takes you to the welcome page by default, and it has no url text after the slash.
Route::get('/', function () {
    return view('welcome');
});

In my welcome page I'm using following condition to apply styling based on the route name.
{!! Route::is('/')? 'class="index"':'' !!}

However this code doesn't work. How can I check the route of the welcome page properly?
Edit: Using "Request" instead of "Route" makes it work. However for consistency's sake I would like to know if it can be done using "Route" too.

A: try this
@if(Request::is('/'))
  class="index"
@endif

or more simply
if(Request::is('/')) {
   class="index"
}

A: Try this:

is('/')) index @endif">

    // ...

You can use wildcards as well with this:

is('/some-url/*')) active @endif">
    // ...

A: Name your route and use this name to condition your styling
Route::get('/', function () {
    return view('welcome');
})->name('home');

In your blade
{!! (Route::currentRouteName() == 'home')? 'class="index"':'' !!}

A: Try this:

...

A: Route::get('/', function () {
    return view('welcome');
})->name('home');

in blade
class = "default class @if(\Request::route()->getName() == 'home')your_class @endif"


text:
Q: using delegates in an array initialization I'm coding a server and I've set up a TCP connection with all the clients.
Now, when a Client sends a packet I check the opcode of the packet so I can process it.
At the moment, I have an OpcodeHandler struct that currently contains String name but I also want it to have a C++-typed function pointer that calls another function, so that when I create an array with the struct as type and I initialize the array like this:
opcodes = new OpcodeHandler[max_opcodes]
{
  new OpcodeHandler("someopcodenamehere", Somefunctionname);
  // more new's..
}

That the function named in the second argument of the constructor : 'Somefunctionname' gets called when calling the function pointer.
I've heard that this is possible with delegates since they behave just like function pointers in C++, but all of my tries were useless.

A: You said you have a struct OpcodeHandler that you want to create an array of.
Now I don't know what else the OpcodeHandler does, but I'll suggest something simpler:
Dictionary<string, Action<PacketData>> OpcodeHandlers = new Dictionary<string, Action<PacketData>>();

This is a dictionary of delegates.
You can add functions to it like so:
OpcodeHandlers["someopcodenamehere"] = Somefunctionname;

and call the functions like so:
OpcodeHandlers["someopcodenamehere"](packetData);

Edit:
You can also fill the Dictionary like this:
Dictionary<string, Action<PacketData>> OpcodeHandlers = new Dictionary<string, Action<PacketData>>
{
  { "functionName1", function1 },
  { "functionName2", function2 }
};

A: new OpcodeHandler("someopcodenamehere", packetData =>
        Somefunctionname(packetData))

redpajama_set_name: RedPajamaStackExchange


text:
Q: PyQt5 QSystemTrayIcon is outside actual tray I have simple PyQt5 application, which is just an example, and doesn't do anything:

#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import sys
from PyQt5 import QtWidgets, QtCore, QtGui

class SystemTrayIcon(QtWidgets.QSystemTrayIcon):

    def __init__(self, icon, parent=None):
        super(SystemTrayIcon, self).__init__(icon, parent)
        menu = QtWidgets.QMenu(parent)
        exitAction = menu.addAction("Exit")
        exitAction.triggered.connect(parent.close)
        self.setContextMenu(menu)

class MainWindow(QtWidgets.QWidget):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.initUI()

    def initUI(self):
        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle('Icon')
        self.tray_icon = SystemTrayIcon(QtGui.QIcon('test.ico'), self)
        self.tray_icon.show()
        self.show()

if __name__ == '__main__':
    app = QtWidgets.QApplication([])
    w = MainWindow()
    sys.exit(app.exec_())

After start, it shows main window and tray icon. But tray icon isn't in tray. It is in left-upper corner.
How do I fix this? This code works normally on Windows 7, Mac OS X, and Archlinux with KDE. So problem probably in Ubuntu DE.
I use latest ubuntu 14.04 amd64, python 3, PyQt5, Qt version is 5.2.1

A: It's known bug; see this bug report.
Apparently, it will be fixed in next releases.


text:
Q: Entity Framework execute query with not mapped properties. Expression tree I want to execute linq method on iqueryable with an expression tree from function where I'm passing name of linq method and name of property. But my sample method works only with mapped properties. It throws an exception when I try to for example to find max of calculated property.
My classes:
    public partial class Something
    {
        public int a { get; set; }
        public int b { get; set; }
    }

    public partial class Something
    {
        public int calculated { get { return a * b; } }
    }

Sample method:
public static object ExecuteLinqMethod(IQueryable<T> q, string Field, string Method)
    {
        var param = Expression.Parameter(typeof(T), "p");

        Expression prop = Expression.Property(param, Field);

        var exp = Expression.Lambda(prop, param);

            Type[] types = new Type[] { q.ElementType, exp.Body.Type };
            var mce = Expression.Call(typeof(Queryable),Method,types,q.Expression,exp);

            return q.Provider.Execute(mce);
    }

A: To be able to query on calculated properties, you have at least 2 options:
1) you store the calculated values in the db with the rows (or in a different table), and use them in your queries of course this requires datamodel change, and redundancy in data, but is the most performant way. But is not that exciting, so lets move on to
2) you need to be able to express the way you "calculate" the properties in a way that sql will understand, meaning the property needs to be replaced with a linq expression in the final query. I found in 2009 an amazing article from Eric Lippert on registering inline such properties, but I cannot find it anymore. As such here is a link to another, that has the same idea. Basically you define your calculation as an expression tree, and use the compiled version in your code.
To make it more convenient, you would attribute your property with a
[AttributeUsage(AttributeTargets.Property)]
class CalculatedByAttribute: Attribute
{
    public string StaticMethodName {get; private set;}
    public CalculatedByAttribute(string staticMethodName)
    {
        StaticMethodName = staticMethodName;
    }
}

Like:
public partial class Something
{
    [CalculatedBy("calculatedExpression")]
    public int calculated { get { return calculatedExpression.Compile()(this); } }
    public static Expression<Func<Something, int>> calculatedExpression = s => s.a * s.b;
}

(of course you can cache the compilation) :)
Then in your method, if the property has your attribute, you get the static property value, and use that in your queries. Something along:
public static object ExecuteLinqMethod<T>(IQueryable<T> q, string Field, string Method)
{
    var propInfo = typeof(T).GetProperty(Field);
    LambdaExpression exp;
    var myAttr = propInfo.GetCustomAttributes(typeof(CalculatedByAttribute), true).OfType<CalculatedByAttribute>().FirstOrDefault();
    if (myAttr != null)
        exp = (LambdaExpression)typeof(T).GetField(myAttr.StaticMethodName, BindingFlags.Static | BindingFlags.Public).GetValue(null);
    else
    {
        var param = Expression.Parameter(typeof(T), "p");
        Expression prop = Expression.Property(param, Field);
        exp = Expression.Lambda(prop, param);
    }

    Type[] types = new Type[] { q.ElementType, exp.Body.Type };
    var mce = Expression.Call(typeof(Queryable),Method,types,q.Expression,exp);

    return q.Provider.Execute(mce);
}


text:
Q: Xcode environment — shortcuts and indentation utilities (Not sure if the question belongs here, so apologies are in order)
I am heavy on sublime text and I often find Xcode to be lacking with some of the text/data processing stuff. I might have more than one question here —

*

*'Command + /' comments code but there is no indentation. Are the any tools or utilities out there that could help me with this?

*'Command + C' and 'Command + X' copy and cut lines in sublime text when there is no text selected. Is this possible in Xcode?
Moving on, is there a set of plugins or utilities for Xcode that could make it a bit more like sublime text? I understand that I need to get along with Xcode and I have, but there are somethings that Xcode doesn't do well and I am wondering if there are ways to accommodate that.

A: Have you considered using ST as an external editor for XCode?
How to set it up is here:
How to set an external editor in Xcode 4.2
Then you could open your files in ST and edit there getting all the features of ST natively.
If you have already tried this and it wasn't a happy experience sorry for wasting your time.


text:
Q: Ruby Threads Die? I've been playing around with threads but I keep running into a problem where the treads seem to just die or stop.
Whats going on here? And how do I get round it?
I've included the code, but didn't paste it here as I think this problem is more fundamental to ruby.
source code
thanks.
Edit
Ruby 1.8, MacOS (snow leopard)

A: It looks like you're forgetting to add your new Thread objects to your threads object.
3.times do |t|
  threads << Thread.new { word_list.process }
end

Your threads.each {|t| t.join} is working on an empty array, and so is ignoring the threads you did create.  Make the change and it should wait.
Edit: I meant to << onto the array, not set it equal.

A: If you've got threads randomly "going away", make sure you've set Thread.abort_on_exception to true. That'll stop the interpreter if an uncaught exception reaches the top-level in a background thread (via SystemExit, so don't rescue Exception or they'll get swallowed), and can be immensely useful in tracking down random bugs.


text:
Q: jQuery Chosen Plugin on live I'm having some trouble finding a way to register a multiselect with the Chosen plugin.
I'm dynamically loading a form into the DOM with Ajax, and want one of the selects to make use of the Chosen plugin.
I've tried calling
$('.chosen-element').chosen()

on ajaxComplete, which suggests that I won't be able to generate a custom event and bind to it. I've also tried cloning the returned select and registering the cloned element with the plugin, but to no avail.
Has anyone found a nice way to get Chosen working dynamically?

A: You do not have closing quote for the selector, you have semi colon ; instead of single quote '
Change
$('.chosen-element;).chosen()

To
$('.chosen-element').chosen()


text:
Q: Como faço para saber e contar a quantidade de linhas em uma consulta SQL com Laravel?  $teste = DB::table("cnaes")
                ->select("id")
                ->where("cnpj", $cnpj)
                ->where("cnae", $cnae);

Como posso saber quantas linhas foram afetadas por esta consulta?

A: Você pode usar o método count()
 $teste = DB::table("cnaes")
                ->select("id")
                ->where("cnpj", $cnpj)
                ->where("cnae", $cnae)
                ->count();

A: beleza ?
Achei um pouco parecido com o codeigniter essa estrutura aí...
No caso, a sql usada é num_rows... Olha na documentação do Laravel para ver como ela se aplica.
Se for igual ao codeigniter, ficaria assim:
   $teste = DB::table("cnaes")
                    ->select("id")
                    ->where("cnpj", $cnpj)
                    ->where("cnae", $cnae);

     echo $teste->num_rows();

A: A resposta correta é de duas formas
1:
$teste = DB::table("cnaes")
                ->select("id")
                ->where("cnpj", $cnpj)
                ->where("cnae", $cnae)->get()->count();

2:
 $teste = DB::table("cnaes")
                ->select(\DB::raw("COUNT(id)" as quantidade))
                ->where("cnpj", $cnpj)
                ->where("cnae", $cnae)->get();

Da uma olhada na documentação que pode haver o ->sum() não me lembro se houver são 4 formas.


text:
Q: Comparing String concatenation I was wondering what the best way is to concat two strings.
Coming from a C# background I am used to String.Format(...),StringBuilder and of course +.
In Axapta (4.0) I have now seen:
str str1, str2, str3;
;

str1 = 'Hello';
str2 = 'world';

str3 = strfmt('%1 %2',str1,str2);
info(str3);

str3 = str1+' '+str2;
info(str3);

My question would be, what is concidered best practise and why ?
And to make it not opinion based: Is there a speed difference ?

A: The simple + operator is fastest as you can quickly benchmark yourself with some loop and a high number of iterations. See below for a quick example which takes (on my machine) ~ 7 secs for the + operator and ~ 10 secs for strfmt. As already pointed out by Guido Preite, write it for the best readability but usually in AX strfmt is used for building up strings facing the user (e.g. through the infolog).
static void StrConcatPerf(Args _args)
{
    int i;
    int startTime;
    int endTime;

    str concat2StringsWithOperator(str _lhs, str _rhs)
    {
        ;

        return _lhs + _rhs;
    }

    str concat2StringsWithStrFmt(str _lhs, str _rhs)
    {
        ;

        return strfmt('%1%2', _lhs, _rhs);
    }
    ;

    startTime = timenow();
    for (i = 0; i < 2000000; ++i)
    {
        //concat2StringsWithStrFmt('lhs_string', 'rhs_string');
        //concat2StringsWithOperator('lhs_string', 'rhs_string');
    }
    endTime = timenow();

    info(strfmt("Processing time was %1 secs", endTime - startTime));
}


text:
Q: combined local and remote journald logs I am using journald forwarding using systemd-journal-remote (local site) and systemd-journal-upload (remote site) on centos7 with systemd-219 on both machines.
Local journals are stored in /var/log/journal/<machine_id>/*.journal whereas remote uploads are stored in /var/log/journal/remote/remote-*.journal.
I'm able to view both seperatly using journalctl -lf or journalctl -D /var/log/journal/remote -lf.
I am now trying to get a combined view using journalctl -m, where the man page says that it would show entries from all available journals, including remote ones, but that doesn't seem to work, at least not the way I'd expect, because the journals aren't merged in any way.
Using SYSTEMD_LOG_LEVEL=debug journalctl -lfm gives hints about the included journal files:
Root directory /var/log/journal added.
Considering /var/log/journal/fb643c7c40aa414aab4fe052ee7aff57.
Directory /var/log/journal/fb643c7c40aa414aab4fe052ee7aff57 added.
File /var/log/journal/fb643c7c40aa414aab4fe052ee7aff57/system.journal added.
File /var/log/journal/fb643c7c40aa414aab4fe052ee7aff57/user-1001.journal added.
File /var/log/journal/fb643c7c40aa414aab4fe052ee7aff57/user-1000.journal added.
Journal filter: none
Considering /var/log/journal/fb643c7c40aa414aab4fe052ee7aff57.
... journal output ...

Is there a way to achive a merged view of all journals, by which I mean all journal files located somewhere under /var/log/journal/?

A: The fix appears to be coming in https://github.com/systemd/systemd/pull/4970

A: I can't find how to set other search path.
Workaround: override the systemd-journal-remote service where set the --output=/var/log/journal instead of /var/log/journal/remote/.
Don't forget take care proper permission settings.

A: journalctl -mf
using -m for merge flag
(-m --merge)


text:
Q: Trouble when attempting to launch Rails Server Sorry if this is a bad question, I'm trying to initially set up Rails, so I don't really know what I'm doing. In the tutorial I'm following it comes to a point at which is says to run "rails server," however this is returning some unexpected results.(See below)
Macbookpro:First Cameron$ sudo rails server
Password:
=> Booting WEBrick
=> Rails 4.1.0 application starting in development on http:// 0.0.0.0:3000
=> Run `rails server -h` for more startup options
=> Notice: server is listening on all interfaces (0.0.0.0). Consider using 127.0.0.1 (--binding option)
=> Ctrl-C to shutdown server
Exiting
/Library/Ruby/Gems/2.0.0/gems/railties-4.1.0/lib/rails/railtie/configuration.rb:95:in `method_missing': undefined method `action_mailer' for #<Rails::Application::Configuration:0x007fea90b47760> (NoMethodError)
    from /Users/admin/Rails/First/config/environments/development.rb:17:in `block in <top (required)>'
    from /Library/Ruby/Gems/2.0.0/gems/railties-4.1.0/lib/rails/railtie.rb:210:in `instance_eval'
    from /Library/Ruby/Gems/2.0.0/gems/railties-4.1.0/lib/rails/railtie.rb:210:in `configure'
    from /Library/Ruby/Gems/2.0.0/gems/railties-4.1.0/lib/rails/railtie.rb:182:in `configure'
    from /Users/admin/Rails/First/config/environments/development.rb:1:in `<top (required)>'
    from /Library/Ruby/Gems/2.0.0/gems/activesupport-4.1.0/lib/active_support/dependencies.rb:247:in `require'
    from /Library/Ruby/Gems/2.0.0/gems/activesupport-4.1.0/lib/active_support/dependencies.rb:247:in `block in require'
    from /Library/Ruby/Gems/2.0.0/gems/activesupport-4.1.0/lib/active_support/dependencies.rb:232:in `load_dependency'
    from /Library/Ruby/Gems/2.0.0/gems/activesupport-4.1.0/lib/active_support/dependencies.rb:247:in `require'
    from /Library/Ruby/Gems/2.0.0/gems/railties-4.1.0/lib/rails/engine.rb:594:in `block (2 levels) in <class:Engine>'
    from /Library/Ruby/Gems/2.0.0/gems/railties-4.1.0/lib/rails/engine.rb:593:in `each'
    from /Library/Ruby/Gems/2.0.0/gems/railties-4.1.0/lib/rails/engine.rb:593:in `block in <class:Engine>'
    from /Library/Ruby/Gems/2.0.0/gems/railties-4.1.0/lib/rails/initializable.rb:30:in `instance_exec'
    from /Library/Ruby/Gems/2.0.0/gems/railties-4.1.0/lib/rails/initializable.rb:30:in `run'
    from /Library/Ruby/Gems/2.0.0/gems/railties-4.1.0/lib/rails/initializable.rb:55:in `block in run_initializers'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/tsort.rb:150:in `block in tsort_each'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/tsort.rb:183:in `block (2 levels) in each_strongly_connected_component'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/tsort.rb:210:in `block (2 levels) in each_strongly_connected_component_from'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/tsort.rb:219:in `each_strongly_connected_component_from'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/tsort.rb:209:in `block in each_strongly_connected_component_from'
    from /Library/Ruby/Gems/2.0.0/gems/railties-4.1.0/lib/rails/initializable.rb:44:in `each'
    from /Library/Ruby/Gems/2.0.0/gems/railties-4.1.0/lib/rails/initializable.rb:44:in `tsort_each_child'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/tsort.rb:203:in `each_strongly_connected_component_from'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/tsort.rb:182:in `block in each_strongly_connected_component'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/tsort.rb:180:in `each'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/tsort.rb:180:in `each_strongly_connected_component'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/tsort.rb:148:in `tsort_each'
    from /Library/Ruby/Gems/2.0.0/gems/railties-4.1.0/lib/rails/initializable.rb:54:in `run_initializers'
    from /Library/Ruby/Gems/2.0.0/gems/railties-4.1.0/lib/rails/application.rb:288:in `initialize!'
    from /Library/Ruby/Gems/2.0.0/gems/railties-4.1.0/lib/rails/railtie.rb:194:in `public_send'
    from /Library/Ruby/Gems/2.0.0/gems/railties-4.1.0/lib/rails/railtie.rb:194:in `method_missing'
    from /Users/admin/Rails/First/config/environment.rb:5:in `<top (required)>'
    from /Users/admin/Rails/First/config.ru:3:in `require'
    from /Users/admin/Rails/First/config.ru:3:in `block in <main>'
    from /Library/Ruby/Gems/2.0.0/gems/rack-1.5.2/lib/rack/builder.rb:55:in `instance_eval'
    from /Library/Ruby/Gems/2.0.0/gems/rack-1.5.2/lib/rack/builder.rb:55:in `initialize'
    from /Users/admin/Rails/First/config.ru:in `new'
    from /Users/admin/Rails/First/config.ru:in `<main>'
    from /Library/Ruby/Gems/2.0.0/gems/rack-1.5.2/lib/rack/builder.rb:49:in `eval'
    from /Library/Ruby/Gems/2.0.0/gems/rack-1.5.2/lib/rack/builder.rb:49:in `new_from_string'
    from /Library/Ruby/Gems/2.0.0/gems/rack-1.5.2/lib/rack/builder.rb:40:in `parse_file'
    from /Library/Ruby/Gems/2.0.0/gems/rack-1.5.2/lib/rack/server.rb:277:in `build_app_and_options_from_config'
    from /Library/Ruby/Gems/2.0.0/gems/rack-1.5.2/lib/rack/server.rb:199:in `app'
    from /Library/Ruby/Gems/2.0.0/gems/railties-4.1.0/lib/rails/commands/server.rb:50:in `app'
    from /Library/Ruby/Gems/2.0.0/gems/rack-1.5.2/lib/rack/server.rb:314:in `wrapped_app'
    from /Library/Ruby/Gems/2.0.0/gems/railties-4.1.0/lib/rails/commands/server.rb:130:in `log_to_stdout'
    from /Library/Ruby/Gems/2.0.0/gems/railties-4.1.0/lib/rails/commands/server.rb:67:in `start'
    from /Library/Ruby/Gems/2.0.0/gems/railties-4.1.0/lib/rails/commands/commands_tasks.rb:81:in `block in server'
    from /Library/Ruby/Gems/2.0.0/gems/railties-4.1.0/lib/rails/commands/commands_tasks.rb:76:in `tap'
    from /Library/Ruby/Gems/2.0.0/gems/railties-4.1.0/lib/rails/commands/commands_tasks.rb:76:in `server'
    from /Library/Ruby/Gems/2.0.0/gems/railties-4.1.0/lib/rails/commands/commands_tasks.rb:40:in `run_command!'
    from /Library/Ruby/Gems/2.0.0/gems/railties-4.1.0/lib/rails/commands.rb:17:in `<top (required)>'
    from bin/rails:4:in `require'
    from bin/rails:4:in `<main>'

Sorry if this is not needed, but I'm really unsure what to do with it.

A: Take a look at the following tutorial. I realise that it is for windows however it solved all the initial problems I was having with my first install.
http://www.soheiokamoto.com/setting-up-ruby-on-rails-on-windows
The main point that helped me install perfectly was;
Run gem update on a fresh install to make sure everything is up to date

A: I don't think you're alone in this error.
Make sure you coordinate your gem versions, and even better if specify the versions of your Rails & Ruby gems to avoid potential conflicts in versioning.
Posting your Gemfile would be helpful, but without seeing it, I'd say to specify your Ruby version at the top of your gemfile like:
source 'https://rubygems.org'
ruby '2.0.0'

Then specify your version of Rails. While I have had no problems with just providing:
gem 'rails'

You could be extra safe and specify a version like:
gem 'rails', '4.0.2'

Then run: bundle install for your app.


text:
Q: Big-O and little-o properties of polynomial $3x^4+6x^3-15x^2+4$ Which of the following statements are correct?
A. $3x^4+6x^3-15x^2+4 \in O(x^4)$
 B. $3x^4+6x^3-15x^2+4 \in o(x^4)$
 C. $3x^4+6x^3-15x^2+4 \in o(x^3)$
 D. $3x^4+6x^3-15x^2+4 \in O(x^5)$
 E. $3x^4+6x^3-15x^2+4 \in o(x^5)$
I have taken up through Calculus 3 and learned about Taylor series expansions. However, we didn't go over Big Oh and Little Oh notation. I have looked at other questions on StackExchange concerning this notation, but I'm not sure how to answer this question because it asks about a polynomial, not necessarily a series expansion.

A: Since the degrees in the O-notation terms are all equal to or larger than the degree in their respective equation, it can safely be assumed that the author of the question was implying as $ x \rightarrow \infty $.

In the most basic terms, big-O says "grows no faster than". So, for $O(x^5)$, the largest degree of any polynomial that satisfies this notation will be $x^5$.
Little-o is to big-O what $>$ is to $\ge$. So, for $ o(x^5) $, the largest degree of any polynomial that satisfies this notation will be $x^4$, assuming we're using integral powers.
If dealing with
There is actually a different notation for each inequality sign:

*

*$O(x^5)$ implies degree $\le 5$.

*$o(x^5)$ implies degree $< 5$.

*$\Theta(x^5)$ implies degree $= 5$.

*$\Omega(x^5)$ implies degree $> 5$.

*$\omega(x^5)$ implies degree $\ge 5$.

If dealing with $ x \rightarrow 0 $, simply use these inequalities bottom to top. This is because as $ x \rightarrow 0 $, $ x^n \rightarrow 0 $, and the notations specifically talk about growth (i.e the original ones talk about decay, so it goes bottom to top).
Correct equations:

 A, D and E.


text:
Q: How to solve get_cv_idxs not available in new version fastai? I am facing this issue when creating a collaborative filter using fastai.
import torch
import pandas as pd
from fastai import *

ratings = pd.read_csv(ratings_path)
movies = pd.read_csv(movies_path, engine='python')
val_idxs = get_cv_idxs(len(ratings))

And I am getting this error:
NameError                                 Traceback (most recent call last)
<ipython-input-25-14332e30e55d> in <module>()
----> 1 val_idxs = get_cv_idxs(len(ratings)) #get validation indices
      2 wd=2e-4 #weight decay
      3 n_factors = 50 #dimension of embedding vector

NameError: name 'get_cv_idxs' is not defined

It seems like this function is only available in the older version fastai.
https://github.com/fastai/fastai/blob/master/old/fastai/dataset.py
Someone actually asked this question in fastai's forum but yet to be answered.
https://forums.fast.ai/t/get-cv-idxs-missing-in-fastai-v1/51020
Does anyone know the solution? Appreciate your help.

A: Use this,
def get_cv_idxs(n, cv_idx=0, val_pct=0.2, seed=42):
  np.random.seed(seed)
  n_val = int(val_pct*n)
  idx_start = cv_idx*n_val
  idxs = np.random.permutation(n)
  return idxs[idx_start:idx_start+n_val]


text:
Q: convert String to runtime code in java I'm creating a software that would execute custom code line by string
SO, is there any method function or whatever you want that can do that :
String command="println("the TEST work !!!")";
magicExecMethod(command);

*and it print : the TEST work !!!
Thancks

A: You have several ways to achieve this.
You can create java file by printing it line-by-line, then compile it by either invocation of compiler from command line or by calling java.lang.Compiler, then run it.
Other way is to run your line directly using Groovy - java based language that supports Java syntax and can be used in interpreter mode.
If you are not sticky to java syntax and for example can use java script instead you can use ScriptingHost and Rhino that is a part of JDK since java 1.5.


text:
Q: Separating tags with BigQuery public dataset for stackoverflow Google makes available a public dataset for the content of Stackoverflow.  We can read about this here.  When I login to the GCP Cloud Console and visit the BigQuery page and submit the following query:
select id, tags from `bigquery-public-data.stackoverflow.posts_questions` limit 10

The resulting table that is shown to me shows the tags field as concatenated items.

If I look at the JSON, I seem to see the same:

My supposition was that the tags would be delimited by the '|' character but the data seems to show otherwise.  I'm hoping to understand this better.  My end goal is to perform queries to find all questions that contain a given tag.

A: To find all the Stackoverflow questions that contain a given tag name you can employ the SQL operator LIKE. This operator is very useful while looking for a particular pattern within a database field. It is specified after the WHERE statement with the following syntax:
SELECT field1, field2, ...
FROM table
WHERE fieldN LIKE pattern;

The patterns are usually written with the following wildcards that make possible to generate regular-like expressions:

*

*The percent symbol "%" looks for any string of zero or more characters.
Example: SELECT * WHERE fieldN LIKE "%foo%" will return all the entries that contain the string "foo" in the fieldN column.

*The underscore symbol "_" looks for any single character.
Example: SELECT * WHERE fieldN LIKE "A_" will return all the entries that start with the character "A".
In order to find all the Stackoverflow questions that contain a given tag TAGNAME, you can employ the pattern "%TAGNAME%".
In this example, the query will return all the entries where the tag field contains the word "javascript":
SELECT
  *
FROM
  `bigquery-public-data.stackoverflow.posts_questions`
WHERE
  tags LIKE "%javascript%"

A: It was discovered that an error was at play in how the source data from Stackoverflows was being transformed into BigQuery tables.  Google created an issue to resolve and eventually posted that it had been fixed.  As such, this story/posting was transient and likely will not be replicable nor of value in the future.


text:
Q: POST json data (stored as json files in ADLS) to REST endpoint in Azure Data factory I have a requirement to POST json data (stored as json files in ADLS) to REST API endpoint. I have to use Azure Data factory for this.  I have gone through Microsoft documentation but unable to get a clear idea on it is implementation.
As per my understanding ADF Data Copy activity doesn't support REST API as output/sink service.
Reaching out if anyone could help me with any documentation or reference material that could guide me to implement this. Thanks!

A: I have repro'd with sample API and was able to post the JSON data from blob storage to the REST endpoint using data flow activity in azure data factory.
Source dataset:

*

*Connect source to json dataset.

*

*Connect sink to rest endpoint.


text:
Q: Como puedo hacer que para precionando la letra 'e' en python Hola amigos tengo un ploblema, Quiero hacer que python imprima del 1 al 100 pero cuando yo precione la letra 'e' para todo. abajo esta el codigo
from time import sleep
import pyautogui
import keyboard
from pynput.keyboard import Listener
import pyautogui

sleep(3)

for i in range(1, 11111):
   print(i)
#pyautogui.typewrite(str(i))
#pyautogui.typewrite('\n')

def on_press_e(e):
   print('You pressed the "e" key!')

def on_release_e(e):
   print('You released the "e" key!')

with Listener(on_press=on_press_e,on_release=on_release_e) as listener:
   listener.join()

A: Buen día,
Si pones el contador adentro del listener entonces se podrá ejecutar y al mismo tiempo detectar las teclas presionadas
En tu función on_press_e no estás revisando si la tecla presionada es "e", por lo que detecta cualquier tecla, y si quieres que el listener se detenga entonces tienes que retornar False al cumplirse la condición de que la tecla presionada es "e"
Ejemplo completo (Como no indicaste en tu pregunta lo que hay que hacer cuando el contador llegue a 100 lo reinicié a 1 y seguirá contando de 1 a 100 hasta que presiones la tecla "e")
Ejemplo completo:
from pynput.keyboard import Key, Listener
from time import sleep

#Variable global para detectar si se ha presionado la tecla "e"
e_press = False

#Función para detectar teclas presionadas
def on_press(key):
    #Uso de la variable global
    global e_press
    #No todas las teclas tienen .char (Por ejemplo shift), por eso hay que usar try - except
    try:
        if key.char == 'e':
            e_press = True
            print('La tecla "e" ha sido presionada')
            #Detener el listener
            return False
    except:
        pass

#Inicialización del contador
i = 1

#Listener
with Listener(on_press=on_press) as listener:
    #Se ejecuta mientras no se haya presionado la tecla "e"
    while not e_press:
        print(i)
        i += 1
        if i > 100:
            i = 1
        sleep(1)
    listener.join()


text:
Q: Replace empty string with with np.nan but got 'NaN' I tried to replace empty string with np.nan
But I got None in cells , what wrong with that ?
Thanks
df.replace('', np.nan)

A: There must be a problem with your data, and not with pandas. See bellow an example:
>>> data = [['a', 'b', ''], ['', 'e', 'f']]
>>> df = pd.DataFrame(data)
>>> df
   0  1  2
0  a  b
1     e  f

If you try to replace '' with np.nan in the above example, you get the desired result:
>>> df.replace('', np.nan)
     0  1    2
0    a  b  NaN
1  NaN  e    f

However, if by any chance your data was not correctly specified:
>>> data = [['a', 'b', None], [None, 'e', 'f']]
>>> df = pd.DataFrame(data)
>>> df
      0  1     2
0     a  b  None
1  None  e     f

pandas cannot help, as your data does not contain empty strings, but non-specified values (None):
>>> df.replace('', np.nan)
      0  1     2
0     a  b  None
1  None  e     f

However, there is still a chance you can remove the Nones from your table. The following, as silly as it sounds, should still work:
>>> df.replace(np.nan, np.nan)
     0  1    2
0    a  b  NaN
1  NaN  e    f

It is hard to say without having your raw data, but hope the above helps.

A: df.replace works only for pandas dataframe.
Kindly check the type of your variable by type(df). It can be a pyspark.pandas.frame.DataFrame because of which you can see that difference.
The following code works,
data = data.to_pandas() #convert pyspark pandas DF to pandas DF
data.replace("", np.NaN, inplace = True) # replace empty string to NaN

Ref: https://spark.apache.org/docs/latest/api/python/user_guide/pandas_on_spark/pandas_pyspark.html


text:
Q: How would a change in mean of the lognormal distribution (keeping variance constant) change the distribution? For normal distribution, a change in mean of the distribution will just lead to horizontal shift of the PDF if it is graphed.
I am wondering if this is also the case for lognormal distribution. (i.e. will the shape of the lognormal distribution graph be affected by the mean of the distribution?)
Thanks for answering my question!


text:
Q: Create/restore database from backup SQL Server Express I don't have SQL Server Management Studio on my machine.
I have a database backup (SQL Server 2008 R2). There is SQL Server Express that installed with Visual studio 2010 ultimate installed on my machine.
How can I restore this back up on a database and attaching it to SQL Server Express?
Is there any solution wihout using SQL Managment Studio Express ?

A: Following link provides similar solution as marc_s, and it goes even deeper. I was able to successfully create a new DB from Backup file with the solution provided in the link below.
http://codeonaboat.wordpress.com/2012/02/16/sql-server-2008-creating-a-database-from-a-bak-file/
The solution below is copied from above link:

*

*In SSMS, open  a query window in the master database of the database server. That's where you will run the following queries.

*See what the "LogicalName" of the database that has been backed up in the .bak file is

RESTORE FILELISTONLY     FROM DISK =
  'c:\DatabaseBackups\dev2012021601.bak'

This will give you the logical name of the database and its associated log file. Lets assume that the names are "dbname" and "dbname_log"

*

*Now run the following restore command. Make sure that a database with the name you are trying to create doesn't already exist (in the code sample below, dbForSocialMigration doesn't exist).

RESTORE DATABASE dbForSocialMigration
FROM DISK = 'c:\DatabaseBackups\dev20120307.bak'
WITH
MOVE 'dbname' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\dbForSocialMigration.mdf',
MOVE 'dbname_log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\dbForSocialMigration_log.mdf'

C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA is the directory where SQL Express usually keeps its data files. You can find the directory your database server is using by selecting a database from it, right clicking and opening the properties dialog and selecting the "Files" option from the left.
That should work, and at that point you should be able to access the database "dbForSocialMigration" populated with all the tables and data from the .bak file.

A: Even with SQL Server Management Studio Express, you won't be able to restore this backup. The Express edition being installed with Visual Studio 2010 is version 2008 of SQL Server - your backup is one from a SQL Server 2008 R2 release - those backups cannot be restore onto a 2008 version.
You will need to download the SQL Server 2008 R2 Express version, and while you're at it - get the version with the Management Studio! Install this, and then you'll be able to restore your database backup.
If you really really want to restore your database without using Mgmt Studio - you can of course use a RESTORE statement in T-SQL and run this using the sqlcmd command line tool:
RESTORE DATABASE YourDatabaseName
FROM DISK = N'(path to your BAK file)'
WITH FILE = 1,
MOVE N'(your DB name)' TO N'(your SQL path)database.MDF',
MOVE N'(your DB name)_LOG' TO N'(your SQL path)database_LOG.LDF',
NOUNLOAD,
REPLACE,
STATS = 10
GO

(and of course, there's also a BACKUP command which you can use in a similar fashion - the MSDN Books Online are your friend for details about the syntax!!).

A: Late one but hopefully useful to others who are viewing this….
If the problem is restoring without management studio this can be easily solved by using sqlcmd as marc_s already pointed out.
However if the real problem is restoring 2008 R2 backup on SQL 2008 without using SSMS then only solution is using third party tools that can read backup and generate scripts for creating schema and inserting data.
Idea is to create empty database on SQL 2008 and use a third party tool to compare it to backup generated with 2008 R2.
I've used ApexSQL Diff and ApexSQL Data Diff with good success in my previous job but there are also good tools from Red Gate (SQL Compare) and Idera (Comparison toolset). If you look up online you'll probably find a lot more….
Disclaimer: I'm not affiliated with any of the companies mentioned above…

A: Why don't you get SQL Managment Studio Express? It is free, and should allow you to administer local sql express instances.
http://www.microsoft.com/downloads/en/details.aspx?FamilyID=c243a5ae-4bd1-4e3d-94b8-5a0f62bf7796
BACKUP DATABASE [AdventureWorks] TO
    DISK = N'\\nas\Backup\L40\SQL2005\AdventureWorks_backup_200702120215.bak'
    WITH NOFORMAT, NOINIT,  NAME = N'AdventureWorks-Full Database Backup',
    SKIP, NOREWIND, NOUNLOAD,  STATS = 10

RESTORE DATABASE [AdventureWorksNew]
    FROM  DISK = N'\\nas\Backup\L40\SQL2005\AdventureWorks_backup_200702120215.bak'
    WITH  FILE = 1,
    MOVE N'AdventureWorks_Data' TO N'C:\Data\MSSQL.1\MSSQL\Data\AdventureWorksNew_Data.mdf',
    MOVE N'AdventureWorks_Log' TO N'C:\Data\MSSQL.1\MSSQL\Data\AdventureWorksNew_Log.ldf',
    NOUNLOAD,  STATS = 10


text:
Q: Erlang List Tuple Match Im learning Erlang
suppose I have two lists
[{a,a,a,b,c},{d,d,a,a,b},{a,b,c,d,e}]
[{{a,a,a,a,a},10},{{a,a,a,a},6},{{a,a,a},4}]

after Patten Match, expected result {a,a,a,b,c} because it can match {{a,a,a},4}
I tried lists:keysearch and  lists:member, but cannot get expected result
any suggestion?
thanks

A: Matching is not consumptive. Your mental model of how matching works is confusing set operations (like set subtraction and intersection) with comparison and assignment. Your concept of set operations might also benefit from some review.
Erlang's matching is only for assignment and assertion (a sort of comparison). If we match an unbound variable (never used before) against any value, the variable will be bound (assigned) that value:
Foo = {a,b,c}.

Now Foo and {a,b,c} can be used interchangeably. This is pure symbolic assignment like in math class, not a "variable" in the sense of other languages where variables are "storage boxes for values".
If we use the = operator against any value and this now bound symbol Foo, we are doing a check comparison (an assertion) not an assignment. Foo can't mean anything other than {a,b,c} in the current context, so trying to assign it any different value causes an exception, but simply stating that {a,b,c} is {a.b.c} is correct and still yields {a,b,c} (and since Foo is now a symbol for {a,b,c} it can appear on either side and still the statement is correct).
Doing
{a,b,c} = {a,b,c}.

or
{a,b,c} = Foo.

or
Foo = {a,b,c}.

returns {a,b,c}, and does not raise an exception because all we did here was assert that {a,b,c} is indeed {a,b,c}.
If I want just the first value assigned, I can match another way:
{Bar,_,_} = {a,b,c}.

Now Bar represents a, and the _ values are ignored (completely skipped). The original {a,b,c} has not been changed. This is also true if we do:
{_,Baz,_} = Foo.

Now Baz represents b, and Foo still represents {a,b,c}. And that's about it. When it comes to lists, like [{a,b,c}, {1,2,3}] we can still do matching, but because of the nature of lists we will check a piece at a time (try this in the interpreter):
Spam = [{a,b,c}, {1,2,3}].
[Boo | _] = [{a,b,c}, {1,2,3}].

Now Boo represents {a,b,c}, and Spam still represents its original list.
That's about all there is to matching. The magical thing about Erlang's pattern matching is not how it works, its how many places provide natural opportunities for pattern matching, and how this winds up naturally solving a huge number of problems that require procedural checks or direct assignment operations in other languages (cond, function parameters, =, message reception, etc.).
Set and list operations are not the same thing as pattern matching in Erlang. I suggest going through some basic learning material first, like some of the many good beginner tutorials and Learn You Some Erlang.


text:
Q: Python Pandas - Apply a filter to values in a table based on date I have the following code and output
df['revenue'] = pd.to_numeric(df['revenue']) #not exactly sure what this does
df['Date'] = pd.to_datetime(df['Date'], unit='s')
df['Year'] = df['Date'].dt.year
df['First Purchase Date'] = pd.to_datetime(df['First Purchase Date'], unit='s')

df['number_existing_customers'] = df.groupby(df['Year'])[['Existing Customer']].sum()
df['number_new_customers'] = df.groupby(df['Year'])[['New Customer']].sum()

Table = df.groupby(df['Year'])[['New Customer', 'Existing Customer', 'revenue']].sum()

Table['TotalCusts'] = Table['New Customer'] + Table['Existing Customer']
Table['Repeat Rate'] = Table['Existing Customer']/Table['TotalCusts']
Table['NewCust Rate'] = Table['New Customer']/Table['TotalCusts']
print(Table)

Output
  New Customer  Existing Customer   revenue  TotalCusts  Repeat Rate  NewCust Rate
Year
2014          7.00               2.00 11,869.47        9.00         0.22          0.78
2015          1.00               3.00  9,853.93        4.00         0.75          0.25
2016          5.00               3.00  4,058.53        8.00         0.38          0.62
2017          9.00               3.00  8,056.37       12.00         0.25          0.75
2018         12.00               7.00 22,031.23       19.00         0.37          0.63
2019         16.00              10.00 97,142.42       26.00         0.38          0.62

Want to be able to apply a filter to the above table and be able to filter by data range.  So, if I filtered on "1/1/2019 to 3/1/2019" It would give me the number of new customers, existing customers and revenue for that period. How would I go about doing that?
Below are the columns of the original dataframe
>>> df.columns
Index(['Subtotal', 'Region', 'Date', 'Ship To State', 'Ship To Customer Zip','Ship To Customer', 'revenue', 'ZipCleaned', 'Customer ID',
       'First Purchase Date', 'New Customer', 'Existing Customer',
       'Total Customers', 'Year', 'number_existing_customers',
       'number_new_customers'],
      dtype='object')

A: Arunmozhi's proposed answer worked as expected
#Table = df.groupby(df['Year'])[['New Customer', 'Existing Customer', 'revenue']].sum() # table with no date filters
#Table = df.loc[df.Date.between('2018-06-01','2018-06-30')].groupby(df['Year'])[['New Customer', 'Existing Customer', 'revenue']].sum() #with date filters for table
Table = df.loc[df.First_Purchase_Date.between('2018-01-01','2018-12-30')].groupby(df['Year'])[['New Customer', 'Existing Customer', 'revenue']].sum() #with date filter on first purchase date


text:
Q: UIView does not resize when orientation changed I am making a custom UIView using the following function. It renders fine in whichever orientation you start with but once rendered, if I change the orientation it does not resize properly. Am I doing something wrong in the function?
class func getRoundedView(text: String, view: UIView, color: UIColor, textColor: UIColor) -> UIView {

        var returnView : UIView = UIView(frame: CGRectMake(0, 0, view.frame.size.width, view.frame.size.height))

        var innerViewX : CGFloat = 0.1 * (returnView.frame.size.width)
        var innerViewY : CGFloat = 0.1 * (returnView.frame.size.height)
        var innerViewWidth : CGFloat = 0.8 * (returnView.frame.size.width)
        var innerViewHeight : CGFloat = 0.8 * (returnView.frame.size.height)
        var innerView : UIView = UIView(frame: CGRectMake(innerViewX, innerViewY, innerViewWidth, innerViewHeight))
        innerView.backgroundColor = color

        var corner : UIRectCorner = UIRectCorner.AllCorners
        var maskPath : UIBezierPath = UIBezierPath(roundedRect: innerView.bounds, byRoundingCorners: corner, cornerRadii: CGSizeMake(4.0, 4.0))
        var maskLayer : CAShapeLayer = CAShapeLayer()
        maskLayer.frame = innerView.bounds
        maskLayer.path = maskPath.CGPath
        innerView.layer.mask = maskLayer

        var label : UILabel = UILabel(frame: CGRectMake(0, 0, innerView.frame.size.width, innerView.frame.size.height))
        label.text = text
        label.center = CGPointMake(innerView.frame.size.width / 2.0, innerView.frame.size.height / 2.0)
        label.textColor = textColor
        label.textAlignment = NSTextAlignment.Center
        label.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleBottomMargin | UIViewAutoresizing.FlexibleTopMargin | UIViewAutoresizing.FlexibleLeftMargin | UIViewAutoresizing.FlexibleRightMargin

        innerView.addSubview(label)
        innerView.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleBottomMargin | UIViewAutoresizing.FlexibleTopMargin | UIViewAutoresizing.FlexibleLeftMargin | UIViewAutoresizing.FlexibleRightMargin

        returnView.addSubview(innerView)
        returnView.backgroundColor = UIColor.clearColor()
        returnView.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleBottomMargin | UIViewAutoresizing.FlexibleTopMargin | UIViewAutoresizing.FlexibleLeftMargin | UIViewAutoresizing.FlexibleRightMargin

        return returnView

    }


text:
Q: JFreechart XYPlot Overlapping Data Artifacts I am trying to draw some bar graphs with a data set that contains overlapping priorities.
E.g. three bars of different colors may be drawn at one point, but the one with the highest priority will be shown.  This works most of the time, but I am getting some artifacts on my plot as some of the colors from lower priorities leak through occasionally.  Any ideas of where I can look to fix this problem?
I thought it may have been an anti-aliasing issue, but turning it on or disabling it has no effect on the artifacts.

A: When I've seen things like this before it was because I was graphing multiple data series, and for the most part there was a huge overlap in the datasets and only the last dataset rendered (top one) was visible most of the time. I suspect that whatever you are doing in your hide code might not be working as well as you think and the 'bleeding' of the other colours is the datasets where the overlap is less significant. Try an experiment and change the order in which your datasets are rendered - I'll bet that you see suddently that the predominant colours of your bars change.

A: I'm not quite sure what you mean, but you probably should remove the priorities you don't want to see from the data model altogether, then they won't be painted at all.


text:
Q: Vimeo player API $f(iframe) value is null in https page I am using Vimeo player in my web site for a video.
I am using the following code that was given in the vimeo web site.
http://jsfiddle.net/bdougherty/HfwWY/light/
The above jsfiddle link is from the vimeo player javascript api link : https://developer.vimeo.com/player/js-api
I am using the exact same code except my video link in the iframe tag is different.
 <iframe src="http://player.vimeo.com/video/MY VIDEO CODE?api=1&player_id=player1" width="400" height="225" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>

Before the video loads I am displaying a loading icon.
I am using the ready and play event to hide the loading icon. The following is my code.
    var iframe = $('#player1')[0];
    player = $f(iframe);

    var videoSource = $('iframe#player1').prop('src');
    $('iframe#player1').prop('src',videoSource + "&autoplay=1");

    if(player !== null && player !== undefined){
        $("#loadingIcon").show();

        // When the player is ready, add listeners for pause, finish, and playProgress
        player.addEvent('ready', function() {

            $("#loadingIcon").hide();

            player.addEvent('play', onPlay);
            //player.addEvent('pause', onPause);
            //player.addEvent('finish', onFinish);
            // player.addEvent('playProgress', onPlayProgress);
        });
    }

    // function onPause(id) {}

    // function onFinish(id) {}

    function onPlay(id) {
        if($("#loadingIcon").length > 0)
            $("#loadingIcon").hide();
    }

The problem I am having is the loading icon getting displayed and not hiding away after the video is ready or starts playing.
Previously, in my https page, the object "player's" value was coming as null. So I added the if condition. It fixed the issue. But, now even that seems to be not working. So, when the video is playing the loading icon is still present.
In addition to this, firebug is throwing errors saying:
Error: Permission denied to access property 'toString'.
Error: Permission denied to access property 'toString'.
Error: Permission denied to access property 'toString'.
(I have pasted it 3 times, because firebug displays it 3 times)
But the video is still playing fine.
If anyone has encountered this issue before, please help.

A: You need FroogaLoop.js Library

A: FroogaLoop.js was being blocked, when I included it in my site, I no longer got this error.


text:
Q: Managing 1 million records per month insert/select I am working on a real time feed which gives me real time data.
The Number of records are up to 1 million per month and I need to provide reports based on these records.
I chose Mongodb as it is high performer in fetching records.
I am facing issue in managing that data because 12 million records.
Do I need to keep every data month wise?
Should I use different collections per month?
There are lot of select queries for Analytics Report and everything.

A: It depends on how you want to use the data, that's up to you to decide. There is nothing wrong with a lot of data, you just need to limit your heavy queries with the same logic as cache works (easier access, but less fresh). A common methods is:
You have a "raw data" table which contains your millions of records. This table is very large, but contains 'pure' data. You want to access this table as little as possible as it'll be slow.
The next table is less accurrate and sums information you need. In your case this could be a 'month_summery' which you create after a month ends. That way you still have the complete dataset, but also a small table with relevent info (e.g. num lines, sumOfX, averageOfY, etc). Your heavy query is now once per month and you can base your stats of this.
If you need data say per week, you'd make a 'week_summery' table. Or if you need stats per day, you make it per day, 365 entries per year is still a whole lot less than millions.


text:
Q: How to get the most recent records from MySQL? I have a table that stores some reports about an url and they have a field like created_date. The same report can be generated (and stored) multiple times because the values can change. How can I get the url reports, but just the most recent ones?
My table (page_report):
id INT PK
url VARCHAR(255)
created_date TIMESTAMP

Sample data:
id    url          created_date
1     google.com   2016-11-01
2     google.com   2016-11-05
3     bing.com     2016-11-03
4     bing.com     2016-11-06

I need:
id    url          created_date
1     google.com   2016-11-05
2     bing.com     2016-11-06

What I have so far:
SELECT r1.*
FROM page_report r1
LEFT JOIN page_report r2 ON r1.url = r2.url AND r1.created_date < r2.created_date
WHERE r2.url IS NULL;

But it's very slow. Is there any better way?
Hope I made myself clear and thanks in advance!

A: One way is to generate a date set of the max records by Some ID / Logical Key.
If I assume a field called ID is the grouping mechanism for the urls...
SELECT T1.URL, T1.Created_Date
FROM TableEName T1
INNER JOIN (SELECT MAX(Created_Date) CD, ID
            FROM TableName
            GROUP BY ID)
 on T1.ID = T2.ID
and T1.Created_Date = T2.CD

The trick here is how do we know a URL "Changed"  would they have the same ID or some other attribute that would remain constant over time?

A: Use UNION ALL and then group by url and select MAX(created_date).
SELECT t.url, MAX(t.created_date)
FROM (SELECT * FROM table1 UNION ALL SELECT * FROM table2) t
GROUP BY t.url

See the myql's UNION documentation for details.

A: I kept with this one:
SELECT DISTINCT r1.url FROM page_report r1
    LEFT JOIN page_report r2 ON r1.url = r2.url AND r1.created_date < r2.created_date
    WHERE r2.url IS NULL;

A: Create a Rank Function for latest Create Date. Something like below.
select * from (select distinct DENSE_RANK () OVER (PARTITION BY url   ORDER BY B.CreatedDate desc) Rnk, t.url  )
where rnk =1


text:
Q: react-native run-android and react-native start Do I have to run react-native run-android and react-native start in my command prompt every time time I reopen my project and emulator?
-- Thanks

A: You usually do. The react-native run-android command might be optional if you do not want to deploy the android native code again (for instance, if you have not made any changes). You will have to launch the application manually and it will try to connect to the packager that starts with react-native start. I am not sure if you can bundle the JS for offline use in debug mode. Maybe you can try the same procedure as in this answer, but with assembleDebug in order to avoid that one.


text:
Q: Redirection mapping in MSMQ. Messages not sent I have a setup where I have a chain of servers that I need to send messages between:
A -> B

On A I have an application which puts a message on a local MSMQ queue. This queue needs to forward the message to a MSMQ queue on B.
The messages do not need to be transactional.
I've enabled HTTP support under the Windows Message Queuing feature. I've added a mapping file under the System32/msmq/mappings folder looking like this:
<redirections xmlns="msmq-queue-redirections.xml">
   <redirection>
     <from>http://A/msmsq/private$/logger</from>
     <to>http://B/msmq/private$/logger</to>
   </redirection>
</redirections>

I am using powershell to send the messages to the queue on A like this:
Get-MsmqQueue -name logger | Send-MsmqQueue -body "test message" -label "test"

When the messages are placed on the queue on A they are not redirected to B, they stay on the A queue.
How should I configure A and B so that messages are forwarded from the MSMQ on A to the MSMQ on B?
UPDATE
In the real scenario there are more servers involved in the chain and each server is only allowed to communicate with the next server in the chain. At the last server in the chain an application reads from the queue on that server and inserts the messages into a DB.

A: You cannot do it the way you are trying. When you send a message to local queue A, that's it. The message has been successfully delivered. Job done.
MSMQ uses outgoing queues to provide the functionality you're after.
Use PowerShell to send the message directly to server B. The message is stored in the outgoing queue on A until it can be delivered to B. Store-and-forward in action.


text:
Q: File Pointers in assembly language I am not able to move pointers in assembly language.I am trying to move my pointer to 4th position in a file and then read and display 3 bytes.
This is my code-
.model tiny
.data
fil1    db      'testing.txt',0
dat1    db      100 dup('$')
dat2    db      100 dup('$')
.code
.startup
        mov     al,02h
        lea     dx,fil1
        mov     ah,3dh
        int     21h

        mov     bx,ax
        mov     al,00
        mov     cx,00
        mov     dx,04
        mov     ah,42h
        int     21h

        mov     bx,ax
        lea     dx,dat2
        mov     cx,3
        mov     ah,3fh
        int     21h
        mov     ah,09h
        lea     dx,dat2
        int     21h

        mov     ah,3eh
        int     21h
.exit
end

This does not display anything on console.
Thanks in advance

A: Your second mov bx,ax (the one right before lea dx,dat2) is incorrect, because ax no longer contains the file handle at that point. Since bx already contains the file handle there you can simply remove that mov.


text:
Q: MySQL database connections broke after DataGrip Upgrade (2021.3.x) After upgrading DataGrip to version 2021.3.2, my existing db connections were broken.  I connect to various DBs (Oracle, MySql) via an SSH tunnel configured to connect through an AWS bastion host.
After the upgrade - DataGrip suggested that the MySql driver had to be updated to Amazon Aurora MySQL driver and it no longer worked to connect where it worked before the upgrade.
Switching between drivers I get two separate errors:
First Error using Amazon Aurora MySQL (suggested driver after update)

[08000][-1] Could not connect to address=(host=localhost)(port=53929)(type=master) : (conn=57522706) could not load system variables[08000][1220] (conn=57522706) Connection is closed.

and second error using original MySQL driver

[08S01]
Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
No appropriate protocol (protocol is disabled or cipher suites are inappropriate).

All of my connections worked immediately prior to the DataGrip upgrade - so seems that upgrade requires new drivers, which have a problem with the way I connect.

A: After some looking - it seems that Aurora has an existing race condition - found my answer here: https://jira.mariadb.org/browse/CONJ-824?focusedCommentId=165412&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-165412
My solution was to change my usePipelineAuth to false (not set prior) in the Advanced tab of the Data Sources configuration:

This fixed my connections and am back in business.

A: Finally, In my case, I fix the issue just replacing/using MariaDB Driver.


text:
Q: Validating multiple HTML form fields with javascript I'm trying to use javascript to validate multiple fields in a HTML form. I can get it to work for a single input, but I cant seem to get it to validate multiple inputs. Here's my JS that works fine -

Here's the HTML
<form name="myForm" action="php/contact.php" onsubmit="return validateForm()" method="post">

then -

Name:
<input type="text" name="Name" id="Name">

But I can't seem to get it to also validate this field -
Address:
<input type="text" name="Address" id="Address">

A: JS

HTML
<form name="myForm" action="php/contact.php" onsubmit="return validateForm()" method="post">

    Name:
    <input type="text" name="Name" id="Name">

    Address:
   <input type="text" name="Address" id="Address">

</form>

Because you're returning false, it will only alert the user of the first incorrect field value. It does this in order for each if statement. They must correct that field and try again.

A: Just copy the existing if statement, but change "Name" to "Address".

Just can't do multiple fields at the same time

If you're saying you want to display a single error message that lists all of the errors then you need to remove the alert() and return statements from each individual field's validation, because obviously the function stops processing as soon as it reaches any return statement. Instead, build up a list of errors, perhaps something like this:
function validateForm() {
    var messages = [];

    if (document.forms["myForm"]["Name"].value == "") {
        messages.push("Name must be filled out");
    }
    if (document.forms["myForm"]["Address"].value == "") {
        messages.push("Address must be filled out");
    }

    if (messages.length > 0) {
        alert(messages.join("\n"));
        return false;
    }
    return true;
}

If you doing the same validation on each field, i.e., checking that they're not empty, then you can use a loop, maybe something like this:
function validateForm() {
    var missingFields = [];

    var fields = document.forms["myForm"].querySelectorAll("input");
    for (var i = 0; i < fields.length; i++) {
        if (fields[i].value == "") {
            missingFields.push(fields[i].name);
        }
    }

    if (missingFields.length > 0) {
        alert("You must enter something in the following fields:\n" + missingFields.join("\n"));
        return false;
    }
    return true;
}

A: If you capture the submit event and then iterate over all of the textual inputs in your form, you can avoid changing this JS code every time you update your HTML:

var inputs = document.forms["myForm"].querySelectorAll('input[type=text]')

document.forms["myForm"].addEventListener('submit', function validate(event) {
    for (var i = 0; i < inputs.length; i++) {
        if (!inputs[i].value) {
            alert(inputs[i].name + ' is required!')
            event.preventDefault()
            return
        }
    }
})
<form name="myForm" action="php/contact.php" method="post">
    Name:
    <input type="text" name="Name" id="Name" required/>

    Address:
    <input type="text" name="Address" id="Address" required>

    <input type="submit" value="Submit"/>
</form>

A: Solved it!
This worked -


text:
Q: How to get ending position of line in React-Konva Sorry, I'm new to coding and am struggling on something I believe is quite basic.
I want to draw a shape via multiple konva line objects. Once I've created a line, instead of manually calculating where the next line should begin, I'm thinking there has to be a way of grabbing the ending position of the last line and setting that as the beginning point of the new line.
As you can see below. I've been calculating the beginning values manually.

import React, { Component } from "react";
import Konva from "konva";
import { Stage, Layer, Rect, Text, Circle, Line, Group } from "react-konva";

class Perimeter extends Component {
  render() {
    return (
      <Stage width={window.innerWidth} height={window.innerHeight}>
        <Layer>
          <Group>
            <Line
              ref="topBar"
              x={450}
              y={150}
              points={[0, 0, 575, 0, 0, 0]}
              stroke="blue"
              strokeWidth={4}
            />
            <Line
              x={450}
              y={150}
              points={[0, 0, 0, 350, 0, 0]}
              stroke="blue"
              strokeWidth={4}
            />
            <Line
              x={1025}
              y={150}
              points={[0, 0, 0, 400, 0, 0]}
              stroke="blue"
              strokeWidth={4}
            />
            <Line
              x={450}
              y={500}
              points={[0, 0, 150, 0, 0, 0]}
              stroke="blue"
              strokeWidth={4}
            />
            <Line
              x={600}
              y={500}
              points={[0, 0, 0, 100, 0, 0]}
              stroke="blue"
              strokeWidth={4}
            />
            <Line
              x={675}
              y={550}
              points={[0, 0, 0, 0, 350, 0]}
              stroke="blue"
              strokeWidth={4}
            />
            <Line
              x={675}
              y={550}
              points={[0, 50, 0, 0, 0, 0]}
              stroke="blue"
              strokeWidth={4}
            />
          </Group>
        </Layer>
      </Stage>
    );
  }
}

export default Perimeter;

A: I checked your code.
But I am having a question now. Why you are going to using multiple Line objects?
I think your purpose is to connect lines. For this purpose, you can add more values to points. This will automatically make a line that connects endpoints to the next point.
Use like this.
<Line x={675} y={550} points={[0, 0, 0, 40, 30, 70, 20, 90, 40, 150]} stroke="blue" strokeWidth={4}/>

I added many points data to Points. Just this. points={[0, 0, 0, 40, 30, 70, 20, 90, 40, 150]}
This means (0,0), (0,40), (30,70), (20,90), (40,150) from start point (675, 550).
Check here result lines
So you don't need to use multiple Line object to draw connected lines.

A:         {lines.map((line, index) => {
          const points = [0, 0]
          line.fromTo.map((item, index) => {
            item.x += line.fromTo[index - 1]? line.fromTo[index - 1].x:0
            item.y += line.fromTo[index - 1]? line.fromTo[index - 1].y:0
            points.push(item.x, item.y)
            return false
          })
          return (
            <Line
              key={index}
              ref={line.ref}
              x={line.start.x}
              y={line.start.y}
              points={points}
              stroke={line.stroke}
              strokeWidth={line.strokeWidth}
            />
          )
        })}


text:
Q: Swift - Restarting an animation after clicking a button I was hoping someone could help.
I have two rectangles which move across the screen. The first constraints for the (rectangles) are activated in my setupViews function which is called in my viewDidLoad.
In my viewDidLayoutSubviews I have an animation function which is called moving the two rectangles.
When I click a button however I would like the rectangles to return to their initial position  and begin the animation from the beginning.
How could I successfully do this?
I initially did not have my animation being called in my viewDidLayoutSubviews, just in another function (which was being called in my viewDidAppear(_ animated: Bool)), however, upon reading it seems as if calling the animation in the viewDidLayoutSubviews might be the best course of action.
I can successfully stop the animation, but getting it to restart again from its initial starting point is proving to be troublesome.
I have tried creating the constraints again in the buttons sender function. But this doesn't seem to do anything, as I'm not sure you can change an elements constraints without reloading the viewDidLoad again.
Below is my code………
override func viewDidLoad() {
    super.viewDidLoad()
    setupViews()
}

func setupViews() {

    self.view.addSubview(backgroundImageView)
    self.backgroundImageView.addSubview(contentView)
    self.backgroundImageView.addSubview(slideDownTintedWhiteView)
    self.backgroundImageView.addSubview(restartSlidingAnimation)

self.contentView.snp.makeConstraints { (make) in
        make.edges.equalToSuperview()
    }

self.slideDownTintedWhiteView.snp.makeConstraints { (make) in
        make.top.equalToSuperview()
        make.leading.equalToSuperview()
        make.trailing.equalToSuperview()
        make.bottom.equalTo(backgroundImageView.snp.top)
    }

self.restartSlidingAnimation.snp.makeConstraints { (make) in
        make.centerX.equalToSuperview()
        make..centerY.equalToSuperview()
        make.width.equalTo(10)
        make.height.equalTo(10)
    }

self.restartSlidingAnimation.addTarget(self, action: #selector(restartAnimationFunction(_:)), for: .touchUpInside)

}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    UIView.animate(withDuration: 10, delay: 0, animations: {

    //Red View:

    self.contentView.frame = CGRect(x: self.contentView.frame.origin.x, y: self.contentView.frame.height, width: self.contentView.frame.width, height: self.contentView.frame.height)

    //White View:

    self.slideDownTintedWhiteView.frame = CGRect(x: self.contentView.frame.origin.x, y: 0, width: self.contentView.frame.width, height: self.contentView.frame.height)

    }, completion: nil)
}

restartAnimationFunction() {
   // Here is obviously where I need to somehow re-establish the constraints of the rectangles back to their original location or somehow start the animation from the beginning.
}

func stopContentViewAnimation() {
   // This is where I am able to stop the animation (called from another button)

    pausedTime = self.contentView.layer.convertTime(CACurrentMediaTime(), from: nil)
    self.contentView.layer.speed = 0.0
    self.contentView.layer.timeOffset = pausedTime
    pausedTime = self.slideDownTintedWhiteView.layer.convertTime(CACurrentMediaTime(), from: nil)
    self.slideDownTintedWhiteView.layer.speed = 0.0
    self.slideDownTintedWhiteView.layer.timeOffset = pausedTime
}

Thanks for any help you can provide.

A: 1- First the animation should not be inside viewDidLayoutSubviews as it's being called many times , best place for it is viewDidAppear
2- You don't set any constraints to backgroundImageView
3- To animate a child remove it's constraints from itself and from it's parent
self.backgroundImageView.removeConstraints(self.backgroundImageView.constraints)
self.contentView.removeConstraints(self.contentView.constraints)
self.slideDownTintedWhiteView.removeConstraints(self.slideDownTintedWhiteView.constraints)
self.restartSlidingAnimation.removeConstraints(self.restartSlidingAnimation.constraints)

4- Re construct the other case constraints and when ready to animate put
self.view.layoutIfNeeded()

inside the animation block
OFF course I don't recommend removing all constraints and constructing them again , but you can have a reference to the constraints you want to change and alter their constants , but for a beginner this may be good to go


text:
Q: Mockito test - reason of failing my testcase Learnt JUnit yesterday, learning Mockito today
I wrote a simple class;
public class FileOperations {
    public boolean autoMove(){
        List<byte[]> patterns = getListofPatterns();
        for(byte[] pattern: patterns){
            System.out.println(new String(pattern));
            if(seekInHeader(pattern)){
                //logic to move file of specific folder of specific extension
                return true;
            }
        }
        return false;
    }

    public boolean seekInHeader(byte[] pattern){
        return false;
    }

    public List<byte[]> getListofPatterns(){
        return null;
    }
}

And trying to test it as follows
@Test
public void autoMoveTest(){
    FileOperations fo = mock(FileOperations.class);//stub
    List<byte[]> dummyPatterns = new ArrayList<byte[]>();//specify stub value
    dummyPatterns.add("amit".getBytes());

    when(fo.getListofPatterns()).thenReturn(dummyPatterns);
    when(fo.seekInHeader(anyString().getBytes())).thenReturn(true);

    System.out.println(new String(fo.getListofPatterns().get(0)));
    System.out.println(fo.seekInHeader("amit".getBytes()));
    System.out.println(fo.autoMove());
    assertTrue(fo.autoMove());
}

Output:

amit
true
false

As I set seekHeader() to return true. Why fo.autoMove() is returning false?

A: With a mock, none of the methods actually do anything, unless you explicitly specify that they should.  The whole point of a mock is that the functionality has been replaced, either by no functionality at all (the default), or by functionality that you stub.
The default functionality for a mock is that every method does nothing at all, then returns either false (for booleans), zero (for numeric primitives), an empty collection, or null.  So in this case, autoMove will always return false, unless you stub it to do something different.
The whole idea of using mocks is that you don't mock the class that you're trying to test.  Instead, you mock other classes that it interacts with.  So if a method of class A calls a method of class B, and you wish to test class A; then you would use a mock of class B, and stub the method of B that gets called.

A: You can do it using spy as follows;
@Test
    public void autoMoveTest(){
        FileOperations fo = new  FileOperations("");
        FileOperations spyFo = spy(fo);

        List<byte[]> dummyPatterns = new ArrayList<byte[]>();//specify stub value
        dummyPatterns.add("amit".getBytes());

        when(spyFo.getListofPatterns()).thenReturn(dummyPatterns);
        when(spyFo.seekInHeader(anyString().getBytes())).thenReturn(true);//stubbing a method

        assertTrue(spyFo.autoMove());
    }

Why your code is failing
Because you were not stubbing fo.autoMove(). When you call a real method with mocked object, actual method never runs. It just returns default value of return-type or stubbed value. So even if you return true from autoMove(), it will return false for a mock object.


text:
Q: laravel syntax error, enexpected ',' , expecting ';' I tried to fix this but don't know how

public function render()
{
    return view('livewire.home')->extends('layouts.app')->section('content'),[
        'products' => Product::take(3)->get()
    ];

It said that the syntax is error,

unexpected ',', expecting ';'

I'm newbie to Laravel so I couldn't write the correct syntax. Please let me know.

A: As you can see in the docs, to pass variables to the view, you need to set the second parameter in the method view() as the array of data.
public function render()
{
    return view('livewire.home', [
        'products' => Product::take(3)->get()
    ])->extends('layouts.app')->section('content');
}


text:
Q: Hypothesis H Sieve Is the following little sieve for generating primes satisfying Hypothesis H valid? Known? Obvious?
Let $F$ be a set of functions satisfying Hypothesis H and let $I$ be the integers greater than 1 (2 in some cases). For each $f \in F$ let $I_j(f)$ be the integers $i$ for which $f(i) \in (I+j)/jI$.  Finally, let $F_k$ be the intersection of $I_j(f)$, j=1(1)k, $f \in F$ and $p_k = 1 + \min F_k$.  Then $f(p_k)$ is prime for each $f$ in $F$.
Cheers, Scott
P.S. I'm happy to send along a Mathematica notebook that implements the sieve to anybody interested.


text:
Q: RegEx to find all symbol 'y' between consonant letters I need to find all symbol 'y' between consonant letters:
For example in 'tyrypyr' i need to find y at 2, 4 and 6 position.
In 'tyraypyr' - in 2 and 7 and NOT in 5 because a in front of y.
I try /[BCDFGHJKLMNPQRSTVWXZ]y[BCDFGHJKLMNPQRSTVWXZ]/gi pattern. But it is not capture middle y in 'tyrypyr' (find only 'tyr' and 'pyr')
If add * in expression like /[BCDFGHJKLMNPQRSTVWXZ]*y[BCDFGHJKLMNPQRSTVWXZ]/gi, but incorrectly  match y after a in tyraypyr.
What is the right way to find symbol y between consonant letters. And, if it is possible just y (without consonant letters i.e. y instead 'tyr' and 'pyr'). Because I want find this y to replace it with another symbols.

A: With lookarounds :
(?<=[BCDFGHJKLMNPQRSTVWXZ])y(?=[BCDFGHJKLMNPQRSTVWXZ])

See it in action here.
This works when your regex doesn't because the lookahead is a 0-width match which doesn't forward your match pointer, while your regex was consuming the next consonant.

A: You need positive Lookahead and Lookbehind
/(?<=[BCDFGHJKLMNPQRSTVWXZ])y(?=[BCDFGHJKLMNPQRSTVWXZ])/gi

Here it is
Your match was 3 characters long. tyrypyr is 7 characters long, so you could only find it twice at most.


text:
Q: Is there HTML tag like Div but doesn't interupt other Divs I am trying to make a table of cells where a few can be logically grouped together and when hovered over they change color.
I started using a HTML tagged table but quickly learnt you cannot nest divs or spans inside, so it would have meant assigning each individual cell (256 cells) a class and possibly a javascript function or two.
I went with a div constructed table and it seemed better at first, however trying to logically group cells causes the table to get all messed up:
The end goal is of 256 cells some of them may be stringed together, for example cells 16-31 (entire second row) or cells 30-33 (first few cells of another row). Each group of cells will have a color and the entire group will change color when any of the cells are hovered over.

My main question is, is there an "invisible" html tag that won't get put around the place (without that id "special" div, the table layout is as expected). So far I have tried div (pictured), span and section. Alternatively a better suggested solution would also be helpful.

body {
  font-family: Consolas, Courier New, Courier, monospace;
}
.divTable {
  border: 2px solid #999999;
  display: table;
  width: auto;
}
.divTableRow {
  display: table-row;
}
.divTableCell,
.divTableHead {
  vertical-align: middle;
  text-align: center;
  border: 1px solid #999999;
  display: table-cell;
  height: 25px;
  width: 25px;
  /*padding: 3px;*/
}
.divTableHeading {
  background-color: beige;
  font-weight: bold;
}
.divTableBody {
  display: table-row-group;
}
/*  */

/*  */

/*  */

.divTableCell {
background-color: green;
}

#special .divTableCell {
background-color: red;
}

body {
  font-family: Consolas, Courier New, Courier, monospace;
}
th {
  background-color: beige;
}
.divTableCell:hover {
  cursor: pointer;
}
.endrow .divTableCell:hover,
.divTableHeading .divTableCell:hover {
  cursor: default;
}
.endrow,
.reserved {
  background-color: lightpink;
}
/*.reserved:hover {
        background-color: red;
    }*/

+

00

0

16

32

48

30

31

32

33

34

35

36

37

38

39

3A

3B

3C

3D

3E

3F

0

0

0

0

0

0

0

0

0

0

0

0

256

A: Using jQuery or similar to find the 38th row and highlight the special divs - do note I did not use the ID but just added a class. IDs must be unique.
Now no need to wrap in special divs. All changes are in the object I called highlight

$(function() {
  var highlight = { "row":"48", "cells":[1,2,3,5] }
  var cells = $(".divTableHeading:contains('"+highlight.row+"')").siblings();
  $.each(highlight.cells,function(_,i) {
    cells.eq(i).addClass("special")
  });
  $(".divTable .special").hover(function() {
    $(this).toggleClass("reserved");
  });
});
body {
  font-family: Consolas, Courier New, Courier, monospace;
}
.divTable {
  border: 2px solid #999999;
  display: table;
  width: auto;
}
.divTableRow {
  display: table-row;
}
.divTableCell,
.divTableHead {
  vertical-align: middle;
  text-align: center;
  border: 1px solid #999999;
  display: table-cell;
  height: 25px;
  width: 25px;
  /*padding: 3px;*/
}
.divTableHeading {
  background-color: beige;
  font-weight: bold;
}
.divTableBody {
  display: table-row-group;
}
/*  */

/*  */

/*  */

.divTableCell {
background-color: green;
}

.special  {
background-color: red;
}

body {
  font-family: Consolas, Courier New, Courier, monospace;
}
th {
  background-color: beige;
}
.divTableCell:hover {
  cursor: pointer;
}
.endrow .divTableCell:hover,
.divTableHeading .divTableCell:hover {
  cursor: default;
}
.endrow,
.reserved {
  background-color: lightpink;
}
/*.reserved:hover {
        background-color: red;
    }*/

+

00

0

16

32

48

30

31

32

33

34

35

36

37

38

39

3A

3B

3C

3D

3E

3F

0

0

0

0

0

0

0

0

0

0

0

0

256

A:
My main question is, is there an "invisible" html tag that won't get put around the place

Answer is Yes, CSS should provide it, ... but:
For firefox you could use (https://samrueby.com/2015/02/09/firefox-is-releasing-support-for-css-display-contents/ )
display:contents;

<display-box>
These values define whether an element generates display boxes at all.
Value     Description

contents   These elements don't produce a specific box by themselves. They are replaced by their pseudo-box and their child boxes.
none       Turns off the display of an element (it has no effect on layout); all descendant elements also have their display turned off. The document is rendered as though the element did not exist.
To render an element box's dimensions, yet have its contents be invisible, see the visibility property.

for the other one ,you'll need jquery to clone child and remove #special . You will also need to add a class if you need special  styling :
$('#special>div').clone().insertAfter('#special').addClass( "special" );
$('#special').remove();

Demo below:

// for none firefox browsers
$('#special>div').clone().insertAfter('#special').addClass( "special" );
$('#special').remove();
$( ".divTableCell" ).each(function() {
  $('.special' ).addClass( "hover" );
});
#special {
  display:contents;
}

#special .divTableCell ,.divTable .special{
background-color: red;
}
.divTable:hover .special.hover {background:turquoise;}

body {
  font-family: Consolas, Courier New, Courier, monospace;
}
.divTable {
  border: 2px solid #999999;
  display: table;
  width: auto;
}
.divTableRow {
  display: table-row;
}
.divTableCell,
.divTableHead {
  vertical-align: middle;
  text-align: center;
  border: 1px solid #999999;
  display: table-cell;
  height: 25px;
  width: 25px;
  /*padding: 3px;*/
}
.divTableHeading {
  background-color: beige;
  font-weight: bold;
}
.divTableBody {
  display: table-row-group;
}
/*  */

/*  */

/*  */

.divTableCell {
background-color: green;
}

body {
  font-family: Consolas, Courier New, Courier, monospace;
}
th {
  background-color: beige;
}
.divTableCell:hover {
  cursor: pointer;
}
.endrow .divTableCell:hover,
.divTableHeading .divTableCell:hover {
  cursor: default;
}
.endrow,
.reserved {
  background-color: lightpink;
}
/*.reserved:hover {
        background-color: red;
    }*/

+

00

0

16

32

48

30

31

32

33

34

35

36

37

38

39

3A

3B

3C

3D

3E

3F

0

0

0

0

0

0

0

0

0

0

0

0

256

Codepen to play with : uncomment jquery script if not running under firefox


text:
Q: NPM module "only refers to a type, but is being used as a value here." in Ionic 2 / Angular 2 I'm trying to import the npm module "ajv" into my Ionic 2 (Angular 2) project.  (https://epoberezkin.github.io/ajv/)
I ran "npm install ajv --save", then made the following changes to my app.modules.js file:
import { Ajv } from 'ajv';

...
providers : [
    Ajv,
    ...
]

When I compile, however, I get the error:
'Ajv' only refers to a type, but is being used as a value here.
c:/Users/me/Documents/Ionic/MyApp/src/app/app.module.ts

Is there a better way to pull in this library?

A: The providers array in NgModule is for use with @Injectable components or similarly functional "providers" or "services" in other speak. This library does not appear to conform to that design.
It's likely that all you really want to do is use the import within your application component, rather than in AppModule. By import I mean the simple ES6 style import of "symbol" and then direct usage in code.
So for example in example.component.ts:
import { Component } from '@angular/core';
import { Ajv } from 'ajv';

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css']
})
export class ExampleComponent {

  myMethod() {
     // Just use Ajv here
  }

}

No need to put this in the decorator arrays.
If an imported third party library is rather something you want to use in a "service like manner", then by all means wrap it as an @Injectable service, but the consumption will stay much the same as the the above example.


text:
Q: In Eclipse, with multiple builders on a project, how can I have all build console displayed? Very similar to the #2 option at this question, I'm wondering how I can have all the stdout/stderr output maintained when I have multiple builders for a project.
As it is, each builder clears the console then starts writing its messages to console, but by the end I want to see all the output from all my builders. Logging to a file isn't ideal because my users won't check there.


text:
Q: how can i get a part of string from xml in batch file First, I'm reallly beginner at batch or cmd syntax.
So my syntax looks very foolish, please read this with a broad mind. Thx!
I want to get a value from my specific local xml file and i want to get a part of that value. Because, I have to compare with that value and specific other value.
well, I found it with all my effort. But I couldn't 100%.
Please read this code.
fc /b "C:\e\e.xml" "C:\Users\%username%\Documents\e\e.xml" return errorlevel

set usr_name=%username:~-2,2%
set _name=

IF %ERRORLEVEL% EQU 0 (
    for /f "tokens=2delims=<>" %%i in ('find "KEY" "c:\e\e.xml"') do echo %%i
    REM echo ^<username^>%usr_name%^</Setup_Date^>^<substr^>%%i^</substr^> > "C:\e\test.xml"

    echo ^<username^>%usr_name%^</username^>^<substr^>%_name%^</substr^> > "C:\e\test.xml"
    if %%i:~-4,2 == %usr_name% (

    REM echo ^<username^>%usr_name%^</username^>^<substr^>%%i:~-4,2%^</substr^> > "C:\e\test.xml"
    echo YES
    ELSE (
echo NO
cscript no.vbs
)

And this is my xml file.
I want to get D4 of KEY tag (D4, It occupies 2 letters from the 4th from the back.)
<Date>2020-08-13</Date><Setup>Zs#ol9fEV9pA</Setup>
<KEY>WY(T5XD4h4<KEY>

the problem is this
REM echo ^<username^>%usr_name%^</Setup_Date^>^<substr^>%%i^</substr^> > "C:\e\test.xml"

echo ^<username^>%usr_name%^</username^>^<substr^>%_name%^</substr^> > "C:\e\test.xml"

if value i = abcdef
I can get the value from xml file abcdef, using REM sentence.
But I can't get the part of variable i.
when i use second sentence or other expressions such as %i:~-4,2% etc. (because i want to compare using that part of value. %i:~-4,2% = cd)
I can't print any values, just print nothing.
Is there a way to solve this problem?
As i said earlier, I have a very tiny knowledge about batch,
So let me know everything you know. Or if this way couldn't solve without using other library or xpath.bat, please tell me as I have to find another way.
Thank you.

A: %%i is only defined inside the for loop. As you wrote it, the whole loop consists of only echo %%i. Then the loop ends and %%i isn't defined anymore.
As others already noted, cmd isn't really a good tool to work with when it comes to XML files (and look-alikes).
But if you are willing to use an external tool, it gets easy. Just a simple REGEX search for a string between <KEY> and <KEY> (shouldn't the second be </KEY>?):
for /f "delims=" %%a in ('^<"c:\e\e.xml jrepl ".*<KEY>(.*)<KEY>.*" "$1" /a') do set "key=%%a"
echo Key: %key%, Subkey:%key:~-4,2%

jrepl.bat was programmed by dbenham.


text:
Q: iOS 8: Autorotation is not working without storyboard So I am trying to start a project w/o Storyboards and I can't seem to figure out why the UIWindow is not passing autorotation commands to the root view controller.  With storyboards, the autorotation works.  If I create the window programmatically, autorotation does not work.

This is how I instantiate the window in the App Delegate:
window = UIWindow(frame: UIScreen.mainScreen().bounds)
if let window = window {
    window.backgroundColor = UIColor.whiteColor()
    window.makeKeyAndVisible()

    let nc: SignInViewController = UIStoryboard(name: "Main", bundle: nil)
            .instantiateViewControllerWithIdentifier("SignInViewController") as SignInViewController
    window.rootViewController = nc
}

Thanks!

A: Are you using storyboards? If so, you may have old code in your application didFinishLaunchingWithOptions method.
Try removing the following line of code and any others to do with UIWindow:
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
Just need to remove above line from AppDelegate.m file.

A: I think your code is correct and you are seeing one (of many) bugs of XCode 6.1.
I tried a very simple app with 6.1 using your code and I could experiment the bug. Then I downgraded to 6.0.1 and the autorotation of my app was perfect.
I advice you to downgrade to XCode 6.0.1 and retry your app.
You can download it from here: Apple Downloads

A: Marked answer is to downgrade to XCode 6.0.1 - I do not recommend it.
1) If you do not use storyboards (Answer for this topic !!)
Go to -> Project Name -> Targets -> Project Name -> Deployment Info -> Main Interface -> Make it Empty

2) In case you use storyboards (not the main answer)
your AppDelegate should look like ...
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
{
    return true
}

A: Make sure you enable the device orientations in the project's General settings
in xcode 6.1, click your main project folder, General tab
Scroll down to Device Orientation, enable "Portrait", "Landscape Left", "Landscape Right"
See iOS 8.1 auto rotation for a picture of the Device Orientation settings

A: i just solved the problem in my project.
for me, the solution was to remove the animation from the following code:
[self presentViewController: root animated: animated completion:^{
    [AppDelegate singleton].window.rootViewController = root;
 }];

which is now just
[AppDelegate singleton].window.rootViewController = root;
i don't know if this answers your question, but it solved my instance of what i think is a shared problem.


text:
Q: Windows Forms DataBinding CheckedListBox I have experience with ASP, but completely new to WinForms.  What I'm trying to do is this: I have a CheckedListBox on Form1 that is linked to a binding source that is linked to a SQL database.  I have another Form (Form2) that pops up upon clicking on an "Add" button, and then they can add a record.  What I would like to have happen is as soon as they Add the record in Form 2, the CheckedListBox in Form1 updates as well.  I've tried DataSource and DisplayMember properties but that doesn't seem to do the trick.  Can someone point me in the right direction?
If anyone knows of a better way to do this, I'm also all ears.  Thanks.

A: Can you access Form1 from Form2? If you can the easiest way would be to just ad a line in button pressed that checks the check-box
something like form1.checkboxName.Checked = true;
it would help if you showed some of your code :)

A: Take a look at a previous answered post.
I directed the person to call the second form with a parameter from the first... Then the second form can utilize it directly. You could do this by passing in the first form itself and have it do almost anything... but in its simplest form, allow you to preserve the form.  Then, in the click / add / save / whatever of the second form, reference the first form and set it directly (or indirectly via a public property getter/setter).

A: I figured out the answer to my question.  I handled everything on form1.  I created a method called refreshData, and when I clicked my icon to pop up form2, I waited for the Dialog Result of form2 to be OK, then I called the refreshData method.  Hope this helps someone else:
private void pictureBox1_Click(object sender, EventArgs e)
    {
        form2 box = new form2();
        using (box)
        {
            box.ShowDialog();
            if (box.DialogResult == DialogResult.OK)
            {
                refreshData();
            }
            box.Dispose();
        }
    }
    private void refreshData()
{
ADODB.Recordset rs = new ADODB.Recordset();
           ADODB.Connection adoCon = new ADODB.Connection();
           adoCon.Open("put Connection String Here");
           rs.Open("Put Select query Here",adoCon,ADODB.CursorTypeEnum.adOpenStatic,ADODB.LockTypeEnum.adLockOptimistic);
           DataSet myDS = new DataSet();
           OleDbDataAdapter da = new OleDbDataAdapter();
           da.Fill(myDS, rs,"MyTable");
           chkList1.DataSource = null;
           chkList1.DataSource = myDS.Tables[0];
           chkList1.DisplayMember = "Put Field to Display in CheckList here";
}


text:
Q: TypeScript: Map union type to another union type Is it possible to map a union type to another union type in TypeScript?
What I'd Like to be able to do
e.g. Given a union type A:
type A = 'one' | 'two' | 'three';

I'd like to be able to map it to union type B:
type B = { type: 'one' } | { type: 'two'} | { type: 'three' };

What I have tried
type B = { type: A };

But this results in:
type B = { type: 'one' | 'two' | 'three' };

which is not quite what I want.

A: You can use conditional type for distributing over the members of the union type (conditional type always takes only one branch and is used only for its distributive property, I
 learned this method from this answer)
type A = 'one' | 'two' | 'three';

type Distribute<U> = U extends any ? {type: U} : never;

type B = Distribute<A>;

/*
type B = {
    type: "one";
} | {
    type: "two";
} | {
    type: "three";
}
*/


text:
Q: How to merge cells in a single column? Given the sample code using ag-grid with Vue 3
<script setup lang="ts">
import "ag-grid-community/dist/styles/ag-grid.css";
import "ag-grid-community/dist/styles/ag-theme-alpine.css";
import { AgGridVue } from "ag-grid-vue3";
import { ref } from "vue";

const columnDefs = ref([
  {
    field: "person",
  },
  {
    field: "car",
  },
]);

const rowData = ref([
  {
    person: "person-1",
    car: "car-1",
  },
  {
    person: "person-1",
    car: "car-2",
  },
  {
    person: "person-1",
    car: "car-3",
  },
  {
    person: "person-2",
    car: "car-4",
  },
  {
    person: "person-3",
    car: "car-5",
  },
  {
    person: "person-3",
    car: "car-6",
  },
]);
</script>

<template>
  <ag-grid-vue
    style="width: 500px; height: 500px"
    class="ag-theme-alpine"
    :columnDefs="columnDefs"
    :rowData="rowData"
  >
  </ag-grid-vue>
</template>

You will get the following output

I could group the table based on person but is there a way to merge cells in a single column?

I think I can't use row-spanning for a single column definition because inside the rowSpan function it is not possible to tell ag-grid to combine multiple cells of a single column.
Any ideas?

A: After spending a few hours on this requirement, I came up with the solution.
Here are the steps which I performed :

*

*To implement rowSpan, You have to manipulate the rowData so that it will contain the person property only in the first occurance object. As a result, When we will apply the rowSpan based on the length it will not take that length for each same person name. This is how I manipulated the rowData :

    const uniq = {};
    const rowData = [{
      person: "person-1",
      car: "car-1",
    }, {
      person: "person-1",
      car: "car-2",
    }, {
      person: "person-1",
      car: "car-3",
    }, {
      person: "person-2",
      car: "car-4",
    }, {
      person: "person-3",
      car: "car-5",
    }, {
      person: "person-3",
      car: "car-6",
}];

rowData.forEach(obj => {
    !uniq[obj.person] ? uniq[obj.person] = true : delete obj.person;
});

console.log(rowData);

*Now, Created a rowSpan function which is basically used to return the length of the objects contains occurrence of same person names.
function rowSpan(params) {
  const person = params.data.person;
  const gridData = getData(); // getData() with return the original rowData array.
  return gridData.filter((e) => e.person === person).length;
}

*At the end, for styling the rowSpan columns. I used these styles (refer from here)
.show-cell {
  background: white;
  border-left: 1px solid lightgrey !important;
  border-right: 1px solid lightgrey !important;
  border-bottom: 1px solid lightgrey !important;
}

This is how the columnDefs for person object looks like :
{
  field: "person",
  rowSpan: rowSpan,
  cellClassRules: { 'show-cell': 'value !== undefined' }
}

Live Demo : Row Spanning Demo

A: Are you sure row-spanning will not work? Can you try to implement this?
function rowSpan(params) {
  const person = params.data.person;
  return rowData.value.filter((e) => e.person === person).length;
}

const columnDefs = ref([
  {
    field: "person",
    rowSpan: rowSpan,
  },
  {
    field: "car",
  },
]);


text:
Q: How to leave the data in database if edit form field is left empty I getting many inputs from a user in create a form(>50 fields) where I would like to edit those details in edit form.
I have made all the fields nullable so that while editing, the fields are left alone,
Controller:
public function update(Request $request, $id)
{
     $engineers = Engineers::findOrFail($id);
     $engineers->input1 = $request->input('input1');
     $engineers->input2 = $request->input('input2');
     $engineers->input3 = $request->input('input3');
     $engineers->input4 = $request->input('input4');
     $engineers->save();
}

When I try to edit input2 leaving everything blank, all the other fields are blank in the database.
Another option I found out was
public function update(Request $request, $id)
{
    $engineers = Engineers::findOrFail($id);
    if($request->input('input1')){
        $engineers->input1 = $request->input('input1');
    }
    if($request->input('input2')){
        $engineers->input2 = $request->input('input2');
    }
    if($request->input('input2')){
        $engineers->input2 = $request->input('input2');
    }
     if($request->input('input2')){
        $engineers->input2 = $request->input('input2');
    }

    $engineers->save();
}

By doing the above, The corresponding record changes and all the other fields are left intact.
I also noticed that an empty edit form can be submitted.
Are there any other better approach to this?

A: filled method of $request is used in this case.
if($request->filled('name')){
  //if name is present in request object and not empty.
}

Read more about it here

A: Do it like this, this step looks short as well,
$engineers = Engineers::findOrFail($id);
$engineers->fill($request->all())->save();

A: You can filter the input before filling the entry e.g.:
$engineers = Engineers::findOrFail($id);
$engineers->fill(array_filter($request->all()))->save();

This will remove all falsy entries i.e. null but also 0 and ''
If you want to strictly remove nulls then you can do :
$engineers = Engineers::findOrFail($id);
$engineers->fill(array_filter($request->all(), function ($value) {
        return $value !== null;
}))->save();


text:
Q: Checking agents in a Seize Block I wonder how I can trigger a conditional state chart transition (located in an agent, Patient) by checking if a queue (located in Main in a Seize Block) contains patients with a certain characteristic (p_contaminated, boolean parameter here should be true in order for the transition to trigger). I.e., if the queue contains one Patient with p_contaminated = true, the statement should yield true in order to trigger the transition.
Picture showing the Main chart and the Patient chart. Emphasizing (with red) the mentioned Seize Block and the conditional transition that is wanted to be triggered

A: Do not use conditional transitions, ever. They have some quirks (not bugs but easy to work in unexpected ways if you are no crack) and can deteriorate your model performance massively.
You can always replace them with message-based transitions.
In your case, have setup as below:

every x seconds, leave Treatment with a timeout transition. Check your patient queue in AnyPatientFound and if true, move to GoToHallway, else return to Treatment
AnyPatientFound should call a boolean function anyPatientContaimated that loops through all patients in your queue and returns true if any is contaminated, else false.