text:
Q: Registration Forms My current WP configuration
Theme used: Hope
Extensions in place: Easy Registration Forms, Gravity Forms
Website address: https://fegu.org
Problem (s) encountered: I am developing a mini site that will allow students to enroll (register) and send me their report cards; however, once a student is registered in my database, I would like him to be able to automatically receive a registration code, so when sending his report card he will simply be asked to first enter his registration code (the latter contains this information, name, first name .......). once he enters the registration code, he has the option to send his ballot.
Please, I have not been able to do this for almost two weeks. I did not do it with Gravity Forms, no results, I did it with Easy Forms (https://fegu.org/enrolement/) like I really need you.
Thank you!


text:
Q: React Native - How to add react-native-navigation into this layout I found some code online and I'm fairly new to react-native. I was wondering is it possible to add in code to make these rendered squares clickable like they were buttons? (see code below or the link as it has a snack build already created for it) I was trying to fiddle with the button or adding onPress in it and sadly my attempts were all unsuccessful. I was hoping to be able to use something like onPress={() => this.props.navigation.navigate('Details')} but the clicks do nothing when its added in the  tags and when I try to add a  tag near the  tags it completely overwrites it on the screen.
// https://snack.expo.io/@spencercarli/react-native-flatlist-grid
import React from 'react';
import { Button, StyleSheet, Text, View, FlatList, Dimensions } from 'react-native';
import { createStackNavigator, createAppContainer } from 'react-navigation';
//import { Container, Header, Content} from "native-base";
//import { SectionList, FlatList, GridView, FlatGrid } from 'react-native-super-grid';<

const data = [
  { key: 'A' }, { key: 'B' }, { key: 'C' }, { key: 'D' }, { key: 'E' }, { key: 'F' }, { key: 'G' }, { key: 'H' }, { key: 'I' }, { key: 'J' },
  // { key: 'K' },
  // { key: 'L' },
];

const formatData = (data, numColumns) => {
  const numberOfFullRows = Math.floor(data.length / numColumns);

  let numberOfElementsLastRow = data.length - (numberOfFullRows * numColumns);
  while (numberOfElementsLastRow !== numColumns && numberOfElementsLastRow !== 0) {
    data.push({ key: `blank-${numberOfElementsLastRow}`, empty: true });
    numberOfElementsLastRow++;
  }

  return data;
};

const numColumns = 3;
export default class App extends React.Component {
  renderItem = ({ item, index }) => {
    if (item.empty === true) {
      return <View style={[styles.item, styles.itemInvisible]} />;
    }
    return (
      <View
        style={styles.item}
      >
        <Text style={styles.itemText}>{item.key}</Text>
      </View>
    );
  };

  render() {
    return (
      <FlatList
        data={formatData(data, numColumns)}
        style={styles.container}
        renderItem={this.renderItem}
        numColumns={numColumns}
      />
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginVertical: 20,
  },
  item: {
    backgroundColor: '#4D243D',
    alignItems: 'center',
    justifyContent: 'center',
    flex: 1,
    margin: 1,
    height: Dimensions.get('window').width / numColumns, // approximate a square
  },
  itemInvisible: {
    backgroundColor: 'transparent',
  },
  itemText: {
    color: '#fff',
  },
});

A: Yes it´s possible, you just need to change the View to TouchableOpacity and add your onPress functionality, like this:
here is the snack modified

redpajama_set_name: RedPajamaStackExchange


text:
Q: PKCS file system in Android I would like to create an android application. In this application I would like to create a PKCS file system (like in Java Card applet) (not involving secure element) and perform cryptographic operations through APDU commands. Is it possible? Any valuable suggestions?
Thanks in advance.

A: Yes, although APDU's are meant to be send over a T=0 or T=1 transmission protocol. You may map those on the internet protocol, but some mapping may be required.
You could start with JCardSim which implements the Java Card specifications (in part) on the JRE. It will likely also run on Android, although you may have to make some modifications.


text:
Q: Swift 2.2 app no longer works on macOS 10.14 Mojave I make a plug-in to ą third-party app. Part of the plug-in is written in Swift. The plug-in is stuck at Xcode 7.3.1/Swift 2.2 because of this issue.
The plug-in no longer works on Mojave.
We have the following observations:

*

*The issue is limited to Mojave, everything works as expected on older macOS versions.

*If the third-party app asks to "load this bundle" of the plug-in, it just gets nil.

*The plug-in's init method is not called at all.

*If I completely remove Swift 2.2 from the plug-in's code base (making in unusable), its bundle is correctly loaded.

Any ideas what might be causing this issue and how to fix it?
PS: Pursuing users to install a newer version of Python/PyObjC is not feasible nor expecting Apple to bundle a newer version of Python/PyObjC with macOS (so the plug-in code base cannot be upgraded to a newer Swift version). Migrate the code from Swift to Objective-C is planned but it will not happen instantly (it's a matter of a few months).

A: I have managed to get the plug-in running on Mojave.
The nil was returned by a call to NSBundle's principalClass.
Based on my understanding of the official documentation, there are two ways how the principalClass is determined.

*

*The principal class name is specified manually in the info.plist file. As the plug-in did not have it specified here, this step should not apply.

*The principal class is the first one listed on the ld command line when linking. As the exactly same plug-in binary was used on both High Siera and Mojave, "the first one listed on the ld command line" was the same so the returned principal class should be the same on both versions.

Somehow, the principalClass call returned different value on High Sierra and Mojave. Personally, I do not see any reason why it should behave differently, as the documentation has not changed and the logic sounds to be dependent solely on what happened while compiling the plug-in not how the world context while running it.
However, after I have added NSPrincipalClass item into the info.plist file, the plug-in loads successfuly on Mojave.


text:
Q: NodeJs back end code structure I'm quite new to web applications and have decided to create a single page web app hosted on Heroku.
My understanding of this web app is as follows:

*

*Client side (AngularJs) has input text box, once button press it requests server side endpoint

*Server (NodeJs) uses data from client to call external API (e.g imgur API) and returns json

*Server processes json and responds to client with information

*Client uses server response to render user interface

Main Concerns

*

*Best practices for external API calling: Should I have an API wrapper class that allows me to call custom methods that return specific external api calls?

*How should I handle http error responses?: I understand that NodeJs is async by nature and all http calls are done async as well. If there are multiple responses, error or success, how do I go about handling them all without doing a custom set of ".error()" and ."success()" methods for each call?
Furthermore
I cannot seem to find a good reference material for a simple NodeJs back end like the one I described. Please direct me if there are any.

A: I recommend looking at this Scotch.io article for creating a Single Page MEAN Application:
Setting Up a Single Page MEAN Application Starter Kit


text:
Q: How to properly execute C# file over local network? Overview
C# File - Users PC
PHP Server - Hosts Webpages for application
Server and Users PC on local network
I have a c# file that reads weight from a USB scale.  How would I trigger this file to run so it feeds into my program.  The problem is I am using PHP to host our webpage/application so its not running client side and the scale is not hooked up to the server but to the clients PC.
The C# script would have to be on the clients in order to read the scale so how would I trigger this to happen?
Is this even possible and if not what would be a better way?
Important Edit
I was able to run the Scale Script (C#) when I wanted by having PHP and C# use TCP sockets.
The C# would listen for PHP to send something and when it did it would read the scale and send this information back to PHP becuase PHP was listening for a response.  Mixed in with a little Ajax and it updates in the web browser.
Gave Chris Credit because he was the most helpful with answering my questions

A: It sounds like what you really want is for the client application to submit the data to the website itself, and the most suitable approach is probably to expose a web service from your server.
This service should accept weight data, along with some sort of customer key or whatever, to correlate the records correctly on the server side. I've never created a web service in PHP personally, so I can't give any advice on the implementation of that, but it is fairly trivial to hook a C# client app up to a web service once you've exposed its metadata (assuming you use SOAP).

A: C# isn't a scripting language, it's a language that compiles into executable binaries or libraries. You won't be able to execute C# code on the client's computer via a website because C# code needs to be compiled before it can run.
Presumably what you really want is for your compiled C# binary to be executed on the client's machine via your website. You won't be able to easily do that. There are a lot of security measures in place to prevent browsers from running programs on your computer. There may be ways to hack around these security measures by using plugins (such as ActiveX), but it's not something that will be a one-liner.
Edit: I think you need to step back and think about what you're trying to do in a broad sense. You're trying to create a website that can read information from a user's USB port. This is the type of thing that browsers are designed to prevent, and for good reason. I wouldn't want random websites to be able to access peripheral hardware without my explicit permission. If you want this website to function the way you're expecting, you're going to have to seriously think about the security implications. You'll need some kind of client-side code (ActiveX, Silverlight, ...), and the user will need to explicitly give permission to for this all to happen. It won't be easy, and it won't be automatic. And I'm damn glad that's true.

A: you can't start C# application from a web page in a way that'll work in every browser every time. BUT, you can have some workarounds:

*

*Use ActiveX component that read the data in the client and upload it to the server. the biggest cons is that it'll only work in Internet Explorer

*use Silverlight client application that runs on elevated mode (v4) and upload the data to your server.

*refer your clients to download application (the C# application you wrote about) and run it - this application will upload the data to your server.

hope this helps.


text:
Q: Looping throughout selected users and populating the drop-down list dynamically So this is a part from the administrator page.
After several modifications I came to this, which is the best I could get unfortunately:
<?php

$sql = "SELECT name
        FROM users";
$result = mysqli_query($connection, $sql);

$users = array();

while ($row = mysqli_fetch_assoc($result))
{
     $users[] = $row["name"];
}

echo ('
<form action="" method="POST" style="display:inline!important">

        <select name="deleteUser">
        <option value="' . $users[1] . '">' . $users[1] . '</option>' .
       '<option value="' . $users[2] . '">' . $users[2] . '</option>' .
       '<option value="' . $users[3] . '">' . $users[3] . '</option>' .
       '<option value="' . $users[4] . '">' . $users[4] . '</option>' .
       '<input class="w3-bar-item w3-button w3-hide-small w3-hover-green"  type="submit" value="Delete" name="delete"></select></form>');
if (isset($_POST["delete"]))
{
     $sql = "DELETE
             FROM users
             WHERE name = '" . $_POST["deleteUser"] . "'";
     mysqli_query($connection, $sql);

}
?>

I tried to write a loop to generate the select options like this:
<?php

$sql = "SELECT name
        FROM users";
$result = mysqli_query($connection, $sql);

$users = array();

while ($row = mysqli_fetch_assoc($result))
{
     $users[] = $row["name"];
}

echo ('
<form action="" method="POST" style="display:inline!important">

        <select name="deleteUser">');

for ($i = 0; $i < count($users); $i++)
{
    echo('<option value="' . $users[$i] . '">' . $users[$i] . '</option>');
}

echo('<input class="w3-bar-item w3-button w3-hide-small w3-hover-green"  type="submit" value="Delete"></select></form>');
if (isset($_POST["delete"]))
{
     $sql = "DELETE
             FROM users
             WHERE name = '" . $_POST["deleteUser"] . "'";
     mysqli_query($connection, $sql);

}
?>

But the browser doesn't render it(i.e Chrome), maybe because it just can't on portions? Like to wait for the loop to complete and then to end with the last part of the form.
Anyway, how could I make it work? Thanks mates...

A: Instead of using while loop you can use foreach this is where you can use foreach properly
Here is an example that might help you
 while ($row = mysql_fetch_assoc($result)) {
   $rows[] = $row;
 }
foreach($rows as $val){

   //Here populate your options like this
   echo '<option> '.$val["name"].' </option'
}

Hope this will help you out :)


text:
Q: Find and replace inside string based on pattern and exception cases I have a JSON string that returns some key value pairs but if the value is numeric it doesn't enclose it with double quotes so my JSON parsing isn't working for those cases.
My idea is to manipulate the string by searching and replacing any occurrences where it finds : with :" except when the : is followed by an open curly brace {
I would also need to close the double quotes at the end so I need to find a way to look for any 0-9 followed by a comma and replace that comma with ",
I am thinking I need SED to search/replace but I am very new to SED and RegEx so not sure how to start especially omitting places where it finds "{ and using RegEx to find [0-9],
Sample JSON string looks like:
{"data":{"project":{"issue":{"session":{"id":"625fdv6b95e232f08d6cy2686624f315","createdAt":1539849060000,"buildVersionId":"75492373","sdk":{"display":"1.11.1"},"os":{"platform":"unknown","modified":false},"memory":{"free":853000192,"used":1896611840},"storage":{"free":241791528960,"used":14197940224},"device":{"architecture":"arm64","manufacturer":"Samsung"}}}}}}

Desired finished JSON after the change would look like:
{"data":{"project":{"issue":{"session":{"id":"625fdv6b95e232f08d6cy2686624f315","createdAt":"1539849060000","buildVersionId":"75492373","sdk":{"display":"1.11.1"},"os":{"platform":"unknown","modified":false},"memory":{"free":"853000192","used":"1896611840"},"storage":{"free":"241791528960","used":"14197940224"},"device":{"architecture":"arm64","manufacturer":"Samsung"}}}}}}

pretty much the same thing but every number now has double quotes around it.

A: I took a different approach and instead of modifying the JSON data, I modified my grepping for numeric values not to look for the double quotes like so:
buildVersionId=`echo $jsonData | grep -m1 -oP '"buildVersionId"\s*:\s*\K[^"]+"'`

then I remove the last 2 characters ( ," ) from the end to get the actual number only:
buildVersionId=${buildVersionId::${#buildVersionId}-2}

A: How about
sed 's/:\([0-9]*\)\([,}]\)/:"\1"\2/g' inp >out

*

*s/:\([0-9]*\)\([,}]\) - search for : followed by digits, followed by either , or }.  Place the digits into capture \1, the , or } into \2.

*/:"\1"\2/g - replace with :" followed by capture \1 (the digits), followed by ", followed by capture \2 (the original suffix character)

Example
$ cat inp
{"data":{"project":{"issue":{"session":{"id":"625fdv6b95e232f08d6cy2686624f315","createdAt":1539849060000,"buildVersionId":"75492373","sdk":{"display":"1.11.1"},"os":{"platform":"unknown","modified":false},"memory":{"free":853000192,"used":1896611840},"storage":{"free":241791528960,"used":14197940224},"device":{"architecture":"arm64","manufacturer":"Samsung"}}}}}}
$ sed 's/:\([0-9]*\)\([,}]\)/:"\1"\2/g' inp >out
$ cat desired
{"data":{"project":{"issue":{"session":{"id":"625fdv6b95e232f08d6cy2686624f315","createdAt":"1539849060000","buildVersionId":"75492373","sdk":{"display":"1.11.1"},"os":{"platform":"unknown","modified":false},"memory":{"free":"853000192","used":"1896611840"},"storage":{"free":"241791528960","used":"14197940224"},"device":{"architecture":"arm64","manufacturer":"Samsung"}}}}}}
$ diff out desired
$

A: jq -c '(.. | select(numbers)) |= tostring' file >newfile

This jq command converts all numbers in your JSON document into strings, regardless of where in the document the numbers are found.
The output is written in "compact" form to the file newfile.
In case you, for whatever reason, have ended up with your JSON document in a shell variable, data, then instead use
jq -c -n --argjson d "$data" '$d | (.. | select(numbers)) |= tostring' >newfile


text:
Q: @ Mentions on Facebook, linking content from my App I know that there's no API from Facebook for adding @mentions in the post from Apps & that the message_tags are read-only, but how the other Apps on Facebook link content on the messages in their posts?

A: This is representation of OpenGraph actions user performed on objects and published by applications.
There is a tutorial and samples. Read Key Concepts of OpenGraph and/or OpenGraph documentation for more detailed information.


text:
Q: read files from hdfs using spark(Scala) please tell me how to read files from hdfs. I'm just starting to work with Scala and Spark. I can read a separate file that lies in the folder:
val parqDF = spark.read.parquet("hdfs://nn1home:8020/user/stg/ads/year=2020/month=1/day=1/16_data.0.parq")

but I would like to read whole folder with all the parquets
and also, one more important question,
how can I add columns to my dataframe with data from the path where there are my parquets
my thanks for any advice

A: import org.apache.spark.sql.functions.lit
val inputPath = "<you path>"
val dataDF = spark.read.parquet(inputPath)
dataDF.printSchema()
//    root
//    |-- _c0: string (nullable = true)
//    |-- _c1: string (nullable = true)
//    |-- _c2: string (nullable = true)
//    |-- _c3: string (nullable = true)

val resDF = dataDF.withColumn("new_col", lit(inputPath))
resDF.printSchema
//    root
//    |-- _c0: string (nullable = true)
//    |-- _c1: string (nullable = true)
//    |-- _c2: string (nullable = true)
//    |-- _c3: string (nullable = true)
//    |-- new_col: string (nullable = false)

resDF.schema
//    res2: org.apache.spark.sql.types.StructType = StructType(
//      StructField(_c0,StringType,true),
//      StructField(_c1,StringType,true),
//      StructField(_c2,StringType,true),
//      StructField(_c3,StringType,true),
//      StructField(new_col,StringType,false)
//    )

// resDF.show(false) - show data dataframe


text:
Q: SQL: Mapping first (or random) result of element from specific column matching certain conditions in another column to variable The problem is as follows:  I want to query a database, and return the number of hits that have particular values in two different columns, grouped by timestamp window.  I am currently doing this successfully with the following query:
SELECT shortdate,
sum(column1 like '%interestingthing1%') thing1count,
sum(column1 like '%interestingthing2%') thing2count,

FROM (
select LEFT(string(DATE), 8) shortdate,column1
from [database]
where column3 like '%thingthatcolumn3shouldbe%'
)
group by shortdate

ORDER BY 1 DESC
LIMIT 1000

What I want to also do is to also return a variable which is a random element of column2, corresponding to a row that satisfies the thingthatcolumn3shouldbe, one for each interestingthingn (n=1,2,...).
I have some intuition that this can be done either with some user-defined function (I am doing this in google bigquery, which allows javascript functions), or a whole mess of UNIONs within the FROM (...) statement above.  But since I am far from a SQL expert, this question is partially an effort to start using some best/better practices early on.  Naked opinions welcome.
Thanks in advance,
Samuel

A: Perhaps something like the query below. It will pick the "first" value for column2 when column1 satisfies your condition, but since order of values going into aggregation function is not deterministic - it is as good as random. And since FIRST aggregate function ignores NULLs, we just need to make sure to convert column2 to NULL when condition isn't met.
SELECT shortdate,
  sum(column1 like '%interestingthing1%') thing1count,
  sum(column1 like '%interestingthing2%') thing2count,
  first(if(column1 like '%interestingthing1%', column2, NULL)) column2forthing1,
  first(if(column1 like '%interestingthing2%', column2, NULL)) column2forthing2
FROM (
  select LEFT(string(DATE), 8) shortdate, column1, column2
  from [database]
  where column3 like '%thingthatcolumn3shouldbe%'
)
group by shortdate

ORDER BY 1 DESC
LIMIT 1000


text:
Q: Swift Popover closing when touching background I have a popover that is being called and I want the only way to close the popover is by clicking the Close button, not by taping on the background. Currently my code to launch the popover is like this:
 let popover = storyboard?.instantiateViewController(withIdentifier: "PopoverVC") as! PopOverViewController

        popover.modalPresentationStyle = .popover
        popover.popoverPresentationController?.delegate = self as? UIPopoverPresentationControllerDelegate

        popover.popoverPresentationController?.sourceView = self.view
        popover.popoverPresentationController?.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)

        popover.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)

        popoverPresentationController?.passthroughViews = nil

        dimView.isHidden = false

        popover.dimView = self.dimView

        self.present(popover, animated: false)

I have a UIview in the background that I use to dim the background when the popover comes up but when you tap on the background, it closes the popover. How can I keep the popover open? I thought the popoverPresentationController?.passthroughViews = nil was supposed to resolve this but it hasn't.
EDIT:
Adding my PopOverViewController Class:
    class PopOverViewController: UIViewController, UIPopoverPresentationControllerDelegate {

    var dimView:UIView?

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func popoverPresentationControllerShouldDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) -> Bool {

        print ("test")

        return false
    }

    @IBAction func closeButton(_ sender: Any) {

        self.dismiss(animated: false, completion: nil)

        dimView?.isHidden = true

    }

}

A: You need to use the delegate of the presentation controller. You're already assigning self, just implement the below delegate method.
extension SelfsType: UIPopoverPresentationControllerDelegate {

    func popoverPresentationControllerShouldDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) -> Bool {
       /* This disables the automatic dismissal, but you can make it conditional, too. Such as if the user entered enough information, etc */
       return false
    }
}

