text:
Q: Rails object value won't display on view page. No errors I currently have an app that allows users to comment on a blog post called a "work". Here are the model relationships:
class User < ActiveRecord::Base
  has_many :works
  has_many :comments

class Work < ActiveRecord::Base
  belongs_to :user
  has_many :comments

class Comment < ActiveRecord::Base
  belongs_to :user
  belongs_to :post
  belongs_to :work

There's a form on the Works show page that allows users to post a comment:
<%= form_for([@work, @comment]) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>
  <div class="field">
    <%= f.text_area :content, placeholder: "Post feedback or contribute content
    to this work!" %>
  </div>
  <%= f.submit "Post", class: "btn btn-small btn-primary" %>
<% end %>

Since the comment form is on the Works page, the Works controller has the following build logic for a comment:
def show
  @work = Work.find(params[:id])
  @comment = @work.comments.build
  @comment.user = current_user
  @activities = PublicActivity::Activity.order("created_at DESC").where(trackable_type: "Work", trackable_id: @work).all
  @comments = @work.comments.order("created_at DESC").where(work_id: @work).all
    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @work }
    end
  end

The Comments controller then creates the comment:
def create
    @work = Work.find(params[:work_id])
    @comment = @work.comments.build(params[:comment])
    @comment.user = current_user
    if @comment.save
      #flash[:success] = "Post created!"
      redirect_to @work
    else
      render 'home#index'
     end
  end

My problem is that the Works show page will display the user's name that submitted the comment but for some reason it will not display the value of the "content" field, even though there is a content value in the database! I don't get any error messages. I simply get an empty box where the content text should be.
Here is the Works show page that displays the content (minus the html formatting):
<% @comments.each do |comment| %>
<%= image_tag @comment.user.photo.url(:avatar) %> <%= link_to @comment.user.full_name, @comment.user if @comment.user %>
<%= @comment.content %>
<% end %>

If I replace @comment.content with something like @comment.work_id, I'll get the number "1" to display on the webpage. As I mentioned before, there is indeed a valid value for content stored in the database. Why won't it display? Why isn't there an error?
Thanks!!

A: In your view code, you are iterating over @comments and storing each one as comment (note lack of @) - then in the loop you are referring to @comment which is probably something else entirely.
Change the @comment to be comment.


text:
Q: Unable to figure out the SyntaxError in Javascript I am using ionic framework and i have the below code to identifyuser for enabling push notification.
$scope.identifyUser=function(){
    console.log("Ionic User :  Identifying Ionic User");
    var user = $ionicUser.get();

    if(!user.user_id){
        user.user_id = $ionicUser.generateGUID();
    }

    angular.extend(user, {
        name:"Poornima"
    });

    $ionicUser.identify(user).then(funtion(){
        alert("User id is : "+ user.user_id);
    });

    $scope.openRouter();
}

I am getting the below error when the controller is loaded
Uncaught SyntaxError: missing ) after argument list

Not sure what i am missing. please help.

A: It's a simple misspelling: funtion should be function

A: You got a typo:
$ionicUser.identify(user).then(funtion(){
    alert("User id is : "+ user.user_id);
});

funtion -> function

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to revert a commit but to a specific folder? I've made commits such that
commit hash - hash1 -> changes = a/1.txt, a/2.txt, b/1.txt
Now I'm reverting this commit by  git revert -m 1 hash1 but I want to remove only changes done to folder a/ but want to retain the changes inside b/
Is it possible?

A: git revert -m 1 hash1
# If needed, resolve conflicts and commit;
# those outside of a/ may be resolved arbitrarily.
git reset --hard HEAD^
git checkout hash1 a/
git commit -C HEAD@{1}

You could also use revert -n and then reset all other directories before committing; the recipe above is preferable only if there are many such other directories since it names only a.

A: You can use --no-commit.
git revert --no-commit <commit_id>
git restore --staged b/
git checkout .
git commit


text:
Q: Is it possible to activate Windows Update after deactivated by system admin? On my windows xp machine, it seems like Windows Update is not active. When I try to start it, I get a message telling me that system admininstrator has deactivated it.
Is there some policy or register key to turn in on again. I have looked through security policy, but without success. I have admin access to the machine. Any chance on activating Windows Update again?

A: Logged in as administrator, run gpedit.msc
Check the settings under User Configuration -> Administrative Templates -> Windows Compnents -> Windows Update
(this might be what you have already done)

A: See if this fixes the issue
http://www.dougknox.com/xp/scripts_desc/xp_winupd_netpolicy.htm

A: According to this MS support document:
it's either caused by group policy, system policy or the registry. It also goes on to mention a fix that you may or may not have tried (the fix may not be applicable but the error message is the same). Try following the link and seeing if there's anything useful there.


text:
Q: contenteditable onkeydown does not work on andriod/mobile I'm trying to use contenteditable with an onkeydown event which should limit my characters input. However I've stumbled across an issue on mobile where this onkeydown event is not working properly, but it works on desktop.
Can anyone help me with this? I just want a method to limit the characters input in the contenteditable that works on desktop & mobile. At the moment it only works for on desktop.

<div onkeydown="return (this.innerText.length <= 11)" contenteditable="true" onpaste="return false;" placeholder="RUN A AWAY" id="quote__text" class="editable">

If i had to use input, how can i make it expand as the text grows?


text:
Q: extjs3.4: How to use store filter on a grid I am using ExtJS3.4.
I want to filter the billingstore based on value selected by the user for billingName.
So, How do I pass the value selected to the store or grid? How do I achieve this?
Here is my code:
// Store for the grid panel - has billing grid data
        this.billingStore = new Ext.data.JsonStore({
                autoLoad: {params:{start: 0, limit: 2}},
                filter: {billingName}
                proxy: new Ext.data.HttpProxy({
                    url: '/ELCM/Client/getBillingList.do',
                }),
                root: 'data',
                fields: ['billingName','billingAmount','usedData','duration'],
                totalProperty:'totalRows'
        });
        var billingStore = this.billingStore;

    //view billing
        this.billingGrid = new Ext.grid.GridPanel({
                    title: 'View Billing',
                    store: that.billingStore,
                    columns:[
                          {header: "Amount",dataIndex: 'billingAmount'},
                           {header: "Data Used", dataIndex: 'usedData'},
                           {header: "Duration", dataIndex: 'duration'}
                         ],
                    sm: new Ext.grid.RowSelectionModel({singleSelect: true}),
                    bbar: new Ext.PagingToolbar({
                           store: that.billingStore,       // grid and PagingToolbar using same store
                           displayInfo: true,
                           pageSize: 2
                        }),
                     listeners: {
                                rowclick : function(grid, rowIndex, e){
                                 console.log("row Index "+rowIndex);
                                 }
                      }
        });
        var billingGrid = this.billingGrid;

Thanks

A: Depending on what you want to filter by a simple filter method on the store will achieve what your looking for.
billingGrid.getStore().filter([{
            property: '',
            id: '',
            value:
        }
]);

Look at http://docs.sencha.com/extjs/4.2.2/#!/api/Ext.data.Store-method-filter for further information.

A: Check out this code ,how does the filter in ExtJS work its required the property (i.e billingName for filtering as per your example) then 'value' on basis of which the filter happen this 2 are the mandatory options required for the filter function to work other optional config property which is exactMatch & caseSensitive which add the accuracy to the filter function.
Try out the below code
// Store for the grid panel - has billing grid data
this.billingStore = new Ext.data.JsonStore({
            autoLoad: {params:{start: 0, limit: 2}},
            filter: [{
                    property: 'billingName',
                    value: ''//Data source which need to be filter or based on value selected by the user for billingName
                    exactMatch: true,
                    caseSensitive: true
                }],
            proxy: new Ext.data.HttpProxy({
                url: '/ELCM/Client/getBillingList.do',
            }),
            root: 'data',
            fields: ['billingName','billingAmount','usedData','duration'],
            totalProperty:'totalRows'
    });

var billingStore = this.billingStore;

//view billing
    this.billingGrid = new Ext.grid.GridPanel({
                title: 'View Billing',
                store: that.billingStore,
                columns:[
                      {header: "Amount",dataIndex: 'billingAmount'},
                       {header: "Data Used", dataIndex: 'usedData'},
                       {header: "Duration", dataIndex: 'duration'}
                     ],
                sm: new Ext.grid.RowSelectionModel({singleSelect: true}),
                bbar: new Ext.PagingToolbar({
                       store: that.billingStore,       // grid and PagingToolbar using same store
                       displayInfo: true,
                       pageSize: 2
                    }),
                 listeners: {
                            rowclick : function(grid, rowIndex, e){
                             console.log("row Index "+rowIndex);
                             }
                  }
    });
    var billingGrid = this.billingGrid;


text:
Q: error while setting authorities with Spring security I use spring security and have some problems when starting the authentication process
Here is my class USER
    @Entity
@Table(name="MEMBRE")
public class Membre  implements UserDetails, Serializable {

    ...................
    private ArrayList<Role> authorities;

    @ManyToMany
    @JoinTable(
            name="MEMBRE_ROLE",
            joinColumns={@JoinColumn(name="id_membre", referencedColumnName="id_membre")},
            inverseJoinColumns={@JoinColumn(name="id_role", referencedColumnName="id_role")})
    public Collection<Role> getAuthorities() {
        return this.authorities;
    }

    public void setAuthorities(ArrayList<Role> authorities) {
        this.authorities = authorities;
    }
    ................
    }

Here is my class Role (GrantedAuthority)
    @Entity
@Table(name="ROLE")
public class Role  implements GrantedAuthority, Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 4160725609927520747L;

    private Integer id;

    private String role;

    @Transient
    public String getAuthority() {
        return this.role;
    }

    @Id
    @GeneratedValue
    @Column(name = "id_role", unique = true, nullable = false, precision = 9, scale = 0)
    public Integer getId() {
        return this.id;
    }

    @Column(name = "role", nullable = false, length = 20)
    public String getRole() {
        return this.role;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public void setRole(String role) {
        this.role = role;
    }

}

