text:
Q: What's the difference between direction and orientation? I frequently see these two words in 3D programming. For example:

the direction of the directional light
the orientation of camera

So, what's the difference between them?

A: In geometry, you can represent the orientation by a line and the direction by a Euclidean vector (represented by an arrow).

A: I think that the words are very similar, but there is arguably a subtle distinction.
The word direction suggests movement. While it may refer to a static object, it describes it as if it were or could move toward the described location.

the position toward which someone or something moves or faces:
Cars were facing every direction after slamming into each other on the icy road.
I glanced in her direction (= toward her).
You're headed in the direction of (= toward) Toronto.

The word orientation seems to connote that the object is static and there is no suggestion of movement. As noted in a comment to this post, it is a relationship to the environment.

the position of something in relation to its surroundings:
The church has an east-west orientation (= has one main side facing east and the opposite side facing west).

There are many cases where either could be used, (even a paraphrase of one of the examples under direction)

Cars were oriented every which way after slamming into each other on the icy road.

However, there are many when only one or the other will do.

He moved in the direction of the door.
His orientation allowed him to see the window while lying prone.

A substitution probably could be made, but it would call for a more convoluted sentence.

A: Orientation means "direction of a thing". For example,

The building was oriented towards north direction.


text:
Q: How to enable permissions in SQL Server 2012 FileTable folder share? After successfully creating a FileTable, I tried viewing the fileshare but my permissions are denied. In Management Studio, right-clicking on FileTable then "Explore FilteTable Directory" gives me the following error message:

The File location cannot be opened. Either access is not enabled or
  your do not have permissions for the same.

If I try to manually reach the share using \mycomputer\sqlexpress..., I'm still denied access.
This is SQL Express running on my local machine. I'm accessing this share from the same machine. What am I missing?

A: Does the windows user you are trying to access the fileshare as have SQL server access to the filetable database?  Windows share permissions don't apply to filestream shares so, make sure you have permissions in the SQL database.
The other things you need to check to make sure you have access are the setting in configuration manager to ensure that Transact-SQL access is enabled as well as file I/O access (you can also set here whether clients can connect to the share remotely too).
To access these settings, open SQL Server configuration manager, in SQL server services, right click on the SQL Server Service for your instance and select properties, on the filestream tab you will see the options.
The next place you need to check for settings (yes, you have to enable this feature in 3 separate places!) is the level of access on the SQL server itself.
Open SQL Server Management Studio, connect to your SQL instance and right click on your server and select properties.  Click on the advanced section and there is a section for filestream, you need to select full access enabled if you want to use filetable.
I actually found this article after typing all of that which explains how to enable the pre-requisites for filetables:
Enable the Prerequisites for FileTable
Hope this helps.

A: For me, since my server is a networked server, the resolution was:

*

*Step into SQL Server Configuration Manager

*Open SQL Server Services

*Right click on SQL Server (MSSQLSERVER) and go to properties

*Go to the FILESTREAM tab and make sure Allow remote clients access to FILESTEAM data is checked

A: Can you check a few things?
Can you via Windows Explorer try to browse to each of the following:
\\YOURCOMPUTERNAME

\\YOURCOMPUTERNAME\[FILESTREAM Share Name]\  e.g MSSQLSERVER

\\YOURCOMPUTERNAME\[FILESTREAM Share Name]\[FILESTREAM Directory Name]

\\YOURCOMPUTERNAME\[FILESTREAM Share Name]\[FILESTREAM Directory Name]\[FILETABLE Table Name]

[FILESTREAM Share Name]

*

*this is the name as defined at the Server Insance level when you set FILESTREAM  access up

*to check it, right click on the Server Connection in SSMS and choose Properties

*then look in Advanced --> FILESTREAM --> FILESTREAM Share Name

[FILESTREAM Directory Name]

*

*this is the name as defined in the database when you set FILESTREAM
access up

*to check it, right click on the Database in SSMS and choose Properties

*then look in Options --> FILESTREAM --> FILESTREAM Directory Name

[FILETABLE Table Name]

*

*Remember when you name your table it has to conform with Windows Folder naming rules (ie avoid special characters) e.g "TABLE|WEIRDCHARACTER"

Note(1): I have found that if you give your user only "ALTER" permission on the Filetable Table it will be browseable at the

\\YOURCOMPUTER\MSSQLSERVER\FILESTREAM_DIRECTORY_NAME\

level but you wont actually be able to browse the contents of the "directory"
Note(2): if you only give SELECT, UPDATE, DELETE, INSERT permission to a user on a filetable Table it will be able to access the folder with the fullpath and see the contents and act on them - create new files, modify existing files

\\YOURCOMPUTER\MSSQLSERVER\FILESTREAM_DIRECTORY_NAME\FILETABLE_NAME\

but not browse it at the FILESTREAM_DIRECTORY_NAME level - it in essence becomes a "hidden" directory that you must know the entire pathname to find (unless you guess it of course in a brute attack)

A: Other posters have dealt with the FILESTREAM set up.
To browse and access files within a filetable, VIEW DEFINTION and SELECT permissions will be required as a minimum. The ALTER permission  referenced in dmc2005's post is not required.
Example (granting access to a Windows user or group):
GRANT VIEW DEFINITION,SELECT ON FileTableName TO [MYDOMAIN\MYGROUPNAME]

Assigning the User / Group to one of the fixed database roles (for example db_datareader) will not grant the required permissions for filestream access. The permissions must be explicitly granted.

redpajama_set_name: RedPajamaStackExchange


text:
Q: OneDrive API: Getting Internal server Error while using action.createLink for a shared file I am trying to create a publicly shared link for OneDrive files.
I have got onedrive.readwrite scope from the onedrive account(A).
I tried creating a sharing link for the Account A's file using the following call,
https://api.onedrive.com/v1.0/drive/items/{normal_file_id}/action.createLink

and it worked. I got the web url and the status is 200.
Then I shared another Account B's folder with Account A.
Now,
I tried the same by creating a sharing link for the Account A's  shared file of Account B using the following call,
https://api.onedrive.com/v1.0/drive/items/{shared_file_id}/action.createLink

Now, I am getting internal server error with status 500.
I tried both these scenarios in Apigee console. getting the same trouble.
Interestingly when I look into the sharing info for the file in Onedrive. I can see a Sharing link created for that file in the name of Apigee Api console.

But, I am always getting 500 errors while working in API. How to rectify this problem?

A: It looks like this is a bug in the API. The error is happening after link creation but before the API call returns which is why the link is successfully created. Please use the issue you opened on GitHub to track: https://github.com/OneDrive/onedrive-api-docs/issues/237


text:
Q: Hard reduction formula for integral evolving $e^{ax}$ and $\cos(\ln x)$ So I spent a whole day trying to do this reduction formula but didn't got it !
The question says find the reduction formula for $$∫ e^{2x} \cos(\ln x) \,d x$$
I've searched a lot and found this integral which is some how close to the problem but this one have a constant derivative to the function inside the Cos integrating by parts twice can send this constant to the outside, but in my question the derivative of $\ln x$ is just another variable
Is this non-integrable function ?!


text:
Q: Optimization with and without exceptions after compilation - would the results be the same?
*

*Given a program , that uses exceptions for its functionality : if we'd run the program with optimization at one time , and after that we'd run it without optimization - would the outputs of the both executions be the same ?

*Given the same program , that doesn't use exceptions for its functionality - if we'd run the program with optimization at one time , and after that we'd run it without optimization - would the outputs of the both executions be the same ?
Both questions are taken from an interview that took place a few days ago ...
I think that the answer for the first questions is NO - since when some code line throws an exception , the scope is dynamic , and optimization would probably change the order of the execution of the program .Hence ,the outputs of two different executions (one with optimization and one without) might be different ...
Is this correct ?
What about the 2nd question ?
Much appreciated :)

A: Optimization is not supposed to change observable behavior. In general, the answer to both questions is yes. You don't mention language. For C++, there are a lot of situations where behavior is undefined, if that's the case you might see differences.
You write:

optimization would probably change the order of the execution of the program .

While that's true, to an extent, C++ has the concept of a checkpoint that limits re-ordering.


text:
Q: Angular 4 Content Bleeding on Route Param Update I have this content bleeding issue. I am routing to pages pulling the product id while subscribing to the route params.
It works fine on the initial load, however, if the route param is updated the new content of the product is loaded on top of the old content. I don't want the content to bleed over into each other as they cause conflicts.
PRODUCT.COMPONENT.TS
...
constructor(
  private authService: AuthService,
  private route: ActivatedRoute,
  private router: Router,
  private httpService: HttpService
) { }

ngOnInit() {
  this.route.params
    .subscribe(params => {
      const id = +params['id'];
      this.loadProduct(id);
      console.log(`Current param ID is: ${id}`);
    });
}

loadProduct(prod_id: number) {
  this.httpService.getProduct(prod_id)
    .subscribe((prod: any) => {
      this.prod = prod.data[0];
      console.log(this.prod);
      this.processProduct();
    });
}
...

APP.COMPONENT.HTML

  <afn-navbar fxFlex="7%"></afn-navbar>

    <afn-sidebar fxLayout="column" fxFlex="10%"></afn-sidebar>

      <router-outlet></router-outlet>

  <afn-footer fxFlex="5%"></afn-footer>

ROUTE CONFIGURATIONS

const routes: Routes = [
  { path: 'lt/dashboard', canActivate: [ AuthGuard ], component: DashboardComponent },
  { path: 'lt/product/:id', canActivate: [ AuthGuard ], component: ProductComponent }
];

DISCOVERY
I noticed that the areas that had the content bleeding are the ones that are embedded/child components whose selector tags that are property bound to an array structure for an input source. I suspect that the array is being appended instead of being overwritten by its new content. Hence the duplication of information.
for example:
<app-stops class="card-spacer" [stops]="prod.delivery.stops">Stops are loading...</app-stops>

STOPS.COMPONENT.TS

import { Component, Input, OnInit } from '@angular/core';

import { Stop } from '../../../definitions/stop';

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

  @Input() stops: Stop[];

  ngOnInit() {
    console.log(this.stops);
  }

}

STOPS.COMPONENT.HTML

      <afn-stop-panel [stop]="stop" *ngFor="let stop of stops"></afn-stop-panel>

How do I clear these tags of their existing content prior to input of new content information?

A: RESOLVED
I was missing a step during the dynamic creation of the Reactive Form.
this.productForm: FormGroup = this.formBuilder.group({});

This issue was the root cause of my page bleeding information because the content reload would halt due to the crash of my form. The new controls would be added to the existing controls in the formGroup/Form.


text:
Q: Is $g(x) \in \mathrm{argmax}_{y \in \Omega} \, f(x,y)$ (Lipschitz) continuous when so is $f(x,y)$? Let $D$ be a subset of $\mathbb{R}^n$ and $\Omega$ be a compact subset of $\mathbb{R}^m$; $\;f: D \times \Omega \to \mathbb{R}$ be a continuous function. Define $M(x) \subseteq \Omega$ as
\begin{equation}
   M(x) := \{ y \in \Omega: f(x,z) \leq f(x,y) \textrm{ for all } z \in \Omega \},
\end{equation}
which can be considered as the "argmax" operator on $f$ over $\Omega$.
Then, $M(x)$ is not empty since for every $x \in D$, $f(x, \cdot)$ has its maximum (and of course its minimum) over the compact set $\Omega$. Let $g: D \to \Omega$ be any function satisfying
\begin{equation}
   g(x) \in M(x).
