text:
Q: How to simplify if statement into loop I'm currently doing this if statement here, I wanted to simplify it into a loop. I try putting it into an array for the client_fullname and etc. but turns out only string form can be done. I wanted to simplicity this coding into a loop but i have no idea how to do it.
<tr class="sale" data-id="<?= $sale['id']; ?>">
                    <?= $pagination->offset + $key + 1; ?>

                    <?php if ($checked_columns['client_fullname']): ?>
                    <?= $sale['client_fullname']; ?>
                    <?php endif; ?>

                    <?php if ($checked_columns['client_email']): ?>
                     <?php echo $sale['client_email']; ?>
                    <?php endif; ?>

                    <?php if ($checked_columns['client_phone_number']): ?>
                     <?php echo $sale['client_phone_number']; ?>
                    <?php endif; ?>

                    <?php if ($checked_columns['total_amount']): ?>
                    <?= $sale['total_amount']; ?>
                    <?php endif; ?>

                    <?php if ($checked_columns['total_sales_amount']): ?>
                    <?= $sale['total_sales_amount']; ?>
                    <?php endif; ?>

                    <?php if ($checked_columns['first_date_buy']): ?>
                    <?= $sale['first_date_buy']; ?>
                    <?php endif; ?>

                    <?php if ($checked_columns['created_at']): ?>
                    <?= $sale['created_at']; ?>
                    <?php endif ?>

A: You can reference the below example to achieve your desired output.
<?php
foreach($checked_columns as $key=>$column){
    if ($column){
    if ($key == 'client_email' || $key == 'client_phone_number'){?>
     <?= $sale[$key]; ?>
    <?php }else{?>
    <?= $sale[$key]; ?>	<?php
    }
}


text:
Q: Will an electrolytic capacitor work reliably with 0 VDC and 100 mVAC? I ran across an instrumentation amplifier datasheet from "THAT Corporation", and noticed the polarized capacitor in series with the gain resistor:

It is a typical 3 op-amp in-amp, so the differential input will be seen across the gain resistor, and C1 is meant to avoid changes in dc output offset with gain.
Now, the input is typically a microphone, and the AC voltage can reach 100mV or even a bit more.
For a 2k gain resistor and 6.8uF cap, 10 Hz will be seen with -3dB across the cap: 70 mVAC.
So the question is, will an electrolytic survive and work properly during these small negative excursions?

A: Yes, it appears that this is OK for such small voltages.
According to CDE's Application Guide, Aluminum Electrolytic Capacitors:

Aluminum electrolytic capacitors are polarized and must be
  connected in the correct polarity. They can withstand
  reverse voltages up to 1.5 V.

If you are uncomfortable with that (from the same application guide):

If two, same-value, aluminum electrolytic capacitors
  are connected in series, back-to-back with the positive
  terminals or the negative terminals connected, the
  resulting single capacitor is a non-polar capacitor with
  half the capacitance.

For solid Tantalum capacitors, from Vishay's Solid Tantalum Capacitors:
Frequently Asked Questions (FAQs):

Tantalum capacitors are capable of withstanding peak voltages in the reverse direction equal to 10 % of the DC rating at
  + 25 °C and 5 % of the DC rating at + 85 °C.

Also, you may not want to consider a ceramic capacitor for this due to the piezoelectric effects: Ceramic vs. Film Capacitor: Which one is preferred in audio circuits?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Detect all computers running a service on a network I'm trying to write a file synchronization protocol presently (consider it a hobby, I know there are plenty of file synchronizers out there) and I wanted to create a way to automatically sync things across a network. I've heard that this can be accomplished via UDP, but I'm totally oblivious to how to accomplish it.
If I use UDP, will I still have to ping 192.168.X.0 - 192.168.X.255? Or does UDP find a way around that? Is there a way I can in some way bypass firewalls so I don't have to go to each computer on my network and allow incoming traffic to the given UDP port?
Forgive me for being so oblivious on this, this is my first time trying to implement a protocol ;)

A: If you're interested in the local network only, and assuming the client knows the server's port number, the client could broadcast a UDP message, to which the server would reply with a unicast message, thus establishing communications.
Or, you could consider using some existing discovery protocol, such as Bonjour/Zero Conf, or UPnP (Universal Plug 'n Play) to locate your devices.
Firewalls are a separate issue, which in any case you must make sure are open to your discovery packets.

A: You can use nmap to scan hosts to see if they have a service listening on a certain port.

There are very few circumstances in which UDP is preferable to TCP:

*

*UDP doesn't work so well for two-way communications. You have to make up your own query/answer association. Even when you're sending data in one direction, you often want the recipient to acknowledge, which is a datum sent in the other direction.

*UDP isn't reliable. If a packet is lost or duplicated, tough.

*UDP travels by packet. If your packet is too big and is systematically discarded, tough.

*UDP introduces some security issues, such as making distributed denials of service easy. For this reason many firewalls block or severely restrict it.

*Few protocols use TCP, so closed-by-default firewalls just don't let any of it through (apart from DNS, which they tightly constrain).

*UDP doesn't do congestion management. If you flood the network, your packets will be discarded randomly. TCP, on the other hand, will restrict the debit to what the network can bear.

You can send a UDP packet to a machine and see if something answers, of course. You can even send a UDP broadcast and see how far it goes, or send a UDP multicast and hope it arrives.
There are two requirements for a network packet (UDP or TCP) to trigger an action on the destination machine. First, all routers and firewalls on the packet's path must have let the packet through to the destination. Second, there must be an application listening on the destination machine. This could be your synchronizer, or a service starter such as inetd, or a server for a higher-level protocol that you synchronizer would embed into such as HTTP(S) or SSH.
If your packets are blocked by a firewall, then in principle there's no way to go around this. Otherwise the firewall just isn't doing its job. Of course, in practice, firewalls do have holes, for example UPnP (). You're more likely to be able to bypass a firewall over TCP (especially over HTTPS, which firewalls generally can't block selectively so have to let by to permit web browsing) than over UDP.
If there's nothing listening on the destination port, again, you won't be able to take control of the target machine to make it execute your application. (That would be the epitome of insecurity, like some older unpatched versions of Windows.) That's an advantage of piggybacking over a common generalist protocol like SSH: you just have to enable one service, and then you can do what you want over it, including file synchronization.


text:
Q: Node.js GraphicsMagic: check installation & functionality I am working with the Node.js module gm (Github)  for GraphicsMagic (Link).
How can I determine whether the required GraphicsMagic software for the gm module is installed & fully functional on the current node.js machine or not? (I want to check this on the initialization process of my server)

A: You can call the command line tool and check the output.
var exec = require('child_process').exec;

exec("gm", function (error, stdout, stderr) {
  // Validate the output with one of the parameters.
});


text:
Q: error selecting div element with a particular id - beginner at jQuery, javascript I am playing around with selecting elements in the DOM using jQuery, and I tried the following:
$(document).ready(function() {

      $("a").toggle(function(){
        $("div[@id=SomeID]").hide('slow');
        },function(){
        $("div[@id=SomeID]").show('fast');
       });

});

And in the html source, I do have this section:
<div id="SomeID">

      <!-- div code -->

</div>

However, when I click on an anchor tag I get the following error:
Syntax error, unrecognized expression: div[@id=SomeID]
Any ideas as to what is going wrong here? I'm a beginner at jQuery and javaScript, so would appreciate any help.

A: To select an element by its id in jQuery, use the same syntax as in CSS:
$('#someID');

To use the attribute-equals selector format then use:
$('div[id="someID"]');

References:

*

*jQuery selectors.

A: You are using the Wrong selector.. Id has to be prepended with a #
These are valid
$("#SomeID").hide('slow'); //  element with id SomeID , can be any element
$("div#SomeID").hide('slow'); //  Div with id SomeID
$("div[id=SomeID]").hide('slow'); //  Div with id SomeID
$("div[id^=SomeID]").hide('slow'); //  Div id that starts with SomeID
$("div[id*=SomeID]").hide('slow'); //  Div id that has SomeID in its id attribute
$("div[id=SomeID]").hide('slow'); //  Div id that ends with SomeID


text:
Q: Why can we get eigenvalue through solving $det(A-\lambda I)=0$? In many notes, I see
$A\vec{v}=\lambda \vec{v}$
$(A-\lambda)\vec{v}=\vec{0}$
$det(A-\lambda I)=0$
How to get line 3 actually?
Thanks.

A: If your system of linear equations has a non-trivial solution, then the matrix of this system must be degenerate, i.e. it's det is $0$. The main point is that the vector $v$ in the first line of your question is non-zero.


text:
Q: How to create another sa in Azure SQL Server I'm a newbie on SQL, I'd like to know how to create an extra account for Azure Sql Server that has all the permission granted.
It would be great if you could provide the SQL script.

A: The best way to achieve this is to use Azure Active Directory Authentication. When setting your Active Directory admin in the portal, choose an AD group. This way, any user who is a member of this group will have full administrator privileges.


text:
Q: Error connecting to API but able to connect when running unit test in C# I am trying to build a service that connects from a Web API using HttpClient class. The service runs okay under unit tests but encounters an error when I call the service from a controller. Here's the code for my service
public List<Recipe> FindRecipe(string searchTerm)
{
    List<Recipe> result = null;
    string apiPath = BuiltApiPath(searchTerm);
    var task = AppHttpClient.Instance().
        GetAsync(new Uri(apiPath))
        .ContinueWith((taskReponse) =>
        {
            var response = taskReponse.Result;
            var jsonString = response.Content.ReadAsStringAsync();
            jsonString.Wait();
            dynamic data = JsonConvert.DeserializeObject<dynamic>(jsonString.Result);
            result = ((IEnumerable)data.hits).Cast<dynamic>().
                Select(h => new Recipe { Name = h.recipe.label, ImageUrl = h.recipe.image, Uri = h.recipe.uri }).
                ToList();
        });
    task.Wait();
    return result;
}

