text:
Q: Websockets with Phalcon Is it possible to use Phalcon to both serve pages and run as a websockets server?
When building my web applications it would be preferential to do all the server side coding within the same framework.
If it's possible can you explain how to set it up or provide a tutorial link(s)?
If it's not possible can you recommend a PHP based framework that is designed for both purposes?
Thanks!

A: The Phalcon CLI Task
<?php
namespace Project\Cli\Tasks;

use ZMQ,
    PDO,
    React\ZMQ\Context as ZMQContext,
    React\EventLoop\Factory as EventLoopFactory,
    Ratchet\Server\IoServer,
    Ratchet\Http\HttpServer,
    Ratchet\WebSocket\WsServer,
    Ratchet\Session\SessionProvider,
    Symfony\Component\HttpFoundation\Session\Storage\Handler,
    Webird\Cli\TaskBase,
    Webird\Cli\Chat;

/**
 * Task for websocket
 *
 */
class ServiceTask extends TaskBase
{
    public function mainAction(array $params)
    {
        echo "The default action inside of the ", CURRENT_TASK, " task is not configured\n";
    }

    public function websocketListenAction(array $params)
    {
        // $this->ensureRunningAsWebUser();
        $opts = $params['opts'];
        $config = $this->config;

        $wsPort = (isset($opts['wsport'])) ? $opts['wsport'] : $config->app->wsPort;
        $zmqPort = (isset($opts['zmqport'])) ? $opts['zmqport'] : $config->app->zmqPort;

        $loop = EventLoopFactory::create();
        $chat = new Chat();
        $chat->setDI($this->getDI());

        // Listen for the web server to make a ZeroMQ push after an ajax request
        // $context = new ZMQContext($loop);
        // $pull = $context->getSocket(ZMQ::SOCKET_PULL);
        // $pull->bind("tcp://127.0.0.1:${zmqPort}"); // Binding to 127.0.0.1 means the only client that can connect is itself
        // $pull->on('message', [$chat, 'onUserJoin']);

        $wsServer = new WsServer($chat);

        $ioServer = IoServer::factory(
            new HttpServer($wsServer),
            $wsPort
        );

        echo "websocket listening on port $wsPort in " . ENVIRONMENT . " mode\n";

        $ioServer->run();
    }

}

The Chat application for Ratchet
<?php
namespace Webird\Cli;

use Phalcon\DI\Injectable as DIInjectable,
    Ratchet\MessageComponentInterface,
    Ratchet\ConnectionInterface,
    Webird\DatabaseSessionReader;

/**
 * Basic chat logic for a Ratchet application
 */
class Chat extends DIInjectable implements MessageComponentInterface
{

    protected $clients;

    /**
     * Class constructor
     */
    public function __construct()
    {
        $this->clients = new \SplObjectStorage();
    }

    /**
     * Connection open function
     *
     * @param \Ratchet\ConnectionInterface  $conn
     */
    public function onOpen(ConnectionInterface $conn)
    {
try {
        echo "New connection! ({$conn->resourceId})\n";

        $cookies = $conn->WebSocket->request->getCookies();
        if (! array_key_exists('PHPSESSID', $cookies)) {
            echo "Connection Rejected: Session Cookie was not present.\n";
            return $conn->close();
        }
        $sessionId = $cookies['PHPSESSID'];

        $sessionReader = $this->getDI()->getSessionReader();
        if ($sessionReader->read($sessionId) === false) {
            echo "Connection Rejected: Session could not be found.\n";
            return $conn->close();
        }
        if (($identity = $sessionReader->get('auth-identity')) === false) {
            echo "Connection Rejected: session auth-identity data is not present.\n";
            return $conn->close();
        }
        if (!isset($identity['role'])) {
            echo "Connection Rejected: session user role data is not present.\n";
            return $conn->close();
        }

        $role = $identity['role'];
        $acl = $this->getDI()->getAcl();

        if (!$this->acl->isAllowed($role, 'websocket', 'open')) {
            echo "Connection Rejected: user does not have permission to open a websocket.\n";
            return $conn->close();
        }

} catch (\Exception $e) {
    echo $e->getMessage() . "\n";
}

        // var_export($sessionReader->get('id'));
        // var_export($sess);

        // Store the new connection to send messages to later
        $this->clients->attach($conn, $sessionId);
    }

    /**
     * Receives a message when registered in the websocket server
     *
     * @param \Ratchet\ConnectionInterface  $from
     * @param string                        $msg
    */
    public function onMessage(ConnectionInterface $from, $msg) {
        $numRecv = $this->clients->count() - 1;

        // echo $from->Session->getName() . "\n";

        echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n"
            , $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's');

        foreach ($this->clients as $client) {
            if ($from !== $client) {
                // The sender is not the receiver, send to each client connected
                $client->send($msg);
            }
        }
    }

    /**
     * Handle closing of a connection
     *
     * @param \Ratchet\ConnectionInterface  $conn
    */
    public function onClose(ConnectionInterface $conn) {
        // The connection is closed, remove it, as we can no longer send it messages
        $this->clients->detach($conn);

        echo "Connection {$conn->resourceId} has disconnected\n";
    }

    /**
     * Handles exceptions in the application
     *
     * @param \Ratchet\ConnectionInterface  $from
     * @param \Exception                    $e
    */
    public function onError(ConnectionInterface $conn, \Exception $e) {
        echo "An error has occurred: {$e->getMessage()}\n";

        $conn->close();
    }

}

The read-only Database session reader.
<?php
namespace Webird;

use Phalcon\Db;

/**
 * Read-only session access
 *
 */
class DatabaseSessionReader
{
    private $options;

    private $data;

    /**
     * {@inheritdoc}
     *
     * @param  array                      $options
     * @throws \Phalcon\Session\Exception
     */
    public function __construct($options = null)
    {
        if (!isset($options['db'])) {
            throw new \Exception("The parameter 'db' is required");
        }
        if (!isset($options['unique_id'])) {
            throw new \Exception("The parameter unique_id is required");
        }
        if (!isset($options['db_table'])) {
            throw new \Exception("The parameter 'db_table' is required");
        }
        if (!isset($options['db_id_col'])) {
            throw new \Exception("The parameter 'db_id_col' is required");
        }
        if (!isset($options['db_data_col'])) {
            throw new \Exception("The parameter 'db_data_col' is required");
        }
        if (!isset($options['db_time_col'])) {
            throw new \Exception("The parameter 'db_time_col' is required");
        }

        $this->options = $options;
        $this->data = false;
    }

    protected function getOptions()
    {
        return $this->options;
    }

    /**
     * {@inheritdoc}
     * @param  string $sessionId
     * @return string
     */
    public function read($sessionId)
    {
        $options = $this->getOptions();
        $row = $options['db']->fetchOne(
            sprintf(
                'SELECT %s FROM %s WHERE %s = ?',
                $options['db']->escapeIdentifier($options['db_data_col']),
                $options['db']->escapeIdentifier($options['db_table']),
                $options['db']->escapeIdentifier($options['db_id_col'])
            ),
            Db::FETCH_NUM,
            [$sessionId]
        );

        $this->data = (empty($row[0])) ? false : $this->unserialize_php($row[0]);

        return ($this->data !== false);
    }

    public function has($key)
    {
        if (!is_string($key)) {
            throw new \Exception('The key must be a string');
        }

        if ($this->data == false) {
            return false;
        }

        $uniqueId = $this->getOptions()['unique_id'];
        return (array_key_exists("{$uniqueId}{$key}", $this->data));
    }

    public function get($key)
    {
        if (!$this->has($key)) {
            return false;
        }

        $uniqueId = $this->getOptions()['unique_id'];
        return $this->data["{$uniqueId}{$key}"];
    }

    private function unserialize_php($session_data)
    {
        $return_data = array();
        $offset = 0;
        while ($offset < strlen($session_data)) {
            if (!strstr(substr($session_data, $offset), "|")) {
                throw new \Exception("invalid data, remaining: " . substr($session_data, $offset));
            }
            $pos = strpos($session_data, "|", $offset);
            $num = $pos - $offset;
            $varname = substr($session_data, $offset, $num);
            $offset += $num + 1;
            $data = unserialize(substr($session_data, $offset));
            $return_data[$varname] = $data;
            $offset += strlen(serialize($data));
        }
        return $return_data;
    }

}

Here is the DI to setup the session reader.
$di->set('sessionReader', function() use ($di) {
    $config = $di->get('config');
    $connection = $di->get('db');

    $sessionReader = new DatabaseSessionReader([
        'db'          => $connection,
        'unique_id'    => $config->session->unique_id,
        'db_table'    => $config->session->db_table,
        'db_id_col'   => $config->session->db_id_col,
        'db_data_col' => $config->session->db_data_col,
        'db_time_col' => $config->session->db_time_col,
        'uniqueId'    => $config->session->unique_id
    ]);

    return $sessionReader;
});

Ref: https://forum.phalconphp.com/discussion/3539/phalcon-websockets


text:
Q: how to group data according to UserID? Everyone!
I am new to MVC and Linq and I have some problems with these code.
I want to group organizationId according to UserId but it only shows an organizationId per UserId in my View.
Actually, I want to get all organizationId with the same UserId.
How can i get it?
public ActionResult Index()
{
    var datas = _userInOrganizationService.UserInOrganizations.GetByAll().ToList();
    var userdata = ApplicationUserManager.Users.Where(x => x.Active == true).ToList();
    var orgdata = _userInOrganizationService.Organizations
        .GetByAll().ToList();

    List<UserInOrganizationViewModel> data = (
      from z in datas
      join user in userdata on z.UserID equals user.Id
      join org in orgdata on z.OrganizationID equals org.OrganizationID
      select new UserInOrganizationViewModel
    {

      UserID = user.Id,
      UserName = user.UserName,
      FullName = user.FullName,
      Email = user.Email,

      NRCNo = user.NRCNo,
          Organizations = ShowOrganizaton(org.OrganizationID),

          PasswordQuestion = user.PasswordQuestion,
      PasswordAnswer = user.PasswordAnswer,
      CreatedDate = user.CreatedDate,
      UpdatedDate = user.UpdatedDate
    }).Distinct().ToList();

    return View(data);
}

public List<Organization> ShowOrganizaton(string orgid)
{
    var data = _userInOrganizationService.Organizations.GetByAll().Where(x => x.Active == true && x.OrganizationID == orgid).AsEnumerable().ToList();

    return data;
}

A: Just add .GroupBy(u => u.UserID) to your LINQ statement.
This will order all records by UserID

redpajama_set_name: RedPajamaStackExchange


text:
Q: Redis ZRANGEBYSCORE: what is offset and count ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT offset count]

What is offset and count? How am I supposed to use them if I just want the member with the highest score?

A: It is written here http://redis.io/commands/zrangebyscore.
Count and offset are used for pagination:

*

*Count is the number of results you want to display

*Offset is the number of results you already displayed