\end{equation}
and suppose that $M(x)$ is a singleton for all $x \in D$, so that $g(x)$ is uniquely defined.
Then, my questions can be summarized as follows.

*

*(Continuity of $g(x)$) Can we conclude that $g$ is continuous? If not, what's the additional condition(s) on $f$ (or its domain $D$) to hold continuity of $g$?

*(Lipschitz Continuity of $g(x)$) Is $g$ is Lipschitz continuous when so is $f$?$-$here, Lipscthiz continuity on $f$ means that there is $L > 0$ such that \begin{equation}
\big | \, f(x_1,y_1) - f(x_2,y_2) \big | \leq L \, \big \|(x_1,y_1) - (x_2,y_2) \big \| \;\;\;\,
\forall (x_1, y_1), \, (x_2, y_2) \in D \times \Omega,
\end{equation}
where $\| \cdot \|$ is any norm on $\mathbb{R}^n \times \mathbb{R}^m$.

*What happens if $M(x)$ is not a singleton, but contains at least two elements for some or all $x \in D$?

I think the statements do not hold in general, but I fail to give a counter-example or prove that it's true. I also found some discussions on the continuity of $h(x) := \max_{y \in \Omega} f(x,y)$, e.g.,

*

*Is supremum over a compact domain of separately continuous function continuous?

*How prove this $g(x)=\sup{\{f(x,y)|0\le y\le 1\}}$ is continuous on $[0,1]$

*Is $f(x)=\sup_{y\in K}g(x, y)$ a continuous function?.
However, those cases do not discuss about the continuity of $g$ constructed by "argmax", rather than "sup" or "max."
Many thanks in advance.


text:
Q: Detect when a clientsocket attempts to connect to a serversocket I create a serversocket and bind it to a local port, then tell it to queue a max of 5 connections in the backlog. I want a way to detect when a clientsocket connects to the serversocket/when the backlog has a queued connection. I'm running the socket.accept() in a separate thread and need to be able to stop the separate thread which i can't do when the thread is hanging for on socket.accept().
The reason for this is that I am trying to have the server socket only listen for connections when a user runs a command and then stop when a user runs a different command.
I would like my code to read something like:
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind((socket.gethostname(), 1024))
serversocket.listen(5)

class connectListner (threading.Thread):
    def run(self):
        while True:
            if <item in backlog>:
                clientsocket, address = serversocket.accept()
            pass

I can then use thread.join() to stop the thread
Any help would be appreciated

A: I propose you to use set the socket to non-blocking mode, and to use select to
know when a client is waiting for accept, since the server socket becomes readable:
serversocket.setblocking(False)

readable, writable, err = select.select([serversocket.fileno()], [], [], 1)
if readable:
    clientsocket, address = serversocket.accept()

After 1 second, if no client is connected, the select call ends, and will be started
again by your while loop. So, you can exit the thread if readable is an empty
list, for example. Feel free to set a lower timeout for the select if you need
more fined-grain control on the thread.


text:
Q: POST the ID to PHP on click JS FILE
       // Three buttons here SAVE, DELETE and CANCEL
       // Save works like supossed to be it saves to Database
       // Delete does only $calendar.weekCalendar("removeEvent", calEvent.id); but dont delete from database

    buttons: {
                   save : function() {
                      calEvent.id = id;
                      id++;
                      calEvent.start = new Date(startField.val());
                      calEvent.end = new Date(endField.val());
                      calEvent.title = titleField.val();
                      calEvent.body = bodyField.val();

                      //post to events.php

                      $.post("events.php?action=save&start="+calEvent.start.getTime()/1000+"&end="+calEvent.end.getTime()/1000+"&title="+calEvent.title+"&body="+calEvent.body);

                      $calendar.weekCalendar("removeUnsavedEvents");
                      $calendar.weekCalendar("updateEvent", calEvent);
                      $dialogContent.dialog("close");
                   },,
                "delete"  : function() {
                      calEvent.id = id;
                      id++;

                      // It must send calEvent.id to PHP action=del
                     $.get( "events.php", { action: "del", id: calEvent.id });

                      $calendar.weekCalendar("removeEvent", calEvent.id);
                      $dialogContent.dialog("close");

                    } ,
                   cancel : function() {
                      $dialogContent.dialog("close");
                   }
                }
             }).show();

PHP FILE
$action = $_REQUEST['action'];

if (!$link = mysql_connect('host', 'user', 'pass')) {
    echo 'Could not connect to mysql';
    exit;
}

if (!mysql_select_db('agenda', $link)) {
    echo 'Could not select database';
    exit;
}
if ($action === 'del')
{
    $id = $_GET['id'];

    $del = "DELETE FROM meeting_rooms_calendar WHERE id='$id'";
    $result = mysql_query($del, $link);
    print_r($id);
}
elseif($action === 'save')
{
    $title = $_REQUEST['title'];
    $body = $_REQUEST['body'];
    $start_time = (int)$_REQUEST['start'];
    $start_time = $start_time + 60*60;
    $end_time = (int)$_REQUEST['end'];
    $end_time = $end_time + 60*60;
    $start = date('c',$start_time);
    $end = date('c',$end_time);
    $sql = "INSERT INTO meeting_rooms_calendar(title,body,start,end) VALUES ('$title','$body','$start','$end')";
    $result = mysql_query($sql, $link);

}

Now if i click save, save will post the request variables to PHP and PHP to the database, when i click DELETE it doenst send the requested ID to PHP so PHP can;t delete it from database how can i make the JS file send the ID to PHP.
If i do it manually by
www.myweb.com/events.php?action=del&id=1

This wil delete it from database, so that means PHP works.
It's just the JS part, it dont delete it automaticly from database.


text:
Q: How to get the complete log for bean shell scripts in jmeter I am using Apache JMeter 3.1 and in my test suite I have a BeanShell PreProcessor. When I run the scrip, in the Log Viewer I can see there are errors in the bean shell script. But the error message is very limited, how can I get the complete error?
For example, an error I see in the Log Viewer is as follows,
ERROR - jmeter.util.BeanShellInterpreter: Error invoking bsh method: eval    Sourced file: inline evaluation of: ``// Following is a sample for input // "abc.org/def/xyz . . . ''
Is there a way I can retrieve the complete error?

A: You can enable debug output in at least 2 ways:

*

*Adding debug() directive to the beginning of your Beanshell script - debugging output will go to STDOUT (JMeter console)

*Putting your code inside the try block like:
try {
    //your code here
}
catch (Throwable ex) {
    log.error("Something went wrong", ex);
    throw ex
}

This way full exception stacktrace will be available in jmeter.log file
I would rather recommend switching to JSR223 Elements and Groovy language as Groovy is more Java-compliant and provides better performance. See Groovy Is the New Black for details.


text:
Q: wcf not picking up the code I have created a wcf service, but when i am installing it on server, it is not picking the code.
Here is my program.cs class:
 log4net.Config.XmlConfigurator.Configure();
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
            {

                new Service1()
            };

            ServiceBase.Run(ServicesToRun);

and here is my service1.cs:
public Service1()
        {
            logger.Info("log started");
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            logger.Info("Service Started");
            timerHandlingFirst.Elapsed += new ElapsedEventHandler(OnElapsedTimeFirst);
            timerHandlingFirst.Enabled = true;

            timerHandling.Elapsed += new ElapsedEventHandler(OnElapsedTime);
            timerHandling.Enabled = true;
        }

I have attached used log4net dll, but its not even generating the logs.


text:
Q: Do JavaScript event handlers get overwritten? I am curious if binding an event to an object multiple times cause problems by stacking multiple event listeners on top of each other or do they override each other?  For example if I have an attachHandlers function
function _attachHandlers() {

            // Slider hover
            var isDown = false;
            $('.ui-slider-handle').mousedown(function () {
                // Create tool tip
                isDown = true;

                var tt = $(document.createElement('span')).addClass('sk-tooltip');
                var handle = $(this);

                var left = parseInt(handle.css('left'));

                var val = _convertSliderValue(Math.round(left / 5 / 14.2857));
                tt.text(val);

                handle.append(tt);

                var newLeft = (handle.outerWidth() - tt.outerWidth()) / 2;
                tt.css({
                    'left': newLeft
                });

                $(document).mousemove(function (event) {
                    var left = parseInt(handle.css('left'));

                    var val = _convertSliderValue(Math.round(left / 5 / 14.2857));
                    tt.text(val);

                    var newLeft = (handle.outerWidth() - tt.outerWidth()) / 2;
                    tt.css({
                        'left': newLeft
                    });
                });

            });

            $(document).mouseup(function () {
                if (isDown) {
                    $(document).unbind('mousemove');

                    $(this).find('.sk-tooltip').remove()
                    isDown = false;
                }

            });
        }

I need to re-attach these handlers at some point in my code and therefore I was just going to call _attachHandlers() to re-bind them, however, I will also be re-binding the document listener for the mouseup event every time this happens. Therefore, is it alright to do this and will the event handler just get overwritten everytime or do I have to unbind the handler first before it can be re-bound?


text:
Q: if else condition in blade file (laravel 5.3) I want to check if/else condition in my blade file. I want to check the condition $user->status =='waiting' as the code given below. Output returns correctly as I expected. But along with my output I caught curly braces {} printed. I want to remove curly braces in result. Is there anything wrong in my if condition ?
@if($user->status =='waiting')
         {
           travel_id }}" data-toggle="modal" data-target="#myModal">Approve/Reject
         }
         @else{
           {{ $user->status }}
         }
         @endif

A: I think you are putting one too many curly brackets. Try this
 @if($user->status=='waiting')
            travel_id !!}" data-toggle="modal" data-target="#myModal">Approve/Reject
            @else
            {!! $user->status !!}
        @endif

A: You don't have to use braces in blade conditions, so your code would be like this:
@if($user->status =='waiting')

        travel_id }}" data-toggle="modal" data-target="#myModal">
            Approve/Reject

@else

        {{ $user->status }}

@endif

A: No curly braces required you can directly write
@if($user->status =='waiting')
      travel_id }}" data-toggle="modal" data-target="#myModal">Approve/Reject
@else
      {{ $user->status }}
@endif

A: If wants to assign value on basis of if else  inside blade.
@if($shipping_fee >= 1)
  @php
    $shipping_fee = $any_variable1
  @endphp
@else
  @php
    $shipping_fee = $any_variable2
  @endphp
@endif


text:
Q: Single Sign-on over Multiple Domains We are developing a single ASP.NET website that is hosted on multiple domains:

*

*website-a.com

*website-b.com
Both websites allow users to login.  We are trying to enable it so that if a user logs into website-a.com, they are automatically logged into website-b.com.  Obviously because of cross-domain security there can't be a single cookie set to serve both domains.
We were thinking of setting up a 3rd domain, auth.company.com, the website will run on that has a couple of simple endpoints:

*

*/authorise will be the endpoint that both website-a and website-b use to authenticate the user

*/client-id will be the endpoint that both websites will use to see if the user is already authenticated