And here's the exception I'm getting
Exception information:
    Exception type: AggregateException
    Exception message: One or more errors occurred.
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
   at System.Threading.Tasks.Task`1.get_Result()
   at RecipeFinder.Services.RecipeService.<>c__DisplayClass0_0.<FindRecipe>b__0(Task`1 taskReponse) in \\dtchyb-mnmh001\c_wfp_users\u595357\my documents\visual studio 2015\Projects\RecipeFinder\RecipeFinder\Services\RecipeService.cs:line 24
   at System.Threading.Tasks.ContinuationTaskFromResultTask`1.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()

An error occurred while sending the request.

Unable to connect to the remote server
   at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
   at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)

A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 107.20.173.119:443
   at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
   at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)


text:
Q: ASP.NET MVC 4 Saving Model List Items in Edit View I'm trying to save below project Model
public partial class Project: BaseModel
{
    public Project()
    {
        ProjectUsers = new List<ProjUser>();
    }

    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    [Display(Name="Project ID")]
    public int ProjectID { get; set; }

    [Required]
    public string Title { get; set; }
    [Display(Name = "Users")]
    public virtual List<ProjUser> ProjectUsers { get; set; }
}

ProjUser Model
public partial class ProjUser: BaseModel
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int ProjUserID { get; set; }

    public int UserID { get; set; }

    public int ProjectID { get; set; }
    [ForeignKey("ProjectID")]
    public virtual Project Project { get; set; }

    public bool? Signatories { get; set; }

}

The Users are populated via a separate database and the link between the project and user are maintains via the ProjUser model, UserID value.
public partial class User : BaseModel
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserID { get; set; }
    [Required]
    [Display(Name = "dispUserName" , ResourceType = typeof(Resource))]
    public string UserName { get; set; }
}

In the view i'm populating the list of users as a selectable (JqueryUI) and selecting the users who are available in the project.
@model Impetro.Models.Project
@{
    ViewBag.Title = "ProjectSettings";
}

@ViewBag.Title

@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Project Settings</legend>
        @Html.HiddenFor(model => model.ProjectID)

                @Html.LabelFor(model => model.Title)

                @Html.EditorFor(model => model.Title)

    </fieldset>

    <input type="submit" value="Save" />

}

@Html.DisplayNameFor(model => model.ProjectUsers)

@{
    var pojectUserIDs = from pu in Model.ProjectUsers
                        select new { pu.UserID };

    String userIDstr = "";
    foreach (var user in pojectUserIDs)
    {
        userIDstr = userIDstr + "#" + user.UserID.ToString() + ";";
    }
}
@Html.Hidden("userValues", userIDstr, "id='userValues'")

    @foreach (var user in ViewBag.Users as IEnumerable<Impetro.Models.Global.User>)
    {

@user.UserName	 @Html.CheckBox("chk" + @user.UserID) @Html.Label("chk" + @user.UserID, "PO Signatory")

    }

The JS to convert the above table to a selectable and to select the already added users.
$(function () {
    $("[data-impetro-uitype='selectable']").bind("mousedown", function (e) {
        e.metaKey = true;
    })
    .selectable({
        filter: "tr",
        create: function (event, ui) {
            var selectable = $(this);
            var valueEle = selectable.attr("data-impetro-selectorvalues");
            var valArr = $(valueEle).val().split(";");
            for (var i = 0; i < valArr.length; i++) {
                if (valArr[i] == "") {
                    continue;
                }
                var id = valArr[i];
                selectable.find(id).addClass("ui-selected");
            }
        }
    });
});

How can the changes to the projusers list be captured in the model?
Btw: Is there an easier method to select the values on initial load itself, which supports tracking the projUser list changes
Thanks in Advance
As Requested by lnanikian here is the GET Action for the controller. I still did not write the POST Action for this, becos im still in doubt about how to proceed with saving the details into the list.
public ActionResult ProjectSettings(int id)
    {
        ViewBag.Users = userRepository.All;
        return View(projectRepository.All
               .Where(p => p.ProjectID == id).SingleOrDefault());
    }

A: If I understand well. Let say when you click on the checkBox of the User he must be updated to the project? Whatn you can also do is create an Action who will save your User for the project.
[HttpPost]
public ActionResult AddUserToProj(int userId){
 //retreive the User by the Id with a Linq query or
 //just add to ProjUsers the Id of the UserId with other importants informations you can
 //pass via th eparameters
}

And then in your view, in your JS function an Ajax Method who will be called let's say if your your user is checked then you call the Action
$(function () {
   $("[data-impetro-uitype='selectable']").bind("mousedown", function (e) {
    e.metaKey = true;
    })
    .selectable({
    filter: "tr",
    create: function (event, ui) {
        var selectable = $(this);
        var valueEle = selectable.attr("data-impetro-selectorvalues");
        var valArr = $(valueEle).val().split(";");
        for (var i = 0; i < valArr.length; i++) {
            if (valArr[i] == "") {
                continue;
            }
            var id = valArr[i];
            selectable.find(id).addClass("ui-selected");
        }
    }
});

$('#check').bind('change', function () {

   if($(this).is(':checked'))
    {//You can ask a question here by a popup
     var userID= $("userId") //You retreive userId in the line by wise selection

     $.ajax({
        url: "@Url.Action("AddUserToProj","ControllerName")",
        type: 'POST',
        dataType: 'json',
        data: {id = $userID },
        async: false,
        success: function (result) {
            //  process the results from the server
            alert('done')

            });

        },
        error: function (errorThrown) {
            alert('error');
        }
    });
  }
 else
  {
    // unchecked, You can call a Deletion Method if you create another Action to do that
  }
  });
});


text:
Q: Rescue Exception to overcome gem error? I am trying to use the pusher-client gem to receive a Pusher from a website (near real-time data). However, the script tends to die a lot.
If I post the Pusher data to my screen, then the client runs for as long as I care to let it run. However, if I save the Pusher data to a file, or pass the data to a Gearman job, using the gearman gem, or put the data into Memcache, using the dalli gem, then my client script crashes.
My server is not overloaded in any way. It has 8 cores and 24 GB of RAM. Typically no single core is at 100% and no more than 6 are in use at any time and no more than 12 GB of the RAM is ever in use.
My current incarnation of the client script is attempting to pass the data off to a Gearman job, and I hope that this will offload the saving of the data and prevent missing any updates provided by Pusher, which can often come very quickly. This is a representative error the script kicks out:
ruby-2.1.1/gems/gearman-ruby-3.0.7/lib/gearman/taskset.rb:99:in `handle_job_created': Got unexpected job_created notification with handle H:hawk898
        from /home/gabe/.rvm/gems/ruby-2.1.1/gems/gearman-ruby-3.0.7/lib/gearman/taskset.rb:222:in `read_packet'
        from /home/gabe/.rvm/gems/ruby-2.1.1/gems/gearman-ruby-3.0.7/lib/gearman/taskset.rb:67:in `add_task_internal'
        from /home/gabe/.rvm/gems/ruby-2.1.1/gems/gearman-ruby-3.0.7/lib/gearman/taskset.rb:29:in `add_task'
        from /var/www/.../utils/pusher_utils.rb:81:in `send_to_gearman'
        from /var/www/.../utils/pusher_utils.rb:10:in `export_to_gearman'
        from /var/www/.../async_pusher.rb:59:in `block in <main>'
        from /home/gabe/.rvm/gems/ruby-2.1.1/gems/pusher-client-0.4.0/lib/pusher-client/channel.rb:30:in `call'
        from /home/gabe/.rvm/gems/ruby-2.1.1/gems/pusher-client-0.4.0/lib/pusher-client/channel.rb:30:in `block in dispatch'
        from /home/gabe/.rvm/gems/ruby-2.1.1/gems/pusher-client-0.4.0/lib/pusher-client/channel.rb:29:in `each'
        from /home/gabe/.rvm/gems/ruby-2.1.1/gems/pusher-client-0.4.0/lib/pusher-client/channel.rb:29:in `dispatch'
        from /home/gabe/.rvm/gems/ruby-2.1.1/gems/pusher-client-0.4.0/lib/pusher-client/channel.rb:22:in `dispatch_with_all'
        from /home/gabe/.rvm/gems/ruby-2.1.1/gems/pusher-client-0.4.0/lib/pusher-client/socket.rb:201:in `send_local_event'
        from /home/gabe/.rvm/gems/ruby-2.1.1/gems/pusher-client-0.4.0/lib/pusher-client/socket.rb:73:in `block (2 levels) in connect'
        from /home/gabe/.rvm/gems/ruby-2.1.1/gems/pusher-client-0.4.0/lib/pusher-client/socket.rb:67:in `loop'
        from /home/gabe/.rvm/gems/ruby-2.1.1/gems/pusher-client-0.4.0/lib/pusher-client/socket.rb:67:in `block in connect'

I don't want to dig into the pusher-client gem and figure out why this is happening. I simply want to move on, so I'm tempted to use rescue Exception. I am saving the data provided by Pusher for downstream logic and action. The data is fast moving and I can either determine if the job actually made it to Gearman, possibly missing the next update or delaying it, or I can simply mark the currently stored data as stale/invalid and wait for the next update from Pusher. My preference is to mark it as stale/invalid and wait.
I've read "Why is it a bad style to `rescue Exception => e` in Ruby?" and know that rescue Exception is bad practice. However, I'm not doing this to cover up a bug in my code - I've looked at the workloads being passed to Gearman at the time of the error and they are fine.
I'm running:
Ubuntu 12.04
RVM and Ruby 2.1.1

Here is some sample code that sends a heartbeat workload to the Gearman job server:
def heartbeat(site, marketId, taskset)
    startTime = timeID()

    workload = myhash()
    workload['marketId'] = marketId
    workload['site'] = site
    workload['src'] = 'pusher'
    workload['time'] = startTime
    workload['staleTime'] = startTime + 1

    send_to_gearman('update_heartbeat', json_encode(workload), taskset)

    endTime = timeID()
    delta =endTime - startTime
    puts sprintf("Heartbeat Task Handoff took: %9.4f msec", delta * 1E3)
end # def heartbeat

def send_to_gearman(wrkr, workload, taskset)
    pp workload

    begin
        task = Gearman::Task.new(wrkr, workload, { :priority => :high, :background => true })
        taskset.add_task(task)
        taskset.wait
    rescue => e
        pp e
    end # begin
end # def send_to_gearman

The entirety of the code runs fine for minutes if not hours before failing. Specifically every line of code is being exercised repeatedly, except those after rescue, without failing prior to the handle_job_created error.
So, is it safe to use rescue Exception in this case? Is there some subset of Exception I could use instead that I'm missing? Any better suggestions or gotchas I may have overlooked?

A: You should only rescue the errors that are actually raised.  In this case Gearman::ProtocolError is the error being raised.  So use:
rescue Gearman::ProtocolError


text:
Q: Fail to create a superuser in django, when use a router I tring to create mongodb/mysql project on Djago 1.11.4 with python3. I intended to use mysql for user authentification and mongodb for all other purposes. I master to create a users but failed in creating a superuser. Here is what happend, when I tried to create a superuser:
$ python3 manage.py createsuperuser username=Admin
System check identified some issues:

WARNINGS:
?: (urls.W001) Your URL pattern '^$' uses include with a regex ending with a '$'. Remove the dollar from the regex to avoid problems including URLs.
Email address: admin@example.com
Password:
Password (again):
Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 363, in execute_from_command_line
    utility.execute()
  File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 355, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 283, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/usr/local/lib/python3.5/dist-packages/django/contrib/auth/management/commands/createsuperuser.py", line 63, in execute
    return super(Command, self).execute(*args, **options)
  File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 330, in execute
    output = self.handle(*args, **options)
  File "/usr/local/lib/python3.5/dist-packages/django/contrib/auth/management/commands/createsuperuser.py", line 183, in handle
    self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
  File "/usr/local/lib/python3.5/dist-packages/django/contrib/auth/models.py", line 170, in create_superuser
    return self._create_user(username, email, password, **extra_fields)
  File "/usr/local/lib/python3.5/dist-packages/django/contrib/auth/models.py", line 153, in _create_user
    user.save(using=self._db)
  File "/usr/local/lib/python3.5/dist-packages/django/contrib/auth/base_user.py", line 80, in save
    super(AbstractBaseUser, self).save(*args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/django/db/models/base.py", line 807, in save
    force_update=force_update, update_fields=update_fields)
  File "/usr/local/lib/python3.5/dist-packages/django/db/models/base.py", line 834, in save_base
    with transaction.atomic(using=using, savepoint=False):
  File "/usr/local/lib/python3.5/dist-packages/django/db/transaction.py", line 158, in __enter__
    if not connection.get_autocommit():
  File "/usr/local/lib/python3.5/dist-packages/django/db/backends/base/base.py", line 385, in get_autocommit
    self.ensure_connection()
  File "/usr/local/lib/python3.5/dist-packages/django/db/backends/dummy/base.py", line 20, in complain
    raise ImproperlyConfigured("settings.DATABASES is improperly configured. "
django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details.

Here is a part of my settings.py:
DATABASES = {
    'default': {
        'ENGINE' : 'django.db.backends.dummy',
        'NAME' : 'my_database'
    },
    'users': {
        'NAME': 'nra_gpb_users',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'django'
    }
}
class AuthRouter(object):
    """
    A router to control all database operations on models in the
    auth application.
    """
    def db_for_read(model, **hints):
        """
        Attempts to read auth models go to auth_db.
        """
        if model._meta.app_label == 'auth':
            return 'users'
        return 'default'

    def db_for_write(model, **hints):
        """
        Attempts to write auth models go to auth_db.
        """
        print(model._meta.app_label)
        if model._meta.app_label == 'auth':
            return 'users'
        return 'default'

    def allow_relation(obj1, obj2, **hints):
        """
        Allow relations if a model in the auth app is involved.
        """
        return False

    def allow_migrate(db, app_label, model_name=None, **hints):
        """
        Make sure the auth app only appears in the 'auth_db'
        database.
        """
        return db == 'auth_db'
DATABASE_ROUTERS = [AuthRouter]

I succefully make a migration for users database, and successfully create a user in interactive mode:
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> django.setup()
>>> from django.contrib.auth.models import User
>>> user = User.objects.create_user('Admin', 'admin@example.com', 'password')
>>> user.save()
>>> exit()

Please, explaim me, what goes wrong?
UPD: Successfully create a superuser with:
python3 manage.py createsuperuser --database users --username Admin
But when I tried to authorize, again receive ImproperConfigure error:
$ python3 manage.py runserver
Performing system checks...

System check identified some issues:

WARNINGS:
?: (urls.W001) Your URL pattern '^$' uses include with a regex ending with a '$'. Remove the dollar from the regex to avoid problems including URLs.

System check identified 1 issue (0 silenced).
October 07, 2017 - 23:23:06
Django version 1.11.4, using settings 'my_django_project.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
[07/Oct/2017 23:23:16] "GET /admin/ HTTP/1.1" 302 0
[07/Oct/2017 23:23:16] "GET /admin/login/?next=/admin/ HTTP/1.1" 200 1654
Internal Server Error: /admin/login/
Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/usr/local/lib/python3.5/dist-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func
    response = view_func(request, *args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/django/contrib/admin/sites.py", line 393, in login
    return LoginView.as_view(**defaults)(request)
  File "/usr/local/lib/python3.5/dist-packages/django/views/generic/base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py", line 67, in _wrapper
    return bound_func(*args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/django/views/decorators/debug.py", line 76, in sensitive_post_parameters_wrapper
    return view(request, *args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py", line 63, in bound_func
    return func.__get__(self, type(self))(*args2, **kwargs2)
  File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py", line 67, in _wrapper
    return bound_func(*args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py", line 149, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py", line 63, in bound_func
    return func.__get__(self, type(self))(*args2, **kwargs2)
  File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py", line 67, in _wrapper
    return bound_func(*args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func
    response = view_func(request, *args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py", line 63, in bound_func
    return func.__get__(self, type(self))(*args2, **kwargs2)
  File "/usr/local/lib/python3.5/dist-packages/django/contrib/auth/views.py", line 90, in dispatch
    return super(LoginView, self).dispatch(request, *args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/django/views/generic/base.py", line 88, in dispatch
    return handler(request, *args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/django/views/generic/edit.py", line 183, in post
    return self.form_valid(form)
  File "/usr/local/lib/python3.5/dist-packages/django/contrib/auth/views.py", line 119, in form_valid
    auth_login(self.request, form.get_user())
  File "/usr/local/lib/python3.5/dist-packages/django/contrib/auth/__init__.py", line 139, in login
    request.session.cycle_key()
  File "/usr/local/lib/python3.5/dist-packages/django/contrib/sessions/backends/base.py", line 311, in cycle_key
    self.create()
  File "/usr/local/lib/python3.5/dist-packages/django/contrib/sessions/backends/db.py", line 50, in create
    self._session_key = self._get_new_session_key()
  File "/usr/local/lib/python3.5/dist-packages/django/contrib/sessions/backends/base.py", line 164, in _get_new_session_key
    if not self.exists(session_key):
  File "/usr/local/lib/python3.5/dist-packages/django/contrib/sessions/backends/db.py", line 46, in exists
    return self.model.objects.filter(session_key=session_key).exists()
  File "/usr/local/lib/python3.5/dist-packages/django/db/models/query.py", line 670, in exists
    return self.query.has_results(using=self.db)
  File "/usr/local/lib/python3.5/dist-packages/django/db/models/sql/query.py", line 517, in has_results
    return compiler.has_results()
  File "/usr/local/lib/python3.5/dist-packages/django/db/models/sql/compiler.py", line 853, in has_results
    return bool(self.execute_sql(SINGLE))
  File "/usr/local/lib/python3.5/dist-packages/django/db/models/sql/compiler.py", line 871, in execute_sql
    sql, params = self.as_sql()
  File "/usr/local/lib/python3.5/dist-packages/django/db/models/sql/compiler.py", line 435, in as_sql
    from_, f_params = self.get_from_clause()
  File "/usr/local/lib/python3.5/dist-packages/django/db/models/sql/compiler.py", line 660, in get_from_clause
    clause_sql, clause_params = self.compile(from_clause)
  File "/usr/local/lib/python3.5/dist-packages/django/db/models/sql/compiler.py", line 373, in compile
    sql, params = node.as_sql(self, self.connection)
  File "/usr/local/lib/python3.5/dist-packages/django/db/models/sql/datastructures.py", line 144, in as_sql
    base_sql = compiler.quote_name_unless_alias(self.table_name)
  File "/usr/local/lib/python3.5/dist-packages/django/db/models/sql/compiler.py", line 364, in quote_name_unless_alias
    r = self.connection.ops.quote_name(name)
  File "/usr/local/lib/python3.5/dist-packages/django/db/backends/dummy/base.py", line 20, in complain
    raise ImproperlyConfigured("settings.DATABASES is improperly configured. "
django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details.
[07/Oct/2017 23:23:35] "POST /admin/login/?next=/admin/ HTTP/1.1" 500 207729

A: The database to use when creating users needs to be passed in terminal as the default database connection parameters is a dummy.
python3 manage.py createsuperuser --database users --username Admin

A: This is the right settings.py part which lead me to succcessful admin authorization:
INSTALLED_APPS = [
    'my_app',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles'
]
DATABASES = {
    'default': {
        'ENGINE' : 'django.db.backends.dummy',
        'NAME' : 'my_database'
    },
    'users': {
        'NAME': 'my_site_users',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'django'
    }
}
class AuthRouter(object):
    """
    A router to control all database operations on models in the
    auth application.
    """
    def db_for_read(model, **hints):
        """
        Attempts to read auth models go to auth_db.
        """
        if model._meta.app_label!='my_app':
            return 'users'
        return 'default'

    def db_for_write(model, **hints):
        """
        Attempts to write auth models go to auth_db.
        """
        if model._meta.app_label!='my_app':
            return 'users'
        return 'default'

    def allow_relation(obj1, obj2, **hints):
        """
        Allow relations if a model in the auth app is involved.
        """
        if obj1._meta.app_label == 'auth' or \
            obj2._meta.app_label == 'auth':
            return True
        return False

    def allow_migrate(db, app_label, model_name=None, **hints):
        """
        Make sure the auth app only appears in the 'auth_db'
        database.
        """
        return db == 'users'
DATABASE_ROUTERS = [AuthRouter]

As @Oluwafemi Sule mentioned, in my case superuser can be created by command:
python3 manage.py createsuperuser --database users --username Admin


text:
Q: What's the default variable type for input in Python 3.x? I've been trying to write a simple checking script for whatever the user inputs.
The script, however, automatically assumes that anything being input is a string by default. Is there a way to change that without using int(input) or float(input)? The point of the script is to use the isinstance to get the correct output.
l = input("Input: ")
if isinstance(l, int) and l >= 0:
    print ("l is %d and is more/equal to zero" % l)
elif isinstance(l, int) and l < 0:
    print ("l is %d and is lesser than zero" % l)
elif isinstance(l, float):
    print ("l is %.2f and is a float variable" % l)
elif isinstance(l, str):
    print ("l is %s and is a string" % l)

A: The input() function always returns a string. If you want it to be some other type, you'll need to manually convert it.
my_str = input("Enter a number")
my_int = int(my_str)
my_float = float(my_str)


text:
Q: One more formulae manipulation question Just making sure I am right...
Make c the subject of the formula:
$ y = \frac{2a+b}{3c -d}$
so $ 3c -d = \frac{2a+b}{y}$
so $ 3c = \frac{2a+b}{y} +d$
so $ c =\frac{6a+3b}{y} + \frac{d}{3}$
If I am not right please say why thanks

A: You are correct up to this point:$$3c-d=\frac{2a+b}{y}$$you then add $d$ to both sides to get:$$3c=\frac{2a+b}{y}+d$$Finally you divide both sides by $3$ to get:$$c=\frac{1}{3}\left(\frac{2a+b}{y}+d\right)=\frac{1}{3}\times\frac{2a+b}{y}+\frac{1}{3}\times d$$Hopefully you can complete from here...

A: Yes, this is correct: $$3c = \frac{2a+b}{y} +d$$
But...Your last line is incorrect; you should get $$c=\frac{2a+b}{3y} + \frac d3$$ since we need to divide both sides by 3 in order to isolate $c$.
Remark Do be careful. The above only holds if $2a \neq -b$, else $y = 0$ and we cannot divide by zero. So I'd simply add the provision: $2a \neq -b$ with the equation for $c$.

A: As Mufasa pointed out, you are correct up to the point where you added $b$ by accident instead of $d$. There is actually a simpler way, I think, to get what you want (solving for $c$, that is):
\begin{align}
y = \frac{2a+b}{3c-d} &\Longleftrightarrow y(3c-d)=2a+b\\[1em]
                      &\Longleftrightarrow 3yc-yd = 2a+b\\[1em]
                      &\Longleftrightarrow c = \frac{2a+b+yd}{3y}.
\end{align}
Does that solve it in the way you desired?


text:
Q: Google Maps Api v3 - Trabalhando com 2 arquivos Json Estou criando um mapa, para apresentar uma série de informações, usando o google maps v3.
Resolvi trabalhar com 2 arquivos Json, para preenchimento do mapa.
O primeiro arquivo contem as informações de Latitude e Longitude dos pontos do mapa, e o segundo contem as informações da InfoWindow.
Até aí tudo bem, consegui preencher o mapa e buscar as informações da InfoWindow no outro arquivo.
Agora gostaria de aplicar filtros neste mapa, para segmentar os dados.
É nesta parte que estou com problema, o filtro precisa ser aplicado no segundo arquivo, e com isto filtrar o primeiro, para setar apenas os pontos de interesse, irão existir mais de 1 filtro para o mapa.
Estou me batendo com isto, alguém já precisou fazer algo semelhante?
Alguma ideia? Fiz algumas tentativas mas sem sucesso até agora.
Segue meu fonte até agora (Preenchendo o mapa e setando a InfoWindow).
<!DOCTYPE html>

    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <title>TESTE</title>

Abaixo o exemplo dos Json:
var lat_long = [
      {
         "ARMARIO_SITE": "ACRBO_O1A01",
         "LONGITUDE": -67.80921,
         "LATITUDE": -9.971221
      },
      {
         "ARMARIO_SITE": "ACRBO_O1A02",
         "LONGITUDE": -67.81101,
         "LATITUDE": -9.960082
      },
      {
         "ARMARIO_SITE": "ACRBO_O1I01",
         "LONGITUDE": -67.81749,
         "LATITUDE": -9.969712
      }
];

var ards = [
    {
        "LOCALIDADE":"FEIRA DE SANTANA",
        "TIPO_CLIENTE":"Padrão",
        "TIPO_ACESSO":"METALICO",
        "UF":"BA",
        "DESC_MES_CRIACAO":"JANEIRO",
        "DESC_CLUSTER":"FEIRA DE SANTANA",
        "ARMARIO_ERB":"ACRBO_O1A01",
        "TIPO_RECLAMACAO":"TT",
        "CLIENTE_RECENTE":"N"
    },
    {
        "LOCALIDADE":"FEIRA DE SANTANA",
        "TIPO_CLIENTE":"Padrão",
        "TIPO_ACESSO":"METALICO",
        "UF":"BA",
        "DESC_MES_CRIACAO":"JANEIRO",
        "DESC_CLUSTER":"FEIRA DE SANTANA",
        "ARMARIO_ERB":"ACRBO_O1A01",
        "TIPO_RECLAMACAO":"TT",
        "CLIENTE_RECENTE":"N"
    },
    {
        "LOCALIDADE":"FEIRA DE SANTANA",
        "TIPO_CLIENTE":"Premium",
        "TIPO_ACESSO":"METALICO",
        "UF":"BA",
        "DESC_MES_CRIACAO":"JANEIRO",
        "DESC_CLUSTER":"FEIRA DE SANTANA",
        "ARMARIO_ERB":"ACRBO_O1A02",
        "TIPO_RECLAMACAO":"TT",
        "CLIENTE_RECENTE":"N"
    },
    {
        "LOCALIDADE":"FEIRA DE SANTANA",
        "TIPO_CLIENTE":"Premium",
        "TIPO_ACESSO":"CABO",
        "UF":"BA",
        "DESC_MES_CRIACAO":"JANEIRO",
        "DESC_CLUSTER":"FEIRA DE SANTANA",
        "ARMARIO_ERB":"ACRBO_O1I01",
        "TIPO_RECLAMACAO":"TT",
        "CLIENTE_RECENTE":"N"
    },
    {
        "LOCALIDADE":"FEIRA DE SANTANA",
        "TIPO_CLIENTE":"Residencial",
        "TIPO_ACESSO":"METALICO",
        "UF":"BA",
        "DESC_MES_CRIACAO":"JANEIRO",
        "DESC_CLUSTER":"FEIRA DE SANTANA",
        "ARMARIO_ERB":"ACRBO_O1I01",
        "TIPO_RECLAMACAO":"TT",
        "CLIENTE_RECENTE":"N"
    }
];

Obrigado.

A: Consegui realizar multiplos filtros utilizando bases distintas.
Segui a ideia deste projeto Marker-Filtering-Google-Maps. Que trabalha de uma maneira muito bem organizada, fiz algumas adaptações apenas, para meus cenários.
Consegui vincular as bases fazendo buscas e setando novos arrays.
Exemplos:
//Para a InfoWindow usei assim.
var as=$(ards).filter(function (i,n){
     return n.ARMARIO_ERB===marker.getTitle();
});

//Para eliminar duplicados
$.each(results, function(index, value) {
    if ($.inArray(value.ARMARIO_ERB, armarios)==-1) {
        armarios.push(value.ARMARIO_ERB);
    }
});

//Buscar a lat_long unica
for(var j = 0; j < armarios.length; j++){
    $.grep( lat_long, function( n, i ) {
        if(n.ARMARIO_SITE===armarios[j]){
            localizacoes.push( n );
        }
    });
}

Funcionou perfeitamente.


text:
Q: I need my jquery slider to auto play I have a jquery slider from http://tympanus.net/codrops/2013/02/26/full-width-image-slider/
I have installed the slider perfectly and its working fine, I need it to slide automatically when a user visits the website.
I have no experience with jQuery and I'm unable to get this to autoplay.
Here is the jQuery code for the slider;
;( function( $, window, undefined ) {

'use strict';

// global
var Modernizr = window.Modernizr;

$.CBPFWSlider = function( options, element ) {
    this.$el = $( element );
    this._init( options );
};

// the options
$.CBPFWSlider.defaults = {

    // default transition speed (ms)
    speed : 500,
    // default transition easing
    easing : 'ease'
};

$.CBPFWSlider.prototype = {
    _init : function( options ) {
        // options
        this.options = $.extend( true, {}, $.CBPFWSlider.defaults, options );
        // cache some elements and initialize some variables
        this._config();
        // initialize/bind the events
        this._initEvents();
    },
    _config : function() {

        // the list of items
        this.$list = this.$el.children( 'ul' );
        // the items (li elements)
        this.$items = this.$list.children( 'li' );
        // total number of items
        this.itemsCount = this.$items.length;
        // support for CSS Transitions & transforms
        this.support = Modernizr.csstransitions && Modernizr.csstransforms;
        this.support3d = Modernizr.csstransforms3d;
        // transition end event name and transform name
        // transition end event name
        var transEndEventNames = {
                'WebkitTransition' : 'webkitTransitionEnd',
                'MozTransition' : 'transitionend',
                'OTransition' : 'oTransitionEnd',
                'msTransition' : 'MSTransitionEnd',
                'transition' : 'transitionend'
            },
            transformNames = {
                'WebkitTransform' : '-webkit-transform',
                'MozTransform' : '-moz-transform',
                'OTransform' : '-o-transform',
                'msTransform' : '-ms-transform',
                'transform' : 'transform'
            };

        if( this.support ) {
            this.transEndEventName = transEndEventNames[ Modernizr.prefixed( 'transition' ) ] + '.cbpFWSlider';
            this.transformName = transformNames[ Modernizr.prefixed( 'transform' ) ];
        }
        // current and old item´s index
        this.current = 0;
        this.old = 0;
        // check if the list is currently moving
        this.isAnimating = false;
        // the list (ul) will have a width of 100% x itemsCount
        this.$list.css( 'width', 100 * this.itemsCount + '%' );
        // apply the transition
        if( this.support ) {
            this.$list.css( 'transition', this.transformName + ' ' + this.options.speed + 'ms ' + this.options.easing );
        }
        // each item will have a width of 100 / itemsCount
        this.$items.css( 'width', 100 / this.itemsCount + '%' );
        // add navigation arrows and the navigation dots if there is more than 1 item
        if( this.itemsCount > 1 ) {

            // add navigation arrows (the previous arrow is not shown initially):
            this.$navPrev = $( '<' ).hide();
            this.$navNext = $( '>' );
            $( '' ).append( this.$navPrev, this.$navNext ).appendTo( this.$el );
            // add navigation dots
            var dots = '';
            for( var i = 0; i < this.itemsCount; ++i ) {
                // current dot will have the class cbp-fwcurrent
                var dot = i === this.current ? '' : '';
                dots += dot;
            }
            var navDots = $( '
' ).append( dots ).appendTo( this.$el );
            this.$navDots = navDots.children( 'span' );

        }

    },
    _initEvents : function() {

        var self = this;
        if( this.itemsCount > 1 ) {
            this.$navPrev.on( 'click.cbpFWSlider', $.proxy( this._navigate, this, 'previous' ) );
            this.$navNext.on( 'click.cbpFWSlider', $.proxy( this._navigate, this, 'next' ) );
            this.$navDots.on( 'click.cbpFWSlider', function() { self._jump( $( this ).index() ); } );
        }

    },
    _navigate : function( direction ) {

        // do nothing if the list is currently moving
        if( this.isAnimating ) {
            return false;
        }

        this.isAnimating = true;
        // update old and current values
        this.old = this.current;
        if( direction === 'next' && this.current < this.itemsCount - 1 ) {
            ++this.current;
        }
        else if( direction === 'previous' && this.current > 0 ) {
            --this.current;
        }
        // slide
        this._slide();

    },
    _slide : function() {

        // check which navigation arrows should be shown
        this._toggleNavControls();
        // translate value
        var translateVal = -1 * this.current * 100 / this.itemsCount;
        if( this.support ) {
            this.$list.css( 'transform', this.support3d ? 'translate3d(' + translateVal + '%,0,0)' : 'translate(' + translateVal + '%)' );
        }
        else {
            this.$list.css( 'margin-left', -1 * this.current * 100 + '%' );
        }

        var transitionendfn = $.proxy( function() {
            this.isAnimating = false;
        }, this );

        if( this.support ) {
            this.$list.on( this.transEndEventName, $.proxy( transitionendfn, this ) );
        }
        else {
            transitionendfn.call();
        }

    },
    _toggleNavControls : function() {

        // if the current item is the first one in the list, the left arrow is not shown
        // if the current item is the last one in the list, the right arrow is not shown
        switch( this.current ) {
            case 0 : this.$navNext.show(); this.$navPrev.hide(); break;
            case this.itemsCount - 1 : this.$navNext.hide(); this.$navPrev.show(); break;
            default : this.$navNext.show(); this.$navPrev.show(); break;
        }
        // highlight navigation dot
        this.$navDots.eq( this.old ).removeClass( 'cbp-fwcurrent' ).end().eq( this.current ).addClass( 'cbp-fwcurrent' );

    },
    _jump : function( position ) {

        // do nothing if clicking on the current dot, or if the list is currently moving
        if( position === this.current || this.isAnimating ) {
            return false;
        }
        this.isAnimating = true;
        // update old and current values
        this.old = this.current;
        this.current = position;
        // slide
        this._slide();

    },
    destroy : function() {

        if( this.itemsCount > 1 ) {
            this.$navPrev.parent().remove();
            this.$navDots.parent().remove();
        }
        this.$list.css( 'width', 'auto' );
        if( this.support ) {
            this.$list.css( 'transition', 'none' );
        }
        this.$items.css( 'width', 'auto' );

    }
};

var logError = function( message ) {
    if ( window.console ) {
        window.console.error( message );
    }
};

$.fn.cbpFWSlider = function( options ) {
    if ( typeof options === 'string' ) {
        var args = Array.prototype.slice.call( arguments, 1 );
        this.each(function() {
            var instance = $.data( this, 'cbpFWSlider' );
            if ( !instance ) {
                logError( "cannot call methods on cbpFWSlider prior to initialization; " +
                "attempted to call method '" + options + "'" );
                return;
            }
            if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) {
                logError( "no such method '" + options + "' for cbpFWSlider instance" );
                return;
            }
            instance[ options ].apply( instance, args );
        });
    }
    else {
        this.each(function() {
            var instance = $.data( this, 'cbpFWSlider' );
            if ( instance ) {
                instance._init();
            }
            else {
                instance = $.data( this, 'cbpFWSlider', new $.CBPFWSlider( options, this ) );
            }
        });
    }
    return this;
};

} )( jQuery, window );

I have looked at different threads but I haven't got any understanding on where to put the autoplay code in the jQuery file.
Can anyone anyone help me on where I need to add the autoplay function?
All help is appreciated.

A: $('document').ready(function () {
        // init slider
        $('#cbp-fwslider').cbpFWSlider();
        /**
              Set a 3 seconds interval
              if next button is visible (so is not the last slide)  click next button
              else it finds first dot and click it to start from the 1st slide
         **/
        setInterval(function () {
            if ($('.cbp-fwnext').is(":visible")) {
                $('.cbp-fwnext').click();
            }
            else {
                $('.cbp-fwdots').find('span').click();
            }
        }, 3000);
    });

You can use below code to solve your problem and slide the images automatically every three seconds..If you want to change the time,change that 3000 as you wish.
Below is the link that i copy the code from:
Autoplay JQuery slideshow Using cbpFWSlider


text:
Q: Hover effect on image and button I have an image with a button centered in the middle of my image. I want when I hover on my image to add an opacity on my image and change the color of my button. The problem I have is that, when I hover over my image, my button also has an opacity which I don't want. I have tried z-index, but it is not working.
This is what i have done so far:

#asides .aside-map {
  min-height: 20px;
  margin-top: 20px;
  margin-bottom: 10px;
  text-align: center;
  -moz-transition: .3s ease-in-out;
  -o-transition: .3s ease-in-out;
  -webkit-transition: .3s ease-in-out;
  transition: .3s ease-in-out;
  position:relative;
  width: 100%;
  height: 350px;
  background: url("http://placehold.it/350x150");
}

#asides .aside-map .btn-main.map {
  position: relative;
  top: 50%;
}

#asides .aside-map:hover {
  opacity: 0.5;
}

#asides .aside-map:hover > .btn-main.map {
  background-color: rgb(254, 204, 0);
  border: 2px solid rgb(254, 204, 0);
  opacity: 1;
}

         Show Map

I am not able to display an image in the snippet, but this is how it looks like:

And when I am hovering on my image this is what i have:

Both my image and button have an opacity of 0.5 and I would like to have my button without any opacity

A: Your issue is that opacity: 0.5 set opacity for the whole element.
You can use background: rgba(0, 0, 0, 0.5) instead:

#asides .aside-map {
        min-height: 20px;
        margin-top: 20px;
        margin-bottom: 10px;
        text-align: center;
        -moz-transition: .3s ease-in-out;
        -o-transition: .3s ease-in-out;
        -webkit-transition: .3s ease-in-out;
        transition: .3s ease-in-out;
        position:relative;
        width: 100%;
        height: 350px;
        background: url("http://placehold.it/350x150");
    }

        #asides .aside-map .btn-main.map {
            position: relative;
            top: 50%;
        }

        #asides .aside-map:hover {
            background: rgba(0, 0, 0, 0.5);
        }

            #asides .aside-map:hover > .btn-main.map {
                background-color: rgb(254, 204, 0);
                border: 2px solid rgb(254, 204, 0);
                opacity: 1;
            }

         Show Map


text:
Q: Vuejs lifecycle issues, data array is only populated after Webpack loader refreshed the element on the page? google maps markers not showing up? I'm pretty new to vueJS, and I'm making an app where I can plot locations, and have them show up on a google maps element. My code is really hacky, but I'm trying to learn by making stuff. Thanks for any help.
Context
I currently have an array of geese objects:
[
    {
        "id": 74,
        "created_at": "Jan 14 08:24:46 PM",
        "latitude": "<a coord near me>",
        "longitude": "<a coord near me>"
    },
    {
        "id": 73,
        "created_at": "Jan 14 06:56:33 PM",
        "latitude": "<a coord near me>",
        "longitude": "<a coord near me>"
    }
]

What I'm trying to do
I'm trying to convert this array of geese objects into another array of markers, containing position objects with just lat/long, which I can pass into google maps and show markers.
Problems
The map is showing up, and getting current location + centering is working fine.
For some reason, my markers array only gets populated when my webpack loader reloads the element on the page (for example, if I make a random console.log statement within my "getMarkers()" method. It isn't populating correctly when the page initially loads. I've tried looking through vue's lifecycle documentation, but just can't get it to work.
Additionally, when the markers do load correctly (checked with vue devtools chrome extension), they still don't appear as markers on the app (but when I manually enter in mock coors with vue devtools, they do?).
My code
<template>
  <div>
    <gmap-map :center="this.center" :zoom="15" style="width:100%;  height: 400px;">
      <gmap-marker
        :key="index"
        v-for="(m, index) in markers"
        :position="m.position"
      ></gmap-marker>
    </gmap-map>
  </div>
</template>
<script>
export default {
  name: "GoogleMap",
  props: {
    geese: Array
  },
  data() {
    return {
      markers: [],
      center: {}
    };
  },
  methods: {
    geolocate() {
      navigator.geolocation.getCurrentPosition(position => {
        this.center = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        };
      });
    },
    getMarkers() {
      console.log("in getMarkers")
      for (var goose of this.geese) {
        console.log("got into for loop of geese")
        console.log("dsdfss")
        const marker = {
          lat: parseFloat(goose.latitude),
          lng: parseFloat(goose.longitude)
        };
        this.markers.push({ position: marker });
      }
    }
  },
  mounted() {
    this.geolocate();
    this.getMarkers()
  }
};
</script>

Thanks again for any help.

A: Fixed the issue!
my mounted code looks like this:
mounted() {
  document.onreadystatechange = () => {
     if (document.readyState == "complete") {
       console.log('Page completed')
       this.getMarkers()
     }
   }
}

i also put "this.geolocate()" into created


text:
Q: How to use vim abbreviation in latex? I want to set some abbreviations for my latex document. Following this instructions, I typed in my .vimrc file
:autocmd FileType latex :iabbrev <buffer> lambda \lambda

But when I type lambda into my tex document nothing happens. Why?
Edit: Some info
I have a line above that works:
:autocmd FileType latex :let localleader="\\"

set ft returns filetype=tex and abbreviate lambda returns no abbreviation found
Second edit:
I changed the order of my .vimrc file from
:autocmd FileType latex :let localleader="\\"
:autocmd FileType tex :iabbrev <buffer> lambda \lambda

to
:autocmd FileType tex :iabbrev <buffer> lambda \lambda
:autocmd FileType latex :let localleader="\\"

And now things seem to work properly.


text:
Q: ASP.NET MVC Best Practice for jQuery updates History
I created a new ASP.NET MVC 4.0 project that was basic and didn't include jQuery or other scripts that the Intranet and Internet templates insert by default. I then went to add the scripts using NuGet and installed the latest version of all the jQuery and related files that are normally installed by the MVC Intranet and Internet templates.
When I tried running the application I started to receive errors. Apparently there are incompatibilities with the libraries/extensions that were written previous to jQuery 1.9. It seemed like after fixing an issue I'd run into another. I finally gave up and copied the versions of the js files that would have installed. This resolved the issues I was able to use features such as remote validation.
Questions
Since I'm new to ASP.MVC, I'd like to know what the Best Practice is related to jQuery updates. I assume I need to wait until all the libraries/extensions have caught up, but I would need to follow the status of each library/extension to determine when I could upgrade.

*

*Is it simply better to wait and just use the versions that are installed with the MVC templates and not upgrade? And when the next update for MVC comes out, then copy those libraries/extensions into the scripts folder that the updated templates use?

*I noticed that the MVC templates do not install the jQuery NuGet packages but install files to the Content and Script folders. Is this to prevent developers from upgrading and experiencing the issues I found with using newer version of the libraries/extensions?

*Does Microsoft time updates to jquery.unobtrusive-ajax.js and related libraries to updates to ASP.NET MVC? If so then it would seem to make sense to hold off updating dependencies until ASP.NET MVC is updated.

A: jQuery deprecated the .live() method in v1.9. It can be replaced with .on(). This broke jquery.unobtrusive-ajax.js. I know from experience when cursing the update that I first pulled from NuGet.
There is an update to jquery.validate out there, also mentioned in this thread. But I have not validated it yet, jquery 1.9.1 is available as well.
For your questions...

*

*I think it is good practice to keep your packages upto date, but also research any deprecated functionality. Also using some source save like tools is a good idea. You could easily revert any breaking changes with one or two mouse clicks.

*Even though there is not a \packages folder added to you virgin project (intra or internet). If you open up the NuGet package manager UI, updates will still show up.


text:
Q: How to print a newline when running 'python -c' The following prints the 2-characters \ and n between each item in the list instead of a newline.
python3 -c 'import airflow.operators as air_ops;  \
    print([f"""{k}: {v}\n""" for k,v in air_ops.__dict__.items()])'

How can we get the desired escape character/newline when running python -c ?

A: This has nothing to do with python3 -c or semicolons or backslashes, actually. Your problem is that you're printing a list of strings, i.e. the for-loop is inside the list comprehension. String elements inside of a list will always be represented using their repr, which means newline characters will be escaped.
Instead, just use a loop. Literal newlines are fine for python3 -c. Let the print function append the trailing new line. You can leave out all the semicolons and  backslashes.
$ python3 -c 'd = {"k1": "v1", "k2": "v2"}
> for k, v in d.items():
>     print(f"{k}: {v}")
> '
k1: v1
k2: v2


text:
Q: order unique accounts by date I have a table:
create table remote (account int ,datecreated datetime,status int)
insert into remote (account , datecreated,status)
values

(123,'2015-08-25',1),
(123,'2015-08-25',1),
(123,'2015-09-26',1),
(1238,'2015-08-25',1),

(123,'2014-08-25',1),
(123,'2014-08-26',1),
(1238,'2014-08-25',1),
(1238,'2014-08-25',1),
(1235,'2014-08-25',1),

(1234,'2014-09-22',1),
(1234,'2014-09-22',1),

(1234,'2014-10-29',1),
(1236,'2014-10-25',1);

From here I would like to get the unique account count for each month/year where status=1
For example using the data above:
the output would be
count | month
-------------
1      |9/2015
2      |8/2015
2      |10/2014
1      |9/2014
3      |8/2014

How can I make this work?
I use sql 2012.

A: This is a group by query with a filter and some datetime logic:
select year(datecreated) as yr, month(datecreated) as mon, count(*)
from remote
where status = 1
group by year(datecreated), month(datecreated)
order by yr desc, mon desc;

This puts the year and month into separate columns.  You can concatenate them together into a single value if you really want to.

A: Use Group by month and year of datecreated to skip day part in count. use the same month and year in order by desc . Then Concatenate the month and year to get the result
SELECT [Count],
       [Mon/Year]= CONVERT(VARCHAR(2), [Month]) + '/' + CONVERT(VARCHAR(4), [year])
FROM  (SELECT [year]=Year(datecreated),
              [month]= Month(datecreated),
              [Count]= Count(distinct account)
       FROM   remote
       GROUP  BY Year(datecreated),
                 Month(datecreated)) a
ORDER  BY [year] DESC,[Month] DESC

Result
Count   Mon/Year
-----   --------
1       9/2015
3       8/2015
2       10/2014
1       9/2014
5       8/2014


text:
Q: What is the subject of a participial phrase?
But the hand which I now saw, clearly enough, in the yellow light of a
mid-London morning, lying half shut on the bedclothes, was lean,
corded, knuckly, of a dusky pallor and thickly shaded with a swart
growth of hair.

This is from the classic novel Strange Case of Dr. Jekyll and Mr. Hyde. I wonder what was lying half shut on the bedclothes. Was it a hand or speaker itself?

A: It was the hand.
There is technically some ambiguity, but we do not talk of people lying half shut, or for that matter parts of the day - a mid-London morning might just as well have been modified by lying half shut.


text:
Q: jQuery UI Datepicker in React throws Uncaught TypeError When trying to get jQuery UI Datepicker working with React.js in a JSFiddle, the following error gets thrown in the console when you click on the input box:

Uncaught TypeError: newDate.setHours is not a function

Link to JSFiddle: http://jsfiddle.net/bengrunfeld/9ay9qdmd/
var Date = React.createClass({
    render: function() {
        return <input type="text" className="datepicker" />;
    }
});

var Calendar = React.createClass({
    componentDidMount: function() {
        $('.datepicker').datepicker();
    },
    render: function() {
        return (
            <form>
                <Date />
            </form>
        )
    }
});

React.render(<Calendar />, document.body);

A: You've redefined a core JavaScript object: Date. If you rename it to something else, like DateInput, it works.
var DateInput = React.createClass({
    render: function() {
        return <input type="text" className="datepicker" />;
    }
});


text:
Q: StringBuilder.insert() not changing output I'm trying to make a short program that converts any string into T H I S F O N T.
For example: "This is a test sentence" turns into "T H I S I S A T E S T S E N T N C E"
I have a StringBuilder inside a while loop, but using finale.insert(i, '\t'); doesn't work.
import java.util.Scanner;

public class Executable {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        String x;
        int i = 0;

        System.out.print("Input text here: ");
        x = input.nextLine();

        StringBuilder finale = new StringBuilder(x.toUpperCase());

        while(i > finale.length()) {
            if(finale.substring(i, i) == " ") {
                i += 2;

                finale.insert(i, '\t');
            }
        }

        System.out.println(finale);

    }
}

Any help?

A: You're saying while i>finale.length() but i is initialized as 0. You never enter the while loop.

A: You have a few issues with your code. Before I present an implementation that works, let's look at those other issues.

*

*Your while loop checks if i > finale.length(). Since i = 0 the while loop never has a chance to begin.

*You are comparing strings using == and this is not correct. == is used to confirm two objects are equal, not the value of two strings.  You would need to use string.equals() instead.

*You're doing too much in your loop anyway. Using a simple for loop can accomplish the goal quite simply.

Here is a new loop you can use instead of what you have:
for (int i = 1; i < finale.length(); i++) {
    finale.insert(i++, " ");
}

The output: T H I S   F O N T

For those unfamiliar with for loops, here's a very simple breakdown of how the above is structured.
The for loop is defined in three parts:
for (variable_to_increment; repeat_until_this_condition_is_met; modify_variable_on_each_iteration) {
    // Code to be executed during each pass of the loop
}

*

*First, we define a variable that we can track on each loop: int i = 1. By setting i = 1, we are going to skip the first character in the string.

*The next statement, i < finale.length() means that we want to keep repeating this loop until we reach the length of our string. For example, if the string is 5 characters long and we've run the loop 4 times, i now equals 5 and is no longer less than the string's length, so the loop ends.

*The last part is i++. This tells Java what we want to do with i after each loop. In this case, we want to increment the value by 1 each time the loop repeats.

*Everything inside the brackets is, obviously, the code we want to execute on each loop.

A: Some issues with your code (see inline comments):
import java.util.Scanner;

public class Executable {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        String x;
        int i = 0;

        System.out.print("Input text here: ");
        x = input.nextLine();

        StringBuilder finale = new StringBuilder(x.toUpperCase());

        while(i > finale.length()) { // this condition is incorrect. Initially
                                     // this condition will always be false
                                     // if you input some sentence. It should be
                                     // i < finale.length()
            if(finale.substring(i, i) == " ") { // here preferably you should use
                                                // equals method to compare strings
                i += 2;
                // you are only incrementing the i if the ith
                // substring equals " ". Firstly, substring(i,i)
                // will return empty string because the second argument
                // is exclusive
                finale.insert(i, '\t');
            }
        }

        System.out.println(finale);

    }
}

If you want to have an alternate method (not very optimal) for doing what you want to do, you can try the following approach:
import java.util.Scanner;

public class Executable {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        String x;
        int i = 0;

        System.out.print("Input text here: ");
        x = input.nextLine();

        String finale = x.toUpperCase().replaceAll(" ","").replaceAll("", " ");

        System.out.println(finale);

    }
}

First, convert the string to uppercase --> then remove all spaces between the words --> then insert spaces between all letters. The code line which does this is,
String finale = x.toUpperCase().replaceAll(" ","").replaceAll("", " ");

Here is a sample run:
Input text here: This is a sentence
 T H I S I S A S E N T E N C E

A: *

*The correct way with your method would be, just increment until you have twice the size of the initial String
while (i < x.length() * 2) {
    finale.insert(i, '\t');
    i += 2;
}

*An easier way would be with a classic for-loop:
StringBuilder finale = new StringBuilder();
for (char c : x.toUpperCase().toCharArray()) {
    finale.append(c).append('\t');
}

A: Use a for loop since you know the number of iterations:
    Scanner input = new Scanner(System.in);

    String x;

    System.out.print("Input text here: ");
    x = input.nextLine();

    StringBuilder finale = new StringBuilder(x.toUpperCase());

    int len = finale.length();
    for (int i = 1; i < 2 * len; i+=2 ) {
        finale.insert(i, '\t');
    }

    System.out.println(finale);

A: You are comparing strings with ==. Never do that; use equals instead.
For future readers: this job can be done elegantly using Java 8 Streams:
String result = str.chars()
    .filter(i -> i != ' ')
    .mapToObj(t -> (char) t)
    .map(Character::toUpperCase)
    .map(Character::valueOf)
    .collect(Collectors.joining(" ");


text:
Q: Returning query results in predefined order Is it possible to do a SELECT statement with a predetermined order, ie. selecting IDs 7,2,5,9 and 8 and returning them in that order, based on nothing more than the ID field?
Both these statements return them in the same order:
SELECT id FROM table WHERE id in (7,2,5,9,8)

SELECT id FROM table WHERE id in (8,2,5,9,7)

A: I didn't think this was possible, but found a blog entry here that seems to do the type of thing you're after:
SELECT id FROM table WHERE id in (7,2,5,9,8)
ORDER BY FIND_IN_SET(id,"7,2,5,9,8");

will give different results to
SELECT id FROM table WHERE id in (7,2,5,9,8)
ORDER BY FIND_IN_SET(id,"8,2,5,9,7");

FIND_IN_SET returns the position of id in the second argument given to it, so for the first case above, id of 7 is at position 1 in the set, 2 at 2 and so on - mysql internally works out something like
id | FIND_IN_SET
---|-----------
7  | 1
2  | 2
5  | 3

then orders by the results of FIND_IN_SET.

A: Your best bet is:
ORDER BY FIELD(ID,7,2,4,5,8)

...but it's still ugly.

A: Could you include a case expression that maps your IDs 7,2,5,... to the ordinals 1,2,3,... and then order by that expression?

A: All ordering is done by the ORDER BY keywords, you can only however sort ascending and descending. If you are using a language such as PHP you can then sort them accordingly using some code but I do not believe it is possible with MySQL alone.

A: This works in Oracle.  Can you do something similar in MySql?
SELECT ID_FIELD
FROM SOME_TABLE
WHERE ID_FIELD IN(11,10,14,12,13)
ORDER BY
  CASE WHEN ID_FIELD = 11 THEN 0
       WHEN ID_FIELD = 10 THEN 1
       WHEN ID_FIELD = 14 THEN 2
       WHEN ID_FIELD = 12 THEN 3
       WHEN ID_FIELD = 13 THEN 4
  END

A: You may need to create a temp table with an autonumber field and insert into it in the desired order. Then sort on the new autonumber field.

A: It's hacky (and probably slow), but you can get the effect with UNION ALL:
SELECT id FROM table WHERE id = 7
UNION ALL SELECT id FROM table WHERE id = 2
UNION ALL SELECT id FROM table WHERE id = 5
UNION ALL SELECT id FROM table WHERE id = 9
UNION ALL SELECT id FROM table WHERE id = 8;

Edit: Other people mentioned the find_in_set function which is documented here.

A: Erm, not really. Closest you can get is probably:
SELECT * FROM table WHERE id IN (3, 2, 1, 4) ORDER BY id=4, id=1, id=2, id=3

But you probably don't want that :)
It's hard to give you any more specific advice without more information about what's in the tables.

A: You get answers fast around here, don't you…
The reason I'm asking this is that it's the only way I can think of to avoid sorting a complex multidimensional array. I'm not saying it would be difficult to sort, but if there were a simpler way to do it with straight sql, then why not.

A: One Oracle solution is:
SELECT id FROM table WHERE id in (7,2,5,9,8)
ORDER BY DECODE(id,7,1,2,2,5,3,9,4,8,5,6);

This assigns an order number to each ID.  Works OK for a small set of values.

A: Best I can think of is adding a second Column orderColumn:
7 1
2 2
5 3
9 4
8 5

And then just do a ORDER BY orderColumn


text:
Q: How to loop PL/SQL a:=a+2; DECLARE

a number(20):=5;
BEGIN
    FOR a in 1..20 LOOP
    dbms_output.put_line('value: '|| a);

    a:=a+2;

    END LOOP;

    END;

Error is :

Error report: ORA-06550: line 8, column 5: PLS-00363: expression 'A'
  cannot be used as an assignment target ORA-06550: line 8, column 5:
  PL/SQL: Statement ignored
  06550. 00000 -  "line %s, column %s:\n%s"
  *Cause:    Usually a PL/SQL compilation error.
  *Action:

How can i do that?

A: The a in the for loop is a for loop index and is read only.
Note that a in the for loop is declared implicitly and is not the same variable as a in the declare section.
This is explained in the documentation.
If you want to modify the value of your variable a inside the loop simply give the for loop index another name:
DECLARE
a number(20):=5;
BEGIN
    -- Note that no declaration of b is necessary
    FOR b in 1..20 LOOP
        dbms_output.put_line('value: '|| a);
        a:=a+2;
    END LOOP;
END;


text:
Q: NetBeans Error Ambiguous on Method contains(Object) Can anybody help me to fix this error in NetBeans 8.0.2 ? I am using Java 1.7 on Mac. This error did not occurred in Eclipse. Netbeans always tell me that the method contains(Object) ambiguous within Collection or List, whereas I am using ArrayList in my method.
reference to contains is ambiguous
  both method contains(Object) in Collection and method contains(Object) in List match
----
(Alt-Enter shows hints)

A: That's... just... weird.  List inherits from Collection and overrides the contains(Object) method, which is implemented in ArrayList.  This works fine in Eclipse.
Looks like a serious bug in NetBeans to me.
I recommend reinstalling NetBeans from scratch to see if that fixes the problem.


text:
Q: Arranging Triangles Consider three identical equilateral triangles of fixed size in a plane that do not intersect.  Connect their centers to form a fourth triangle.  Arrange the original three triangles to produce the smallest possible fourth triangle that is equilateral.  What is its size relative to the original three?  Here is an example:

This problem came up in arranging painters triangles to support a small bowl.


text:
Q: JAVA try catch ArrayIndexOutOfBoundsException I would like to Rewrite the getContents method below to incorporate exception handling. In particular, when an ArrayIndexOutOfBoundsException is generated, the method should return the value -1.0
public class Four
{
 private double [] numbers = {1.0, 2.0, 3.0, 4.0};

 public double getContents(int index)
 {
 return numbers[index];
 }
}

A: public class Four
{
    private double [] numbers = {1.0, 2.0, 3.0, 4.0};

    public double getContents(int index)
    {
       try
       {
          return numbers[index];
       }
       catch(ArrayIndexOutOfBoundsException e)
       {
          return -1.0;
       }
    }
}

A: try {
    return numbers[index] ;
}
catch(ArrayIndexOutOfBoundsException exception) {
    return -1;
}

A: you could do it this way
public double getContents(int index)
 {
  try {
   return numbers[index];
  } catch (ArrayIndexOutOfBoundsException e){
   return -1.0;
  }
 }

otherwise you could just check if the index is larger than the size of your array.


text:
Q: Save excel worksheet to specific folder and filename based on same cell I am trying to save a copy of a worksheet to a specific folder based on cell B8 and name the .xlsx file based on the cell range B8 too.
For example, a user first creates a new folder named "test1", & then enters this folder name/text into cell "B8".  He/she will activate the macro after completing their work on the worksheet, & it will save a copy to the folder named "test1" and name the .xlsx file as "test1".  (So the .xlsx file will be named as "testfolder1" and the folder where it is stored is also called "test1")
I am using the following code to save a copy of the worksheet to a folder. Just can't figure out how to include the cell B8 into the SaveAs line. Too new with VB to figure it out.
Sub SaveForm()

 exampleForm = Range("B8").Value

Application.ScreenUpdating = False
Application.DisplayAlerts = False

ActiveSheet.Copy
With ActiveWorkbook.ActiveSheet
    .Range("42:" & Rows.Count).EntireRow.Delete xlShiftDown
    .Range(.Cells(1, "J"), .Cells(1, Columns.Count)).EntireColumn.Delete xlToRight
    .Parent.SaveAs "C:\Users\JohnSmith\Desktop\ExtractedWorksheet\" &  exampleForm & ".xlsx"
    .Parent.Close False
End With
End Sub

Appreciate any input and hopefully my ending goal is understandable.
-Thanks!

A: I think this is what you're after, give it a try:
Sub SaveForm()
Static Path as string
Static FileName as string

if len(Path) = 0 then
  Path = Range("B8")
  if right(Path,1) <> "\" then
    'make sure the path is "\" terminated
    Path = Path & "\"
  End if
else
  FileName = Range("B8")

  'Application.ScreenUpdating = False
  Application.DisplayAlerts = False
  ActiveSheet.Copy   'not sure why you're doing this, but do so if it makes sense elsewhere in your code
  With ActiveWorkbook.ActiveSheet
    .Range("42:" & Rows.Count).EntireRow.Delete xlShiftDown
    .Range(.Cells(1, "J"), .Cells(1, Columns.Count)).EntireColumn.Delete xlToRight
    .Parent.SaveAs "C:\Users\JohnSmith\Desktop\ExtractedWorksheet\" & Path & _
                   FileName & ".xlsx"
    .Parent.Close False
  End With
  Path = ""
  FileName = ""
End if
End Sub

If you call this code from your worksheet_OnChange event, then when cell B8 is updated, it will:

*

*check to see if you have a Path stored. If not, assume this is the Path

*If you have a Path already, assume this is the FileName and save it.

Leave the 'Application.ScreenUpdating` commented out until everything is working OK, then put it back in. Makes figuring out what's going on much easier.
UPDATE based on your latest comment on OP:
Sub SaveForm()

  'Application.ScreenUpdating = False
  Application.DisplayAlerts = False
  ActiveSheet.Copy   'not sure why you're doing this, but do so if it makes sense elsewhere in your code
  With ActiveWorkbook.ActiveSheet
    .Range("42:" & Rows.Count).EntireRow.Delete xlShiftDown
    .Range(.Cells(1, "J"), .Cells(1, Columns.Count)).EntireColumn.Delete xlToRight
    .Parent.SaveAs "C:\Users\JohnSmith\Desktop\ExtractedWorksheet\" & _
                   Range("B8")  & "\" & FileName & ".xlsx"
    .Parent.Close False
  End With
  Path = ""
  FileName = ""
