text:
Q: Database connection PrepareStatement with unknown NULL Pointer I'm new to the use of Java with database connections, but am getting a NullPointerException using the following code:
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

public ArrayList<UserVO> getAllUsers(Connection connection) throws Exception {
            ArrayList<UserVO> userList = new ArrayList<UserVO>();
            try {
                PreparedStatement ps = connection.prepareStatement("SELECT * FROM user");
                ResultSet rs = ps.executeQuery();
                while (rs.next()) {
                    UserVO uservo = new UserVO();
                    uservo.setUsername(rs.getString("username"));
                    uservo.setPassword(rs.getString("password"));
                    userList.add(uservo);
                }
                return userList;
            } catch (Exception e) {
            throw e;
            }
        }

    }

At
PreparedStatement ps = connection.prepareStatement("SELECT * FROM user");

the code throws an exception for java.lang.NullPointerException.I don't know why this is happening, as a
System.out.println("isClosed = " + connection.isClosed());

before the PreparedStatement declaration returns false, and I can print out the connection info.
Any idea of the cause or how to properly compose a statement before query execution? Thanks!
EDIT: Full(ish) stack trace - it's very long
java.lang.NullPointerException
    at com.mysql.jdbc.PreparedStatement.asSql(PreparedStatement.java:649)
    at com.mysql.jdbc.PreparedStatement.asSql(PreparedStatement.java:587)
    at com.mysql.jdbc.PreparedStatement.toString(PreparedStatement.java:4068)
    at java.lang.String.valueOf(String.java:2994)
    at java.lang.StringBuffer.append(StringBuffer.java:263)
    at com.mysql.jdbc.trace.Tracer.printParameters(Tracer.aj:240)
    at com.mysql.jdbc.trace.Tracer.printEntering(Tracer.aj:167)
    at com.mysql.jdbc.trace.Tracer.entry(Tracer.aj:126)
    at com.mysql.jdbc.trace.Tracer.ajc$before$com_mysql_jdbc_trace_Tracer$1$f51c62b8(Tracer.aj:45)
    at com.mysql.jdbc.Connection.registerStatement(Connection.java)
    at com.mysql.jdbc.Statement.<init>(Statement.java:270)
    at com.mysql.jdbc.PreparedStatement.<init>


text:
Q: Names for generic classes - how to avoid naming them just "object"? Use synonyms? When programming, I often end up naming some generic class (think of an abstract base class for stuff you manage in your project) something like FooObject, FooComponent or FooItem (where Foo is an abreviation of project name). The problem is, that these names are used so often, they become meaningless - I mean, when I'm talking about an "object", no-one knows whether I mean "a subclass of FooObject", or an ordinary object.
I think that a good list of synonyms for "object", "component", "callback", "handler", "action" and so on would help, because we could just redefine these world on a per-project basis. You could even make up some totally nonsense word and define your meaning in documentation. I think it would be clearer than naming stuff "objects".
Here's what I mean by "nonsense" (taken from Alice in Wonderland):

Twas brillig, and the slithy toves
Did gyre and gimble in the wabe:
All mimsy were the borogoves,
And the mome raths outgrabe.

Maybe you can have some nice words you use in such cases?
How do you deal with similar situations in your projects?
[ Related: How to avoid general names for abstract classes? ]

A: On the matter, Kent Beck said:

"[...] The names should be short and punchy. However, to make the
  names precise sometimes seems to require several words. A way out of
  this dilemma is picking a strong metaphor for the computation. With a
  metaphor in mind, even single words bring with them a rich web of
  associations, connections, and implications. For example, in the
  HotDraw drawing framework, my first name for an object in a drawing
  was DrawingObject. Ward Cunningham came along with the typography
  metaphor: a drawing is like a printed, laid-out page. Graphical items
  on a page are figures, so the class became Figure. In the context of
  the metaphor, Figure is simultaneously shorter, richer, and more
  precise than DrawingObject."

(From Marcio Aguiar's answer in https://stackoverflow.com/questions/38019/whats-the-best-approach-to-naming-classes)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why doesn't rails.vim recognize any gems that I install? I'm a ruby and vim newbie. I recently installed the rails.vim plugin and all the commands work fine apart from the commands to create a new Rails project. Every time I do this it says rails is not installed on my system, but it is! It also acts up when I create a class that requires a gem that I've installed. Can anyone help with this?

A: Did you rvm use system before building / brew install-ing macvim? I didn't and got many errors. Doing rvm use system beforehand fixed things up for me.


text:
Q: Move torrent in folders fixing moving inside folders I use 2 scripts to reordening by year torrent files inside folders but each of these scripts are incomplete because I must use both to move them.
For example
1st scripts
    @Echo Off
For %%a In (*19???.torrent *20???.torrent) Do Call :Sub "%%~a"
Exit/B
:Sub
Set "mfn=%~n1"
Set "lfc=%mfn:~-5%
Set "lfc=%lfc:(= %"
Set "lfc=%lfc:)= %"
Set "lfc=%lfc: =%"
If Not Exist "%lfc%\" MD %lfc%
Move %1 %lfc%

DON'T MOVE files like (files extension is .torrent)
Animali Pazzi (1939) Toto
Anno 2000 La Corsa Della Morte
American History X 1998 1080p ENG
Devil 2010_001

2nd script
@Echo Off
For /F "Tokens=*" %%a In (
    'Dir/B/A-D *.torrent^|Findstr/R "\<19[0-9][0-9]\> \<20[0-1][0-9]\>"') Do (
    For %%b In (%%~na) Do Call :Sub "%%a" "%%b")
Pause
Exit/B
:Sub
Set "mfn=%~2"
Set "mfn=%mfn:(=%"
If %mfn:)=% GEq 1900 (If %mfn:)=% Lss 2017 (If Not Exist "%mfn:)=%\" MD %mfn:)=%
        Move %1 %mfn:)=%))

but DON'T MOVE files like
Alla 39 Eclisse - The Awakening 1980_001
Predators 2010_002
Sono il Numero Quattro.2011_001
Abbronzatissimi.1991.avi
Continuavano a chiamarlo trinita1971 x264
32.Dicembre.1988.avi

I want a FUSION of both script that FIXING this moving problem.

A: I would suggest a different scripting method, such as powershell:
$ToFolder = "$env:USERPROFILE\Desktop\to"
$FromFolder = "$env:USERPROFILE\Desktop\From"

#Create the sample folder on your desktop
#This line can be commented out if your ToFolder exists
New-Item $ToFolder -ItemType directory -Force

GCI -Path $FromFolder *.torrent | % {
    if ($_.Name -match "(19|20)\d{2}") {

        #Check to see if year folder already exists at the destination
        #If not then create a folder based on this year
        if (!(Test-Path "$ToFolder\$($Matches[0])")) {
            New-Item -Path "$ToFolder\$($Matches[0])" -ItemType directory
        }

        #Transfer the matching file to its new folder
        #Can be changed to Move-Item if happy with the results
        Copy-Item -Path $_.FullName -Destination "$ToFolder\$($Matches[0])" -Force
    }
}


text: Q: Google search images in React.JS Application I have a search bar in my application. When I search a name in the search bar, I want to show the google image search results in my application. Then I need to select few images from the results and put/copy them into another section in my application. I know I have to it using Google Custom Search API. But I am not able to implement it as I am not able to get a good implementation example for reactjs application. How should I implement it?