When a user hits website-a.com an AJAX request will be made to auth.company.com/client-id, if the user is authenticated then an identifier will be returned, website-a.com will set a cookie, ideally referencing the same ASP.NET Session as the other websites and refresh the page.
All websites will be running over HTTPS, and I was contemplating encrypting the client-id sent back from the authorisation server, but figured this may not be necessary since if a user has access to this information, they could just spoof the user's ASP.NET session cookie anyway.
The questions I have are: is this safe? is this sane? is there another/better way of doing this?
We ideally want to avoid introducing something as complex as OAuth2 or OpenID as the above mentioned functionality is the extent of what will be required.


text:
Q: HQL: Path expected for join! could not resolve property I cannot find any documentations on how to treat this situation. I keep receiving the following errors:
org.hibernate.QueryException: could not resolve property: id_alumno_origen
of: dm.model.tramite.TrasladoInterno
....
antlr.SemanticException: Path expected for join!

I am using the following query, although I found some solution referring the lack of referencing to the fields in the case of JOIN + ON, I had no luck:
from pe.edu.innovaschools.dm.model.tramite.TrasladoInterno a
    JOIN  gen_sede b ON b.id = a.id_sede_destino
    JOIN  aca_grado c ON a.id_grado_destino = c.id
    WHERE a.tipo = 'INTERPERIODO'
        AND a.estado IN ('ACEP' , 'PEND')
        AND a.id_periodo_origen = :PERIODOORIG
        AND a.id_periodo_destino = :PERIODODEST
GROUP BY a.id_sede_destino , b.nombre , a.id_grado_destino , c.nombre_ps , a.estado

A: On HQL I prefer to use implicit JOIN notation (more times explicit JOIN can  result wrong).
If you use GROUP BY, you must apply a projection to your SELECT, so try this:
select a.id_sede_destino, b.nombre,
    a.id_grado_destino , c.nombre_ps , a.estado
from pe.edu.innovaschools.dm.model.tramite.TrasladoInterno a,
gen_sede b,
aca_grado c
WHERE b.id = a.id_sede_destino
    AND a.tipo = 'INTERPERIODO'
    AND a.id_grado_destino = c.id
    AND a.estado IN ('ACEP' , 'PEND')
    AND a.id_periodo_origen = :PERIODOORIG
    AND a.id_periodo_destino = :PERIODODEST
GROUP BY a.id_sede_destino, b.nombre,
    a.id_grado_destino , c.nombre_ps , a.estado


text:
Q: What is the meaning of @[object1, object2]?
Possible Duplicate:
What kind of object does @[obj1, obj2] create?

Looking at the Master-Detail Template in Xcode, in the App Delegate the SplitViewController's view controllers are set like so:
self.splitViewController.viewControllers = @[masterNavigationController, detailNavigationController];

I don't know what the purpose of the @ sign is before the square brackets. Is this just how NSArrays are made when not using [NSArray arrayWithObjects:]?

A: It's a new syntax feature. It's syntactic sugar for creating an array (NSArray) with the given objects.


text:
Q: angular4 router outlet override I'm using angular4 router. I have a layout page with a navbar and I want to use different navbars when visiting /admin/** and other pages. I set the global empty path with
{
    path: '',
    component: NavbarComponent,
    outlet: 'navbar'
};

and set the admin empty path with
{
    path: 'admin',
    children: [
        {
            path: '',
            component: AdminNavbarComponent,
            outlet: 'navbar'
        },
        ...ADMIN_ROUTES
    ]
}

But accessing admin pages ends up with error

Cannot activate an already activated outlet

I thought maybe the admin empty path would override the global empty path because it matches the url mostly.
And I don't want to specify the outlet using the url like
http://.../admin(navbar:adminnarbar)

because if the user visits front page with http://...(navbar:adminnavbar) would render the admin navbar which is not desired.
In fact, I just want something like overriding a outlet like most template engine does.
Any idea How should I do?
Here is the plunker Please help.


text:
Q: Apple store question about installing new hard drive I plan to make a trip up to the apple store tomorrow. I need them to put in a new hard drive in my Macbook Pro mid-2010 15". Do I need to make an appointment with them? or can I just show up and drop it off with them?
Thanks

A: The generally accepted procedure for any Genius Bar visit is to use the store locator on the Apple site and then use the 'Concierge' web application to book an appointment. While Apple staff (at least in Japan) tend to be rather accommodating for walk-in client issues, having an appointment can ensure your waiting time is minimized. This is especially important at a busier location.


text:
Q: Rails: How to make has_many :through association work with Single Table Inheritance So in my current project I have an Article model that can have different kinds of Transactions. It has one main Transaction, but under certain circumstances it can have multiple sub-transactions.
Until now I set it up like this:
class Article < ActiveRecord::Base
  has_one :transaction, inverse_of: :article
  has_many :partial_transactions, through: :transaction, source_type: 'MultipleFixedPriceTransaction', source: 'PartialFixedPriceTransaction', inverse_of: :articles
end

class Transaction < ActiveRecord::Base
  belongs_to :article, inverse_of: :transaction # Gets inherited to all kinds of Transaction subclasses
end

class MultipleFixedPriceTransaction < Transaction
  has_many :children, class_name: 'PartialFixedPriceTransaction', foreign_key: 'parent_id', inverse_of: :parent
end

class PartialFixedPriceTransaction < Transaction
  belongs_to :parent, class_name: 'MultipleFixedPriceTransaction', inverse_of: :children
  belongs_to :article, inverse_of: :partial_transactions # Overwriting inheritance
end

Now with this set up I sometimes get errors like
ActiveRecord::Reflection::ThroughReflection#foreign_key delegated to
source_reflection.foreign_key, but source_reflection is nil:

#<ActiveRecord::Reflection::ThroughReflection:0x00000009bcc3f8 @macro=:has_many,
@name=:partial_transactions, @options={:through=>:transaction,
:source_type=>"MultipleFixedPriceTransaction",
:source=>"PartialFixedPriceTransaction", :inverse_of=>:articles, :extend=>[]},
@active_record=Article(id: integer ...

By the way, I experimented a lot with the source and source_type parameters and the ones there are just examples. I don't really know what to do with them.
So, how can I make this work? How is the association set up correctly?
Thank you.


text: Q: Stop trying to Download block maps in electron-builder update I'm looking for a way to disable looking for the blockmap file in the update process in Electron-builder. This will never exist for us and we're happy to rely on the full download. So far I cant seem to find any way to do this. but it results in the log being spammed with the fail and a stack trace. If this is not possible is there a way to explicitly declare a URL for the blockmap in the latest.yml rather than it just insert .blockmap in the exe url. As i'm hoping a 404 wont result in the stack trace, as we are getting with the 403. Thanks


text:
Q: Load balancing with iptables in "nth" mode Here is my iptables script, it does not work. Port 9000 is closed, opened ports are 9001-9003. I want to balance loadage between three services located at these ports on localhost. What am I doing wrong?
#!/bin/bash

start()
{
  echo -e "\e[32mStarting firewall ...\e[m"

  iptables -F

  iptables -t nat -A PREROUTING -p tcp --dport 9000 -j DNAT --to-destination 127.0.0.1:9001 -m statistic --mode nth --every 3 --packet 0
  iptables -t nat -A PREROUTING -p tcp --dport 9000 -j DNAT --to-destination 127.0.0.1:9002 -m statistic --mode nth --every 2 --packet 0
  iptables -t nat -A PREROUTING -p tcp --dport 9000 -j DNAT --to-destination 127.0.0.1:9003 -m statistic --mode nth --every 1 --packet 0
}

stop()
{
  echo -e "\e[31mStoping firewall ...\e[m"

  iptables -F
}

case "$1" in
'start')
  start
  ;;
'stop')
  stop
  ;;
'restart')
  stop
  start
  ;;
*)
  echo -e "\e[36mUsage:\e[m {start|stop|restart}"
esac

Thank you.

A: Here is solution:
#!/bin/bash

start()
{
  echo -e "\e[32mStarting firewall ...\e[m"

  iptables -t nat -F

  iptables -t nat -A OUTPUT -p tcp --dport 9000 -m state --state NEW -m statistic --mode nth --every 3 --packet 0 -j DNAT --to-destination :9001
  iptables -t nat -A OUTPUT -p tcp --dport 9000 -m state --state NEW -m statistic --mode nth --every 2 --packet 0 -j DNAT --to-destination :9002
  iptables -t nat -A OUTPUT -p tcp --dport 9000 -m state --state NEW -m statistic --mode nth --every 1 --packet 0 -j DNAT --to-destination :9003
}

stop()
{
  echo -e "\e[31mStoping firewall ...\e[m"

  iptables -t nat -F
}

case "$1" in
'start')
  start
  ;;
'stop')
  stop
  ;;
'restart')
  stop
  start
  ;;
*)
  echo -e "\e[36mUsage:\e[m {start|stop|restart}"
esac

A: This will send one package to 9001, the next to 9002 and so on...
iptables -t nat -A PREROUTING -p tcp --dport 9000 -j DNAT --to-destination 127.0.0.1:9001 -m nth --every 3 --packet 0
iptables -t nat -A PREROUTING -p tcp --dport 9000 -j DNAT --to-destination 127.0.0.1:9002 -m nth --every 3 --packet 1
iptables -t nat -A PREROUTING -p tcp --dport 9000 -j DNAT --to-destination 127.0.0.1:9003 -m nth --every 3 --packet 2

You specified the mode parameter twice, -m and --mode.


text:
Q: Scope ActiveRecord Relation based on record data I a model like this:
class Club < ActiveRecord::Base
  belongs_to :organization
  has_many :career_clubs
  has_many :careers, through: :career_clubs
end

Which appropriately gets careers through the table career_clubs. So far this is only using the club's id field and getting all the records in the career_clubs table with that id.
What I actually want this to do, is use both the id and organization_id, so that it gets all the career_clubs with matching id and organization_id.
I know how to scope things using static data like below, but that doesn't seem to work here.
has_many :career_clubs, -> { where active: true }

A: This should do what you want
has_many :career_clubs, ->(club) {
  where(club_id: club.id, organization_id: club.organization_id)
}


text:
Q: How to make the "@" symbol work in a formula inside of a macro in VBA? I have the below macro:
Sub GenerateTestData()
    Range("F3:F151").Formula = "= $B2 & ""."" & $D2 & "@gmail.come""
End Sub

There is an issues with the @ symbol, and I am not sure how to make it work as a string.

A: To close out this question: You have quotes issues:
"= $B2 & ""."" & $D2 & ""@gmail.com"""


text:
Q: Dynamic file creation in COBOL/JCL I have an requirement, Where I have to read DB2 table and create multiple output file, one for each program name in the table. We don't know how many unique program name in the table. My job will run every 4 hrs. So for eg: my first run may have 10 program name and I will have to create 10 output file and second run may 20 program name and 20 output files.
I'm looking for a dynamic way to create DD name and file name in the JCL as well in my COBOL program. So I don't want to define 20 or max DD statement in my JCL, as this 20 can be 50,60....
Please help me with the possibilities.

A: One option is BPXWDYN, which is callable from COBOL, et. al.  A COBOL example is here.

A: I'm not aware of a canned service that will do what you want.  You can explore how to call a program that would do the dynamic allocation for you.  Here is a starting point in the z/OS documentation.
This example is a 'C' program that will execute a dynamic allocation based on values from the caller.
It's not turnkey but is worth exploring.