End Sub

A: Here is one that I have created for a project that I worked on.

*

*I first named a cell (through Excel user interface-formula-name
manager-define name) and called it prform_prnumber.

*I passed the value in that to a variant variable in vba and called it prnumber.

*I then used that variable as name in the exporttopdf method.

*I kept the path as that of the workbook.

This code will run (once the button is clicked) in the active worksheet:
Sub exporttopdf()

Dim prnumber As Variant
Set prnumber = ActiveWorkbook.Names("prform_prnumber").RefersToRange

ActiveSheet.ExportAsFixedFormat xlTypePDF, ActiveWorkbook.Path & "/" & filesavename & ".pdf", , , False

End Sub


text:
Q: Add Android Source build jar library to Android Studio I did tried many solution on Stackoverflow to include library in Android Studio.
I am trying to build the jar file in android source.
I have my source copied to /device/company_name/Device_name/Amol/framework/java/com/symbol/amol/Amol.java
After build completes. I see the com.symbol.amol.jar is created in /system/framework/.
Now, to try this jar file, I have created a Android application in Android Studio.
I have included the jar in Dependencies.
Here it is what I see in gradle file after adding the jar in dependencies:
=> compile files('libs/com.symbol.amol.jar')
Application compiles fine.
But now if I add 'import com.symbol.amol' in the Activity.java file in the application, the error I get is => error: package com.symbol.amol does not exists.
Following is the image when I extract jar file.