text:
Q: Solve a System of Differential Equations using" bvp4c" Matlab fuction , Error -->Error using bvp4c Too many input arguments I had a hard time trying to run a code of  Differential Equations  using" bvp4c" Maltab function,always geting the same error " Error using bvp4c Too many input arguments" I've tried too many other codes from different works but the result is the same! any help please? The code is shown below:
function bvp4c
L=0.2;
xlow=0;
xhigh=L;
solinit=bvpinit(linspace(xlow,xhigh,20),[1 -1]);
sol=bvp4c(@bvp4ode,@bvp4bc,solinit);
xint=linspace(xlow,xhigh);
sxint=deval(sol,xint);
plot(xint,sxint(1,:))
%-----------------
function dydx=bvp4ode(x,y)
L=0.2;
V=1;
E0=8.85e-12;
Er1=2.64;
Er2=3.25;
K11=6.95e-12;
AE=Er2-Er1;
Vth=pi*(K11/(E0*AE))^1/2;
dydx=[y(2) (V^2/Vth^2)*(pi^2/L^2)*sin(y(1))*cos(y(1))];
%-----------------
function res=bvp4bc(ya,yb)
res=[ya(1) yb(1)];

A: You define a function bvp4c and inside that function you try to call the built-in MATLAB bvp4c function. This does not work. When you define a function that has the same name as a built-in function, MATLAB uses only your function. That is why you have an error Too many input arguments: your bvp4c function has no input arguments, while inside you call it with three arguments.
To solve this problem, rename your function to e.g. callBvp4c or any other name which is not used by MATLAB. Further, make sure that you also rename the file to callBvp4c.m, as MATLAB addresses functions via their name.
I assume that all three functions are saved in the same .m file. This is generally possible, but then bvp4ode and bvp4bc will only be visible inside callBvp4c. When you call sol=bvp4c(@bvp4ode,...), you give a function handle to the bvp4c function, but it won't find the corresponding function. That is what the error says: it doesn't find bvp4ode. To solve this, you will have to create a separate .m file for every function and make sure the .m file has the same name as the function. In your case: callBvp4c.m, bvpode.m and bvp4bc.m.


text:
Q: Test Angular component that brings in an observable derived from @angular-redux/store's "@select()" method Okay. So I have a component called "Account" which uses @select() to make user$. The type of user$ is an Observable with the interface of "User"
@select user$: Observable<User>

I also have a variable called 'user'. In the constructor of this component, I subscribe to "user$", and derive the properties of 'user' from the observable.
constructor(private ngRedux: NgRedux<gdcClientState>, private dbService: DatabaseService){
 this.user$.subscribe(user => this.user = user)
}

This works great in practice, but when I try to test I immediately get hit with an error about how it can't read 'firstName' of undefined.
*one of the properties set into 'user' by the observable 'user$' is a firstName.
Here is what my test looks like:
/* tslint:disable:no-unused-variable */
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import {NgReduxTestingModule, MockNgRedux} from '@angular-redux/store/testing';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { DatabaseService } from '../database.service';
import { User } from '../user';
import { Observable } from 'rxjs';

import { AccountComponent } from './account.component';

describe('AccountComponent', () => {
  let component: AccountComponent;
  let fixture: ComponentFixture<AccountComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ AccountComponent ],
      imports: [NgReduxTestingModule, FormsModule, ReactiveFormsModule],
      providers: [
        {provide: DatabaseService}
      ]
    })
    .compileComponents();
  }));

  beforeEach(()=>{
    MockNgRedux.reset();

    fixture = TestBed.createComponent(AccountComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();

  });

  afterEach(()=>{
    fixture.destroy();
  })

  it('should create', async(() => {
    const fixture = TestBed.createComponent(AccountComponent);
    fixture.detectChanges();
    const compiled = fixture.debugElement.nativeElement;

 fixture.detectChanges();

    expect(compiled).toBeTruthy();
  }));
});

I tried implementing some fixes and suggestions from these two threads: Testing @select decorators with @angular-redux/store
Testing Angular with @angular-redux/store in Storybook
But it didn't work out for me. I would love some help with this.
Thank you.

A: You shouldn´t initialize the subscription on the constructor of the Component, but on the ngOnInit lifecycle hook.
ngOnInit(){
 this.user$.subscribe(user => this.user = user)
}

In your spec, be sure you are initializing the user on your component before firing the first detectChanges. So better to create a mockUser and set it there:
    fixture = TestBed.createComponent(AccountComponent);
    component = fixture.componentInstance;
    component.user = mockUser;
    fixture.detectChanges();

Cheers!


text:
Q: will stopService() stop a foreground service? Will stopService() stop a service running as a foreground service?
It appears to, but also "feels" like it trumps the importance of foreground services.

A: Confirmed: Yes - running stopService() from an Activity outside of the service will stop the service -- even if the service is a foreground running service.

A: It stops the service outright. It doesn't trump any importance, if your code is sending an Intent to stop the service, it would make perfect sense to obey said Intent.


text:
Q: AutoMapper - mapper not found I can't seem to get anything working with AutoMapper...
First off, the documentation is wrong or outdated or I'm stupid:
AutoMapperConfiguration.Configure(); // this doesn't exist

Second, I'm creating my maps by calling:
Mapper.CreateMap(myType1, myType2)

where the types are literally exact property maps of one another.
But when I call
Mapper.Map(myInstanceOf1, myType2)

I get a mapper not found error. And if I check the AutoMapper internal _objectMapperCache Dictionary, I can see the internal value for my mapping above is null (hence the exception).
What am I doing wrong?

A: You need to create the AutoMapperConfiguration class yourself. Add a static Configure method and put your configuration code there. For example:
public class AutoMapperConfiguration
{
    public static void Configure()
    {
       Mapper.Initialize( x => x.AddProfile<MyProfile>() );
    }
}

public class MyProfile : Profile
{
    public override string ProfileName
    {
       get { return "MyProfile"; }
    }

    public MyProfile()
    {
    // Configuration here
      CreateMap<Account, AccountViewModel>();
    }
}