text:
Q: R dplyr filter not working right with mildly complex filter dplyr filter not working when I have a list subsetting in the check Value.
Samething works when I assign to to variable. See code below
df1<-data.frame(x=1:26, y=letters, stringsAsFactors = F)
templist<-list(alpha=df1)
res<-df1 %>% filter(y %in% templist$alpha$y)
nrow(res)
[1] 0
tempLetters <- templist$alpha$y
res<-df1 %>% filter(y %in% tempLetters)
nrow(res)
[1] 26

I thought this used to work earlier. Please help. Note that the column names are same in both (y) by design.
I have updated dplyr, tidyr, pipeR to the latest versions on cran just now (4 jan, 2017)

A: @hadleywickham has confirmed that this is a known bug fixed in dev
Pls see his response on twitter at:
https://twitter.com/gunapemmaraju/status/816639470166544384


text:
Q: $filter with custom function in angular How I can create a $filter with custom function  to determining if match ?
This is a json sample with structure:
     $scope.routes =[
    {
        "id": 0,
        "name": "Rosa Barnes",
        "origin": [
            {
                "address": [
                    {
                        "locality": "Madrid",
                        "country": "ES"
                    }
                ]
            }
        ]
    },
    {
        "id": 1,
        "name": "Wright Montoya",
        "origin": [
            {
                "address": [
                    {
                        "locality": "London",
                        "country": "UK"
                    }
                ]
            }
        ]
    },
    {
        "id": 2,
        "name": "Pearson Johns",
        "origin": [
            {
                "address": [
                    {
                        "locality": "London",
                        "country": "UK"
                    }
                ]
            }
        ]
    }
];

I want a $filter that passing one country, match in origin.address.country , is possible?
I proved this code but not works:
       $scope.routesToShow = $filter('filter')($scope.routes, {origin.address.country: "UK"});

Here there are a demo:
http://jsfiddle.net/86U29/43/
Thanks

A: What you need is a custom filter. It also looks like you might need to tweak your data structure too.
Take a look at this:
app.filter('CustomFilter', function () {
    function parseString(propertyString) {
        return propertyString.split(".");
    }

    function getValue(element, propertyArray) {
        var value = element;
        propertyArray.forEach(function (property) {
            value = value[property];
        });
        return value;
    }

    return function (input, propertyString, target) {
        var properties = parseString(propertyString);
        return input.filter(function (item) {
            return getValue(item, properties) == target;
        });
    }
});

You could use this filter, like this:
$scope.routesToShow = $filter('CustomFilter')($scope.routes, 'origin.address.country', 'UK');

Here is an updated jsfiddle (notice the updated data structure): http://jsfiddle.net/moderndegree/86U29/44/
You can find more information on creating custom filters here:
https://docs.angularjs.org/guide/filter#creating-custom-filters

A: Simply.
var filter = function(obj){
   return obj.origin[0].address[0].country === 'UK';
}
$scope.routesToShow = $filter('filter')($scope.routes, filter);


text:
Q: Unable to read csv from S3 presigned url directly in jupyter notebook Hi is there anyway to open csv file from s3 presigned url in a script rather than downloading it from browser! I recieve a presigned s3 url every hour on gmail. I have to download it manually everytime. I decided to automate the process by scraping my emails, have reached the step where I am able to get the fresh presigned link but unable to open the csv file, rather it returns a script. Please help.

A: You can use requests to perform a GET request.
From the AWS page explaining boto3 and presigned URLs:

The user can download the S3 object by entering the presigned URL in a browser. A program or HTML page can download the S3 object by using the presigned URL as part of an HTTP GET request.

The following code demonstrates using the Python requests package to perform a GET request.

import requests    # To install: pip install requests

url = create_presigned_url('BUCKET_NAME', 'OBJECT_NAME')
if url is not None:
    response = requests.get(url)

A: You can read it directly using pandas read_csv. From the docs:

So you can simply:
import pandas as pd
df = pd.read_csv('https://...')


text:
Q: Taking input and working with numbers in MIPS I'm working with Emulator 8085A and I am trying to do an exercise, but I can't find any information or examples of taking input and working with it.
I have to make an assembly program for MIPS processors which reads 50 numbers from keyboard. We call a procedure for each number to check if it can be divided by 5, and if it can be, then we call another procedure to sum all numbers which are NOT divided by 5 and then print the sum.
Any help about this? Thanks in advance!


text:
Q: Wierd structure of many clauses
Rep. Jason Smith, the House's new top tax writer, is promoting an approach he says would favor
working-class Americans over large corporations, a shift in tone from his predecessors
that raises questions about companies' ability to push tax cuts through Congress.

It is from the Wall Street Journal.
I understand the passage as he is promoting an approach (and) he says (that the approach) would favor ...
If so, how can 'and' and 'that the approach' be omitted? If not so, how can I disassemble the passage to simpler parts to correctly understand?
Lastly, is it  a usual expression?

A: I think you are parsing the sentence very slightly incorrectly.  It isn't exactly that he is promoting an approach, and he says the approach would favor working-class Americans; rather, he is promoting an approach that he says would favor working-class Americans.
The entire thing is kind of an example of deleting which is and that - "...an approach that he says would favor...which is a shift in tone..."
References:
https://www.quickanddirtytips.com/articles/when-to-delete-that/
https://english.stackexchange.com/tags/whiz-deletion/info


text:
Q: Detect differences between two video frames displayed in HTML5 canvas I'm displaying a live video stream in a HTML5 canvas which works fine.
Now, what I need to do is to check for any "motion" in the camera which is being displayed in the HTML5 Canvas.
During my research, I found out that this can be done by checking the previous frame with the current frame that's being displayed in the canvas.
So I tried this code within a setInterval function:
  var c = document.querySelector('.mycanv');
  var ctx = c.getContext("2d");

  var imageData = ctx.getImageData(0, 0, 200, 200);
  var data = imageData.data.length;

  console.log(data);

However, when I look in the console, the Number that the variable data outputs is always the same which is 16000! and it wont change even if there is a movemnet infront of the camera.
I'm not entirely sure if I am on a right track.
Could someone please advice on this issue and point me in a right direction please?
Thanks in advance.
Here is a minified and simple example:
https://jsfiddle.net/2648xwgz/
Basically, the code draws a frame of the video in the canvas.
Now, what I need to do is to check if the previous frame/image in the canvas is the same as the current frame/image.

Second EDIT:

Okay, so I've taken all the advice in the comments on board and tried to come up with something that actually doesn't check for all the random pixels in the images as that is heavy and not a good practic...
So, I tried something like this:
https://jsfiddle.net/qpxjcv3a/6/
The above code will run fine in Firefox and with a local Video file. but on JSFIDDLE, you will get a cross origion error.
Anyway, The key point in the code above is using the ctx.globalCompositeOperation = 'difference'; i guess.
And then doing a "scrore" calculation taken from here to detect some changes.
However, when I run my code, I always get: console.log('we have motion'); in the console! Even when the video is paused and there is no more new frames.
So I did console.log(imageScore); and it is always adding up by 10000 even when the video is paused or ended! I'm not sure why that is and whether this calculation is correct at all. But that is where I am at the moment.
Any pointers and help appreciated.

A: As Daniel said you need to check the pixels, the legnth would be the same for all iterations.
You should look into image hashing algorithms. At every interval you can calculate a hash, and store that in a global variable to compare at the next interval. This would also give you the option to set a threshold, so minor changes would not trigger motion detection.
This page explains image hashing in more details: https://jenssegers.com/61/perceptual-image-hashes
You can start by implementing average hash. It is quite simple. You would reduce your canvas size to 8x8 pixels.
ctx.drawImage(video, 0, 0, video.width, video.height, 0, 0, 8, 8);
var imageData = ctx.getImageData(0, 0, 8, 8);
var data = imageData.data;

Then you iterate over the image data and calculate the brightness.
var brightnessdata = []
for(var i = 0; i<data.length; i+=4){
    brightnessdata.push((data[i]+data[i+1]+data[i+2])/3);
}

The rest is simply calculating the average brightness and comparing each pixel brightness to the average brightness to calculate the hash.


text:
Q: Return records that don't have specific key - Rails4 HStore Postgresql query I have a model Task
t.string   "name"
t.hstore   "actions"

Example:
#<Task id: 1, name: "first", actions: {"today"=>"9"},
#<Task id: 2, name: "second", actions: {"yesterday"=>"1"},
#<Task id: 3, name: "third", actions: nil,
#<Task id: 4, name: "four", actions: {"today"=>"11"},

I need to find all records where actions: nil, :today<10 and key :today not present.
It is 1,2,3 task.
Task.where("actions -> 'today' < '10'") - it return only first task.
Task.where("actions -> 'today' < '10' OR actions IS NULL")  - it return 1 and 3 records.

How i can find all records which do not have the key :today in action?

A: From here, according to your question:
Task.where("actions IS NULL OR EXIST(actions, 'today') = FALSE")

and according to your comments:
Task.where("actions -> 'today' < '10' OR actions IS NULL OR EXIST(actions, 'today') = FALSE")


text:
Q: Python Side by side box plots after groupby in Matplotlib Need to do a group by and print 2 boxplots side by side. In the example below I need to plot boxplots for column A by grouping its values by column B.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.DataFrame(np.random.rand(10,1), columns=['A'])
df['B'] = [1, 2, 1, 1, 1, 2, 1, 2, 2, 1]
for n, grp in df.groupby('B'):
   plt.boxplot(x='A',data=grp)

Current output
desired output - Something Like:

A: You could add a position to the call to plt.boxplot() to avoid that the boxplot will be drawn twice at the same position:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.DataFrame(np.random.rand(10, 1), columns=['A'])
df['B'] = [1, 2, 1, 1, 1, 2, 1, 2, 2, 1]
for n, grp in df.groupby('B'):
    plt.boxplot(x='A', data=grp, positions=[n])
plt.xticks([1, 2], ['Label 1', 'Label 2'])
plt.show()

Or you could use seaborn let the grouping. You can replace the numbers in the column to have labels.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

df = pd.DataFrame(np.random.rand(10, 1), columns=['A'])
df['B'] = [1, 2, 1, 1, 1, 2, 1, 2, 2, 1]
df['B'] = df['B'].replace({1: 'Label 1', 2: 'Label 2'})
sns.boxplot(data=df, x='B', y='A' )
plt.show()


text:
Q: Object assignment Lua I have a problem similar to this one: LUA and Corona error: Attempt To Call Method ' ' (A Nil Value) - Driving Me Crazy
I have a TCell class:
local TCell={};
local cell_mt = { __index=TCell };
function TCell.new(_contents_name,_x,_y)
    ...
    local ncell=
    {
        ...
    };
    function ncell:setup()
        ...
    end
    ncell:setup();
    return setmetatable(ncell,cell_mt);
end
return TCell;

I have 2d array of TCell references called cells.
When I assign
cells[ind1][ind2]=cells[ind3][ind4]

cells[ind1][ind2] begins to lose some properties. If I understood the link above correctly it's caused by losing the metatable association. Do I need to use setmetatable another time? How can I do it if the assignment is not done in the TCell body?
upd.
reset_metatable=function(target)
    return setmetatable(target,cell_mt);
end;
cells[ind1][ind2]=cells[ind3][ind4];
cells[ind1][ind2]=cells[ind1][ind2]:reset_metatable();