A: Try to go to the Project Properties -> App -> Dependencies and add your jar dependencies, this will do all instead of you


text:
Q: HTTP status 500 for wso2 carbon application I tried this tutorial and after entering with admin as in step 8, I got the error as follows:
HTTP Status 500 - Exception while making the decision : org.apache.axis2.AxisFault: Connection refused: connect
org.wso2.carbon.identity.entitlement.filter.exception.EntitlementFilterException: Exception while making the decision : org.apache.axis2.AxisFault: Connection refused: connect
org.wso2.carbon.identity.entitlement.filter.EntitlementFilter.doFilter(EntitlementFilter.java:191)

A: 1)
Is your WSO2 Server running against loclahost only or is it just running on his IP adres? Looks like you are not able to contact the server through this IP and/or port number.
2)
Are there any proxies defined? If so, try to disable them.


text:
Q: Waiting for inputs to end and only then reading the textbox Basically, I want to make a constant input reader in my form, that waits for inputs and only after the input finishes(these inputs are from an external source, specifically - a hand-held scanner) should it be read, this code works exactly how I want, because the scanner at the end of input somehow informs that it's the end of stream/line(not really sure how though):
while (true)
{
    string someString = Console.ReadLine();
    doSomethingWithString(someString);
}

but I don't know how to cleanly transfer it to a form application.
Any help would be appreciated.