Here is my table MEMBRE_ROLE
    CREATE  TABLE IF NOT EXISTS `MEMBRE_ROLE` (
  `id_role` INT NOT NULL AUTO_INCREMENT ,
  `id_membre` INT NOT NULL),
  PRIMARY KEY (`id_role`, `id_membre`) ,
  CONSTRAINT `fk_membre_role_membre`
    FOREIGN KEY (`id_membre` )
    REFERENCES `membre` (`id_membre` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_membre_role_role`
    FOREIGN KEY (`id_role` )
    REFERENCES `role` (`id_role` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;

And when I try to authenticate, I get the following error
org.springframework.security.authentication.InternalAuthenticationServiceException: IllegalArgumentException occurred while calling setter for property [domain.Membre.authorities (expected type = java.util.ArrayList)]; target = [domain.Membre@1807f3f2], property value = [[domain.Role@16cc0706, domain.Role@88b48]] setter of domain.Membre.authorities; nested exception is IllegalArgumentException occurred while calling setter for property [domain.Membre.authorities (expected type = java.util.ArrayList)]; target = [domain.Membre@1807f3f2], property value = [[domain.Role@16cc0706, domain.Role@88b48]]
I understand that the setter isn't properly defined, but I can' see how to manage it and if the mapping of authorities is properly defined considering spring security

A: To not confuse JPA, use the same type for field, getter and setter:
private Collection<Role> authorities;

public Collection<Role> getAuthorities() {
    return this.authorities;
}

public void setAuthorities(Collection<Role> authorities) {
    this.authorities = authorities;
}

(JPA annotations omitted for brevity.)

A: I tried to debug repacing my setter method by
    public void setAuthorities(Object authorities) {
    this.authorities = (ArrayList<Role>)authorities;
}

And I get a PersistentBag as argument for authorities
Here is the inspection of authorities expression

*

*Authorities

*bag  --> ArrayList

*

*elementData --> Object[10]

*

*[0] -->  Role

*1 -->  Role

How to get an ArrayList as argument ? I suppose there is an issue with the mapping.
I found this post on internet, but it didn't give me a solution that works
http://www.coderanch.com/t/431759/ORM/databases/JPA-returning-collection-type-PersistentBag

A: finally I found a temporary solution, not very elegant, but it works. If you have a better solution ..........
public void setAuthorities(PersistentBag authorities) {
final List<Object> listObject = Arrays.asList(authorities.toArray());
final ArrayList<Role> roles = new ArrayList<Role>();
for (final Object object : listObject) {
    if (object instanceof Role) {
        roles.add((Role)object);
    }
}
this.authorities = roles;

}


text:
Q: MySQL Script to automate creation of audit (history) tables and triggers? For regulatory and fraud requirements, we need to record every change to most of the tables in the DB.  The way we did this very successfully with a previous project is to have a copy of each table, identical except that:

*

*4 additional columns: DateChanged, UserId, Action (Create, Update, delete), and IP

*The Id pk no longer is unique.

*all other constraints (FK, unique indexes etc) removed.

*the audit tables are in a separate audit schema

At a previous job, the Oracle DBAs wrote a script to automatically generate all this, it did the following:

*

*Created a new schema called audit if not existing

*Iterate over each table t in the normal schema:

*

*created a new table in the audit schema with the same table name except prefixed it with a_, e.g. a_t

*Added all the same columns as the original table, plus the 4 additional columns (DateChanged, UserId, IP Address and Action)

*generated and added triggers to the original table (if not already there) to:

*If updating, write a new row to the corresponding a_ table, with action of "Update" containing the pre-updated (old) values in all the columns (the main table will have the new values)

*If deleting, Add a row which is a copy of the main tables row, but action = "Delete".

*If inserting, add the row to the audit schema

NOTE:

*

*All tables have a ID PK.

*A few tables need to be excluded for performance or because not needed (e.g. the balance table which is updated by a trigger)

The beauty of this system is you can query what changed and when, or who made changes to what, and see the record before and after the change.  changes are at the DB row level, not the individual column level.
Has anyone come across something like this for MYSQL 5.6?  We don't have a DBA on our team who could write something like this from scratch, but we know enough to modify something similar.

A: I just wrote this earlier today.  It's a select statement working off the information_schema database, which produces the schema for the audit tables and the triggers.
SET GLOBAL group_concat_max_len = 1000;

SET @dbName = "[[[your_db_name_here]]]";

SELECT concat("DROP TABLE IF EXISTS `", @dbName, "`.`", table_data.audit_table, "`;\r",
          "CREATE TABLE `", @dbName, "`.`", table_data.audit_table, "`\r",
          "(\r",
          "  `auditAction` ENUM ('INSERT', 'UPDATE', 'DELETE'),\r",
          "  `auditTimestamp` DATETIME DEFAULT CURRENT_TIMESTAMP,\r",
          "  `auditId` INT(14) AUTO_INCREMENT,",
          column_defs, ",\r"
          "  PRIMARY KEY (`auditId`),\r",
          "  INDEX (`auditTimestamp`)\r",
          ")\r",
          "  ENGINE = InnoDB;\r\r",
          "DROP TRIGGER IF EXISTS `", @dbName, "`.`", table_data.insert_trigger, "`;\r",
          "CREATE TRIGGER `", @dbName, "`.`", table_data.insert_trigger, "`\r",
          "  AFTER INSERT ON `", @dbName, "`.`", table_data.db_table, "`\r",
          "  FOR EACH ROW INSERT INTO `", @dbName, "`.`", table_data.audit_table, "`\r",
          "     (`auditAction`,", table_data.column_names, ")\r",
          "  VALUES\r",
          "     ('INSERT',", table_data.NEWcolumn_names, ");\r\r",
          "DROP TRIGGER IF EXISTS `", @dbName, "`.`", table_data.update_trigger, "`;\r",
          "CREATE TRIGGER `", @dbName, "`.`", table_data.update_trigger, "`\r",
          "  AFTER UPDATE ON `", @dbName, "`.`", table_data.db_table, "`\r",
          "  FOR EACH ROW INSERT INTO `", @dbName, "`.`", table_data.audit_table, "`\r",
          "     (`auditAction`,", table_data.column_names, ")\r",
          "  VALUES\r",
          "     ('UPDATE',", table_data.NEWcolumn_names, ");\r\r",
          "DROP TRIGGER IF EXISTS `", @dbName, "`.`", table_data.delete_trigger, "`;\r",
          "CREATE TRIGGER `", @dbName, "`.`", table_data.delete_trigger, "`\r",
          "  AFTER DELETE ON `", @dbName, "`.`", table_data.db_table, "`\r",
          "  FOR EACH ROW INSERT INTO `", @dbName, "`.`", table_data.audit_table, "`\r",
          "     (`auditAction`,", table_data.column_names, ")\r",
          "  VALUES\r",
          "     ('DELETE',", table_data.OLDcolumn_names, ");\r\r"
)
FROM (
   # This select builds a derived table of table names with ordered and grouped column information in different
   # formats as needed for audit table definitions and trigger definitions.
   SELECT
     table_order_key,
     table_name                                                                      AS db_table,
     concat("audit_", table_name)                                                    AS audit_table,
     concat(table_name, "_inserts")                                                  AS insert_trigger,
     concat(table_name, "_updates")                                                  AS update_trigger,
     concat(table_name, "_deletes")                                                  AS delete_trigger,
     group_concat("\r  `", column_name, "` ", column_type ORDER BY column_order_key) AS column_defs,
     group_concat("`", column_name, "`" ORDER BY column_order_key)                   AS column_names,
     group_concat("`NEW.", column_name, "`" ORDER BY column_order_key)               AS NEWcolumn_names,
     group_concat("`OLD.", column_name, "`" ORDER BY column_order_key)               AS OLDcolumn_names
   FROM
     (
       # This select builds a derived table of table names, column names and column types for
       # non-audit tables of the specified db, along with ordering keys for later order by.
       # The ordering must be done outside this select, as tables (including derived tables)
       # are by definition unordered.
       # We're only ordering so that the generated audit schema maintains a resemblance to the
       # main schema.
       SELECT
         information_schema.tables.table_name        AS table_name,
         information_schema.columns.column_name      AS column_name,
         information_schema.columns.column_type      AS column_type,
         information_schema.tables.create_time       AS table_order_key,
         information_schema.columns.ordinal_position AS column_order_key
       FROM information_schema.tables
         JOIN information_schema.columns
           ON information_schema.tables.table_name = information_schema.columns.table_name
       WHERE information_schema.tables.table_schema = @dbName
             AND information_schema.columns.table_schema = @dbName
             AND information_schema.tables.table_name NOT LIKE "audit\_%"
     ) table_column_ordering_info
   GROUP BY table_name
 ) table_data
ORDER BY table_order_key
INTO OUTFILE "[[[your_output_file]]]"

A: Vanyo's answer almost worked for me. It was fine once I moved the backtick in the NEW and OLD references (so instead of `NEW.column1` I get NEW.`column1`):
group_concat("NEW.`", column_name, "`" ORDER BY column_order_key)               AS NEWcolumn_names,
group_concat("OLD.`", column_name, "`" ORDER BY column_order_key)               AS OLDcolumn_names


text:
Q: For which recursive functions (or infinite expressions) can substitution be used for a solution? I have a question about recursive functions and their convergence as sequences.
We know that the golden ratio can be represented by:
$$
\phi= 1+\frac{1}{1+\frac{1}{1+\frac{1}{...}}}
$$
Rewriting the above infinite expression as a recursive function gives us:
$$
\phi(x)=1+\frac{1}{x}
$$
$\lim_{p \to \infty} \phi^p(x)$ converges to the golden ratio for $x \in \mathbb{R}, x\neq0,\Phi$ (the golden ratio conjugate). The solution for this convergence can be found when substituting $\phi(x)$ in for $x$ if you assume $\lim_{p \to \infty} \phi^p(x)=\phi^{p-1}(x)$. My question is: for which recursive functions (as a sequence) can you assume that for in order to solve for convergence? Also, how will you know how many solutions there are for any of these functions? Here's a few examples I've found/wondered about:
$$
\phi(x)=1+\frac{1}{x}, \lim_{p \to \infty} \phi^p(x)=1.618... \text{ (unless $x=0,\Phi$), two convergences ($\phi$ and $\Phi$), for } x \in \mathbb{R}
$$
$$
f(x)=\frac{x}{2}, \lim_{p \to \infty} f^p(x)=0, \text{one convergence, for } x \in \mathbb{R}
$$
$$
d(x)=x-1+0^{x-1}, \lim_{p \to \infty} d^p(x)=1, \text{one convergence, for } x \in \mathbb{N} \text{ (a strange function, but I'm still curious)}
$$

A: You were able to see that your recursion was of the form $x_{n+1} = \phi(x_n)$. Therefore, if you assume that $(x_n)$ is a convergent sequence, it must converge to a fixed point of $\phi$, .i.e. a solution of the equation
$x = \phi(x)$. In your example, $x = \phi(x) \Leftrightarrow  x = \frac 12 (1\pm \sqrt{5})$, where one of the solutions can be discarded based on the signal of the terms.
This "method" can be used whenever you can assure that $(x_n)$ is a convergent sequence. The fixed point theorem gives nice sufficient conditions for convergence, just based on the behavior of $\phi(x)$ and $x_0$.


text:
Q: Rich UI Web application development We have been developing the html template editor which allows you to drag and drop the components (TextBox,Label,Image, Videos etc), positioning and styling them. Writing boilerplate JavaScript would require huge effort, we initially thought of taking advantage of GWT. Since GWT is Java based, I wonder if any JavaScript libraries are available as an alternative to it.
 I went though the typescript and angular2 but not very sure whether such sophisticated application can be developed using it. I would be very happy to know if someone helps to compare the power of GWT and angular2 or any other libraries available for my requirement. Thank you.


text:
Q: Objective-c timeIntervalSince1970 return 0 NSUInteger currentTime = [[NSDate date] timeIntervalSince1970];

Here current time is 0.
Can you tell me reason for this?

A:   NSUInteger currentTime = [[NSDate date] timeIntervalSince1970];
  NSLog(@"%d",currentTime);

this gives me correct value of current time in Milliseconds .

A: Use NSTimeInterval instead of NSUIntegeralthough NSUInteger is also giving the correct answer

A: NSUInteger currentTime = [[NSDate date] timeIntervalSince1970];
NSLog(@"timeIntervalSince:%lu",(unsigned long)currentTime);

as currentTime gives a unsigned long value..


text:
Q: Padarn Session for many users I'm evaluating Padarn for my project and I'm trying to implement a very simple authentication scheme:
namespace SampleSite
{
    public class Login : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Form["login"] == "admin" && Request.Form["password"] == "123")
            {
                Session["username"] = "admin";
                Response.Redirect("PostFiles.html");
            }
            else
            {
                Response.Redirect("Default.aspx");
            }
        }
    }
}

It's working fine for a single user, however, when my friend tried to hit the page while I was debugging, a NullReferenceException was thrown at
Session["username"] = "admin";

Then we realized it's not working for concurrent users.
Are concurrent sessions really not supported? Is this some configuration I'm missing?

A: Multiple sessions are definitely supported.  By default 10 concurrent sessions are supported.
I put together this quick validation test Page:
class SessionTest : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        var newVariable = Request.Form["value"];

        if (newVariable != null)
        {
            Session["TestVariable"] = newVariable;
        }
    }

    protected override void Render(HtmlTextWriter writer)
    {
        var sessionVariable = Session["TestVariable"];

        writer
            .Html()
                .Body()
                    .Form(t => t
                        [HtmlTextWriterAttribute.Id, "Test"]
                        ["method", "POST"])

                        .Text(string.Format("CurrentValue: {0}", sessionVariable ?? "[null]"))
                        .Br()
                        .Input(t => t
                                [HtmlTextWriterAttribute.Type, "text"]
                                [HtmlTextWriterAttribute.Name, "value"]
                                [HtmlTextWriterAttribute.Maxlength, "32"])
                        .EndTag() // input
                        .Br()
                        .SubmitButton("Submit", "Submit")
                    .EndTag() // form
                    .Form(t => t
                        [HtmlTextWriterAttribute.Id, "Reload"]
                        ["method", "POST"])
                        .SubmitButton("Reload", "Reload")
                    .EndTag() // form
                .EndTag() // body
            .EndTag(); // html
    }
}

It simply displays a variable for the current Session and lets you change it.  I opened two browsers, on in IE and one in Chrome, which generates two sessions just like two PCs would.  I then hit the page from both browsers and they showed different saved session state as expected:

A: It turns out that, for no good reason at all, the hands-on lab ships with a domain set for the cookies.  Even worse, the domain is nonsensical.  It's probably a remnant of some sort of testing we were doing internally and never reverted for release.
What's happening is that the configuration has this in it:
<Cookies Domain="169.0.0.2" />

This is causing the session cookies to get stripped from any client (unless it's IP happens to be 169.0.0.2).
This, in turn, causes a new session to be generated with every browser request, which effectively throws out your session variables.
Change your web.config to not have a cookie domain like this, and all will be well:
<Cookies />

The NullReferenceException you get in your Page code is because the Session object on the page in null.  This happens when the maximum number of Sessions for the service has been reached (which occurs quickly when each request is generating a new Session).


text:
Q: Randomize li items and freeze multiple I need to randomize a list of 5-n li items and set for 1-5 items a specific place, for example, I have

*

*a

*b

*c

*d

*e

*f

And I want to randomize the last 4 and put on li[0] letter D and on li[2] letter F
Results:

*

*d

*f

*c

*b

*a

*e

Here is my code. Where I'm wrong? Thanks!
    var ul = document.querySelector('ul');
    for (var i = ul.children.length; i >= 0; i--) {

    if(ul.children.innerHTML == "XXX") {
        ul.appendChild(ul.children[0]);
    }
    if(ul.children.innerHTML == "XXXX") {
        ul.appendChild(ul.children[1]);
    }
    if(ul.children.innerText == "XX") {
        ul.appendChild(ul.children[2]);
    } else {
        ul.appendChild(ul.children[generateRandom(i) | 0]);
    }
}

function generateRandom(i) {
    var num = Math.random() * i | 0;
    return (num === 0 || num === 1 || num === 2) ? generateRandom(i) : num;
}

A:

var $test = $('#test');
var $li = $test.children();

while ($li.length > 0) {
  //pick a random li from the variable
  var $next = $li.eq( Math.floor( Math.random() * 10 * $li.length ) % $li.length );
  //move it to the end of ul
  $test.append($next);
  //remove the li from our variable so it won't be found again
  $li = $li.not($next);
}

//move the f to the top, so when we move the d to the top it will be second
$test.prepend($test.children().filter(function(){ return this.innerHTML === 'f'; }));
//move the d to the top
$test.prepend($test.children().filter(function(){ return this.innerHTML === 'd'; }));

a

b

c

d

e

f

g

h

i

j

k


text:
Q: Cannot form weak reference to UIScrollView sub class (EXC_BAD_INSTRUCTION) when dismissing modal view Hi everyone I've been debugging this issue for quite some time but no luck so far. I am quite lost here and have no clue on the reason causing this crash and how to fix it. I will be very grateful if anyone can offer me some help on this, thanks a lot!
I've prepared a sample project to demonstrate the issue at GitHub here.
The scenario is as the following:

*

*There are two view controllers, namely the root view and modal view, each has a custom scroll view (class namely SubScorllView) as sub view, and the modal view has a button for dismissing the modal view.

*The scroll views are sub-classes of UIScrollView, each with their corresponding delegate protocol, and their class hierarchy is as below:

UIScrollView
  ∟ SuperScrollView
  .....∟ SubScrollView

The app launches and runs in a very simple manner, in AppDelegate's didFinishLaunchingWithOptions:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor blackColor];

    RootViewController * rootVC = [[RootViewController alloc] init];
    self.navVC = [[UINavigationController alloc] initWithRootViewController:rootVC];
    self.navVC.navigationBarHidden = TRUE;

    self.window.rootViewController = self.navVC;
    [self.window makeKeyAndVisible];

    ModalViewController *modalVC = [[ModalViewController alloc] init];
    [self.navVC presentViewController:modalVC animated:YES completion:nil];

    return YES;
}

And the views are loaded from xib files, which the scroll views' delegate are also set inside, and there are some overrides regarding the methods for initiating and setting delegate for the scroll view sub-classes.
The problem occurs when I dismiss the modal view through clicking the "Close" button in the modal view, when the button is clicked, the following happens:
- (IBAction)didPressedCloseButton:(id)sender {

    self.subScrollView.delegate = nil;
    [self dismissViewControllerAnimated:YES completion:nil];

}

And the app crashes at the following segment in SuperScrollView:
- (void)setDelegate:(id<SuperScrollViewDelegate>)delegate {

    _superScrollViewDelegate = delegate;

    // trigger UIScrollView to re-examine delegate for selectors it responds
    super.delegate = nil;
    super.delegate = self;  // app crashes at this line
}

With the following error message in the console:

objc[6745]: Cannot form weak reference to instance (0x7fa803839000) of
  class SubScrollView. It is possible that this object was
  over-released, or is in the process of deallocation.

I don't understand why the app would crash and giving the above error message, or how should I fix it. I tried to search with the error message but seems that message is mostly related to other classes like text views, while some others solved it with setting the delegate of the scroll view to nil before deallocating but it doesn't work in my case.
==========
Update: Just tested if this happens on iOS 8 with simulator, it doesn't crash like on iOS 9 at all.

A: When the SuperScrollView is deallocated, setDelegate is called implicitly. In iOS 9, you cannot set the delegate to self, because self is in the process of being deallocated (no idea why this worked in iOS 8). To work around this issue, you can check first to see if the passed in delegate parameter is not nil, and only then set super.delegate to self:
- (void)setDelegate:(id<SuperScrollViewDelegate>)delegate {

    _superScrollViewDelegate = delegate;

    // trigger UIScrollView to re-examine delegate for selectors it responds
    super.delegate = nil;

    if(delegate)
    {
        super.delegate = self;
    }
}

If for some reason you need to support self responding to the UIScrollView delegate methods even when _superScrollViewDelegate is nil, you could create a parameter
@interface SuperScrollView ()

@property (nonatomic, weak) SuperScrollView * weakSelf;

@end

at the top of the file, and set it in setup
- (void)setup {

    super.delegate = self;
    self.weakSelf = self;
}

Then, in setDelegate, just check that weakSelf is not nil. If weakSelf is nil, then self is in the process of deallocating and you should not set it to the super.delegate:
- (void)setDelegate:(id<SuperScrollViewDelegate>)delegate {

    _superScrollViewDelegate = delegate;

    // trigger UIScrollView to re-examine delegate for selectors it responds
    super.delegate = nil;

    if(self.weakSelf)
    {
        super.delegate = self;
    }
}

A: super.delegate = self ,super here is UIScrollView, super.delegate is of type UIScrollViewDelegate, and self is of type UIScrollView, so you are setting UIScrollView's delegate to be a scroll view, which doesn't make sense, normally controller should be the delegate of UIScrollView.
When you dismiss modal view controller, it is in the process of deallocation. super.delegate = self;, here self is a scroll view which is a subview of self.view, which belongs to the modal view controller. so self is also deallocating.

A: I had the same problem in Swift and cncool's answer helped me.
The following (considering being in the parent class's instance) fixed my issue:
deinit {
    self.scrollView.delegate = nil
}


text:
Q: TestDisk: The harddisk is reported as too small? I am trying to restore partitions on an old hard drive. The drive has been formatted previously. I am using TestDisk 6.14. When I choose the option Deeper Search I think it finds something, because a screen that looks like a list of partitions flashes quickly before my eyes, but it says that the hard drive is too small.
A hard drive being too small... what does that imply? It's quite normal for an old hard drive to be small. It's only 15 GB! If it was a 1750 GB hard drive and I got that message that would be alarming. But for an old hard drive... well, of course it's small?! I'm sure TestDisk supports hard drives that are 15 GB or smaller?!
Disk /dev/sdd - 15 GB / 14 GiB - CHS 1871 255 63

The harddisk (15 GB / 14 GiB) seems too small! ((30 GB / 28 GiB))
Check the harddisk size_ HD jumpers settings, BIOS detection...

The following partition can't be be recovered:
  Partition      Start         End           Size in sectors
> HPFS - NTFS    1870 254 63   3741 253 62   30057552

[ Continue ]
NTFS, blocksize=4096, 15 GB / 14 GiB

What are my chances of restoring the partitions?
Screenshots; step by step.

The screen that just flashes by appears here, right between these two. I would have to do a screen recording to capture that particular frame. Is there a way to pause TestDisk at this point to allow me to read what it says on that screen?...
Update: Here is a screenshot of that screen.

Pressing Enter just returns to the main menu.

A: I believe DISKPART may be what you're looking for. I use this niffty command line tool for just about all my stuburn HDD woes.
Note: Don't get nervous by Microsofts overly verbose summaries and descriptions- DISKPART is a simple tool to use.


text:
Q: How to use navigation.navigate() in map function I'm trying to display a list of TouchableOpacity to navigate to an other page with navigation.navigate(...).
I'm using map to display the list but I can't navigate, the onPress don't work with this error message : "undefined is not an object (evaluating 'navigation.navigate')
What am I doing wrong ?
function PopupMenuAction ({navigation}) {
   return (
        <>
            <TouchableOpacity style={style.shape1to2} onPress={() => resizeBox(1)}>
                <Text style={style.subtext}>Add <Text style={{ color: layouts.secondary }}>+</Text></Text>
            </TouchableOpacity>
            <Modal transparent visible={visible}>
                <SafeAreaView style={{ flex: 1 }} onTouchStart={() => resizeBox(0)}>
                    <Animated.View
                    style={[
                        style.popUp,
                            { opacity: scale.interpolate({ inputRange: [0, 1], outputRange:[0, 1]}) },
                            { transform: [{ scale }]},
                        ]}
                    >
{/* THERE IS THE CODE WHERE IT DONT WORK

=>>>*/}

                        {actions.map((op, i) => (
                            <TouchableOpacity style={[
                                style.option,
                                { borderBottomWidth: i === actions.length - 1 ? 0 : 1 }]}
                                key={i}
                                onPress={() => navigation.navigate('CreateReaction')}
                            >
                                <Text style={{ fontFamily: "Title-Font", fontSize: 15 }}>{op.title}</Text>
                            </TouchableOpacity>
                        ))}

                    </Animated.View>
                </SafeAreaView>
            </Modal>
        </>
    )
}

A: Believe navigation does not exist in your functional components because the error indicates it is undefined.
Try to import the useNavigation() hook from react-navigation library and use the returned navigate function.
import { useNavigation } from '@react-navigation/native';

function PopupMenuAction ({navigation}) {

   const { navigate } = useNavigation()

   return (
      // rest of your code
   )

docs: https://reactnavigation.org/docs/use-navigation/


text:
Q: JsonConvert.DeserializeObject for json with different key names I am trying to use the Json.Net converter for this strange json:
{
  "Key1": {
  "id": "1",
  "name": "one"
  },
  "Key2": {
  "id": "2",
  "name": "two"
  },
...
  "CouldBeAnything": {
  "id": "n",
  "name": "CouldBeAnything"
  }
}

If I use the json to xml source generation,  I get objects with with properties called Key1, Key2 etc.  That doesn't work as I need a list of those keys and values associated with them.  Is there a way to create an object that can be serialized directly?  Thanks in advance.

A: You could do something like this:
    class Class1
    {
        public string id { get; set; }
        public string name { get; set; }
    }

    static void Main(string[] args)
    {
        var d = new Dictionary<string, Class1>();

        d.Add("Key1", new Class1() { id = "1", name = "one" });
        d.Add("Key2", new Class1() { id = "2", name = "two" });
        d.Add("CouldBeAnything", new Class1() { id = "n", name = "CouldBeAnything" });

        var json = JsonConvert.SerializeObject(d, Formatting.Indented);

    }


text:
Q: How to animate the Counter value in UI to increase the value in C# WPF? I want to develop an application in WPF, and same in Windows Phone 8.1. Where I want to increase the value of a variable from 100 to 200, from 200 to 300 and go on. This is a score of the game. Now I want to animate this in the UI. I have written a sample code like this.
<Button Click="Button_Click" >Start</Button>
<TextBlock x:Name="tbvalue" />

So when the button is clicked the value will be from 100 to 200, but this should be displayed in the UI like 101,102,103 ... with incremental value animated in the UI.
I have written the code behind like
private void Button_Click(object sender, RoutedEventArgs e)
{
    while (count < upperLimit)
    {
        count += 1;
        this.Dispatcher.BeginInvoke(new Action<object>(perform), sender);
        System.Threading.Thread.Sleep(100);
    }

    i++;
    upperLimit = i * 100;
}

and in that
private void perform(object obj)
{
    tbvalue.Text = count.ToString();
}

But using this I am not achieving the counter animation. any ideas or suggestions how to achieve this functionality.

A: This is what I did and it is working fine.I made a demo wpf application
 public MainWindow()
        {

            InitializeComponent();
            Counter_Timer.Interval = new TimeSpan(0, 0, 1);
            Counter_Timer.Tick += dispatcherTimer_Tick;
            counter.Content = 100;
        }
        private readonly DispatcherTimer Counter_Timer = new DispatcherTimer();
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Counter_Timer.Start();
        }

        public void dispatcherTimer_Tick(object sender, object e)
        {
            counter.Content = Convert.ToInt16(counter.Content) + 1;
        if (Convert.ToInt16(counter.Content) >= 200)
        {
            Counter_Timer.Stop();
        }
        }

Xaml File:
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition />
        </Grid.RowDefinitions>
        <Button Click="Button_Click" Grid.Row="0" Name="Counter" ></Button>
        <Label Name="counter" Grid.Row="1"></Label>
    </Grid>

A: ViewModel approach (this will animate text change from 0 to 100 when button clicked)
public MainWindowViewModel()
{
   BtnClicked = new DelegateCommand(() => TextBlockValue += 100);
}

private double value;
public double TextBlockValue
{
    set
    {
        DispatcherTimer counterTimer = new DispatcherTimer
        {
            Interval = TimeSpan.FromMilliseconds(5),
        };
        counterTimer.Tick += (sender, args) =>
        {
            SetProperty(ref this.value, this.value + 1);
            if (this.value >= value) counterTimer.Stop();
        };
        counterTimer.Start();
    }
    get => value;
}


text:
Q: Gnuplot 3D splot in tikz raw gnuplot (without pgfplots) please look at the following MWE:
\documentclass{article}

\usepackage{tikz}

\begin{document}

\begin{tikzpicture}[scale=.5]
\draw[color=blue] plot[raw gnuplot, smooth] function{
splot sin(x)*sin(y)};
\end{tikzpicture}

\end{document}

I try to plot a function of 2 variables, but I get a very strange output:

It should be similar to the output in Gnuplot:

Where is my mistake? (I know I could use pgfplots, but I look for a solution without.)

A: I have no idea how to steer splot from TikZ only. The following produces something reminiscent of the screen shot you seem to be looking for,
\documentclass[tikz,border=3.14mm]{standalone}
\begin{document}
\begin{tikzpicture}[scale=.5]
\foreach \Y in {-10,-9,...,10}
{\begin{scope}[shift={(0,0,\Y)}]
\draw[color=blue] plot[raw gnuplot,smooth]
function{plot sin(x)*sin(\Y)};
\end{scope}}
\end{tikzpicture}
\end{document}

but obviously there are tons of things that could be improved, starting from an orthonormal projection.

A: What about knitr?

\documentclass{article}
\begin{document}
<<echo=F,dev="tikz",message=FALSE>>=
fsinsin <- function (x, y) {return (sin(x)*sin(y))}
x <- seq(-6, 6, length= 40)
y <- x
z <- outer(x, y, fsinsin)
library(lattice)
library(gridExtra)
trellis.par.set("axis.line", list(col=NA,lty=1,lwd=1))
wireframe(z, drape=T, shade=F, xlab="x", ylab="y",
col.regions=rainbow(150), aspect = c(1, .2), borders=F,
scales = list(arrows = FALSE),
colorkey=F)
@

\end{document}

A: What about using the gnuplottex package with the tikz output terminal (page 9, gnuplottex.pdf)?
Furthermore, if you have many pictures the tikz-package offers the possibility to externalize the pictures, see p. 11 gnuplottex.pdf.
Output:

Code:
\documentclass{article}
\usepackage{graphicx}
\usepackage{latexsym}
\usepackage{ifthen}
\usepackage{moreverb}
\usepackage{tikz}
\usepackage{gnuplot-lua-tikz}
\usepackage[miktex]{gnuplottex}
\begin{document}
    \begin{figure}%
            \centering%
            \begin{gnuplot}[terminal=tikz]
            set out "tex-gnuplottex-fig1.tex"
            set term lua tikz latex createstyle
            splot sin(x)*sin(y);
            \end{gnuplot}
        \caption{This is using the \texttt{tikz}-terminal. The function $f(x,y)=sin(x)*sin(y)$}%
        \label{pic:tikz}%
    \end{figure}%
\end{document}

A: According to the current manual TikZ PGF Packages Manual 3.1.4 with status from July 17, 2019 TikZ simply cannot read 3D GNUPLOT table files and that explains why you get a very strange output. By the way, this output changes with the scale factor.

22.4 Plotting Points Read From an External File
  [...]
  Currently, the only file format that TikZ allows is the following: Each
  line of the〈filename〉should contain one line starting with two numbers,
  separated by a space. A line may also be empty or, if it starts
  with # or % it is considered empty. For such lines, a "new data set" is
  started, typically resulting in a new subpath being started in the plot
  (see Section 112.2.2 on how to change this behaviour, if necessary).
  For lines containing two numbers, they must be separated by a space.
  They may be following by arbitrary text, which is ignored, except if it
  is o or u.
  [...]
  (This is exactly the format that gnuplot produces when you say set
  terminal table.)

With the restriction...if you command: plot

But you want this with 3 numbers from 'splot':
# Surface 0 of 1 surfaces
# Curve title: "sin(x)*sin(y)"
# IsoCurve 0, 100 points
# x y z type
-10.00000 -10.00000 0.29596 i
-9.79798 -10.00000 0.19835 i
-9.59596 -10.00000 0.09267 i
-9.39394 -10.00000 -0.01677 i

marmot only used plot (2D) in his answer and thus avoided this problem.
One question now is why you don't want to use PGFPLOTS. It can replace or supplement GNUPLOT. The replacement is an \addplot expression which evaluates the expressions using the math parser of PGF while \addplot gnuplot employs GNUPLOT to compute the coordinates.
\addplot3[raw gnuplot,smooth] gnuplot[id=sinus3d] {splot sin(x)*sin(y)};

There are some more options to control the GNUPLOT interaction. For more details see SE question: PGFplots and GNUplot with addplot3, an MWE with 9 lines and pay attention to the comments from Christian Feuersänger.
Bottom line:
TikZ cannot currently understand GNUPLOT 3D plots without additional packages.


text:
Q: Creating a duplicate SQL Server database on the same Amazon RDS Background: I'm moving some clients to an AWS RDS SQL server instance. Each has two databases: one for their live data, and one for training data, which is a copy of their live data. The training database is kept up to date by routinely restoring it using the live database. Ideally these databases would be hosted on the same RDS instance, since they aren't that big and it would halve the cost of hosting.
The problem: Amazon has these limitations in their documentation:

You can't restore a backup file to the same DB instance that was used
  to create the backup file. Instead, restore the backup file to a new
  DB instance. Renaming the database is not a workaround for this
  limitation.
You can't restore the same backup file to a DB instance multiple
  times. That is, you can't restore a backup file to a DB instance that
  already contains the database that you are restoring. Renaming the
  database is not a workaround for this limitation.

So backing up the live database and restoring it to the training database as I normally would is out. Other than hosting two separate instances per client, what's my best option here?

A: Great News:
The limitation listed previously in the RDS Documentation has been removed:

You can't restore a backup file to the same DB instance that was used to create the backup file. Instead, restore the backup file to a new DB instance. Renaming the database is not a workaround for this limitation.
You can't restore the same backup file to a DB instance multiple
  times. That is, you can't restore a backup file to a DB instance that
  already contains the database that you are restoring. Renaming the
  database is not a workaround for this limitation.

I have just tested this, and have been able to restore the same backup multiple times to different database names on the same RDS SQL Server without issue, using the msdb.dbo.rds_restore_database stored procedure as defined within the linked documentation.

A: While possible to generate a script for a database, import it elsewhere, back it up and restore it back on the original instance, it wasn't a great workaround in my case. I've had to give up on using an RDS instance and go down the more traditional route of hosting multiple training databases on a Windows EC2 instance.


text:
Q: How to use gesture on specific place of screen in android I am wondering how to check if the user is performing gesture on our predefined area. I have an criteria and that is , let suppose , If I have a transparent graphics of word "B" on the screen , then user should start filling it with color with gesture (with the touch of his finger). he starts it with the below corner of the B and end up how we write the b when writing with the pencil.
So how to achieve this type of gesture and how to just restrict user to use the gesture on on that part of the screen ? please any idea about it or share me any thing which is similar to it.


text:
Q: Only moving DOWN when plays 2048 automatically with Selenium I am trying to play 2048 automatically with Selenium as directed in Automate the Boring Stuff.
But every move is DOWN no matter what argument I send to send_keys().
Here is the code:
from selenium.webdriver.common.keys import Keys
from selenium import webdriver
import time, requests

browser.get('https://play2048.co/')

time.sleep(2)

game = browser.find_element_by_tag_name('body')
over = browser.find_element_by_class_name('retry-button')
control = ['Keys.UP','Keys.RIGHT','Keys.DOWN','Keys.LEFT']

act = 0

while True:
     if over.is_displayed() is False:
         if act == 4:
             act = 0
         game.send_keys(control[act])
         print('act=' + str(act) + ' control =' + control[act])  # To check every move output.
         act += 1
         time.sleep(0.1)

     else:
          print('Done')
          time.sleep(2)
          over.click()

The argument sent to game.send_keys() is different for every move (UP > RIGHT > DOWN > LEFT > UP).
But the actual results in the game is always moving DOWN each time.
After several attempts, I changed the "control" dict to:
control = ['\ue013','\ue014','\ue015','\ue012']

And the problem solved...
I am just wondering what leads the problem, and why it always moving DOWN as arguments are all different.
Thanks, guys.
--------------------------------- Edit ---------------------------------
The problem here is I send strings, not keys, to send_keys() as Iain Shelvington (Thanks mate) answered.
And why the game is always moving down?
Because 2048 could also be controlled via W,D,S,A instead of UP, LEFT, DOWN, and RIGHT, so the game will receive commands from the string 'Keys.UP' letter by letter.
'K', 'e', and 'y' means nothing to the game, but 's' will make the blocks go DOWN.
Therefore all the strings start with 'Keys.' will direct the game to go DOWN.


text:
Q: Mview Refresh error while doing Force refresh We have 4 Mviews which uses Force refresh method to get refreshed every day using our control-M jobs after loading new data in the base table (The Mview logs created on the base tables).
In our Current Production DB (11g), Non-Production it is working fine and these is issue while refreshing these views.
Now we are moving our DB to oracle 12c and as part of migration we are importing all the objects from current 11g to new 12c DB.
So now when we run our control-M jobs to load new data in base tables and after that force refresh these mviews they got failed with ORA-12008: error in materialized view refresh path
ORA-00923: FROM keyword not found where expected
I tried running the query used in Mview and they work fine(on new 12c DB) as excepted and did not give any error I tried gather stat and tried refreshing after that but still error persist to refresh, we tried dropping the MVIEWS and Recreating them as well but same error persist, use CTAS with MVIEW select query and table got created without error with data in it.
Below are supporting DDL of one of the Mview --
CREATE MATERIALIZED VIEW HEW.MV_EUC_MVT_ADM_MULTI
    (NUMCOM,ACCOUNT,BANK_CODE,PRODUCT,CUST_TYPE,
     SOURCE,CI,DEVISE,"DATE TRT",DATE_CBL,
     ORIGINE,MONTANT,MONTANT_CVEUR,SENS,ENTITE,
     AFFILIATE,BOOK_CODE,BU,MAFF,J_SOURCE,
     PM)
NOCACHE
LOGGING
NOCOMPRESS
BUILD IMMEDIATE
REFRESH FORCE ON DEMAND
WITH PRIMARY KEY
AS
/* Formatted on 7/5/2021 1:03:02 PM (QP5 v5.277) */
SELECT    SUBSTR ('00000000000' || MVT.ACCOUNT,
                  LENGTH ('00000000000' || MVT.ACCOUNT) - 10,
                  11)
       || SUBSTR ('000000' || MVT.PRODUCT,
                  LENGTH ('000000' || MVT.PRODUCT) - 5,
                  6)
       || SUBSTR ('0000000000' || MVT.CHARTFIELD2,
                  LENGTH ('0000000000' || MVT.CHARTFIELD2) - 9,
                  10)
       || SUBSTR ('0000000000' || MVT.CHARTFIELD1,
                  LENGTH ('0000000000' || MVT.CHARTFIELD1) - 9,
                  10)
          AS NUMCOM,
       MVT.ACCOUNT,
       MVT.BANK_CODE AS BANK_CODE,
       NVL (MVT.PRODUCT, '0') AS PRODUCT,
       NVL (MVT.CHARTFIELD2, '0') AS CUST_TYPE,
       NVL (MVT.CHARTFIELD1, '0') AS SOURCE,
       SUBSTR (MVT.DEPTID, 6, 5) AS CI,
       MVT.FOREIGN_CURRENCY AS DEVISE              --,MVT.Z_DT_TRT AS DATE_TRT
                                     ,
       MVT.DATE_SITU AS "DATE TRT",
       MVT.JOURNAL_DATE AS DATE_CBL,
       MVT.Z_CD_ORIGINE AS ORIGINE,
       MVT.FOREIGN_AMOUNT AS MONTANT,
       MVT.MONETARY_AMOUNT AS MONTANT_CVEUR,
       DECODE (SIGN (MVT.FOREIGN_AMOUNT), 1, 'C', 'D') AS SENS,
       SUBSTR (MVT.DEPTID, 8, 3) AS ENTITE,
       NVL (MVT.AFFILIATE, '00000') AS AFFILIATE,
       MVT.BOOK_CODE AS BOOK_CODE,
       MVT.BUSINESS_UNIT_GL AS BU,
          MVT.FISCAL_YEAR
       || TO_CHAR (TO_DATE (MVT.ACCOUNTING_PERIOD, 'MM'), 'MM')
          AS MAFF,
       MVT.SOURCE AS J_SOURCE,
       DBMS_MVIEW.pmarker (mvt.ROWID) AS pm
  FROM CRAFT_MVT_MULTI_H MVT, CRAFT_PARAM_DATE DT
 WHERE     (   (    MVT.FISCAL_YEAR = DT.fiscyear_lastday_mon_1
                AND ACCOUNTING_PERIOD = DT.accper_lastday_mon_1)
            OR (    MVT.FISCAL_YEAR = DT.fiscyear_yesterday
                AND ACCOUNTING_PERIOD = DT.accper_yesterday))
       AND (   (    (MVT.ACCOUNT LIKE '4%' OR MVT.ACCOUNT LIKE '5%')
                AND MVT.FOREIGN_CURRENCY <> 'EUR'
                AND (MVT.Z_CD_ORIGINE <> '716' OR MVT.Z_CD_ORIGINE IS NULL))
            OR (MVT.ACCOUNT = '4083513001' AND MVT.FOREIGN_CURRENCY = 'EUR')
            OR (MVT.ACCOUNT = '2059630001'))
       AND MVT.DATE_SITU > DT.lastday_month_2;

CREATE MATERIALIZED VIEW LOG ON HEW.CRAFT_MVT_MULTI_H
NOCACHE
LOGGING
WITH ROWID
EXCLUDING NEW VALUES;

CREATE MATERIALIZED VIEW LOG ON HEW.CRAFT_PARAM_DATE
NOCACHE
LOGGING
WITH ROWID
EXCLUDING NEW VALUES;

Error --
ORA-12008: error in materialized view refresh path

ORA-00923: FROM keyword not found where expected
Detailed Error Message :

ORA-06512: at "SYS.DBMS_SNAPSHOT", line 2821

ORA-06512: at "SYS.DBMS_SNAPSHOT", line 3058

ORA-06512: at "SYS.DBMS_SNAPSHOT", line 3017

Please note that this Mview is getting force refreshed daily without error on our current 11g DB.
Also one thing that I have noticed that just after the migration we run a DROP, Create script for all Mviews with Grants and all other things and after that when i do a force refresh on these Mview then they got refreshed but next day when we load new data in the base table and refresh these mviews only then they start throwing error so here i am assuming that the it gives error when we insert data in base tables !!
New 12c DB version --
Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit Production

Current working 11g DB version --
Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production

Please let me know you need more information I will try to arrange it.

A: Oracle does not use the query in the MVIEW definition to perform the refresh. It builds the refresh query dynamically using its own internal rules to leverage MVIEW Logs and other database features. There is a syntax error in the constructed refresh query, indicated by the ORA-00923 error: that is why you are able to initially create the MVIEW but refreshes are failing.
This is not something that you can correct directly. The recommended course of action as given in the Master Note for MVIEW 'ORA-' error diagnosis. For Materialized View CREATE or REFRESH is to open a Service Request with Oracle Support.


text:
Q: How to use a keypress event in AngularJS? I want to catch the enter key press event on the textbox below. To make it more clear I am using a ng-repeat to populate the tbody. Here is the HTML:
<input type="number" id="closeqty{{$index}}" class="pagination-right closefield"
    data-ng-model="closeqtymodel" data-ng-change="change($index)" required placeholder="{{item.closeMeasure}}" />

This is my module:
angular.module('components', ['ngResource']);

I am using a resource to populate the table and my controller code is:
function Ajaxy($scope, $resource) {
//controller which has resource to populate the table
}

A: You need to add a directive, like this:
Javascript:
app.directive('myEnter', function () {
    return function (scope, element, attrs) {
        element.bind("keydown keypress", function (event) {
            if(event.which === 13) {
                scope.$apply(function (){
                    scope.$eval(attrs.myEnter);
                });

                event.preventDefault();
            }
        });
    };
});

HTML:

    <input type="text" my-enter="doSomething()">

A: html
<textarea id="messageTxt"
    rows="5"
    placeholder="Escriba su mensaje"
    ng-keypress="keyPressed($event)"
    ng-model="smsData.mensaje">
</textarea>

controller.js
$scope.keyPressed = function (keyEvent) {
    if (keyEvent.keyCode == 13) {
        alert('presiono enter');
        console.log('presiono enter');
    }
};

A: You can also apply it to a controller on a parent element. This example can be used to highlight a row in a table by pressing up/down arrow keys.
app.controller('tableCtrl', [ '$scope', '$element', function($scope, $element) {
  $scope.index = 0; // row index
  $scope.data = []; // array of items
  $scope.keypress = function(offset) {
    console.log('keypress', offset);
    var i = $scope.index + offset;
    if (i < 0) { i = $scope.data.length - 1; }
    if (i >= $scope.data.length) { i = 0; }
  };
  $element.bind("keydown keypress", function (event) {
    console.log('keypress', event, event.which);
    if(event.which === 38) { // up
      $scope.keypress(-1);
    } else if (event.which === 40) { // down
      $scope.keypress(1);
    } else {
      return;
    }
    event.preventDefault();
  });
}]);

        {{key}}

        {{value}}

A: An alternative is to use standard directive ng-keypress="myFunct($event)"
Then in your controller you can have:
...

$scope.myFunct = function(keyEvent) {
  if (keyEvent.which === 13)
    alert('I am an alert');
}

...

A: Trying
ng-keypress="console.log($event)"
ng-keypress="alert(123)"

did nothing for me.
Strangley the sample at https://docs.angularjs.org/api/ng/directive/ngKeypress, which does ng-keypress="count = count + 1", works.
I found an alternate solution, which has pressing Enter invoke the button's ng-click.
<input ng-model="..." onkeypress="if (event.which==13) document.getElementById('button').click()"/>
<button id="button" ng-click="doSomething()">Done</button>

A: <!DOCTYPE html>

Informe your name:<input type="text" ng-model="pergunta" ng-keypress="pressionou_enter($event)" ></input>
<button ng-click="chamar()">submit</button>

{{resposta}}

A: This is an extension on the answer from EpokK.
I had the same problem of having to call a scope function when enter is pushed on an input field. However I also wanted to pass the value of the input field to the function specified. This is my solution:
app.directive('ltaEnter', function () {
return function (scope, element, attrs) {
    element.bind("keydown keypress", function (event) {
        if(event.which === 13) {
          // Create closure with proper command
          var fn = function(command) {
            var cmd = command;
            return function() {
              scope.$eval(cmd);
            };
          }(attrs.ltaEnter.replace('()', '("'+ event.target.value +'")' ));

          // Apply function
          scope.$apply(fn);

          event.preventDefault();
        }
    });
};

});
The use in HTML is as follows:
<input type="text" name="itemname" lta-enter="add()" placeholder="Add item"/>

Kudos to EpokK for his answer.

A: Here is what I figured out when I was building an app with a similar requirement,
it doesn't require writing a directive and it's relatively simple to tell what it does:
<input type="text" ng-keypress="($event.charCode==13)?myFunction():return" placeholder="Will Submit on Enter">

A: My simplest approach using just angular build-in directive:
ng-keypress, ng-keydown or ng-keyup.
Usually, we want add keyboard support for something that already handled by ng-click.
for instance:
action

Now, let's add keyboard support.
trigger by enter key:
action

by space key:
action

by space or enter key:
action

if you are in modern browser
action

More about keyCode:
keyCode is deprecated but well supported API, you could use $evevt.key in supported browser instead.
See more in https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key

A: You can use ng-keydown
="myFunction($event)" as attribute.
<input ng-keydown="myFunction($event)" type="number">

myFunction(event) {
    if(event.keyCode == 13) {   // '13' is the key code for enter
        // do what you want to do when 'enter' is pressed :)
    }
}

A: Another simple alternative:
<input ng-model="edItem" type="text"
    ng-keypress="($event.which === 13)?foo(edItem):0"/>

And the ng-ui alternative:
<input ng-model="edItem" type="text" ui-keypress="{'enter':'foo(edItem)'}"/>

A: What about this?:
<form ng-submit="chat.sendMessage()">
    <input type="text" />
    <button type="submit">
</form>

Now when you push enter key after write something in your input, the form know how to handle it.

A: Some example of code that I did for my project.
Basically you add tags to your entity.
Imagine you have input text, on entering Tag name you get drop-down menu with preloaded tags to choose from, you navigate with arrows and select with Enter:
HTML +  AngularJS v1.2.0-rc.3

        <form ng-submit="addTag(newTag)">
            <input id="newTag" ng-model="newTag" type="text" class="form-control" placeholder="Enter new tag"
                   style="padding-left: 10px; width: 700px; height: 33px; margin-top: 10px; margin-bottom: 3px;" autofocus
                   data-toggle="dropdown"
                   ng-change="preloadTags()"
                   ng-keydown="navigateTags($event)">

 0">

                            {{ preloadedTag.label }}

        </form>

Controller.js
$scope.preloadTags = function () {
    var newTag = $scope.newTag;
    if (newTag && newTag.trim()) {
        newTag = newTag.trim().toLowerCase();

        $http(
            {
                method: 'GET',
                url: 'api/tag/gettags',
                dataType: 'json',
                contentType: 'application/json',
                mimeType: 'application/json',
                params: {'term': newTag}
            }
        )
            .success(function (result) {
                $scope.preloadedTags = result;
                $scope.preloadedTagsIndex = -1;
            }
        )
            .error(function (data, status, headers, config) {
            }
        );
    } else {
        $scope.preloadedTags = {};
        $scope.preloadedTagsIndex = -1;
    }
};

function checkIndex(index) {
    if (index > $scope.preloadedTags.length - 1) {
        return 0;
    }
    if (index < 0) {
        return $scope.preloadedTags.length - 1;
    }
    return index;
}

function removeAllActiveTags() {
    for (var x = 0; x < $scope.preloadedTags.length; x++) {
        if ($scope.preloadedTags[x].activeTag) {
            $scope.preloadedTags[x].activeTag = false;
        }
    }
}

$scope.navigateTags = function ($event) {
    if (!$scope.newTag || $scope.preloadedTags.length == 0) {
        return;
    }
    if ($event.keyCode == 40) {  // down
        removeAllActiveTags();
        $scope.preloadedTagsIndex = checkIndex($scope.preloadedTagsIndex + 1);
        $scope.preloadedTags[$scope.preloadedTagsIndex].activeTag = true;
    } else if ($event.keyCode == 38) {  // up
        removeAllActiveTags();
        $scope.preloadedTagsIndex = checkIndex($scope.preloadedTagsIndex - 1);
        $scope.preloadedTags[$scope.preloadedTagsIndex].activeTag = true;
    } else if ($event.keyCode == 13) {  // enter
        removeAllActiveTags();
        $scope.selectTag($scope.preloadedTags[$scope.preloadedTagsIndex]);
    }
};

$scope.selectTag = function (preloadedTag) {
    $scope.addTag(preloadedTag.label);
};

CSS + Bootstrap v2.3.2
.preloadedTagPanel {
    background-color: #FFFFFF;
    display: block;
    min-width: 250px;
    max-width: 700px;
    border: 1px solid #666666;
    padding-top: 0;
    border-radius: 0;
}

.preloadedTagItemPanel {
    background-color: #FFFFFF;
    border-bottom: 1px solid #666666;
    cursor: pointer;
}

.preloadedTagItemPanel:hover {
    background-color: #666666;
}

.preloadedTagItemPanelActive {
    background-color: #666666;
}

.preloadedTagItem {
    display: inline-block;
    text-decoration: none;
    margin-left: 5px;
    margin-right: 5px;
    padding-top: 5px;
    padding-bottom: 5px;
    padding-left: 20px;
    padding-right: 10px;
    color: #666666 !important;
    font-size: 11px;
}

.preloadedTagItem:hover {
    background-color: #666666;
}

.preloadedTagItemActive {
    background-color: #666666;
    color: #FFFFFF !important;
}

.dropdown .preloadedTagItemPanel:last-child {
    border-bottom: 0;
}

A: I'm a bit late .. but i found a simpler solution using auto-focus .. This could be useful for buttons or other when popping a dialog :
<button auto-focus ng-click="func()">ok</button>
That should be fine if you want to press the button onSpace or Enter clicks .

A: here's my directive:
mainApp.directive('number', function () {
    return {
        link: function (scope, el, attr) {
            el.bind("keydown keypress", function (event) {
                //ignore all characters that are not numbers, except backspace, delete, left arrow and right arrow
                if ((event.keyCode < 48 || event.keyCode > 57) && event.keyCode != 8 && event.keyCode != 46 && event.keyCode != 37 && event.keyCode != 39) {
                    event.preventDefault();
                }
            });
        }
    };
});

usage:
<input number />

A: you can use ng-keydown , ng-keyup , ng-press such as this .

to triger a function :

   <input type="text" ng-keypress="function()"/>

or if you have one condion such as when he press escape (27 is the key
  code for escape)

 <form ng-keydown=" event.which=== 27?cancelSplit():0">
....
</form>

A: I think using document.bind is a bit more elegant
constructor($scope, $document) {
  var that = this;
  $document.bind("keydown", function(event) {
    $scope.$apply(function(){
      that.handleKeyDown(event);
    });
  });
}

To get document to the controller constructor:
controller: ['$scope', '$document', MyCtrl]

A: (function(angular) {
  'use strict';
angular.module('dragModule', [])
  .directive('myDraggable', ['$document', function($document) {
    return {
      link: function(scope, element, attr) {
         element.bind("keydown keypress", function (event) {
           console.log('keydown keypress', event.which);
            if(event.which === 13) {
                event.preventDefault();
            }
        });
      }
    };
  }]);
})(window.angular);

A: All you need to do to get the event is the following:
console.log(angular.element(event.which));

A directive can do it, but that is not how you do it.


text:
Q: C#: How to Serialize RenderFragment (Razor template)? Im working on a Blazor Wasm Hosted (client and server) project to render dynamic razor components loaded from dlls. I tried to send the components to the client via SignalR but failed because of System.Type. That is why I decided to create the render tree RenderFragment from dynamic component at the server-side instead, then serialize and send it to the client to render the component in razor page. But I get an error when serializing RenderFragment. How to fix this error?
The function below creates the render tree from IDynamicComponent to RenderFragment, then serializes it to string which produces the error. After that It sends the string to the client via SignalR.
public async Task GetPlugin()
{
    try
    {
        // Build the render tree of the component
        RenderFragment renderFragment = builder => {

            // Gets the component by name
            IDynamicComponent component = ComponentService.GetComponentByName("Counter");

            builder.OpenComponent(0, component.Component);

            for (int i = 0; i < component.Parameters.Count; i++)
            {
                var attribute = component.Parameters.ElementAt(i);
                builder.AddAttribute(i + 1, attribute.Key, attribute.Value);
            }
        };

        // Serialize the renderfragment to string
        string componentFragment = JsonConvert.SerializeObject(renderFragment); // Error occurs here

        // Send to client
        await myHub.Clients.All.SendAsync("Plugin", componentFragment);
    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex.Message);
    }
}

Error Output:
This error occurs when serializing the RenderFragment
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
 ---> System.PlatformNotSupportedException: This instance contains state that cannot be serialized and deserialized on this platform.
   at System.Security.Claims.ClaimsPrincipal.OnSerializingMethod(StreamingContext context)

Additional Information
The components are created using the IDynamicComponent Interface below:
public interface IDynamicComponent
{
    IDictionary<Type,Type> InjectableDependencies { get; }
    IDictionary<string,string> Parameters { get; }
    string Name { get; }
    Type Component { get;}
}

Component Example (Razor Class Library)
MyComponent.cs
public class MyComponent : IDynamicComponent
{
    public IDictionary<Type, Type> InjectableDependencies => new Dictionary<Type, Type>();
    public IDictionary<string, string> Parameters => new Dictionary<string, string>();
    public string Name => "Example1";
    public Type Component => typeof(Component1);  // Component1.razor

}

Component1.razor

Counter

Current count: @currentCount

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
    private int currentCount = 0;
    private void IncrementCount()
    {
        currentCount++;
    }
}


text:
Q: Sum up set of values based in a column and collapse rows based on conditions in bigquery I have a query for transforming a table in Bigquery. I have a table where I need to sum up certain rows based on specific conditions in two columns.

I need to collapse rows where I have Occ= S1 and MT = English for a unique combination across code,UR and gen. pct values should sum up to a single row as follows -

A: Below is for BigQuery Standard SQL
#standardSQL
SELECT code, UR, gen, Occ, MT, SUM(pct) AS pct
FROM (
  SELECT * REPLACE(IF(collapse, 'S1', Occ) AS Occ, IF(collapse, 'English', MT) AS MT)
  FROM (
    SELECT *,
      COUNTIF(Occ = 'S1' AND MT = 'English') OVER(PARTITION BY code, UR, gen) > 0 AS collapse
    FROM `project.dataset.table`
  )
)
GROUP BY code, UR, gen, Occ, MT

if to apply to sample data from your question - result is
Row code    UR      gen Occ MT      pct
1   128     Rural   F   D2  Ao      0.77
2   128     Rural   F   D3  Ao      0.38
3   128     Rural   M   D4  Ao      0.89
4   128     Rural   M   D5  Ao      0.02
5   128     Urban   F   S1  English 0.63
6   128     Urban   M   S1  English 0.63

A: If I understand correctly, you can use aggregation with some conditional logic:
select code, ur, gen,
       coalesce((case when cnt_s1 is null then occ end), 'S1') as occ,
       mt,
       sum(pct) as pct
from (select t.*,
             countif( occ = 'S1' ) over (partition by code, ur, gen, mt) as cnt_s1
      from t
     ) t
group by code, ur, gen, occ, mt;


text:
Q: AngularFireStore return collection with subquery I have the following function
getParticipations(
    meetingId: string
  ): Observable<Participation[]> {
    return this.meetingCollection
      .doc(meetingId)
      .collection<ParticipationDto>('participations')
      .snapshotChanges()
      .pipe(
        map(actions =>
          actions.map(m => {
            const participationDto = m.payload.doc.data() as ParticipationDto;
            const id = m.payload.doc.id;
            return new Participation(id, participationDto.vart, null);
          })
        )
      );
  }

In the participationDto there is a document reference and I would like to get that document in order to return an object (participation) with a mapping of the referenced document.
Something like
  getParticipations(
    meetingId: string
  ): Observable<Participation[]> {
    return this.meetingCollection
      .doc(meetingId)
      .collection<ParticipationDto>('participations')
      .snapshotChanges()
      .pipe(
        map(actions =>
          actions.map(m => {
            const participationDto = m.payload.doc.data() as ParticipationDto;
            const id = m.payload.doc.id;
            return this.participantCollection.doc(participationDto.participant.id).get().pipe(
              map(pp => {
                return new Participation(id, participationDto.vart, pp.data() as Participant);
              })
            );
          })
        )
      );
  }

But then it returns an Observable<Observable<Participation>[]>
I probably need to merge, map or something like that but I don't find the right way to get my Observable enriched with my object mapping and keep my Observable<Participation[]>
Thanks for help

A: You could try using forkJoin on the inner list of Observables and switching the outer map to a switchMap.
     getParticipations(
    meetingId: string
  ): Observable<Participation[]> {
    return this.meetingCollection
      .doc(meetingId)
      .collection<ParticipationDto>('participations')
      .snapshotChanges()
      .pipe(
        switchMap(actions =>
          forkJoin(actions.map(m => {
            const participationDto = m.payload.doc.data() as ParticipationDto;
            const id = m.payload.doc.id;
            return this.participantCollection.doc(participationDto.participant.id).get().pipe(
              map(pp => {
                return new Participation(id, participationDto.vart, pp.data() as Participant);
              })
            ));
          })
        )
      );
  }

A: You need to use mergeMap instead of map
something like below
getParticipations(
    meetingId: string
  ): Observable<Participation[]> {
    return this.meetingCollection
      .doc(meetingId)
      .collection<ParticipationDto>('participations')
      .snapshotChanges()
      .pipe(
        mergeMap(actions =>
          actions.map(m => {
            const participationDto = m.payload.doc.data() as ParticipationDto;
            const id = m.payload.doc.id;
            return this.participantCollection.doc(participationDto.participant.id).get().pipe(
              map(pp => {
                return new Participation(id, participationDto.vart, pp.data() as Participant);
              })
            );
          })
        )
      );
  }

getParticipations(
    meetingId: string
  ): Observable<Participation[]> {
    return this.meetingCollection
      .doc(meetingId)
      .collection<ParticipationDto>('participations')
      .snapshotChanges()
      .pipe(
        map(actions =>
          actions.map(m => {
            const participationDto = m.payload.doc.data() as ParticipationDto;
            const id = m.payload.doc.id;
            return this.participantCollection.doc(participationDto.participant.id).get().pipe(
              mergeMap(pp => {
                return new Participation(id, participationDto.vart, pp.data() as Participant);
              })
            );
          })
        )
      );
  }

(since it's complicated and nested and no stackblitz provided, I am not able to verify the solution, however if it doesn't work let me know to delete this answer)


text:
Q: How To Dynamically Request Access Token Using Passport And Laravel I am working with a multi-tenant setup and I am looking for a way that when I attempt to request access tokens I can send the request to the correct login end point.
For instance in a single tenant set up when I make a request for a access_token it would look something like this
$http = new \GuzzleHttp\Client;

    try {
        $response = $http->post('http://mydomain.test/oauth/token', [
            'form_params' => [
                'grant_type' => 'password',
                'client_id' => env('CLIENT_ID'),
                'client_secret' => env('CLIENT_SECRET'),
                'username' => $request->username,
                'password' => $request->password,
                ]
                ]);

                return response()->getBody();
            }

Now what I am trying to do is make the login end point $http->post(my url) to change depending on the tenant user making the request.
So currently when I make a post request to the login controller I have the route wrapped in a middle ware like this
Route::group(['middleware' => 'tenancy.enforce'], function () {
    Route::post('/login', 'PassportTokenController@login');
});

and then in my controller I can call the client secret and the fqdn based on the tenant requesting the information
So when I ask for the fqdn of the request being made and the client_secret from the database of the tenant I will get the correct data
$passport = DB::table('oauth_clients')->where('id', 2)->first();

$hostname  = app(\Hyn\Tenancy\Environment::class)->hostname();

now if I insert these variables into the login method I will get an 500 internal server error
public function login(Request $request)
    {
        $passport = DB::table('oauth_clients')->where('id', 2)->first();

        $hostname  = app(\Hyn\Tenancy\Environment::class)->hostname();

        $http = new \GuzzleHttp\Client;

        try {
            $response = $http->post('http://' . $hostname->fqdn . '/oauth/token', [
                'form_params' => [
                    'grant_type' => 'password',
                    'client_id' => 2,
                    'client_secret' => $passport->secret,
                    'username' => $request->username,
                    'password' => $request->password,
                    ]
                    ]);

                    return response()->getBody();
                } catch (\GuzzleHttp\Exception\BadResponseException $e) {
                    if ($e->getCode() === 400) {
                        return response()->json('Invalid Request. Please enter a username or a password.', $e->getCode());
                    } else if ($e->getCode() === 401) {
                        return response()->json('Your credentials are incorrect. Please try again', $e->getCode());
            }
            return response()->json('Something went wrong on the server.', $e->getCode());
        }

    }

Notice the $http->post(my url) changes depending on the tenant user making the request.
Is there something with passport I should be doing so that I can dynamically make the request for the oauth access token?
*Update so after figuring out how to get an actual server error response I am noticing that the Guzzle http is trying to query the system database instead of the tenant database
Base table or view not found: 1146 Table 'multitenant-diy.oauth_clients' doesn't exist (SQL: select * f (truncated...)
 in C:\laragon\www\multitenant-diy\vendor\guzzlehttp\guzzle\src\Exception\RequestException.php:113


text:
Q: Was Saruman a landlord, a robber baron or something? In The Return of the King (extended edition) there is a line where Gandalf? explains that Saruman claimed Rohan as his own. It sounded like a robber barons who used force and violence to claim ownership of the English forests / lands from the natives.
Was this a reference to the enclosure movement in English history? Is there more information on this from the book on this or was it a line made for the film?

A: It's not really a comparable situation. Saruman de jure held Isengard in fief to the Steward of Gondor, though he had long since made the surrounding area, Nan Curunír, de facto an independent jurisdiction. His attack on Rohan was a straightforward invasion of a foreign country. He was in no sense a landlord: he had no legal authority over Rohan, or even a pretence thereof.
There's no real similarity to the enclosure of the commons or the highland clearances in Scotland, either, which were measures imposed by the nobility on the peasantry of their own country.

A reminder that fiefdom can be complicated. Henry III was at one time Duke of Aquitaine (in fief to the king of France), Lord of Ireland (in fief to the Pope), and King of England (in his own right, answering to nobody). Saruman was an emissary of the Valar, and that was his primary role, but in his position at Isengard he was acting as a lieutenant of the Steward of Gondor.


text:
Q: remote svn up won't finish I ssh to the remote application server where I need to do svn up. That is one amongst few servers. Should have the same set up as all other ones where svn up works.

*

*ssh to the server

*su wwwrun finishes ok

*svn info gives me

URL: svn+ssh://svnuser@repository.server.com.au/var/lib/svn/edu2/tags/4.1.0

*

*svn st runs ok too.

*ssh svnuser@repository.server.com.au logs me in without asking for password.

*svn up will never finish

If I log into repository server using another session and do ps aux |grep svn I can see that  process svnserve -t under svnuser is running. If I do ctrl+c in the session where I started svn up I get ^Csvn: Caught signal and the process svnserve -t on repository server will finish.
When I try svn up on few other application servers that (should) have the same set up everything works fine. The ssh to the server in question is slow but svn up worked on even slower connections.
Any idea how to fix that or debug what is going on?


text:
Q: XCode/LLDB: Can LLDB break on the calling function? I'm setting a symbolic breakpoint on -[CALayer setSpeed:], and I'd like the breakpoint to only be triggered when the function is called by a specific function
-[UIPercentDrivenInteractiveTransition _updateInteractiveTransition:percent:isFinished:didComplete:]
Is there a way to do this?
I can see the value of the calling function manually, by doing bt 2. Is there perhaps some way to perform a string comparison with this output in a breakpoint conditional?
Thanks!

A: You can do this with a bit of python scripting on the breakpoint.  It means that lldb will stop the process every time the breakpoint is hit and resume it -- for a really hot function like objc_msgSend, this will impact performance dramatically.
Create a python function in your homedir like ~/lldb/stopifcaller.py with these contents
import lldb
def stop_if_caller(current_frame, function_of_interest):
  thread = current_frame.GetThread()
  if thread.GetNumFrames() > 1:
    if thread.GetFrameAtIndex(1).GetFunctionName() != function_of_interest:
      thread.GetProcess().Continue()

Then put
command script import ~/lldb/stopifcaller.py

in your ~/.lldbinit file.
Use it like this in lldb:
(lldb) br s -n bar
Breakpoint 1: where = a.out`bar + 15 at a.c:5, address = 0x0000000100000e7f
(lldb) br comm add --script-type python -o "stopifcaller.stop_if_caller(frame, 'foo')" 1

and you're done - breakpoint 1 (on bar()) will only stop if the caller frame is foo().  Or to put it another way, it will continue if the caller frame is not foo().


text:
Q: Accessing Keyboard API I am looking to intercept keyboard events in a Mac app.
I would like the user to initiate a "record" activity which will copy the keystones and then a "stop" activity.
Is that possible via Cocoa's Mac API?

A: Have a look at the NSEvent method addLocalMonitorForEventsMatchingMask:handler:. This will allow you to receive events (specifically keyDown events in your case) that occur in your app, and you can then do whatever you want with the keystrokes that the method returns. Here is a simple example of how to use that method:
self.keystrokes = [NSMutableString string];
    [NSEvent addLocalMonitorForEventsMatchingMask:NSKeyDownMask handler:^NSEvent* (NSEvent* event){
        NSString *keyPressed = event.charactersIgnoringModifiers;
        [self.keystrokes appendString:keyPressed];
        return event;
    }];

A: To intercept all keyboard input (and also mouse if you want it) check out the Quartz Events API. This post has some code demonstrating usage of the API.


text:
Q: Filtering one column on an array of values without using UNION I'm trying to create an arbitrary UNION ALL SQL query using SQL code.
Currently, I have these table descriptions.

enter image description here

For a given app_id value, I am trying to get all its description ids. Then for each of these description ids, I am trying to get the category ids and then the category names to list them out.
I could easily generate SQL code using PHP, but that seems like cheating.

A: You can join those four table using their foreign key relationship and then get the required result set you don't need a loop for this
SELECT a.id as app_id,c.cat_name as category_name
  FROM apps a inner join app_permission ap
   on ap.app_id=a.id inner join description d
   on d.desc_id=ap.desc_id inner join categories c
   on c.cat_id=d.cat_id where a.id=$appid;


text:
Q: .Net Zip Up files Whats the best way to zip up files using C#? Ideally I want to be able to seperate files into a single archive.

A: This is now built into the framework if you have version 4.5+
Otherwise, use Ionic.
Namespace is System.IO.Packaging.ZIPPackage.
See http://visualstudiomagazine.com/articles/2012/05/21/net-framework-gets-zip.aspx for a story.

A: Have you looked at SharpZipLib?
I believe you can build zip files with classes in the System.IO.Packaging namespace - but every time I've tried to look into it, I've found it rather confusing...

A: Take a look at this library:
http://www.icsharpcode.net/OpenSource/SharpZipLib/
It is pretty comprehensive, it deals with many formats, is open-source, and you can use in closed-source commercial applications.
It is very simple to use:
byte[] data1 = new byte[...];
byte[] data2 = new byte[...];
/*...*/

var path = @"c:\test.zip";
var zip = new ZipOutputStream(new FileStream(path, FileMode.Create))
            {
                IsStreamOwner = true
            }

zip.PutNextEntry("File1.txt");
zip.Write(data1, 0, data1.Length);

zip.PutNextEntry("File2.txt");
zip.Write(data2, 0, data2.Length);

zip.Close();
zip.Dispose();

A: There are a few librarys around - the most popular of which are DotNetZip and SharpZipLib.

A: You can use DotNetZip to archieve this. It´s free to use in any application.
Here´s some sample code:
   try
   {
     // for easy disposal
     using (ZipFile zip = new ZipFile())
     {
       // add this map file into the "images" directory in the zip archive
       zip.AddFile("c:\\images\\personal\\7440-N49th.png", "images");
       // add the report into a different directory in the archive
       zip.AddFile("c:\\Reports\\2008-Regional-Sales-Report.pdf", "files");
       zip.AddFile("ReadMe.txt");
       zip.Save("MyZipFile.zip");
     }
   }
   catch (System.Exception ex1)
   {
     System.Console.Error.WriteLine("exception: " + ex1);
   }

A: Hi i created two methods with the ShapLib library (you can download it here http://www.icsharpcode.net/opensource/sharpziplib/) that would like to share, they are very easy to use just pass source and target path (fullpath including folder/file and extension). Hope it help you!
//ALLYOURNAMESPACESHERE
using ...

//SHARPLIB
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;

public static class FileUtils
{

    /// <summary>
    ///
    /// </summary>
    /// <param name="sourcePath"></param>
    /// <param name="targetPath"></param>
    public static void ZipFile(string sourcePath, string targetPath)
    {
        string tempZipFilePath = targetPath;
        using (FileStream tempFileStream = File.Create(tempZipFilePath, 1024))
        {
            using (ZipOutputStream zipOutput = new ZipOutputStream(tempFileStream))
            {
                // Zip with highest compression.
                zipOutput.SetLevel(9);
                DirectoryInfo directory = new DirectoryInfo(sourcePath);
                foreach (System.IO.FileInfo file in directory.GetFiles())
                {

                    // Get local path and create stream to it.
                    String localFilename = file.FullName;
                    //ignore directories or folders
                    //ignore Thumbs.db file since this probably will throw an exception
                    //another process could be using it. e.g: Explorer.exe windows process
                    if (!file.Name.Contains("Thumbs") && !Directory.Exists(localFilename))
                    {
                        using (FileStream fileStream = new FileStream(localFilename, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            // Read full stream to in-memory buffer.
                            byte[] buffer = new byte[fileStream.Length];
                            fileStream.Read(buffer, 0, buffer.Length);

                            // Create a new entry for the current file.
                            ZipEntry entry = new ZipEntry(file.Name);
                            entry.DateTime = DateTime.Now;

                            // set Size and the crc, because the information
                            // about the size and crc should be stored in the header
                            // if it is not set it is automatically written in the footer.
                            // (in this case size == crc == -1 in the header)
                            // Some ZIP programs have problems with zip files that don't store
                            // the size and crc in the header.
                            entry.Size = fileStream.Length;
                            fileStream.Close();

                            // Update entry and write to zip stream.
                            zipOutput.PutNextEntry(entry);
                            zipOutput.Write(buffer, 0, buffer.Length);

                            // Get rid of the buffer, because this
                            // is a huge impact on the memory usage.
                            buffer = null;
                        }
                    }
                }

                // Finalize the zip output.
                zipOutput.Finish();

                // Flushes the create and close.
                zipOutput.Flush();
                zipOutput.Close();
            }
        }
    }

    public static void unZipFile(string sourcePath, string targetPath)
    {
        if (!Directory.Exists(targetPath))
            Directory.CreateDirectory(targetPath);

        using (ZipInputStream s = new ZipInputStream(File.OpenRead(sourcePath)))
        {

            ZipEntry theEntry;
            while ((theEntry = s.GetNextEntry()) != null)
            {

                if (theEntry.Name != String.Empty)
                {
                    using (FileStream streamWriter = File.Create(targetPath + "\\" + theEntry.Name))
                    {

                        int size = 2048;
                        byte[] data = new byte[2048];
                        while (true)
                        {
                            size = s.Read(data, 0, data.Length);
                            if (size > 0)
                            {
                                streamWriter.Write(data, 0, size);
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }
            }
        }
    }

}


text:
Q: SQL Server 2008R2 Full Text Catalog Missing Records I create one simple Full Text Catalog on a varchar(500) filed, which mainly store address text like 24 King Street Melbourne VIC 3000. The catalog is set to auto track changes. But I found there are always a few records in the table are not indexed by Full Text Catalog after I fully populate it.
For example, the table has 10,000 records, but the full text has only 9,997 records. So there are three records are not indexed. I rebuild the full text and all records are indexed. But after user start to insert data, there are missing records again. Table records increased to 11,000. But the full text records only have 10,999. Any idea why full text always missing some records?
If I run a manual update on the missing record, it will automatically indexed.
The filed included in the full text is updated by a trigger. It seems full text has issues tracking field that are updated by trigger?
Environment
SQL Server 2008 R2 Service Pack 2 - 10.50.4000
Full Text is set to Auto Track Changes

A: Full-Text Catalog Indexing takes time.
The official Microsoft Document states (emphasis by me) in the section Population based on change tracking:

By default, or if you specify CHANGE_TRACKING AUTO, the Full-Text Engine uses automatic population on the full-text index. After the initial full population completes, changes are tracked as data is modified in the base table, and the tracked changes are propagated automatically. The full-text index is updated in the background, however, so propagated changes might not be reflected immediately in the index.

Reference: Populate Full-Text Indexes (Microsoft Docs)
You might want to consider using Incremental population based on timestamp which is mentioned in the same document.

An incremental population is an alternative mechanism for manually populating a full-text index. If a table experiences a high volume of inserts, using incremental population can be more efficient that using manual population.+
  You can run an incremental population for a full-text index that has CHANGE_TRACKING set to MANUAL or OFF.
  The requirement for incremental population is that the indexed table must have a column of the timestamp data type. If a timestamp column does not exist, incremental population cannot be performed.
  SQL Server uses the timestamp column to identify rows that have changed since the last population. The incremental population then updates the full-text index for rows added, deleted, or modified after the last population, or while the last population was in progress. At the end of a population, the Full-Text Engine records a new timestamp value. This value is the largest timestamp value that SQL Gatherer has found. This value will be used when the next incremental population starts.


text:
Q: How to make a third line dock with the first bootstrap I have the following bootstrap layout:

This way you will create 3 lines. I would like to know if it is possible
make the column with id "teste2" create a new line for it and the column with id "teste3" completes the first column with id "teste1". However, I need it to be in that column order, without changing to this form, as follows:

A: You can achieve reordering of content on different screen sizes by using order css classes . For your example, like this:

  Teste 1

    Teste 2

    Teste 3