isn't really helpful. upd2: deleted all code not connected with camera. Camera and TCell have no enterframe. The problem seems to be in metatables. Output gives NOW 6 1 width i 50 and after it  START NOW 6 1 width is nil
-----------------------------------------------------------------------------------------
--
-- Main Cycle
--
-----------------------------------------------------------------------------------------

local storyboard = require( "storyboard" )
local scene = storyboard.newScene()
-- include Corona's "physics" library
local physics = require "physics"
--control_circle=display.newImageRect(C.INTERFACE_DIR..C.INTERFACE_CONTROL_CIRCLE or C.EMPTY_IMAGE,C.CARS_W,C.CARS_W,true);
local events_added=false;

stage_frames=0;
physics.start(); physics.pause()
physics.setGravity( 0,0);

local PCar=require("TCar")
local PBiped=require("TBiped");
local PCell=require("TCell");

local control_circle_len;

local cells={};
local cells_w,cells_h;
local wshift,hshift=-(C.SCREEN_THEORETICAL_W-C.SCREEN_W)/2,-(C.SCREEN_THEORETICAL_H-C.SCREEN_H)/2;

--------------------------------------------

-- forward declarations and other locals

-----------------------------------------------------------------------------------------
-- BEGINNING OF YOUR IMPLEMENTATION
--
-- NOTE: Code outside of listener functions (below) will only be executed once,
--       unless storyboard.removeScene() is called.
--
-----------------------------------------------------------------------------------------
local wsells,hcells=(C.SCREEN_W-C.SCREEN_W%C.LANDSCAPE_CELL_W)/C.LANDSCAPE_CELL_W+1,(C.SCREEN_H-C.SCREEN_H%C.LANDSCAPE_CELL_H)/C.LANDSCAPE_CELL_H+1;

local dfd=false;
local function manage_cells(cmx,cmy)
    --print("#",cmx,cmy);
    if((cmx==0 and cmy==0) or dfd)
    then
        return;
    end
    local cells_shift_w,cells_shift_h=0,0;
    if(cmx>=0)
    then
        for i=cells_w,1,-1
        do
            if(cells[i][1]:out_of_borders_w()==true)
            then
                cells_shift_w=cells_shift_w+1;
            else
                break;
            end
        end
    else
        for i=1,cells_w,1
        do
            if(cells[i][1]:out_of_borders_w()==true)
            then
                cells_shift_w=cells_shift_w-1;
            else
                break;
            end
        end
    end
    if(cmy>=0)
    then
        for i=cells_h,1,-1
        do
            if(cells[1][i]:out_of_borders_h()==true)
            then
                --[[cells[1][i].contents.rotation=45;
                dfd=true;]]
                cells_shift_h=cells_shift_h+1;
            else
                break;
            end
        end
        --return;
    else
        for i=1,cells_h,1
        do
            if(cells[1][i]:out_of_borders_h()==true)
            then
                cells_shift_h=cells_shift_h-1;
            else
                break;
            end
        end
    end
    --print("~",cells_shift_w,cells_shift_h);
    local stx,finx,sty,finy=1,cells_shift_w,1,cells_shift_h;
    if(cmx<0)
    then
        stx=cells_w+cells_shift_w;
        finx=cells_w;
    end
    if(cmy<0)
    then
        sty=cells_h+cells_shift_h;
        finy=cells_h;
    end
    for i=stx,finx,1
    do
        for j=1,cells_h,1
        do
            if(cells[i][j])
            then
                cells[i][j]:destroy();
                cells[i][j]=nil;
            end
        end
    end
    for i=1,cells_w,1
    do
        for j=sty,finy,1
        do
            if(cells[i][j])
            then
                cells[i][j]:destroy();
                cells[i][j]=nil;
            end
        end
    end
    stx,finx,sty,finy=cells_w-cells_shift_w-1,1,cells_h-cells_shift_h-1,1;
    local itx,ity=-1,-1;
    if(cmx>=0)
    then
        stx=cells_shift_w+1;
        finx=cells_w;
        itx=1;
        print(stx,finx);
    end
    if(cmy>=0)
    then
        sty=cells_shift_h+1;
        finy=cells_h;
        ity=1;
    end

    for i=stx,finx,itx
    do
        for j=1,cells_h,1
        do
            if(cells_shift_w~=0)
            then

                if(j==1)
                then
                    print(i,1,"to",i-cells_shift_w,1);
                end
                cells[i-cells_shift_w][j]=cells[i][j];
                cells[i-cells_shift_w][j]=cells[i-cells_shift_w][j].reset_metatable(cells[i][j]);
                print("++",cells[i-cells_shift_w][j].contents.width);
                cells[i][j]:destroy();
                cells[i][j]=nil;
                if(j==1)
                then
                    print(i-cells_shift_w,1,"width is",cells[i-cells_shift_w][1].contents.width);
                    if(i==7)
                    then
                        cells[6][1].debug=true;
                        print("debug is set");
                    end
                end
            end
        end
    end
    for i=1,cells_w,1
    do
        for j=sty,finy,ity
        do
            if(cells_shift_h~=0)
            then
                print("?this?",i,j);
                cells[i][j-cells_shift_h]=cells[i][j];
                cells[i][j]:destroy();
                cells[i][j]=nil;
            end
        end
    end
    for i=1,cells_w,1
    do
        for j=1,cells_h,1
        do
            if(cells[i][j]==nil)
            then
                print("*new",i,j);
                cells[i][j]=PCell.new(C.LANDSCAPE_DICTIONARY(nil,1),(i-1)*C.LANDSCAPE_CELL_W+C.LANDSCAPE_CELL_W/2-wshift-camera:getX(),(j-1)*C.LANDSCAPE_CELL_H+C.LANDSCAPE_CELL_H/2-hshift-camera:getY());
            end
        end
    end

end
local function stage_main_frame()
    print("START NOW",6,1,"width is",cells[6][1].contents.width);
    local old_camera_x,old_camera_y=camera._view.x,camera._view.y;
    if(dfd==false)
    then
        --print("&");
        camera._view.x=camera._view.x-stage_frames;
    end
    local cmx,cmy=-(camera:getX()-old_camera_x),-(camera:getY()-old_camera_y);
    manage_cells(cmx,cmy);

    stage_frames=stage_frames+1;
    print("NOW",6,1,"width is",cells[6][1].contents.width);
    return function(event)
    end

end
-- Called when the scene's view does not exist:
function scene:createScene( event )
    local group = self.view
end

-- Called immediately after scene has moved onscreen:
function control_player(event)
    car1:get_touch(event);
end
function scene:enterScene( event )
    camera:newLayer("land",1);
    camera:newLayer("bipeds",1);
    camera:newLayer("cars",1);

    i=1;
    while((i-1)*C.LANDSCAPE_CELL_W-C.LANDSCAPE_CELL_W/2-wshift<=C.SCREEN_W)
    do
        j=1;
        cells[i]={};
        while((j-1)*C.LANDSCAPE_CELL_H-C.LANDSCAPE_CELL_H/2-hshift<=C.SCREEN_H)
        do
            cells[i][j]=PCell.new(C.LANDSCAPE_DICTIONARY(nil,1),(i-1)*C.LANDSCAPE_CELL_W+C.LANDSCAPE_CELL_W/2-wshift-camera:getX(),(j-1)*C.LANDSCAPE_CELL_H+C.LANDSCAPE_CELL_H/2-hshift-camera:getY());
            j=j+1;
        end
        i=i+1;
    end
    cells_w,cells_h=#cells,#cells[1];
    local group = self.view
    physics.start();
    physics.setPositionIterations( 1 )
    if(events_added==false)
    then
        events_added=true;
        Runtime:addEventListener("touch",control_player);
        Runtime:addEventListener("enterFrame",stage_main_frame);
    end
end

-- Called when scene is about to move offscreen:
function scene:exitScene( event )
    local group = self.view

    physics.stop()

end

-- If scene's view is removed, scene:destroyScene() will be called just prior to:
function scene:destroyScene( event )
    local group = self.view

    package.loaded[physics] = nil
    physics = nil
end

-----------------------------------------------------------------------------------------
-- END OF YOUR IMPLEMENTATION
-----------------------------------------------------------------------------------------

-- "createScene" event is dispatched if scene's view does not exist
scene:addEventListener( "createScene", scene )

-- "enterScene" event is dispatched whenever scene transition has finished
scene:addEventListener( "enterScene", scene )

-- "exitScene" event is dispatched whenever before next scene's transition begins
scene:addEventListener( "exitScene", scene )

-- "destroyScene" event is dispatched before view is unloaded, which can be
-- automatically unloaded in low memory situations, or explicitly via a call to
-- storyboard.purgeScene() or storyboard.removeScene().
scene:addEventListener( "destroyScene", scene )

-----------------------------------------------------------------------------------------

return scene

.
local TCell={};
local cell_mt = { __index=TCell };
function TCell.new(_contents_name,_x,_y)
    --print(camera.x);
    if(_x==nil)
    then
        _x=0;
    end
    if(_y==nil)
    then
        _y=0;
    end
    camera:newLayer( "abacaba", 1 );
    local ncell=
    {
        contents_name=_contents_name;
        contents;
        sequence_data;
        sheet_data;

        debug=false;
        --[[main_frame;
        main_frame_handler=function(self)
            main_frame=function(event)
                if(self.contents.x+self.contents.width/2<0 or self.contents.y+self.contents.height/2<0 or self.contents.x-self.contents.width/2>C.SCREEN_W or self.contents.y-self.contents.height/2>C.SCREEN_H)
                then
                    --self:destroy();
                end
            end
            return main_frame;
        end;]]
        clear=function(self)
            if(self.debug==true)
            then
                print("CLEAR!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n\n\n\n");
            end
            --print(self.contents);
            self.contents:removeSelf();
            camera:removeObject("land",self.contents);
        end;
        show=function(self,_contents_name,__x,__y)
            if(self.debug==true)
            then
                print("SHOW!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n\n\n\n");
            end
            self.contents_name=_contents_name;
            if(self.contents_name~=C.EMPTY_IMAGE)
            then
                self:set_sequence_data();
            end
            if(self.contents_name~=C.EMPTY_IMAGE)
            then
                self.sheet_data=graphics.newImageSheet(self.contents_name,C.LANDSCAPE_SHEET_DATA);
                self.contents=display.newSprite(self.sheet_data,self.sequence_data);
            else
                self.contents=display.newImageRect(C.EMPTY_IMAGE,C.LANDSCAPE_CELL_W,C.LANDSCAPE_CELL_H,true);
                self.sequence_data=nil;
            end
            self.contents.x=__x;
            self.contents.y=__y;
            camera:addObject("land",self.contents);
        end;
        out_of_borders_w=function(self)
            --print(self.contents.width);
            return self.contents.x+self.contents.width/2-camera:getX()<C.LANDSCAPE_CELLS_LEFT_BORDER-C.LANDSCAPE_CELL_W or
                self.contents.x-self.contents.width/2-camera:getX()>C.LANDSCAPE_CELLS_RIGHT_BORDER+C.LANDSCAPE_CELL_W;
        end;
        out_of_borders_h=function(self)
            return self.contents.y+self.contents.height/2-camera:getY()<C.LANDSCAPE_CELLS_UPPER_BORDER-C.LANDSCAPE_CELL_H or
                self.contents.y-self.contents.height/2-camera:getY()>C.LANDSCAPE_CELLS_LOWER_BORDER+C.LANDSCAPE_CELL_H;
        end;
        reset_metatable=function(target)
            return setmetatable(target,cell_mt);
        end;
        set_sequence_data=function(self)
            local px=math.floor(((_x)%C.LANDSCAPE_SHEET_DATA.sheetContentWidth)/C.LANDSCAPE_SHEET_DATA.width)+1;
            local py=math.floor(((_y)%C.LANDSCAPE_SHEET_DATA.sheetContentHeight)/C.LANDSCAPE_SHEET_DATA.height)+1;
            self.sequence_data=
            {
                { name = "only", start=C.LANDSCAPE_SHEET_DATA.sheetContentWidth/C.LANDSCAPE_SHEET_DATA.width*(py-1)+px, count=1 }
            };
        end;

        destroy=function(self)
            --Runtime:removeEventListener("enterFrame",self.main_frame);
            --Runtime:removeEventListener("enterFrame",self.main_frame_handler);

            self:clear();
            if(index~=nil)
            then
                --destroy_cell(index);
            end
        end
    };
    function ncell:setup()
        self:show(self.contents_name,_x,_y);
    end
    ncell:setup();
    return setmetatable(ncell,cell_mt);