A: Assuming I understand you correctly, you want to do something like this:
public void SendScansToForm(string[] scans) //pass in an array (or list, or etc.) of the scanned items
{
    MyForm form = new MyForm(); //Create a new instance of the form
    form.variableToHoldScans = scans; //variable (on the form instance) to pass the scan to
}

In this way, you read in all the scans, then pass them into a new instance of the form. Presumably, this could be followed with a form.Open() or display the scans to the user, or change as needed to do whatever task is required.
EDIT:
Apparently I didn't understand; if you want to port the current code to forms, you can use System.IO.Stream (as mentioned in the comments). Additionally, you will need to determine how the scanner terminates an entry. This may be with a return character \n, \r, etc. or some other method and likely changes with different scanner models.
EDIT 2 - Additional info from the comments:
In order to read input from a scanner, you need to determine what character it's passing in to terminate the input. From my limited experience, this should be carriage return, line feed, enter or something similar.
Once this has been determined, it should be trivial to implement a method that acts on the presence of this character, allowing you to process each scan as they come in.


text:
Q: Out of source builds (external build directory) with Cargo? Having used CMake, I've become used to out-of-source builds, which are encouraged with CMake. How can out-of-source builds be done with Cargo?

Using in-source-builds again feels like a step backwards:

*

*Development tools need to be configured to ignore paths. Sometimes multiple plugins and development tools - especially using VIM or Emacs!