Where SelfsType is the class of self as used in the context of
popover.popoverPresentationController?.delegate = self as? UIPopoverPresentationControllerDelegate

Your code doesn't include that.


text:
Q: Rendering to QOpenGLFramebufferObject without PaintGL call I want to call the rendering routine out without calling PaintGL, the reason is that I'm trying to render a multipass effect using the modern routines of Qt OpenGL implemementation so the pseudo code should be something like:
for i=0 i<npasses i++
   glwidget->renderlayer i
glwidget->repaint //this calls PaintGL

The problem is that if I call renderlayer out of the PaintGL function everything goes mad and it gets drawn over my entire app instead on my glwidget (that inherits from QOpenGLWidget) in the other hand renderlayer funcion is ok since being called only from inside PaintGL it works like it was expected.
Any tip on this?
Thank you in advance

A: You can create a QOffscreenSurface like this:
QOpenGLWidget* widget = ...;
QOpenGLContext* ctx = widget->context();

QOffscreenSurface surface;
surface.setFormat(ctx->format());
surface.setScreen(ctx->screen());
surface.create();

Then re-target your GL context to that offscreen surface, do your FBO rendering, and finally re-target the GL context back.
ctx->makeCurrent(&surface);

// Bind FBO, do the rendering

widget->makeCurrent();