end
return TCell;

A: I believe you may misunderstanding variable assignment in Lua. All variables are actually references/pointers to objects. When you write:
cells[ind1][ind2]=cells[ind3][ind4]

you are throwing away (removing a reference to) the object that was pointed to by cells[ind1][ind2], and you create a second reference to the object pointed to by cells[ind3][ind4].
If you put some stuff (like the properties you think are disappearing) in cells[ind1][ind2] before the assignment, it won't be there after the assignment because that variable is now pointing at a different object.


text:
Q: .NET stack memory limit I am using C#, .NET 4.0, 64-bit. I need to store in memory 500 million "data points" that are used in computations. I need to decide whether to create these as struct or class objects. Structs seem so much faster.
Is there a memory limit for the stack? If so, how can it be adjusted.
Will storing so much data on a stack affect the overall performance of the system?
(By the way, I am aware of the single-object size limitation in .NET, so that's being addressed -- the data will be stored in multiple collections).

A: You're asking the wrong question. If stack size matters, you're doing something wrong.
If you use many datapoints, you'll put them in a collection, such as an array. Arrays are always allocated on then heap. An array of structs embeds the individual structs and forms a continuous memory block. (If you have more than 2GB, you need several arrays).
Whereas with reference types, the array will only contain the references, and the objects get allocated individually on the heap. A heap allocation has about 16 bytes of overhead, the reference in the array accounts for another 8.
You'll also get worse cache locality due to the indirections, and the GC has to do more work, to crawl all those references.
My conclusion is that if you have many small datapoints, make them a struct, and put them in an array.

A: You are going to store your data in arrays and arrays are always stored on the heap. So it doesn't matter whether or not you use structs or classes to hold those arrays. You may well want to make sure that your data points are value types (i.e. structs) so that arrays of data points can be allocated efficiently in contiguous blocks of memory.
Performance differences between heap and stack allocated memory are most likely to be seen with small objects that are allocated and deallocated in a short space of time. For long-lived objects of the size you describe, I would expect there to be no difference in performance between stack and heap allocated memory.

A: You could use classes for your data points. In this case, the memory will be allocated on the heap.
But considering that you are talking about 500 million data points, and especially since you are programming in the .NET world with a more restricted memory limit for apps, I would strongly encourage using some kind of embedded database, like sqlite, for example. In this way, you would avoid having all of your data points in memory simultaneously, but only the ones you need for computation now.

A: It's surprising that no one seemed to try to answer the actual question.
I absolutely understand that this is the wrong question to ask 99.9% of the time, but it would still be interesting to know the results (at least I was curious).
The test program
It is really simple using unsafe code and the stackalloc keyword.
class Program
{
    static void Main(string[] args)
    {
        for (int i = 100; i < Int32.MaxValue; i+=10)
        {
            StackCheck(i);
            Console.WriteLine($"Successfully allocated {i} bytes on the stack");
        }
    }

    public static unsafe void StackCheck(int size)
    {
        byte* array = stackalloc byte[size];
    }
}

Results
Mind that this is 100% implementation detail and may differ by CLR, CLR version, operating system or individual machine. In my experiment both the full .NET Framework 4.7.2 and .NET Core 2.1.4 crashed just above the 1MB mark. Interestingly it is not even consistent between runs, the results fluctuate by a few hundred bytes.
Adjusting the stack limit
You cannot change the stack size on an existing thread, but you can set it on new ones:
Thread testThread = new Thread(() =>
{
    for (int i = 1000; i < Int32.MaxValue; i+=1000)
    {
        StackCheck(i);
        Console.WriteLine($"Successfully allocated {i} bytes on the stack");
    }
}, 200_000_000);
testThread.Start();
testThread.Join();

Obviously the whole stack is allocated when you create the thread, if you set it too large, the Thread constructor will throw an OutOfMemoryException.
But again, this test was done to mainly to satisfy my own curiosity, as others stated don't do this unless you really really know what you're doing.


text:
Q: How to create vm with libvirt-go package - get boot error I would like to create a new centos 7 vm with kickstart option over the golang library libvirt-go.
To create the new vm I need a XML-Config which I generate over the libvirt-go-xml package.
Here is my function to generate a domain struct which I parse later into a XML-Dom.
func defineDomain(domainName string, vcpu *libvirtxml.DomainVCPU, disks []libvirtxml.DomainDisk, interfaces []libvirtxml.DomainInterface, memory *libvirtxml.DomainMemory) *libvirtxml.Domain {
  domainId := 10

  domain := &libvirtxml.Domain{
    XMLName: xml.Name{
      Space: "Hello",
      Local: "World",
    },
    Type:        "kvm",
    ID:          &domainId,
    Name:        domainName,
    UUID:        uuid.Must(uuid.NewV4()).String(),
    Title:       domainName,
    Description: domainName,
    Metadata: &libvirtxml.DomainMetadata{
      XML: "",
    },
    Memory: memory,
    VCPU:   vcpu,
    OS: &libvirtxml.DomainOS{
      BootDevices: []libvirtxml.DomainBootDevice{
        libvirtxml.DomainBootDevice{
          Dev: "hd",
        },
      },
      Kernel:  "",
      Initrd:  "/home/markus/workspace/worker-management/centos/kvm-centos.ks",
      Cmdline: "ks=file:/home/markus/workspace/worker-management/centos/kvm-centos.ks method=http://repo02.agfa.be/CentOS/7/os/x86_64/",
      Type: &libvirtxml.DomainOSType{
        Arch: "x86_64",
        Type: "hvm",
      },
    },
    OnCrash:    "restart",
    OnPoweroff: "destroy",
    OnReboot:   "restart",
    Devices: &libvirtxml.DomainDeviceList{
      Emulator:   "/usr/bin/kvm-spice",
      Disks:      disks,
      Interfaces: interfaces,
      Graphics: []libvirtxml.DomainGraphic{
        libvirtxml.DomainGraphic{
          VNC: &libvirtxml.DomainGraphicVNC{
            AutoPort: "yes",
            Listen:   "127.0.0.1",
            Keymap:   "de",
            Listeners: []libvirtxml.DomainGraphicListener{
              libvirtxml.DomainGraphicListener{
                Address: &libvirtxml.DomainGraphicListenerAddress{
                  Address: "127.0.0.1",
                },
              },
            },
          },
        },
      },
    },
  }

  return domain

}

When I want to create the new vm with my XML-Dom, I get the following error.
2018/09/25 08:12:45 virError(Code=1, Domain=10, Message='internal error: process exited while connecting to monitor: 2018-09-25T06:12:45.683418Z qemu-system-x86_64: -append only allowed with -kernel option')
I defined an empty string as Kernel option, because I don't know what to show off.

*

*What exactly do I need to specify under kernel option for my VM to boot properly and

*where can I find good documentation about setting the kernel option?

A: You've provided a wrong Initrd:
      Initrd:  "/home/markus/workspace/worker-management/centos/kvm-centos.ks",

This is not an initrd, but your kickstart file (which you correctly specified in Cmdline.
Specifying Kernel and Initrd is not recommended. This is intended for booting a VM from a kernel which is outside the VM instance itself. In almost all circumstances, you do not want this.
Instead, this should also be the empty string, the same as Kernel. The VM will then boot from the virtual boot media (hard drive, ISO image, etc.) that you will provide.


text:
Q: Dividing up a map into polygon regions based on a list of single point coordinates I'm trying to divide up a city map into polygon regions based on a list of single point coordinates.
The idea is that a polygon region would extend outwards from a single point in all directions until it bordered with polygon regions extending out from  nearby / adjacent points.   I don't want to use a fixed radius because I want the end result to be complete coverage of the map.  So the regions will be irregularly shapes and sized, extending their "territory" as far as possible before bumping up against other territories or the map boundary.
Does anyone know of an algorithm, library or program that can generate such a list of polygons given a list of single point coordinates and a map boundary?

A: Perhaps you want delaunay-triangulation or a voronoi diagram.
Example page from JSTS

*

*delaunay triangulation

*voronoi diagram


text:
Q: Using onClientClick and onClick together with form submission So I'm having some trouble. Even after trying many different solutions my problem is still persistent.
The button click will fire the java script code, but not the server side code.
<asp:Button ID="btnSubmit" runat="server" CssClass="ins_sub_btn_form_map" OnClientClick="javascript: stripeSubmit(); return true;" onClick="btnSubmit_Click"
                                        UseSubmitBehavior="false" ValidationGroup="Submit" Text="Submit" />

here's my javascript:
function stripeResponseHandler(status, response) {
            if (response.error) {
                // show the errors on the form
                $(".payment-errors").html(response.error.message);
            } else {
                var form$ = $("#form1");
                // token contains id, last4, and card type
                var token = response['id'];
                // insert the token into the form so it gets submitted to the server
                form$.append("<input type='visible' id='stripeToken' name='stripeToken' value='" + token + "' />");
                // and submit
                form$.get(0).submit();
            }
        }

        function stripeSubmit() {
            Stripe.setPublishableKey($("input#txtStripePK").val());
            var expDate = $("input#txtExpirationDate").val();
            if (Stripe.card.validateCardNumber($("input#txtCreditCardNumber").val()) == false)
            {
                alert("Credit Card Number Error");
                return;
            }
            if (Stripe.card.validateCVC($("input#txtCVVNumber").val()) == false) {
                alert("CVN Number Error");
                return;
            }
            if (Stripe.card.validateExpiry((expDate.slice(0, 2)) , ("20" + expDate.slice(2, 4))) == false) {
                alert("Expiration Date Error");
                return;
            }
                // createToken returns immediately - the supplied callback submits the form if there are no errors
                Stripe.card.createToken({
                    number: $("input#txtCreditCardNumber").val(),
                    cvc: $("input#txtCVVNumber").val(),
                    exp_month: (expDate.slice(0, 2)),
                    exp_year: ("20" + expDate.slice(2, 4))
                }, stripeResponseHandler);
                //return true; // submit from callback
            }

I've tried it without the return true in javascript, with it in javascript. Also tried it without the return true in the onClientClick, also without the "javascript:". Literally everything I can think of.
Any help is appreciated. Thanks in advance.

A: If I'm not mistaken, by default, asp control's UseSubmitBehavior property is set to true. This means any event performed on that control will cause a postback. You have UseSubmitBehavior set to false so the code behind will never get executed since no postback occurs. When using OnClientClick() and OnClick() together, the client side code will execute first and then the server side code. Hope this helps

A: Use closing () on the method inside your Onclick. ex onClick="SomeMethod()"


text:
Q: ¿Cómo poner un TextView a la derecha de un ImageView, dentro de un LinearLayout? Cómo podría alinear en la parte del primer layout, donde dice "Cambiar Clave"  para que quede a la derecha del imageview (la imagen de la llave)
Aquí dejó mi código:
  <LinearLayout
        android:orientation="vertical"
        android:minWidth="25px"
        android:minHeight="25px"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#6094bc"
        android:layout_marginTop="25px"
        android:layout_marginRight="15px"
        android:layout_marginLeft="15px"
        android:id="@+id/linearLayout1">
        <ImageView
            android:src="@drawable/key"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingLeft="2px"
            android:padding="2px"
            android:paddingTop="2px"
            android:id="@+id/imageView1" />
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="#D3D3D3"
            android:textSize="40px"
            android:id="@+id/lblCam"
            android:text="Cambiar Clave:" />
</LinearLayout>

A: Es tan sencillo como cambiar el valor de la propiedad android:orientation="vertical" a horizontal.
<LinearLayout
    <!-- solo cambie el valor de vertical a horizontal-->
    android:orientation="horizontal"
    android:minWidth="25px"
    android:minHeight="25px"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#6094bc"
    android:layout_marginTop="25px"
    android:layout_marginRight="15px"
    android:layout_marginLeft="15px"
    android:id="@+id/linearLayout1">

    ...

</LinearLayout>


text:
Q: Unable to run poetry install on Windows 10 due to wrapt 1.14.1 installation error I have Python 3.10.2 installed on my Windows 10 system and Poetry 1.1.14
When I run poetry install, I get the below error
ERROR: wrapt-1.14.1-cp310-cp310-win_amd64.whl is not a supported wheel on this platform.
Below is the system information on running poetry env info
System
Platform: win32
OS:       nt
I have even installed wrapt 1.14.1 manually on my system but despite this poetry install fails with same issue.
Any help is appreciated.


text:
Q: Compiz animations jittery with an ATI Radeon HD 6520G
Possible Duplicate:
Performance being really choppy with ATI drivers

I have Ubuntu 11.10 64bit installed on a machine with an AMD A6-3400M CPU, and a Radeon HD 6520G card. For some reason all compiz animations are very jittery and unpleasant to look at.
I have the ATI FGLRX driver installed but when I try to install the version with post-release updates from jockey it says installation failed.
I have tried downloading compiz config, and setting the refresh rate to 60hz (from 50hz, I read online that this helps) but it always changes back to 50, even after I check off not to detect the refresh rate.
If need be, I can post the jockey log.
Perhaps the issue is with 64 bit ubuntu, but if I install 32 bit, will it be able to address all 6GB of my ram? I know windows 32 bit can't.
Thanks in advance.


text:
Q: How to bind IP:port in AWS ECS I'm not able to bind a IP:port to container port in AWS ECS task definition. Such that on command line,
docker run "-p 172.17.42.1:14242:3000"

172.17.42.1:14242 is IP:port. But in AWS ECS there are only two options, hostPort and containerPort and they take only integers not strings:
"portMappings": [
   {
      "hostPort": 14242,
      "containerPort": 3000
  }
]

So, how can I provide IP:port in task definition?
When I do (Without IP) port:port mapping, and after task creation I do:
aws ecs describe-tasks

it shows

0.0.0.0:14242:3000.

But I want specific IP not 0.0.0.0.

A: This is not a supported feature as far as I'm aware, and it wouldn't make too much sense on ECS since the ip address of the host instance isn't known ahead of time.
ECS is designed to use all available EC2 instances in a "cluster" to deploy containers belonging to to a service/task.  One of ECS's core features is the flexibility to add/remove/update EC2 instances in the  cluster in an ad-hoc manner, and allow containers to be deployed on whichever cluster instances has available resources at the particular time when the task is launched.  This means there's no guarantee that you'll know the IP address ahead of time when you create the task definition, since you won't know for sure which EC2 instance it will be deployed on.
If you really have a strong use case where you must deploy a task/container on a specific EC2 instance and IP, then you could roll your own solution by interacting directly with the ECS agent. [1][2]
That said, I'd highly recommend re-examining your design and trying to implement it in a way that's host/ip agnostic.  For example, you could use Elastic Load Balancer (ELB) in the ECS "service" definition [3] to allow the containers to be reached through a fixed DNS hostname regardless of which IP they're hosted on.
[1] http://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_agent.html
[2] https://github.com/aws/amazon-ecs-agent
[3] http://docs.aws.amazon.com/AmazonECS/latest/developerguide/service-load-balancing.html


text:
Q: Sorted list printing out key and value How can I print out the key and the value of an item from a sorted list using bool contains? I only want to print out that one which has the key in match. Thanks in advance!
As you asked I declared the sorted list I have a class in it and an artist for key which is from a textboxt of a gui.
Let us say that
   string artsearch = something;
   bool contains = list.ContainsKet(artsearch);
   SortedList<string, Artist> list = new SortedList<string, Artist>();
    Artist a = new Artist(artist, members, albm1);
        a.Name = artist;
        a.Members = members;
        list.Add(artist, a);

   public class Artist : IComparable
{
    public string name;
    public string members;
    public string album;
    public Guid artistID;
    public LinkListGen<string> albums;

    public Artist()
    {
        artistID = new Guid();
    }

    public Artist(string name, string members, LinkListGen<string> albums)
    {
        this.name = name;
        this.members = members;
    }

    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    public string Albums
    {
        get { return album; }
        set { album = value; }
    }

    public string Members
    {
        get { return members; }
        set { members = value; }
    }

    public int CompareTo(object obj)
    {
        if (obj is Artist)
        {
            Artist other = (Artist)obj;
            return name.CompareTo(other.name);
        }
        if (obj is string)
        {
            string other = (string)obj;
            return members.CompareTo(other);
        }
        else
        {
            return -999;
        }
    }

}

A: You can get the value using the indexer:
if(contains)
{
   Console.WriteLine("{0} -> {1}", artsearch, list[artsearch]);
}

You can combine these using TryGetValue:
Artist value;
if(list.TryGetValue(artsearch, out value))
{
    Console.WriteLine("{0} -> {1}", artsearch, value);
}

Note this works on any class which implements IDictionary<TKey, TValue>, not just SortedList<TKey, TValue>.


text:
Q: netbeans icon ok in designer but fails when run (maven) So I followed the netbeans (I'm using 12.2) tutorial for handling images:
https://netbeans.org/kb/73/java/gui-image-display.html?print=yes
I can see the icon in the designer but when run getResource() returns a null indicating it can't find the resource.
I have found this question which seemed to be related:
Netbeans ImageIcon not displaying
I have ensured that I am using a package and not a folder.
The error generated :
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at java.desktop/javax.swing.ImageIcon.<init>(ImageIcon.java:217)
    at com.byotrader.zom.ZomFrame.initComponents(ZomFrame.java:37)

The line of code:
   jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/byotrader/zom/resources/ZomIcon.gif"))); // NOI18N

I have no idea why this is failing when run.
So my introduction to netbeans isn't going as smoothly as I hoped!
As requested project screen shot:
https://photos.app.goo.gl/CJ4EB3PD4a86nAVK8
Any ideas what I have failed to do?
One suggested answer relating to the following question :
netbeans & java, resourceMap.getString returning null
However the answer clearly states this is only a problem if a Clean build has not been done.  That is not my issue as I have tried a clean build!
However looking in the .jar file I can see the picture resources have not been added! I assume this is the problem.  However I have no idea how I can force the IDE to do its job!
Link to files structure:
https://photos.app.goo.gl/bRxHHW2UtRjPF7LeA
This link may also help others in future:
Netbeans Maven Project - Other Sources does not appear

A: (It is a Maven-Project!*) Put your image under:
src/main/resources/com/byotrader/zom/resources/ZomIcon.gif
../resources/...
Explanation:
Netbeans (when on a maven project) completely (except maybe in designer mode!;) builds with maven! ...which means... no gif (etc.) files are considered form src/main/java ... (check your target/classes folder!)
After my fix proposal, the image should be in the desired location.

* The tutorial(, which explicitly tells "Java Project") is little outdated for Netbeans 12.2, where there is no "Java Project"... possible alternatives are (maven/gradle) "Java Frontend Project" (requires javaFX!) or the "good ole" (ant) "Samples>Java With Ant".


text:
Q: How to rearrange the letter in string in alphabetical order in SQL How to rearrange the letter in string in alphabetical order  in SQL
For example
cbaz to abcz

A: You can split the string up into characters and then aggregate:
WITH characters ( rid, value, ch, i, l ) AS (
  SELECT ROWID,
         value,
         SUBSTR(value, 1, 1),
         1,
         LENGTH(value)
  FROM   table_name
UNION ALL
  SELECT rid,
         value,
         SUBSTR(value, i + 1, 1),
         i + 1,
         l
  FROM   characters
  WHERE  i < l
)
SELECT MAX( value ) AS original,
       LISTAGG(ch) WITHIN GROUP ( ORDER BY ch ) AS ordered
FROM   characters
GROUP BY rid

or:
SELECT value As original,
       ordered
FROM   table_name t
       CROSS APPLY (
         SELECT LISTAGG(SUBSTR(t.value, LEVEL, 1))
                  WITHIN GROUP (ORDER BY SUBSTR(t.value, LEVEL, 1)) AS ordered
         FROM   DUAL
         CONNECT BY LEVEL <= LENGTH(t.value)
       )

Which, for the sample data:
CREATE TABLE table_name ( value ) AS
SELECT 'cbaz' FROM DUAL UNION ALL
SELECT 'zyx' FROM DUAL UNION ALL
SELECT 'zyx' FROM DUAL;

Outputs:

ORIGINAL
ORDERED

cbaz
abcz

zyx
xyz

zyx
xyz

db<>fiddle here

A: Just for fun, you could do this programmatically:
with function sort_letters
         ( p_str varchar2 )
         return varchar2
     as
         type charList is table of simple_integer index by varchar2(1);
         letters charList;
         letter varchar2(1);
         sorted_letters long;
     begin
         if p_str is not null then
             for i in 1..length(p_str) loop
                 letter := substr(p_str,i,1);

                 letters(letter) :=
                     case
                         when letters.exists(letter) then letters(letter) +1
                         else 1
                     end;
             end loop;

             letter := letters.first;

             loop
                 sorted_letters := sorted_letters || rpad(letter, letters(letter), letter);
                 letter := letters.next(letter);
                 exit when letter is null;
             end loop;
         end if;

         return sorted_letters;
     end;
select sort_letters('abracadabra')
from   dual
/

SORT_LETTERS('ABRACADABRA')
---------------------------
aaaaabbcdrr


text:
Q: Nativescript Camera Plus photoCapturedEvent not called and image not saving to library nativescript+vue I am trying to implement the nativescript-camera-plus plugin to take an image. I am developing an IOS (for iPad) application with NativeScript + vue and am using an emulator to test.
For some reason the photoCapturedEvent event is not been triggered when the takePicture() is called. Furthermore, when { saveToGallery: true } is been passed through this method, the image is not saved to the photo gallery.
The loaded event works and runs as the component is loaded. I am unsure if the errorEvent event gets triggered.
Here is a snippet of my code (in TakePhoto.vue):
<CameraPlus ref="CameraPlus" height="600" id="camPlus"
                saveToGallery="true"
                showCaptureIcon="true"
                showGalleryIcon="false"
                showToggleIcon="false"
                showFlashIcon="false"
                debug="true"
                enableVideo="false"
                confirmVideo="false"
                defaultCamera="front"
                @loaded="onCameraLoaded"
                @photoCapturedEvent="photoCaptured($event)"
                @errorEvent="onCameraError">
</CameraPlus>

And here is the associated methods
onCameraLoaded(result) {
    this.cam = result.object;
    console.log("Camera loaded...");
},

onButtonCapture() {
    console.log('Take Picture');
    this.image = this.cam.takePicture({ saveToGallery: true });
},

photoCaptured(args){
    console.log("ARGS - ", args)
},

I would also like to mention that I have registered the component in the app.js file like so: Vue.registerElement('CameraPlus', () => require('@nstudio/nativescript-camera-plus').CameraPlus);
Any help would be appreciated.


text:
Q: Кнопка на регистрацию и вход в wordpress без виджета и плагина, какие варианты? столкнулся с такой проблемой: нужно поставить кнопки на вход и регистрацию. Если использовать виджет мета , то войдя кнопка регистрации меняется на кнопку управление сайтам , даже если ты не админ. Если есть вариант как это исправить , пожалуйста подскажите. среди плагинов ничего нормального тоже не нашел. Как можно сделать ссылки на вход и регистрацию? Может совет есть или решение готовое? Спасибо

A: можно вывести ссылки вот так, добавив этот код в нужное вам место в шаблоне
if ( ! is_user_logged_in() ) {
    echo '' . __( 'Login' ) . '';
}

if ( ! is_user_logged_in() && get_option( 'users_can_register' ) ) {
    echo '' . __( 'Register' ) . '';
}


text:
Q: jQuery fetching incorrect data In my todo app project here, I am having a problem.
Reproducing the problem:  Add an unstarred item eg: x, now if you star/unstar this item, it will be updated in the localStorage. Now, edit this item to, eg: xxx, and now if you star/unstar this item, it does not update the localStorage. The reason is, the item text read is xxxxxx and NOT xxx. I checked it in console.log().
Why is this happening? What am I doing wrong here?
jsFiddle
Code:
function toggleStar(element, pushToUndoStack){
    console.log($(element).parent().find('p').text());
    // fetch this starred item content to locate it in the localStorage
    var starred_item = $(element).parent().find('p').text();

    // fetch current items from localStorage
    var todo_items = getLocalStorageData();

    // parse to locate 'that' item
    $.each(todo_items,function(index,item){
        //console.log(item[0]);
        if(starred_item.toLowerCase() === item[0].toLowerCase()){
            //console.log("found -> " + item[0]);
            // toggle starred true/false
            item[1] = !item[1];
            //console.log(item[1]);
            // cut the loop
            return false;
        }
    });

    // update localStorage
    localStorage.setItem('todo_items', JSON.stringify(todo_items));

    if(pushToUndoStack){
        // update undo stack
        todo_item.undoStack.push(['toggleStar',$(element).parent().find('button').text(),$(element).parent().find('.star').prop('checked')]);
        $("#undo").removeAttr('disabled');
        //console.log(todo_item.undoStack);
    }
}

A: In your JS code you have function editItem(element, pushToUndoStack) with the code:
// replace textarea with the new text
$(element).find('textarea').replaceWith("
"+edited_text+"
");

Each time you edit your task you duplicate

.
Change it with
// replace textarea with the new text
$(element).find('textarea').replaceWith(edited_text);

http://jsfiddle.net/G288G/1/


text:
Q: How to implement animations using react router 4 I'm rusing React Router v4 and I have some difficulties implementing transitions between pages.
I'm using the package react-addons-css-transition-group using transitions for showing the animations as the official React Router examples.
Here's my router:
<BrowserRouter>
  <Route render={
    ({ location }) => (
      <ReactCSSTransitionGroup
        transitionEnterTimeout={300}
        transitionLeaveTimeout={300}
        transitionName="fade"
      >
        <Route
          component={LoginView}
          exact
          key="l"
          location={location}
          path="/"
        />

        <Route
          component={UnderConstructionView}
          exact
          key="uc"
          location={location}
          path="/under-construction"
        />
      </ReactCSSTransitionGroup>
    )
  }
  />
</BrowserRouter>

Now, On the UnderConstructionView I have a simple link <Link to="/">home page</Link> that takes my tot he LoginView, but no animation is showed.
Anyone who can provide some advice why it's not working.
I must be missing something but I don't see it.
Kind regards,

A: You should try wrapping the Route Components with a Switch
<BrowserRouter>
  <Route render={
    ({ location }) => (
      <ReactCSSTransitionGroup
        transitionEnterTimeout={300}
        transitionLeaveTimeout={300}
        transitionName="fade">
          <Switch key={location.key}>
            <Route
              component={LoginView}
              exact
              key="l"
              location={location}
              path="/" />

            <Route
              component={UnderConstructionView}
              exact
              key="uc"
              location={location}
              path="/under-construction" />
          </Switch>
      </ReactCSSTransitionGroup>
    )
  }
  />
</BrowserRouter>


text:
Q: Disable browser's autocomplete credentials in input type password in ZKoss I would ask you a question...
I want to disable browser's autocomplete credentials in input type password in ZKoss.
My ZK version is 6.5
Here is my zul code
<grid width="344px">
    <rows>
      <row>
        <label value="Username" />
        <textbox id="username" name="j_username" focus="true" hflex="true" />
      </row>
      <row>
        <label value="Password" />
        <textbox id="password" type="password" name="j_password" hflex="true" />
      </row>
    </rows>
</grid>

Do you have any ideas? solutions?
Thank you!

A: Try this
<zk xmlns:ca="client/attribute">
    <grid>
        <!-- removed for brevity -->
        <textbox ca:autocomplete="off" />
    </grid>
</zk>


text:
Q: What wrong with this SQL Query I need to find what bad with this SQL:
SELECT DepartmentName, COUNT(*)
FROM employee,department
WHERE employee.DepartmentID = department.DepartmentID
GROUP BY DepartmentName
WHERE COUNT(*)>1

I think the problem in COUNT(*) beacause it return the count of all rows. So how I think the property sql will be without where statement. Help me I not good in SQL.

A: You have to use having cluase instead of where at the end of the statement:
SELECT DepartmentName, COUNT(*)
FROM employee,department
WHERE employee.DepartmentID = department.DepartmentID
GROUP BY DepartmentName
having COUNT(*)>1

A: SELECT DepartmentName, COUNT(*) AS count
FROM employee,department
WHERE employee.DepartmentID = department.DepartmentID
GROUP BY DepartmentName
HAVING count>1;


text:
Q: Initial Value Problem into Euler and Runge-Kutta scheme Having a bit of difficulty with this question:
Convert the initial value problem,
$$\frac{d^2y}{dx^2}-\frac{dy}{dx}+2y=x+1$$ where $$y(0)=2,\ \frac{dy}{dx}(0)=-1,$$
into a set of two coupled first-order initial value problems.
Firstly I let $$\frac{dy}{dx}=z$$ giving me the equation:
$$\frac{dz}{dx}=z-2y+x+1$$ where $$y(0)=2,\ z(0)=-1,\ x(0)=0$$
Use a step length h = 0.1 to find numerical approximations to y at x = 0.2
using generalizations to two coupled equations of the following numerical
schemes:

*

*Trapezoidal method using the explicit Euler method as a predictor and one iteration of the corrector.

for this method I'm really confused and don't know where to start so any help would be great.

*the third-order Runge-Kutta scheme:
$$k_1 = hf (x_n, y_n)\\
k_2=hf(x_n+\frac{h}{2},y_n+\frac{k_1}{2})\\
k_3=hf(x_n+h,y_n-k_1+2k_2)\\
y_{n+1}=y_n+\frac{1}{6}(k_1+4k_2+k_3)
$$

for this method I'm a little confused I don't know where to start because of the 3 different variables z,y,x I tried starting by doing $$k_1=hz_0$$ and then $$l_1=hf(x_0,y_0)$$ but I found it difficult because of the 3 variables, any help is appreciated thanks.

A: *

*Trapezoidal method with Euler as predictor  and one corrector step can be implemented as a 3-stage Runge-Kutta method for the vector $u=(y,z)$
\begin{align}
k_1 &= hf(x,u)\\
k_2 &= hf(x+h,u+k_1)\\
k_3 &= hf(x+h,u+0.5(k_1+k_2))\\
u_+ &= u+0.5(k_1+k_3)
\end{align}
I assume that the involved description is to distinguish the method from the explicit trapezoidal method and to compare the 2nd order 3-stage method to the 3rd order 3 stage method of the second point.

*Yes, depending on notation you can expand the scalar method to the vector method that way.
\begin{align}
k_{1y} &= hz \\
k_{1z} &= hf(x,y,z) \\
k_{2y} &= h(z+0.5k_{1z}) \\
k_{2z} &= hf(x+0.5h, y+0.5k_{1y}, z+0.5k_{1z})
\end{align}
etc.
There are only 2 components to this differential equation, the independent variable $x$ has explicitly available updates.


text:
Q: Passing javascript object to flex I have a very strange issue.
My web application pass a javascript object to flex application using addCallback function.
when the flex application is in modal dialog in safari browser, the object in the flex application is null and when i open the flex application just in a new window, the object is passed correctly.
but, I need the showmodaldialog to show the flex application.
any ideas???
the flex code:
ExternalInterface.addCallback( "handleEvent", handleEvent );

override public function handleEvent( event:Object ):Object
    {
        Alert.show(String(event)); .....

A: Might be a sync problem as Alert.show stops the app, maybe some other javascript call came during the alert.show ?
Need more code :)


text:
Q: Swipe Fragments Android app I'm trying to make a app where its basically a book. Inside this app it has books, which has chapters, which has verses. I'm trying to decide which is the best way to implement this. I'm using fragments and swipe views,and when i swipe to the to the next page the it will change chapters. My question is since this app is going to have about a hundred books, more chapters, and many more versus, I don't think making new Fragments for each chapter would be good for the app performance. Is there a certain method or layout which suits my app best?

A: You want curl animation like this:
https://www.youtube.com/watch?v=mP_AlvJqSLQ
to achive this animation use  overridePendingTransition:
startActivity(new Intent(this, NewActivity.class));
overridePendingTransition(R.anim.push_left_in,R.anim.push_up_out);

push_left_in.xml:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

  <translate android:fromXDelta="100%p" android:toXDelta="0" android:duration="300"/>
  <alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="300" />

</set>

push_up_out.xml :
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

  <translate android:fromXDelta="100%p" android:fromYDelta="100%p" android:toXDelta="0" android:toXDelta="0" android:duration="300"/>

</set>

If you want tutorial or sample, Please follow below link:

*

*http://www.41post.com/3368/programming/android-changing-the-animation-between-activities

*https://github.com/harism/android_page_curl

*https://github.com/emilsjolander/android-FlipView

*https://github.com/MysticTreeGames/android-page-curl