text:
Q: Can't pickle a module object while using Hyperopt for Logistic Regression I am trying to fine tune Logistic Regression using Hyperopt in Python. Please find the optimization function below:
def objective(params, n_folds = N_FOLDS):
    """Objective function for Logistic Regression Hyperparameter Tuning"""

    # Perform n_fold cross validation with hyperparameters
    # Use early stopping and evaluate based on ROC AUC

    clf = LogisticRegression(**params,random_state=0,verbose =0)
    cv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1)
    score = cross_val_score(clf, X_train, y_train, cv=cv, scoring='f1_macro')

    # Extract the best score
    best_score = max(score)

    # Loss must be minimized
    loss = 1 - best_score

    # Dictionary with information for evaluation
    return {'loss': loss, 'params': params, 'status': STATUS_OK}

While running the algorithm, It is showing me the following error.
TypeError: can't pickle module objects

TypeError                                 Traceback (most recent call last)
<ipython-input-22-934e4c484469> in <module>
      6
      7 # Optimize
----> 8 best = fmin(fn = objective, space = space, algo = tpe.suggest, max_evals = MAX_EVALS, trials = bayes_trials)

<ipython-input-20-d9ea5e676676> in objective(params, n_folds)
      7     clf = LogisticRegression(**params,random_state=0,verbose =0)
      8     cv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1)
----> 9     score = cross_val_score(clf, X_train, y_train, cv=cv, scoring='f1_macro')
      10
      11     # Extract the best score

How can I solve this problem?

A: I have solved the question by removing the class weight parameter from the space.
space = {

    'warm_start' : hp.choice('warm_start', [True, False]),
    'fit_intercept' : hp.choice('fit_intercept', [True, False]),
    'tol' : hp.uniform('tol', 0.00001, 0.0001),
    'C' : hp.uniform('C', 0.05, 3),
    'solver' : hp.choice('solver', ['newton-cg', 'lbfgs', 'liblinear', 'sag', 'saga']),
    'max_iter' : hp.choice('max_iter', range(5,1000))
}


text:
Q: request.form did not show value I try to send value CSRFToken inside a form and I try to recall it but it did not show any value, the form type is POST, in javascript the value of CSRFToken is exist but when i try to request form the value is empty
function OutputForm()
%>
    <form name="frmSend" method="POST" enctype="multipart/form-data" action="Upload_Data_Transaksi.asp" onSubmit="return onSubmitForm();">

            Data Transaksi

            File : <input name="attach1" type="file" size=50>

                <input type="text" name="CSRFToken" value="<%= token %>" readonly>

                <input style="margin-top:4" type=submit value="Upload">

Tipe File Harus .mdb !

    </form>
<%
end function

<%
Dim diagnostics
if Request.ServerVariables("REQUEST_METHOD") <> "POST" then
    diagnostics = TestEnvironment()
    if diagnostics<>"" then
        response.write "
"
        response.write diagnostics
        response.write "
After you correct this problem, reload the page."
        response.write "
"
    else
        response.write "
"
        OutputForm()
        response.write "
"
    end if
else
    userauthentication()
    response.write "
"

    response.Write request.form("CSRFToken")
    response.End
    OutputForm()
    %>

         <% x = SaveFiles()
        if left(x,1)=1 then

            Response.Redirect "insert_mdb.asp?nmfile=us3r" & SESSION("User_id") & mid(x,3)
        else
        response.Write x
        end if
        %>

    <%

    response.write "

"
end if

%>

i try to recall it in request.form("CSRFToken") but it show no value, i alert it on javascript it show the value how do i solve this?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to Clear previous ajax response images before appending new images using ajax? I want to clear my previous ajax response images before appending new images please help me how can i do that ? thank u.
Ajax
<script>
$(document).ready(function(){
    var preloaded = [];
    $(document).on('click','.editBtn',function(){
        var marchandiseId = $(this).data("id");
        var file ="{{Config('wfh.file')}}";

        $(".input-images-edit").empty();
        $("#editModel").modal('show');
        var url = "{{URL('/marchandise/edit/')}}";
        $.ajax({
            type:"GET",
            url: url + '/' + marchandiseId,
            dataType:'JSON',
            success:function (response){

                var data = response.marchandise.marchandise_details;

                $.each(data, function(i, item) {
                    preloaded.push({id: item.id, src:  file + '' + item.images });
                });
                $('.input-images-edit').imageUploader({
                    preloaded: preloaded,
                    imagesInputName: 'photos',
                    preloadedInputName: 'old'
                });
            }
        });
    });


text:
Q: Problem with test keys of a snapshot.value I have this solution that works, but I don't want to take any risks with import problems in Firebase. I want to verify that the [Nom], [Prenom], [Club], [Cat], [License] and [Selected] keys exist in dtlSnapdict. I couldn't find a solution that worked
Do you have an idea
Thank you very much for your help
Best regards
Georges
 if let snapDict = snapshot.value as? [String:AnyObject]{

    for dtlSnapdict in snapDict as [String:AnyObject]{
        self.contenuliste.removeAll()
        self.nom = dtlSnapdict.value["Nom"] as! String
        self.prenom = dtlSnapdict.value["Prenom"] as! String
        self.club = dtlSnapdict.value["Club"] as! Int
        self.cat = dtlSnapdict.value["Cat"] as! String
        self.licence = dtlSnapdict.value["Licence"] as! Int
        self.selected = dtlSnapdict.value["Selected"] as! String


text:
Q: Assigning occurrences of whitespace to variables I was wondering if it possible to assign occurrences of characters to variable until I hit a white space character.
For instance if I have the string "17 23 4 54 6 343 4" How would I assign the first number 17 to a variable, and the next subsequent numbers.

A: String values = "17 23 4 54 6 343 4";
String[] variables = values.split("\\s");

Now you've got an array variables that holds 17 in variables[0], 23 in variables[1] and so on.

A: I would use a Scanner:
import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        String input = "17 23 4 54 6 343 4";
        Scanner s = new Scanner(input);

        while (s.hasNextInt())
            System.out.println(s.nextInt());
    }
}

Output:
17
23
4
54
6
343
4

How would I assign the first number 17 to a variable, and the next subsequent numbers.

If you literally want the first value in one variable, and the remaining string in another, you could do:
String input = "17 23 4 54 6 343 4";
Scanner s = new Scanner(input);

int firstValue = s.nextInt();
String remaining = s.nextLine();

A: Just use a split and a list or a Scanner

A: You could just split on whitespace, then loop over the resulting array and convert the String representation of the numbers to actual ints.
Something like
String input = "17 23 4 54 6 343 4";
String [] inputTokens = input.split(" ");
List<Integer> result = new ArrayList<Integer>();

for (String string : inputTokens) {
    result.add(new Integer(string.trim()));
}

A: You could use the Scanner to class to read the String.
Scanner input = new Scanner("17 23 4 54 6 343 4");
while(input.hasNextInt()) {
    int theValue = input.nextInt();
}


text:
Q: Video Duration Convert PHP I have a function what is convert the video duration example = 856.7 is 14:17
function duration( $duration )
{
    $duration_formated  = NULL;
    $duration           = round($duration);
    if ( $duration > 3600 ) {
        $hours              = floor($duration/3600);
        $duration_formated .= sprintf('%02d',$hours). ':';
        $duration           = round($duration-($hours*3600));
    }
    if ( $duration > 60 ) {
        $minutes            = floor($duration/60);
        $duration_formated .= sprintf('%02d', $minutes). ':';
        $duration           = round($duration-($minutes*60));
    } else {
        $duration_formated .= '00:';
    }

    return $duration_formated . sprintf('%02d', $duration);
}

but how i can convert 14:17 to show me the video duration 856.7


text:
Q: Cumulative Probability Suppose the % of an independent event happening is 20%. If I want to compute the probability of the independent event occurring at least 1 or more times if the event happens two times, would I be correct with the following math:
100 - ((100 - 20%) * (100-20%) / 100)

To illustrate, say you have 5 unique cards, so drawing at random 1 card, the chance of that card being the desired one, is 20%. But if I draw once, put the card back, and draw again, what are the CUMULATIVE odds of getting the desired card at least ONCE in either the first OR second draw.
If my math above is correct, the answer would be "The chance of drawing the desired card at least once over those two draws is 36%. Am I correct in my thinking?

A: Yes, your formula is, essentially, the Rule of product applied to Complementary events.


text:
Q: How to reformat data stored in a record and output it in oracle Let's go about this with an example
Let's say my table column holds the following data
   Col_ID  Col_Name
   ------  ---------------------------------------------------
   102     LOCATION_ID IN (7351,7550,76202,7350)
   121     265,76700,76701,72701,74210)
   111     ,76200,76201,76202,76203,76204,76205,76206,76207,7

The above data is stored in that manner in the tables already which cannot be changed. The output that I desire is as follows:-
     Col_ID Col_Name
     ------ --------
        102     7531
        102     7550
        102    76202
        102     7350
        121      265
        121    76700

And So on.....

A: There are multiple ways of extracting data from a delimited string.
One of which is to use a recursive sub-query factoring clause:
WITH data ( col_id, col_name, lvl, max_lvl, value ) AS (
  SELECT col_id,
         col_name,
         1,                                                  -- First level
         REGEXP_COUNT( col_name, '\d+' ),                    -- Count the number of numbers
         TO_NUMBER( REGEXP_SUBSTR( col_name, '\d+', 1, 1 ) ) -- Extract the first number
  FROM   your_table
  WHERE  1 <= REGEXP_COUNT( col_name, '\d+' )                -- Check there is a number
UNION ALL              -- Iterate over the previous rows
  SELECT col_id,
         col_name,
         lvl + 1,      -- Increase the level by one
         max_lvl,
         TO_NUMBER( REGEXP_SUBSTR( col_name, '\d+', 1, lvl + 1 ) )
                       -- Extract the (lvl+1)th number from the string.
  FROM   data
  WHERE  lvl < max_lvl -- Continue until all the numbers have been parsed
)
SELECT col_id,
       value
FROM   data;

A: The parenthesis is removed with some pattern, so try as below and make necessary modifications.
WITH outer_table
     AS (SELECT col_id, col_name
           FROM (SELECT col_id,
                        REGEXP_SUBSTR (col_name,
                                       '[^)]+',
                                       1,
                                       1)
                           col_name
                   FROM t5
                  WHERE col_name LIKE '%)%'
                 UNION ALL
                 SELECT col_id,
                        REGEXP_SUBSTR (col_name,
                                       '[^(]+',
                                       1,
                                       2)
                           col_name
                   FROM t5
                  WHERE col_name LIKE '%(%'
                 UNION ALL
                 SELECT col_id, (col_name) col_name
                   FROM t5
                  WHERE col_name NOT LIKE '%(%' AND col_name NOT LIKE '%)%'))
    select col_id, regexp_substr(col_name,'[^,]+',1,column_value) col_name
     from  outer_table,
           table(
                 cast(
                     multiset(
                              select  level
                                from  dual
                                connect by level <= length(regexp_replace(col_name,'[^,]')) + 1
                             )
                     as sys.OdciNumberList
                    )
               )
  ORDER BY col_id,col_name

Demo

A: WITH T AS
(SELECT '102' AS COL_ID, 'LOCATION_ID IN (7351,7550,76202,7350)' AS       COL_NAME
FROM   DUAL
UNION ALL
SELECT '121', '265,76700,76701,72701,74210)'
FROM   DUAL
UNION ALL
SELECT '111', ',76200,76201,76202,76203,76204,76205,76206,76207,7'
FROM   DUAL)
SELECT COL_ID, COL_NAME
FROM   (SELECT T.COL_ID,
            REGEXP_SUBSTR(REGEXP_SUBSTR(T.COL_NAME, '[^,]+', 1,
                                         T1.COLUMN_VALUE), '[0-9]+', 1, 1) AS COL_NAME
     FROM   T,
            TABLE(CAST(MULTISET
                        (SELECT LEVEL
                         FROM   DUAL
                         CONNECT BY LEVEL <=
                                    REGEXP_COUNT(T.COL_NAME, ',') + 1) AS
                        SYS.ODCINUMBERLIST)) T1)
WHERE  COL_NAME IS NOT NULL


text:
Q: OCaml: Type Checking Objects If I have an object, how can I determine its type? (Is there an OCaml equivalent to Java's instanceof operator?)

A: OCaml has structural typing for objects rather than nominative typing as in Java. So the type of an object is basically determined (and only determined) by its methods. Objects in OCaml can be created directly, without going through something like a class.
You can write functions which require that its argument objects have certain methods (and that those methods have certain types); for example, the following method takes an argument that is any object with a method "bar":
let foo x = x#bar

A: There's a discussion of "Matching Objects With Patterns" on Lambda the Ultimate (the paper uses Scala as the language, so won't answer your question).  A more relevant Ocaml mailing list thread indicates that there's no RTTI/safe-downcasting for objects.
For algebraic (non object) types you obviously have:
match expr with
  Type1 x -> x
  Type2 (x,y) -> y

called (pattern) matching
Someone did write an extension that allows down/up-casting Ocaml objects.

A: In short, you have to encode your own RTTI mechanism.  OCaml provides no RTTI or up/down casting (the latter in part because inheritance and subtyping are orthogonal in OCaml rather than unified as in Java).
You could do something with strings or polymorphic variants to encode type information in your classes and objects.  I believe that LablGTK does some of this, and provides a utility library to support object tagging and up/down casting.

A: Somewhat out-of-topic, but the OPA language (which draws heavily from some aspects of OCaml), allows the equivalent of pattern-matching on objects. So it's quite feasible.


text:
Q: MVC controller's string[] parameter is null when posting JSON data I post data with jQuery but I have a problem with array data. The values supplied to the MVC controller are always null.
This is my JavaScript code:
 var FilterCategory = $('input:checkbox:checked').map(function () {
                return this.value;
            }).get();
 var posting = $.post(url, { cursorid: lastid, CatFilter: FilterCategory });

The form data from the network:
cursorid:5434cdc84ba4dd0c40396851
Filter[]:1
Filter[]:3
Filter[]:4

Here's the C# side:
public ActionResult GetDataTweets(string cursorid,string[] CatFilter)
    {
       bla bla
    }

cursorid has a value, but CatFilter is null.
What do I need to do to have the correct value supplied to CatFilter?

A: This code here:
var posting = $.post(url, { cursorid: lastid, CatFilter: FilterCategory });

From MVC's perspective it's sending a class, so you need a reciprocal C# class to package the data.
Create a class to handle that data, for example:
I am assuming your CatFilter array is a string array:
public class Data{
  public string cursorid { get; set;}
  public string[] CatFilter {get; set;}
}

Then change your controller:
public ActionResult GetDataTweets(Data data)
{
   var s1 = data.cursorid;
   var s2 = data.CatFilter[0];
}

if CatFilter is a class then you'd need to create a CatFilter class to map to the javascript version.


text:
Q: Create thumbnail after upload of any file extension I want to upload a file with any extensions and then from that extension I need to create the thumbnail image for that particular image.
For example, if I upload .pdf file then the thumbnail image should be 'pdf.jpg', so as if .docx file then should be 'word.jpg' and if .zip file then name should be 'zip.jpg'.
I have tried to do this but no luck, file is uploaded but thumbnails is not.
Is there any codes which can do this, I mean to upload any extension and from that extension to create the thumbnail image also?
If any one has idea please share.  :)