*Some tools can't be configured to easily hide build files. While dotfiles are typically hidden, they will still show Cargo.lock and target/, worse still, recursively exposing their contents.

*Deleting un-tracked files to remove everything outside of version control, typically to cleanup editor temp files or some test output, can backfire if you forgot to add a new file to version control and don't manually check the file list properly before deleting them.

*Dependencies are downloaded into your source code path, sometimes adding *.rs files in the target directory as part of building indirect deps, so operating on all *.rs files may accidentally pickup other files which aren't in a hidden directory, so might not be ignored even after development tools have been configured.

While it's possible to work around all these issues, I'd rather just have an external build path and keep the source directory pristine.

A: While useful manually setting this up isn't all that convenient, I wanted to be able to build multiple crates within a source tree, having all of them out-of-source, something that ../target-dir configuration option wouldn't achieve.

Helper utility for convenient out-of-source builds
Using the environment variable I've written a small utility to wrap cargo, so it automatically builds out-of-source, supporting crates both at the top-level, on in a subdirectory of the source tree.

Thanks to Lukas for pointing out CARGO_TARGET_DIR and target-dir configuration option.

A: You can specify the directory of the target/ folder either via configuration file (key build.target-dir) or environment variable (CARGO_TARGET_DIR). Here is an example using a configuration file:
Suppose you want to have a directory ~/work/ in which you want to save the Cargo project (~/work/foo/) and next to it the target directory (~/work/my-target/).
$ cd ~/work
$ cargo new --bin foo
$ mkdir .cargo
$ $EDITOR .cargo/config