text:
Q: renderPartial different model Yii several models working but not all of them i have a View that combines many models and I make a tab that each contains different models
this is my script at the view
<?php
$this->widget(
        'booster.widgets.TbTabs',
        array(
            'type' => 'tabs',
            'tabs' => array(
                array(
                    'label'=>'Genset',
                    'content'=>$this->renderPartial('/ats/genset', array('model'=>new genset), true ),
                    'active'=> false
                ),
                array(
                    'label'=>'ATS',
                    'content'=>$this->renderPartial('/ats/ats', array('model'=>new ats), true ),
                    'active'=> false
                ),
                array(
                    'label'=>'UPS',
                    'content'=>$this->renderPartial('/ats/ups', array('model'=>new ups), true ),
                    'active'=> false
                ),
                array(
                    'label'=>'PLN',
                    'content'=>$this->renderPartial('/ats/pln', array('model'=>new pln), true ),
                    'active'=> false
                ),
            ),
        )
)
?>

at the final tab, which the label name is PLN doesn't work and return error like this
CException
Property "pln.merk" is not defined.
where there are something odd, pln is my model, and merk is not one of the columns from pln but from another model which is ats, i made this view file based on ats which has merk column, but this doesn't make sense when all of the view i do renderPartial like Genset, UPS, ATS works fine
only pln, and several other models throws an error message, like somehow they don't recognize the pln's model column but instead read the wrong column from ats model
Edit:
Basically the view is generated by CRUD, and this is the admin.php file where it contains CGridView
<?php
/* @var $this PlnController */
/* @var $model pln */

$this->breadcrumbs=array(
    'Plns'=>array('index'),
    'Manage',
);

$this->menu=array(
    array('label'=>'List pln', 'url'=>array('index')),
    array('label'=>'Create pln', 'url'=>array('create')),
);

Yii::app()->clientScript->registerScript('search', "
$('.search-button').click(function(){
    $('.search-form').toggle();
    return false;
});
$('.search-form form').submit(function(){
    $('#pln-grid').yiiGridView('update', {
        data: $(this).serialize()
    });
    return false;
});
");
?>

Manage Plns

You may optionally enter a comparison operator (<, <=, >, >=, <>
or =) at the beginning of each of your search values to specify how the comparison should be done.

<?php echo CHtml::link('Advanced Search','#',array('class'=>'search-button')); ?>

<?php $this->renderPartial('_search',array(
    'model'=>$model,
)); ?>

<?php $this->widget('zii.widgets.grid.CGridView', array(
    'id'=>'pln-grid',
    'dataProvider'=>$model->search(),
    'filter'=>$model,
    'columns'=>array(
        'id',
        'siteid',
        'capacity',
        'arus_r',
        'arus_s',
        'arus_t',
        /*
        'id_pelanggan',
        'jumlah_fasa',
        */
        array(
            'class'=>'CButtonColumn',
        ),
    ),
)); ?>

ATS.php
<?php
/* @var $this AtsController */
/* @var $model ats */

$this->breadcrumbs=array(
    'Ats'=>array('index'),
    'Manage',
);

$this->menu=array(
    array('label'=>'List ats', 'url'=>array('index')),
    array('label'=>'Create ats', 'url'=>array('create')),
);

Yii::app()->clientScript->registerScript('search', "
$('.search-button').click(function(){
    $('.search-form').toggle();
    return false;
});
$('.search-form form').submit(function(){
    $('#ats-grid').yiiGridView('update', {
        data: $(this).serialize()
    });
    return false;
});
");
?>

Dapot

You may optionally enter a comparison operator (<, <=, >, >=, <>
or =) at the beginning of each of your search values to specify how the comparison should be done.

<?php
$this->widget(
        'booster.widgets.TbTabs',
        array(
            'type' => 'tabs',
            'tabs' => array(
                array(
                    'label'=>'Genset',
                    'content'=>$this->renderPartial('/ats/genset', array('model'=>new genset), true ),
                    'active'=> false
                ),
                array(
                    'label'=>'ATS',
                    'content'=>$this->renderPartial('/ats/ats', array('model'=>new ats), true ),
                    'active'=> false
                ),
                array(
                    'label'=>'UPS',
                    'content'=>$this->renderPartial('/ats/ups', array('model'=>new ups), true ),
                    'active'=> false
                ),
                array(
                    'label'=>'Rectifier',
                    'content'=>$this->renderPartial('/ats/rectifier', array('model'=>new rectifier), true ),
                    'active'=> false
                ),
                array(
                    'label'=>'Baterai',
                    'content'=>$this->renderPartial('/ats/baterai', array('model'=>new baterai), true ),
                    'active'=> false
                ),
                array(
                    'label'=>'BBS',
                    'content'=>$this->renderPartial('/ats/bbs', array('model'=>new bbs), true ),
                    'active'=> false
                ),
                array(
                    'label'=>'Inverter',
                    'content'=>$this->renderPartial('/ats/inverter', array('model'=>new inverter), true ),
                    'active'=> false
                ),
                array(
                    'label'=>'Trafo',
                    'content'=>$this->renderPartial('/ats/trafo', array('model'=>new trafo), true ),
                    'active'=> false
                ),
                /*array(
                    'label'=>'PLN',
                    'content'=>$this->renderPartial('/ats/pln', array('model'=>new PLN), true ),
                    'active'=> false
                ),*/
            ),
        )
)
?>

A: I have solved this problem, so i use crud generator which creates the advanced search option code below,
the 'model'=>$model overwrite the desired model, so i have to remove this code below if you use crud generator
<?php echo CHtml::link('Advanced Search','#',array('class'=>'search-button')); ?>

<?php $this->renderPartial('_search',array(
    'model'=>$model,
)); ?>

After that, i tried using the search function and it didn't work, so i added for each view to unset it's attributes
$model_x=new model_x('search');
$model_x->unsetAttributes();
if(isset($_GET['model_x']))
            $model_x->attributes=$_GET['model_x'];

now i'm stuck at the view,update,delete where it always uses ats as primary key identifier from the loadModel at the controller file


text:
Q: Class Design and Separation Of Concerns I'm working on an MVC application and am wondering about the best way to design one of my models.
I have a class called RightLeftPersonToggle which represents two select list boxes on the page. The user is able to move "persons" between the left and right box using buttons between them.
This class can represent both a vehicle driver or manager so the load and save code is different for each type. The class is below.
public class RightLeftPersonToggle
{
    public RightLeftPersonToggle()
    {
        LeftList = new List<Person>();
        RightList = new List<Person>();
    }

    public List<Person> LeftList { get; set; }
    public List<Person> RightList { get; set; }
    public string LeftListTitle { get; set; }
    public string RightListTitle { get; set; }
    public string PropertyName { get; set; }
}

I'm wondering what the best way to handle the loading and saving of the lists is. I've come up with two solutions but I'm not sure on which one is best.
1) The controller (or parent model) is responsible for loading and saving both LeftList and RightList. The RightLeftPersonToggle class has no knowledge of that code and remains exactly like the code above.
2) RightLeftPersonToggle gets two methods (one for save and one for load) which take functions as parameters to tell it how to do its job.
public void LoadAndFilterLists(Func<List<Person>> leftListFilter, Func<List<Person>> rightListFilter)

public void LoadSaveLists(Func<List<Person>> leftListSave, Func<List<Person>> rightListSave)

Solution number one keeps the code more simple in my opinion while solution number two seems to provide better sepration of concerns since RightLeftPersonToggle should know how to load and save itself.
Keeping in mind the fact that RightLeftPersonToggle doesn't always load and save data the same way, which of my proposed solutions would be considered best practice? Do you have any other recommendations for improvement?

A: If the logic needed to save the data differs depending on what's being shown in the lists, you should have the controller handle saving the lists. The code you've shown seems to be for your view, so all it should worry about is displaying the lists and shouldn't need to know what's actually in them. Let the controller figure out what type of data is in the 2 lists and what the appropriate save logic would be.

A: In a more general sense, I would have my business classes represent the real-world relationships.  When a non-technical person is speaking about a Person, are they really talking about a Person's LeftList and RightList?  Or is this more of a hierarchical relationship?
The use of list boxes and such is a UI concern.  Your UI will be responsible for taking the set of list boxes and other input elements and mapping them over to objects that the domain model can work with.
Personally, I try to avoid exposing my domain model to my UI so I use a service layer that handles mapping between my entities and the DTOs that my UI works with.  The service layer also makes calls to the repository and I strive to keep all of my business logic in my entities.
The ASP.NET MVC UI takes the DTOs and maps them to view models and the views are strongly typed to view-specific view models.  The view models have awareness of UI components like SelectList but not the DTOs or entities.  The controllers are as thin as possible and coordinate service calls and returning views/redirects.

A: I have two ideas, one that I've struck off and the second which I favour.

*

*My non-favoured idea: Why not create two sub classes of RightLeftPersonToggle, one for VehicleDriver and one for Manager, and implementing the Save/Load functionality in those subclasses? Your Parent class is responsible for creating the right type of class based on what kind of objects it is dealing with.

*My second idea is to have your RightLeftPersonToggle class accept something like an IPersonRepository in the constructor, and call _personRepository.Save and _personRepository.Load from within the RightLeftPersonToggle class. It keeps the code separate, but still allows it to be called from the object repsonsible for it.