text:
Q: How to implement radion button with check box in one tree in flex 3.0 Here is main Application file
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="initList()">

 <mx:Script>
  <![CDATA[
   import mx.managers.PopUpManager;
   import mx.messaging.channels.StreamingAMFChannel;
   import mx.events.ListEvent;
   import mx.collections.ArrayCollection;
   import mx.rpc.events.ResultEvent;
   import mx.collections.XMLListCollection;
   import mx.controls.Alert;

   [Bindable]
   public static var tList:XML;

   private function initList():void{
    tree_List.send();
   }

   private function onResultList(event:ResultEvent):void{
    tList = new XML(event.result);
   }

   private function addTreeNode():void{
    var cNode:CreateNode = new CreateNode();
    PopUpManager.addPopUp(cNode,this,true);
   }

   private function addItem():void{
    if(treeComp.selectedItem == null){
    }
    else{
     if(XML(treeComp.selectedItem).@first=="true")
      XML(treeComp.selectedItem).appendChild("<item state='unchecked' isBranch='false' label='New Label' first='true'/>");
     else
      XML(treeComp.selectedItem).appendChild("<item state='unchecked' isBranch='false' label='New Label' first='false'/>");
    }
   }

   public function remTreeNode():void {
               treeComp.dataDescriptor.removeChildAt(XML(treeComp.selectedItem).parent(),XML(treeComp.selectedItem),XML(treeComp.selectedItem).childIndex())
            }

            private function saveTreeNode():void{
             Alert.show(tList);
            }

            protected function treeComp_dblClickHandler(event:ListEvent):void
            {
                Tree( event.target ).editedItemPosition = {columnIndex: 0, rowIndex: event.rowIndex };
            }

            protected function treeComp_itmEditBegHandler(event:ListEvent):void
            {
                event.preventDefault();
            }
  ]]>
 </mx:Script>
 <mx:HTTPService
  id="tree_List"
  resultFormat="xml"
  result="onResultList(event)"
  showBusyCursor="true"
  method="POST"
  url="Tree/List.xml"
  useProxy="false"
 />

 <mx:Canvas id="canMain" width="340" height="100%" minWidth="100">
  <mx:Tree id="treeComp" itemRenderer="CheckTreeRenderer" toolTip="For deselection press ctl and click"
   labelField="@label"
   showRoot="false"
   width="340"
   height="{canMain.height - treeComp.y - 2}"
   dataProvider="{tList}"

   editable="true"
         doubleClickEnabled="true"
         itemDoubleClick="treeComp_dblClickHandler(event)"
         itemEditBeginning="treeComp_itmEditBegHandler(event)"
         folderOpenIcon="{null}"
         folderClosedIcon="{null}"
         defaultLeafIcon="{null}"
        />

 </mx:Canvas>
</mx:Application>

here is the ItemRenderer file
package
{
 import flash.events.MouseEvent;
 import flash.xml.*;

 import mx.collections.*;
 import mx.controls.CheckBox;
 import mx.controls.Image;
 import mx.controls.RadioButton;
 import mx.controls.Tree;
 import mx.controls.listClasses.*;
 import mx.controls.treeClasses.*;
 import mx.controls.RadioButtonGroup;

 public class CheckTreeRenderer extends TreeItemRenderer
 {
        protected var myImage:Image;
        // set image properties
        private var imageWidth:Number  = 6;
     private var imageHeight:Number  = 6;
        private var inner:String  = "inner.png";
  protected var myCheckBox:CheckBox;
  public var RadioBtnGR:RadioButtonGroup
  protected var myRadio:RadioButton;
  static private var STATE_SCHRODINGER:String = "schrodinger";
  static private var STATE_CHECKED:String = "checked";
  static private var STATE_UNCHECKED:String = "unchecked";
  public var itemXml:XML;

        public function CheckTreeRenderer ()
  {
   super();
   mouseEnabled = false;
  }

  override protected function createChildren():void
  {
   super.createChildren();
   myCheckBox = new CheckBox();
   myCheckBox.setStyle("verticalAlign", "middle");

   addChild(myCheckBox);

   myRadio = new RadioButton();
   //RadioBtnGR = new  RadioButtonGroup();
   //RadioBtnGR =
   //myRadio.group = RadioBtnGR
   myRadio.setStyle("verticalAlign", "middle");
   addChild(myRadio);

     }

  override public function set data(value:Object):void
  {
   super.data = value;
    /* if(value != null){

                this.itemXml = XML(value);
                if(this.itemXml.@check == true ){
                    this.myRadio.selected = true;
                }else{
                    this.myRadio.selected = false;
                }
      }*/
     }

     override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void{
            super.updateDisplayList(unscaledWidth,unscaledHeight);
            if(super.data){

                var tld:TreeListData = TreeListData(super.listData);
                if(tld.hasChildren){
                    this.myCheckBox.visible = false;
                    this.myRadio.visible = true;
                    //this.myRadio.groupName = data.@label
                }else{
                    /* You HAVE to have the else case to set visible to true even though you'd think
                    the default would be visible it's an issue with itemrenderers... */
                    this.myCheckBox.visible = true;
                    this.myRadio.visible = false;
                }
                if(data.@first == "true"){
                 myRadio.visible = false;
     myCheckBox.visible = true;
                }
                else{
                 //this.myRadio.groupName = data.@label
                 //addChild(myRadio);
                 myRadio.visible = true;
     myCheckBox.visible = false;
                }
                if(data.@isBranch =="true" ){
                 myRadio.visible = false;
     myCheckBox.visible = false;
    }
                if(myCheckBox.visible || myRadio.visible){
                    //if the checkbox is visible then reposition the controls to make room for checkbox
                    this.myCheckBox.x = super.label.x
                    this.myCheckBox.y = super.label.y + 10;
                    this.myRadio.x = super.label.x ;
                    this.myRadio.y = super.label.y + 10;
                    super.label.x = this.myRadio.x + 15;
                }
            }
        }
 }
}