text:
Q: Why isn't my mvc ajax not finding the action I am using a  to call an API action through a $ajax call, but it doesn't seem to be calling the api at all, and when the button is clicked, the fail message just comes up. What am I missing/doing wrong?
Here is the View and the embedded ajax:

          View
                Refuse

 } @section scripts
{

And here is the related API:
 using CailzMk2.DataLayer;
 using System.Linq;
 using System.Web.Http;
 using CailzMk2.Models;

 namespace CailzMk2.API
 {
     [Authorize]
     public class CailzController : ApiController
     {
         private ApplicationDbContext _context;

         public CailzController()
         {
             _context = new ApplicationDbContext();
         }

         [HttpPost]
         public IHttpActionResult Refuse(int id)
         {
             var refusedOrder = _context.Orders.Single(o => o.ID == id);
             refusedOrder.OrderRefused = true;
             _context.SaveChanges();
             return Ok();
         }
     }
 }

I've been struggling with this for some time.
The Function is called with a button press, and the correct ID does come through.  All I can think of is that it can't find it.
And here is a the route Config, just the default configuration:
namespace CailzMk2
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

A: Your URL (in the Ajax call) appears to be incorrect as it doesn't have the action component. It should be something like this:
url: "/api/Cailz/Refuse/" + link.attr("data-order-id"),
method: "POST"

Also, you should use [HttpPost] on the action instead of [HttpDelete] for consistency.


text:
Q: Laravel 5.0 - NotFoundHttpException in compiled.php I have Laravel 5.0 version, whenever the user types any route that wasnt present, system throws the following exception message.
Sorry, the page you are looking for could not be found.

1/1
NotFoundHttpException in compiled.php line 7959:
in compiled.php line 7959
at RouteCollection->match(object(Request)) in compiled.php line 7230
at Router->findRoute(object(Request)) in compiled.php line 7202
at Router->dispatchToRoute(object(Request)) in compiled.php line 7194
at Router->dispatch(object(Request)) in compiled.php line 2040
at Kernel->Illuminate\Foundation\Http\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in compiled.php line 9244
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Debugbar.php line 49
at Debugbar->handle(object(Request), object(Closure)) in compiled.php line 9236
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in compiled.php line 2548
at VerifyCsrfToken->handle(object(Request), object(Closure)) in VerifyCsrfToken.php line 29
at VerifyCsrfToken->handle(object(Request), object(Closure)) in compiled.php line 9236
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in compiled.php line 12416
at ShareErrorsFromSession->handle(object(Request), object(Closure)) in compiled.php line 9236
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in compiled.php line 11106
at StartSession->handle(object(Request), object(Closure)) in compiled.php line 9236
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in compiled.php line 12118
at AddQueuedCookiesToResponse->handle(object(Request), object(Closure)) in compiled.php line 9236
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in compiled.php line 12066
at EncryptCookies->handle(object(Request), object(Closure)) in compiled.php line 9236
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in compiled.php line 2589
at CheckForMaintenanceMode->handle(object(Request), object(Closure)) in compiled.php line 9236
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in compiled.php line 9227
at Pipeline->then(object(Closure)) in compiled.php line 1996
at Kernel->sendRequestThroughRouter(object(Request)) in compiled.php line 1983
at Kernel->handle(object(Request)) in index.php line 53

I have checked the permissions for storage folder as well, which is already set as 0755. Also I have already tries php artisan clear-compiled php artisan optimize php artisan cache:clear, but still it didnt work.
This error is happening only when the user types a route that wasnt present, for rest of the routes that already exists in route.php the site is working fine.
Any help in fixing the issue is highly appreciated.


text:
Q: Silverlight - User Control Binding I am learning Silverlight. In the process, I'm trying to build a custom user control. My ultimate goal is to be able to write the following statement in XAML:
<my:CustomControl>
  <my:CustomControl.MainControl>
    <Canvas><TextBlock Text="Hello!" /></Canvas>
  </my:CustomControl.MainContent>
</my:CustomControl>

The content of the control will be wrapped in a custom border. Once again, this is just a learning exercise. To append my border, I have create the following UserControl:
<UserControl x:Class="CustomControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006">

    <Grid x:Name="LayoutRoot">
      <Border>
        <!-- CustomControl Content -->
      </Border>
    </Grid>
</UserControl>

The code-behind for this file looks like the following:
public partial class CustomControl : UserControl
{
  public UIElement MainContent
  {
    get { return (UIElement)GetValue(MainContentProperty); }
    set { SetValue(MainContentProperty, value); }
  }

  public static readonly DependencyProperty MainContentProperty =
    DependencyProperty.Register("MainContent", typeof(UIElement), typeof(CustomControl),
    new PropertyMetadata(null));

  public CustomControl()
  {
    InitializeComponent();
  }
}

The thing I am having a problem with is getting the MainContent to appear in my CustomControl. I am confident that I am setting it properly, but I'm not sure how to display it. I really want it to be a DependencyProperty as well so I can take advantage of data binding and animations.
How do I get the MainContent to appear in the CustomControl?  Thank you

A: First you need to wait until the rest of the control has been parsed so you need to hook the loaded event:-
public CustomControl()
{
    InitializeComponent();
    Loaded += new RoutedEventHandler(CustomControl_Loaded);
}

Then in the loaded event assign your MainControl property to the Child property of the border. To do that its best if you give your Border an x:Name which for now I'll simple call "border".
void CustomControl_Loaded(object sender, RoutedEventArgs e)
{
    border.Child = MainControl;
}

That'll get you going.  Of course you may need to deal with the MainControl property being changed dynamically so you need add a bool isLoaded field in your control and set that in the loaded event.  When true your MainControl setter should assign the incoming value to the border.Child.
Things can start to get more complicated and in fact I don't recommend this approach to creating a custom control.  For a better approach see Creating a New Control by Creating a ControlTemplate


text:
Q: How to print car detail from dict cars = {"Austin 7": 1922, "Lancia Lambda": 1922, "Bugatti Type 35": 1924, "Hanomag 2": 1925,
        "Ford Model A": 1927, "Cadillac V16": 1930}

for i in range:

print("car: {}, year: {}".format(_, cars[_]))

A: cars = {"Austin 7": 1922, "Lancia Lambda": 1922, "Bugatti Type 35": 1924, "Hanomag 2": 1925, "Ford Model A": 1927, "Cadillac V16": 1930}

list_keys = cars.keys()

for key in list_keys:
   print("car: {}, year: {}".format(key, cars[key]))

A: What you are missing is that you can iterate over the keys of a dictionary using the syntax: for key in dict:.
cars = {"Austin 7": 1922, "Lancia Lambda": 1922, "Bugatti Type 35": 1924, "Hanomag 2": 1925, "Ford Model A": 1927, "Cadillac V16": 1930}

for car in cars:
    print("car: {}, year: {}".format(car, cars[car]))

Alternatives exist such as iterating over the items of the dictionary:
for car, year in cars.items():
    print(f"car: {car}, year: {year}")

cars.items() returns a list of tuples containing the key and value. These are unpacked into the variables car and year which are then printed using an f-string.
Or you can do it in one line using Python f-strings, list comprehension, and tuple unpacking:
print(*[f'car: {car}, year: {cars[car]}' for car in cars], sep='\n')


text:
Q: Retrive data from database in Odoo 14 I have a requirement that want to fulfill is bringing a value from the database and display in the UI, we have a app which we can assign "projects" to many people so i have to display in the persons information a field with the project currently assigned to him/her.
I was thinking about creating a function to retrieve that data using the "search()" method to fetch the field needed.
#for the moment i have added the variable in the class
project_name = fields.Char('Project Name', compute='_compute_get_employee_project')

#this is the function i am building (trying)
@api.model
    def _compute_get_employee_project(self):
        #verify the employee belongs to a project
        employee_task = self.env['project.task'].search([('user_id','=',self.user_id.id),('status','=','assigned')],limit=1)
        employee_project = self.env['project.project'].search([('id', '=', employee_task.project_id.id)], limit=1)

Thank you for your time!!

A: The compute method must assign the computed value to the field.
You can use a many2many field that depends on the related user to compute projects assigned to the selected user. Odoo will show one project if there is only one project assigned to the selected user.
Example:
class ResEmployee(models.Model):
    _inherit = 'hr.employee'

    project_ids = fields.Many2many('project.project', compute='_get_assigned_projects', string='Projects')

    @api.depends('user_id')
    def _get_assigned_projects(self):
        project_task = self.env['project.task']
        for employee in self:
            if employee.user_id:
                employee.project_ids = [(4, project_id, 0) for project_id in
                                        project_task.search(
                                            [('status', '=', 'assigned'),
                                             ('user_id', '=', employee.user_id.id)]
                                        ).mapped('project_id.id')]
            else:
                employee.project_ids = False

Use the following code to show the assigned project tag before the work mobile field:
<record id="view_employee_form" model="ir.ui.view">
    <field name="name">hr.employee.form</field>
    <field name="model">hr.employee</field>
    <field name="inherit_id" ref="hr.view_employee_form"/>
    <field name="arch" type="xml">
        <field name="mobile_phone" position="before">
            <field name="project_ids" widget="many2many_tags"/>
        </field>
    </field>
</record>

A: you could do the following:
#for the moment i have added the variable in the class
project_name = fields.Char('Project Name', compute='_compute_get_employee_project')

#this is the function i am building (trying)
@api.multi
@api.depends('user_id')
def _compute_get_employee_project(self):
    for emp in self:
        #verify the employee belongs to a project
        employee_task = self.env['project.task'].search([('user_id','=',self.user_id.id),('status','=','assigned')],limit=1)
        employee_project = self.env['project.project'].search([('id', '=', employee_task.project_id.id)], limit=1)
        emp.project_name = employee_project.display_name

or you could go another route
project_ids = fields.One2many('project.project', compute='_compute_get_employee_project')

@api.multi
@api.depends('user_id')
def _compute_get_employee_project(self):
    for emp in self:
        emp_task_ids = self.env['project.task'].search([('user_id','=', emp.user_id.id),('status','=','assigned')])
        emp_project_ids = emp_task_ids.mapped('project_id')
        emp.write({
            'project_ids': [(6, 0, emp_project_ids.ids)]
        })

please note the difference between the previous field definition Char & the new one One2many. the difference between the first case where limit=1 added & the second one where no limit. this because the user could be assigned to multiple tasks in different projects.
don't hesitate to let us know if everything works fine with you.


text:
Q: System.IO.FileNotFoundException: ASP.NET MVC Core 1.0 Website not Working IIS I have been trying to run a website built on MVC6 on IIS 7 in Windows 7 x64.
I followed all the steps closely on the ASP.NET Documentation regarding publishing to IIS. But I cannot make the website working. The stdout log has the following error:
System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.Extensions.Configuration.EnvironmentVariables, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60' or one of its dependencies. The system cannot find the path specified.
File name: 'Microsoft.Extensions.Configura
tion.EnvironmentVariables, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60' ---> System.IO.DirectoryNotFoundException: The system cannot find the path specified. (Exception from HRESULT: 0x80070003)
   at System.Runtime.Loader.AssemblyLoadContext.LoadFromPath(IntPtr ptrNativeAssemblyLoadContext, String ilPath, String niPath, ObjectHandleOnStack retAssembly)
   at System.Runtime.Loader.AssemblyLoadContext.LoadFromAssemblyPath(String assemblyPath)
   at Microsoft.Dnx.Runtime.Loader.PackageAssemblyLoader.Load(AssemblyName assemblyName, IAssemblyLoadContext loadContext)
   at Microsoft.Dnx.Host.LoaderContainer.Load(AssemblyName assemblyName)
   at Microsoft.Dnx.Runtime.Loader.AssemblyLoaderCache.GetOrAdd(AssemblyName name, Func`2 factory)
   at System.Runtime.Loader.AssemblyLoadContext.LoadFromAssemblyName(AssemblyName assemblyName)
   at System.Runtime.Loader.AssemblyLoadContext.Resolve(IntPtr gchManagedAssemblyLoadContext, AssemblyName assemblyName)
   at Microsoft.AspNet.Hosting.WebApplication.Run(Type startupType, String[] args)
   at Microsoft.AspNet.Server.Kestrel.Program.Main(String[] args)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.Dnx.Runtime.Common.EntryPointExecutor.Execute(Assembly assembly, String[] args, IServiceProvider serviceProvider)
   at System.Threading.Tasks.Task`1.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()
System.IO.DirectoryNotFoundException: The system cannot find the path specified. (Exception from HRESULT: 0x80070003)
   at System.Runtime.Loader.AssemblyLoadContext.LoadFromPath(IntPtr ptrNativeAssemblyLoadContext, String ilPath, String niPath, ObjectHandleOnStack retAssembly)
   at System.Runtime.Loader.AssemblyLoadContext.LoadFromAssemblyPath(String assemblyPath)
   at Microsoft.Dnx.Runtime.Loader.PackageAssemblyLoader.Load(AssemblyName assemblyName, IAssemblyLoadContext loadContext)
   at Microsoft.Dnx.Host.LoaderContainer.Load(AssemblyName assemblyName)
   at Microsoft.Dnx.Runtime.Loader.AssemblyLoaderCache.GetOrAdd(AssemblyName name, Func`2 factory)
   at System.Runtime.Loader.AssemblyLoadContext.LoadFromAssemblyName(AssemblyName assemblyName)
   at System.Runtime.Loader.AssemblyLoadContext.Resolve(IntPtr gchManagedAssemblyLoadContext, AssemblyName assemblyName)

I have given IIS_USRS all rights on the PublishOutput folder. Running the web.cmd returns the same error! I have tried to find it, but to no luck.
Note:
I am using coreclr 1.0.0-rc1-update1 x64. The project is working fine when run locally on IIS Express.
UPDATE 1:
The problem is some what similar to this issue on Github. But the solution is not that which is mentioned in my case.
UPDATE 2:
My project.json:
{
  "userSecretsId": "aspnet5-QMS.Identity.Test-a8974d85-8259-4653-be08-47e9a674ac6c",
  "version": "1.0.0-*",
  "compilationOptions": {
    "emitEntryPoint": true
  },

  "dependencies": {
    "EntityFramework.Commands": "7.0.0-rc1-final",
    "EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final",
    "Microsoft.AspNet.Authentication.Cookies": "1.0.0-rc1-final",
    "Microsoft.AspNet.Diagnostics.Entity": "7.0.0-rc1-final",
    "Microsoft.AspNet.Identity.EntityFramework": "3.0.0-rc1-final",
    "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
    "Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
    "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-final",
    "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
    "Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final",
    "Microsoft.AspNet.Tooling.Razor": "1.0.0-rc1-final",
    "Microsoft.Extensions.CodeGenerators.Mvc": "1.0.0-rc1-final",
    "Microsoft.Extensions.Configuration.FileProviderExtensions": "1.0.0-rc1-final",
    "Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final",
    "Microsoft.Extensions.Configuration.UserSecrets": "1.0.0-rc1-final",
    "Microsoft.Extensions.Logging": "1.0.0-rc1-final",
    "Microsoft.Extensions.Logging.Console": "1.0.0-rc1-final",
    "Microsoft.Extensions.Logging.Debug": "1.0.0-rc1-final",
    "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-rc1-final",
    "Microsoft.Dnx.Watcher": "1.0.0-rc1-final",
    "Microsoft.AspNet.Authentication.JwtBearer": "1.0.0-rc1-final",
    "IdentityServer3.Integration.AspNet": "1.0.0-rc1",
    "IdentityServer3.EntityFramework": "2.0.0-rc1",
    "IdentityServer3.AccessTokenValidation": "2.0.0-rc1"
  },

  "commands": {
    "web": "Microsoft.AspNet.Server.Kestrel",
    "ef": "EntityFramework.Commands",
    "watch": "Microsoft.Dnx.Watcher"
  },

  "frameworks": {
    "dnx451": { }
  },

  "exclude": [
    "wwwroot",
    "node_modules"
  ],
  "publishExclude": [
    "**.user",
    "**.vspscc"
  ],
  "scripts": {
    "prepublish": [ "npm install", "bower install", "gulp clean", "gulp min" ]
  }
}


text:
Q: Can't call puts with subclass of Ruby Hash I have built a subclass of Hash, and whenever I call puts with an instance of my class as an argument, I get the following:
> puts data
TypeError: can't convert Reporting::Search::Data to Array (Reporting::Search::Data#to_ary gives Reporting::Search::Data)

Does anyone have any idea what to do? I'd like it to output a string representation of a Hash, just like calling puts with an ordinary Hash would do.
My class is really simple:
  class Data < HashWithIndifferentAccess
    def method_missing meth, *args, &block
      if meth.to_s =~ /=$/
        send :[]=, meth.slice(0...-1), *args
      elsif args.empty?
        fetch meth, Data.new
      else
        super meth, *args, &block
      end
    end

    def compact!
      delete_if do |k,v|
        v.compact! if v.is_a?(Data)
        v.blank?
      end
    end
  end

A: You have two options, either write a to_s method. Or you could see what the .inspect instance method gives you, though it may not be very useful!
Have you tried adding a to_s method like this?
def to_s
  super.to_s
end

Also, it may not be the only reason you're having issues, but you've named your subclass Data which is already a class in Ruby.

A: Looks like the issue is to do with your use of method_missing.
When you call puts, it tries to output the object in a human-readable form, so it calls to_ary on the object. However, you haven't defined to_ary on your class, so it falls back to method_missing where it gets confused and fails.
Define, to_ary as a stub, and I'm not getting the error anymore.
def to_ary
end

This is one of the many pitfalls of metaprogramming in Ruby!

A: You are violating Ruby's type conversion protocols in various ways.
First off, your object responds to to_int, to_float, to_str, to_ary etc. without actually being an integer, a float, a string or an array. The three letter (ahem f-l-o-a-t ahem) versions of those type conversion methods are supposed to be used only in the case where the object in question really absolutely positively is an integer, float, string or array and is just not represented as an instance of Integer, Float, String or Array.
However, your object isn't an Array, it's a map. So, it should only respond to to_hash, if at all.
And secondly, the return value of to_int, to_float, to_str, to_ary etc. should be an instance of the Integer, Float, String or Array class.
So, you are implementing methods that you shouldn't even be implementing in the first place and you are returning the wrong value from them. Doing that for something as deeply ingrained in the core of Ruby as its type conversion protocols is bound to wreak all sorts of havoc of which you are only seeing the beginning.


text:
Q: Regarding single column or composite primary key Is it better to have a single column primary key, or use composite primary keys . I have examples below:
 create table emp(
 subsidiary_id  smallint   ,
 Employee_id    int        ,
 emp_name       varchar,
 constraint emp_pkey primary key ( subsidiary_id   , Employee_id     )

Data will be line
 subsidiary_id , employee_id
    1,                 1
    1,                 2
    1,                 3
    2,                 4
    3,                 5
    2,                 6

employee id cannot be same for any subsidiary , always unique but on my reports using both the column in where clause as subsdiary_id = 1 and employee_id = 1 or and so on
so want to know to better approach to create primary on employee_id column or both which one is better?

A: It sounds like a composite primary key is the right solution for you:
CREATE TABLE emp (
   subsidiary_id  smallint  NOT NULL,
   employee_id    int       NOT NULL,
   emp_name       text,
   CONSTRAINT emp_pkey PRIMARY KEY (subsidiary_id, employee_id)
);

The index that is created for this constraint will also be useful for queries where only subsidiary_id appears in the WHERE condition.


text:
Q: Disconnecting outlets/removing views when changing states in Ember router? I have an application with an application template that has two outlets. When I enter the root.index state, I only want one outlet to be connected, and when I enter the root.chats state, I want both outlets to be connected. This works fine when I navigate from root.index to root.chats, but when I navigate back the navpane outlet is still present (as it should be). How do I go about disconnecting this outlet or removing the view that was hooked up in the first place? Is the disconnectOutlet method for the controller mixin deprecated? Should I be structuring this completely differently? I've included my code below. Thanks.
// State flag helper function. See https://github.com/ghempton/ember-router-example/blob/master/js/app.js

function stateFlag(name) {
  return Ember.computed(function() {
    var state = App.router.currentState;
    while(state) {
      if(state.name === name) return true;
      state = state.get('parentState');
    }
    return false;
  }).property('App.router.currentState');
}

// Application

App = Em.Application.create({

    ApplicationController: Ember.Controller.extend({
        isChats: stateFlag('chats')
    }),
    ApplicationView: Ember.View.extend({
        templateName: 'application'
    }),
    ChatlistController:  Em.Controller.extend({
        hideView: false
    }),
    ChatlistView:  Em.View.extend({
        templateName:  'chatlist',
        didInsertElement: function(){
            this.$("#nav_pane").css({'left':'-=275', 'z-index':'-5'}).animate({
                left: ["+=275", 'swing'],
            },500,function() {
                $(this).css('z-index','5')
            });
        },
        _hideViewChanged: function() {
            if (this.get('hideView')) {
                this.hide();
            }
        }.observes('hideView'),
        hide: function() {
            var that = this;
            this.$("#nav_pane").hide("slow", function() {
                that.remove();
            });
        }
    }),
    ChatroomController:  Em.Controller.extend({

    }),
    ChatroomView:  Em.View.extend({
        templateName:  'chatroom'
    }),
    DashboardController:  Em.Controller.extend({

    }),
    DashboardView:  Em.View.extend({
        templateName:  'dashboard'
    }),
    Router: Ember.Router.extend({
        //location: 'history',
        enableLogging: true,
        goToDashboard:  Ember.Route.transitionTo('root.index'),
        goToChats:  Ember.Route.transitionTo('root.chats'),
        root:  Ember.Route.extend({
            index:  Ember.Route.extend({
                route:  '/',
                connectOutlets: function(router, context) {
                    router.get('applicationController').connectOutlet('content', 'dashboard');
                }
            }),
            chats:  Ember.Route.extend({
                route:  '/chats',
                connectOutlets: function(router, context) {
                    router.get('applicationController').connectOutlet('navpane', 'chatlist');
                    router.get('applicationController').connectOutlet('content', 'chatroom');
                }
            }),
            files:  Ember.Route.extend({
                route:  '/files'
            })
        })
    })
});

App.initialize();

A: I believe you're looking for disconnectOutlet, which is not at all deprecated: http://emberjs.com/api/classes/Ember.Controller.html#method_disconnectOutlet
A good place for it to live is on the route's exit event: http://emberjs.com/api/classes/Ember.State.html#event_exit
chats:  Ember.Route.extend({
    route:  '/chats',
    connectOutlets: function(router, context) {
        router.get('applicationController').connectOutlet('navpane', 'chatlist');
        router.get('applicationController').connectOutlet('content', 'chatroom');
    },
    exit: function(router){
      router.get('applicationController').disconnectOutlet('chatroom');
    }
}),


text:
Q: Close Gtk.Window modal in Genie I'm not sure what is the best way to close a modal window (this is a Gtk.Window defined as window.set_modal (true) and not a Gtk.Dialog).
I want to use a button in the window connected to a function with Gtk.WIndow.destroy (), but it does not work well.
I read that you should use "delete-event" but I do not know how to implement it. Does anyone have an example in Genie? Thank you.


text:
Q: How to determine a specific proxy in use determined by wpad.dat outside of IE My company has a very large and complex web proxy auto configuration (PAC) file. Is there any way to determine from command line, or maybe Java/Powershell, which proxy will be used by IE i.e. I want to determine the output from FindProxyForURL(url, host) for any supplied url.
I've searched all over and found lots of other stuff, and even tried a couple of Java programs - no joy! Any suggestions welcome.

A: You will have to write some code. I suggest VisualStudio and CSharp. You can try VisualBasic or any othet language which has Windows API bindings. I think that PowerShell can do the trick.
Windows API has WinHttpGetProxyForUrl  https://msdn.microsoft.com/en-us/library/windows/desktop/aa384097(v=vs.85).aspx
There is a sample C# code here https://github.com/respec/BASINS/blob/master/WebDownload/ProxyHelper.cs
You can also copy&paste the PAC file into any of the online tools like https://jsfiddle.net/ and call FindProxyForURL() at the bottom of the file.


text:
Q: Initializing an array of objects with {" ", " "} I am trying to initialize an array of String (the class contains a default constructor and a constructor like this one: String(const char* helper). I also have overloaded operator for <<;
However when I try to do the following, nothing happens :
 String suits[4] = {"Hearts", "Clubs", "Diamonds", "Spades"};
        std::cout << suits[2];

But this one is okay :
        const String suit = "Hearts";
        std::cout <<suit;

0
it works the same without the const. I wanted to build myself the string class. About the string class :
class String
{
    char* buffer;
    int size;
    public:

    String(const char* helper)
    {
        size_t sizeH = strlen(helper);
        buffer = new char[sizeH];
        for (int i = 0; i < sizeH; ++i)
        {
            buffer[i] = helper[i];
        }
        buffer[sizeH] = 0;
        size = sizeH;
    }
    String()
    {
        buffer = nullptr;
        size = 0;
    }
    void sizeOfBuffer()
    {
        std::cout <<size<<"\n";
    }

    ~String()
    {
        delete[] buffer;
    }


text:
Q: Another SharePoint query regarding calculation Sorry I just need abit of help understanding this:
I have column W, X, Y, Z.

*

*W is Dates

*X is Rota

*Y is Yes or No

*Z needs to be something, for
example:

If X is Rota1 and Y is Yes, then Z will be 1.
Hope someone can help me again. Thank you.

A: You may use a calculate column field for Z, with return type Number where you may add a formula (You may use IF conditions too in the formula) to set value for Z field.
Apply below formula:
=IF(AND([X]="Quarter 1",[Y]),"1","-")

To know more about calculated column refer

*

*https://msdn.microsoft.com/en-us/library/office/bb862071(v=office.14).aspx

*https://sharepoint.rackspace.com/calculated-columns-tutorial

A: Built your logic in Excel first
all basic functions are the same syntax for Calculated Columns in SharePoint
Here are all the SharePoint Functions available:
https://www.365csi.nl/vm365com/365coach/#/Calculated_Column_Functions_List


text:
Q: Instability of electron gas I am trying to understand the following statement from notes which I found: "For electron gas with long-range Coulomb interaction there is a problem with its instability". What does it mean? I know the problem of Cooper instability, but in that case the problem was related to the attractive potential between pair of electron exchanging phonon. How should I understand meaning of this sentence (I do not have any richer context - it was just one sentence given as a remark)?

A: The coulomb potential is $1/r$ type potential. When you calculate the total interaction energy as,$E=\frac{1}{4\pi \epsilon_0}\sum_{<i,j>}\frac{q_iq_j}{|r_{ij}|}$ the summation will not readily converge. The described sum converge very slowly and also conditionally convergent. So we can use the
Ewald summation technique to break it up into two parts. One summation is carried out in real space and another part is carried out in reciprocal space. This technique is often useful for these $1/r^n$ potentials and for dipolar interaction.
I think the problem lies in the convergence in the series.
PS: The Ewald Summation Technique:
Let us assume there is N number of charged atoms placed in a box of dimension $L\times L\times L$. The position of each particles having charge $q_1,q_2,q_3,\hdots,q_n$ from a suitable chosen origin are denoted by $r_1,r_2,r_3,\hdots r_n$. So the total Coulomb interaction among the particles can be expressed as,
\begin{align}
E=\frac{1}{4 \pi \epsilon_0}\sum_{<i,j>} \frac{q_i q_j}{|r_{ij}|} \label{coulomb1}
\end{align}
and $r_{ij}$ is denoted as $r_i-r_j$.
Under periodic boundary condition, we have an identical particle at a distance $r_i+n1a1+n2a2+n3a3$ as the particle situated at a distance $r_i$ from the origin. Here $a1,a2 and a3$ are the primitive vector and $n1,n2 and n3$ are any arbitrary integers. For the sake of simplicity let us choose the box cubic and $L=|a1|=|a2|=|a3|$ and vector $n$ from a simple cubic lattice $(n1,n2,n3)$.
So we can modify our \cref{coulomb1} as,
\begin{align}
E&=\frac{1}{4 \pi \epsilon_0}\sum_{n} \sum_{<i,j>} \frac{q_i q_j}{|r_{ij}+nL|} \nonumber \\
&=\frac{1}{4 \pi \epsilon_0} \frac{1}{2} \sum_{n} \sum_{i=1}^{N} \sum_{j=1}^{N} {'} \frac{q_i q_j}{|r_{ij}+nL|}\label{coulomb2}
\end{align}
The factor $\frac{1}{2}$ comes due to double counting and the symbol ($'$) denotes the fact that $i\neq j$.
The described sum converge very slowly and also conditionally convergent. So we can use the Ewald summation technique to break it up into two parts. We will use simple tricks to do that. We can write the \cref{coulomb2} as,
\begin{align}
E=\frac{1}{2} \sum_{i=1}^{N} q_i \phi_{[i]} (r_i) \label{Energy}
\end{align}
where,
\begin{align*}
\phi_{[i]}(r_i)=\frac{1}{4 \pi \epsilon_0} \sum_{n}\sum_{j=1}^{N} {'} \frac{ q_j}{|r_{ij}+nL|}
\end{align*}
Or, changing variable we can identify the potential field generated by all the ions excluding the ion $i$ as,
\begin{align}
\phi_{[i]}(r)=\phi(r)-\phi_{i}(r)=\frac{1}{4 \pi \epsilon_0} \sum_{n}\sum_{j=1}^{N} {'} \frac{ q_j}{|r-r_j+nL|}
\end{align}
The sum will give the potential field at any point $r$ of the box due to the other charges. But the direct sum is not easy to determine because it is divergent. So we will use a little trick to handle this problem. The potential field created by only one charge $q_i$ at the point $r_i$ is given by;
\begin{align}
\varphi_{i}(r)=\frac{1}{4 \pi \epsilon_0} \sum_{n} \frac{q_i}{|r-r_i+nL|}
\end{align}
The Fourier transformation of it is
\begin{align}
\varphi_{i}(K)= \frac{1}{\epsilon_0 K^2}e^{-i|K|r_i} \label{phi}
\end{align}
Where $K$ is the reciprocal lattice vector. We can further write $k^2$ (where $k=|K|$) in terms of integral.
\begin{align}
\frac{1}{k^2}=\int_{0}^{\infty} e^{-k^2 t}dt
\end{align}
Putting back into the \cref{phi} we get,
\begin{align}
\varphi_{i}(K)= \frac{1}{\epsilon_0 }e^{-ikr_i} \int_{0}^{\infty} e^{-k^2 t}dt \label{phi1}
\end{align}
Here we can divide the \cref{phi1} into two parts using a suitably chosen Ewald cut off parameter ($\Gamma$) as both the integral part converge rapidly.
\begin{align}
\varphi_{i}(K) &= \varphi_{i}^{S}(K)+\varphi_{i}^{L}(K)\nonumber \\
&= \frac{1}{\epsilon_0 }e^{-ikr_i} \int_{0}^{\Gamma} e^{-k^2 t}dt+\frac{1}{\epsilon_0 }e^{-ikr_i} \int_{\Gamma}^{\infty} e^{-k^2 t}dt
\end{align}
We can easily carry out the integral and get the expression for long range interaction term.
\begin{align}
\varphi_{i}^{L}(K)= &\frac{1}{\epsilon_0 }e^{-ikr_i} \int_{\Gamma}^{\infty} e^{-k^2 t}dt \nonumber \\
&=\frac{1}{\epsilon_0 }e^{-ikr_i} e^{-\Gamma k^2} \label{long}
\end{align}
And the $\varphi_{i}^{S} (K)$ is not convergent in reciprocal space. So we pull it back to the real space to calculate the integral. So using inverse Fourier transformation we get,
\begin{align}
\varphi_{i}^{S} (r) &=\frac{1}{V} \sum_{k} \varphi_{i}^{S} (K) e^{ikr} \nonumber \\
&=\frac{1}{V \epsilon_0} \sum_{k} \int_{0}^{\Gamma} e^{-ik(r-r_i)} e^{-k^2t} dt \nonumber \\
&= \frac{1}{4 \pi \epsilon_0} \sum_{n} \frac{1}{|r-r_i|} erfc\Bigg(\frac{|r-r_i|}{\sqrt{2}\Gamma}  \Bigg) \label{short}
\end{align}
Now putting \cref{short} and \cref{long} back to \cref{Energy} we can find out the Energy terms.
\begin{align}
E^S &=\frac{1}{2} \sum_{i=1}^{N} q_i \phi_{[i]}^{S} (r_i) \nonumber \\
&= \frac{1}{4 \pi \epsilon_0} \frac{1}{2} \sum_{n} \sum_{i=1}^{N} \sum_{j=1}^{N} {'} \frac{q_i q_j}{|r_{i}-r_{j}+nL|} erfc\Bigg(\frac{|r_i-r_j+nL|}{\sqrt{2}\Gamma}  \Bigg)
\end{align}
where we have used a variable transformation $r=r_i+nL$.
Similarly we get,
\begin{align}
E^L &=\frac{1}{2} \sum_{i=1}^{N} q_i \phi_{[i]}^{L} (r_i) \nonumber \\
&= \frac{1}{2} \sum_{i=1}^{N} q_i \phi^{L} (r_i)-\frac{1}{2} \sum_{i=1}^{N} q_i \phi_{i}^{L} (r_i) \nonumber \\
&= \frac{1}{2 V \epsilon_0} \sum_{k \neq 0} \sum_{i=1}^{N} \sum_{j=1}^{N} \frac{q_i q_j}{k^2} e^{-ik(r_i-r_j)} e^{-\Gamma k^2} -E^{Self}
\end{align}
Combining the Energy expression can be expressed as $E_E^S+E^L-E^{Self}$ where $E^{Self}=\frac{1}{2} \sum_{i=1}^{N} q_i \phi_{i}^{L} (r_i)$ term is the self interaction energy term.
The final expression of Energy becomes,
\begin{align}
E=\frac{1}{4 \pi \epsilon_0} \frac{1}{2} \sum_{n} \sum_{i=1}^{N} \sum_{j=1}^{N} {'} \frac{q_i q_j}{|r_{i}-r_{j}+nL|} erfc\Bigg(\frac{|r_i-r_j+nL|}{\sqrt{2}\Gamma}  \Bigg) + \nonumber \\
\frac{1}{2 V \epsilon_0} \sum_{k \neq 0} \sum_{i=1}^{N} \sum_{j=1}^{N} \frac{q_i q_j}{k^2} e^{-ik(r_i-r_j)} e^{-\Gamma k^2} -\frac{1}{4 \pi \epsilon_0} \frac{1}{\sqrt{4 \pi \Gamma}} \sum_{i=1}^{N} q_{i}^2
\end{align}

Reference:
1. http://micro.stanford.edu/mediawiki/images/4/46/Ewald_notes.pdf
2. https://www.academia.edu/29151377/Ewald_Summation_and_its_Applications


text:
Q: Can we tell something about rest mass from this plot of differential cross-section? What we can interpret from the plots below? My aim is to find any resonance peak for  di-leptons considering the  the produced gamma from quarks and antiquarks can annihilate to  lepton and anti lepton.
The  plot here is for 120 GeV CM energy proton proton scattering.

EDIT:
I have changed the CM energy (14 TeV) and got a different cross-section peak for transverse momentum.

A: Transverse momentum was and is still a strong analysis variable for checking whether new phenomena appear in complicated hadronic interactions, as is proton proton scattering. The reason is that transverse momentum to the beam is invariant to lorentz boosts in the beam direction, so the distributions give a snapshot  of the maximum momenta possible in the interaction. High  $p_t$ are a signal for deep inelastic scattering, and also give an upper limit to a possible mass of a new resonance.
Choosing  high $p_t$ leptons in each event one enhances the probability of , for example the Z, to be in the sample and see the resonance enhanced in the invariant mass plot, and then one can use analysis to extract the true production crossection as in this publication for example..
The first  plot you are showing is not physical as the the $p_t$ from a resonance will go from a maximum down to zero smoothly, because of the angular distribution of the  decay  momentum vectors of the produced resonance.
So from $p_t$ you can only get upper limits: supposing it is a resonance that has decayed completely perpendicularly then it would have a mass the invariant mass of the two supposed vectors as an upper limit.
edit after question edit.
The second plot is physically possible,  again one has to check with other variables in order to be able to extract a mass estimate , if it is not possible to get the invariant mass from the two leptons directly.

A: You can't really interpret anything from the transverse momentum of a lepton.
What you see here is simply zero events below a threshold, followed by an falling exponential, which is very standard for virtually all kinds of events at a collider.
In order to see a resonance, you want to plot the invariant mass of pairs of leptons, $m=\left(p_1+p_2\right)^2$, where $p_1$ and $p_2$ are four-momenta.
If longitudinal information is not available, you can also plot the "transverse mass," which is simply the invariant mass assuming $p_L$ is zero, and use statistical methods to determine the true invariant mass. This is often used for particles that decay as $\rm X\to Y+invisible$, since in a hadron collider the longitudinal momentum of invisible particles can usually not be detected.


text:
Q: Are you late tonight? vs Will you be late tonight? In the morning, my wife asked me " Will you be late tonight?".
So I answered, "I am going to be late tonight."
If she asked me " Are you late tonight?", is that question right ?
Either gramatically or semantically, does that question sound natural ?
Is there any of native speakers who can explain the difference between these two?
I'd really appreciate it if someone would do that.

A: The correct phrase is:

Will you be late tonight?

One is not "late" until a certain time has passed, so it is incorrect to ask if someone is late in the present tense when speaking about a later time (tonight).
You could ask:

Are you going to be late tonight?

Using "to be" as an auxiliary verb allows for the different tense.


text:
Q: como resolver este problema de JS? posicionar las rocas en el planeta marte Misión del Rover de Marte
Tu tarea:

Formas parte del equipo que explora Marte enviando vehículos controlados a distancia a la superficie del planeta. Desarrolla un software que traduzca los comandos enviados desde la Tierra a instrucciones que sean entendidas por el rover.

Requisitos:

*

*Se le da el punto inicial de partida (x,y) de un rover y la dirección (N,S,E,W) a la que está orientado.

*El rover recibe una colección de comandos. (Por ejemplo) FFRRFFFRL

*El rover puede moverse hacia adelante (f).

*El rover puede moverse a la izquierda/derecha (l,r).

*Supongamos que estamos en un planeta realmente extraño que es cuadrado. 200x200 por ejemplo :)

*Implementar la detección de obstáculos antes de cada movimiento a un nuevo cuadrado. Si una determinada secuencia de comandos encuentra un obstáculo, el rover se mueve hasta el último punto posible, aborta la secuencia e informa del obstáculo.

Tengo el ejercicio casi completo, me falta posicionar los obstáculos dentro del planeta, e echo un array de objetos con las rocas y su posición en el planeta pero no consigo mapearlas correctamente para que se coloquen y se vean en el DOM, el resultado es undefined.
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">

    <title>Document</title>

                        Hi I'm George Clooney and I'm still lost in space.

                        Today is a good day to conquer the earth!!!!

Panel Control

                <input id="inputX" type="number" min="0" max="36" placeholder="0..36">
                <input id="inputY" type="number" min="0" max="36" placeholder="0..36">
                <button id="buttonPosition" class="btn btn-success" style="height: 29px;
                width: 107px;
                align-items: center;
                display: flex;">set position</button>

                <input id="inputM" class="input-start" type="text">
                <button id="buttonStart" class="btn btn-success" style="height: 29px;
                width: 107px;
                justify-content: center;
                align-items: center;
                display: flex;">start</button>

Instructions

The planet Mars has dimensions of 400x400 for better visibility.
 The rover has dimensions of 40x40.
 To visualize the rover you have to enter the starting coordinates, and then you can give movement commands.
 The rover cannot leave
                the planet, and any command to move it out of the planet will not be executed and an alert will be triggered.
 The images contain hidden surprises.
 Enjoy the mission.

let rover = document.getElementById("rover");
let moveLeft = 0;
let moveFront = 0;
let buttonStart = document.getElementById("buttonStart");
let buttonPosition = document.getElementById("buttonPosition");
let movements;
let planetSizeX = 400;
let planetsizeY = 400;
let roverSizeX = 40;
let roverSizeY = 40;
let roverCrashed;

let positionRocks = [{
    r1: { x: 60, y: 10 },
    r2: { x: 150, y: 300 },
    r3: { x: 320, y: 120 }
}];

positionRocks.map((rock) => (
    rock = document.getElementById("rock"),
    document.getElementById("container-mars").innerHTML = rock.r1,
    document.getElementById("container-mars").innerHTML = rock.r2,
    document.getElementById("container-mars").innerHTML = rock.r3
))

buttonStart.addEventListener("click", () => {
    roverCrashed = false;
    let inputM = document.getElementById("inputM");
    movements = inputM.value.toUpperCase();

    [...movements].forEach((step) => {
        setTimeout(function() {
            if (!roverCrashed) {
                MoveRover(step);
            }
        }, 1000);
    });
    document.getElementById("inputM").value = "";
});

buttonPosition.addEventListener("click", () => {
    let initialX = document.getElementById("inputX").value;
    let initialY = document.getElementById("inputY").value;
    moveLeft = initialX * 10;
    rover.style.marginLeft = moveLeft + "px";
    moveFront = initialY * 10;
    rover.style.marginTop = moveFront + "px";
    rover.style.visibility = "visible";
    document.getElementById("container-input-movement").style.visibility =
        "visible";
});

function MoveRover(commands) {
    switch (commands) {
        case "L":
            MoveLeft();
            break;

        case "R":
            MoveRight();
            break;

        case "F":
            MoveFront();
            break;

        default:
            break;
    }
}

function MoveLeft() {
    if (moveLeft > 0) {
        moveLeft -= 10;
        rover.style.marginLeft = moveLeft + "px";
    } else {
        roverCrashed = true;
        alert(
            "The rover cannot execute these movements because it would leave the planet."
        );
    }
}

function MoveRight() {
    if (moveLeft < planetSizeX - roverSizeX) {
        moveLeft += 10;
        rover.style.marginLeft = moveLeft + "px";
    } else {
        roverCrashed = true;
        alert(
            "The rover cannot execute these movements because it would leave the planet."
        );
    }
}

function MoveFront() {
    if (moveFront < planetsizeY - roverSizeY) {
        moveFront += 10;
        rover.style.marginTop = moveFront + "px";
    } else {
        roverCrashed = true;
        alert(
            "The rover cannot execute these movements because it would leave the planet."
        );

    }
}

document
    .getElementById("astronaut")
    .addEventListener("mouseover", mouseOverAstronaut);
document
    .getElementById("astronaut")
    .addEventListener("mouseout", mouseOutAstronaut);

function mouseOverAstronaut() {
    document.getElementById("astronaut-paragraph").style.visibility = "visible";
}

function mouseOutAstronaut() {
    document.getElementById("astronaut-paragraph").style.visibility = "hidden";
}

document
    .getElementById("spacecraft")
    .addEventListener("mouseover", mouseOverSpacecraft);
document
    .getElementById("spacecraft")
    .addEventListener("mouseout", mouseOutSpacecraft);

function mouseOverSpacecraft() {
    document.getElementById("spacecraft-paragraph").style.visibility = "visible";
}

function mouseOutSpacecraft() {
    document.getElementById("spacecraft-paragraph").style.visibility = "hidden";
}

A: Prueba este snippet, hay los cambios que te sugieren en los comentarios y alguno más.

let rover = document.getElementById("rover");
let mLeft = 0;
let mRight = 0;
let mTop = 0;
let boton = document.getElementById("boton");
var valor

boton.addEventListener("click", () => {

  let input = document.getElementById("input");
  valor = input.value;
  MoveRover()
  // alert("El valor del campo es:" + valor);

});

function MoveRover() {
  if (valor === "l") {
    MoveLeft()
  } else if (valor === "r") {
    MoveRight()
  } else if (valor === "f") {
    MoveTop()
  }
}

function MoveLeft() {
  mLeft += 1;
  rover.style.marginLeft = mLeft + "px"
}

function MoveRight() {
  mRight += 1;
  rover.style.marginRight = mRight + "px"
}

function MoveTop() {
  mTop += 1;
  rover.style.marginTop = mTop + "px"
}
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <title>Document</title>

      <input id="input" type="text">
      <button id="boton">click</button>

a

Aunque solo parece funcionar lo de ir hacia abajo (le he puesto una a al div para verlo, supongo que con tu css se apreciaria mejor).
Explicación de los cambios

*

*Se ha agregado la variable global valor para que se pueda usar en todas las funciones

var valor

*Se ha cambiado su asignación dentro del evento capturado click, cambiando simplemente su valor:

valor = input.value

*Se ha agregado la llamada a la función MoveRover() dentro del evento capturado y se ha suprimido del elemento con id="boton" para evitar dobles llamadas al mismo evento que no estarian sincronizadas seguramente.

Prueba y verás que al menos cuando pones la f en el snippet y pulsas varias veces el botón la a se mueve hacia abajo.  El resto de movimientos no funcionan, pero quizás es por la falta del css, compruébalo y arréglalo.


text:
Q: WebStorm - Cmd-Click not working Pretty new to WebStorm.
Usually, when I Cmd + Click on a directive or CSS class in the code-base, WebStorm opens a new tab with the file from which that code originates from.
Lately though, WebStorm has just been taking me to the same minified file for everything I click on.
Any idea what's going on? I've updated and restarted the program.

A: Do Ctrl + B , you jump to the referenced file or imported module
https://blog.jetbrains.com/webstorm/2015/06/10-webstorm-shortcuts-you-need-to-know/


text:
Q: I want to display a hyper link in product summary I am trying to add a hyperlink titled as "see details on manufacturer's website" so customer click on the hyperlink and will go to the brand's website to read all details
I am suing ACF to get hyperlink for each product but failed to successfully apply on front end its show hyperlink but when click it says page not found please help
I want this type of hyper link
hyperlink area
here is the url of hyperlink I want same on my site
https://czone.com.pk/lcd-led-monitors-asus-asus-rog-swift-pg329q-gaming-monitor-32-2k-wqhd-fast-ips-175hz-1ms-g-sync-compatible-displayhdr-600-pakistan-p.12565.aspx
I am failed to connect acf with hyperlink actually


text:
Q: Como usar 2 função updates no UserController em Laravel Estou tentando adicionar imagem do perfil de usuário e também a carteira btc em um input. Se eu adiciono a carteira não consigo adicionar a img do perfil.
Vi que os dois usam a função update e por isso estou tendo conflito, se eu retirar a rota da carteira, a foto vai de boa, mas preciso dos 2 ok.
Minha rota:
Route::get('userp', 'UserController@index');
Route::post('userp', 'UserController@update');

Meu controlador da imagem perfil:
public function update_avatar(Request $request){
        if ($request->hasFile('avatar')){
            $avatar = $request->file('avatar');
            $filename = time() . '.' . $avatar->getClientOriginalExtension();
            Image::make($avatar)->resize(300, 300)->save( public_path('/uploads/avatars/' . $filename ));

            $user = Auth::user();
            $user->avatar = $filename;
            $user->save();
        }

        return view('userp', array('userp' => Auth::user()) );

}

Meu controlador da carteira:
public function update(Request $request) {

        $data = \Input::all();

        $valida = [
            'passaport' => 'passaport',
            'nascimento' => 'date',
            'bitzpayer_email' => 'email'
        ];

        if (!empty($data['password'])) {
            $valida = array_merge($valida, ['password' => 'required|confirmed|min:6',]);
        }
        if (\Auth::user()->ativo == 0 && \Auth::user()->dataAtivacao == '0000-00-00') {
            $valida = array_merge($valida, ['pacote' => 'required|integer',]);
        }
        $validator = Validator::make($data, $valida);

        if ($validator->fails()) {

            return redirect('/userp')
                            ->withErrors($validator)
                            ->withInput();
        }
        if (!isset($data['saque'])) {

            if (!empty($data['bitzpayer_id'])) {
                if (!$this->checkAddress($data['bitzpayer_id'])) {
                    return redirect('/userp')->withErrors(['Invalid Wallet.']);
                }

            }

            $dados = [
                'bitzpayer_id' => @$data['bitzpayer_id'],
              ];
          } else {
            $dados = [
                'bitzpayer_id' => @$data['bitzpayer_id'],
             ];
        }

        if (\Auth::user()->ativo == 0 && \Auth::user()->dataAtivacao == '0000-00-00') {
            $dados['pacote'] = $data['pacote'];
        }
        if (!empty($data['password'])) {
            $senha = \DB::table('users')->where('id', \Auth::user()->id)->first()->password;
            if (\Hash::check($data['current_password'], $senha)) {
                $dados = array_merge($dados, ['password' => bcrypt($data['password']),]);
            } else {
                return redirect('userp')->withErrors(['Senha inválida, tente novamente.']);
            }
        }

        $user = \Auth::user()->update($dados);

        if ($user) {

            return redirect()->back()->with('message', 'Your bitcoin wallet has been updated successfully!');
        } else {
            return redirect('/userp')->withErrors(['Não foi possivel atualizar suas informações, tente novamente.']);
        }
    }


text:
Q: How do I create a list of forms from an array? Im on Rails 4. I have a two lists of objects that I want a page to display a form to update a field on each of them

Teas

        <% @teas.each do |tea| %>
            <%= form_tag(controller: "teas", action: "update", method: "patch") %>
                <%= label_tag(:price, tea.name.titleize) %>
                <%= text_field_tag :price %>
            <% end %>
        <% end %>

Mixins

        <% @mixins.each do |mixin| %>
            <%= form_tag(controller: "mixins", action: "update", method: "patch") %>
                <%= label_tag(:price, mixin.name.titleize) %>
                <%= text_field_tag :price %>
            <% end %>
        <% end %>

When I use this, I get an syntax error, unexpected keyword_end, expecting end-of-input error. What is wrong here?

A: Seems like you have missed do on form
<%= form_tag(controller: "teas", action: "update", method: "patch") do %>


text:
Q: firewall-cmd error on polkit I am trying to run firewall-cmd --list-all but i am receiving the response

Authorization failed  Make sure polkit application is running
or run the application as superuser.

I can see that polkit is running by systemctl status polkit but I do not know how to start it as superuser.  I am sure this is a lame question but i have been searching.
Thanks for any info.

A: duh.  I just needed to run the command with sudo or as root
sudo firewall-cmd --list-all


text:
Q: Android NDK/JNI: is malloc global (static char*) variable without free ok? I have an android app which has some JNI methods.
Each of these methods works with java reflections mostly and for that I need to have some strings (names of java methods/classes/etc - they are not constants in my case).
So I want to do some JNI initialization work which will prepare these strings before calling these JNI methods from java - I allocate (using malloc) global string variables (static char*) which will be used inside these methods whenever they called.
What is the best way to allocate/deallocate such global variables?
I could do constants but I need to modify their values at runtime (during initialization)
Right now I have initialization method which I call from Application.onCreate() - it allocates like 50 of string variables (static char*) and assigns them.
But I never call free().
Will there be any problem with this approach?
For example, when the app is killed by system, will there be any memory leak or corruption?
What if my app is started again (onCreate() called and variables are re-initialized again?)
I have not seen such problems myself, but memory is such a thing... maybe its just my luck :)
I thought of doing initialization in JNI_OnLoad, but again - when to free the resources?


text:
Q: Undefined control sequence (\chemmacros_load_module:n {nomenclature}) is there currently a problem with the chemmacros package? I've just come back to my thesis to make corrections but I'm getting this new random error when I hadn't seemingly changed anything since the last time I processed the document. I've fully updated MikTex console but I always get this error when I use chemmacros:
! Undefined control sequence.
l.669 \chemmacros_load_module:n
{nomenclature}

This error occurs no matter which chapter I build and it always adds one page at the beginning of the document with only the word nomenclature.
In my document preamble I have:
\usepackage{chemmacros}
\chemsetup{modules={all}}

A: The error most likely does come from ghsystem and can be reproduced by:
\documentclass{article}
\usepackage{ghsystem}
\begin{document}
\end{document}

The problem is that the package is not adapted to v6 of chemmacros, yet. Until it is the error can be resolved by defining \chemmacros_load_module:n to simply gobble its argument:
\documentclass{article}
\ExplSyntaxOn
\cs_new:Npn \chemmacros_load_module:n #1 {}
\ExplSyntaxOff
\usepackage{ghsystem}
\begin{document}
\end{document}

Unrelated, but since you mention having
\usepackage{chemmacros}
\chemsetup{modules={all}}

in your preamble: this should raise the following warning in your log:
Package chemmacros Warning: The module mechanism has changed with v6!
(chemmacros)                =========================================
(chemmacros)                * All modules have been integrated into
(chemmacros)                the main package and thus are preloaded
(chemmacros)                already (unless you have loaded
(chemmacros)                `chemmacros' with the `minimal' option).
(chemmacros)                * The new default corresponds to the
(chemmacros)                earlier setting `modules=all'.

This means with an up to date chemmacros (newer than 2022/01/16) you can simply drop loading any modules. \usepackage{chemmacros} should suffice.


text:
Q: How i can typed event in handleSumbit? I don't quite understand how to do typing in handleSubmit?
The "password" property does not exist in the "EventTarget" type.
The "email" property does not exist in the EventTarget type.
import { FormEvent, useState } from "react"
import { NavLink } from "react-router-dom"
import { useAppDispatch, useAppSelector } from "../../../hooks"
import { loginThunkCreator } from "../../../redux/appReducer"
import Menu from "../../common/Menu"
import './Login.css'

const Login = () => {
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const dispatch = useAppDispatch()

  const isAuth = useAppSelector( state => state.isAuth)

  const handleSubmit = (e: FormEvent) => {
    e.preventDefault()
    const dataSubmit = {
      email: e.target.email.value,
      password: e.target.password.value
    }
    dispatch(loginThunkCreator(dataSubmit))
  }
  if (isAuth) { return

                          <Menu/>

You are already authorized!

  } else return (

<NavLink to="/*">Menu</NavLink>

      <form action="" onSubmit={handleSubmit} className='login-form form'>

Login

        <input className='login-form__input-email input-form' type="text" name='email' placeholder='email' value={email} onChange={(e) => setEmail(e.target.value)}/>
        <input className='login-form__input-password input-form' type='password' name='password' placeholder="password" value={password} onChange={(e) => setPassword(e.target.value)}/>
        <button className="login-buton form-button">Log in</button>

Doesn't have account? <NavLink to="/register">Register</NavLink>

      </form>

  )
}

export default Login

A: no need to get it from event.target in the submit handler, and also the event you are passing in the submit handler doesn't contain target prop, and since you already set the values of email and password via change handler, then just use your state :
const handleSubmit = (e: FormEvent) => {
        e.preventDefault()
        const dataSubmit = {
          email, // instead of : email: e.target.email.value
          password // instead of : e.target.password.value
        }
        dispatch(loginThunkCreator(dataSubmit))
      }


text:
Q: Tool to Unminify / Decompress JavaScript Are there any command line scripts and/or online tools that can reverse the effects of minification similar to how Tidy can clean up horrific HTML?
(I'm specifically looking to unminify a minified JavaScript file, so variable renaming might still be an issue.)

A: Most of the IDEs also offer auto-formatting features. For example in NetBeans, just press CTRL+K.

A: Got it! JSBeautifier does exactly this, and you even have options for the auto-formatting.

A: You can use this : http://jsbeautifier.org/
But it depends on the minify method you are using, this one only formats the code, it doesn't change variable names, nor uncompress base62 encoding.
edit: in fact it can unpack "packed" scripts (packed with Dean Edward's packer : http://dean.edwards.name/packer/)

A: As an alternative (since I didn't know about jsbeautifier.org until now), I have used a bookmarklet that reenabled the decode button in Dean Edward's Packer.
I found the instructions and bookmarklet here.
here is the bookmarklet (in case the site is down)
javascript:for%20(i=0;i<document.forms.length;++i)%20{for(j=0;j<document.forms[i].elements.length;++j){document.forms[i].elements[j].removeAttribute(%22readonly%22);document.forms[i].elements[j].removeAttribute(%22disabled%22);}}

A: I'm not sure if you need source code. There is a free online JavaScript formatter at http://www.blackbeltcoder.com/Resources/JSFormatter.aspx.

A: Try this one, with code coloration:
http://labs.swelen.com/tools/javascript/beauty.html

A: click on these link for JS deminification. That will install on FF as extension that help you in debugging js at runtime.
https://addons.mozilla.org/en-US/firefox/addon/javascript-deminifier/eula/141018?src=dp-btn-primary

A: Similar to Stone's answer, but for Windows/.NET developers:
If you have Visual Studio and ReSharper - An easy alternative for formatting Javascript is:

*

*Open the file with Visual Studio;

*Click on ReSharper > Tools > Cleanup Code (Ctrl+E, C);

*Select "Default: Reformat code", and click OK;

*Crack open a beer.

A: Despite its miles-away-from-being-pretty interface, JSPretty is a good, free and online tool for making javascript source codes human-readable. You can enforce your preferred type of indentation and it can also detect obfuscation.

A: If one is in JS possibility of using Firefox is more. And if its Firefox add on is for rescue. Following one is particularly useful.
https://addons.mozilla.org/en-US/firefox/addon/phoenix/

A: Pretty Diff will beautify (pretty print) JavaScript in a way that conforms to JSLint and JSHint white space algorithms.

A: Wasn't really happy with the output of jsbeautifier.org for what I was putting in, so I did some more searching and found this site: http://www.centralinternet.com.br/javascript-beautifier
Worked extremely well for me.

A: http://unminify.appspot.com/
Great tools for unminify javascript and json

A: Chrome developer tools has this feature built-in. Bring up the developer tools (pressing F12 is one way), in the Sources tab, the bottom left bar has a set of icons. The "{}" icon is "Pretty print" and does this conversion on demand.
UPDATE: IE9 "F12 developer tools" also has a "Format JavaScript" feature in the Script tab under the Tools icon there. (see Tip #4 in F12 The best kept web debugging secret)

A: Can't you just use a javascript formatter (http://javascript.about.com/library/blformat.htm) ?

A: In Firefox, SpiderMonkey and Rhino you can wrap any code into an anonymous function and call its toSource method, which will give you a nicely formatted source of the function.
toSource also strips comments.
E. g.:
(function () { /* Say hello. */ var x = 'Hello!'; print(x); }).toSource()

Will be converted to a string:
function () {
    var x = "Hello!";
    print(x);
}

P. S.: It's not an "online tool", but all questions about general beautifying techniques are closed as duplicates of this one.

A: If you have a Mac and TextMate - An easy alternative for formatting Javascript is:

*

*Open the file with Textmate.

*Click on > Bundles > JavaScript > Reformat Document

*Crack open a beer.


text:
Q: How to force Chrome to use integrated GPU for decoding? I want Chrome to utilize iGPU (GT630 on i7-8700k) for video decoding, especially VP9 decoding on YouTube. My discrete GPU is GTX970 and it is not capable of decoding VP9. Currently, VP9 is software decoded on my system, putting load on CPU and occasionally skipping frames.
Both GPUs are detected by the system (Windows 10): GT630 as GPU0 and GTX970 as GPU1. I use 2 screens. I don't care where they need to be connected (970 or Motherboard) as long as Chrome uses iGPU and I can keep using Nvidia for gaming. One of the screens is 144Hz.
The motherboard is ASUS ROG Hero.
I've tried different settings, but nothing seems to work as intended, and usually people look for a solution to the exactly opposite problem...
Update (command switches):
Running chrome with --gpu-active-vendor-id=0x8086 --gpu-active-device-id=0x3E92 or --gpu-vendor-id=0x8086 --gpu-device-id=0x3E92 or --gpu-testing-vendor-id=0x8086 --gpu-testing-device-id=0x3E92 results in:

GPU0   VENDOR = 0x10de, DEVICE= 0x13c2 ACTIVE
  GPU1    VENDOR = 0x8086, DEVICE= 0x3e92
  GL_RENDERER ANGLE (NVIDIA GeForce GTX 970 Direct3D11 vs_5_0 ps_5_0)`

Vivaldi browser seems to accept --gpu-testing-vendor-id=0x8086 --gpu-testing-device-id=0x3E92 which results in:

GPU0   VENDOR = 0x8086, DEVICE= 0x3e92 ACTIVE
  GL_RENDERER ANGLE (NVIDIA GeForce GTX 970 Direct3D11 vs_5_0 ps_5_0)`

However it still uses Nvidia for renderer and doesn't utilize GT630 igfx.
The only method that works so far is disabling Nvidia card in Device Manager, launching Chrome, and re-enabling Nvidia card. When Chrome is launched without the discrete card present in the system, it runs with the following configuration and it's the only one that uses HW decoding from GT630:

GPU0   VENDOR = 0x8086, DEVICE= 0x3e92 ACTIVE
  GPU1    VENDOR = 0x10de, DEVICE= 0x13c2
  GL_RENDERER ANGLE (Intel(R) UHD Graphics 630 Direct3D11 vs_5_0 ps_5_0)

A: If you wish to automate the task of disabling the Nvidia adapter,
launching Chrome and re-enabling the adapter, you may use a batch script
(.bat file) that you can put on the desktop as an icon.
Using the Microsoft command line tool
Devcon.exe :
devcon.exe disable "NVIDIA GeForce GTX 970"
start "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
timeout 5
devcon.exe enable "NVIDIA GeForce GTX 970"

Check in Device Manager, section Display adapters, that the above name
of the adapter is correct.
Other utilities that can be used instead of Devcon are
DevManView
and
MultiMonitorTool.

A: I had this problem for a few months now and yesterday I found a solution to the problem:
Display settings -> Graphic settings -> Choose an app to set preference: Classic App -> Browse -> Firefox.exe (Chrome in your case) -> Firefox (Button that appears below the browse button) -> Options. I then chose Power Saving which makes my browser use the iGPU. High Performance would make the browser use my dedicated GPU.
Screenshot:

A: Spent a few hours tracking down a working solution to this with Windows 10 October 2018 Update. As of right now, using the directions provided by Unrul3r, I have been able to successfully enable hardware VP9 decoding in Chrome powered by the iGPU.
(Link to screenshot) Setup is as follows:
AMD Radeon R9-290 dGPU -> Connected via DisplayPort to 3840x2160 (4K) primary monitor.
Intel Core i5-8400 w/UHD 630 iGPU -> Connected via motherboard HDMI to 1920x1080 secondary monitor.
(Link to screenshot) This is what you want to see in chrome://gpu to verify everything is working:
Now, here's a quick walkthrough on how to get this working correctly.
Setup requirements

*

*A primary and secondary monitor

*At least one monitor must be physically connected to the iGPU outputs on the motherboard

*Connect the primary monitor and any others to your dGPU

Step-by-step

*

*Enter BIOS and make sure the iGPU is set to "Enabled" (not "Auto"). Check to make sure your dGPU is still set as the first enabled. Save and restart.

*Boot to Windows. It should automatically download and install the Intel drivers for the iGPU since it is now enabled and in-use. Personally I grabbed the full driver package for my UHD 630 from Intel and installed it manually.

*Restart once iGPU drivers are installed.

*Once back in Windows, open Display Settings and adjust the multiple display settings and positioning if your setup has changed.

*Near the bottom of the Display Settings window, click on Graphics settings. Leave the dropdown on Classic app, then click Browse and find the executable for the program you want to force to the iGPU.

*Once added, click the new listing, select Options, then select Power Saving to always force the iGPU to handle the rendering for that app.

(Link to screenshot) What you should see in the Graphics settings window when finished:
And there we go! Testing with this 8K YouTube video of the Unigine Superposition benchmark now shows ~2-3% CPU usage and <1% dropped frames (totally smooth to the eye, no stuttering). In comparison without the hardware decoder, CPU usage would be capped out, and the result was an unwatchable mess with >50% of frames dropped.

A: The simple solution is the one gave by Unrul3r, you just need to go to Graphic Settings in Windows 10 Control Panel and add Google Chrome or Firefox in Classic app mode, and press option button, select High performarce and that's it. Run some WebGL Benchmark and you will see the web browser using GPU-1 or the number of your discrete GPU. It works for any other application like Word, Excel, etc.
Another option to improve the performance in Google Chrome and specially the video playback (i.e Youtube), is to use the flags configuration page, to set the GPU Rendering to Enable, see the picture:
Google Chrome flags configuration
As you can see in the next image, my Discrete GPU es the GPU-1 AMD Radeon R7
GPU-1 as Radeon R7
Descripción en español: Activar el uso de la GPU discreta en Google Chrome (ATI Radeon), Activar la reproducción de vídeo por hardware en Youtube.

A: There is no desktop counterpart to Nvidia Optimus (sans discontinued Lucid Virtu) which allows dynamic GPU switching. In order to use Intel IGP for hardware acceleration in Chrome, you must connect a monitor to Intel port and set it as main display in settings (while allowing additional displays with Nvidia).
However, if your goal is to simultaneously game on one screen with Nvidia and play youtube on another screen with Intel, you are out of luck, as games also run from the main display (now rendered by Intel).
If you only do one at a time with a single monitor, try connecting it to both Intel and Nvidia, and toggle main display and panel input source as a workaround.


text:
Q: Merge iteratively one of multiple columns to dataframes in a list I have a (probably small) issue in iteratively combining columns from a single dataframe with other dataframes from a list. Some data to illustrate:
# load example data
library(vegan)
data(varechem)
data(varespec)

# generate predictor tables with overlapping rows and different amount of cols
varespec1 <- varespec[c(1:9), ]
varespec2 <- varespec[c(8:16), c(1:43)]
varespec3 <- varespec[c(14:24), c(1:41)]

# store predictor tables in list
subset_list <- list(varespec1 = varespec1,
  varespec2 = varespec2,
  varespec3 = varespec3)

# generate a table that holds ALL possible response variables as presence/absence
varechem_binary <- as.data.frame(apply(varechem, 2, cut,
  breaks = c(-Inf, 1.0, Inf), labels = c("Absent", "Present")))
row.names(varechem_binary) <- row.names(varechem)

The code above illustrates how I have prepared my data for classification tasks. The idea now is that the data.frames containing the predictor variables (varespec1, ...) in the list should be used to predict each of the columns in the response table (varechem_binary), but only one at a time. It is easy to merge the response table with each of the predictor tables:
# merge response table with each predictor table
merge_counter <- 0
merged_list <- list()
for(table in subset_list) {
    merge_counter <- merge_counter + 1
    current_name <- names(subset_list)[merge_counter]
    tmp <- merge(table, varechem_binary, by = "row.names")
    row.names(tmp) <- tmp$Row.names
    tmp <- tmp[, -1]
    merged_list[[current_name]] <- tmp
    rm(tmp)
}

Expected output:
What I'm now (or earlier in the code, if that makes more sense) looking for is a way to have a combination of each predictor table with each and exactly one of the columns from response table varechem in a list. This would be basically:
# storing in data frames just for illustration, I would like to do this within the list
# subsets for the 3 predictor tables with the first response variable
aa <- merged_list[[1]][,-c(46:58)]  # column 1:44 are the predictor variables, then the different response variables start
bb <- merged_list[[2]][,-c(45:57)]  # column 1:43 are the predictor variables, then the different response variables start
cc <- merged_list[[3]][,-c(43:58)] # column 1:41 are the predictor variables, then the different response variables start

# subsets for the 3 predictor tables with the second response variable
dd <- merged_list[[1]][,-c(45, 47:58)]
ee <- merged_list[[2]][,-c(44, 46:57)]
ff <- merged_list[[3]][,-c(42, 44:58)]

# subsets for the 3 predictor tables with the third response variable
gg <- merged_list[[1]][,-c(45, 46, 48:58)]
...

# this is just to illustrate how the list could look like, I would like to keep all files in a list all the time
list_for_classification_runs <- list(aa, bb, cc, dd, ee, ff, gg, ...)

This resulting list would be the input to a Random Forest classification call where the response variable will be classified by all other predictor variables coming from varespec such as:
for (current_table in list_for_classification_runs) {
  counter <- counter + 1
  # response_variable should be the one variable added to the predictor variables in the data frames
  RF_list[[counter]] <- ranger(response_variable ~ ., data = current_table)
}

A: Based on the comments of Gregor I came up with a similar approach. I did not merge the full varechem_binary with all elements of the subset_list, instead I added another for loop and iterated over all the columns in varechem_binary. Using drop = FALSE the row.names and structure are preserved, so the merge works:
merge_col_counter <- 0
column_counter <- 0
merged_column_list <- list()

for(table in subset_list) {
    merge_col_counter <- merge_col_counter + 1
    for (column in names(varechem_binary)) {
      column_counter <- column_counter + 1
      current_name <- paste(names(subset_list)[merge_col_counter], names(varechem_binary)[column_counter], sep = "_")
      print(current_name)
      tmp <- merge(table, varechem_binary[, column_counter, drop = FALSE], by = "row.names")
      row.names(tmp) <- tmp$Row.names
      tmp <- tmp[, -1]
      merged_column_list[[current_name]] <- tmp
      rm(tmp)
    }
    column_counter <- 0
}

There are probably ways to do this cleaner or more efficient, but it works, so I can continue

A: Another solution using apply functions:
lapply(subset_list, function(x) apply(varechem_binary, 2, function(var) merge(var, x, by= 'row.names')))

Using system.time() to benchmark these two approaches using your sample data, this approach is twice as fast (0.075 user  time) as your solution using the for loop (0.143 user time).


text:
Q: Populating a combobox with List After a combobox index changes, another combobox has to be populated with List<string> values. How am I able to do this?
For example:
Form (This is the way I'm having it now, incorrect though):
private void cbSelectEditFunction_SelectedIndexChanged(object sender, EventArgs e)
{
    cbSelectEditName.Items.Add(emp.FindEmployeeinFunction(cbSelectEditFunction.Text));
}

Class method:
public List<string> FindEmployeeinFunction(string aFunction)
{
    List<string> EmployeeListFunction = new List<string>();

    foreach (Employee TempEmployee in EmployeeList)
    {
        if(TempEmployee.Function == aFunction)
        {
            EmployeeListFunction.Add(TempEmployee.Username);
        }
    }
    return EmployeeListFunction;
}

Hope it's understandable this way. Let me know if I've forgotten something!

A: I think AddRange is the method you're looking for
//Assuming you don't want to continually add new items use Clear()
cbSelectEditName.Items.Clear();

//Use AddRange to add the list.  ToArray() is used to convert List<> to string[]
cbSelectEditName.Items.AddRange(emp.FindEmployeeinFunction(cbSelectEditFunction.Text).ToArray());


text:
Q: Read shapefile with Tkinter produce error I'm trying to load and read shapefile via Tkinter and tkFileDialog.
Following code shows what done .
Firstly I try to read shapefile directly and print its content  - no error , then reading the same shapefile with Tkinter dialog produce error.
import shapefile
import Tkinter, tkFileDialog

# Read the Arena shapefile using the Reader class of the pyshp module
arenafile = r"data\Arenas_NBA\Arenas_NBA.shp"
arena_shapefile = shapefile.Reader(arenafile)
arena_shapes = arena_shapefile.shapes()
arena_records = arena_shapefile.records()

print arena_records

root = Tkinter.Tk()
root.withdraw()
arenafile_tk = tkFileDialog.askopenfile(parent=root,
                                    mode='rb',
                                    initialdir="data\Arenas_NBA",
                                    title="Select Arena Shapefile",
                                    filetypes=(("shapefiles", "*.shp"),    ("all files", "*.*")))
if arenafile_tk != None:
    arena_shapefile_tk = shapefile.Reader(arenafile_tk)
    arena_shapes_tk = arena_shapefile_tk.shapes()
    arena_records_tk = arena_shapefile_tk.records()
    arenafile_tk.close()
    print arena_records_tk

This code produce following output:
[[u'High Value/Symbolic', u'Sports Arena', u'NBA', u'20040211', u'20100215', u'', u'American Airlines Arena', u'', u'', u'601 Biscayne Boulevard', u'', u'', u'', u'Miami', u'FL', u'33132', u'', u'Dade', u'Miami-Fort Lauderdale', 4.0, 25.78117, -80.18758, u'High', u'NGA', u'', u'Eastern', u'Southeast', 19600.0, u'Miami Heat'], [u'High Value/Symbolic', u'Sports Arena', u'NBA', u'20040211', u'20100215', u'', u'ARCO Arena', u'', u'', u'1 Sports Parkway', u'', u'', u'', u'Sacramento', u'CA', u'95834', u'', u'Sacramento', u'Sacramento', 9.0, 38.64932, -121.51869, u'High', u'NGA', u'', u'Western', u'Pacific', 17317.0, u'Sacramento Kings'], [u'High Value/Symbolic', u'Sports Arena', u'NBA', u'20040211', u'20100215', u'', u'EnergySolutions Arena', u'', u'', u'301 West South Temple', u'', u'', u'', u'Salt Lake City', u'UT', u'84101', u'', u'Salt Lake', u'Salt Lake City-Ogden', 8.0, 40.76629, -111.90093, u'High', u'NGA', u'Shares arean with Thunder (AF1).', u'Western', u'Northwest', 19911.0, u'Utah Jazz'], [u'High Value/Symbolic', u'Sports Arena', u'NBA', u'20040226', u'20100215', u'', u'Fed Ex Forum', u'', u'', u'191 Beale Street', u'', u'', u'', u'Memphis', u'TN', u'38103', u'', u'Shelby', u'Memphis', 4.0, 35.1381, -90.0513, u'High', u'NGA', u'Shares arena with Memphis Tigers (NCAA).', u'Western', u'Southwest', 18119.0, u'Memphis Gizzlies'], [u'High Value/Symbolic', u'Sports Arena', u'NBA', u'20060411', u'20100215', u'', u'Quicken Loans Arena', u'', u'', u'1 Center Court', u'', u'', u'', u'Cleveland', u'OH', u'44115', u'44115-4001', u'Cuyahoga', u'Cleveland-Akron', 5.0, 41.49648, -81.6887, u'High', u'NGA', u'Shares areana with Monsters (AHL) and Gladiators (AF1)', u'Eastern', u'Central', 20562.0, u'Cleveland Cavaliers'], [u'High Value/Symbolic', u'Sports Arena', u'NBA', u'20060411', u'20100215', u'', u'Oracle Arena', u'', u'', u'7000 Coliseum Way', u'', u'', u'', u'Oakland', u'CA', u'94621', u'94621-1917', u'Alameda', u'San Francisco-Oakland', 9.0, 37.75131, -122.20217, u'High', u'NGA', u'', u'Western', u'Pacific', 19596.0, u'Golden State Warriors'], [u'High Value/Symbolic', u'Sports Arena', u'NBA', u'20060411', u'20100215', u'', u'New Orleans Arena', u'', u'', u'1601 Girod Street', u'', u'', u'', u'New Orleans', u'LA', u'70113', u'70113-3124', u'Orleans', u'New Orleans', 6.0, 29.94889, -90.08203, u'High', u'NGA', u'', u'Western', u'Southwest', 18500.0, u'New Orleans Hornets'], [u'High Value/Symbolic', u'Sports Arena', u'NBA', u'20060411', u'20100215', u'', u'Rose Garden', u'', u'', u'1 Center Court', u'', u'', u'', u'Portland', u'OR', u'97227', u'', u'Multnomah', u'Portland', 10.0, 45.53165, -122.66692, u'High', u'NGA', u'Shares areana with Winterhawks (WHL).', u'Western', u'Northwest', 20630.0, u'Portland Trailblazers'], [u'High Value/Symbolic', u'Sports Arena', u'NBA', u'20060411', u'20100215', u'', u'Amway Arena', u'', u'', u'600 West Amelia Street', u'', u'', u'', u'Orlando', u'FL', u'32801', u'', u'Orange', u'Orlando', 4.0, 28.54883, -81.38636, u'High', u'NGA', u'Shares arena with Titans (NLL) and Predators (AF1)', u'Eastern', u'Southeast', 17519.0, u'Orlando Magic'], [u'High Value/Symbolic', u'Sports Arena', u'NBA', u'20060411', u'20100215', u'', u'Bradley Center', u'', u'', u'1001 North 4th Street', u'', u'', u'', u'Milwaukee', u'WI', u'53203', u'53203-1314', u'Milwaukee', u'Milwaukee', 5.0, 43.04346, -87.91736, u'High', u'NGA', u'Shares arena with Marquette Golden Eagles (NCAA)', u'Eastern', u'Central', 18717.0, u'Milwaukee Bucks'], [u'High Value/Symbolic', u'Sports Arena', u'NBA', u'20060411', u'20100215', u'', u'American Airlines Center', u'', u'', u'2500 Victory Avenue', u'', u'', u'', u'Dallas', u'TX', u'75219', u'75219-7601', u'Dallas', u'Dallas-Fort Worth', 6.0, 32.79062, -96.81043, u'High', u'NGA', u'Shares arena with Stars (NHL)..', u'Western', u'Southwest', 20337.0, u'Dallas Mavericks'], [u'High Value/Symbolic', u'Sports Arena', u'NBA', u'20060411', u'20100215', u'', u'TD Garden Center', u'', u'', u'100 Legends Way', u'', u'', u'', u'Boston', u'MA', u'02114', u'02114-4714', u'Suffolk', u'Boston', 1.0, 42.36653, -71.06206, u'High', u'NGA', u'Shares arena with Bruins (NHL) and Blazers (NLL).', u'Eastern', u'Atlantic', 18624.0, u'Boston Celtics'], [u'High Value/Symbolic', u'Sports Arena', u'NBA', u'20060411', u'20100215', u'', u'Pepsi Center', u'', u'', u'1000 Chopper Circle', u'', u'', u'', u'Denver', u'CO', u'80204', u'', u'Denver', u'Denver', 8.0, 39.74916, -105.00677, u'High', u'NGA', u'Shares arena with Avalanche (NHL) and Mammoth (NLL).', u'Western', u'Northwest', 19155.0, u'Denver Nuggets'], [u'High Value/Symbolic', u'Sports Arena', u'NBA', u'20060411', u'20100215', u'', u'Philips Arena', u'', u'', u'1 Philips Drive NW', u'', u'', u'', u'Atlanta', u'GA', u'30303', u'', u'Fulton', u'Atlanta', 4.0, 33.7573, -84.39631, u'High', u'NGA', u'Shares arena with Thashers (NHL) and Dream (WNBA).', u'Eastern', u'Southeast', 19445.0, u'Atlanta Hawks'], [u'High Value/Symbolic', u'Sports Arena', u'NBA', u'20060411', u'20100215', u'', u'United Center', u'', u'', u'1902 West Madison Street', u'', u'', u'', u'Chicago', u'IL', u'60612', u'60612-2459', u'Cook', u'Chicago', 5.0, 41.88059, -87.67418, u'High', u'NGA', u'Shares arena with Blackhawks (NHL).', u'Eastern', u'Central', 20917.0, u'Chicago Bulls'], [u'High Value/Symbolic', u'Sports Arena', u'NBA', u'20060411', u'20100215', u'', u'Wachovia Center', u'', u'', u'3601 South Broad Street', u'', u'', u'', u'Philadelphia', u'PA', u'19148', u'', u'Philadelphia', u'Philadelphia', 3.0, 39.90097, -75.17218, u'High', u'NGA', u'Shares arena with Flyers (NHL) and Wings (NLL).', u'Eastern', u'Atlantic', 21600.0, u'Philadelphia 76ers'], [u'High Value/Symbolic', u'Sports Arena', u'NBA', u'20060411', u'20100215', u'', u'IZOD Center', u'', u'', u'50 Route 120', u'', u'', u'', u'East Rutherfor', u'NJ', u'07073', u'', u'Bergen', u'New York-Newark', 2.0, 40.81163, -74.06767, u'High', u'NGA', u'', u'Eastern', u'Atlantic', 20049.0, u'New Jersey Nets'], [u'High Value/Symbolic', u'Sports Arena', u'NBA', u'20060411', u'20100215', u'', u'Madison Square Garden', u'', u'', u'4 Pennsylvania Plaza', u'', u'', u'', u'New York', u'NY', u'10001', u'', u'New York', u'New York-Newark', 2.0, 40.7506, -73.99378, u'High', u'NGA', u'Shares arena with Rangers (NHL), Saint John Red Storm (NCAA), and Liberty (WNBA).', u'Eastern', u'Atlantic', 19763.0, u'New York Knicks'], [u'High Value/Symbolic', u'Sports Arena', u'NBA', u'20060411', u'20100215', u'', u'Verizon Center', u'', u'', u'601 F Street NW', u'', u'', u'', u'Washington', u'DC', u'20004', u'', u'District of Columbi', u'Washington', 3.0, 38.89838, -77.02098, u'High', u'NGA', u'Shares arena with Capitals (NHL), Mystics (WNBA) and Georgetown Hoyas (NCAA)', u'Eastern', u'Southeast', 20173.0, u'Washington Wizards'], [u'High Value/Symbolic', u'Sports Arena', u'NBA', u'20060411', u'20100215', u'', u'Staples Center', u'', u'', u'1111 South Figueroa Street', u'', u'', u'', u'Los Angeles', u'CA', u'90015', u'', u'Los Angeles', u'Los Angeles', 9.0, 34.04321, -118.26716, u'High', u'NGA', u'Shares arena with Kings (NHL), Sparks (WNBA), and D-Fenders(D-League).', u'Western', u'Pacific', 18997.0, u'Los Angeles Lakers, Clipppers'], [u'High Value/Symbolic', u'Sports Arena', u'NBA', u'20060411', u'20100215', u'', u'Target Center', u'', u'', u'600 First Avenue North', u'', u'', u'', u'Minneapolis', u'MN', u'55403', u'', u'Hennepin', u'Minneapolis-Saint Paul', 5.0, 44.97944, -93.27609, u'High', u'NGA', u'Shares arena with Lynx (WNBA).', u'Western', u'Northwest', 20500.0, u'Minnesota Timberwolves'], [u'High Value/Symbolic', u'Sports Arena', u'NBA', u'20060411', u'20100215', u'', u'US Airways Center', u'', u'', u'201 East Jefferson', u'', u'', u'', u'Phoenix', u'AZ', u'85004', u'85004-2412', u'Maricopa', u'Phoenix', 8.0, 33.446, -112.07125, u'High', u'NGA', u'Shares arena with Mercury (WNBA), Rattlers (AF1)', u'Western', u'Pacific', 18422.0, u'Phoenix Suns'], [u'High Value/Symbolic', u'Sports Arena', u'NBA', u'20060411', u'20100215', u'', u'Time Warner Cable Arena', u'', u'', u'333 East Trade Street', u'', u'', u'', u'Charlotte', u'NC', u'28202', u'', u'Mecklenburg', u'Charlotte', 4.0, 35.22373, -80.83999, u'High', u'NGA', u'Shares arena with Checkers (AHL),', u'Eastern', u'Southeast', 19026.0, u'Charlotte Bobcats'], [u'High Value/Symbolic', u'Sports Arena', u'NBA', u'20060411', u'20100215', u'', u'Conseco Fieldhouse', u'', u'', u'125 South Pennsylvania Street', u'', u'', u'', u'Indianapolis', u'IN', u'46204', u'', u'Marion', u'Indianapolis', 5.0, 39.76401, -86.15557, u'High', u'NGA', u'Shares arena with Fever (WNBA).', u'Eastern', u'Central', 18345.0, u'Indiana Pacers'], [u'High Value/Symbolic', u'Sports Arena', u'NBA', u'20060411', u'20100215', u'', u'Toyota Center (Houston)', u'', u'', u'1510 Polk Street', u'', u'', u'', u'Houston', u'TX', u'77002', u'77002-7130', u'Harris', u'Houston', 6.0, 29.75078, -95.36218, u'High', u'NGA', u'Shares arena with Comets (WNBA).', u'Western', u'Southwest', 18300.0, u'Houston Rockets'], [u'High Value/Symbolic', u'Sports Arena', u'NBA', u'20060411', u'20100215', u'', u'Palace of Auburn Hills', u'', u'', u'2 Championship Drive', u'', u'', u'', u'Auburn Hills', u'MI', u'48326', u'', u'Oakland', u'Detroit', 5.0, 42.69721, -83.24467, u'High', u'NGA', u'Shares arena with Shocks (WNBA).', u'Eastern', u'Central', 22076.0, u'Detroit Pistons'], [u'High Value/Symbolic', u'Sports Arena', u'NBA', u'20060411', u'20100215', u'', u'AT&T Center', u'', u'', u'1 AT&T Center Parkway', u'', u'', u'', u'San Antonio', u'TX', u'78219', u'', u'Bexar', u'San Antonio', 6.0, 29.42703, -98.43766, u'High', u'NGA', u'Shares arena with Silver Stars (WNBA), Rampage (AHL).', u'Western', u'Southwest', 18581.0, u'San Antonio Spurs'], [u'High Value/Symbolic', u'Sports Arena', u'NBA', u'20060411', u'20100215', u'', u'Ford Center', u'', u'', u'100 West Reno Avenue', u'', u'', u'', u'Oklahoma City', u'OK', u'73102', u'73102-2473', u'Oklahoma', u'Oklahoma City', 6.0, 35.46347, -97.51483, u'High', u'NGA', u'', u'Western', u'Southwest', 18203.0, u'Oklahoma City Thunder'], [u'High Value/Symbolic', u'Sports Arena', u'NBA', u'20100215', u'', u'', u'Air Canada Centre', u'', u'', u'40 Bay Street', u'', u'', u'', u'Toronto', u'ON', u'M5J', u'2X2', u'', u'', 0.0, 43.64333, -79.37916, u'High', u'NGA', u'Shares arena with Maple Leafs (NHL) and Rock (NLL).', u'Eastern', u'Atlantic', 19800.0, u'Toronto Raptors']]
Traceback (most recent call last):
 File "C:/Users/test.py", line 22, in <module>
arena_shapefile_tk = shapefile.Reader(arenafile_tk)
File "C:\Python27\lib\site-packages\shapefile.py", line 546, in __init__
raise ShapefileException("Shapefile Reader requires a shapefile or file-like object.")
shapefile.ShapefileException: Shapefile Reader requires a shapefile or file-like object.

Process finished with exit code 1

Link to Arena shapefile

A: Short answer:  try:
arenafile_tk = tkFileDialog.askopenfilename()

instead of:
arenafile_tk = tkFileDialog.askopenfile()

and adjust the arguments accordingly.
Long answer: A shapefile consists of multiple files, when you open the ".shp" file name, it seeks out the others:
arena_shapefile = shapefile.Reader(r"data\Arenas_NBA\Arenas_NBA.shp")

If you try to pass an open file handle, as returned by askopenfile(), it expects you to provide information about those other files:
arena_shp_file = open(r"data\Arenas_NBA\Arenas_NBA.shp", "rb")
arena_dbf_file = open(r"data\Arenas_NBA\Arenas_NBA.dbf", "rb")
arena_shapefile = shapefile.Reader(shp=arena_shp_file, dbf=arena_dbf_file)

Or some such.


text:
Q: Responsive layouting with mdbootstrap 4 I'm using mdbootstrap4 to create a prototype UI for a web application.
I've been trying to achieve the following:
Design
Essentially, the login container scales up as screen width increases. As the available screen width decreases (on mobile), the link and button should conform to mobile UI patterns: login button first, full width of its container. I've been trying to get this to work, but either the link text overflows (multiple lines) or the button's dimensions become weird and overflows the text as well.
Additionally, I can't seem to fix the responsive ordering and alignment.
My code:

                    <form name="">

                        <input type="text" id="form1" class="form-control">
                        E-mailadres

                        <input type="password" id="form2" class="form-control">
                        Password

                                Ik ben mijn paswoord vergeten

                                <button class="btn btn-primary btn-block order-last order-sm-first" target=".">Inloggen</button>

                    </form>

I've been fiddling to find an elegant solution to this. Can anyone point me in the right direction?

A: Try this

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

                    <form name="">

                            <input type="text" id="form1" class="form-control">
                            E-mailadres

                            <input type="password" id="form2" class="form-control">
                            Password

 Ik ben mijn paswoord vergeten

                                    <button class="btn btn-primary btn-block order-last order-sm-firstt" target=".">Inloggen</button>

                    </form>