Then insert the following into the configuration file:
[build]
target-dir = "./my-target"

If you then build in your normal Cargo project directory:
$ cd foo
$ cargo build

You will notice that there is no target/ dir, but everything is in ~/work/my-target/.

However, the Cargo.lock is still saved inside the Cargo project directory, but that kinda makes sense. For executables, you should check the Cargo.lock file into your git! For libraries, you shouldn't. I guess having to ignore one file is better than having to ignore an entire folder.
Lastly, there are a few caveats to changing the target-dir, which are listed in the PR which introduced the feature.

A: What I really wanted was a dynamic CARGO_TARGET_DIR that changes relative to where I am.
This bash alias puts all builds in a mirrored directory structure, e.g. instead of putting target into ~/mydir/myproj it puts in into ~/rustbuild/mydir/myproj
alias cargo='CARGO_TARGET_DIR=$(echo $PWD | sed "s|$HOME|$HOME/rustbuild|g") cargo'

You could also make your rustbuild directory hidden.


text:
Q: Inserted EmailMessage always "Outbound"? We have an inbound Email handler that currently just creates a Task. I'd like to update it to create an EmailMessage object instead. However I've noticed that when viewing the Apex-inserted object in Salesforce it appears with a heading of "Outbound Email Message".
Is there a way to signal to Salesforce, when creating an EmailMessage, that it was in fact inbound?