here is the xml file for accessing the data
<list>
 <group state="unchecked" isBranch="true" label="Grains" first="true">
  <item state="unchecked" isBranch="false" label="White Bread" first="true"/>
  <item state="unchecked" isBranch="false" label="Wheat Bread" first="true"/>
  <item state="unchecked" isBranch="false" label="Pasta Bread" first="true" />
  <item state="unchecked" isBranch="false" label="Oatmeal Bread" first="true"/>
 </group>
 <group id="itm1" state="unchecked" isBranch="true" label="Dairy" first="false" >
  <item state="unchecked" isBranch="false" label="Milk" first="false" check="true" parentid="itm1"/>
  <item state="unchecked" isBranch="false" label="Cheese" first="false" check="false" parentid="itm1"/>
  <item state="unchecked" isBranch="false" label="Yogurt" first="false" check="false" parentid="itm1"/>
 </group>
 <group state="unchecked" isBranch="true" label="Fruits" first="true">
  <item state="unchecked" isBranch="false" label="Apple" first="true"/>
  <item state="unchecked" isBranch="false" label="Banana" first="true"/>
  <item state="unchecked" isBranch="false" label="Citrus" first="true"/>
 </group>
 <group id="itm2" state="unchecked" isBranch="true" label="Nuts" first="false">
  <item state="unchecked" isBranch="false" label="Pecans" first="false" check="true" parentid="itm2"/>
  <item state="unchecked" isBranch="false" label="Cashews" first="false" check="false" parentid="itm2"/>
  <item state="unchecked" isBranch="false" label="Brazil Nuts" first="false" check="false" parentid="itm2"/>
  <group state="unchecked" isBranch="false" label="Check" first="false" check="false" parentid="itm2">
   <item state="unchecked" isBranch="false" label="Testnut" first="false" check="false" parentid="itm2"/>
  </group>
 </group>
</list>

Problem is radio button click show once in the tree,for ex. suppose we have two nodes in tree in this have the radio button but when clicking on the first node radio button automatically second node radio button deselect.
not separated each node radio button with others node radio button

A: I think what you're saying is that when you check one radio button in your tree, all the others are unchecked, which is not what you want.  This is how radio buttons behave.  If you want to be able to check the buttons independently, you need to use check boxes.  If you want the buttons to work in smaller groups, you need to define those groups.