text:
Q: What are the precedence rules for Perl regular expressions? I can find't an official reference for the precedence rules for Perl regular expressions. What I can find is only Know the precedence of regular expression operators. However, it's not an official reference given by perldoc.

A: Regular expressions only have two binary operators, one of which is implicit rather than represented by a symbol. Regular expressions also have a number of unary operators, but their precedence is moot due to the restrictions on their operands. That makes talking about precedence really odd.
It's simpler conveying the information you seek using the following statements:

*

*Quantifiers modify a single atom.

*Quantifiers modifiers modify a single quantifier.

*Alternation is unbounded except by the parens in which they reside.

The above information is conveyed one way or another in perlretut.

That said, it is possible to build a precedence table. Since the above statements convey all the information you need, it's possible to build the precedence table from them. It is the following:

*

*Atoms (e.g. a, \n, \^, ., ^, \w, [...], \1, (...))

*Postfix unary operators (quantifiers and quantifier modifiers)

*Implicit "followed by" operator between (possibly-quantified) atoms

*Alternation

This matches the chart in the page to which you linked.

For fun, the following would be the BNF:
pattern              ::= <alternation>

alternation          ::= <sequence> <alternation2>
alternation2         ::= "|" <alternation> | ""

sequence             ::= <quantified_atom> <sequence> | ""

quantified_atom      ::= <atom> <quantified_atom2>
quantified_atom2     ::= <modified_quantifier> | ""
modified_quantifier  ::= <quantifier> <modified_quantifier2>
modified_quantifier2 ::= <quantifier_modifier> | ""


text:
Q: Django empty a modal which contain an html I am working with Django wherein I have a modal on a html page which includes the the html to be displayed when the modal is clicked. The modal is refreshed every 1 second until closed so as to get the latest data from the server. Now, when the modal is closed and clicked again for another link, the old data is still present and new data takes a second or two to be displayed. I want to know how we could empty the modal html before displaying the new data.
My modal:

        <button type="button" id="close" class="close" data-dismiss="modal" aria-hidden="true">×</button>

IP details

            {% include "ip_list.html" %}

    <button type="button" id ="close2" class="btn btn-primary btn-md" data-dismiss="modal">Close</button>

Here ip_list.html is the html file which gets called when the modal is clicked.
Right below this I have my Jquery running to display the data.

Let me know if you need any other info. Any leads as to how I could achieve the empty HTML after the modal is closed is appreciated. Thanks in advance!


text:
Q: Annihilating polynomials of non-diagnolizable matrices
For every non-diagonalizable matrix in $M_n(\mathbb{F})$, there is a polynomial $P(t)$ with coefficients over $\mathbb{F}$ and of degree $n-1$ such as $P(A)^2=0$.

Is the above statement true for $\mathbb{F}=\mathbb{C}$ or $\mathbb{F} = \mathbb{R}$? Or none of them?
How can I find out if this is true for any field?

A: This is true iff the field is algebraically closed. For non-algebraically closed fields, any matrix (at least of size 2x2) with with an irreducible characteristic polynomial is a counterexample.


text:
Q: Error 1267 Illegal mix of collations I am running the following query
SELECT * FROM leads WHERE LCASE(address) = "2560 Cherry cir"

I am getting the error
General error: 1267 Illegal mix of collations (latin1_swedish_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE) for operation '='

I think there are some strange space characters causing the error ( 2560 Cherry cir )
The address is inputted by the user, and submitted to a php page that uses PDO to assemble and run the query.
<input type='text' name='address' />

$this->db->select(
            "SELECT
                *
            FROM leads
            WHERE
                LCASE(address)=:address

                array( ":address" => strtolower($address) ) );

The select function is defined as follows:
public function select($sql, $array = array(), $fetchMode = PDO::FETCH_ASSOC)
    {
        $sth = $this->handleDB->prepare($sql);
        foreach ($array as $key => $value) {
            $sth->bindValue("$key", $value);
        }

        $sth->execute();
        return $sth->fetchAll($fetchMode);
    }

How should I go about addressing this issue? The collation on the database and the tables are both UTF-8? I am using PHP with PDO, and have set the charset to UTF-8 in PDO as well.

A: Found the problem, the table was set to the UTF-8 collation, but the column was set to Latin.


text:
Q: Conditional expectation $E[\min{\{X,Y\}}|Y^{2}]$ Let $X$ and $Y$ be an independent random variables with exponential distribution $Exp(1)$.
Compute $E[\min{\{X,Y\}}|Y^{2}]$.
My attempt:
I. If we want to compute $E[\min{\{X,Y\}}|Y]$ may be sufficient to use the following formula:
$$E[f(X,Y)|Y]=\int\limits_{-\infty}^{+\infty}f(x,Y)f_{X}(x)dx$$
Is this correct? Is there any other simpler method to compute this conditional expectation?
II. What about $E[\min{\{X,Y\}}|Y^{2}]$? First thing which comes to my mind is that we should find distribution of vector $(\min{\{X,Y\}},Y^{2})$ and $Y^{2}$ and then use appropriate formula. Am I right? How to find distribution of vector $(\min{\{X,Y\}},Y^{2})$? Is there any simpler method to compute this conditional expecation?

A: *

*Yes, you are correct. So we have
$$ \Bbb{E}[\min\{X, Y\} | Y] = \int_{0}^{\infty} \min\{x, Y\} \, e^{-x} \, dx = 1 - e^{-Y}. $$

*Notice that both $Y$ and $Y^2$ generate the same $\sigma$-algebra: $\sigma(Y) = \sigma(Y^2)$. So we have
$$ \Bbb{E}[f(X, Y)|Y^2] = \Bbb{E}[f(X, Y)|\sigma(Y^2)] = \Bbb{E}[f(X, Y)|\sigma(Y)] = \Bbb{E}[f(X, Y)|Y]. $$
If you have not learned the axiomatic approach to the probability theory, ignore this explanation. We have an alternative, more computational explanation as follows: Let $Z = Y^2$. Then
\begin{align*}
\Bbb{E}[f(X, Y) | Y^2]
&= \Bbb{E}[f(X, \sqrt{Z}) | Z] \\
&= \int_{0}^{\infty} f(x, \sqrt{Z}) \, e^{-x} \, dx \\
&= \int_{0}^{\infty} f(x, Y) \, e^{-x} \, dx \\
&= \Bbb{E}[f(X, Y) | Y].
\end{align*}


text:
Q: How to exclude Cucumber feature files In cucumber tests, I want to skip some feature files without changing feature files, such as adding additional tags. Though tags can exclude feature files to run, I can't modify those files. Is there a way to configure in maven pom.xml? Or can I use @CucumberOptions with special features parameters?
Changing feature files will affect other git branches. So I want other way to exclude feature files rather than modifying feature files directly.
One way is to use a Maven plugin to generate a Junit Runner Class for each feature file. Then with maven-failsafe-plugin we can specify exclusions or inclusions to exclude or include those Junit Runner Classes.

A: You can tell Cucumber to ignore scenarios with a particular tag. See the docs.
Since that is the way to do it in Cucumber, could you explain why you are looking for a different way? What is it you are trying to accomplish?


text:
Q: Impossible to uninstall outlook addin multiuser x64 I'm having trouble with my outlook addin x64 for multi user.
The installation process works fine, and the addin works correctly, but when I try to uninstall it, I got those three messages box :

(english translation: Permission denied on HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\WwanSvc)