A: Try using the generic syntax, it works for me:
Mapper.CreateMap<A, B>().ForMember(....

b = Mapper.Map<A, B>(a);


text:
Q: React Router useNavigate hook unwanted scroll to the top onclick I am adding url parameters as so using the Reach router library.
import { useNavigate } from '@reach/router'
const navigate = useNavigate()
Then I am using the qs library to add query parameters to the url as so
const handleSliderChange = (event) => {
  event.preventDefault()
  const params = location.search.slice(1)
  const paramsObj = qs.parse(params)
  paramsObj.date = newValue
  const paramsStr = qs.stringify(paramsObj)
  navigate(`/?${paramsStr}`, { replace: true })
  setSliderValue(newValue)
}

This works well for adding the query parameters but the page scrolls to the top. How do I stop this default behaviour?


text: Q: Is it possible to run ios simulator with Android studio in windows 10? I am fresher in flutter. I opened my first project in flutter using android studio in windows 10 and run it in android emulator. It is working as expected. I want to run my app in ios emulator also. I searched in Google and YouTube a lot how to use an ios emulator with my Android studio in windows 10 but I couldn't success. Is it possible to have ios simulator or emulator in windows 10 to use with android studio or not? if it is not what should I do? Please anyone help me. Thanks a lot.


text:
Q: Force rerender parent component when done with update data I have data stored in an array of objects that will be sent through axios PUT. After done with updating data, I want the page to rerender so that it display the current data after update.
Parent component:-

  {appSettingsList.map((appSettings, i) => (
   <EditButton appSettings={appSettings} i={i} />
   ))}

first child component:-
const [showEdit, setShowEdit] = useState(false);
return (

  {appSettings.appid}
  {appSettings.Name}
  {appSettings.BackgroundColor}
  {appSettings.FontSize}
  {appSettings.FontFamily}
  {appSettings.Theme}
  {appSettings.NavigationBar}

    {showEdit ? (
      <EditApplicationSettings
        appSettings={appSettings}
        changeState={(showEdit) => setShowEdit(showEdit)}
      />
    ) : (
      <button
        key={i}
        className="button-green"
        onClick={() => setShowEdit(!showEdit)}
      >
        Edit
      </button>
    )}

Second child component (this is where the update occurs)
const [newValue, setNewValue] = useState([]);
  const [attributeId, setAttributeId] = useState([]);
  let attributes = {
    appid: [],
    attributeid: [],
    newvalue: [],
    datemodified: [],
  };

function submitUpdate(e) {
e.preventDefault();
for (var i = 0; i < newValue.length; i++) {
  attributes.appid = appSettings.appid;
  attributes.attributeid = attributeId[i];
  attributes.newvalue = newValue[i];
  attributes.datemodified = GetCurrentLocalDateTime();
  axios
    .put(
      `http://localhost:8080/application-settings/${appSettings.appid}`,
      {
        attributes,
      }
    )
    .catch((error) =>
      console.log(
        "Failed to update employment type data",
        error.response.data
      )
    );
}
Swal.fire({
   icon: "success",
   title: "Successfully Updated!",
   showConfirmButton: false,
   timer: 1500,
});
props.changeState(false);

How to make the component rerender without having to force refresh on the whole page?


text:
Q: Magento 2.1.7 unable to locate gallery.css file I need to remove a style that is listed in the below listed gallery.css file.
How ever I believe the path below is the location of a cached version of the file not the actual file??
I need to find the actual file and not sure were/how to find it?
domain.com/pub/static/version1500569382/frontend/Smartwave/porto_child/en_US/mage/gallery/gallery.css

any suggestions on where I can find this file? I looked in
domain.com/app/design/frontend/Smartwave/porto_child
however That directory does not contain a en_US folder?

A: If you want to remove this file then add below code in <theme_dir>\Magento_Catalog\layout\catalog_product_view.xml file.
<head>
   <remove src="mage/gallery/gallery.css" />
</head>

If you want to edit gallery style:
If you are not locate this file in <theme_dir>\web\mage\gallery then copy gallery.less file from <root>\lib\web\mage\gallery and add in your theme.
Run command:

*

*php bin/magento cache:clean

*php bin/magento setup:static-content:deploy

en_US folder is generate from themes when you run php bin/magento setup:static-content:deploy.

A: If you are looking for the static file you should check in
domain.com/pub/static/frontend/Smartwave/porto_child/en_US/mage/gallery/gallery.css

Otherwise if you are looking for the original file which you want to deploy in future after finishing the changes, you should check in
domain.com/app/design/frontend/Smartwave/porto/mage/gallery/gallery.css

Since 'porto' is a parent theme for the 'porto_child', it will be there in the porto theme directory.


text:
Q: TypingError: Failed in nopython mode pipeline (step: nopython frontend) I am trying to write my first function using numba jit, I have a pandas dataframe that I need to iterate through and find the root mean square for each 350 points, since the for loop of python is quite slow I decided to try numba jit, the code is:
@jit(nopython=True)
def find_rms(data, length):
    res = []
    for i in range(length, len(data)):
        interval = np.array(data[i-length:i])
        interval =np.power(interval, 2)
        sum = interval.sum()
        resI = sum/length
        resI = np.sqrt(res)
        res.appennd(resI)
    return res

mydf = np.array(df.iloc[:]['c0'], dtype=np.float64)
df.iloc[350:]['rms'] = find_rms(mydf, 350)

I read somewhere thad I need to specify datatypes, therefore I wrote "dtype = np.float64" but I still get the error as:
---------------------------------------------------------------------------
TypingError                               Traceback (most recent call last)
<ipython-input-39-4d388f72efdc> in <module>
----> 1 df.iloc[350:]['rms'] = find_rms(mydf, 350.0)

c:\users\1\appdata\local\programs\python\python35\lib\site-packages\numba\dispatcher.py in _compile_for_args(self, *args, **kws)
    346                 e.patch_message(msg)
    347
--> 348             error_rewrite(e, 'typing')
    349         except errors.UnsupportedError as e:
    350             # Something unsupported is present in the user code, add help info

c:\users\1\appdata\local\programs\python\python35\lib\site-packages\numba\dispatcher.py in error_rewrite(e, issue_type)
    313                 raise e
    314             else:
--> 315                 reraise(type(e), e, None)
    316
    317         argtypes = []

c:\users\1\appdata\local\programs\python\python35\lib\site-packages\numba\six.py in reraise(tp, value, tb)
    656             value = tp()
    657         if value.__traceback__ is not tb:
--> 658             raise value.with_traceback(tb)
    659         raise value
    660

TypingError: Failed in nopython mode pipeline (step: nopython frontend)
Invalid use of Function(<built-in function array>) with argument(s) of type(s): (array(float64, 1d, C))
 * parameterized
In definition 0:
    TypingError: array(float64, 1d, C) not allowed in a homogeneous sequence
    raised from c:\users\1\appdata\local\programs\python\python35\lib\site-packages\numba\typing\npydecl.py:463
In definition 1:
    TypingError: array(float64, 1d, C) not allowed in a homogeneous sequence
    raised from c:\users\1\appdata\local\programs\python\python35\lib\site-packages\numba\typing\npydecl.py:463
This error is usually caused by passing an argument of a type that is unsupported by the named function.
[1] During: resolving callee type: Function(<built-in function array>)
[2] During: typing of call at <ipython-input-34-edd252715b2d> (5)

File "<ipython-input-34-edd252715b2d>", line 5:
def find_rms(data, length):
    <source elided>
    for i in range(length, len(data)):
        interval = np.array(data[i-length:i])
        ^

This is not usually a problem with Numba itself but instead often caused by
the use of unsupported features or an issue in resolving types.

To see Python/NumPy features supported by the latest release of Numba visit:
http://numba.pydata.org/numba-doc/dev/reference/pysupported.html
and
http://numba.pydata.org/numba-doc/dev/reference/numpysupported.html

For more information about typing errors and how to debug them visit:
http://numba.pydata.org/numba-doc/latest/user/troubleshoot.html#my-code-doesn-t-compile

If you think your code should work with Numba, please report the error message
and traceback, along with a minimal reproducer at:
https://github.com/numba/numba/issues/new

Does anybody know what the problem is?

A: You had a typo in append and I think you also made a mistake with what the square root is to be taken of (I believe resI not res).
Other than that, the only problem was the initialization of interval. Numba doesn't want you to pass a numpy array to a numpy array. It doesn't help with anything to wrap the np.array around the slice of the array, python simply doesn't care if you do that and treats the code like you didn't but Numba in nopython mode does care and throws an error. Leaving that part out solved the problem.
@jit(nopython=True)
def find_rms(data, length):
    res = []
    for i in range(length, len(data)):
        interval = data[i-length:i]
        interval = np.power(interval, 2)
        sum = interval.sum()
        resI = sum/length
        resI = np.sqrt(resI)
        res.append(resI)
    return res

mydf = np.array(df.iloc[:]['c0'], dtype=np.float64)
target = find_rms(mydf, 350)


text:
Q: How to restore Android ListView position? I used this code to save list View position.
How i can restore it?
View c = listview.getChildAt(0);
int scrolly = -c.getTop() + listview.getFirstVisiblePosition() * c.getHeight();

A: This is what you all are looking:
onResume(){
   refresh_your_data();
    if(listview.getadapter()==null)
    // create the adapter
    }
    else
    {
    //create method in adapter to refresh list of data
    refill_data(listdata);
    adapter.notifydatasetchanged();
    }
 }

A: You can restore the saved position to the ListView by this method
listview.scrollListBy(scrolly);

If you want to scroll the list to top then you can use this
listview.smoothScrollToPosition(0);

Or
 listview.setSelection(0);

you can also use this method to scroll listview to top
listView.setSelectionAfterHeaderView();

A: //Create Hashmap of listview item:
HashMap<Integer, View> hashMap = new HashMap<Integer, View>();

//put listview items in hashmap
hashMap.put(position, view);

//get view item at particular position

hashMap.get(position);


text:
Q: Cannot set feed_previous to tf.bool in embedding_attention_seq2seq I am using the tf.contrib.legacy_seq2seq.embedding_attention_seq2seq() function and I try to set the feed_previous argument to tf.placeholder(tf.bool), however, this does not work. Error messages:
Traceback (most recent call last):
  File "D:/beamSearch/main.py", line 6, in <module>
    parser.main()
  File "D:\beamSearch\neuralParser\neuralParser.py", line 107, in main
    self.model = Model(self.args, self.textData)
  File "D:\beamSearch\neuralParser\model.py", line 26, in __init__
    self.buildNetwork()
  File "D:\beamSearch\neuralParser\model.py", line 62, in buildNetwork
    feed_previous=self.test
  File "C:\Python35\lib\site-packages\tensorflow\contrib\legacy_seq2seq\python\ops\seq2seq.py", line 849, in embedding_attention_seq2seq
    encoder_cell = copy.deepcopy(cell)
  File "C:\Python35\lib\copy.py", line 182, in deepcopy
    y = _reconstruct(x, rv, 1, memo)
  File "C:\Python35\lib\copy.py", line 297, in _reconstruct
    state = deepcopy(state, memo)
  File "C:\Python35\lib\copy.py", line 155, in deepcopy
    y = copier(x, memo)
  File "C:\Python35\lib\copy.py", line 243, in _deepcopy_dict
    y[deepcopy(key, memo)] = deepcopy(value, memo)
  File "C:\Python35\lib\copy.py", line 155, in deepcopy
    y = copier(x, memo)
  File "C:\Python35\lib\copy.py", line 218, in _deepcopy_list
    y.append(deepcopy(a, memo))
  File "C:\Python35\lib\copy.py", line 182, in deepcopy
    y = _reconstruct(x, rv, 1, memo)
  File "C:\Python35\lib\copy.py", line 297, in _reconstruct
    state = deepcopy(state, memo)
  File "C:\Python35\lib\copy.py", line 155, in deepcopy
    y = copier(x, memo)
  File "C:\Python35\lib\copy.py", line 243, in _deepcopy_dict
    y[deepcopy(key, memo)] = deepcopy(value, memo)
  File "C:\Python35\lib\copy.py", line 182, in deepcopy
    y = _reconstruct(x, rv, 1, memo)
  File "C:\Python35\lib\copy.py", line 297, in _reconstruct
    state = deepcopy(state, memo)
  File "C:\Python35\lib\copy.py", line 155, in deepcopy
    y = copier(x, memo)
  File "C:\Python35\lib\copy.py", line 243, in _deepcopy_dict
    y[deepcopy(key, memo)] = deepcopy(value, memo)
  File "C:\Python35\lib\copy.py", line 182, in deepcopy
    y = _reconstruct(x, rv, 1, memo)
  File "C:\Python35\lib\copy.py", line 297, in _reconstruct
    state = deepcopy(state, memo)
  File "C:\Python35\lib\copy.py", line 155, in deepcopy
    y = copier(x, memo)
  File "C:\Python35\lib\copy.py", line 243, in _deepcopy_dict
    y[deepcopy(key, memo)] = deepcopy(value, memo)
  File "C:\Python35\lib\copy.py", line 182, in deepcopy
    y = _reconstruct(x, rv, 1, memo)
  File "C:\Python35\lib\copy.py", line 297, in _reconstruct
    state = deepcopy(state, memo)
  File "C:\Python35\lib\copy.py", line 155, in deepcopy
    y = copier(x, memo)
  File "C:\Python35\lib\copy.py", line 243, in _deepcopy_dict
    y[deepcopy(key, memo)] = deepcopy(value, memo)
  File "C:\Python35\lib\copy.py", line 174, in deepcopy
    rv = reductor(4)
TypeError: can't pickle _thread.lock objects

Code:
self.dropOut = tf.placeholder(dtype=tf.float32, shape=(), name='dropOut')
self.test = tf.placeholder(tf.bool, name='test')

with tf.variable_scope("cell"):  # TODO: How to make this appear on the graph ?
    encoDecoCell = tf.contrib.rnn.BasicLSTMCell(self.args.hiddenSize,
                                                state_is_tuple=True)  # Or GRUCell, LSTMCell(args.hiddenSize)
    encoDecoCell = tf.contrib.rnn.DropoutWrapper(encoDecoCell, input_keep_prob=self.dropOut,
                                                 output_keep_prob=self.dropOut)
    encoDecoCell = tf.contrib.rnn.MultiRNNCell([encoDecoCell] * self.args.numLayers, state_is_tuple=True)

# Network input (placeholders)

with tf.name_scope('placeholder_encoder'):
    # encoderInputs are intergers, representing the index of words in the sentences
    self.encoderInputs = tf.placeholder(tf.int32, [None, self.args.maxLength])

with tf.name_scope('placeholder_decoder'):
    self.decoderInputs = tf.placeholder(tf.int32, [None, self.args.maxLength+2], name='decoderInputs')
    self.decoderTargets = tf.placeholder(tf.int32, [None, self.args.maxLength+2], name='decoderTargets')
    self.decoderWeights = tf.placeholder(tf.int32, [None, self.args.maxLength+2], name='decoderWeights')

decoderOutputs, states = tf.contrib.legacy_seq2seq.embedding_attention_seq2seq(
    self.encoderInputs,
    self.decoderInputs,
    encoDecoCell,
    self.textData.getInVocabularySize(),
    self.textData.getOutVocabularySize(),
    embedding_size=self.args.embeddingSize,
    feed_previous=self.test
)

A: It looks like that the copy.deepcopy(cell) method does not support placeholders. Since this method is used to copy the RNN model specified as the cell parameter so that both the encoder and decoder can use the same architecture, and it does not give you any other alternatives to specify them separately, the only possibility, in case you do need to use placeholders, you may have to reproduce this seq2seq module by yourself (by copying the source code and make slight changes). In your own implementation, you just create two separate models for the encoder and decoder.


text:
Q: HTML5 WebSocket: Client's messages are buffered in Google Chrome 22 I am writing a very simple chat application based on the HTML5 WebSocket technology where the server (implemented using node.js WS) keeps track of all the connected users and broadcasts each received message. The client on the other hand, connects to the server and according to user's actions, sends messages to the server.
The problem that I am observing is that unless the server sends a message to the client after opening the connection, all messages sent from the client running on Google Chrome get buffered until several messages have been sent. Once the buffer is full, all messages are sent at once. This creates a very unresponsive chat experience for the end user.
The fix that I found was to add single ws.send("Hello Client:" + clientId); after opening the connection on the server side, but I am not sure why this is necessary? Below you can find snippet from my client and server components, but the entire source code is available at ChatMate git project.
Server Code:
wsServer.on('connection', function (ws) {
    var clientId = nextClientId += 1;
    clients[clientId] = ws;
    log("Accepted connection from client " + clientId + ".");

    //The fix: If you emit this initial message from the server, then
    //all of client's messages will be cached.
    ws.send("Hello Client: " + clientId);

    ws.on('message', function (message) {
        log("Received message: " + message);
        var id;
        for (id in clients ) {
            if (clients.hasOwnProperty(id)) {
                if (parseInt(id, 10) !== clientId) {
                    clients[id].send(message);
                }
            }

        }
    });
});

Client Code:
function WebSocketTest() {
    "use strict";
    ws = new WebSocket("ws://DOMAIN:8080/");

    ws.onopen = function () {
        console.log("Connection is open.");
        //This message will not be sent if the server does not send
        //a message first.
        ws.send("Client Message.");
    };

    ws.onmessage = function (e) {
        console.log("Message is received: " + e.data);
    };

}

Thanks!


text:
Q: Plot better graph using a vector of data X and Y I tried to plot my data using some packages but I didn't get something nice. I've data like this:
X=[590 598 599 600 601 602 603 604 605 606 607 608 609 610 611 627 628 629 634 641 642 644 645 648 649 651 652 653 654 655 657 658 659 660 690 691 692 693 694 695 696 697 698 699 700 701 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 720 721 722 723 724 726 729 730 731 732 733 734 735 736 737 738 739 740 741 744 761 762 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 800 801 802 803 804 806 807 808 809 810 812 813 814 816 818 819 820 821 822 824 825 827 828 830 831 833 835 837 838 839 841 843 860 875 876 877 879 881 884 885 886 889 910 926 927 928 929 930 932 933 934 935 936 937 938 939 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 959 997 999 1000];
Y=[2 6 4 4 3 5 5 3 6 2 3 5 2 3 3 1 1 -1 1 -1 -1 -1 -2 1 1 -2 -1 -1 -1 -1 -2 -3 2 -2 1 1 -1 -1 2 3 1 2 2 2 -1 -1 -1 2 -1 5 6 3 1 1 3 5 1 4 2 3 1 4 1 3 2 1 -2 -1 1 7 2 1 6 2 2 1 5 -1 6 4 3 1 2 2 7 6 8 7 3 -1 3 5 5 9 2 2 1 4 1 4 6 1 -1 5 3 3 3 1 2 3 1 -2 5 10 6 2 6 7 4 2 5 4 2 5 3 1 6 6 2 3 3 2 1 3 2 1 3 2 2 2 -2 -2 -1 1 1 1 1 1 1 -1 -1 1 1 3 -1 9 -3 -2 -2 -1 1 1 1 -1 1 2 5 1 -1 4 1 4 1 -1 4 1 2 -1 1 1 7 1 3 5 4 3 1 2 1 3 3 2 1 1]
I want to show that I've more positive numbers in Y than negative ones. X are just frame numbers (images).
I get something like that using tikzpicture
Someone has any better idea how to plot those data?

A: Put your data into a table and place markers depending on the sign of the data
\documentclass[]{article}
\usepackage{pgfplotstable}
\pgfplotsset{compat=1.14}

\pgfplotstableread{
X Y
         590           2
         598           6
         599           4
         600           4
         601           3
         602           5
         603           5
         604           3
         605           6
         606           2
         607           3
         608           5
         609           2
         610           3
         611           3
         627           1
         628           1
         629          -1
         634           1
         641          -1
         642          -1
         644          -1
         645          -2
         648           1
         649           1
         651          -2
         652          -1
         653          -1
         654          -1
         655          -1
         657          -2
         658          -3
         659           2
         660          -2
         690           1
         691           1
         692          -1
         693          -1
         694           2
         695           3
         696           1
         697           2
         698           2
         699           2
         700          -1
         701          -1
         703          -1
         704           2
         705          -1
         706           5
         707           6
         708           3
         709           1
         710           1
         711           3
         712           5
         713           1
         714           4
         715           2
         716           3
         717           1
         718           4
         720           1
         721           3
         722           2
         723           1
         724          -2
         726          -1
         729           1
         730           7
         731           2
         732           1
         733           6
         734           2
         735           2
         736           1
         737           5
         738          -1
         739           6
         740           4
         741           3
         744           1
         761           2
         762           2
         764           7
         765           6
         766           8
         767           7
         768           3
         769          -1
         770           3
         771           5
         772           5
         773           9
         774           2
         775           2
         776           1
         777           4
         778           1
         780           4
         781           6
         782           1
         783          -1
         784           5
         785           3
         786           3
         787           3
         788           1
         789           2
         790           3
         791           1
         792          -2
         793           5
         794          10
         795           6
         796           2
         797           6
         798           7
         800           4
         801           2
         802           5
         803           4
         804           2
         806           5
         807           3
         808           1
         809           6
         810           6
         812           2
         813           3
         814           3
         816           2
         818           1
         819           3
         820           2
         821           1
         822           3
         824           2
         825           2
         827           2
         828          -2
         830          -2
         831          -1
         833           1
         835           1
         837           1
         838           1
         839           1
         841           1
         843          -1
         860          -1
         875           1
         876           1
         877           3
         879          -1
         881           9
         884          -3
         885          -2
         886          -2
         889          -1
         910           1
         926           1
         927           1
         928          -1
         929           1
         930           2
         932           5
         933           1
         934          -1
         935           4
         936           1
         937           4
         938           1
         939          -1
         941           4
         942           1
         943           2
         944          -1
         945           1
         946           1
         947           7
         948           1
         949           3
         950           5
         951           4
         952           3
         953           1
         954           2
         955           1
         956           3
         959           3
         997           2
         999           1
        1000           1
}\mytable

\begin{document}
\begin{tikzpicture}
\begin{axis}[ytick=0,xtick=\empty, ymajorgrids, hide x axis, axis y line*=left]
\addplot[scatter, only marks, point meta=sign(y)] table \mytable;
\end{axis}
\end{tikzpicture}
\end{document}

A:
Why dont you use a histogram as suggested? This was made in Matlab, but can be easily replicated in LaTex. I think this shows the distribution best.
It is important to note that a graph or diagramn should only depict relevant data. With you saying "X are just frame numbers (images)" you are admitting those are irrelevant and so they should not be shown in the graph.
Edit: This is how its done in LaTex/Pgfplots. Part of the code was taken from How to compute an histogram (plot bars) binning the values from a .csv using TeX?. Note that Matlab and pgfplots use different ranges to calculate the histogram. I still prefer the one in Matlab and I would suggest using Matlab to work with the data and then just display it with a bar graph in LaTex. A free alternative is Octave by the way.
To convert the data I used the replace function in Notepad++ (replace " " with \n).

\documentclass[border=5mm]{standalone}
\usepackage{filecontents}
\usepackage{pgfplots, pgfplotstable}
\usepgfplotslibrary{statistics}

\begin{filecontents}{data}
2
6
4
4
3
5
5
3
6
2
3
5
2
3
3
1
1
-1
1
-1
-1
-1
-2
1
1
-2
-1
-1
-1
-1
-2
-3
2
-2
1
1
-1
-1
2
3
1
2
2
2
-1
-1
-1
2
-1
5
6
3
1
1
3
5
1
4
2
3
1
4
1
3
2
1
-2
-1
1
7
2
1
6
2
2
1
5
-1
6
4
3
1
2
2
7
6
8
7
3
-1
3
5
5
9
2
2
1
4
1
4
6
1
-1
5
3
3
3
1
2
3
1
-2
5
10
6
2
6
7
4
2
5
4
2
5
3
1
6
6
2
3
3
2
1
3
2
1
3
2
2
2
-2
-2
-1
1
1
1
1
1
1
-1
-1
1
1
3
-1
9
-3
-2
-2
-1
1
1
1
-1
1
2
5
1
-1
4
1
4
1
-1
4
1
2
-1
1
1
7
1
3
5
4
3
1
2
1
3
3
2
1
1
\end{filecontents}

\begin{document}
\begin{tikzpicture}
\begin{axis}[
    ybar,
    ymin=0
]
\addplot +[
    hist={
        bins=13 %this says how many columns you want (10-(-3)=13)
    }
] table [y index=0] {data};
\end{axis}
\end{tikzpicture}
\end{document}


text:
Q: Dynamic fields params inside the controller I have a form containing some dynamically added date fields using jQuery, In order to handle their params submitted I need to count the number of those fields, then inside the controller I can make a loop based on that number:
application.js
$(function() {
  var scntDiv = $('#foo');
  var i = $('#foo div.bar').size();

  $(document).on('click', '#addField', function() {
    $('
<input type="text" id="start" name="start_'+ i +'"><input type="text" id="end" name="end_'+ i +'">
').appendTo(scntDiv);
    i++;
    return false;
  });

Saying I added n input, then the html output will be:
<input type="text" id="start" name="start_1">
<input type="text" id="end" name="end_1">
.
.
.
<input type="text" id="start" name="start_n">
<input type="text" id="end" name="end_n">

My question is, how to access that "n" inside my controller?
I have to store all the dates range in one array then create multiple records based on each date.

A: Another option, close to how nested_attributes are implemented (not the most beautiful javascript you'll see out there, but you get the spirit) :
$(function() {
  var $scntDiv = $('#foo');

  $('#addField').click( function(){
    var index = $scntDiv.find( '.bar' ).size();
    $(
      '
' +
        '<input type="text" class="start" name="ranges[' + index + '][start]">' +
        '<input type="text" class="end" name="ranges[' + index + '][end]">' +
      '
'
     ).appendTo( $scntDiv );
     return false;
  });
});

This will build a hash like this :
>> params[:ranges]
=> {"0" => {"start" => "a_date_string", "end" => "another_date_string"},
    "1" => {"start" => "a_date_string", "end" => "another_date_string"} }

it's then easy to process this hash, even using mass assignment :
class MyClass
  def ranges= ranges
    ranges.each do |*,attributes|
      # whatever logic pleases you, self.ranges.build( attributes ) for instance
    end
  end
end

however, if you go this way, you better use directly nested_attributes, except if you have a very convoluted logic to perform. Nested attributes come with a lot of goodies like auto instantiation of child records, record deletion management, auto-rejection of some attributes if needed, they work well with the fields_for form helper, etc. It's native to rails, so why bother and reinvent the wheel ?

A: This will help.
$(function() {
  var scntDiv = $('#foo');

  $('#addField').click(function(){
    $('
<input type="text" id="start" name="start[]"><input type="text" id="end" name="end[]">
').appendTo(scntDiv);
    return false;
  });
});

This will send the params like below. for example
"start"=>["1", "2", "3"], "end"=>["11", "22", "33"]


text:
Q: Kotlin - Type mismatch required collection found list I need to append two list but it say me:
type mismatch required collection found list

It is like bellow:
val list: List<Cohort> = ArrayList()
private fun fillFromDao() {
    val notesObserver: Observer<ArrayList<Cohort?>?>? =
        Observer { cohort: ArrayList<Cohort?>? ->
                list.toMutableList().addAll(cohort)
        }
    if (notesObserver != null) {
        otherDialogFragmentViewModel.fetchIsFree()?.observe(this, notesObserver)
        otherDialogFragmentViewModel.fetchHasCertificate()?.observe(this, notesObserver)
    }
}

A: Two changes:
val list: List<Cohort?> = ArrayList()    ----> add '?' after Cohort
    private fun fillFromDao() {
        val notesObserver: Observer<ArrayList<Cohort?>?>? =
            Observer { cohort: ArrayList<Cohort?>? ->
                    list.toMutableList().addAll(cohort!!) ----> add '!!' after Cohort
            }
        if (notesObserver != null) {
            otherDialogFragmentViewModel.fetchIsFree()?.observe(this, notesObserver)
            otherDialogFragmentViewModel.fetchHasCertificate()?.observe(this, notesObserver)
        }
    }

A: list variable of type List<Cohort>, but notesObserver value type is ArrayList<Cohort?>: so notesObserver value can have nullable elements.
Thus either list variable should accept nullable or notesObserver should not have nullable values.


text:
Q: Python list splicing for 2D array matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
matrix[3][1:] = matrix[3][0:-1]
print(matrix)

gives the following output:
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 13, 14, 15]]

But:
rows = 3
k = 0
matrix[rows-k][1+k:-k] = matrix[rows-k][k:-1-k]
print(matrix)

gives the following output:
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 13, 14, 15, 14, 15, 16]]

Can someone please explain to me what's going on?

A: Interesting question.
This happens because
matrix[rows-k][1+k:-k] = matrix[rows-k][k:-1-k]

is equivalent to
matrix[3][1:0] = matrix[3][0:-1]

which is equivalent to
matrix[3][1:1] = matrix[3][0:-1]

So when you do matrix[3][1:0] => matrix[index][start:stop:None]
Your start value is 1, which is more than your stop value of 0. In case of start >= stop Python sets stop = start and returns an empty slice.
You can check the value of matrix[3][1:1] which is an empty slice like matrix[3][1:0]
>>> matrix[3][1:0]
[]
>>> matrix[3][1:1]
[]

Read more: Python doc

If i is greater than or equal to j, the slice is empty

A: If you insert rows = 3 and k = 0:
matrix[3][1:0] = matrix[3][0:-1]

And it is not the same like your second line:
matrix[3][1:] = matrix[3][0:-1]

Added.
In first example you insert some data from 1. position to the end:
a = [1, 2, 3, 4]
a[1:] = [100, 200, 300]
print(a)
OUTPUT: [1, 100, 200, 300]

In the second case you insert a value between the 0. and 1. position:
a = [1, 2, 3, 4]
a[1:0] = [100, 200, 300]
print(a)
OUTPUT: [1,100, 200, 300, 2, 3, 4]


text:
Q: How can I format percentages in Excel so that they stay percentages on an iPhone? I have a report built in Excel.  One of the summary columns is presented as a percentage.  This works fine.  Unless you open the file on a mobile phone.  Is there something I can do to fix this?

A: use polaris office to view excel reports
https://itunes.apple.com/us/app/polaris-office-for-pdf-+-microsoft/id698070860?mt=8


text:
Q: Ninject Interception dynamic proxy problems I'm trying to set up interception to work with Ninject which we have been using as our dependency injection framework for a while.
I have downloaded the interception extension from NuGet and tried it with both the Castle Dynamicproxy implementation and the LinFu implementation but could not be either to work with our applications.
Castle gave an error when creating a proxy on a class that did not have a parameterless constructor, since all the service objects have their dependencies injected via the constructor this is a problem. The error is:
System.ArgumentException: Can not instantiate proxy of class: emedia.RapidSystems.Subscriber.Presenters.RRSubmissionPresenter.
Could not find a parameterless constructor.
Parameter name: constructorArguments
The LinFu interceptor worked better, right up until the code called a method with a generic parameter then it gave me the following:
System.ArgumentException: Generic types are not valid.
Parameter name: methodInfo
Here is a simplified version code for one of the classes I am trying to intercept:
[LogCalls]
public class Repository<T> : IRepository<T>
        where T : class
{
    public virtual T GetEntity<TKey>(ObjectContext context, TKey key)
    {
        var entity = GetEntity(context, key, _emptyLoadingStrategy);
        return entity;
    }

    public virtual IQueryable<T> GetAll(ObjectContext context)
    {
        var query = GetAll(context, _emptyLoadingStrategy);
        return query;
    }

    public virtual T Add(ObjectContext context, T entity)
    {
        context.AddObject(EntitySetName(context), entity);
        return entity;
    }

     //other code goes here

}

Add and GetAll work fine but the error happens when GetEntity is called on the proxy.
At this point I'm stuck, as neither interceptor works with the code base. Has anyone got Ninject interception working with a real complex production system, rather than a simple demo class, and if so how? I don't mind which interceptor I use as long as it works.
Or is interception with Ninject just not mature enough yet, and do I need to look at replacing the whole thing with something else like Unity?

A: Use version 3.0.0-rc2. it adds support for interface proxies to dynamic proxy


text:
Q: Checking if user is admin or not in PHP I  am fairly new to php and I am trying to do my school assignment but teacher just says "google it" and I seriously can't find an asnwer that works for me.
Here's my login.php (please excuse the Swedish notes in it, those are for my teacher)
<?php  //Start the Session
session_start();
require('connect.php');
//3. If the form is submitted or not.
//3.1 If the form is submitted
if (isset($_POST['username']) and isset($_POST['password'])){
//Sätter form värderna i variabler
$username = $_POST['username'];
$password = $_POST['password'];
//Kollar om variblerna redan finns i databasen
$query = "SELECT * FROM `user` WHERE username='$username' and password='$password'";

$result = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($result);
//Kollar om bägge värdena är likadana i databasen och sedan skapar sessionen om de är det.
if ($count == 1){
$_SESSION['loggedin'] = 1;
$_SESSION['username'] = $username;
}else{
//3.1.3 Om värdena inte stämmer kommer ett fel medelande att skickas till användaren.
echo "Invalid Login Credentials.";
}
}
//Om han loggar in så skickas han vidare till protected.php
if ($_SESSION['loggedin'] == 1) {
header('Location: protected.php');
}else{
?>

Here's the page that is accessed after you've logged in(the protected page)
<?php

    session_start();
    require('connect.php');
    // startar sessionen så att man kan använda session variablerna
    // Inkluderar connect.php för att ansluta till databasen

    if ($_SESSION['loggedin'] != 1) {
        //Om loggedin är inte lika med 1 skickas han till första login sidan

        header('Location: index.php');
        exit;
    }

?>

<title>Logged in!</title>
ASDSDFSDF
Log out

<?php
    $sql = "SELECT admin FROM `user` WHERE username='$_SESSION['username']'";
    $result = mysql_query($sql);
    $admin = mysql_fetch_array($result);
    $_SESSION['admin'] = $admin['admin'];
    if ($_SESSION['admin']) == 1 {
    echo "You are an Admin!";
    }else{
    echo "You are a normal user";
    }
?>

I don't understand how this code won't work. :/
 <?php
        $sql = "SELECT admin FROM `user` WHERE username='$_SESSION['username']'";
        $result = mysql_query($sql);
        $admin = mysql_fetch_array($result);
        $_SESSION['admin'] = $admin['admin'];
        if ($_SESSION['admin']) == 1 {
        echo "You are an Admin!";
        }else{
        echo "You are a normal user";
        }

A: Please check again this code:
$sql = "SELECT admin FROM `user` WHERE username='$_SESSION['username']'";

There maybe 2 mistakes here:

*

*You cannot interpolate $_SESSION in ' ';

*When in quote, "$_SESSION['username']" should be change to "$_SESSION[username]";

To recap, you can use the way below:
$sql = "SELECT admin FROM `user` WHERE username='".$_SESSION['username']."'";

By this way you can keep the original method of SQL that have the quote:
WHERE username='xxx'

A: Try this code:
$sql = "SELECT admin FROM user WHERE username='".$_SESSION['username']."'"; //  username='".$_SESSION['username']."'"   instead username='$_SESSION['username']'";

$result = mysql_query($sql);
$admin = mysql_fetch_array($result);

$_SESSION['admin'] = $admin['admin'];
if ($_SESSION['admin'] == 1) {  // Be carefull you had if($_SESSION['admin']) == 1 {  leaving "1" outside of the if
echo "You are an Admin!";
}else{
echo "You are a normal user";
}

Note: Tell your teacher that is time for her to stop teaching mysql and instead teach mysqli or PDO

A: Don't worry about mysqli and other comments, this code works just fine for learning purposes. Here is it explained line by line:
    $sql = "SELECT admin FROM `user` WHERE username='$_SESSION['username']'";
    $result = mysql_query($sql);

Perform an sql query searching for user with username stored in session['username']. It doesn't fetch all the columns, just the admin column, which says if the user is admin or isnt.
    $admin = mysql_fetch_array($result);

This just loads the sql result into an array. If the user with the stored username is found, it will be just an array with one boolean variable: 1 or 0
    $_SESSION['admin'] = $admin['admin'];

Stores the boolean variable into session
    if ($_SESSION['admin']) == 1 {
        echo "You are an Admin!";
    }else{
        echo "You are a normal user";
    }

prints the result of the operation.
There are several caveats however. For example what happens if the username doesnt exist. If you receive some errors, please try to print out everything and send the error messages.

A: Your code is not safe because:

*

*You can be injected (mySql Injection)

*Your password is stored as plain text

Moreover, I suggest that you use MVC pattern.
login.php:
<?php
session_start();
require("functions.php"); // file with your functions

if ($_SESSION["logged"]) // if already logged, redirect to admin page
    header("Location: ./admin.php");
else
{
    if ($_SERVER["REQUEST_METHOD"] == "POST")
    {
        // logIn function in "functions.php" file, returns true if correctly logged
        $login = logIn($_POST["user"], $_POST["password"]);
        if ($login === true)
        {
            $_SESSION["logged"] = true;
            header("Location: ./admin.php");
        }
        else
        {
            // login failed, show error page

            $error = $login;
            // html code for header
            require("templates/header.php");

            // html code for body that will display $error
            require("templates/error_page.php");

            // html code for last part of the page
            require("templates/footer.php");
        }
    }
    else
    {
        // No POST request, so the user must fill the form yet

        require("templates/header.php");

        // Contains html code for login form
        require("templates/login_form.php");

        require("templates/footer.php");
    }
}
?>

functions.php (file used to store your php functions):
function logIn($username, $pass)
{
    if ($username == "" || $pass == "")
        return "Please, fill every text field.";
    $pdo = connectToServer();

    $stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
    $stmt->execute(array("username" => $username));

    $fetch = $stmt->fetch();

    $numberRows = $stmt->rowCount();
    if ($numberRows > 0)
    {
        // user exists, check for password
        $crypted = hash('ripemd160', $fetch["salt"] . $pass);
        /* NOTE: you must have encrypted passwords in the same way
           at the moment of signing up.
           Without encryption (not recommendable) you can use:
           $crypted = $pass;
        */

        if ($crypted == $fetch["pass"])
        {
            // Logged, do whatever you want and return true
            return true;
        }
        else
            return "You have inserted a wrong username or password";
     }
     else
         return "You have inserted a wrong username or password";
}


text:
Q: How to update column value of one dataframe with other dataframe value in pandas? I have following 2 dataframes -
df1:
                            job                                              e_msg
0  f_maf_crm_customer_request_global_jgvcc  permission denied for relation f_maf_custome

df2:
                 master_job                           error_msg      current_count
0    JGCC_Genesys_Conversations_Aggregates
1  f_maf_crm_customer_request_global_jgvcc                              100

if df1 is having the same job name so df2 should update error_msg with df1.e_msg and current_count should change as 0.
In final output:
             master_job                               error_msg                            current_count
0    JGCC_Genesys_Conversations_Aggregates
1  f_maf_crm_customer_request_global_jgvcc  permission denied for relation f_maf_custome     0

A: You can try an outer join on the two dataframes from the merge function in pandas. If you don't know what joins are then refer to this webpage.
Code -
merged_df = pd.merge(df1, df2, on = "master_job", how = "outer")
merged_df

Output -

master_job
error_msg_x
current_count

0
JGCC_Genesys_Conversations_Aggregates
nan

1
f_maf_crm_customer_request_global_jgvcc
permission denied for relation f_maf_custome
100

Here we are getting two error_msg columns because error_msg_x is from df1 and error_msg_y is from df2. Because error_msg_y isn't of any use to use, we can drop it using the code below.
merged_df = merged_df.drop(columns = "error_msg_y")

We can merge the two dataframes and drop the error_msg_y column in just one line using this code,
merged_df = pd.merge(df1, df2, on = "master_job", how = "right").drop(columns = "error_msg_y")

A: A simple approach would be this one liner.
df2.loc[df2.master_job.isin(df1.job), ['error_msg', 'current_count']] = [df1['e_msg'].values, 0]

This gives the output you want. Please note that I have abbreviated the error_msg for brevity. You can test it out yourself and see that the output message is the same as the one you are using.
    job                                     error_msg             current_count
0   JGCC_Genesys_Conversations_Aggregates
1   f_maf_crm_customer_request_global_jgvcc permission denied...    0.0

What that single line of code does is quite simple. It checks if the records in df1 exist in df2 and if it does, then the values in df2 are changed accordingly to match your requirement. You can read more about isin here.


text:
Q: Save data to a hosted .dat File I am saving Data into a .dat file using this Piece of Code:
void saveFile () {

    try {
        FileOutputStream fos = new FileOutputStream ("File.dat", true);
        DataOutputStream dos = new DataOutputStream (fos);
        dos.writeUTF (saves[count][0]);
        dos.writeUTF (saves[count][1]);
        dos.writeUTF (saves[count][2]);
        dos.writeUTF (saves[count][3]);
        dos.writeUTF (saves[count][4]);
        dos.writeUTF (saves[count][5]);
        JOptionPane.showMessageDialog (this, "The Record has been Saved Successfully",
                    "Record Saved", JOptionPane.PLAIN_MESSAGE);
        txtClear ();
        dos.close();
        fos.close();
    }
    catch (IOException ioe) {
        JOptionPane.showMessageDialog (this, "There are Some Problem with File",
                    "Problem", JOptionPane.PLAIN_MESSAGE);
    }

}

I need to have the .dat File Hosted on some Online Domain Say http://Domain.com/File.dat
What would I need to do to the Piece of code In Order to be able to Accomplish the Save?

A: 1- Either the "domain" is managed on the same server, then you just put the file at the correct place (usually under 'www' folder, check your web server configuration)
2- It's another computer, then you'll have to transfer the file there (FTP? Another Java piece of code using sockets? API given by the host? ...)

Unrelated but you should close your Streams in a finally block
xxxxxxxStream s = null;
try {
  s = new xxxxxxxStream();
} catch (WhateverException we) {
  ...
} finally {
  s.close();
}


text:
Q: System.exit(0); not working for hang man game everything works perfectly fine, I just can't get the program to finish when instead of entering a letter the user typer the number 0. I've tried System.exit(0); and its not working, if you have any recommendations on what i can do i would aprecciate it!!
Here is what i have:
package com.mycompany.reto66;
import java.io.*;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;

public class Reto66
{public static BufferedReader entrada = new BufferedReader(new InputStreamReader(System.in));

private static String[] palabrasF = { "casa", "gato", "hola", "cuba"};
private static String[] palabrasII = { "caballos", "elefante", "langosta", "mariposa"};
private static String[] palabrasA = { "amarillistas", "circulatorio", "evangelistas", "californiana"};

private static ArrayList<String> palabras = new ArrayList<>();
private static String palabraB;
private static String adivinadas;
private static ArrayList<Character> letrAA = new ArrayList<>();
private static int intentos = 6;
private static int intentados = intentos;

public static void main(String[] args) throws IOException
{
    int menu;
    do
    {
        System.out.println(" ");
        System.out.println("¡Bienvenido al juego ahorcado!");
        System.out.println("Eliga un nivel: ");
        System.out.println("1) Fácil");
        System.out.println("2) Intermedio");
        System.out.println("3) Avanzado");
        System.out.println("0) Salir");
        System.out.print("Respuesta: ");
        menu = Integer.parseInt(entrada.readLine());

        switch(menu)
        {
            case 1:
              emppalabraF();
              palabraB = palaram();
              adivinadas = new String(new char[palabraB.length()]).replace("\0", "X");

               while (intentados > 0 && !palabraB.equals(adivinadas)) {
                   System.out.println("Palabra: " + adivinadas);
                   System.out.println("intentos: " + intentados);
                   System.out.println("Letras adivinadas: " + letrAA.toString());
                   System.out.print("Introduce letra: ");
                   char adv = entrada.readLine().charAt(0);

                   if(adv == 0){
                       System.exit(0);
                   }

                   if (letrAA.contains(adv)) {
                       System.out.println("Ya has usado esa letra antes, intenta de nuevo.");
                   } else {
                       letrAA.add(adv);
                       if (palabraB.contains(Character.toString(adv))) {
                           StringBuilder newpal = new StringBuilder(adivinadas);
                           for (int i = 0; i < palabraB.length(); i++) {if (palabraB.charAt(i) == adv) {
                               newpal.setCharAt(i, adv);
                    }
                           }adivinadas = newpal.toString();
                           System.out.println("Correcto!");
                        } else {
                           intentados--;
                           System.out.println("Intentalo de nuevo!");
                       }
                    }
                }

                if (palabraB.equals(adivinadas)) {
                    System.out.println("Felicidades! Adivinaste la palabra: " + palabraB);
                } else {
                    System.out.println("Se acabaron los intentos, la palabra era: " + palabraB);
                }

            break;

            case 2:
              emppalabraII();
              palabraB = palaram2();
              adivinadas = new String(new char[palabraB.length()]).replace("\0", "X");

               while (intentados > 0 && !palabraB.equals(adivinadas)) {
                   System.out.println("Palabra: " + adivinadas);
                   System.out.println("intentos: " + intentados);
                   System.out.println("Letras adivinadas: " + letrAA.toString());
                   System.out.print("Introduce letra: ");
                   char adv = entrada.readLine().charAt(0);

                   if(adv == 0) {
                       System.exit(0);
                   }

                   if (letrAA.contains(adv)) {
                       System.out.println("Ya has usado esa letra antes, intenta de nuevo.");
                   } else {
                       letrAA.add(adv);
                       if (palabraB.contains(Character.toString(adv))) {
                           StringBuilder newpal = new StringBuilder(adivinadas);
                           for (int i = 0; i < palabraB.length(); i++) {if (palabraB.charAt(i) == adv) {
                               newpal.setCharAt(i, adv);
                    }
                           }adivinadas = newpal.toString();
                           System.out.println("Correcto!");
                        } else {
                           intentados--;
                           System.out.println("Intentalo de nuevo!");
                       }
                    }
                }

                if (palabraB.equals(adivinadas)) {
                    System.out.println("Felicidades! Adivinaste la palabra: " + palabraB);
                } else {
                    System.out.println("Se acabaron los intentos, la palabra era: " + palabraB);
                }
            break;

            case 3:
               emppalabraA();
              palabraB = palaram3();
              adivinadas = new String(new char[palabraB.length()]).replace("\0", "X");

               while (intentados > 0 && !palabraB.equals(adivinadas)) {
                   System.out.println("Palabra: " + adivinadas);
                   System.out.println("intentos: " + intentados);
                   System.out.println("Letras adivinadas: " + letrAA.toString());
                   System.out.print("Introduce letra: ");
                   char adv = entrada.readLine().charAt(0);

                   if(adv == 0){
                       System.exit(0);
                   }

                   if (letrAA.contains(adv)) {
                       System.out.println("Ya has usado esa letra antes, intenta de nuevo.");
                   } else {
                       letrAA.add(adv);
                       if (palabraB.contains(Character.toString(adv))) {
                           StringBuilder newpal = new StringBuilder(adivinadas);
                           for (int i = 0; i < palabraB.length(); i++) {if (palabraB.charAt(i) == adv) {
                               newpal.setCharAt(i, adv);
                    }
                           }adivinadas = newpal.toString();
                           System.out.println("Correcto!");
                        } else {
                           intentados--;
                           System.out.println("Intentalo de nuevo!");
                       }
                    }
                }

                if (palabraB.equals(adivinadas)) {
                    System.out.println("Felicidades! Adivinaste la palabra: " + palabraB);
                } else {
                    System.out.println("Se acabaron los intentos, la palabra era: " + palabraB);
                }
            break;
        }

    }while (menu!=0);

}

//para nivel facil
private static void emppalabraF() {
    for (String palabra : palabrasF) {
        palabras.add(palabra);
    }
}

private static String palaram() {
    int index = (int) (Math.random() * palabras.size());
    return palabras.get(index);
}

//para nivel intermedio
private static void emppalabraII() {
    for (String palabra : palabrasII) {
        palabras.add(palabra);
    }
}

private static String palaram2() {
    int index = (int) (Math.random() * palabras.size());
    return palabras.get(index);
}

//para nivel avanzado
private static void emppalabraA() {
    for (String palabra : palabrasA) {
        palabras.add(palabra);
    }
}

private static String palaram3() {
    int index = (int) (Math.random() * palabras.size());
    return palabras.get(index);
}

}
that's my whole code, and this
if(adv == 0){
                   System.exit(0);
               }

is the part that i cant get right.


text:
Q: how to change db user name and db group name in Sybase Anywhere 11 all!
I have a db with tables User and Group, which represent entities in some application. But at the same time there are database users and database groups with the same names. I need to anonymize the database. It's easy to change db tables, e.g. update User set "Name" = "John",... where Id = 100500
But what to do with db users and db groups?
My first thought was to drop user and that create a new one:
drop user John;
create user njoh identified by 'pswd' login policy "root";

But belonging to groups is lost in the approach.
Is there any kind of rename method for db users in Sybase Anywhere 11?
Also I don't know how to change last log-in time and comments for a db user.
The same problem with groups. I didn't try to 'drop groups', 'cause I don't know if there is a possibility in Sybase Anywhere 11.
Could anyone tell me the truth - does the problem have a solution?

A: No, there is no way to rename an existing user. You can certainly drop it and create a new user but like you said, any group memberships are lost, as are permissions granted on objects like tables and procedures.
The only way to change the last login time for a user is by logging in. You can change the comment on a user by using comment on user is '<string>'.
There is no drop group statement - a group in SQL Anywhere (versions 12 and older) is simply a user with "group authority", so to drop a group you would use revoke connect from <group name>.
Disclaimer: I work for SAP in SQL Anywhere engineering.


text:
Q: Getting unique value records from a field Building a desktop application using C#.net and ArcObjects. I'm trying to retrieve records from a shapefile using IQueryFilter. Having trouble writing the where clause in my scenario and the applicable logic.
Here is the scenario:
I have a 'Category' and "Completed" field, (both are of type string).  What I need to do is, for a given category to see whether all the values in the completed field are unique. If values are not unique I need to display those records out.
Sample data

In the above example Category B and C does not have unique values. So all these records for B and C should be displayed.
I suppose a using an IQueryFilter interface should work. But puzzled on how I can achieve this by using a correct where clause. (I just need to get where the combination of Category and Completed fields are not unique)
Please help...

A: What petr k. has said is correct, But I'll like to expand it further.
I would do this by having multiple Queries.
You can get Distinct values from IDataStatistics.UniqueValues Property. So I would first get the Unique values from the Category field.
I would then loop on that and get the Uniquevaluecount for the Completed Field, (while getting the cursor with only those features with the particular Category)
This way you can find out which category has more than one Unique value.

A: You are hitting the limits of querying data using ArcObjects. ArcObjects will not let you write atribrary query using IQueryFilter, you are limited to only very simple queries.
I will not try to compose the query for you since others have already provided some answers. But, let me outline more complex querying possibilities in ArcObjects, even though they are not directly related to your particular scenario. You or someone else might find this information useful.

*

*More complex queries involving table joins can be performed using query defs, i.e. the IQueryDef interface. Refence to this interface can be obtained by calling IFeatureWorkspace.CreateQueryDef.

*If you need ORDER BY, GROUP BY on query filters, you can use IQueryFilterDefinition.PostfixClause. However, you will not be able to, for example, retrieve the count of rows within a group, because you cannot put expressions like COUNT(*) into the query filter's SubFields. It doesn't work because there is not any field named COUNT(*) in the table you are querying. You also cannot put a HAVING expression into the query filter's WhereClause. In real world applications, this effectively renders IQueryFilterDefinition useless for any grouping purposes.

*At ArcGIS 10, you can use IQueryFilterDefinition2.PrefixClause to specify clauses like DISTINCT.

*You can overcome some of the difficulties with query filters and GROUP BY with query defs, but only in ArcGIS 10. There is a new interface IQueryDef2 which lets you specify both PrefixClause and PostfixClause on query defs. Query defs do not force you to query only for fields which actually exist on a table, so you are able to compose queries like, say, SELECT A, COUNT(*) FROM TABLE GROUP BY A.
Now, you probably understand that none of this information is particularly helpful in your solution. There are basically few things which you CAN do:

*

*Examining the table in a single query, storing data in intermediate data structures (lists, dictionaries) in order to identify groups and records within these groups. This could be quite memory intensive if you have lots of data.

*Break down your problem into multiple queries and execute them one by one. This could also affect performance big time, but it might not be a problem if the amount of data is low.

*Create a database view (using queries from the other answers, for example) and then query it using ArcObjects. You'll be able to open views just like any other tables and query them using both IQueryFilter or IQueryDef. This has the benefit of making use of existing database capabilities, but is a pain if you have limited database administration access. Works only on SDE geodatabases and your data must not be versioned. Otherwise, you are out of luck.

A: There's got to be a better way than what I'm about to post - someone cleverer in the charms of SQL can undoubtedly fix this up:
SELECT * FROM table WHERE category IN (
  SELECT category FROM (
    SELECT category, COUNT(*) AS c2 FROM (
      SELECT category, completed, COUNT(*) AS c1 FROM table
      GROUP BY category, completed
    ) AS t1
    GROUP BY category
  HAVING COUNT(*) > 1
  ) AS t2
)

This does have the intended result of displaying all the records of B & C, since they have multiple values for "completed", but it's at the expense of being nearly incomprehensible.
B   No
C   Yes
B   No
B   Yes
C   No
C   Yes

If you wanted to make it less awful, you could remove the outer query, which would give you the records back that were failing, and their count.
I've tested the above on SQL Server, for what it's worth, but not Oracle. And it almost certainly won't work in Access. Any takers for simplifying this?

A: Since you asked for C#, below is a way to do this with System.Collections.Generic.  I haven't tested it.
public void Test()
{
    try
    {
        var fLayer = ArcMap.Document.Maps.get_Item(0).get_Layer(0) as IFeatureLayer;
        var categories = Categorize((ITable)fLayer.FeatureClass, "Category", "Completed");
        foreach (KeyValuePair<string, List<string>> kvp in categories)
        {
            if (kvp.Value.Count > 1)
                Debug.Print("Category {0} has {1} unique values", kvp.Key, kvp.Value.Count);
        }
    }
    catch (Exception ex)
    {
        Debug.Print(ex.Message);
    }
}

public Dictionary<string, List<string>> Categorize(ITable table, string categoryFld, string otherFld)
{
    var outList = new Dictionary<string, List<string>>();
    IQueryFilter qf = new QueryFilter();
    qf.SubFields = String.Format("{0},{1}", categoryFld, otherFld);

    int idxCat = FindField(table,categoryFld);
    int idxOther = FindField(table,otherFld);
    ICursor cur = null;
    // **edited to release cursor in a finally block**
    try
    {
        cur = table.Search(qf, true);
        IRow row;
        while ((row = cur.NextRow()) != null)
        {
            string category = GetStrVal(row, idxCat);
            string other = GetStrVal(row, idxOther);
            if (!outList.ContainsKey(category))
                outList.Add(category, new List<string>());
            if (!outList[category].Contains(other))
                outList[category].Add(other);
        }
    }
    catch
    {
        throw;
    }
    finally
    {
        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(cur);
    }
    return outList;
}

public static string GetStrVal(IRow row, int idx)
{
    return row.get_Value(idx) is DBNull ? "<Null>" : row.get_Value(idx).ToString();
}

public static int FindField(ITable table, string fldName)
{
    int idx = table.FindField(fldName);
    if(idx == -1)
        throw new Exception(String.Format("field {0} not found on table {1}",
            fldName,((IDataset)table).Name));
    return idx;
}

A: It's probably impossible to write a LINQ provider, but here's a custom ORM for geodatabase.  It works with anything that implements IFeatureClass or ITable.
http://jshirota.github.com/Earthworm/


text:
Q: Deploying to AWS Lambda in VS2019 with API Gateway gives {"message":"Internal Server Error"} Testing the Lambda itself works from the Lambda console; I pass in "asdf" and get "ASDF" as a response.
However when I add an API Gateway:

*

*Go to Lambda console: https://us-west-2.console.aws.amazon.com/lambda/home

*Add trigger

*API Gateway

*HTTP API (REST API has the same issue)

*Open

*CORS enabled

I get a {"message":"Internal Server Error"}
This code works (removing the input parameter):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

using Amazon.Lambda.Core;
using Complyify.Contexts;
using Complyify.Engines;

// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace ComplyifyLambda
{
    public class Function
    {
        public string FunctionHandler(/* string input, */ ILambdaContext context)
        {
            return "Hello, World";
        }
    }
}

This code does not work:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

using Amazon.Lambda.Core;
using Complyify.Contexts;
using Complyify.Engines;

// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace ComplyifyLambda
{
    public class Function
    {
        public string FunctionHandler(string input, ILambdaContext context)
        {
            return input?.ToUpper();
        }
    }
}

A: As @zaitsman pointed out, I need to use the Amazon.Lambda.APIGatewayEvents NuGet package.
I found this answer useful.
This code worked:
        public APIGatewayProxyResponse FunctionHandler(APIGatewayProxyRequest request, ILambdaContext context)
        {
            var bodyString = request?.Body;

            if (!string.IsNullOrEmpty(bodyString))
            {
                return new APIGatewayProxyResponse
                {
                    StatusCode = 200,
                    Body = bodyString.ToUpper()
                };
            }

            return new APIGatewayProxyResponse
            {
                StatusCode = 200,
                Body = "No body!"
            };
        }


text:
Q: How to make parallel HTTP requests to Django within the same session? Lets say I have a webpage with 3 tables which I load through ajax. I make 3 async ajax calls, but since they are coming from the same session, they are actually run one after another on the server, not in parallel as I would like.
I don't need to worry about concurrent data corruption, the 3 requests are completely independent read only requests, I only need the session to verify if the user is still logged in.
So the question is: how do I make the real parallel http requests on nginx + uwsgi + django stack for the same user session? If it's indeed not possible, what would be the best way to make it possible? I searched everywhere for any hints, and I see people saying it is a limitation of: nginx, uwsgi, django, python, a browser, a programmer, without any real answers how to solve it.


text:
Q: Does xsd:choice require one or the other, or are both allowed too? I have two complex types and an element in an XML can take any of these two types. And sometimes, I know which one of these type the element can take. So accordingly I define in XSD.
<xs:complexType name="A">
    <xs:sequence>
        <xs:element name="one" type="onetype" minOccurs="0"
            maxOccurs="1" />
        <xs:element name="two" type="twotype" minOccurs="0"
            maxOccurs="unbounded" />
        <xs:element name="three" type="country" minOccurs="0"
            maxOccurs="1" />
    </xs:sequence>
    <xs:attribute name="oneattr" type="xs:string" />
    <xs:attribute name="twoattr" type="xs:string" />
</xs:complexType>

<xs:complexType name="B">
    <xs:sequence>
        <xs:element name="four" type="fourtype" minOccurs="0"
            maxOccurs="1" />
    </xs:sequence>
    <xs:attribute name="fourattr" type="xs:string" />
</xs:complexType>

But sometimes i don't, so i have created another type like AorB.
<xs:complexType name="AorB">
        <xs:choice>
            <xs:sequence>
                <xs:element name="one" type="onetype" minOccurs="0"
                    maxOccurs="1" />
                <xs:element name="two" type="twotype" minOccurs="0"
                    maxOccurs="unbounded" />
                <xs:element name="three" type="country" minOccurs="0"
                    maxOccurs="1" />
            </xs:sequence>
            <xs:sequence>
                <xs:element name="four" type="fourtype" minOccurs="0"
                    maxOccurs="1" />
            </xs:sequence>
        </xs:choice>
        <xs:attribute name="oneattr" type="xs:string" />
        <xs:attribute name="twoattr" type="xs:string" />
        <xs:attribute name="fourattr" type="xs:string" />
    </xs:complexType>

So my question is this:  Of the two sequences inside xsd:choice, when the XML is validated, does it validate true if XML contains elements from both sequence or only one ?

A: xsd:choice requires one or the other

when the XML is validated, does it validate true if XML contains
  elements from both sequence or only one ?

The default of @minOccurs on xsd:choice is 1, which means one or the other, not both, of the children content models apply.  If you add minOccurs="value" for value greater than 1 or for value equal to unbounded, then multiple occurrences of its children are allowed.  Note, however, that the second occurrence might be a repeat of the child chosen from the first occurrence.


text:
Q: Value of type 'Double' has no member 'roundDouble' I am trying to code a weather app in swift and I keep getting this

error: Value of type 'Double' has no member 'roundDouble'.

This is the line resulting in the error
WeatherRow(logo: "thermometer", name: "Max temp", value: (weather.main.tempMax.roundDouble() + "°"))

struct MainResponse: Decodable {
    var temp: Double
    var feels_like: Double
    var temp_min: Double
    var temp_max: Double
    var pressure: Double
    var humidity: Double
}

A: The syntax to round is round(var), not var.roundDouble(). (example)
Using the following function call: round(weather.main.tempMax)

A: Instead of converting a Double to String, use a formatter. In this case you can save yourself some work by using MeasurementFormatter, example:
let formatter = MeasurementFormatter()
formatter.numberFormatter.maximumFractionDigits = 0

let maxTemperature = 42.54
let measurement = Measurement(
    value: maxTemperature,
    unit: UnitTemperature.celsius
)

let formattedTemperature = formatter.string(from: measurement)
print(formattedTemperature) // 43°C

A: In most cases you should not round floats/doubles, they are only approximations of real number, for example a double can not exactly store 1/10 for the same reason you can not store 1/3 with a finite number of decimal points, you are going to get gaps, and just have a less accurate value. The main reason to round is for display purposes, and so you should round when turning your value into a string to display, NumberFormatter has lots of control over this, you can also us c like print formatting options like "%.3f"


text:
Q: SSIS and SQL Agent - running jobs using proxy vs using MSA We have multiple servers, each with its own SQL Server instance.
We have external companies that develop applications for us. This companies deploy SSIS packages and run them via SQL Agent.
I'm wondering how our setup should look like security vise.
Scenario 1

*

*SQL Agent Service account - Local Virtual Account

*SSIS login - personal domain login for each employee

*Job owner - personal domain account of whoever created it

*Step run as - domain proxy account

It seems quite "normal" scenario, but I'm not sure if it is still relevant. Microsoft changed some things concerning security and introduced Virtual and Managed Service Accounts couple years back. Yet many resources found online still do not mention them and it seems like they treat default service account the old way. So maybe it is now acceptable to use default SQL Service account to run the jobs? Like in scenario 2.
Scenario 2

*

*SQL Agent Service account - Local Virtual Account

*SSIS login - personal domain login for each employee

*Job owner - personal domain account of whoever created it

*Step run as - without proxy - SQL Agent Service account

This uses Virtual Account to run the jobs, but Microsoft documentation mention that in case we need to access remote resources we should use MSA instead. And it is the case for us.

*When resources external to the SQL Server computer are needed, Microsoft recommends using a Managed Service Account (MSA), configured with the minimum privileges necessary. ** When installed on a Domain Controller, a virtual account as the service account isn't supported.

Scenario 3

*

*SQL Agent Service account - Managed Service Account (MSA)

*SSIS login - personal domain login for each employee

*Job owner - personal domain account of whoever created it

*Step run as - without proxy - SQL Agent Service account (MSA)

There is also a question about who should own the job. There is a possibility of creating generic SSIS login that would be used by everyone to deploy packages and this login would own all the jobs steps.
Scenario 4

*

*SQL Agent Service account - Managed Service Account (MSA)

*SSIS login - generic domain login for working with SSIS

*Job owner - SSIS domain login

*Step run as - without proxy - SQL Agent Service account (MSA)

Which scenario would you recommend? Or maybe there is a different preferable scenario?


text:
Q: MS SQL Server 2005 - Grouping Similar Data I am trying to find a solution to the following type of groupings:
My Data
Formula #   Date
1           2016-01-02 12:05:00
1           2016-01-02 12:07:00
2           2016-01-02 12:10:00
2           2016-01-02 12:15:00
3           2016-01-02 12:25:00
3           2016-01-02 12:30:00
3           2016-01-02 12:50:00
3           2016-01-02 12:55:00
2           2016-01-02 13:05:00
2           2016-01-02 13:25:00
2           2016-01-02 13:40:00

And I am trying to get a result like this:
Formula     Count  Start Date             End Date
1           2      2016-01-02 12:05:00    2016-01-02 12:07:00
2           2      2016-01-02 12:10:00    2016-01-02 12:15:00
3           4      2016-01-02 12:25:00    2016-01-02 12:55:00
2           3      2016-01-02 13:05:00    2016-01-02 13:40:00

I've tried various things and while I can roll up the similar formula numbers, I cannot seem to get it to sort out to get the results in the format I've listed. I'm also not sure at all how to get the starting and ending date of the groups of data..
Any thoughts or help would be greatly appreciated..

A: The below query will group by the formula and provide the count as well as min and max dates. Based on the data in the table there is no way to know that there are supposed to be 2 separate sets of data for Formula #2, so it is being grouped into one row.
SELECT
    [Formula]
    ,COUNT([Formula]) AS [COUNT]
    ,MIN([Date]) AS [MIN_DATE]
    ,MAX([Date]) AS [MAX_DATE]
FROM
    #test_table
GROUP BY
    [Formula]


text:
Q: Prove $NP$ is parallel to $BC$ Given triangle $\triangle ABC$, let $M$ be the midpoint of $BC$, $I$ the incenter of $\triangle ABC$, $L$ the foot of the external $A$ angle bissector on $BC$ ($AL \perp AI$).
Also, define:
$N = CI \cap AL$ and $P = AB \cap MI$. Prove that $NP \parallel BC$

this smells like projective geometry, I think the key is to assume lines $NP$ and $BC$ meet on $X$ and then show that $(B,C;M,X) = -1$ but I haven't found this projection yet. Projection (centered at $I$) of point $B$ on $NP$ is weird and I think $NP \cap AI$ doesn't help much. Any suggestions?
Very well observed: $N$ is the $C$ ex-incenter

A: Sketch. $N$ is the $C$-excenter of the triangle $ABC$ as intersection of angle bissectors $AL$ and $CI$. Hence, $\angle IBN=90^{\circ}$. Now choose $P\in AB$ usch that $NP'\parallel BC$, then it is easy to check that $NP'=P'B$. Besides that, since $\angle IBN=90^{\circ}$ the line $BI$ intersects $NP'$ at point $R$ such that $P'$ is the midpoint of $NR$. Now $NRCB$ is a trapezoid, so the midpoints of $NR$ and $BC$ and $I=NC\cap BR$ are collinear. Thus, $P'$, $M$ and $I$ are collinear, so $P=P'$ and $NP\parallel BC$, as desired.

A: I found the answer and I will not give points to answers after this one.
$R = NC \cap AB$, then $(C,R;I,Q) = -1$ (because $Q$ is the $C$-exincenter and we have $I$ and $Q$ as feet of the angle bissectors of $\triangle BCR$)
$-1 =(C,R;I,Q) \frac{P}{\overline \wedge} (C,B;M,PQ \cap BC)$
therefore $PQ \cap BC = \infty \iff PQ \parallel BC$


text:
Q: Prove that $\sum_{r=1}^n r\binom n r^2 = n\binom{2n-1}{n-1}$ Prove that $\sum_{r=1}^n r\binom n r^2 = n\binom{2n-1}{n-1}$
I tried: $\sum_{r=1}^n r\binom n r^2 = n\sum_{r=1}^n \binom {n-1}{r-1}\binom n r$ using the identity $\binom n r = \frac n r \binom {n-1}{r-1}$ for $r \ge 1$.
Not sure how to proceed from there. I tried expanding the RHS but can't seem to find a way to cancel out the factorials.

A: So we want to show that
$$\sum^n_{r=1}\binom{n-1}{r-1}\binom{n}{r}=\binom{2n-1}{n-1},$$
or
$$\sum^n_{r=1}\binom{n-1}{n-r}\binom{n}{r}=\binom{2n-1}{n}.$$
Now, how many ways to choose a committee of $n$ people out of $n-1$ males and $n$ females? Consider the cases where there are $r$ females in the committee.

A: A shop has $n$ different doughnuts and $n$ different muffins. I want to choose a total of $n$ items, including at least one doughnut, and I would like to have one doughnut to eat right away, and the remaining $n-1$ put in a bag. How many ways can this be done?
The doughnut I eat right away can be chosen in $n$ ways, and for each of these ways there are $\binom{2n-1}{n-1}$ ways to choose the remaining items.
Let us count another way. If we decide to get $r$ doughnuts, that can be done in $\binom{n}{r}$ ways, and then the doughnut we eat right away can be chosen in $r$ ways. The $n-r$ muffins can be chosen in $\binom{n}{n-r}$ ways, that is, in $\binom{n}{r}$ ways. So there are $r\binom{n}{r}\binom{n}{r}$ to carry out the task while choosing $r$ doughnuts. Add up, $r=1$ to $n$.

A: Using Vandermonde's Identity, we get
$$
\begin{align}
\sum_{r=0}^nr\binom{n}{r}^2
&=\sum_{r=0}^nr\binom{n}{r}\binom{n}{n-r}\\
&=n\sum_{r=0}^n\binom{n-1}{r-1}\binom{n}{n-r}\\
&=n\binom{2n-1}{n-1}
\end{align}
$$


text:
Q: Flutter issues after flutter upgrade to Flutter 1.11.0 (Mac OS) After upgrading flutter to 1.11.0 it is showing this error below when trying to run a project.

Couldn't read file LocalFile:
  '/Users/h/flutter/.pub-cache/hosted/pub.dartlang.org/audio_recorder-1.0.1/android/src/main/kotlin/com/jordanalcaraz/audiorecorder/audiorecorder/AudioRecorderPlugin.kt'
  even though it exists. Please verify that this file has read
  permission and try again.

A: A colleague found this:
https://github.com/ZaraclaJ/audio_recorder/issues/46
And according to DyaryRaoof the solution is:
I am on the master branch. This error appears in iOS.
To solve it you need to locate your audio_recorder plugin inside flutter. then change the name of it's last child folder on android. You have to change it from audio_recorder to audiorecorder(remove the underscore).
Or just wait for the package maintainer to solve that issue.


text:
Q: Кривая в цилиндрической системе координат, какие задать параметры? Есть кривая заданная в цилиндрических системах координат, нужно отрисовать, но это уже мелочи.
r = exp(a * t)
fi = b * t^2
z = sqrt(-t)
Переходя к декартовым у меня вышло
x = exp(a * t) * cos(b * t^2)
y = exp(a * t) * sin(b * t^2)
z = sqrt(-t)
на что влияют коэффицента a и b которые по идее константные и что это за фигура? как изменяется t
Пока что выходит что то такое