text:
Q: Thumbnails from JS Gallery Placed in Footer I am trying to add the thumbnails section of the js gallery in the footer of a web page. I've never broken up a gallery before and figured it's the only way to achieve this look
http://img69.imageshack.us/img69/5923/bsade.jpg
The link for what I have now is this: http://www.marisaraskin.com/two.html.
(The borders are just guides for me while I'm still working on it)
The CSS code for the thumbnails container is:
.galleria-thumbnails-container {
    height: 100px;

    bottom: 0;

    position: absolute;

    left: 10px;

    right: 10px;

    z-index: 1;

    border:1px solid yellow;

}

I'm not sure what my other options are for this. I was maybe thinking overlapping the content container over the footer with z-index. Though I'm iffy about that especially because everyone's screen resolution is different. I can post more code per request. I am not sure what else you need to see as of now.
In case you need to know I'm using a gallery js called "Galleria" (classic).

A: If I were you I'd modify the js script so that you can populate blocks that are not contiguous in the actual HTML code, but here's a rough approach to doing it all through css:

*

*remove position:relative from #container

*remove position:relative from .galleria-container

*add position:absolute to .galleria-stage and remove left and right
positioning. Also, add top:90px (or something close to that) and
give it a width: width:920px.

*change .galleria-thumbnails-container to use absolute positioning and
use the bottom:___ property to set it where you belong.

Basically what you're doing here is removing all the relatively positioning in the parent elements of the gallery so that the gallery segments all all being positioned with respect to the page rather than any of their parent elements. Once this is done, you can just modify the absolute positioning and width of the stage block and the thumbnail block so that they sit where you want them.


text:
Q: Cant update values in mysql database php I am trying to update a record on my admin mysql table. But still no changes when i try this method.. I can't see the problem wth this code..
Info.php
<?php
$query = "SELECT * from admin where username = '{$_SESSION['login_user']}'";
$result = mysqli_query($conn,$query);

while($row=mysqli_fetch_assoc($result))
    {
          echo '<input type="text" class="form-control" name="user_id" disabled value='.$row['user_id'].'>';
          echo '<input type="text" class = "form-control" name = "lastname"  value='.$row['lname'].'>';
          echo '<input type="text" class = "form-control" name = "firstname"  value='.$row['fname'].'>';
          echo '<input type="text" class = "form-control" name = "middlename"  value='.$row['mname'].'>';
          echo '<input type="text" class = "form-control" name = "address"  value='.$row['address'].'>';
          echo '<input type="text" class = "form-control" name = "contact"  value='.$row['contact'].'>';
          echo '<input type="text" class = "form-control" name = "email_add"  value='.$row['email_add'].'>';
          echo '<input type="text" class = "form-control" name = "username"  value='.$row['username'].'>';
          echo '<input type="password" class = "form-control" name = "password"  value='.$row['password'].'>';
          echo '<input type="password" class = "form-control" name = "confirmPassword" value='.$row['conf_pass'].'>';
    }?>

          <button type="submit" class="btn btn-primary" name="update">Submit</button>

update.php ---- I don't know what's the problem with it.
<?php
include('pgconnect.php');
if(isset($_GET['update'])){
    $acctid = $_GET['user_id'];
    $lname = $_GET['lastname'];
    $fname = $_GET['firstname'];
    $mname = $_GET['middlename'];
    $address = $_GET['address'];
    $contact = $_GET['contact'];
    $email = $_GET['email_add'];
    $user = mysql_real_escape_string($_GET['username']);    # use whatever escaping function your db requires this is very important.
    $pass = mysql_real_escape_string($_GET['password']);
    $confpass = mysql_real_escape_string($_GET['confirmPassword']);
        $sql = "UPDATE admin SET lname='$lname', fname='$fname', mname ='$mname', address='$address' contact = $contact, email_add = '$email', username ='$user',password = '$pass', conf_pass = '$confpass' where user_id = '$acctid'";
        $result = mysqli_query($conn,$sql);
            echo "$sql";
                if($result){
                    echo"Succesully Updated!";
                }
                    else
                        {
                        echo"Cannot be Updated!";
                    }
        mysqli_close($conn);
    }?>

A: To understand the mechanism behind forms:
index.html:
<form action="update.php?param=234" method="post">
  <input type="text" name="firstfield" />
  <button name="update">Submit</button>
</form>

update.php:
<?php

echo $_GET['param']; //should output 234
echo $_POST['firstfield']; //should output whatever you put in your textfield
var_dump($_POST['update']); //should return something

as you noticed, the parameter after ? in your action is passed as GET value and all the other values are POST values.


text:
Q: How to set the datasource of RDLC to the return of a specific method I want to set the datasource of my RDLC report to the return of a specific method .but the report wizard can't detect my methods.

The Method is in Class Utility in DataLayer namespace and my report in another class library(FinanceReportBundle).
The Class is like that :
namespace DataLayer
{

    public  class Utility
    {

         public static IEnumerable<object> GetAnalysisDataForConsecutiveYears(int year, int periodTypeId, int period)
        {
            ////Business
        }
    }

 }

A: You don't have to do it in the designer. You can set your data source in code easily, like this:
var dataSource = getmyDataSource();
var rds = new ReportDataSource("myDataSourceName", dataSource);
this.reportViewer1.LocalReport.DataSources.Add(rds);
this.reportViewer1.LocalReport.ReportPath = "path your your rdlc";
this.reportViewer1.RefreshReport();


text:
Q: Determining critical value of likelihood ratio test for two Poisson distributions Let $X_1,X_2$ be two independent Poisson random variables with $X_1 \sim \text{Pois}(\lambda_1)$ and $X_2 \sim \text{Pois}(\lambda_2)$.  Find the likelihood ratio test for $H_0:\, \lambda_1 = \lambda_2$ vs $H_a:\, \lambda_1 \neq \lambda_2$ with 0.05 significance level.
This is what I did:
$L(\lambda_1,\lambda_2)=$$\lambda_1^{X_1} e^{-\lambda_1}\lambda_2^{X_2} e^{-\lambda_2} \over X_1!X_2! $
After partial differentiating with respect to $\lambda_1$ and $\lambda_2$ respectively I get the maximum likelihood estimates $\hat\lambda_1=X_1$ and $\hat\lambda_2=X_2$.
Then $sup_{\theta\in \Theta}L(\lambda_1,\lambda_2)=$$X_1^{X_1} e^{-(X_1+X_2)}X_2^{X_2}\over X_1!X_2! $
Under$ H_0$ when $\lambda_1=\lambda_2=\lambda$  I get $\hat\lambda={X_1+X_2\over2}$.
Then $sup_{\theta\in \omega}L(\lambda_1,\lambda_2)=$$({X_1+X_2\over2})^{X_1+X_2} e^{-(X_1+X_2)}\over X_1!X_2! $
Therefore likelihood ratio:  $\Lambda={sup_{\theta\in \Theta}\over sup_{\theta\in \omega}}={X_1^{X_1}X_2^{X_2} 2^{(X_1+X_2)}\over(X_1+X_2)^{(X_1+X_2)}}$
Therefore Decision rule, Reject $H_0$ if $\Lambda >k$  where k>1 such that
 $sup_ {\theta\in \omega} Pr(\Lambda>k $ when$ \lambda_1=\lambda_2)<=0.05$
So I wrote the following R code to determine k
poisson<-function(nsim,lam){
    delta<-c()
    for (i in 1:nsim){
        x1<-rpois(1,lam)
        x2<-rpois(1,lam)
        d<-((x1^x1)*(x2^x2)*2^(x1+x2))/((x1+x2)^(x1+x2))
        delta<-c(delta,d)
    }
delta
}

p1<-poisson(10000,10)
quantile(p1,0.95)

I get
    95%
7.333328

So my k=7.33.(I have taken $\lambda=10$).
Is my k correct?
Also to determine k does the value of $\lambda$ matter?
Then in order to come up with a power function I wrote the following R code as
power=Pr(Reject $H_0$ when $H_0$ is false)=Pr($\Lambda>7.33$ when $\lambda_1\neq\lambda_2$).
I chose arbitrary $\lambda_1 and \lambda_2$  such that  $\lambda_1\neq\lambda_2$ and came up with the following
    powerCalc<-function(lambda1,lambda2,critvalue){
    power<-c()
    for (i in 1:length(lambda1)){
        delta<-c()
        for(j in 1:10000){
        x1<-rpois(1,lambda1[i])
        x2<-rpois(1,lambda2[i])
        d<-((x1^x1)*(x2^x2)*2^(x1+x2))/((x1+x2)^(x1+x2))
        delta<-c(delta,d)
        }
        y=sum((delta>critvalue)*1)/10000
        power<-c(power,y)

    }
power
}
lambda1<-c(10,15,18,4,9)
lambda2<-c(12,13,8,5,11)
f<-powerCalc(lambda1,lambda2,7.3)

But the powers I get are > f
[1] 0.0729 0.0641 0.5150 0.0617 0.0755
Why do I get so low power values? Is my power function wrong?

A: The power really is that low when you're dealing with such small numbers.  If you multiplied your rates by ten, you'd have more observations and therefore more weight of evidence with which to reject the null hypothesis.
Examples using an exact Binomial test:
(edit to note: my r are your lambda)
     r1 r2        pwr
[1,] 10 12 0.04413046
[2,] 15 13 0.04211265
[3,] 18  8 0.42347262
[4,]  4  5 0.02698215
[5,]  9 11 0.04530927

      r1  r2       pwr
[1,] 100 120 0.2483590
[2,] 150 130 0.2054563
[3,] 180  80 0.9990446
[4,]  40  50 0.1562124
[5,]  90 110 0.2690279

You can reproduce this, but a tweak is needed to your code because it breaks for "large" r1 and r2 owing to the way that d is calculated.  If you work with logs instead then you can reproduce these results.  Specifically, change the d calculation to
d<-x1*slog(x1)+x2*slog(x2)+(x1+x2)*log(2)-(x1+x2)*slog(x1+x2)

where slog(x)=function(x)log(x+0.0001), then observe the (simulated) power with your original rates, e.g. ...
[1] 0.0712 0.0634 0.5129 0.0825 0.0728
[1] 0.0694 0.0650 0.4989 0.0572 0.0705
[1] 0.0619 0.0687 0.4907 0.0572 0.0641

and the (simulated) power for those lambda* times ten:
[1] 0.2590 0.2100 0.9999 0.1770 0.2868
[1] 0.2613 0.2160 1.0000 0.1754 0.2806
[1] 0.2615 0.2065 1.0000 0.1741 0.2758


text:
Q: Kohana multi language website .I'm trying to set up a multi language website with kohana v3, following this tutorial: http://kerkness.ca/wiki/doku.php?id=example_of_a_multi-language_website
Routing to a controller or action within i.e. website/controller/action seems to work as the url is properly redirected to website/lang/controller/action.

*

*However this is not working for ajax request calls. I have to manually edit the url with the appropriate language, to successfully retrieve the data. This also applies for anchors on the html page.

*In addition to this problem, the overflow parameter 'id' also doesn't work. It takes the 'lang' variable as its parameter.
I have setup my default route just like in the tutorial i.e.:
Route::set('default', '((<lang>)(/)(<controller>)(/<action>(/<id>)))', array('lang' => "({$langs_abr})",'id'=>'.+'))  ->defaults(array('lang' => $default_lang,'controller' => welcome', 'action' => 'index'));

Any help is much appreciated ! Cheers

A: Have you set the default language in the config file?
Try the following route instead:
Route::set('default', '(<lang>/)(<controller>(/<action>(/<id>)))', array('lang' => "({$langs_abr})",'id'=>'.+'))
    ->defaults(array(
        'lang' => $default_lang,
        'controller' => 'welcome',
        'action' => 'index'));

If you want to add the current language to any link you output you could try transparently extending the URL class, or perhaps just the HTML class (for the anchor() method).
The current language should be available in the request object Request::$instance->param('lang').


text:
Q: Workflow build precedence What is the expected behavior when one build surpasses another while the former one is paused? If I have a workflow job with 2 stages and I have run 2 builds on it, and build #1 is paused in stage 1 (e.g. maybe someone just forgot to abort it) but build #2 is already on or past stage 2, is it desirable that build #1 should abort? Presumably we wouldn't want that one to continue if the last step is, say, Deploy To Production, otherwise it may well overwrite build #2 running in production, which is actually the one we want. Looking for some insight on how we're expected to handle this situation , or how others already have, as there are a number of ways to address it.

A: Probably you are looking for JENKINS-27039.


text:
Q: Mongoose getter function doesn't return updated array when making async calls I have an app which makes use of two models: Movie and Tag. The idea is that one can create a record of a movie and attach tags to it.  A Movie references one or more Tag models via the Movie.tags attribute which is a array containing the ObjectId of corresponding Tags.
When displaying the properties of a Movie on the client side it makes sense to display the text of the tag, rather than the ObjectId of the tag (remember: Movie.tags is an array of ObjectIds).  I thought about the problem and concluded that the best method would be to make use of a getter function, so that when I retrieve a Movie document, the value of tags attribute is converted from an array of ObjectIds into an array of corresponding tag names.
To do this I must perform a db query for each ObjectId in the array Movie.tags. Since db queries are done asynchronously in Mongoose, I tried implementing the getter function using async.forEach() function from the Async module.  The problem is that the final value is not being returned at the end of the async.forEach function.
I have two questions regarding this problem:

*

*Given my overall objective, is using a getter function the best way of going about this?

*Why is async.forEach() failing to return the updated array?

from model.js

/**
 * Mongo database models
 */

function defineModels(mongoose, async, fn) {
  var Schema = mongoose.Schema,
      ObjectId = Schema.ObjectId;

  /**
   * Model - Movie
   */

  /**
   * Getter function
   *
   * Gets tag text as well as tag ObjectId.
   */
  function getTagNames(tags) {
    var newArray = new Array();
    async.forEach(
      tags,
      function(id, done) {
        mongoose.models['Tag'].findOne({ _id: id }, function(err, doc) {
          if (err) {
            done(err);
          }
          else if (doc) {
            newArray.push(doc);
            done(null);
          }
          else {
            console.log(doc);
            // Just incase something weird like no document is found.
            // Technically this condition should not occur in reality. But we
            // put something here to catch it just in case.
            done(new Error('No tag document found.'));
          }
        });
      },
      function(err) {
        if (err) {
          throw err;
        }
        console.log(newArray);
        return newArray;
      }
    );
  }

  /**
   * Define schema
   */
  Movie = new Schema({
    'name': String,
    'machineFileName': String,
    'originalFileName': String,
    'size': Number,
    'type': String,
    'permanent': {
      type: Boolean,
      default: false
    },
    'dateUploaded': Date,
    'amountUploaded': {
      type: [],
      default: 0
    },
    'viewed': Number,
    'uid': String,
    'flags': [],
    'tags': {
      type: Array,
      get: getTagNames
    }
  }, { strict: true });

  mongoose.model('Movie', Movie);

  /**
   * Model - Tag
   */
  Tag = new Schema({
    'title': { type: String, unique: true, sparse: true }
  }, { strict: true });

  mongoose.model('Tag', Tag);

  fn();
}

exports.defineModels = defineModels;

Retrieving the document:
/**
 * View individual movie.
 */
exports.movie = function(req, res) {
  var Movie = mongoose.model('Movie');
  Movie.findById(req.params.id, function(err, doc) {
    if (err) {
      res.send('An error occured.', 500);
    }
    else {
      console.log('View movie');
      console.log(doc);
      res.render('movie', {
        locals: {
          title: 'Watch Movie',
          movie: doc
        }
      });
    }
  });
}

A: I think you'll be better off making tags an ObjectId refs array and then using Mongoose's populate to populate that with the actual tag objects when needed.
In the Movie schema, tags becomes:
tags: [{ type: ObjectId, ref: 'Tag' }]

And then when you query Movie:
Movie.findById(req.params.id).populate('tags').exec(function(err, doc) {
    // doc.tags is now an array of Tag instances


text:
Q: How to make generic `class Foo` with specific initial values in TypeScript? I have this code, for a generic class:
export default class XYZValues<T = any> extends Observable {
    private _x: T = undefined
    private _y: T = undefined
    private _z: T = undefined
}

but it says undefined is not assignable to T.
Sub classes should specify types, f.e. XYZNumberValues would extends XYZValues<number> for T, and XYZStringValues would extends XYZValues<string>.
At the moment, I'm using any, but it doesn't feel right:
export default class XYZValues<T = any> extends Observable {
    private _x: T = undefined as any
    private _y: T = undefined as any
    private _z: T = undefined as any
}

Is there a recommended way to create generic classes with default values (such as undefined) without using any?


text:
Q: Google Maps: "This API project is not authorized to use this API." Recently I started coding a Google Maps service integration. I went ahead and generated an API Key associated with my business email account on bronze level. When I use the service sans API Key everything works swimmingly.
If I use the API Key parameter, with my API key generated in my developer console I get the error message:

This API project is not authorized to use this API.

The URL used to access maps is below:
https://maps.googleapis.com/maps/api/distancematrix/xml?origins={origin_address}&destinations={destination_addresses}&mode=driving&language=en-US&sensor=false&key={APIKey}

How does one get the API Key to be authorized for v3 Maps JavaScript API. I am making the call as a raw post in the ASPX code behind to that address. It seems to me this used to work fine when I first started all this, now today all of the sudden I'm getting this error.
I need this to work since I will also be using places and that service seems to only work with the API Key. I would like to be able to have the key configured once and be done with it.

A: You'll need to enable each API you want to use.
The maps-javascript-API is one API, the DistanceMatrix-API(Webservice) another.
Go to the developer-console->API's and enable the Distance Matrix API
Note: this is only related to the DistanceMatrix-Webservice, when you use the DistanceMatrix-Service of the Javascript-API you don't need to enable this service.


text:
Q: String diff on punctuation: is preg_split the answer? http://piratepad.net/IY48xXzsys (modified by Peter West, from the original here: http://paulbutler.org/archives/a-simple-diff-algorithm-in-php/)
Currently a diff between "I think, therefore" and "I think therefore" will produce:
I < del >think,< /del >< ins >think< /ins > therefore

I would like it to produce:
I think< del >,< /del > therefore

I think the answer would be to include the comma as a separate entity in the array that results from the preg_split function.  I tried to play around with parenthesis, but could not get this to work. Can you help me out?

A: I think that adding a comma to the delimiters in the call to split will do it.


text:
Q: AngularJS pushing/updating new data (likes/dislikes) to API using PUT I am trying to create an app that counts likes for beer! This would updates the API the beers are stored on and in turn update the number of likes on the API and angularJS view using the PUT method. I am able to get the view to work correctly increasing every time the like is clicked. I am unsure why my PUT method continues to return a 404 and will not update the API. please see code below for my put method. I have also included my JS and HTML for this. I feel like I am close but cannot figure out how to get the "likes" to update on the API. Thank you in advance!! I think i am passing incorrect data to the PUT method.
HTML:

{{beer.name}}

{{beer.likes}}

            <button ng-click="decrease(beer)">X</button>
            <button ng-click="increase(beer)">\3</button>

JS:
 angular.module('beerApp', []).controller('BeerController', function($scope, $http) {

             $scope.allBeer = [];
             $scope.beerSum = function() {
             $http({
                method: 'GET',
                url: /api/beers
              }).
             then( function(response) {

             if(typeof response === 'object') {
                var dataArr = response.data;
                for (var i = 0; i < dataArr.length; i++) {
                    var beer = dataArr[i];

                    $scope.allBeer.push(beer);
                }

            } else {
                return;
            }

            }, function(error) {
            console.log('i am an error', error);
            })
          };

          $scope.beerSum();

          $scope.increase = function(beer){

          var newLikes = beer.likes++;

          $http({
            method: 'PUT',
            url: '/api/beer/',
            data: JSON.stringify($scope.allBeer.likes),
        }).then(function successCallback(response) {
            console.log("Updated!");
        }, function errorCallback(response) {
            console.log("not updated")

        });

    };

A: First things first you are missing some syntax for the http api's. Secondly you are calling a property on an array that doesn't exist. Thirdly your api won't work because of the logic that you have. You have an array of beers and you want to increase the likes on a single beer. Create a method on the server that accepts a beer, the server will take that beer and increase it's likes by 1, then save to the database or whatever.
Depending on the server you are using you have two options.
You can define a command simply at /api/beers and configure the server to accept an object and use that objects id for the server update. If this is the case I recommend creating this endpoint, /api/beers/update and make it a POST, and pass it the object, then within this command do all your update logic.
Or for example the Microsoft Web Api the default put (update) endpoint looks like so, public void Update(int id, object data){} with a url of /api/beers/{id}. To use this method you need to change the code for the updateLikes method I wrote.
See Below:
$scope.updateLikes = function(beer, likeCount){
        beer.likes+= likeCount;
        $http({
              method: 'PUT',
              url: '/api/beer/' + beer.id,
              data: JSON.stringify(beer),
          }).then(function successCallback(response) {
                console.log("Updated!");
                //Trigger reload of data
                $scope.beerSum();
          }, function errorCallback(response) {
                console.log("not updated")
            });
    };

Extra Help
If you are still having trouble and are working in a GitHub environment I would gladly help you with your code more directly. Other than that the answer I have posted answer's your question, and does so in what I believe to be good coding practices for AngularJS. With one minor exception there code be a changes to the line that reads, beer.likes += likeCount because this also updates the original beer object. I suppose that is preference, but please contact me if you need more help.
JS:
     angular.module('beerApp', []).controller('BeerController', function($scope, $http) {
     $scope.allBeer = [];
     $scope.beerSum = function() {
     $http({
        method: 'GET',
        url: '/api/beers' //<-- Added string opening and closing tags
      }).
     then( function(response) {

         if(typeof response === 'object') {
            var dataArr = response.data;
            for (var i = 0; i < dataArr.length; i++) {
                var beer = dataArr[i];

                $scope.allBeer.push(beer);
            }

        } else {
            return;
        }

        }, function(error) {
        console.log('i am an error', error);
        })
      };

      $scope.beerSum();

      $scope.increase = function(beer){

      var newLikes = beer.likes++;

//Your code
          $http({
            method: 'PUT',
            url: '/api/beer/', //<-- closing
            data: JSON.stringify($scope.allBeer.likes), //<-- Where does likes come from? $scope.allBeer is an array of beer but the array itself doesn't have a property called likes.
        }).then(function successCallback(response) {
            console.log("Updated!");
        }, function errorCallback(response) {
            console.log("not updated")

        });

//End your code

//My Code
    beer.likes+=1; //<-- My bad I fixed this.
    $http({
          method: 'PUT',
          url: '/api/beer/', //<-- closing
          data: JSON.stringify(beer), //<-- The object you passed into the function
      }).then(function successCallback(response) {
            console.log("Updated!");
      }, function errorCallback(response) {
            console.log("not updated")

        });
//End my code

    };

Possible problems

*

*Your api doesn't work with put, in which case this question isn't the correct one.

*Something else is internally wrong with your program, but from this point on I think you're looking at something wrong with your api, whatever that may be.

angular.module('beerApp', []).controller('BeerController', function($scope, $http) {
     $scope.allBeer = [];
     $scope.beerSum = function() {
       $scope.allBeer.push({
         "name": "Miller Lite",
         "likes": 0
       });
     $http({
        method: 'GET',
        url: '/api/beers' //<-- Added string opening and closing tags
      }).
     then( function(response) {
         if(typeof response === 'object') {
            var dataArr = response.data;
            for (var i = 0; i < dataArr.length; i++) {
                var beer = dataArr[i];

                $scope.allBeer.push(beer);
            }
          }
        }, function(error) {
        console.log('i am an error', error);
        })
      };

      $scope.beerSum();

      $scope.updateLikes = function(beer, likeCount){
        beer.likes+= likeCount;
        $http({
              method: 'PUT',
              url: '/api/beer/',
              data: JSON.stringify(beer),
          }).then(function successCallback(response) {
                console.log("Updated!");
                //Trigger reload of data
                $scope.beerSum();
          }, function errorCallback(response) {
                console.log("not updated")
            });
    };
});

<!DOCTYPE html>

    <link rel="stylesheet" href="style.css" />

Beers on Tap

{{beer.name}}

{{beer.likes}}

          <button ng-click="updateLikes(beer, -1)">Down Vote</button>
          <button ng-click="updateLikes(beer, 1)">Up Vote</button>


text:
Q: Infinite scrolling using tabview is flashing I am trying to combine these two tutorials Instagram Reels UI and Infinite Carousel Slider, so that I get Reels with Infinite scrolling. I implemented the solution to the flashing of the Infinite Slider but my offset is never 0, I tried printing it and it was something like -201. I guess my .preference(key: OffsetKey.self, value: proxy.frame(in: .global).minX) returns something else. I tried using minY since my scrolling is to the top/bottom, and checking for index == 0 && -offset < size.height && offset < size.height but this leads to lag/flashing. To test the flashing just comment out the .onChange(of: offset, perform: {...}
ReelView:
struct Reels: View {
    @State var currentReel = ""
    @State var offset: CGFloat = 0
    @State var items: [Item] = [
        Item(reel: Reel(player: AVPlayer(url: URL(fileURLWithPath: Bundle.main.path(forResource: "apple-watch", ofType: "mp4") ?? "")))),
        Item(reel: Reel(player: AVPlayer(url: URL(fileURLWithPath: Bundle.main.path(forResource: "ibiza", ofType: "mp4") ?? "")))),
        Item(reel: Reel(player: AVPlayer(url: URL(fileURLWithPath: Bundle.main.path(forResource: "sneaker", ofType: "mp4") ?? "")))),
        Item(reel: Reel(player: AVPlayer(url: URL(fileURLWithPath: Bundle.main.path(forResource: "rolex", ofType: "mp4") ?? "")))),
        Item(reel: Reel(player: AVPlayer(url: URL(fileURLWithPath: Bundle.main.path(forResource: "lambo", ofType: "mp4") ?? ""))))
        ]

    var body: some View {
        ZStack {
            GeometryReader { proxy in
                let size = proxy.size

                TabView(selection: $currentReel) {
                    ForEach($items) { $reel in
                        ReelsPlayer(currentReel: $currentReel, item: $reel)
                            .frame(width: size.width)
                            .rotationEffect(.init(degrees: -90))
                            .ignoresSafeArea(.all, edges: .top)
                            .tag(reel.id)
                            .overlay {
                                GeometryReader { proxy in
                                    Color.clear
                                        .preference(key: OffsetKey.self, value: proxy.frame(in: .global).minX)
                                }
                            }
                            .onPreferenceChange(OffsetKey.self, perform:  { offset in
                                self.offset = offset
                            })
                    }
                }.tabViewStyle(.page)
                    .onChange(of: offset, perform: { newValue in
                        let index = items.lastIndex(where: { item in
                            item.id == currentReel
                        }) ?? 0
                        if index == 0 && offset == 0 {
                            currentReel = items[items.count - 2].id
                        }
                        if index == items.count - 1 && offset == 0 {
                            currentReel = items[1].id
                        }
                    })
                    .onAppear() {
                        guard var first = items.first else {
                            return
                        }

                        guard var last = items.last else {
                            return
                        }
                        last.id = UUID().uuidString
                        first.id = UUID().uuidString
                        items.append(first)
                        items.insert(last, at: 0)
                        currentReel = items[1].id
                    }
                .rotationEffect(.init(degrees: 90))
                .frame(width: size.height)
                .tabViewStyle(.page(indexDisplayMode: .never))
                .frame(width: size.width)
            }
        }
    }
}

ReelsPlayer:
struct ReelsPlayer: View {
    @Binding var currentReel: String
    @Binding var item: Item

    var body: some View {
        ZStack {
            if let player = item.reel.player {
                CustomVideoPlayer(player: player)
                    .allowsHitTesting(false)

                GeometryReader { proxy -> Color in
                    let minY = proxy.frame(in: .global).minY

                    let size = proxy.size

                    DispatchQueue.main.async {
                        if -minY < (size.height / 2) && minY < (size.height / 2)  && currentReel == item.id {
                            player.play()
                        } else {
                            player.pause()
                            player.seek(to: .zero
                            )
                        }
                    }
                    return Color.clear
                }
            }
            BottomOverlay(item: $item)
                .allowsHitTesting(true)
        }
    }
}

CustomVideoPlayer:
struct CustomVideoPlayer: UIViewControllerRepresentable {

    var player: AVPlayer

    func makeCoordinator() -> Coordinator {
        return Coordinator(parent: self)
    }

    func makeUIViewController(context: Context) -> AVPlayerViewController {
        let controller = AVPlayerViewController()

        controller.player = player
        controller.showsPlaybackControls = false

        controller.videoGravity = .resizeAspectFill

        player.actionAtItemEnd = .none

        NotificationCenter.default.addObserver(context.coordinator, selector: #selector(context.coordinator.restartPlayback), name: .AVPlayerItemDidPlayToEndTime, object: player.currentItem)

        return controller
    }

    func updateUIViewController(_ uiViewController: AVPlayerViewController, context: Context) {

    }

    class Coordinator: NSObject {
        var parent: CustomVideoPlayer
        init(parent: CustomVideoPlayer) {
            self.parent = parent
        }
        @objc func restartPlayback() {
            parent.player.seek(to: .zero)
        }
    }
}


text:
Q: autohotkey type in another window with gui Autohotkey Example Needed
Need some help, please.  I've searched and can't seem to find an example of what I need.
What I want to do is create a ahk dialog box with a button (I can do this part), and when I click on it, it will type some text into another window.  Basically, I want want to offload the "shortcut" to a "mouse click".  But, without mapping a shortcut.
Something like this:
When user clicks BOX1, "text" is stored. Then, when user clicks elsewhere, vBOX1 is typed into the cursor location of the window activated by that click
I hope I'm explaining this succinctly. Any help would be appreciated.

A: Here are two possible alternatives:
First alternative expands @scso's suggestion:
~LButton::
sleep, 200 ;give the window below the cursor some time to get activated
Send, %vBOX1%
return

Now this may seem fine but what it actually does is type the text EVERY time you click the mouse in ANY window. Let's put an additional check so if vBOX1 is empty it doesn't type anything.
~LButton::
sleep, 200 ;give the window below the cursor some time to get activated
If (vBOX1 != "")
{
  Send, %vBOX1%
  vBOX1 := ""  ; clears the contents of vBOX1
}
return

Second alternative:
You use the mouse clicks normally and the text gets typed only when you do Control + Click.
So in order to type the text you need to click once to select the window and then control+click to do the actual typing
~^LButton::
Send, %vBOX1%
vBOX1 := ""  ; clears the contents of vBOX1
return

You can expand both alternatives by adding commands for detecting the active window and then typing the text or changing the mouse click combination to something else.


text:
Q: What are categorical models of W-types in intensional type theory? I'm familiar with container functors and older work by Dybjer on categorical models for W-types in the extensional theory, but I was looking for some similar semantics in the intensional case.

A: Unless I've not understood your question correctly (sometimes people mean different things by the distinction between intensional and extensional), then I think the answer is: the semantics for W-types in intensional type theory are exactly the same as the semantics for W-types in extensional type theory.
A model of type theory (comprehension category, category with attributes, et cetera) is essentially just a Grothendieck fibration $p:E\to B$ which comes equipped with certain structure.  Being a model of W-types just means that $p$ comes equipped with certain extra structure.  As I understand it, the difference between intensional and extensional type theory has to do with which axioms are satisfied by the identity types.  (In terms of $p$ this is just whether it is equipped with one or another kind of structure for interpreting identity types.)  Whether or not you are able to interpret W-types is again simply a question of whether $p$ has a further kind of additional structure and is a prior independent of which kind of identity types $p$ is able to interpret.
In practical terms, what this means is that the question of whether your model supports the interpretation of W-types has everything to do with your fibration $p$ and formulated in this way the question is completely independent of whether the model is intensional or extensional.  E.g., if your fibration $p$ comes from something like a class of display maps and you want to interpret W-types as initial algebras for polynomial endofunctors, then you will need to verify that these initial algebras land in the class of display maps.


text: Q: ASP.NET подгрузка файлов при старте сервера В общем. Есть проект ASP.NET MVC. В папке проекта, дополнительно к шаблонному проекту, есть ещё одна папка. В этой папке находятся файлы формата json, .js и ещё всякие другие ресурсы. Так вот, как подгрузить файлы формата .js и css при помощи bundlow я знаю, а как мне подгружать всё остальное(при старте самого сервера)?


text:
Q: EMR Spark java Application GC Problems i'm working on a spark application and i have a serious issues
with the CGTime task time that result very high.
I exported the logs and analysed it with GC easy.
Clusters Hardware:
1 Driver
m4.2xlarge
16 vCore, 32 GiB memory, EBS only storage
EBS Storage:32 GiB
15 cores:
m4.2xlarge
16 vCore, 32 GiB memory, EBS only storage
EBS Storage:32 GiB
Configuration
hadoop-env.export   JAVA_HOME   /usr/lib/jvm/java-1.8.0
mapred-site mapreduce.fileoutputcommitter.algorithm.version 2
mapred-site mapred.output.committer.class   org.apache.hadoop.mapred.FileOutputCommitter
spark-defaults  spark.default.parallelism   880
spark-defaults  spark.executor.instances    44
spark-defaults  spark.yarn.executor.memoryOverhead  3072
spark-defaults  spark.executor.cores    10
spark-defaults  spark.yarn.driver.memoryOverhead    3072
spark-defaults  spark.driver.memory 18G
spark-defaults  spark.driver.cores  10
spark-defaults  spark.executor.memory   18G
spark-env.export    JAVA_HOME   /usr/lib/jvm/java-1.8.0

Inputs
Dimension 1.2 Tera of data.
Pseudo Instructions
1 read data
2 map to pair | row -> Tuple(row,1)
3 distinct
Logs Problem

*

*Consecutive Full GC

*Long Pause

*Application waiting for resources

Analysis Link
http://gceasy.io/my-gc-report.jsp?p=c2hhcmVkLzIwMTgvMTAvMTIvLS1leGVjdXRvcjFzdGRvdXQudHh0LnppcC0tMTAtMzUtMjY=
I'm not an expert of CG collector dynamics, can somebody help me to found the problem ?

A: Your spark executor(s) size is big and big executor(s) introduce heavy GC overhead.
Watch this video for how to choose an executor size and tune performance.
I recommend to watch full video: https://www.youtube.com/watch?v=OkyRdKahMpk
or at least from here to tune executor(s): https://youtu.be/OkyRdKahMpk?t=1308


text:
Q: Google client.js Oauth2 refused to display iFrame Background:
I am using Google client.js to access a cloud endpoints project that I created.
When the code executes, and returns the iFrame that should show the authentication confirmation, I get the error

Refused to display "......" in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.

I know that this is a security feature to prevent malicious sideloading of content but I cant seem to figure out where I went wrong.
var CLIENT_ID = "this is my id";
var SCOPES = "https://www.googleapis.com/auth/userinfo.email";

function init() {
    var apisToLoad;
    var loadCallback = function() {
        if (--apisToLoad == 0) {
            signin(true, userAuthed);
        }
    };

    apisToLoad = 2; // must match number of calls to gapi.client.load()
    apiRoot = '//' + window.location.host + '/_ah/api';
    gapi.client.load('business', 'v1', loadCallback, apiRoot);
    gapi.client.load('oauth2', 'v2', loadCallback);
}

signin = function(mode, callback) {
    gapi.auth.authorize({client_id: CLIENT_ID,
            scope: SCOPES, immediate: mode},
        callback);
};

function userAuthed() {
    var request =
        gapi.client.oauth2.userinfo.get().execute(function(resp) {
            if (!resp.code) {
                // User is signed in, call my Endpoint
                gapi.client.business.retrieve().execute(function(resp) {
                    console.log(resp);
                });
            }
        });
}

A: Turns out that i was using the wrong api key. If you run into this issue, use the proper api key.


text:
Q: Only replace pattern if the whole line matches regex I am sure there is a trivial solution to this question but I can't seem to get it right:
I want to replace a specific pattern in a line only if the whole line matches the regex.
So in my case three pipes | should be replaced by underscores _ only if the whole line is numbers and pipes:
|||10|||-80|||-120|||400           ---> replace
|||10|||asdf|||-120|||400          ---> don't replace
|||10|||-80|||400                  ---> replace
|||10|||-80|||-120|||400|||test    ---> don't replace

Expected result:
___10___-80___-120___400
|||10|||asdf|||-120|||400
___10___-80___400
|||10|||-80|||-120|||400|||test

My attempts:
\|\|\|(?=\-?\d+)

replaces the pipes if followed by numbers as expected but of course also in the "invalid" lines
^(\|\|\|\-?\d+){1,}$

matches the whole line and therefore I can't replace only the pipes
I understand why my patterns don't work and perhaps I have to simply do it with two passes but it feels like this should totally be possible.

A: Without more details, it seems you can use
(?<=^(?:\|{3}-?\d+)*)\|{3}(?=-?\d+(?:\|{3}-?\d+)*$)

Or, if you need to process lines in a larger string:
(?m)(?<=^(?:\|{3}-?\d+)*)\|{3}(?=-?\d+(?:\|{3}-?\d+)*\r?$)

See the regex demo.

Details:

*

*(?<=^(?:\|{3}-?\d+)*) - a positive lookbehind that requires that, immediately to the left of the current location, there is:

*

*^ - start of string anchor

*(?:\|{3}-?\d+)* - zero or more sequences of 3 |s followed with an optional - (-?) and then 1 or more digits

*\|{3} - 3 pipes

*(?=-?\d+(?:\|{3}-?\d+)*$) - a positive lookahead that requires that, immediately to the right of the current location, there is

*

*-?\d+ - an optional - and then 1+ digits

*(?:\|{3}-?\d+)* - 0 or more sequences of 3 |s + an optional - and then 1+ digits

*$ - end of string anchor.

C#:
var res = Regex.Replace(s, @"(?<=^(?:\|{3}-?\d+)*)\|{3}(?=-?\d+(?:\|{3}-?\d+)*$)", "___", RegexOptions.ECMAScript);

The RegexOptions.ECMAScript flag is used to make \d only match ASCII digits.


text:
Q: Generating units with an algorithm Give an efficient algorithm for generating the first $T = 20$ time units to a Poisson process not homogeneous, whose intensity function is given by
$\lambda(t) = \begin{cases}\frac{t}{5} & \text{if } t\in[0, 5) \\
1+5(t-5) & \text{if } t\in[5,10)
 \end{cases}$
Can you help me? Thanks to all.


text:
Q: How can I read a file from ajax call in Django? I'm working in Django. I need to upload a txt file and print its content in a table. I've tried many things but none of them work. Someone recommended that I just print the table in an ajax call, but it's not working. Here's what I'm trying:
I'm showing a form to upload the file:
class UploadFileForm(forms.Form):
    file = forms.FileField(label = "File:")

I'm returning the form in a view:
def upload(request):
    form = UploadFileForm()
    return render(request, 'upload.html', {'form': form})

I'm printing the form in the template:
<form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
</form>

Then I have a button to confirm the upload:
<button id="upload">Upload file</button>

And here's where I try to print the table in a fetch, which is not working:
var upload = document.getElementById("upload");
upload.addEventListener("click", function(){
    const url = "{% url 'table' %}";
    fetch(url, {method:'POST'}).then(response => response.json()).then(function(data){
        var table = document.getElementById('table');
        tableRow1.innerHTML = data.tableHTML;
    })
})

The url 'table' goes to this function:
def table(request):
    data = file_to_HTML(request.FILES['file'])
    json_response = {"tableHTML":data}
    return JsonResponse(json_response)

The problem here is that the table isn't printed at all and I get the following error:
Internal Server Error: /table/
Traceback (most recent call last):
  File "C:\Users\Daniel\miniconda3\envs\env1\lib\site-packages\django\utils\datastructures.py", line 78, in __getitem__
    list_ = super().__getitem__(key)
KeyError: 'file'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Daniel\miniconda3\envs\env1\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\Daniel\miniconda3\envs\env1\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Daniel\miniconda3\envs\env1\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Daniel\miniconda3\envs\env1\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "C:\Users\Daniel\Trabajo\module1\app1\views.py", line 22, in table
    data_list = read_bank_file(request.FILES['file'])
  File "C:\Users\Daniel\miniconda3\envs\env1\lib\site-packages\django\utils\datastructures.py", line 80, in __getitem__
    raise MultiValueDictKeyError(key)
django.utils.datastructures.MultiValueDictKeyError: 'file'

I don't know what is going on here. If someone can help me print the table, I would really appreciate it. Printing it in a different page is fine, I just can't print it at all.

A: I solved it by using JQuery and changing a bunch of stuff in the ajax call:
-Trigger the call when the form is submitted, and use event.preventDefault() to stop it from being actually submitted.
-Sending the form to Django inside a FormData object.
-Using processData: false and contentType: false.
Here's the full Ajax call:
$("#formulario").submit(function(event){
    event.preventDefault();
    var formData = new FormData(this);
    $.ajax({
        url : "{% url 'table' %}",
        type: "POST",
        processData: false,
        contentType: false,
        data: formData,
        success: function (data){
            $("#tableData").append(data.tableHTML);
        }
    })
});

A: For getting files from the request you can do something like this.
Update
def get_file_data_from_ajax(request):
    if not request.is_ajax():
        return BadRequest

    form = forms.UploadFileForm(request.POST, request.FILES or None)
    if not form.is_valid():
        return BadRequest

    info_form = form.save(commit=False)
    info_form.user = request.user if requset.user.is_authenticated else None
    info_form.is_active = True
    info_form.save(commit=True)

    return JsonResponse({'status':'form is valid'})


text:
Q: Prove that $GL_n(\mathbb{F}_p)$ contains an element of order $p^n-1$
If $p$ is prime and $n$ is a positive integer, prove that GL$_n(\mathbb{F}_p)$ contains an element of order $p^n-1$.

I am a bit stuck on how to get started on this problem. I found it in the Galois theory section on a list of past qualifying exams, so I'm guessing some kind of Galois theory should be involved, but I can't seem to get anywhere with it. I know that $\mathbb{F}_{p^n}$ and $\mathbb{F}_p^n$ are isomorphic as $\mathbb{F}_p$ vector spaces, so $Gal(\mathbb{F}_{p^n}/\mathbb{F}_p)$ is isomorphic to a cyclic subgroup of GL$_n(\mathbb{F}_p)$ of order $n$, though this doesn't seem too useful (but maybe I'm wrong!). My only other idea at this point is to try to find some $\mathbb{F}_p$-linear transformation $T$ of $\mathbb{F}_{p^n}$ with characteristic polynomial $x^{p^n-1}-1$ and then use Cayley-Hamilton to get that $T$ has order dividing $p^n-1$, and hopefully the definition of $T$ (whatever it may be) will show it's order can't be lower than $p^n-1$. Can anyone see a more clever way to attack this problem?

A: Hint: If $\alpha$ is a generator of the cyclic group $\mathbb{F}_{p^n}^*$, then what is the order of $\alpha \cdot : \mathbb{F}_{p^n} \to \mathbb{F}_{p^n}$?


text:
Q: iOS8 Animate Transform Not Working As Expected I had a beautiful zoom animation that was working perfectly up until iOS8.  Now it seems to 'jump' to halfway through the animation and it looks terrible.  The code was quite simple...
// zoom in on this focus kanji
[UIView animateWithDuration:0.5f animations:^{
    // zoom in
    newFocusSentence.transform = [self getZoomTransformForKanji:thisKanji];

So I'm pretty sure there's nothing wrong with it.  The zoom ends up in the right place, but doesn't seem to start from the right place.  The fact that it ends up in the eight place and was working before leads me to believe that the transform itself is fine.  Is anyone else seeing bad results with animating transforms?
Thanks
Ray


text:
Q: Installing Connectwise I'm wondering if anyone out that has been able to install ConnectWise PSA on Ubuntu?
I've got wine up and running, and I know Connectwise needs Microsoft .Net 3.5. Can I just install .Net through wine, or would I have to go the route of installing Mono, then trying to install Connectwise?

A: The .NET framework 3.5 or 4 doesn't run under wine (source). Right now (March 2011) there are some big profile bugs that are not likely to be solved soon. You can try to run this program with Mono, but very likely the only realistic way to run it on linux is through virtualization.

A: You could install .NET 3.5 on wine (I think it is possible with #winetricks ), but I'm not too sure if it would result in a working product. You're probably better off using that in a virtual machine.


text:
Q: GSON: encode map of objects and preserve type when decoding I have a class like:
public class MyClass {
    private final Map<Property, Object> properties;
}

where Property is an enum.
Let's say that properties contains 2 elements, one whose value is a Double and one whose value is a class instance having only one attribute called ownerName. When I serialise this class I get the following string:
{"properties":{"NAME":{"ownerName":"MyBucket"},"DIVISOR":33.0}}

The problem is that when I tried to obtain a MyClass instance from the string above, the value for NAME property will be a Map instead of an instance of the class having ownerName attribute. I tried to write a custom serializer/deserializer but I was not able to do that only for NAME property. Any ideas?

A: You need to write custom deserialiser for the whole Map. Custom deserialiser could look like below:
class PropertyJsonDeserializer implements JsonDeserializer<Map<Property, Object>>, JsonSerializer<Map<Property, Object>> {

    @Override
    public Map<Property, Object> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        if (!json.isJsonObject()) {
            return Collections.emptyMap();
        }

        JsonObject root = json.getAsJsonObject();
        Map<Property, Object> result = new LinkedHashMap<>();
        root.entrySet().forEach(entry -> {
            Property property = Property.valueOf(entry.getKey());
            switch (property) {
                case DIVISOR:
                    result.put(property, entry.getValue().getAsDouble());
                    break;
                case NAME:
                    Object owner = context.deserialize(entry.getValue(), Owner.class);
                    result.put(property, owner);
            }
        });
        return result;
    }

    @Override
    public JsonElement serialize(Map<Property, Object> src, Type typeOfSrc, JsonSerializationContext context) {
        return context.serialize(src, Map.class);
    }
}

Example usage:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.annotations.JsonAdapter;

import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.EnumMap;
import java.util.LinkedHashMap;
import java.util.Map;

public class GsonApp {

    public static void main(String[] args) throws Exception {
        Map<Property, Object> properties = new EnumMap<>(Property.class);
        properties.put(Property.DIVISOR, new BigDecimal("33.0"));
        properties.put(Property.NAME, new Owner());

        MyClass myClass = new MyClass(properties);

        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String json = gson.toJson(myClass);
        System.out.println(json);

        myClass = gson.fromJson(json, MyClass.class);
        System.out.println(myClass);
    }
}

class MyClass {

    @JsonAdapter(PropertyJsonDeserializer.class)
    private final Map<Property, Object> properties;

    public MyClass(Map<Property, Object> properties) {
        this.properties = properties;
    }

    // getters, setters, toString
}

class Owner {
    private String ownerName = "MyBucket";

    // getters, setters, toString
}

enum Property {
    NAME, DIVISOR
}

Above code prints:
{
  "properties": {
    "NAME": {
      "ownerName": "MyBucket"
    },
    "DIVISOR": 33.0
  }
}

MyClass{properties={NAME=Owner{ownerName='MyBucket'}, DIVISOR=33.0}}


text:
Q: xargs touch followed by second command I am randomly selecting files from a directory that I want to process, and I want to apply the touch command to them so that I know the last one that's been visualized, then apply the visualization program. Something like this:
while [ 1 ]; do ls | shuf | xargs "touch & vizprogram"; done

Since I am manually inspecting these datasets, I want to be able to "Esc" from the loop at any point, so that I interrupt the vizprogram and go through the loop again. Then when I find a file I want to follow on, I want to Ctrl+C and do an ls -rt | tail -n 1 to have the name of the last file I've used. I tried this with a for or while loop instead of xargs, but then I cannot do "Esc" on the main loop.
Any ideas how to do the "touch then vizprogram" within xargs?

A: Create a shell script such as the following:
#!/usr/bin/env bash
while [ $# -gt 0 ]
do
    touch "$1"
    vizprogram "$1"
    shift
done

Then have xargs execute it:
echo "file file2 file3" | xargs /path/to/script.sh

A: If vizprogram returns true if exited with ESC and false if exited with Ctrl-C you can do:
while ls | shuf | parallel --halt 2 -j1 "touch {}; vizprogram {}"; do true; done

You can install GNU Parallel simply by:
wget http://git.savannah.gnu.org/cgit/parallel.git/plain/src/parallel
chmod 755 parallel
cp parallel sem

Watch the intro videos for GNU Parallel to learn more:
https://www.youtube.com/playlist?list=PL284C9FF2488BC6D1


text:
Q: Relation between group action in abstract algebra and semi-automaton If $G$ is a set acting on a set $A$, can it define a semi-automaton? How is this concept of abstract algebra related to semi-automata?

A: Your notation is a bit misleading, since $A$ usually denotes an alphabet. So let me switch the role of $G$ and $A$. Suppose that $A$ acts on $G$, that is, there is a map  $(g,a) \mapsto g \cdot a$ from $G \times A$ to $G$. This map can be extended, to an action on $G$ of every word $u$ of $A^*$. This can be done by induction on the length of $u$. Let $g \in G$. For the empty word $1$, just set $g \cdot 1 = g$. Now if $u$ is a word and $a$ is a letter, set $g \cdot (ua) = (g \cdot u) \cdot a.\ $ You define in this way a semi-automaton $(G, A)$ where $G$ is the set of states and $A$ is the alphabet.

A: Guess by $G$ you mean a group, and not just as a set, as written in the title?
Then for a group $G$ and a set $A$ a group action is a mapping $A \times G \to G$ such that $a1 = a$ and $a(gh) = (ag)h$ for $a \in A$ and $g,h \in G$.
On the other side, a semi-automaton is a certain computational device to decribe formal languages or (sequentiell) computations. Without giving all the definitions, the more algebraic definition of a (finite) semi-automaton are two finite sets $Q$ (states) and $\Sigma$ (alphabets) such that $\Sigma$ acts on $Q$, i.e. we have a mapping $Q \times \Sigma \to Q$.
Now looking at the free monoid $\Sigma^{\ast}$ this gives us a action of the free monoid $\Sigma^{\ast}$ on $Q$. This is what Jean-Eric Pin wrote in his answer (he took $A$ for the alphabet and $G$ for the state set, I guess you mean $G$ acting on $A$ as written above, but the wording of your question is not clear about that...)
Anyway, are you asking about the relation of these two notions? They are closely related, but they are not the same, with different things that they should model in mind.
For a group action, it could be viewed as a (group-) automaton, the inputs are group elements and the state is the element of the permutation group after applying them to some initial permutation. Think of symmetry groups, for example the symmetry of a pentagon. The current configuration is a state, and applying some group element changes it. And if you want to push this further every group element could be written as a word over some alphabet (the generators and their inverses) and by this you get even an action of words on your set.
But in general a group action is looked at as given and fixed, and we try to classify groups that could act in a certain way, try to determine point stabilizers etc. On the other side, for an automaton we look at word sets, call certain states initial or final, and try to minimize them, i.e. try to find automata accomplishing the same (external) behaviour with fewer states. To my knowledge such questions are never asked for a group action, because the focus is different. For example in the automata setting it is quite often asked what words transform certain states into each other and the focus is on the resulting set of words. In the group action setting the group elements transforming two points into each other would be somehow analog to that, and this would be a coset of the point stabilizer, which has entirely a different structure as a formal language and I would think totally different about them (despite the mentioned connections above).


text:
Q: Controller is not defined in AngularJS 1.3.7 I am trying to do routing in angular Js in mvc but I am not able to find solution for this errors.

*

*$injector:modulerr this Error i am getting

*Uncaught ReferenceError: controller is not defined

A: Your not chaining, after the end of .config remove the ; and add another . to chain the controller call:
angular.module('APP', ['ngResource']).config({}).controller()
                                                ^^ MISSING THIS

A: you need app.controller and it is $http not $htp
 controller('directoryController', ['$scope', '$http', function ($scope, $htp) {

should be:
 app.controller('directoryController', ['$scope', '$http', function ($scope, $http) {


text:
Q: What's the most efficient way to transfer data/packets between native code and Java code in Android I'm going to write an Android App to read raw packet from native code with raw socket interface. My phone is rooted so my native code can access to the native code by using runtime.exec("su"). But I don't know how to efficient transfer packets between the native code and Java code. (In this case, the native code and Java code are running in different processes) Since my App must process the raw packets from the native code as efficient as possible, I need a "fast tunnel" between them. Any ideas or suggestions?
P.S. I have tired Android NDK, but in NDK, native code and Java code are running in the same process so the native code cannot have the root privilege to access raw socket.

A: The solution is: create an agent at native layer so that it can talk to your java activity via JNI. Then hook up the agent and your native service by using IPC (binder).
One issue: it is not convenient to pass complex data structure via JNI. So step back, why do you want to pass entire packets? Can you process the packets at native layer and submit the result (e.g., integers) only?


text:
Q: Is there a way to dismiss an no button UIalertView after some time? UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"tittle"
               message:@""
                 delegate:self
              cancelButtonTitle:@""
              otherButtonTitles:nil];
  [alertView show];
  [alertView release];

i want to dimiss the alerview after it's showing for some time,but when the alertview has no button,it doesn't work if i invoked -dismissWithClickedButtonIndex:animated: methodand-performSelector:withObject:afterDelay:
is there any other way to dismiss it ?
thanks for any ideas!

A: -(void)xx  {
     [self performSelector:@selector(dismissAlertView:) withObject:alertView afterDelay:2];
}
-(void)dismissAlertView:(UIAlertView *)alertView{
    [alertView dismissWithClickedButtonIndex:0 animated:YES];
}

that's it.i fix it

A: Use 10 seconds delays to dismiss
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:@"" preferredStyle:UIAlertControllerStyleAlert];
[self presentViewController:alertController animated:YES completion:nil];

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    [alertController dismissViewControllerAnimated:YES completion:^{
        p\Perform Action after dismiss alertViewController
    }];
});

A: In Xamarin.iOS / Monotouch this worked for me:
private async Task ShowToast(string message, UIAlertView toast = null)
    {
        if (null == toast)
        {
            toast = new UIAlertView(null, message, null, null, null);
            toast.Show();
            await Task.Delay(2000);
            await ShowToast(message, toast);
            return;
        }

        UIView.BeginAnimations("");
        toast.Alpha = 0;
        UIView.CommitAnimations();
        toast.DismissWithClickedButtonIndex(0, true);
    }

Remember that if an async method is called from a background thread (not the main UI thread) then InvokeOnMainThread would still be required.
This just means that you call the above method like this:
 BeginInvokeOnMainThread(() =>
 {
   ShowToast(message);
 });

A: update to the answer above as UIAlertView is deprecated
Answer At this Link
the 2nd function should be like this
-(void)dismissAlertView:(UIAlertController *)alertView{

  [alertView dismissViewControllerAnimated:YES completion:nil];
}


text:
Q: SCSS: Auto-generated vendor prefixes kill input placeholder styles HTML input fields can have a placeholder text that is shown while the field is empty. You can style the look of this text with the ::placeholder pseudo class. But there's a problem: This CSS breaks as soon as there is an unknown pseudo class present in the statement.
So this works:
.header-search-input::placeholder {
    color: red;
}

... but this doesn't (in Chrome):
.header-search-input::-moz-placeholder,
.header-search-input::placeholder {
    color: red;
}

... because the browser expects this to be done like so:
.header-search-input::-moz-placeholder {
    color: red;
}

.header-search-input::placeholder {
    color: red;
}

Fiddle: https://jsfiddle.net/eqftxyc6/2/
Is there a way to prevent these prefixes from being auto-generated by the SCSS compiler, or to get it to compile them correctly?

A: You must separate rules in 3 groups, do not combine them in one unique CSS rule...
Try it to custom the placeholder text
    :-moz-placeholder,
    ::-moz-placeholder{ color:red; }

    :-ms-input-placeholder{ color:red; }

    ::-webkit-input-placeholder,
    ::placeholder{ color:red; }


text:
Q: Print function in angular is not showing text inside inputs and angular material style I need to print specific part of a component in angular. The component html is built with angular material.
When I use the following:
print(){
    let divToPrint = document.getElementById('divToPrint').innerHTML;
    let newWindow = window.open('', '_blank', 'top=0,left=0,height=100%,width=auto');
    newWindow.document.open();
    newWindow.document.write(`
    <html>
        <head>
          <title>Print tab</title>
          <link rel="stylesheet" href="./login.component.css" type="text/css" media="print">
          <style>
            @media print {
              .noprint {display:none;}
            }
          </style>
        </head>
        <body onload="window.print();window.close()">${divToPrint}
        </body>
      </html>
    `);
    newWindow.document.close();
  }

If there is text inside inputs, the printable window does not show them.
I checked this answer on stackexchange, where the user said:

That's because innerHTML does not reflect changes by the user in input
  fields.

And we should add print media.
I already added the @media style and nothing happened as the inputs still empty.
Please take note that I am getting the values from database.
The other problem is that all material style are not shown either. So, an input is shown as basic html input instead of it's related mat-input style.


text:
Q: SSL with Nginx and Play Framwork 2.2.x I'm running my Play application on Amazon EC2 on port 9000.
I configured Nginx as a reverse proxy listening on port 443.
Here is my nginx configuration :
proxy_buffering        off;
proxy_set_header       X-Real-IP $remote_addr;
proxy_set_header       X-Scheme $scheme;
proxy_set_header       X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header       Host $http_host;
proxy_http_version     1.1;

upstream my-app {
    server 127.0.0.1:9000;
}

server {
    server_name www.my-app.com my-app.com;
    rewrite ^(.*) https://www.my-app.com$1 permanent;
}

server {
    listen               443;
    ssl                  on;
    ssl_certificate      /home/my-app.com/certificate.crt;
    ssl_certificate_key  /home/my-app.com/certificate.key;
    keepalive_timeout    70;
    server_name          www.my-app.com;
    location / {
        proxy_pass       http://my-app;
    }
}

My question is : do I need to launch my Play app with HTTPS instead of HTTP or is it enough to set SSL at nginx level ?
Given the fact that I want all my pages to be opened via HTTPS.
Thanks.

A: You don't need to use SSL connection between proxy and app, anyway in such case make sure that app port is NOT accessible from the world - most probably with Amazon's security rules (or some firewall in case of using other provider/OS).


text:
Q: Number of prime implicants How many  prime Implicants are there, 2 or 3?
F(w,x,y,z)=Σ(5,7,8,10)+d(9,11,13,15)

I am confused if red block will be counted as Prime Impicant or not?

A: By the definition:

A prime implicant of a function is an implicant that cannot be covered
  by a more general, (more reduced - meaning with fewer literals)
  implicant.

it is a prime implicant as it cannot be covered by some other (single) implicant.
But it is not an essential prime implicant defined as:

Essential prime implicants (aka core prime implicants) are prime
  implicants that cover an output of the function that no combination of
  other prime implicants is able to cover.

because it is fully covered by two other implicants.


text:
Q: Scipy curve_fit does not seem to change the initial parameters I know that there are several similar questions such as Use of curve_fit to fit data but the answer there (specific float type) does not seem to work for me. I am wondering if anyone is able to explain to me why the following code (which is an adaptation from an answer -> https://stackoverflow.com/a/11507723/1093485) does not work.
sample code:
#! /usr/bin/env python
import numpy
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt

def gaussFunction(x, A, mu, sigma):
    return A*numpy.exp(-(x-mu)**2/(2.*sigma**2))

x_points = [4245.428, 4245.4378, 4245.4477, 4245.4575, 4245.4673, 4245.4772, 4245.487, 4245.4968, 4245.5066, 4245.5165, 4245.5263, 4245.5361, 4245.546, 4245.5558, 4245.5656, 4245.5755, 4245.5853, 4245.5951, 4245.605, 4245.6148, 4245.6246, 4245.6345, 4245.6443, 4245.6541, 4245.6639, 4245.6738, 4245.6836, 4245.6934, 4245.7033, 4245.7131, 4245.7229, 4245.7328, 4245.7426, 4245.7524, 4245.7623, 4245.7721, 4245.7819, 4245.7918, 4245.8016, 4245.8114, 4245.8213, 4245.8311, 4245.8409, 4245.8508, 4245.8606, 4245.8704, 4245.8803, 4245.8901, 4245.8999, 4245.9097, 4245.9196, 4245.9294, 4245.9392, 4245.9491, 4245.9589, 4245.9687, 4245.9786, 4245.9884, 4245.9982, 4246.0081, 4246.0179, 4246.0277, 4246.0376, 4246.0474, 4246.0572, 4246.0671, 4246.0769, 4246.0867, 4246.0966, 4246.1064, 4246.1162, 4246.1261, 4246.1359, 4246.1457, 4246.1556, 4246.1654, 4246.1752, 4246.1851, 4246.1949, 4246.2047, 4246.2146]
y_points = [978845.0, 1165115.0, 1255368.0, 1253901.0, 1199857.0, 1134135.0, 1065403.0, 977347.0, 866444.0, 759457.0, 693284.0, 679772.0, 696896.0, 706494.0, 668272.0, 555221.0, 374547.0, 189968.0, 161754.0, 216483.0, 181937.0, 73967.0, 146627.0, 263495.0, 284992.0, 240291.0, 327541.0, 555690.0, 758847.0, 848035.0, 800159.0, 645769.0, 444412.0, 249627.0, 125078.0, 254856.0, 498501.0, 757049.0, 977861.0, 1125316.0, 1202892.0, 1263220.0, 1366361.0, 1497071.0, 1559804.0, 1464012.0, 1196896.0, 848736.0, 584363.0, 478640.0, 392943.0, 312466.0, 355540.0, 320666.0, 114711.0, 690948.0, 1409389.0, 1825921.0, 1636486.0, 1730980.0, 4081179.0, 7754166.0, 11747734.0, 15158681.0, 17197366.0, 17388832.0, 15710571.0, 12593935.0, 8784968.0, 5115720.0, 2277684.0, 769734.0, 674437.0, 647250.0, 708156.0, 882759.0, 833756.0, 504655.0, 317790.0, 711106.0, 1011705.0]

# Try to fit the gaussian
trialX = numpy.linspace(x_points[0],x_points[-1],1000)
coeff, var_matrix = curve_fit(gaussFunction, x_points, y_points)
yEXP = gaussFunction(trialX, *coeff)

# Plot the data (just for visualization)
fig =  plt.figure()
ax = fig.add_subplot(111)
plt.plot(x_points, y_points, 'b*')
plt.plot(trialX,yEXP, '--')
plt.show()

The output that it generates:

A: Without starting parameters they default to 1. Putting in
reasonable p0, it works:

p0 = [np.max(y_points), x_points[np.argmax(y_points)], 0.1]
coeff, var_matrix = curve_fit(gaussFunction, x_points, y_points, p0)

Leads to:


text:
Q: Show Overlay automatically without Tap on Marker in Maps I am able to show a custom Overlay by clicking on the Marker on the Map. But how can I show this Overlay without clicking the Marker?!

A: The following link provides you a solution for showing Overlay automatically without Tapping on Marker in maps
How to remove Marker and redraw it again when changing location on Android map


text:
Q: Variable productimage not showing I've set up a product with multiple variations. I want to have a single image (for all variations) and a imagegallery. I've set a featured image and added a image to the productgallery. I've also set an image under "Variations".
I've read that this problem could be caused by not having a secure connection (SSL Certificate), so I installed Let's Encrypt.
The images don't show up, but I can see the URL in the code. What is going wrong?
https://do-it-creatief.nl/product/scheepjeswol-stonewashed/
Thanks!

A: you have to set opacity from 0 to 1 in woocommerce.css
.product.has-default-attributes.has-children>.images{opacity:1}