And the addin does not want to unistall.
Basically, my problem is the same than this one (http://sourceforge.net/mailarchive/forum.php?thread_name=4EB922D9.1090903%40mistoll.de&forum_name=wix-users ).
The explanation, apparently, comes from a registry key that refers [TARGETDIR], but I need it ! The guilty key content is : [TARGETDIR]/myaddin.vsto|vstolocal.
I tried adding 'file:///' (as suggested here https://stackoverflow.com/questions/13070586/create-registry-in-both-wow6432node-and-normal-hive ), but then :

*

*the addin does not work

*the uninstallation process "works", but still shows another message box (the same than the first one, but on another registry key). The addin is then surprisingly correctly unistalled despite the message box

I should also add that this only append on x64 machines for multiusers. I developped other installers for x86 and/or single user that worked perfectly.

A: A few thoughts:

*

*The SYSTEM account sometimes loses access to parts of the system. I don't know why this happens, but installs etc run with the SYSTEM account so check the access on that registry item. Also, it's mentioning a rollback file, and that implies that Windows is trying to clean up a failed install or otherwise doing something with it after a reboot, and it can't see that file (1712 error) and that may also be a SYSTEM account access issue.  I have also seen issues with the config.msi folder, so again see if SYSTEM has access. If you search for config.msi issues you'll find some.
I have no idea why the uninstall wants to look at the auto config service.

*The errors might happen if somebody "cleaned" up the \windows\installer folder that is used to cache MSI files, patches and other install related stuff.


text:
Q: TPU terminology confusion So I know how epochs, train steps, batch sizes and this kind of stuff are defined, but it is really hard to me to get my head wraped around the TPU terminology like train loops, iterations per loop and so on. I read this but Im still confused.
Also how can I benchmark the time for iterations per loop for example.
Any explanation would help me a lot there. Thanks!

A: As the other answers have described, iterations_per_loop is a tuning parameter that controls the amount of work done by the TPU before checking in with it again. A lower number lets you inspect results (and benchmark them) more often, and a higher number reduces the overhead due to synchronization.
This is no different from familiar network or file buffering techniques; changing its value affects performance, but not your final result. In contrast, ML hyperparameters like num_epochs, train_steps, or train_batch_size will change your result.
EDIT: Adding an illustration in pseudocode, below.  Notionally, the training loop functions like this:
def process_on_TPU(examples, train_batch_size, iterations_per_loop):
    # The TPU will run `iterations_per_loop` training iterations before returning to the host
    for i in range(0, iterations_per_loop):
        # on every iteration, the TPU will compute `train_batch_size` examples,
        # calculating the gradient from every example in the given batch
        compute(examples[i * train_batch_size : (i + 1) * train_batch_size])

# assume each entry in `example` is a single training example
for b in range(0, train_steps, train_batch_size * iterations_per_loop)
    process_on_TPU(examples[b:b + train_batch_size * iterations_per_loop],
                   train_batch_size,
                   iterations_per_loop)

From this, it might appear that train_batch_size and iterations_per_loop are simply two different ways of accomplishing the same thing.  However, this is not the case; train_batch_size affects the learning rate, since (at least in ResNet-50) the gradient is computed at each iteration from the average of the gradient of every example in the batch. Taking 50 steps per 50k examples will produce a different result from taking from 1k steps per 50k examples, since the latter case calculates the gradient much more often.
EDIT 2: Below is a way to visualize what's happening, with a racing metaphor.  Think of the TPU as running a race that has a distance of train_steps examples, and its stride lets it cover a batch of examples per step.  The race is on a track, which is shorter than the total race distance; the length of the lap is your total number of training examples, and every lap around the track is one epoch.  You can think of iterations_per_loop as being the point where the TPU can stop at a "water station" of sorts where the training is temporarily paused for a variety of tasks (benchmarking, checkpointing, other housekeeping).

A: By "train loop", I'm assuming it's the same meaning as "training loop". The training loop is the one that iterates through each epoch in order to feed the model.
The iterations per loop is related to how Cloud TPU handles the training loop. In order to amortize the TPU launch cost, the model training step is wrapped in a tf.while_loop, such that one Session run actually runs many iterations for a single training loop.
Because of this, Cloud TPU runs a specified number of iterations of the training loop before returning to the host. Therefore, iterations_per_loop is how many iterations will run for one session.run call.

A: TPU literally means "Tensor Processing Unit", it's a hardware device used for computation in exactly the same way a GPU is used. The TPUs are effectively Google proprietary GPUs. There are technical differences under the hood of a GPU vs a TPU, mostly regarding speed and power consumption, and some issues of floating point precision, but you don't need to care about the details.
iterations_per_loop appears to be an effort to improve efficiency by loading the TPU with multiple training batches. There are often hardware bandwidth limitations when transferring large amounts of data from main memory to a GPU/TPU.
It appears that the code you reference is passing iterations_per_loop number of training batches to the TPU, then running iterations_per_loop number of training steps before pausing to do another data transfer from main memory to TPU memory.
I'm rather surprised to see that though, I would expect that asynchronous background data transfers would be possible by now.
My only disclaimer is that, while I'm proficient with Tensorflow, and have watched TPU evolution in papers and articles, I'm not directly experienced with the Google API or running on TPUs, so I'm inferring from what I read in the documentation you linked to.


text:
Q: Trying to find file extension on hidden download url I am trying to make a script to take a downloadable file and put it onto my ftp server to then update a database. I cannot figure out what the url extention should be to able to make this work.
<?php
$src = fopen('https://www.atf.gov/firearms/docs/0516-ffl-listxlsx/download', 'r');
$dest1 = fopen('first1k.xlsx', 'w');
$dest2 = fopen('remainder.xlsx', 'w');

echo stream_copy_to_stream($src, $dest1, 19759460) . " bytes copied to first1k.txt\n";
echo stream_copy_to_stream($src, $dest2) . " bytes copied to remainder.txt\n";

?>

This is where I am trying to get the data from https://www.atf.gov/firearms/listing-federal-firearms-licensees-ffls-2016

A:     <?php
$file = "0516.xlsx";
$url = 'https://www.atf.gov/firearms/docs/0516-ffl-listxlsx/download' ;

$handle = fopen("0516.xlsx", "w+");
fwrite($handle, file_get_contents($url));
rewind($handle);

$read = htmlentities(fread($handle, filesize($file)));

?>

fixed it out


text:
Q: How can I add only one cell from every excel file to new excel file? import pandas as pd
import glob

location = 'C:\\Users\\rober\\Desktop\\zgony2\\*.xlsx'
excel_files = glob.glob(location)

df1 = pd.DataFrame()

for excel_file in excel_files:
    df2 = pd.read_excel(excel_file)
    df1 = pd.concat([df2.iloc[1, 1], df1.iloc[1, 1]])

df1.to_excel("C:\\Users\\rober\\Desktop\\zgony2\\asdf.xlsx", index=False)

I have 365 excel files and I need to take 1 same cell from every excel file and put them all in new. the problem is my code takes all the data. I tried to make it by adding iloc to df2 and df 1 in for loop with column name and number of cell in that column but it gives me an error. how can I do this?
Error:
C:\PythonProjekty\excel\venv\Scripts\python.exe "C:/PythonProjekty/excel/laczenie plikow excela tylko 1 wartosc z kazdego.py"
Traceback (most recent call last):
  File "C:\PythonProjekty\excel\laczenie plikow excela tylko 1 wartosc z kazdego.py", line 11, in <module>
    df1 = pd.concat([df2.iloc[1, 1], df1.iloc[1, 1]])
  File "C:\PythonProjekty\excel\venv\lib\site-packages\pandas\core\indexing.py", line 960, in __getitem__
    return self.obj._get_value(*key, takeable=self._takeable)
  File "C:\PythonProjekty\excel\venv\lib\site-packages\pandas\core\frame.py", line 3613, in _get_value
    series = self._ixs(col, axis=1)
  File "C:\PythonProjekty\excel\venv\lib\site-packages\pandas\core\frame.py", line 3440, in _ixs
    label = self.columns[i]
  File "C:\PythonProjekty\excel\venv\lib\site-packages\pandas\core\indexes\base.py", line 5039, in __getitem__
    return getitem(key)
IndexError: index 1 is out of bounds for axis 0 with size 0

Process finished with exit code 1

2 Error:
C:\PythonProjekty\venv\Scripts\python.exe C:\PythonProjekty\asd.py
Traceback (most recent call last):
  File "C:\PythonProjekty\asd.py", line 13, in <module>
    temp = pd.read_csv(excel_file)
  File "C:\PythonProjekty\venv\lib\site-packages\pandas\util\_decorators.py", line 311, in wrapper
    return func(*args, **kwargs)
  File "C:\PythonProjekty\venv\lib\site-packages\pandas\io\parsers\readers.py", line 680, in read_csv
    return _read(filepath_or_buffer, kwds)
  File "C:\PythonProjekty\venv\lib\site-packages\pandas\io\parsers\readers.py", line 575, in _read
    parser = TextFileReader(filepath_or_buffer, **kwds)
  File "C:\PythonProjekty\venv\lib\site-packages\pandas\io\parsers\readers.py", line 933, in __init__
    self._engine = self._make_engine(f, self.engine)
  File "C:\PythonProjekty\venv\lib\site-packages\pandas\io\parsers\readers.py", line 1231, in _make_engine
    return mapping[engine](f, **self.options)
  File "C:\PythonProjekty\venv\lib\site-packages\pandas\io\parsers\c_parser_wrapper.py", line 75, in __init__
    self._reader = parsers.TextReader(src, **kwds)
  File "pandas\_libs\parsers.pyx", line 544, in pandas._libs.parsers.TextReader.__cinit__
  File "pandas\_libs\parsers.pyx", line 633, in pandas._libs.parsers.TextReader._get_header
  File "pandas\_libs\parsers.pyx", line 847, in pandas._libs.parsers.TextReader._tokenize_rows
  File "pandas\_libs\parsers.pyx", line 1952, in pandas._libs.parsers.raise_parser_error
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb3 in position 366: invalid start byte

Process finished with exit code 1

A: The problem is that you are accessing an empty df1 with iloc. Also, iloc will return a value only, so you won't be able to concat that. Since the number of values is small, you can iterate over your dataframes, append these values to the list, and create a new dataframe instead:
values = []

for excel_file in excel_files:
    temp = pd.read_excel(excel_file)
    values.append(temp.iloc[1, 1])

df = pd.DataFrame({'values': values})
df.to_excel('path/here', index=False)


text:
Q: How to make a Website and API REST with Laravel with the same Controllers? I'm really new in Laravel Framework, I want to develop a Web Application that also has their own API Rest, but I don't know which is the best way to do it.
I want that the Controllers and methodos could be the sames for a Web opperation and for a API REST operation, for example for the Module of Users if I make a request like this:
http://myproject.com/userRegister/
Then the web shows me a view HTML with a form for user registration, but if I call a request like this:
http://myproject.com/api/userRegister/
Then the response will be a JSON with the Form data that I need for register the user.
I want that both of them use the UserRegisterController and the same method for example : "formRegister", all of this for avoid repeat bussines logic in differents methods.
Any idea of what is the best way to do this? I researched and some people recommend make all the services with JSON responses and parse with AngularJS or similar, but I don't want that, I want only use Laravel with HTML.

A: Let the same controllers handle api and web requests is not the best decision. Sooner or later this logic will lead to the mess in your code.
Do not forget to keep your controllers as thin as possible and move most of your logic to models, services and repositories. This will help you to have two standalone controllers versions that will have as less code as possible.
But if you still want to combine them you can use \Request::acceptsJson() \Request::acceptsHtml() methods to determine what type of request you have.


text:
Q: Trace representation of density matrix question System $A$ and system $B$ form a composite system.
https://en.wikipedia.org/wiki/Partial_trace
I wonder why $\rho_{AB}$ cannot be represented as $(\text{tr}_{B}(\rho))\otimes
(\text{tr}_{A}(\rho))$. I test it on Bell state and they are different. But can you give me a proof?
We know $\text{tr}_{B}(\rho)$ is the density matrix of system $A$.

A: You can represent $\rho_{AB}$ by $tr_B(\rho_{AB})\otimes tr_A(\rho_{AB})$ only if the two subsystems are not entangled, i.e. $\rho_{AB}=\rho_A \otimes \rho_B$.


text:
Q: Приложение не появляется в эмуляторе Собственно изучал себе спокойно андроид. Делал всякие  activity  layouts для них. Тестил в эмуляторе, который был в android-sdk пакете (extras/intel).
Все бы хорошо, однако в один прекрасный момент вышло каким-то так, что при запуске приложения оно и не запускалось автоматически в эмуляторе, и не присутствовало в меню.
Уже пробовал и переставлять все, что только можно, но ничего не помогает. Может кто-то сталкивался с такой проблемой. Как решали?
Работаю с IDEA 14. Вроде никаких ошибок не вылазит.
"C:\Program Files (x86)\android-sdk\tools\emulator.exe" -avd Nexus17 -netspeed full -netdelay none
emulator: device fd:784
HAXM is working and emulator runs in fast virt mode
creating window 40 81 335 557
emulator: emulator window was out of view and was recentered
emulator: UpdateChecker: skipped version check

Waiting for device.
"C:\Program Files (x86)\android-sdk\tools\emulator.exe" -avd Nexus17 -netspeed full -netdelay none
Device connected: emulator-5554

Сейчас попробовал просто запустить дефолтный helloworld
Файл манифеста. Ничего не менял.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="ru.smirnov.Application"
          android:versionCode="1"
          android:versionName="1.0">
    <uses-sdk android:minSdkVersion="17"/>
    <application android:label="@string/app_name" android:icon="@drawable/ic_launcher">
        <activity android:name="MainActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
</manifest>


text:
Q: router is on .1.1 but devices on .0.1 can I move devices Had a new provider and router last week and the lan is different. The IP is 192.168.1.1 but the devices ie: firestick has IP of 192.168.0.1 I am not good with networking and scared to change anything. can someone pls help. thx x

A: It sounds like you still have to routers connected.  Have you changed the Fire TV Stick to use the new router.  If you are using the same router, but the IP has changed, just power off the TV Stick and turn it back on.  It should clear any IP addresses the stick has.


text:
Q: Is SQL server 2008 storing uf8 I have a java servlet that is using utf8. I have entered numerous characters (chinese traditional, russian, etc) and they seem to be stored in and retreived from sql server 2008 fine. Does sql server 2008 handle utf8 encoded strings? If not, why no problems, yet.
    psmt.setString(7, myString); //myString is UTF8 encoded
    psmt.executeUpdate();

A: No, your string is actually UTF-16-encoded - it's a Java string, and Java strings are sequences of UTF-16 code units.
It (mostly) doesn't matter how SQL server stores the value internally, so long as it can represent the same character repertoire. Your SQL schema should determine what values can be stored - how they're stored is irrelevant.
There are potentially many important encodings here:

*

*The encoding you use when you present data from your app, e.g. via HTML

*The encoding used internally by Java (UTF-16, as least as it's exposed by the language)

*The encoding used to transfer data to the database (which is under the control of the database driver; this may or may not need to be configured)

*The encoding used to store the data within the database

All of these can be different - so long as they can store the same set of characters. So while the bytes used to represent ☃ (U+2603, Unicode Snowman) will be different when it's encoded in UTF-8 and UTF-16, so long as it can be encoded (and is encoded properly), that's all that matters.
Now there are some cases where the abstraction falls down, of course - if you ask for the length of a string in Java with the String.length(), that's the length in UTF-16 code units, not in Unicode characters. Similarly, if you've got SQL fields which are limited to a particular length, you should pay careful attention to what those units are. (I don't know offhand for SQL Server 2008, but I've seen databases where that's in terms of UTF-16 code units, and others where it's in terms of bytes required in the UTF-8 encoding.) So in that sort of situation, the difference can be important - but the general "Can I store my data?" question doesn't require the encodings to be the same.


text:
Q: How can I name a sqlite column "primary" with Rails? I'm trying to create this table in Rails:
create_table :artist_names do |t|
  t.string :name
  t.boolean :primary, :default => true
  t.integer :artist_id

  t.datetime :deleted_at
  t.timestamps
end

However, my queries against it fail:
[Dev]> ArtistName.all(:conditions => ['artist_names.primary = ?', true])  ArtistName Load (0.0ms)
SQLite3::SQLException: near "primary": syntax error: SELECT * FROM "artist_names" WHERE (artist_names.primary = 't') AND ("artist_names"."deleted_at" IS NULL)
ActiveRecord::StatementInvalid: SQLite3::SQLException: near "primary": syntax error: SELECT * FROM "artist_names" WHERE (artist_names.primary = 't') AND ("artist_names"."deleted_at" IS NULL)

My queries work when I change the column's name to something else, but the name "primary" makes the most sense to me.
How can I make this work while keeping the column name "primary"?

A: User back-ticks around primary word.
ArtistName.all(:conditions => ['`primary` = ?', true]) ...


text:
Q: Create own flutter plugin I would be glad if someone can point me a direction on creating own plugin. Let's say at first I have a dart class that will make a few api calls, basically are configurations apis from a server.
class Api {
Future<dynamic> getConfig() async {
  var response = await http.get(url, headers:header)
  return response;
}

But now I tend to make it into a plugin, for the other projects to use. But after I read on some tutorial on how to create plugin for flutter. I am a bit unclear on the structure. From what I have read, after created a plugin project, a lib, android, ios, and example directories will be created. File inside lib included this default code
static Future<String> get platformVersion async {
  final String version = await _channel.invokeMethod('getPlatformVersion');
  return version;
}

And the getPlatformVersion method is located in both android and ios folder, it has two different implementation written in java and objective c, but they do the same thing.
So my question is, does it mean that I need to write two different apis calling implementations for both ios (like NSURLConnection) and android (AsyncHttpClient )? Can't seem to find any answer out there.


text:
Q: Using Log Parser Studio and UrlScan Logs I'm trying to view UrlScan 3.1 Logs in Log Parser Studio 2.  I have tried selecting urlscanlog as the log type but no results are returned.  I can use log parser directly from the command line and parse urlscan logs without any problem. Log Parser Studio is also working fine with IIS logs.  Can anyone else open UrlScan Logs in Log Parser Studio? If so, what settings are being used?

A: First of all select TSVLOG as the log type. Then click on the gear symbol to the right of the log type. The iSeparator needs changing to space, the nSkip lines needs to be 4, and the header file needs pointing to a new file which contains only:
Date Time c-ip s-siteid cs-method cs-uri x-action x-reason x-context cs-data x-control
This is you setting that the separator is a space between each field, there are 4 lines in the log files to ignore at the start and then the header file contains the name of each field in the log file.
Once this was complete I was able to query urlscan logs in Log Parser Studio without a problem.


text:
Q: How to filter objects from template? I have 2 models Category and Spending where Category is one of the Spending fields.
User can create custom categories and add spending on the webpage.
The question is, how to filter spendings by categories in Template?
I have:
{% for category in categories %}
    {% for spending in spendings %} 'I want this FOR have only spendings from this category.'

I know how to filter objects with Object.objects.filter() but I am not sure it applies here, because categories are dynamic here

A: Use the reverse relation. You haven't shown your models, but presumably there is a foreign key from Spending to Category. If so:
{% for spending in category.spending_set.all %}

A: You can do this way.
{% for category in categories %}
     {% for spending in category.spending_set.all %}
         {{spending}}
     {% endfor %}
{% endfor %}


text:
Q: Where is the constant for "HttpRequest.RequestType" and "WebRequest.Method" values in .NET? I need to check the RequestType of an HttpRequest in ASP.NET (or WebRequest.Method). I know that I can just use the string values "POST" or "GET" for the request type, but I could have sworn there was a constant somewhere in some class in .NET that contained the values.
Out of curiosity I was wondering if anyone knew what class these string constants for GET and POST were in. I've tried searching online but I've had no luck, so I thought I'd ask here.

A: Also exists System.Net.Http.HttpMethod which can serve instead of enum. You can compare them aMethod == HttpMethod.Get, etc. To get string method name call e.g. HttpMethod.Get.Method.

A: In ASP.NET MVC they're in System.Web.Mvc.HttpVerbs.  But all methods that take one of these enum values also has a text override, as there is no complete set of HTTP verbs, only a set of currently defined values (see here and here and here).
You can't create an enumeration that covers all verbs, as there is the possibility that verbs can be added, and enumerations have versioning issues that make this impractical.

A: System.Net.WebRequestMethods.Http
    .Connect = "CONNECT"
    .Get = "GET"
    .Head = "HEAD"
    .MkCol = "MKCOL"
    .Post = "POST"
    .Put = "PUT"

Ultimately, though; since const expressions are burned into the caller, this is identical to using "GET" etc, just without the risk of a typo.

A: In ASP.NET Core you will find a collection of http method strings in the HttpMethods.cs class under the Microsoft.AspNetCore.Http namespace.
This class also offers boolean helpers such as IsGet() or IsPost() for better semantics.
Please note that these strings are exposed as public static readonly string and not as constants.
UPDATE 2020-05-17: GetCanonicalizedValue(string method) was added to the HttpMethods.cs class in ASP.NET Core v5, which returns the static instance equivalent to the provided string method name.


text:
Q: Google Sheets/Excel Web Scraping - Variable page count into Link URL If there's an easier way to do this please lmk, but this is what I have so far.
=importhtml("https://example/101", "list", 4)

There are 100 items per page, so if this is in A1, would like something like this:
=importhtml("https://example/201", "list", 4)

to go into A101 (or B1 and then change to single column later)
... and so on so the last part of the url keeps getting incremented by 100 each time.

A: try:
={IMPORTHTML("https://example/101", "list", 4)
  IMPORTHTML("https://example/201", "list", 4)}


text:
Q: Sorting and outputting a multi-dimensional array I have a multi-dimensional array right now that looks like this:
function art_appreciation_feeds() {
 $items = array(
  array('site' => '', 'uri' => '', 'feed' => ''),
  array('site' => '', 'uri' => '', 'feed' => ''),
  array('site' => '', 'uri' => '', 'feed' => ''),
  array('site' => '', 'uri' => '', 'feed' => ''),
 );
 return $items;
}

Right, so I output the values of the array using this function:
foreach($items as $i => $row) {

What I'm looking to do, is add another value to that array called category so that I'd have:
array(
  array('site' => '', 'uri' => '', 'feed' => '', 'category' => ''),
);

And when I'm going through the loop above, to output it in order by the category field with a
Category
 at the top only of each section.
Is that the best way to do this and if so, how would I change my loop to accommodate that?  Caveat: I can change the array as well if you think something else is better.
Thanks!

A: I am sure there are better ways to go about it and not sure if this is easy to do in your situation, but just a suggestion. Why not have the category as an array key and inserting all the records relevant to that category as sub array?
for instance:
$items['catname1'][] = array('site' => '', 'uri' => '', 'feed' => '');
$items['catname2'][] = array('site' => '', 'uri' => '', 'feed' => '');
$items['catname1'][] = array('site' => '', 'uri' => '', 'feed' => '');

and then sorting based on the array key?
Or if you dont want to add that extra layer. Add a counter value to catname and store the catname in the sub array itself like
$items['catname1'.$c] = array('site' => '', 'uri' => '', 'feed' => '', cat=>'catname1');
$items['catname2'.$c] = array('site' => '', 'uri' => '', 'feed' => '', cat=>'catname2');
$items['catname1'.$c] = array('site' => '', 'uri' => '', 'feed' => '', cat=>'catname1');

using ksort() you should be able to sort on the array key easily.

A: One way is using usort(), which allows you to specify a sort function:
function compareTwoItems($a, $b)
{
   return strcmp($a["category"], $b["category"]);
}

usort($items, "compareTwoItems");

Once usort() is done, the items are sorted, with all items of the same category being adjacent in the array.
If you want, you can continue to fine-tune your compareTwoItems() function -- e.g. do sub-sorting within a category:
function compareTwoItems($a, $b)
{
    $strcmp = strcmp($a["category"], $b["category"]);
    if ($strcmp != 0)
        return $strcmp;
    else
        return strcmp($a["site"], $b["site"]);
}

A: Use array_multisort to sort multiple or multi-dimensional arrays.
http://php.net/manual/en/function.array-multisort.php
Suppose, you have the following multi-dimensional array:-
array(
  array('site' => 'some value', 'uri' => 'some value', 'feed' => 'some value', 'category' => 'some value'),
  array('site' => 'some value', 'uri' => 'some value', 'feed' => 'some value', 'category' => 'some value'),
  array('site' => 'some value', 'uri' => 'some value', 'feed' => 'some value', 'category' => 'some value'),
  array('site' => 'some value', 'uri' => 'some value', 'feed' => 'some value', 'category' => 'some value'),
);

Suppose, the above array is stored in variable named $data
// Obtain a list of columns
foreach ($data as $key => $row) {
    $category[$key]  = $row['category'];
}

// Sort the data with category descending
// Add $data as the last parameter, to sort by the common key
array_multisort($category, SORT_DESC, $data);

Hope this helps.


text:
Q: Kafka-Connect For MSSQL Invalid value java.sql.SQLException: No suitable driver found for for configuration I am trying to connect kafka-connect to my local mssql with localhost:3030
I am receiving this error when I try to make a new connection for mssql. in centos 7(linux). Mssql data is from an external IP(windows), my consumer is inside of linux environment.

"No suitable driver found for configuration".

connect-distributed.properties is shown below;
plugin.path=/usr/local/share/java,/usr/local/share/kafka/plugins,/opt/connectors,

I added "ojdbc7-12.1.0.2.jar" file under /opt/connectors/kafka-connect-jdbc/ but still I am receiving error messages. I dont know what is wrong.
Also my connect-console-source.properties
name=source-sqlserver-user
connector.class=io.confluent.connect.jdbc.JdbcSourceConnector
tasks.max=1
topic.prefix=my-timestamp
connection.url=jdbc:sqlserver://externalIP;database=database;username=username;password=password

version: '2'

services:
  kafka-cluster:
    image: landoop/fast-data-dev:cp3.3.0
    environment:
      ADV_HOST: 127.0.0.1
      RUNTESTS: 0
    ports:
      - 2181:2181                 # Zookeeper
      - 3030:3030                 # Landoop UI
      - 8081-8083:8081-8083       # REST Proxy, Schema Registry, Kafka Connect ports
      - 9581-9585:9581-9585       # JMX Ports
      - 9092:9092                 # Kafka Broker

A: ojdbc7-12.1.0.2.jar is the JDBC driver for Oracle.
For MS SQL you need the MS SQL JDBC driver

Edit: Since you're using Docker to run Kafka Connect, you need to make the JDBC JAR file available to the Kafka Connect worker before it runs. You can't just run the Docker container and copy the JDBC driver into it, because you need to restart Kafka Connect afterwards.
To workaround this, you can mount the JAR from your local machine to the relevant path in the container. The relevant path is whereever the Kafka Connect JDBC jar is. Looking at the fast-data-dev image it's in
root@fast-data-dev / $ ls -l /opt/confluent-3.3.0/share/java/kafka-connect-jdbc
total 6544
-rw-r--r-- 1 root root  133842 Jul 28  2017 kafka-connect-jdbc-3.3.0.jar
-rw-r--r-- 1 root root  658466 Jul 28  2017 postgresql-9.4-1206-jdbc41.jar
-rw-r--r-- 1 root root 5575351 Jul 28  2017 sqlite-jdbc-3.8.11.2.jar

So you can run
docker run --rm --net=host --volume ~/Downloads/mssql-jdbc-7.4.1.jre8.jar:/opt/confluent-3.3.0/share/java/kafka-connect-jdbc/mssql-jdbc-7.4.1.jre8.jar landoop/fast-data-dev:cp3.3.0

or mount it in your Docker Compose with a volumes config:
version: '2'

services:
  kafka-cluster:
    image: landoop/fast-data-dev:cp3.3.0
    environment:
      ADV_HOST: 127.0.0.1
      RUNTESTS: 0
    ports:
      - 2181:2181                 # Zookeeper
      - 3030:3030                 # Landoop UI
      - 8081-8083:8081-8083       # REST Proxy, Schema Registry, Kafka Connect ports
      - 9581-9585:9581-9585       # JMX Ports
      - 9092:9092                 # Kafka Broker
    volumes:
      - ~/Downloads/mssql-jdbc-7.4.1.jre8.jar:/opt/confluent-3.3.0/share/java/kafka-connect-jdbc/mssql-jdbc-7.4.1.jre8.jar

It's worth noting that Confluent Platform 3.3.0 is really old - the latest is 5.3.1. If you want to see an up-to-date example of running Kafka, Kafka Connect, SQL Server etc with JDBC driver automatically set up see this example here.


text:
Q: iPhone - voice recording in background I'm using AVAudioRecorder and able to record voice of the user.
But how can I countinue recording the voice when the app goes to background also?

A: Honestly, it is allowed, you should set the key UIBackgroundModes's value to audio in the application's Info.plist file.


text:
Q: How to check if a button in bootstrap modal window clicked using PHP I have a page which has a button. When a user clicks on the button, a bootstrap modal window will pop up. The modal window has two buttons 'Close' and 'Save'.
Based on the bootstrap website, 'Close' will dismiss the window and no action will be triggered to that page. But, what I want is when user click on the other button (For example 'Save'), some action should happen (By using PHP).
If using php is not easy, then any other methods using javascript or jquery is also ok, but how to do that?
Could someone explain how to make the Save button do some actions?
For a reference, I copied the codes mentioned in the bootstrap website.
JSbin link: https://jsbin.com/rebuwuvefe/edit?html,output

<!DOCTYPE html>

  <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

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

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
  Launch demo modal
</button>

Modal title

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

        ...

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

A: I think you should reword the title of your question, as it is misleading to what you are really asking.
What you are looking for is jQuery's $.ajax method.
You can create a separate PHP script to perform whatever actions you need to perform on the database.
http://api.jquery.com/jQuery.ajax/
// Assuming the save button is already set to the variable
// 'save_button', use the jQuery $.click method to apply a
// click event listener to the button.
$(save_button).click(function(){
    // Initiate the jQuery AJAX request
    $.ajax({
        // Method of request, POST (insert) or GET (select)
        method: "POST",
        // Location of the PHP file that connects to the database
        url: "some.php",
        // The data you want to send to the php file
        // Think of this data format as:
        // some.php?name=John&location=Boston
        data: { name: "John", location: "Boston" }
    })
    // Do this function when the request is done and a response
    // is received. The variable msg will contain whatever the PHP
    // file outputs (for JS interpretation, usually JSON).
    .done(function( msg ) {
        alert( "Data Saved: " + msg );
    });
});

A: with jQuery:
Add an id to your button element:
<button id="save-button" type="button" class="btn btn-primary">Save changes</button>

Then attach the event listener:
$('#save-button').on("click", function (){
    // do something
});

Hope this helps!

A: Simple jQuery example

$(function() {
$( ".save-btn" ).on( "click", function() {
  alert('success');
});
});
<!DOCTYPE html>

  <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

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

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
  Launch demo modal
</button>

Modal title

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

        ...

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary save-btn">Save changes</button>

A: You can use Jquery click() method. I made a sample for you

$( "#sample" ).click(function() {
  alert( "You can AJAX call or whatever you want" );
  $('#exampleModal').modal('toggle');
});
<!DOCTYPE html>

  <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

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

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
  Launch demo modal
</button>

Modal title

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

        ...

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button id="sample"  type="button" class="btn btn-primary">Save changes</button>

.


text:
Q: Validating forms in HTML, PHP, and JavaScript If I am defining a function in JavaScript at the top of my page that validates if the string entered in a form is (A-Z,a-z, or 0-9). And then I call that function when they submit it saying :
onsubmit="return Validator(this);"

If the function name is :
function Validator(form)

Why isn't it actually validating the string submitted when we actually click on submit, and is there a better way of validating forms?

A: Almost certainly because the Validator function is not written correctly… but since you haven't shown us what it looks like, we can't say specifically why.
Perhaps it is expecting a String and you are giving it an HTMLFormElement.

A: An onsubmit handler function needs to return false to cancel the event (form submission) if you want to not submit and show a validation error message instead.
Plain Javascript approaches:
Form is still submitted even though listener function returns false
jQuery approaches:
How to not submit a form if validation is false

A: Lots of options for form validation.  Depending on your framework, you may want to use Jquery's validation.  If you go with yui, I have submitted a form validator that will be useful
Here is the gallery submission, from thee you can look at examples

A: You aren't submitting a string to Validator, you are submitting an input element. So you would do if(form.element.value != "") ... or something... And yes there is a better way


text:
Q: Problemas con wow.js y animate.css en adobe muse Estoy utilizando la versión de adobe muse 17.1, hace unos días todo funcionaba correctamente con las animaciones, pero de pronto las animaciones ya no funcionan más, y no entiendo porqué. Tengo varias teorías:
1.-Fallo de actualización de adobe muse.
2.-Fallo mío en el diseño, habré tocado algún botonsito (he desinstalado e instalado d nuevo)
3.-Adobe me está castigando por utilizar una versión pirata (juro comprarme la versión de pago si todo funciona correctamente, de momento no me convence).
He hecho una versión de prueba bastante sencilla para mostrarla por aquí, el código no es mi fuerte, aunque no veo ningún fallo importante o no soy capaz de detectarlo.
Agradecería cualquier ayuda al respecto.
 <!DOCTYPE html>

  <meta http-equiv="Content-type" content="text/html;charset=UTF-8"/>
  <meta name="generator" content="2017.1.0.379"/>

  <title>Inicio</title>

  <link rel="stylesheet" type="text/css" href="css/site_global.css?crc=444006867"/>
  <link rel="stylesheet" type="text/css" href="css/index.css?crc=4168683600" id="pagesheet"/>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.1/animate.min.css">

titulo

titulo

titulo

titulo

Muchas gracias de antemano!!


text:
Q: Some questions about the conditions for the CARE/DARE solutions I'm trying to understand the CARE/DARE solution and have a few questions. For example, for the CARE the equation is
$$A^tP + PA - PBR^{-1}B^tP+Q=0$$
where $P,Q,R,A,B$ are $n\times n$ matrices and $P,Q,R$ are symmetric; P is the unknown for which a solution is sought. This equation can be conveniently written as a "quadratic form"
$$X^t JZ X=0$$
where
$$X=\begin{pmatrix} 1 \\ P \end{pmatrix} \qquad J=\begin{pmatrix} 0 & 1 \\ -1 & 0 \end{pmatrix} \qquad Z=\begin{pmatrix} A & -BR^{-1}B^t \\ -Q & -A^t \end{pmatrix}$$
and $$JZ=\begin{pmatrix} -Q & -A^t \\ -A & BR^{-1}B^t\end{pmatrix}=(JZ)^t \, .$$
Since $JZ$ is symmetric, its $2n$ eigenvalues are all real. However, this doesn't imply that the eigenvalues of $Z$ are all real, but since the characteristic polynomial
$$\det\left(Z-t1 \right)=\det\left(JZ-tJ\right)=\det\left( (JZ-tJ)^t \right)=\det\left( JZ+tJ \right)$$
is an even function (with real coefficients) in $t$, every eigenvalue $\lambda$ actually occurs as $\lambda,-\lambda,\lambda^*,-\lambda^*$. Thus, if no eigenvalue is on the imaginary axis, half of all the eigenvalues have negative real part. Then we encode the corresponding subspace in the first column (block) of the eigenmatrix
$$U=\begin{pmatrix} U_{11} & U_{12} \\ U_{21} & U_{22} \end{pmatrix}$$
and see that $$X=\begin{pmatrix} 1 \\ U_{21} U^{-1}_{11}\end{pmatrix}$$
actually solves the equation $$X^t JZ X=\begin{pmatrix} 1 & U_{21} U^{-1}_{11} \end{pmatrix} JZ \begin{pmatrix} 1 \\ U_{21} U^{-1}_{11} \end{pmatrix}=\begin{pmatrix} - U_{21} U^{-1}_{11} & 1 \end{pmatrix} Z \begin{pmatrix} U_{11} \\ U_{21} \end{pmatrix} U^{-1}_{11} = \begin{pmatrix} - U_{21} U^{-1}_{11} & 1 \end{pmatrix} \begin{pmatrix} U_{11} \\ U_{21} \end{pmatrix} \Lambda_- U^{-1}_{11} = 0$$
where $\Lambda_-$ is the $n\times n$ matrix of negative eigenvalues on the diagonal. Now I have two questions:

*

*Why are only the negative eigenvalues of interest? I mean, obviously the positive eigenvalues also give rise to solutions. What does it have to do with the loop transfer matrix
$$A-BR^{-1}B^t P$$
for the system to be stable?

*How do you see that this loop transfer matrix has only negative eigenvalues? I mean, by putting the corresponding subspace into the first column of U, is just a convention and not a conclusion, isn't it?


text:
Q: Name for hyperbolic analogue of a parallelogram? Is there a name for a hyperbolic quadrilateral where opposite sides have equal length, or equivalently so that the diagonals bisect each other, as shown below?

"Hyperbolic parallelogram" is the obvious name (and it seems to be used a little), but has the obvious downside that these quadrilaterals generalize many properties of Euclidean parallelograms, but not the property that gives the "parallelogram" its name.
In a paper I need the easy lemma that
$$
\cosh (OX)\cosh(OY) = \frac{\cosh(XY) + \cosh(YZ)}{2}
$$
generalizing the Euclidean parallelogram law. In general these quadrilaterals seem pretty pleasant to work with.

A: If you're looking for a self-describing term, consider point-symmetric quadrilateral. Alternatively, rhomboid is an uncommon term for parallelograms, but traditionally only refers to parallelograms that are neither rectangles or rhombi.


text:
Q: Animating color for vtkGlyph3D object in VTK I want to render a fixed number of spheres with fixed positions and modify their colors with time.
I create a vtkPolyData object with the corresponding positions and then create a vtkGlyph3D with the vtkPolyData object as input and a vtkSphereSource object as the source.
The colors are stored in a Scalars-array of the vtkPolyData object.
Currently I am using a RepeatingTimer and I set the input and source of the vtkGlyph3D object again and again in the execute method. This seems like a very inefficient approach. Is there a way to only update the color-values in the Scalars-array of the vtkPolyData object?
Obviously just changing the array-values and calling the Update method of the vtkGlyph3D object doesn't work.
import numpy as np
import vtk

class vtkTimerCallback():

    def __init__(self, tspan, radius, mapper, actor, glyph, polyData):
        self._tspan = tspan
        self._radius = radius
        self._mapper = mapper
        self._actor = actor
        self._glyph = glyph
        self._polyData = polyData
        self._timeIndex = 0

    def execute(self, obj, event):
        array = self._polyData.GetPointData().GetScalars()
        for i in xrange(coords.shape[0]):
            v = int(float(i) / coords.shape[0] * 255)
            if self._timeIndex % 2 == 0:
                red = 0
                green = 255 - v
                blue = v
            else:
                red = v
                green = 0
                blue = 255 - v
            array.InsertTuple3(i, red, green, blue)
        self._polyData.Update()
        sphereSource = vtk.vtkSphereSource()
        sphereSource.SetRadius(self._radius)
        self._glyph.SetColorModeToColorByScalar()
        self._glyph.SetSource(sphereSource.GetOutput())
        self._glyph.SetInput(self._polyData)
        self._glyph.Update()
        self._mapper.SetInput(self._glyph.GetOutput())
        self._mapper.Update()

        self._timeIndex += 1
        if self._timeIndex >= self._tspan.shape[0]:
            self._timeIndex = 0
        iren = obj
        iren.GetRenderWindow().Render()

def viewData(coords, tspan, radius=0.1, interval=50):
    points = vtk.vtkPoints()
    points.SetNumberOfPoints(coords.shape[0])
    for i in xrange(coords.shape[0]):
        coord = coords[i, :]
        points.InsertPoint(i, coord[0], coord[1], coord[2])

    polyData = vtk.vtkPolyData()
    polyData.SetPoints(points)

    array = vtk.vtkUnsignedCharArray()
    array.SetName('colors')
    array.SetNumberOfComponents(3)
    array.SetNumberOfTuples(coords.shape[0])
    polyData.GetPointData().SetScalars(array)

    sphereSource = vtk.vtkSphereSource()
    sphereSource.SetRadius(radius)

    glyph = vtk.vtkGlyph3D()
    glyph.SetColorModeToColorByScalar()
    if vtk.VTK_MAJOR_VERSION <= 5:
        glyph.SetSource(sphereSource.GetOutput())
        glyph.SetInput(polyData)
    else:
        glyph.SetSourceConnection(sphereSource.GetOutputPort())
        glyph.SetInputData(polyData)
    glyph.ScalingOff()
    glyph.Update()

    #glyph.FillCellDataOn()

    # Create a mapper and actor
    mapper = vtk.vtkPolyDataMapper()
    if vtk.VTK_MAJOR_VERSION <= 5:
        mapper.SetInput(glyph.GetOutput())
    else:
        mapper.SetInputConnection(glyph.GetOutputPort())

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    # Create a renderer, render window, and interactor
    renderer = vtk.vtkRenderer()
    renderer.AddActor(actor)

    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)
    renderWindowInteractor.Initialize()

    # Register callback for animation
    cb = vtkTimerCallback(tspan, radius, mapper, actor, glyph, polyData)
    renderWindowInteractor.AddObserver('TimerEvent', cb.execute)
    timeId = renderWindowInteractor.CreateRepeatingTimer(interval)

    cb.execute(renderWindowInteractor, None)

    renderWindow.Render()

    # Render and interact
    renderWindowInteractor.Start()

if __name__ == '__main__':
    # Create a 3D-grid of 11x11x11 points
    r = np.linspace(-10.0, 10.0, 15)
    X, Y, Z = np.meshgrid(r, r, r)
    X, Y, Z = X.flatten(), Y.flatten(), Z.flatten()
    coords = np.array([(X[i], Y[i], Z[i]) for i in xrange(X.shape[0])], dtype=np.double)
    tspan = np.arange(100, dtype=np.double)
    viewData(coords, tspan, radius=0.5, interval=1)


text:
Q: Regex Find Text Between Previous Period and String Example Text:  "This is the beginning.  First group of words.  Second plain sentence.  Another set of words."
Pattern logic:  Match anything between the word "sentence" and the preceding period.  The match may extend multiple lines.
Desired match:  "  Second plain "
Note:  Match should not include quotation marks.

A: this is pretty simple:
\.([^.]+?)sentence

the match is the first group ($1)

A: without grouping, using look ahead (zero width)
 [^.]*(?=sentence)


text:
Q: regex check if array contains some words I have an array of matching words:
$search = array("lorem","dolor","sit");

And an array to search in:
 $results= array(
       "Lorem ipsum dolor sit amet, consectetur",
       "Ut enim ad minim veniam, quis nostrud exercitation"
       "Duis aute irure dolor in reprehenderit in voluptate velit esse"
       "Excepteur sint occaecat cupidatat non proident"
    );

Is there a regex to return true  where two of given words are matching?

A: You could use a word boundary \b in your regular expression.

A word boundary is a position between \w and \W (non-word char), or at the beginning or end of a string if it begins or ends (respectively) with a word character.

So maybe something like this..
foreach ($results as $result) {
   $pattern = "/\b(" . implode('|', $search) . ")\b/i";
   $found   = preg_match_all($pattern, $result, $matches);

   if ($found) {
     print_r($matches[0]);
   }
}

Or you could do away with your search array and just use it as a regular expression:
foreach ($results as $result) {
   $found = preg_match_all("/\b(?:lorem|dolor|sit)\b/i", $result, $matches);
   if ($found) {
     print_r($matches[0]);
   }
}

Output:
Array
(
    [0] => Lorem
    [1] => dolor
    [2] => sit
)
Array
(
    [0] => dolor
)

A: You can generate a regex to search by this
$regex = '/(' . implode('|', $search) . ')/i';

which will be:
/(lorem|dolor|sit)/i

The /i makes it caseless.
You can then use the return value of preg_match_all() to see the number of matched words.