A: You need to set the Incomng field to true. See the documentation:

Field
  Incoming
Type
  boolean
Properties
  Create, Defaulted on create, Filter
Description
  Indicates whether the email was received (true) or sent (false).


text:
Q: Grafana dashboard panel with custom time range I have a Grafana dashboard with a time range for "today so far"
"time": {
    "from": "now/d",
    "to": "now"
 }

But I have a service that runs only between 4am and 5am every day for which I would like to plot some metrics in a panel on this dashboard. I'm trying to set the time range for that panel to 4am-5am of the current day so that it doesn't show a full 24 hour x-axis for data that only exists between 4am and 5am. If I were able to specify the time range for the panel using From: and To:, it would have looked something like this:
"time": {
    "from": "now/d+4h",
    "to": "now/d-19h"
 }

But of course, you can't specify a time range like that for individual panels. You have to make use of the Relative Time and Time Shift values in Query Options for the panel but, for the life of me, I can't figure out how to represent the time range I want in relative time using those two values. It would seem that Grafana's documentation in this regard is sorely lacking; They only show a few very basic and specific examples, none of which helps me with this query.
Would anyone be able to set me straight here please?
For what it's worth, my data source for this Grafana dashboard is Prometheus but I don't think that is germane to this question.


text:
Q: How to read a text file from last line to first line in c#
Possible Duplicate:
How to read a text file reversely with iterator in C#

I wanted to know how to read a text file from last line to first line in c#.
I am using this code for reading a text file
            using (var sr = File.OpenText("C:\\test.txt"))
            {
                string line;
                bool flag = true;
                while ((line = sr.ReadLine()) != null)
                {
                }
            }

I dont know how to read Backwards.
There would be a great appreciation if someone could help me.
Thanks In Advance.

A: Try to reverse the collection of read lines
    List<string> lines = new List<string>();
    using (var sr = File.OpenText("C:\\test.txt"))
    {
        string line;
        while ((line = sr.ReadLine()) != null)
        {
            lines.Add(line);
        }
    }

    lines.Reverse();

A: File.ReadAllLines(@"C:\test.txt").Reverse()


text:
Q: Rails + Delayed jobs: SSH connections pool Current situation:
I have a rails app with N delayed job workers. Whenever I want to send an SSH request to some machine, I create a task for the worker. Worker performs something like:
Net:SSH.start(hostname, username, :password => pass) do |ssh|
  ssh.exec!(command)
end

Sometimes I create e.g. 50 such tasks to be performed one by one, or within 5-10 minutes from each other. Each task in this case opens separate connection, which is not effective and sometimes is blocked by target servers due to too many connections.
What I want: Have opened connections stored somewhere and reused by each worker. So that each worker obtains connection somehow and then just run
ssh.exec!(command)

What I have tried:

*

*storing connections in file/database/cache looks to be not possible as they are not serializable

*have tried using singleton class with global variables instantiated under initializers. However class object is different for each worker (later have found that global variables can not be an option).

Are there way to solve that? Any other ideas? Thanks!!

A: First some basics; one SSH connection is at its core a low-level socket connection to a remote machine. Sockets cannot be (easily) shared between processes. Therefore things that run on multiple processes cannot share the same SSH connection.
Next you need to know which parts in your current setup are run in separate processes. What we get is:

*

*Rails is in most cases process-based: separate web requests run on separate processes. So storing SSH connections in a Rails app is not a reliable solution.

*Delayed Job is, as far as I know, also process-based. A master process launches slave processes to handle each job. Therefore DJ doesn't work for this purpose either.
What you need is a master process that stores the SSH session(s), and then waits for incoming messages that are commands which need to be executed on one of your remote SSH machines.
Personally I would just code a simple threaded Ruby daemon process myself that handles this task. You could use something like EventMachine to handle the communication and processing if you don't want to deal with socket programming directly.
If you're not comfortable with EventMachine or socket programming, then you could look at some messaging systems like RabbitMQ, or
ZeroMQ to create your client and server with.
I also found something for Rails called ActiveMessaging, although I'm not sure how current and working that project is.
But like I said, I think the simplest implementation is just a socket daemon process that runs in the background and keeps track of the open SSH connections, and then listens to commands from your Rails app.
Remember to take into account security considerations also if you implement something like this. Otherwise you can easily give anyone SSH access to all your remote machines through your daemon process.
EDIT
An even simpler idea:
Just have a daemon process periodically read commands from a database table from your Rails app. Then this daemon can execute these commands based on what it finds in this "job queue" table. This way you don't have to deal with socket communications at all, with the disadvantage that this solution is a polling solution.


text:
Q: Get Microphone Permission when Phone is Locked I'd love to know if there is any way for an app to be recording the microphone/camera input when the screen is locked, granted proper permissions given by the user. The question is valid for both Android and iOS (both native).
Cheers!


text:
Q: Strategies to speed up Odoo search queries via XML-RPC when ordered Using Odoo 14 hosted by odoo.sh.
I would like to know if there are any methods to speed up an XML-RPC search. For instance, if I want use an order of 'write_date ASC' or 'id ASC', this will cause several models to timeout (HTTP 502) when attempting to return even a single record. Is it possible to set indexes on the models that I want to set a sort order for to make the queries more efficient? I am essentially trying to iterate every record via a cursor, hence needing to order the results.
Any help is appreciated. Thanks.


text:
Q: Linux block driver merge bio's I have a block device driver which is working, after a fashion. It is for a PCIe device, and I am handling the bios directly with a make_request_fn rather than use a request queue, as the device has no seek time. However, it still has transaction overhead.
When I read consecutively from the device, I get bios with many segments (generally my maximum of 32), each consisting of 2 hardware sectors (so 2 * 2k) and this is then handled as one scatter-gather transaction to the device, saving a lot of signaling overhead. However on a write, the bios each have just one segment of 2 sectors and therefore the operations take a lot longer in total. What I would like to happen is to somehow cause the incoming bios to consist of many segments, or to merge bios sensibly together myself. What is the right approach here?
The current content of the make_request_fn is something along the lines of:

*

*Determine read/write of the bio

*For each segment in the bio, make an entry in a scatterlist* with sg_set_page

*Map this scatterlist to PCI with pci_map_sg

*For every segment in the scatterlist, add to a device-specific structure defining a multiple-segment DMA scatter-gather operation

*Map that structure to DMA

*Carry out transaction

*Unmap structure and SG DMA

*Call bio_endio with -EIO if failed and 0 if succeeded.

The request queue is set up like:
#define MYDEV_BLOCK_MAX_SEGS 32
#define MYDEV_SECTOR_SIZE 2048

blk_queue_make_request(mydev->queue, mydev_make_req);

set_bit(QUEUE_FLAG_NONROT, &mydev->queue->queue_flags);
blk_queue_max_segments(mydev->queue, MYDEV_BLOCK_MAX_SEGS);
blk_queue_physical_block_size(mydev->queue, MYDEV_SECTOR_SIZE);
blk_queue_logical_block_size(mydev->queue, MYDEV_SECTOR_SIZE);

blk_queue_flush(mydev->queue, 0);

blk_queue_segment_boundary(mydev->queue, -1UL);
blk_queue_max_segments(mydev->queue, MYDEV_BLOCK_MAX_SEGS);
blk_queue_dma_alignment(mydev->queue, 0x7);