text:
Q: I cannot workout how to use a Partial View in a form that uses Knockout in MVC This is my view;
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<SHP.Models.TrainingListEmployeesViewModel>" %>
<%@ Import Namespace="System.Web.Script.Serialization" %>
<%@ Import Namespace="SHP.Helpers" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Bulk Training
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<form class="employeeListEditor" data-bind="submit: save">
    <fieldset>
    <legend>Allocate or cancel training for the selected employees</legend>

            Course Name
            <%: Html.EditorFor(model => model.TrainingName)%>

            Description (optional)
            <%:
           Html.TextAreaFor(
               model => model.TrainingDescription, new { maxlength = "255", style = "width:400px;height:100px;" })%>

    <%: Html.EditorFor(model => model.ClientEmployeeSelector)%>
    <button id="btnAdd" data-bind="click: addEmployee">Add</button><button data-bind="click: clearEmployee">Clear</button>

 0">

                    Employee

                        Remove
                        <input type="hidden" data-bind="value: SearchTextId"/>

        <% if(Model.Cvm != null)
           {%>
            <% Html.RenderPartial("Calendar", Model.Cvm); %>

                    <%:Html.MakePopupForm<SHP.Controllers.LeaveController>(o => o.TrainingSingleDate(), refreshOnSuccess: true)%>
                    <%:Html.PopupFormActionLink<SHP.Controllers.LeaveController>(o => o.TrainingSingleDate(), "Add a single date")%>

            <% if (TempData["SuccessMessage"].ToSafeString().Length > 0)
               {%>

<%: TempData["SuccessMessage"].ToSafeString() %>

            <% } %>
        <% }%>

    </fieldset>
</form>

</asp:Content>

You may notice I have a popup form in this view.
Also I would like to put all the code in the employeeCalendar div in a partial view.
Because of the popup window, I have to make sure in my controller that I redirect my Post method to my Get method so that when the popup data input has been completed and undates this view, I do not get an unwanted resend message  from windows.
The problem with doing these redirects is that I get a full page postback that looks unpleasent. So I would prefer to refresh my claendar from a partial view via Ajax.
So how do I do this?
This is my controller
   [HttpGet]
    [Authorize(Roles = "Administrator, Trainer, ManagerAccounts, ManagerIT")]
    public ActionResult BulkTraining()
    {
        if (SessionObjects.Tlevm == null)
        {
            return this.View(new TrainingListEmployeesViewModel());
        }

        return this.View(new TrainingListEmployeesViewModel(
            SessionObjects.Tlevm.EmployeeList,
            SessionObjects.TrainingName,
            SessionObjects.TrainingDescription));
    }

    [HttpPost]
    [Authorize(Roles = "Administrator, Trainer, ManagerAccounts, ManagerIT")]
    public ActionResult BulkTraining([FromJson] IEnumerable<ClientEmployeeSelector> employees, string trainingName, string trainingDescription)
    {
        // Items stored in Session used when saving the training dates for the employee
        // via the popup window
        SessionObjects.TrainingName = trainingName.JsonTrim();
        SessionObjects.TrainingDescription = trainingDescription.JsonTrim();
        SessionObjects.EmployeeIdList = employees.Select(x => x.SearchTextId).ToList();
        SessionObjects.EmployeeNameList = SessionObjects.EmployeeIdList.Count > 0
                        ? Employee.GetNameList(SessionObjects.EmployeeIdList)
                        : string.Empty;
        SessionObjects.Tlevm = new TrainingListEmployeesViewModel(
            employees.ToList(),
            SessionObjects.TrainingName,
            SessionObjects.TrainingDescription);
        return this.RedirectToAction("BulkTraining");
    }


text:
Q: Dynamic regex matching I have some strings like the following ones :
var resource1 = '/myapi/person/pascal/address/town';
var resource2 = '/myapi/person/john/address/town';
var resource3 = '/myapi/person/messi/address/town';

This is what I tried so far :
The pattern is :
var pattern = '/myapi/person/(.*)/address/town';

This is what I tried so far :
var resource1 = '/myapi/person/pascal/address/town';
var resource2 = '/myapi/person/john/address/town';
var resource3 = '/myapi/person/messi/address/town';
var pattern = '/myapi/person/(.*)/address/town';

var pattern = new RegExp(pattern);
if (pattern.test(resource1)){
    console.log('yes');
}

Question
How can I dynamically use that pattern to check if resource1, resource2 or resource3 match that pattern?
Regards.

A: The following regex should work:
/\/myapi\/person\/(.*)\/address\/town/

It can be used like so:
var string = '/myapi/person/pascal/address/town';
var re = /\/myapi\/person\/(.*)\/address\/town/;
re.test(string); //will return true

I encourage you to take a look it how it works here:
https://regexr.com/3ri4m

A: I suggest using stricter pattern. Use a negated character class instead of a greedy wildcard.

let resources = ['/myapi/person/pascal/address/town',
                 '/myapi/person/john/address/town',
                 '/myapi/person/messi/address/town'];

var regex = new RegExp('/myapi/person/([^/]+)/address/town');
for (var i = 0, len = resources.length; i < len; i++) {
  if(regex.test(resources[i]))
    console.log(`valid: ${resources[i]}`);
}

You have put a capture group around the person names variable. If you intend to capture those you can use .exec instead of .test:

let resources = ['/myapi/person/pascal/address/town',
                 '/myapi/person/john/address/town',
                 '/myapi/person/messi/address/town'];

var regex = new RegExp('/myapi/person/([^/]+)/address/town');
for (var i = 0, len = resources.length; i < len; i++) {
  if ((m = regex.exec(resources[i])) !== null) {
          console.log(m[1]);
  }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Retrieving RDS tags using boto3 gives an index error. I am trying to retrieve a tags using boto3 but I constantly run into the ListIndex out of range error.
My Code:
rds = boto3.client('rds',region_name='us-east-1')
rdsinstances = rds.describe_db_instances()
for rdsins in rdsinstances['DBInstances']:
        rdsname = rdsins['DBInstanceIdentifier']
        arn = "arn:aws:rds:%s:%s:db:%s"%(reg,account_id,rdsname)
        rdstags = rds.list_tags_for_resource(ResourceName=arn)
        if 'MyTag' in rdstags['TagList'][0]['Key']:
            print "Tags exist and the value is:%s"%rdstags['TagList'][0]['Value']

The error that I have is:
Traceback (most recent call last):
  File "rdstags.py", line 49, in <module>
    if 'MyTag' in rdstags['TagList'][0]['Key']:
IndexError: list index out of range

I also tried using the for loop by specifying the range, it didn't seem to work either.
for i in range(0,10):
   print rdstags['TagList'][i]['Key']

Any help is appreciated. Thanks!

A: You should iterate over list of tags first and compare MyTag with each item independently:
something like that:
 if 'MyTag' in [tag['Key'] for tag in rdstags['TagList']]:
     print "Tags exist and.........."

or better:
for tag in rdstags['TagList']:
    if tag['Key'] == 'MyTag':
        print "......"

A: I use function have_tag to find tag in all modul in Boto3
client = boto3.client('rds')
instances = client.describe_db_instances()['DBInstances']
if instances:
    for i in instances:
        arn = i['DBInstanceArn']
        # arn:aws:rds:ap-southeast-1::db:mydbrafalmarguzewicz
        tags = client.list_tags_for_resource(ResourceName=arn)['TagList']
        print(have_tag('MyTag'))
        print(tags)

Function search tags:
def have_tag(self, dictionary: dict, tag_key: str):
    """Search tag key
    """
    tags = (tag_key.capitalize(), tag_key.lower())
    if dictionary is not None:
        dict_with_owner_key = [tag for tag in dictionary if tag["Key"] in tags]
        if dict_with_owner_key:
            return dict_with_owner_key[0]['Value']
    return None


text:
Q: Get more probable positions in geolocation cloud I have no clue how to get some information about this problem I want to solve. I would like you to tell me the keywords to search or any information about this.
I have a cloud of geolocations (latitude, longitude) by user. I would like to know the middle point (not sure about this concept) of the different groups of locations.
For example, I register every minute the location of a wild animal so I get something like .
What I want to process it's to get the most usual (?) group of points and the mid point (Something like )
and know for example that the midpoint group one is the most "repeated" so it's where the animal sleeps, the second one is where the animal drinks and the third one is where eat (for example).
I have the points in a csv database so I can use elasticsearch, java or even python to get this information.
Any clue about this would be really interesting.

A: This is a typical clustering use case and I see essentially two options:
1. Centroid-based clustering
which could be approached in Elasticsearch through centroid aggregations.
2. Density-based clustering
DBC is a much better approach b/c it's outlier-based. Here's a python implementation. There might be better ones out there, incl. scikit's very own. Not overly familar w/ them so that's all I can say at this point.

I'm here to talk about Elasticsearch so here's how you'd do option #1:

*

*Set up an index

PUT animals
{
  "mappings": {
    "properties": {
      "location": {
        "type": "geo_point"
      }
    }
  }
}

*Add some locations to it

POST _bulk
{"index":{"_index":"animals","_type":"_doc"}}
{"location":[7.5146484375,51.17934297928927]}
{"index":{"_index":"animals","_type":"_doc"}}
{"location":[7.207031249999999,50.94458443495011]}
{"index":{"_index":"animals","_type":"_doc"}}
{"location":[7.734374999999999,51.069016659603896]}
{"index":{"_index":"animals","_type":"_doc"}}
{"location":[7.536621093749999,50.94458443495011]}
{"index":{"_index":"animals","_type":"_doc"}}
{"location":[8.525390625,51.16556659836182]}
{"index":{"_index":"animals","_type":"_doc"}}
{"location":[9.55810546875,50.83369767098071]}
{"index":{"_index":"animals","_type":"_doc"}}
{"location":[9.0087890625,51.138001488062564]}
{"index":{"_index":"animals","_type":"_doc"}}
{"location":[10.21728515625,50.56928286558243]}
{"index":{"_index":"animals","_type":"_doc"}}
{"location":[10.87646484375,50.84757295365389]}
{"index":{"_index":"animals","_type":"_doc"}}
{"location":[11.25,50.84757295365389]}
{"index":{"_index":"animals","_type":"_doc"}}
{"location":[11.09619140625,50.77815527465925]}
{"index":{"_index":"animals","_type":"_doc"}}
{"location":[11.513671874999998,50.84757295365389]}
{"index":{"_index":"animals","_type":"_doc"}}
{"location":[11.3818359375,50.708634400828224]}
{"index":{"_index":"animals","_type":"_doc"}}
{"location":[11.00830078125,50.736455137010665]}
{"index":{"_index":"animals","_type":"_doc"}}
{"location":[11.6455078125,51.52241608253253]}
{"index":{"_index":"animals","_type":"_doc"}}
{"location":[10.78857421875,50.3734961443035]}
{"index":{"_index":"animals","_type":"_doc"}}
{"location":[10.546875,49.96535590991311]}
{"index":{"_index":"animals","_type":"_doc"}}
{"location":[10.01953125,49.681846899401286]}
{"index":{"_index":"animals","_type":"_doc"}}
{"location":[9.29443359375,49.85215166776998]}
{"index":{"_index":"animals","_type":"_doc"}}
{"location":[8.942871093749998,49.710272582105695]}
{"index":{"_index":"animals","_type":"_doc"}}
{"location":[9.20654296875,49.5822260446217]}
{"index":{"_index":"animals","_type":"_doc"}}
{"location":[8.98681640625,49.52520834197442]}
{"index":{"_index":"animals","_type":"_doc"}}
{"location":[8.6572265625,49.603590524348704]}
{"index":{"_index":"animals","_type":"_doc"}}
{"location":[11.546630859375,50.14874640066278]}
{"index":{"_index":"animals","_type":"_doc"}}
{"location":[11.865234375,50.0289165635219]}
{"index":{"_index":"animals","_type":"_doc"}}
{"location":[11.42578125,50.52041218671901]}

I'm using some randomized points in Germany based on your sketch:

*Compute the centroids

POST animals/_search
{
  "size": 0,
  "aggs": {
    "weighted": {
      "geohash_grid": {
        "field": "location",
        "precision": 2
      },
      "aggs": {
        "centroid": {
          "geo_centroid": {
            "field": "location"
          }
        }
      }
    }
  }
}

This traverses all the points and not just those "clearly bound" in your sketch. This means there'll be outliers containing very few points that'll need to be skipped.
So taking the buckets that Elasticsearch returns, filtering just the larger buckets (I'm using JS instead of python here), and converting them to geojson with TurfJS:
turf.featureCollection(
  buckets.filter(p => p.doc_count > 3)
         .map(p => turf.point([
           p.centroid.location.lon,
           p.centroid.location.lat
         ])))

yields the following:

As you can see, the "centers" are skewed b/c the concentrations are not "high enough". With more concentrated groups the algorithm gets better.
But to be frank, DBSCAN is the way to go here, not weighted centroids.


text:
Q: Spring-boot data jpa reads from the database before inserts get completed @Transactional
    public void save(String myIds)
    {
            synchronized (this)
            {
                List<mydata> data = getDataToSaveOrUpdate(myIds);//Returns the new dataList and updates old data
                repository.saveAll(data);
                logger.info("request processed");
            }
        logger.debug("exiting the method");
    }

When this method is called in two separate request from postman what happens synchronized block gets completed but inserts are going and second request start reading from the data base .So second thread founds same data to insert in both the request and give unique key violation error how should we resolve this problem in springboot data jpa hibernate


text:
Q: why do i have to add a new variable in this code I was trying to write a code that takes two numbers as a input and change the numbers into words in certain rules.
Below is the code I wrote at first, but whatever input I put in, the loop starts from x=0.
#include <iostream>

int main() {

    string nums[10] = {"zero","one","two","three","four","five","six","seven","eight","nine"};

    int x,y;
    cin >> x;
    cin >> y;

    for (int x = x; x <= y; x++){
        if (x <= 9){
            cout << nums[x] << "\n";
        }
        else if (x % 2 == 0){
            cout << "even" << "\n";
        }
        else {
            cout << "odd" <<"\n";
        }
    }
    return 0;
}

Below is the second code I wrote and it worked as I wanted to.
#include <iostream>

int main() {

    string nums[10] = {"zero","one","two","three","four","five","six","seven","eight","nine"};

    int x,y;
    cin >> x;
    cin >> y;

    for (int i = x; i <= y; i++){
        if (i <= 9){
            cout << nums[i] << "\n";
        }
        else if (i % 2 == 0){
            cout << "even" << "\n";
        }
        else {
            cout << "odd" <<"\n";
        }
    }
    return 0;
}

I found out that if I add a variable, it works as what I wanted too. I found the solution but I don't know why I have to add a variable and why the first one always starts from x=0.

A: In first sample that you provided you  defined a local variable(x) as same name in outer block:
  for (int x = x; x <= y; x++)

In fact shadowing of variable take place here and c++ hide the declaration of variable of outer block with same name in nested block.


text:
Q: How to write a fraction in SwiftUI I'm making a small application to help kids to learn mathematics for kids.
However, I don't know how to write a fraction in SwiftUI ?
I would like something like this : 1⁄2
Thanks for your help :)

A: Updated: Xcode 13.4 / iOS 15.5
Now completely dynamic with font scaling supported, no layout hardcodes.
Main part:
    ZStack {
        Text("\(numerator) ")
            .alignmentGuide(VerticalAlignment.center,
                            computeValue: { d in d[.bottom] })
            .alignmentGuide(HorizontalAlignment.center,
                            computeValue: { d in d[.trailing] })

        Text("\u{2215}").font(.system(size: scale))

        Text(" \(denominator)")
            .alignmentGuide(VerticalAlignment.center,
                            computeValue: { d in d[.top] })
            .alignmentGuide(HorizontalAlignment.center,
                            computeValue: { d in d[.leading] })
    }

Test code is here
Original
Hope the following will be helpful. Of course you can tune parameters as you wish.
Demo:

Approach code:
import SwiftUI

struct FractionView: View {
    var numerator: String
    var denominator: String
    var body: some View {
        HStack {
            Text("\(numerator)")
                .offset(x: 4, y: 0)
                .alignmentGuide(VerticalAlignment.center,
                                computeValue: { d in d[.bottom] })
            Text("∕").font(.system(size: 32))
            Text("\(denominator)")
                .offset(x: -4, y: 0)
                .alignmentGuide(VerticalAlignment.center,
                                computeValue: { d in d[.top] })
        }
    }
}

struct TestFraction: View {
    var body: some View {
        VStack(spacing: 8) {
            FractionView(numerator: "1", denominator: "2")
            FractionView(numerator: "5", denominator: "7")
            FractionView(numerator: "11", denominator: "19")
            FractionView(numerator: "31", denominator: "9")
        }
    }
}

struct TestFraction_Previews: PreviewProvider {
    static var previews: some View {
        TestFraction()
    }
}

A: I recently came across an approach that might be more flexible than the currently proposed solution (not needing adaptation for different font sizes or styles).
Use the Unicode symbols for superscript and subscript numbers in combination with the Unicode fraction slash. A very simple solution could be:
Text("\u{2077}\u{2044}\u{2081}\u{2081}") // --> returns ⁷⁄₁₁

There is an interesting article that discusses this approach further: https://coderexmachina.medium.com/displaying-mathematical-fractions-in-swiftui-6a4dd625d842


text:
Q: Software Requirement Specifications for Web Applications I'm looking for some guidance/books to read when it comes to creating a software requirement specification for a web application. For inspiration I have read some spec documents for desktop based applications. The documents I have read capture a systems functional requirements in use cases which tend to be rather data oriented with use cases centered around the various CRUD operations the application is intended to perform.
I like this structure however I'm finding it rather difficult to marry it to what my web application needs to do, mostly reading data as opposed to manipulating it. I've had a go at writing some use cases however they all tend to boil down to "Search for item", "Change view of search results" or "User selects facet to refine search results". This doesn't sound quite right to me and makes me wonder if I'm going about this the right way.
Are there planning differences between web based and desktop based applications?

A: In my experience, there is really nothing wrong as having all the specifications being CRUD. Most of the time, any application isn't just "a simple CRUD app." Requirements evolve and different parts of the systems tend to diverge and acquire some specific logic.
Even if it feels like repeating the same CRUD sentences over and over, actually writing them down and thinking about it (instead of copy & pasting) will often uncover hidden requirements.

A: The differences between desktop based applications and web based applications is staggering.
I recommend reading these in exactly this order and apply this knowledge in exactly the opposite order, aside from CSS 3, HTML 5, and XHTML 1.1:
RFC 3986 - URI
RFC 2616 - HTTP 1.1
RFC 4346 - TLS 1.1
RFC 4251 - SSH Protocol
RFC 4252 - SSH Authentication
RFC 4253 - SSH Transport
RFC 2045 - MIME
RFC 4627 - JSON
HTML 4.01
XML
XHTML 1.0
XHTML 1.1
ECMAScript
CSS 2
HTML 5 (Not a standard)
CSS 3 (Not a standard)
Web Content Accessibility Guidelines 2.0
Symantec Internet Security Threat Report Volume XIV
Symantec Internet Security Threat Report Volume XV
OWASP Top 10
SEO
Once you have finished reading this you should begin to understand how the basic technology of the web works.  Only at this point would you be ready to develop, conformantly, for a web application.  There are many other technologies at play, but these are the basics and once you are familiar with the basics you will know where else to look for more information.

A: Basically you can sue the same method as for desktop applications, although you might make some addition, because we applications often tend to have different type of requrements. First of all, read something good about Use Cases, there are different use case levels and that might be a solution to your use cases which do not seem so right. Also do not forget about use case generalization and parametrized use cases if CRUD repetition is the problem. One thing, which is often more important in web applications than in desktop apps is the aspect of usability. This is because of the nature of the web - people have ofthe the coice of not using your service and go to next google result if you app is not usable. So what I think is a good addition to the spec are Personas - just find some possible instances of the human actors for your use cases and try to think of some goals they might want to achieve often using your web app and present how they will achieve them using your web app (and try to make it super easy of course). Another important thing is the Information Architecture - the way in which you will provide information in your web app. This comprises of navigation, some basic layout, but not necessarily design, just information about where to find something in your web app. This can be done using some rapid prototyping tools.


text:
Q: NTSC -> ADC -> USB. A video digitzer circuit I'm working on a project that ultimately needs to incorporate an analog video camera input, digitizing it and spitting it out a USB port as an MPEG stream.  My general aim is for roughly a VGA resolution, so it's not super demanding in those terms.
While I've been digging quite a lot, I'm having a tough time finding ICs or example circuits that aren't either overkill or more focused on frame grabs rather than real-time streams.
Overkill examples are the enormous line of TI products that are aimed at home A/V receivers with multiple HDMI IO, for example.
I want this to essentially be a stand-alone module, but the larger project has a microcontroller and other elements that make me lean away from any SOC or FPGA or Linux-on-OMAP etc solutions, in favor of what I hope and would think could be a simpler circuit.
Can anyone here point me in the right direction?  Or give me an appropriate kick-in-the-head, if I'm running off half-cocked in my thinking so far?
BTW - there is one cool, albeit dated design that I found here
Homebrew digitizer:  http://www.techmind.org/vd/vidmk2.html


text:
Q: undefined method `paypal_url' for nil:NilClass I have a model class page.rb:
class Page < ActiveRecord::Base

    def paypal_url(return_url)
      values = {
        :business => 'seller_1229899173_biz@railscasts.com',
        :cmd => '_cart',
        :upload => 1,
        :return => return_url,
        :invoice => id
      }
      line_items.each_with_index do |item, index|
        values.merge!({
          "amount_#{index+1}" => item.unit_price,
          "item_name_#{index+1}" => item.product.name,
          "item_number_#{index+1}" => item.id,
          "quantity_#{index+1}" => item.quantity
        })
      end
     "https://www.sandbox.paypal.com/cgi-bin/webscr?" + values.to_query
    end

end

And in my controller:
def order_form
    if params[:commit] == "Proceed to Checkout"
        redirect_to(@cart.paypal_url("/pages/order_online"))
end

but when I click on "Proceed to Checkout", it gives me an error:

undefined method `paypal_url' for nil:NilClass

Any idea if I'm missing anything or doing anything wrong?
Thanks!

A: The simple answer is your @cart variable is not being populated with any data
The way to fix this is to create a @cart variable in your order_form controller, like so:
def order_form
    @cart = Cart.new cart_params #-> how to define your cart var?
    redirect_to @cart.paypal_url "/pages/order_online"
end

I looked at the Railscast you've been using, and it seems he's continuing on from another episode, where he explains how to create the cart object using standard ActiveRecord

A longer answer is that I believe your system is flawed, in that you're calling PayPal methods in your Page model (why?)
We've set up our own cart in Rails before (you can see here):

*

*Cart session model #-> stores product id's in a cart model

*Product model stores the products & links with cart id's

*Order controller sends data to Paypal & handles returns

Here's some code for you:
#config/routes.rb
get 'cart' => 'cart#index', :as => 'cart_index'
post 'cart/add/:id' => 'cart#add', :as => 'cart_add'
delete 'cart/remove(/:id(/:all))' => 'cart#delete', :as => 'cart_delete'

get 'checkout/paypal' => 'orders#paypal_express', :as => 'checkout'
get 'checkout/paypal/go' => 'orders#create_payment', :as => 'go_paypal'
get 'checkout/stripe' => 'orders#stripe', :as => 'stripe'

#app/models/cart_session.rb #-> "session based model"
class CartSession

    #Initalize Cart Session
    def initialize(session)
        @session = session
        @session[:cart] ||= {}
    end

    #Cart Count
    def cart_count
        if (@session[:cart][:products] && @session[:cart][:products] != {})
            @session[:cart][:products].count
        else
            0
        end
    end

    #Cart Contents
    def cart_contents
        products = @session[:cart][:products]

        if (products && products != {})

            #Determine Quantities
            quantities = Hash[products.uniq.map {|i| [i, products.count(i)]}]

            #Get products from DB
            products_array = Product.find(products.uniq)

            #Create Qty Array
            products_new = {}
            products_array.each{
                |a| products_new[a] = {"qty" => quantities[a.id.to_s]}
            }

            #Output appended
            return products_new

        end

    end

    #Qty & Price Count
    def subtotal
        products = cart_contents

        #Get subtotal of the cart items
        subtotal = 0
        unless products.blank?
            products.each do |a|
                subtotal += (a[0]["price"].to_f * a[1]["qty"].to_f)
            end
        end

        return subtotal

    end

    #Build Hash For ActiveMerchant
    def build_order

        #Take cart objects & add them to items hash
        products = cart_contents

        @order = []
        products.each do |product|
            @order << {name: product[0].name, quantity: product[1]["qty"], amount: (product[0].price * 100).to_i }
        end

        return @order
    end

    #Build JSON Requests
    def build_json
        session = @session[:cart][:products]
        json = {:subtotal => self.subtotal.to_f.round(2), :qty => self.cart_count, :items => Hash[session.uniq.map {|i| [i, session.count(i)]}]}
        return json
    end

end

#app/controllers/cart_controller.rb
# shows cart & allows you to click through to "buy"
class CartController < ApplicationController
include ApplicationHelper

#Index
def index
    @items = cart_session.cart_contents
    @shipping = Shipping.all
end

#Add
def add
    session[:cart] ||={}
    products = session[:cart][:products]

    #If exists, add new, else create new variable
    if (products && products != {})
        session[:cart][:products] << params[:id]
    else
        session[:cart][:products] = Array(params[:id])
    end

    #Handle the request
    respond_to do |format|
        format.json { render json: cart_session.build_json }
        format.html { redirect_to cart_index_path }
    end
end

#Delete
def delete
    session[:cart] ||={}
    products = session[:cart][:products]
    id = params[:id]
    all = params[:all]

    #Is ID present?
    unless id.blank?
        unless all.blank?
            products.delete(params['id'])
        else
            products.delete_at(products.index(id) || products.length)
        end
    else
        products.delete
    end

    #Handle the request
    respond_to do |format|
        format.json { render json: cart_session.build_json }
        format.html { redirect_to cart_index_path }
    end
end

 end

 #app/controllers/orders_controller.rb
 #Paypal Express
def paypal_express
    response = EXPRESS_GATEWAY.setup_purchase(total,
      :items => cart_session.build_order,
      :subtotal => subtotal,
      :shipping => 50,
      :handling => 0,
      :tax => 0,
      :return_url => url_for(:action => 'create_payment'),
      :cancel_return_url => url_for(:controller => 'cart', :action => 'index')
    )
    redirect_to EXPRESS_GATEWAY.redirect_url_for(response.token)
end

#Create Paypal Payment
def create_payment
    response = express_purchase
    #transactions.create!(:action => "purchase", :amount => ((cart_session.subtotal * 100) + 50).to_i, :response => response)
    #cart.update_attribute(:purchased_at, Time.now) if response.success?
    response.success?
    redirect_to cart_index_path
end

#Stripe
def stripe
    credit_card = ActiveMerchant::Billing::CreditCard.new(
        :number             => "4242424242424242",
        :month              => "12",
        :year               => "2020",
        :verification_value => "411"
    )

    purchaseOptions = {
        :billing_address => {
            :name     => "Buyer Name",
            :address1 => "Buyer Address Line 1",
            :city     => "Buyer City",
            :state    => "Buyer State",
            :zip      => "Buyer Zip Code"
        }
    }

    response = STRIPE_GATEWAY.purchase(total, credit_card, purchaseOptions)
    Rails.logger.debug response.inspect

    @responder = response
    render cart_index_path
end

private
def subtotal
    (cart_session.subtotal * 100).to_i
end

def total
    ((cart_session.subtotal * 100) + 50).to_i
end

def express_purchase
    EXPRESS_GATEWAY.purchase(total, express_purchase_options)
end

def express_purchase_options
    {
      :token => params[:token],
      :payer_id => params[:PayerID]
    }
end

def express_token=(token)
    self[:express_token] = token
    if new_record? && !token.blank?
        details = EXPRESS_GATEWAY.details_for(token)
        self.express_payer_id = details.payer_id
        self.first_name = details.params["first_name"]
        self.last_name = details.params["last_name"]
    end
end

 end


text:
Q: How can I create a number range filter in react table v7? How can I create a number range filter in react table v7? Here is my relevant column definition, and filter function.
// The Filter function
import { Box, Input } from '@mui/material';
    const NumberFilter = ({ column, data }) => {
        const { filterValue = [], setFilter } = column;
        console.log('filterValue: ' + filterValue);
        return (
            <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                <Input
                    placeholder="Min"
                    value={filterValue[0] || ''}
                    type="number"
                    onChange={(e) => {
                        setFilter([e.target.value || undefined, filterValue[1]]);
                    }}
                />
                <Input
                    placeholder="Max"
                    value={filterValue[1] || ''}
                    type="number"
                    onChange={(e) => {
                        setFilter([filterValue[0], e.target.value || undefined]);
                    }}
                />{' '}
            </Box>
        );
    };
    export default NumberFilter;

// The column definition...
{
 Header: 'Pant Size',
 accessor: 'pant-size',
 Filter: NumberFilter,
 filter: 'isNumberRange',
 filterValue: [0, 10],
 Cell: ({ value}) => value);
}

This does not work. Instead of filtering all rows that have a value within the range of min and max, the column seems to be doing text matching, which is the default.
I think my issue is that there are various options for the filter parameter. For example, 'text' and 'exact'. I read somewhere that there is an option for numeric ranges and it was "isNumberRange". This clearly is incorrect. Is there another option? Does anyone know where this documentation lives?


text:
Q: Limit mysql data value to 100.0 I want to put completion of task in percentage (eg. 24.5,88.4,12.9,100.0,etc), the maximum value is 100.0
I have try using decimal(3,1) but it gave me maksimum of 99.9 ,
decimal(4,1) gave me maksimum of 999.9
is there any other correct data type for my problem ?

A: I don't think MySQL has a native way of doing this.  You are left to do it either with your external application or using a stored procedure.

A: I believe MySQL still doesn't support check constraints. However, you can use an INSERT/UPDATE trigger that verifies the new value of the column and throws an error if it's outside a range that you specify.


text:
Q: Dependency issues migrating project from ASP.NET 5 RC1 to ASP.NET Core 1.0 I am having a hard time converting my asp.net (core) app from dnx46 to .netcoreapp1.0 because of two particular dependencies ( Microsoft.Azure.ServiceBus and System.IO.Ports.SerialPort )
Being positive, I'm making the bet that these feature will eventually land on .net core one day.. but in the meantime, I found that converting my app from moniker dnx46 to .netstandard1.3 allows me to resolve the ServiceBus dependency.
Resolving System.IO.Ports.SerialPort however is still an issue and I don't understand how to make this work. I was hoping that importing net462 framework in .netstandard1.3 moniker, would allow to find the System.IO.Ports.SerialPort object but it does not.
What am I missing ?
For reference, there's my project.json :
{
  "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.0-rc2-3002702",
      "type": "platform"
    },
    "Microsoft.NETCore.Platforms": "1.0.1-*",
    "Microsoft.EntityFrameworkCore": "1.0.0-rc2-final",
    "Microsoft.EntityFrameworkCore.Sqlite": "1.0.0-rc2-final",
    [...more stuff...]
  },
  "frameworks": {
    "netcoreapp1.0": {
      "dependencies": {
        // To be restored when they'll become available on .net core
        //  "Microsoft.WindowsAzure.ConfigurationManager": "3.2.1",
        //  "WindowsAzure.ServiceBus": "3.2.1",
      }
    },
    "netstandard1.3": {
      "buildOptions": {
        "define": [ "INCLUDE_WINDOWSAZURE_FEATURE" ]
      },
      // Imports of net462 fixes loading of
      //  - NewtonSoft.Json
      //  - System.Runtime.Loader for "Microsoft.NETCore.App"
      "imports": [
        "net462"
      ],
      "dependencies": {
        "Microsoft.NETCore.Portable.Compatibility": "1.0.1-rc2-24027"
        "Microsoft.WindowsAzure.ConfigurationManager": "3.2.1",
        "WindowsAzure.ServiceBus": "3.2.1",
      }
    }
  }
}

A:
Resolving System.IO.Ports.SerialPort however is still an issue and I don't understand how to make this work. I was hoping that importing net462 framework in .netstandard1.3 moniker, would allow to find the System.IO.Ports.SerialPort object but it does not.

You can't reference System.IO.Ports.SerialPort when targeting .NET Core or .NET Standard, because this contract only exists in the full .NET Desktop framework.
This library might be eventually ported but in the meantime, you'll have to use .NET Desktop (e.g net462) instead of .NET Core.
Remove netcoreapp1.0 and netstandard1.3 and add net462 and it should work.

A: If you plan on deploying to a windows box and targeting net452, then simply take on a dependency on net452. I put together a migration guide to share my upgrading experiences, perhaps it might help? I initially had this misunderstanding that I would take a dependency of netstandard1.* and then "import": "net4*", David Fowler laughed at me and said something to the extent of "dude that's do wrong!". :P
You should change your project.json frameworks to look like this:
"frameworks": {
    "net462": { }
  }


text:
Q: How to bind data from Dictionary to xaml and use selected object CategoriesView.xaml
<local:AllViewBase x:Class="Test.View.Tab.CategoriesView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:Test.View.Abstract"
             mc:Ignorable="d">

    <UserControl.Resources>
        <ResourceDictionary Source="pack://application:,,,/Content/Style/MainWindowDictionary.xaml"/>
    </UserControl.Resources>

    <Grid>
        <ListBox ItemsSource="{Binding Path=dcCategory}" SelectedItem="{Binding Path=Category,Mode=TwoWay}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel>
                        <StackPanel Orientation="Horizontal" >
                            <Button Content="Add Value" Command="{Binding Path=DataContext.AddValue, RelativeSource= {RelativeSource FindAncestor, AncestorType={x:Type ListBox}}}"/>
                            <TextBlock Text="{Binding Path=Key}"/>
                        </StackPanel>
                        <ListBox ItemsSource="{Binding Path=Value}" />
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Horizontal" />
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>
        </ListBox>
    </Grid>
</local:AllViewBase>

CategoriesViewModel.cs
namespace Test.ViewModel.Tab
{
    public class CategoriesViewModel : AllViewModel<CategoryValueAllView>
    {
        private BaseCommand _AddValue;

        private Category _Category;
        public Category Category
        {
            get
            {
                return _Category;
            }
            set
            {
                if (_Category != value)
                {
                    _Category = value;
                    OnPropertyChanged(() => Category);
                }
            }
        }

        private Dictionary<Category, List<string>> _dcCategory;
        public Dictionary<Category, List<string>> dcCategory
        {
            get
            {
                if (_dcCategory == null) LoadDictionary();
                return _dcCategory;
            }
            set
            {
                if (_dcCategory != value)
                {
                    _dcCategory = value;
                    OnPropertyChanged(() => dcCategory);
                }
            }
        }

        public ICommand AddValue
        {
            get
            {
                if (_AddValue == null)
                {
                    _AddValue = new BaseCommand(() => Messenger.Default.Send(CategoryValueCode.AddValue + "," + Category.CategoryId));
                }
                return _AddValue;
            }
        }

        public void LoadDictionary()
        {
            dcCategory = (from k in db.Category join w in db.CategoryVal on k.CategoryId equals w.CategoryId select new CategoryValueAllView { Category = w.Category, Val = w.Val }).GroupBy(x => x.Category).ToDictionary(grp => grp.Key, grp => grp.Select(obj => obj.Val).ToList());
        }
    }
}

My goals are:

*

*<TextBlock Text="{Binding Path=Key}"/> show Category.Name. I don't
know how to use Key like an object and use property Name

*when I push the button 'Add Value' I want to set 'CategoryId' in 'Category' object and sent it throught 'AddValue' Command by
Messenger

Earlier I used the string category.name instead of the category object for dictionary key. Then <TextBlock Text="{Binding Path=Key}"/> showing correct name, but after all I was unable to pass the 'category.name' to the 'AddValue' command after click button to get id by name and set data by Messenger.
Getting id by the name is acceptable too, the Category object as a key is not required
in spite of everything I would like to learn it, but I can not stand an example which has show such a problem
Thanks!

A: *

*Use Key.Name for binding to TextBlock

*For binding to the listbox you have two ways:

-Use SelectedItem. You already have a property "Category" in your viewmodel. Bind that property to the listbox selected item. You can then use Category.CategoryID in your AddValue command.
<ListBox ItemsSource = "{Binding Path = dcCategory}" SelectedItem = "{Binding Path = Category, Mode = TwoWay}">

-Use SelectedValue. SelectedCategoryId should be a property on the viewmodel. You can then directly use this property inside your AddValue command.
<ListBox ItemsSource = "{Binding Path = dcCategory}" SelectedValuePath = "CategoryId" SelectedValue = "{Binding Path = SelectedCategoryId, Mode = TwoWay}">


text:
Q: Setting iChat status from a web app I'd like my web app to be able to set ichat status: Available or Away + Custom message
Basically my web app is related to tracking and status so at present, you have to remember to update both (if you use iChat), which is a pain.
Is there a way to do this? using Javascript or the like?
Alternatively, the other way around would work too but I guess that would involve creating some sort of extension or plugin for iChat.

A: use this in you link weather it be javascript:window.location = '' or href="" use this link aim:goaway?message=hi you can also do a javascript like javascript:window.location = 'aim:goaway?message=' + new Date() with a variable


text:
Q: Get current location in foreground service I run my foreground service every 3 minutes. Therefore my goal is: Run a foreground service, get the current user location and then stop the foreground service.
So now I use this:
locationCallback = object : LocationCallback(){
        override fun onLocationAvailability(locationAvailability: LocationAvailability?) {
            super.onLocationAvailability(locationAvailability)
            if(locationAvailability!!.isLocationAvailable){
                fusedLocationClient.lastLocation.addOnSuccessListener { location: Location? ->
                    if (location != null) {
                       // do my action with this location and finish the foreground service
                    }
                }
            }else{
                prepareFinishService() // finish service
            }
        }
    }
    fusedLocationClient.requestLocationUpdates(locationRequest,
            locationCallback, Looper.getMainLooper())

And my locationRequest:
fun createLocationRequest(): LocationRequest {
    val locationRequest = LocationRequest.create()
    locationRequest.interval = 10000L * 10
    locationRequest.fastestInterval = 50000L
    locationRequest.smallestDisplacement = 10f
    locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
    return locationRequest
}

But in this solution I get not fresh location. For example user change location but onLocationAvailability retrun previous location. After some time for example after 15 minutes when my service run it return a updated location.
I know that I can add also this callback :
override fun onLocationResult(locationResult: LocationResult?) {
     // my action with location
}

But as per documentation :
onLocationResult

"Even when isLocationAvailable() returns true the onLocationResult(LocationResult) may not always be called regularly, however the device location is known and both the most recently delivered location and getLastLocation(GoogleApiClient) will be reasonably up to date given the hints specified by the active LocationRequests."

It is possible that this function will not be called and my service will run all the time until the next start. I do not want this situation. Is there any solution to always access the current service and then stop the service?

A:
For example user change location but onLocationAvailability retrun
  previous location.

This is what getLastLocation does. It returns the last known location, it doesn't mean the newest location. According to the documentation :

It is particularly well suited for applications that do not require an accurate location [...]

That said, for a decent accuracy, you should use requestLocationUpdates.
But don't start/stop you service manually. If you want regular updates on the user location, just set the right parameters.
LocationRequest locationRequest = new LocationRequest();
locationRequest.setInterval(1000*60*3); // max: 3 min
locationRequest.setFastestInterval(1000*60*1); // min: 1 min
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);


text:
Q: org.hibernate.MappingException: Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister I am actually new to hibernate and tried to set up 1 class, supplier.
Here are some details.
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
   <session-factory>
      <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
      <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
      <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/transaksi?zeroDateTimeBehavior=convertToNull</property>
      <property name="hibernate.connection.username">root</property>
      <property name="hibernate.show_sql">true</property>
      <property name="hibernate.query.factory_class">org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory</property>
      <property name="hibernate.format_sql">true</property>
      <mapping resource="Pojo/Supplier.hbm.xml"/>
   </session-factory>
</hibernate-configuration>

hibernate.reveng.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd">
<hibernate-reverse-engineering>
   <schema-selection match-catalog="transaksi"/>
   <table-filter match-name="supplier"/>
</hibernate-reverse-engineering>

Supplier.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated Jun 1, 2016 9:01:44 PM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
<class name="Pojo.Supplier" table="supplier" catalog="transaksi"    optimistic-lock="version">
    <id name="kdSup" type="string">
        <column name="kd_sup" length="25" />
        <generator class="assigned" />
    </id>
    <property name="nmSup" type="string">
        <column name="nm_sup" length="25" not-null="true" />
    </property>
    <property name="nmBrg" type="string">
        <column name="nm_brg" length="25" not-null="true" />
    </property>
    <property name="hrg" type="int">
        <column name="hrg" not-null="true" />
    </property>
    <property name="jml" type="int">
        <column name="jml" not-null="true" />
    </property>
    <property name="tgl" type="date">
        <column name="tgl" length="10" not-null="true" />
    </property>
    <property name="FStatus" type="int">
        <column name="f_status" not-null="true" />
    </property>
    <property name="FUpdate" type="int">
        <column name="f_update" not-null="true" />
    </property>
</class>
</hibernate-mapping>

Supplier.java
package Pojo;

import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name ="supplier")
public class Supplier  implements java.io.Serializable {

 @Id
 private String kdSup;
 private String nmSup;
 private String nmBrg;
 private String hrg;
 private String jml;
 private Date tgl;
 private String FStatus;
 private String FUpdate;

public Supplier() {
}

public Supplier(String kdSup, String nmSup, String nmBrg, String hrg, String jml, Date tgl, String FStatus, String FUpdate) {
   this.kdSup = kdSup;
   this.nmSup = nmSup;
   this.nmBrg = nmBrg;
   this.hrg = hrg;
   this.jml = jml;
   this.tgl = tgl;
   this.FStatus = FStatus;
   this.FUpdate = FUpdate;
}

public String getKdSup() {
    return this.kdSup;
}

public void setKdSup(String kdSup) {
    this.kdSup = kdSup;
}
public String getNmSup() {
    return this.nmSup;
}

public void setNmSup(String nmSup) {
    this.nmSup = nmSup;
}
public String getNmBrg() {
    return this.nmBrg;
}

public void setNmBrg(String nmBrg) {
    this.nmBrg = nmBrg;
}
public String getHrg() {
    return this.hrg;
}

public void setHrg(String hrg) {
    this.hrg = hrg;
}
public String getJml() {
    return this.jml;
}

public void setJml(String jml) {
    this.jml = jml;
}
public Date getTgl() {
    return this.tgl;
}

public void setTgl(Date tgl) {
    this.tgl = tgl;
}
public String getFStatus() {
    return this.FStatus;
}

public void setFStatus(String FStatus) {
    this.FStatus = FStatus;
}
public String getFUpdate() {
    return this.FUpdate;
}

public void setFUpdate(String FUpdate) {
    this.FUpdate = FUpdate;
}

}

SupplierGui.java
package Gui;
import Pojo.Supplier;
import java.util.List;

public interface SupplierGui {

    List<Supplier> listSupplier();
}

SupplierDAO.java
package DAO;
import Pojo.Supplier;
import Gui.SupplierGui;
import Util.HibernateUtil;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import javax.persistence.EntityManager;
import javax.swing.JOptionPane;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.Criteria;
import org.hibernate.Query;

public class SupplierDAO implements SupplierGui {

private SessionFactory sessionFactory;

public SupplierDAO(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
}

@Override
public List<Supplier> listSupplier() {
    Session session = sessionFactory.openSession();
    session.beginTransaction();
    List list = new ArrayList();
    try {
        Query query = session.createQuery("from supplier where f_status = '1'");
        list = query.list();
        session.getTransaction().commit();
    } catch (IllegalStateException ex) {
        session.getTransaction().rollback();
        JOptionPane.showMessageDialog(null, ex);
    }
    return list;
 }

 }

this is main class...
frmSupplier.java
package Tampilan;
import java.sql.*;
import java.text.ParseException;
import javax.swing.*;
import java.lang.*;
import java.awt.*;
import javax.swing.table.DefaultTableModel;
import java.text.SimpleDateFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.Date;

import Pojo.Supplier;
import Gui.SupplierGui;
import java.util.ArrayList;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import Util.HibernateUtil;
import Util.SupplierTableModel;
import java.util.Calendar;

public class frmSupplier extends javax.swing.JFrame {

private SupplierGui supplierInters = HibernateUtil.getSupplier();
private Supplier sup;
private List listSuplierAll = new ArrayList();

String tanggal;

public frmSupplier() {
    initComponents();
    BacaTabelSupplier();    }

private void BacaTabelSupplier(){
    try{
        listSuplierAll = supplierInters.listSupplier();

    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, ex);
    }
    String[][] data1 = new String[listSuplierAll.size()][6];
    for (int x = 0; x < listSuplierAll.size(); x++) {
        Supplier tm1 = (Supplier) listSuplierAll.get(x);
        data1[x][0] = tm1.getKdSup();
        data1[x][1] = tm1.getNmSup();
        data1[x][2] = tm1.getNmBrg();
        data1[x][3] = tm1.getHrg();
        data1[x][4] = tm1.getJml();
        data1[x][5] = tm1.getTgl().toString();
    }
    String[] label = {"Kode Supplier","Nama Supplier","Nama Barang","Harga Satuan",
                        "Jumlah","Tanggal"};
    DefaultTableModel model = new DefaultTableModel(data1, label);
    tabel.setModel(model);

}

public static void main(String args[]) {

    java.awt.EventQueue.invokeLater(new Runnable() {

        public void run() {
            new frmSupplier().setVisible(true);
        }
    });
}

}

HibernateUtil.java
package Util;

import DAO.SupplierDAO;
import Gui.SupplierGui;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;

public class HibernateUtil {

private static final SessionFactory sessionFactory;
private static final SupplierGui supplierInter;

static {
        try{
        sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        supplierInter = new SupplierDAO(sessionFactory);
        } catch (Throwable ex) {
        System.err.println("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}

public static SessionFactory getSessionFactory() {
    return sessionFactory;
}

public static SupplierGui getSupplier() {
    return supplierInter;
}

}

and here is my problem.
org.hibernate.MappingException: Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister
Initial SessionFactory creation failed.org.hibernate.MappingException: Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister
Exception in thread "AWT-EventQueue-0" java.lang.ExceptionInInitializerError
at Util.HibernateUtil.<clinit>(HibernateUtil.java:33)

this is my structure package
i really don't know where is mistake in their code, can someone help me? i am new to try hibernate, i really happy if you want to help me.
thanks =)

A: I think you can solve by adding this line to your hibernate.cfg.xml
<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>


text:
Q: how to use Fourier transform to predict future trend by fitting the dominant frequency Here I have several depth profiles at the same location. This profiles were measured in a time series but not in evenly time interval. I decomposed those profiles by FFT and found the dominant frequency. Then I found the amplitudes of the dominant frequencies in each profile fit exponential regression. So how can I use this point to predict future development of the profiles. It's like you give a time then you get a profile.
Here my idea is to fit amplitude with the time. But I can only fit the real part of the complex not the imaginary part. As long as I change the value of the imagina part then the inverse FFT, the profiles would disappear. And I don't know why...

Here is part of the program
%fitting%forecast
pp1=polyfit(xx,YY1,1);
%pp2=polyfit(xx,YY2,1);
xx=log([5000 10000 20000 30000 50000 100000 500000]);
p1=pp1(1)*xx+pp1(2);
%p2=(pp2(1)*xx+pp2(2))*1i;
p=p1;%+p2;
%kk2=imag(Y1);
kk1=real(Y1);
%kk2(:,6)=kk2(:,5);
%kk2(:,7)=kk2(:,5);
kk1(:,6)=kk1(:,5);
kk1(:,7)=kk1(:,5);
kk1(5,:)=p;
kk1(91,:)=p;
kk=kk1;%+kk2*1i;
%as long as I fit the imaginary part the profile becomes strange
k=ifft(kk);
plot(a1)
hold on
plot(k,'*')


text:
Q: Retrieving date range from Pandas HDF5Store I wish to select a date range from my HDFStore using Pandas. I noticed that my datetimes (millisecond frequency) are stored as Unix time with extra right padded zeroes i.e 1514797200002000000. I suspect my where clause is incorrect.
This is my reproducible code:
import pandas as pd
import numpy as np

path_file = "hdf5_store.h5"
data = np.random.randn(5)
cols = ["values"]
date_range = pd.date_range('20180101 09:00:00', periods=5, freq='ms')
df = pd.DataFrame(data=data, index=date_range, columns=cols)

with pd.HDFStore(path_file, mode="w", driver="H5FD_CORE") as store:
        store.append("df", df, format="table", data_columns=["date_time"], index=False)
        store.create_table_index("df", columns=["date_time"], kind="full")
        print(store["df"])

df1 = pd.read_hdf(path_file, "df", where=["date_time>1514797200002000000"])
print(df1)

A: This works as a query:
dt = pd.to_datetime(1514797200003000000)
df1 = pd.read_hdf(path_file, "df", where=["index>dt"])


text:
Q: How to Stop Pushing segue when some condition Happens? How to Stop Pushing segue when some condition is failed
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{

    internet *myclass = [[internet alloc]init];
    if ([myclass connectedToInternet]) {

    if ([[segue identifier] isEqualToString:@"showShoping"]) {
        _pass = @"shop";
        MyTabController *mvc = (MyTabController *)segue.destinationViewController;
        mvc.myCategory = _pass;
    }
    if ([[segue identifier] isEqualToString:@"showTravel"]) {
        _pass = @"travel";
        MyTabController *mvc = (MyTabController *)segue.destinationViewController;
        mvc.myCategory = _pass;
    }
    if ([[segue identifier] isEqualToString:@"showFood"]) {
        _pass = @"food";
        MyTabController *mvc = (MyTabController *)segue.destinationViewController;
        mvc.myCategory = _pass;
    }
    else{

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No Internet!"
                                                        message:@"No working internet connection is found."
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];

    }

}

Thanks

A: - (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(nullable id)sender NS_AVAILABLE_IOS(6_0);

you can override this method, return No to stop perform segue when some condition happens.
for example
- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender {

    if ([identifier isEqualToString:@"showShoping" ]) {

        return NO;

  }
 return YES;

}

}


text:
Q: Injecting an object that requires enum in Guice I have an object to be injected that is defined as:
    public class EnvironmentModule extends AbstractModule {

        @Override
        protected void configure() {
        }

        @Provides
        @Singleton
        private String getObject(final Client client) {
            ...
        }
}

Client is an enum defined as :
@NoArgsConstructor(force = true)
public enum Client {
    private String name;

    Client(final String name) {
        this.name = name;
    }

    public static Client identifyClient(final String clientName) {

    }
}

This gives me an error-
Could not find a suitable constructor in Client. Classes must have either one (and only one) constructor annotated with @Inject or a zero-argument constructor that is not private
at Client.class(Client.java:5)
at EnvironmentModule.getObject(EnvironmentModule.java:35)
Please help. What has to be done.

A: The reason this is happening is because in your module you do not declare an instance of Client to be injected in the scope of the module, so it tries to create one with an empty constructor. This does not work because your enum has two constructors, and guice requires a single empty constructor. The solution to this to create a singleton of your client. I assume the code you omitted in Client looks like
public enum Client {

    //I assume it works like this
    NORMAL_CLIENT("whatever");

    private String name;

    Client(final String name) {
        this.name = name;
    }

    public static Client identifyClient(final String clientName) {
        return Arrays.stream(Client.values())
            .filter(client -> clientName.equals(client.name))
            .findAny()
            //This is dangerous, throw an error if its not found
            .get();
    }
}

So we need to create a singleton in the environment module for the client. this would look like
public class EnvironmentModule extends AbstractModule {
    @Override
    protected void configure() {
        super.configure();
    }

    @Provides
    @Singleton
    private Client getClient() {
        return Client.identifyClient("whatever");
    }

    @Provides
    @Singleton
    private String doWhatever(final Client client) {
        System.out.println("found client " + client);
        return "cool it works";
    }
}

invoking the module through
public class Main {
    public static void main(String[] args) {
        final var envInjector = Guice.createInjector(new EnvironmentModule());
        final var client = envInjector.getInstance(Client.class);
        final var doWhateverString = envInjector.getInstance(String.class);
        System.out.println(doWhateverString);
        System.out.println("found instance " + client);
    }
}

we can see
found client NORMAL_CLIENT
cool it works
found instance NORMAL_CLIENT


text:
Q: How to delete all files which have certain name? I need to delete all files which have certain name, at once and using the terminal.
All their name starts with in.lsp.
What is the command to achieve that?

A: rm -f in.lsp*

Another answer would be:
find . -name 'in.lsp*' -exec rm {} \;

This second version gives you a little more power.   It lets you search directories other than ., it lets you choose to filter -type d or -type f, it lets you choose whether to remove files-only (rm {}) or files and directories (rm -r {}), etc.  It lets you choose on whether to follow symbolic links, to choose a search depth, search through regex, size, permissions, context, etc.
find . -name 'in.lsp*' -delete

can also work.


text:
Q: How to create a conference call to multiple numbers using node js I want to create a conference to multiple numbers using Twilio and Nodejs.

In my application I want to create a conference from the number I bought from Twilio to multiple numbers.

I am following this link.
My code is as follows
const Twilio = require('twilio');
const client = new Twilio(account_sid, authToken);

mobileArr.forEach(function(number,ind) {
    console.log("mobile array iteration",ind, number);
    client
      .conferences(conferences.title)
      .participants.create({
        to: number,             //number which i want to add to conference
        from: myTwilioNumber,  //number I bought from Twilio
        statusCallback: twilioCallBackUrl,
        statusCallbackMethod: 'POST',
        statusCallbackEvent: ['initiated', 'ringing', 'answered', 'completed'],
        Timeout: '15',
        method: 'GET',
    }, function(err, participant) {
        if (err) {
            console.error('conf failed because: '+ err);
        } else {
           console.log(participants)
        }
    })
})

The issue I am facing is I am not receiving all the webhook callback for
  all participants I have added to the conference properly.
I want to know that, am I doing it the right way or is there another
  better way of doing it.

Suppose I add 3 participants to a conference I Should receive a total 12 callBacks from Twilio for 'initiated', 'ringing', 'answered', 'completed' for each individual person I have added to the conference.
But on some occasion's this does not happen.

Is there a way through which I can recieve callBacks for conference
  status as a whole.

Is there a way to pass an array of numbers to create conference instead of adding each number in the forEach loop.
I am new to Twilio please help.

A: Only a couple of modifications in the code and things are working fine.

Simply add conferenceStatusCallback and conferenceStatusCallback to
  the above code, implement the desired logic in callbacks.

const Twilio = require('twilio');
const client = new Twilio(account_sid, authToken);

mobileArr.forEach(function(number,ind) {
    console.log("mobile array iteration",ind, number);
    client
      .conferences(conferences.title)
      .participants.create({
        to: number,             //number which i want to add to conference
        from: myTwilioNumber,  //number I bought from Twilio
        statusCallback: callBackUrl,//any logic on call events
        statusCallbackMethod: 'POST',
        statusCallbackEvent: ['initiated', 'ringing', 'answered', 'completed'],
        conferenceStatusCallbackEvent: ['start', 'end','join','leave'],
        conferenceStatusCallback:conferenceCallBackUrl, //any business logic on conference events
        Timeout: '15',
        method: 'GET',
    }, function(err, participant) {
        if (err) {
            console.error('conf failed because: '+ err);
        } else {
           console.log(participants)
        }
    })
})

Thats it.
Thanks, philnash.


text:
Q: MS Access VBA Refresh Only Visible Items
Can anyone tell me the VBA command in Access to refresh only the visible items in the dataset? This is the equivalent of clicking the refresh button shown on the ribbon. It has the benefit of keeping the scroll position and not refreshing the entire dataset. Thanks.

A: You can create a recordset or querydef of the records that you want to  show in a form and then use the command Application.RefreshDatabaseWindow to show the live refresh in the database.

A: I found the answer using information from https://msdn.microsoft.com/en-us/library/dd627337(v=office.12).aspx
commandbars.FindControl(ID:=1020).Execute


text:
Q: Extract id from inside class I am doing web scraping using beautiful. When I extracted class variable using find all I am getting array of data.
My query is how to extract id value from the extracted value. I tried the tag. but it did not help much.
I need following output

measurement_a000_20c0_0002

data[0]

0.0

A: Based on your example just find the element and then use get id attribute. element['id']
from bs4 import BeautifulSoup
html='''

0.0

	'''

soup=BeautifulSoup(html,"html.parser")
for item in soup.select(".measurement >div "):
    print(item['id'])

If you want to use find_all() try this.
from bs4 import BeautifulSoup
html='''

0.0

	'''

soup=BeautifulSoup(html,"html.parser")
for item in soup.find_all("td" , class_="measurement"):
    print(item.find_next('div')['id'])


text:
Q: What/Which towns do we go through on the way? What is the difference between "what" and "which" here? Which one do we prefer? Do they mean the same?

*

*What towns do we go through on the way?

*Which towns do we go through on the way?

A: We usually use which when we are asking about a fixed or limited number of things, and what when we are not.
Often, however, we can use either which or what with little difference in meaning (like in this case).

What towns do we go through on the way? (the speaker doesn't know the area)
Which towns do we go through on the way? (the speaker knows the area and the towns in it)


text:
Q: Using a powerline adapter and wireless bridge together as failover or loadbalancing I have two routes via ethernet. One is more stable but slow, the other is fast but might disconnect. What solutions are available to have a load balancer or fail over? The routes are both from a single router.
My current setup is:
pfSense -> Wireless AP -> SwitchA -> powerline A
powerline B -> SwitchB -> PCs in room
Powerline A-B gets 20mbit
Basically I want to add a wireless bridge that also connects to switch B.
powerline B -> SwitchB -> PCs in room
Wireless Bridge -> SwitchB -> PCs in room
The switch by itself doesn't know which route to use (I assume), would a dual wan router with disabled DHCP work in this case or there a better solution?

A: You have not provided nearly enough information to go on - particularly how the "disconnect" works.     Making huge assumptions there are a few ways to deal with this -

*

*Ensure the more reliable route is less preferred and set the faster but less reliable
connection up in such a way that the interface (or at least its route) disappears when
its not available - this will provide automatic failover and give you largely the best
of both worlds - but it assumes you can make the route disappear (which is not
hard if you are using PPP.  (Note that ethernet does not preclude the use of PPP,
PPPoE is very common)

*Use dynamic routing like BGP (or OSPF or RIP, but in reality it will be BGP on
the assumption your routes go to different providers).  This of-course assumes your
router is BGP capable, you own rights to IP space and both  providers will play
together.

*Set up source routing so packets can go through either connection depending on the
source IP (or mark) assigned to them.   Then balance this connection.  Again, there
are multiple ways to do this depending on what you are trying to do and your
hardware ability, but include:

*

*Routes which require low bandwidth or high reliability go through the slow
connection.  "Nice to haves" go through the fast connection.

*Get an reliable offsite connection (virtual server), set up 2 VPN's to the
server - one through each link, aggregate the links as and available and
route everything across them.   This probably offers the best of both worlds
but requires quite a bit of skill and, of-course, a fast connection on the
other side.   [ And yes, I know someone doing just this, so its quite
practical with the knowledge ]
In order to do any of this stuff you need a decent router - but decent could be a Linux based embedded system (I've done all of these things at one time or another using Linux).  The exact howtos are not really amenable to a Superuser question as they require an in-depth understanding of networking.

A: I don't quite follow your diagram, but assuming you're talking about local networking, and not two seperate WAN uplinks, I suggest get decent switches that support OSPF, and let them do the hard work.
OSPF correctly configured will also occasionally exceed the bandwidth of a single link depending on your network topology (consider 4 nodes as 2 pairs, each node wired to a switch, and each pair also cross-connected), while other setups won't.


text:
Q: fragments visibility gone and visible on respective button click I have view pager and bottom navigation bar with five fragments, tried to hide other fragments when first fragment is called.
FragmentManager fm = getSupportFragmentManager();

FragmentTransaction ft = fm.beginTransaction();

protected void selectFragment(MenuItem item) {
    item.setChecked(true);

    switch (item.getItemId()) {
        case R.id.action_home:
            displayFragment(DefaultFragment.class);
            ft.hide(FavouriteFragment.class);//need help here
            break;
        case R.id.action_info:
            displayFragment(FavouriteFragment.class);
            break;
        case R.id.action_msg:
            displayFragment(NotifyFragment.class);
            break;
        case R.id.action_profile:
            displayFragment(ProfileFragment.class);
            break;
        case R.id.action_history:
            displayFragment(OrderHistoryFragment.class);
            break;

    }
}

background you can see the previous fragments are coming, though the clicked fragment have background color blue

A: All you need to do is:
switch (item.getItemId()) {
        case R.id.action_home:
            Fragment fragment = new DefaultFragment();
            loadFragment(fragment);
            break;
        case R.id.action_info:
            Fragment fragment = new FavouriteFragment();
            loadFragment(fragment);
            break;
        case R.id.action_msg:
            Fragment fragment = new NotifyFragment();
            loadFragment(fragment);
            break;
        case R.id.action_profile:
            Fragment fragment = new ProfileFragment();
            loadFragment(fragment);
            break;
        case R.id.action_history:
            Fragment fragment = new OrderHistoryFragment();
            loadFragment(fragment);
            break;

    }

private void loadFragment(Fragment fragment)
{
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    ft.replace(R.id.content_login_activity, fragment);
    ft.commitAllowingStateLoss();
    this.getSupportFragmentManager().popBackStackImmediate(null,
    FragmentManager.POP_BACK_STACK_INCLUSIVE);
}


text:
Q: Calling multiple functions in parallel in PHP I have the following code on a controller
class SomController extends Controller
{
public function index(){
    $var1           = $this->function1();
    $var2           = $this->function2();
    $var3           = $this->function3();
    $var4           = $this->function4();
    return view('someview', array(self::SOME1 => $var1,self::SOME2 => $var2,self::SOME3 => $var3,self::SOME4 => $var4));
  }
}

So I want to call this 4 functions in parallel and wait to all of then to finish in order to render the laravel view, I've tried to use pthreads,pcntl_fork, I even used hhvm with hack, With no good result nor parallel results theres any simplier way to achieve this?

A: You can't do that purely in PHP, it's just the nature of synchronized programming language like PHP, Ruby, and Python, to execute code one by one from start of the code to end. If you want to do that, then use an asynchronous language like Node.js or try to search asynchronous PHP library (which isn't recommended because no mature solution for this).
But here: a lot of big companies use synchronous language for their site like Google, Youtube, Bootcamp, etc. Most of the time what you really need is to be clever about the execution of your program first, then if you really need asynchronize request, do it with AJAX on user-end, but it will make your code A LOT complex then what you may really need .


text:
Q: More ImageView on TabActivity It's my first post, and I hope I have searched well before I post.
I have created my first app studying many examples and tutorials. My app has a tabbed activity with swipe and it does function well.
I have two imageviews, one in one tab and the second in a second tab. When i write the public void imageclick to open a new activity with Intent, each image calls the same activity, but it should open different activity for different image.
I'm not able to set Findviewbyid to indicate which image I'm clicking.
public class welcome extends ActionBarActivity implements android.support.v7.app.ActionBar.TabListener{

private ViewPager tabsviewPager;
private ActionBar mActionBar;
private Tabsadapter mTabsAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_welcome);

    tabsviewPager = (ViewPager) findViewById(R.id.tabspager);

    mTabsAdapter = new Tabsadapter(getSupportFragmentManager());

    tabsviewPager.setAdapter(mTabsAdapter);

    getSupportActionBar().setHomeButtonEnabled(false);
    getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    Tab friendstab = getSupportActionBar().newTab().setText("Lo Staff").setTabListener(this);
    Tab publicprofiletab = getSupportActionBar().newTab().setText("La Storia").setTabListener(this);
    Tab communitytab = getSupportActionBar().newTab().setText("Creazioni").setTabListener(this);

    getSupportActionBar().addTab(friendstab);
    getSupportActionBar().addTab(publicprofiletab);
    getSupportActionBar().addTab(communitytab);

    //This helps in providing swiping effect for v7 compat library
    tabsviewPager.setOnPageChangeListener(new OnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {
            // TODO Auto-generated method stub
            getSupportActionBar().setSelectedNavigationItem(position);

        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
            // TODO Auto-generated method stub

        }
    });

}

   // Intent creat = new Intent(getApplicationContext(), collezioni.class);
    //startActivity(creat);

public void imageClick (View view) {
    Intent creat = new Intent(getApplicationContext(),collezioni.class);
    startActivity(creat);
}

@Override
public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
    // TODO Auto-generated method stub

}

@Override
public void onTabSelected(Tab selectedtab, FragmentTransaction arg1) {
    // TODO Auto-generated method stub
    tabsviewPager.setCurrentItem(selectedtab.getPosition()); //update tab position on tap
}

@Override
public void onTabUnselected(Tab arg0, FragmentTransaction arg1) {
    // TODO Auto-generated method stub

}
}

A: I'm sorry...but i have solved using switch case statement.
I didn't know how use it, but triyng i'm was able to use.
I hope this will be helpful
public void imageClick (View view) {
    ImageView imgStaff = (ImageView) findViewById(R.id.imgStaff);
    ImageView imgCat = (ImageView) findViewById(R.id.imgCatalog);
    switch (view.getId()){

        case(R.id.imgCatalog):
            Intent creat = new Intent(getApplicationContext(),collezioni.class);
            startActivity(creat);

        case(R.id.imgStaff):
                Intent mTouch = new Intent(getApplicationContext(),MultiTouchAct.class);
                startActivity(mTouch);

    }

}


text:
Q: Why Button click event works in all version but does not work in Pie? All my old apps are working fine in android. But during recent testing in the Android emulator with android Pie, I am stuck in the first page. I am not able to click. It shows on email field "Unverified Post".
I don't know what it means. So does anybody know what was updated in PIE?
I have checked the code but I can't find where the problem is.
And, what is "Unverified Post" that shows on email Textview?
Code:
findViewById(R.id.submit_btn).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        findViewById(R.id.submit_btn).setEnabled(false);
        register();
    }
});

Image

java
validateform()

@JohnJoe in there validateform() is
private boolean validateForm() {
    boolean result = true;
    if (TextUtils.isEmpty(firstNameEditText.getText().toString())) {
        firstNameEditText.setError("Required");
        result = false;
    } else if (firstNameEditText.getText().toString().length() < 3) {
        firstNameEditText.setError("Please enter first name");
        result = false;
    } else {
        firstNameEditText.setError(null);
    }
    if (TextUtils.isEmpty(lastNameEditText.getText().toString())) {
        lastNameEditText.setError("Required");
        result = false;
    } else if (lastNameEditText.getText().toString().length() < 3) {
        lastNameEditText.setError("Please enter last name");
        result = false;
    } else {
        lastNameEditText.setError(null);
    }

    if (TextUtils.isEmpty(emailEditText.getText().toString())) {
        emailEditText.setError("Required");
        //result = false;
    } else if (!isValidEmail(emailEditText.getText().toString())) {
        emailEditText.setError("Please enter valid email");
       // result = false;
    } else {
       // emailEditText.setError(null);
    }
    return result;

A: thank you guys for clearing ways
Just Removed Current Email Validation and replace with another method! not found the right solution for the now.


text:
Q: Too Much Wait TIme So I was trying to use a procedure(with a parameter)...I asked the user for inputs and created a validate function to check the inputs and see if they are strings...I checked it but the outputs are taking too long to output. How do I fix this?
I tried:
# Create Validate function

def validate_input(LETTER):
  while True:
    try:
      if len(LETTER) == 0:
        pass
    except:
      if len(LETTER) >= 2:
        print('Sorry, please enter a single letter')
      if LETTER.strip().isdigit():
        print('Sorry, please enter a letter')
        break

#Ask for inputs

# Create function to validate input that returns true or false. If false then ask for input again.

first_char = input('Enter first character(lower cases) or press Enter: ')

validate_input(first_char)

second_char = input('Enter second character(lower cases) or press Enter: ')

validate_input(second_char)

third_char = input('Enter third character(lower cases) or press Enter: ')

validate_input(third_char)

fourth_char = input('Enter fourth character(lower cases) or press Enter: ')

validate_input(fourth_char)

fifth_char = input('Enter fifth character(lower cases) or press Enter: ')

validate_input(fifth_char)

But it came out to be:
Enter first character(lower cases) or press Enter: 2
And from there it takes too much time to say it it must be a string...
Thank you in advance!

A: the input() function in python always take the inputs as string, if you want to get integer as input then the following functions would be used => int(input())
it is not taking too long to execute it just a logical error in your code ;)
lets say the the input is "hello" so the len("hello") is 5
now , the input goes to the validation function(your function) first it starts with infinite while loop with no terminal condition and starts to checks the condition len(LETTER) == 0 whether it is true or false but it won't raise any exception so it won't go to the except block where the actual terminal condition is located(break) so its keep running forever.
hope it'll be helpful for you, thank you.


text:
Q: fflush(stdout) in eclipse build error: can't open output file I put fflush(stdout) in between printf and scanf as suggested in the Internet. However, I got the following build error:
Info: Internal Builder is used for build
g++ -O0 -g3 -Wall -c -fmessage-length=0
-o "src\\linkedlist.o" "..\\src\\linkedlist.cpp"
g++ -o linkedlist.exe "src\\linkedlist.o"
c:/mingw/bin/../lib/gcc/x86_64-w64-mingw32/8.1.0/../../../../x86_64-w64-
mingw32/bin/ld.exe: cannot open output file linkedlist.exe: Permission
denied
collect2.exe: error: ld returned 1 exit status

The IDE I am using is eclipse. Any suggestions on how to fix this problem?


text:
Q: It is possible to use a URL address that was used for another project excluded? I used a a URL address on a Google App Engine project that was deleted about a year ago but I need to use the same address again and it is no longer available. There is no way to get get it back? The address doesn't expire after a certain period?
Example:
my-project.appspot.com

A: Since you're looking for the appspot.com URL, which is based on the project ID, the answer would be No, because according to the documentation:

c. Accept the generated project ID or supply your own ID. This project
  ID is used as the App Engine application ID. Note that this ID can
  only be used once: if you subsequently delete your project, you won't
  be able to re-use the ID in a new project.


text:
Q: Is it wrong to use an action's payload inside a component with react-redux? I'd like to keep track of API requests that I make with react-redux. To do this I'd like to generate a request Id inside the action and pass that along to middleware and reducers through the payload. Then when I'm dispatching the action from my component I can capture the request Id and use it for updating the component as the request progresses.
Here's some example code
State
export interface State {
  [requestId: number]: Request;
}
export interface Request {
  status: string;
  error?: string;
}

Action
export function createRequest(): Action {
  return {
    type: "request",
    payload: {
      requestId: Math.random () // Make a random Id here
    }
  };
}

Reducer
export function createRequestReducer(state: State): State {
  return {
    ...state,
    ...{ state.payload.requestId: { status: "pending" } }
  };
}

Component
interface props {
  getRequestById: (id: number) => Request;
  createRequest: () => number;
}

const component = (props: testProps): JSX.Element => {
  const getRequestById = props.getRequestById;
  const [requestId, setRequestId] = useState(null);
  const [request, setRequest] = useState(null);

  useEffect(() => {
    if (requestId !== null) {
      setRequest(getRequestById(requestId));
    }
  }, [requestId]);

  return
The request status is {(request && request.status) || "Not started"}
;
}

function mapStateToProps(state: State) {
  return {
    getRequestById: (requestId: number): Request => {
      getRequestById(state, requestId)
    }
  };
}

function mapDispatchToProps(dispatch: Dispatch) {
  return {
    createRequest: (): number => {
      const action = createRequest();
      dispatch(action);
      return action.payload.requestId;
    }
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(component);

I expect this will work but it may be a massive anti pattern. Is this not advised and, if so, is there an alternative?

A: I think your approach works technically totally fine. Only "logically" it might make sense to make a some changes:
Yes, the "action" is something that is supposed to be sent to the reducer (and not used anywhere else, although there is technically no problem with that).
But what you can do:
1. separate action and values
Inside the action creator function, you can do whatever you want.
So you can create and use the action and the requestId seperately.
This is technically exact the same as what you did, but logically separated.
E.g.:
function createRequest(){
    const requestId = createUniqueId();
    const action = { type: "request", payload: { requestId: requestId } };
    return {
        requestId: requestId, // <-- request id independent of the action
        action: action,       // <-- action independent of the request id
    };
}

function mapDispatchToProps( dispatch: Dispatch ){
  return {
    createRequest: (): number => {
      const { requestId, action } = createRequest();
      dispatch( action );    // <-- action independent of the request id
      return requestId;      // <-- request id independent of the action
    }
  };
}

2. "action dispatchers"
I (and apparently others as well) like to use what I call "action dispatchers".
This is an extra step and more code, but I think when you got used to this concept, it eliminates any doubts where code like that has to be put.
E.g.:
// Create the action, and nothing else:
const createRequestActionCreator = function( requestId ){
  return { type: "request", payload: { requestId: requestId } };
};

// Preper some data needed to create the action:
const createRequestActionDispatcher = function( dispatch ){
  return function(){
    const requestId = createUniqueId();
    dispatch( createRequestActionCreator( requestId ) );
    return requestId;
  };
};

//
function mapDispatchToProps( dispatch: Dispatch ) {
  return {
    createRequest: (): number => {
      const requestId = createRequestActionDispatcher( dispatch )();
      return requestId;
    }
  };
}

2.a
Additionally you could pass such an "action dispatcher" directly as a prop, if you want.
In this case it basically replaces your function in mapDispatchToProps, but is reusable, e.g.:
function mapDispatchToProps( dispatch: Dispatch ) {
  return {
    createRequest: createRequestActionDispatcher( dispatch ),
  };
}

2.b
Some people prefer to use a fat-arrow-function here, which I find more confusing, not less, but it looks cleaner as soon as you got used to that pattern:
const createRequestActionDispatcher = (dispatch: Dispatch) => (maybeSomeValue: MyType) => {
    const requestId = createUniqueId();
    dispatch( createRequestActionCreator( requestId ) );
    return requestId;
};

Remark:
I generally prefer to be consistent, for which I should always (or never) use these "action dispatchers",
but I found that most of the time I don't need one, but sometimes I find them very useful.
So I'm actually using dispatch( myAction ) in some places and myActionDispatcher(value)(dispatch) in others.
I don't like that, but it works well, and I don't have a better idea.


text:
Q: higher-level independence of three or more correlated RVs I'm hoping for some help in nailing down a vague idea about independence. It starts with finding the expectation of a product of three RVs (or more, but I'll stick to three for now). These are not necessarily independent, but we know all the pairwise covariances. This is enough information to predict the expected value of the product of any pair, but it is not enough to predict the expected value of the product of all three, as can be shown by an example. Let A, B, and C be three Bernoulli RVs: each takes on the values 0 and 1 with equal probability. Further, assume that they are independent. Obviously $\mathbb{E}\left[ABC\right]=1/8$. Define a new variable $Z=A(1-B)+B(1-A)$, that is, $Z=1$ iff $A\ne B$. Z is independent of A, and it is independent of B. In fact, all the pairwise joint distributions of ${A,B,C}$ are identical to the pairwise joint distributions of ${A,B,Z}$. The joint distributions of the three taken together are different, of course. And, in particular, $A=B=Z=1$ never happens, and $\mathbb{E}\left[ABZ\right]=0\ne \mathbb{E}\left[ABC\right]$. This shows that knowledge of all the pairwise joint distributions of three or more RVs is not sufficient to predict the expected value of their product.
Is there a way, for Bernoulli RVs or more generally, to define the distribution that has specified single-variable (p's for each variable) and pairwise (correlations for each pair) statistics, but has no higher-level correlations? I know that I'm being vague--what do I mean by "higher-level correlations"? But that's the problem: I can't think how to define it. The idea is something like conditional independence, but I haven't been able to make it precise.

A: Higher order correlations are called joint cumulants or semi-invariants. They can be expressed in terms of joint moments. If you want one of the cumulants to be equal to zero, that gives you an algebraic equation on moments. A joint moment of Bernoulli r.v.'s equals the probability that the r.v.'s involved are all equal to $1$. Combining all that one obtains a system of algebraic equations on the set of probability distributions on the binary cube. That needs to be solved. So, the more cumulants you want to be zero, the more equations you have, so the system may easily be overdefined.


text:
Q: React-navigation: how to have different headerBackTitles within a single StackNavigator I am using react-navigation for my react-native app. I have read the docs on headerBackTitle, but I can't figure out how to set different headerBackTitle for navigating from different screens in the stack.
When navigating from EditProfile to MyProfile, I want the headerBackTitle: to say Cancel.
When navigating from Comments to MyProfile, I want the headerBackTitle to say Go back.
Currently, going from both Comments and EditProfile to MyProfile say Cancel. How do I accomplish this?
const MyProfileStack = createStackNavigator({
  MyProfile: {
    screen: profile,
    navigationOptions: {
      headerTitle: "My Profile",
      headerBackTitle: 'Cancel'
    }
  },
  Comments: {
    screen: comments,
    navigationOptions: {
      headerTitle: "Comments"
    },
  },
  EditProfile: {
    screen: editProfile,
    navigationOptions: {
      headerTitle: "Edit Profile"
    },
  }
})

A: Another way of doing it, is by making your own header, like so

Comments.js

class Comments extends React.Component{
 render(){
  return(
     <View style={{flex:1}}>
      <View style={styles.header}>
        <Text onPress={() => this.props.navigation.goBack(null)}>Go Back</Text>
        <Text>Comments</Text>
      </View>
     </View>
     )
    }
   }

EditProfile.js

class Comments extends React.Component{
     render(){
      return(
         <View style={{flex:1}}>
          <View style={styles.header}>
            <Text onPress={() => this.props.navigation.goBack(null)}>Cancel</Text>
            <Text>Edit Profile</Text>
          </View>
         </View>
         )
        }
       }


text:
Q: Pycharm Database for SQlite converts date and datetime columns to long integers
I am trying to export this database but whenever I try to make a row and add a date Pycharm database turns it into an integer and it cant export

A: According to the issue on the JetBrains issue board, this seems to be a common problem. But can be solved by setting the date_class in the SQLite driver.
In the "Database" tool window, open the Data Source properties window "Data Sources and Drivers" and select the tab "Drivers" > the entry "SQLite" > tab "Advanced" > Set date_class to value TEXT.


text:
Q: Number of the circles of radius $\frac{\pi}{4}$ in the circle of radius $\pi$ . QUESTION:
How many circles of radius $\frac{\pi}{4}$ can be drawn within a circle of radius $\pi$ such that they do not intersect one another?
I have seen a solution where it is stated to use the expression below :

$$\sin \frac{360}{2n}=\frac{\frac{\pi}{4}}{\pi-\frac{\pi}{4}}$$

where $n$=number of circles possible.
But I'm unable to understand the geometry behind it.

A: The answer is eleven (proved by Melissen) [thanks @Rushabh Mehta]
(And why is this problem posed with the radii in multiples of $\pi$ rather than just $1$?)

A:

I previously answered this question, of course,
 I did not prove that 11 is maximal but
 I showed OP that at least you can make 11 circles inside and  9 circles touching the outer circle
but @rushabhamehta said that it is not possible to draw 9 circles touching inner part of the outer circle.
So I decided to plot them one by one and you can clearly see that drawing 9 circles touching the inner part of the outer circle is possible
however here I am not claiming that the circles themselves must touch they may not touch themselves.
Then I decided to draw 2 extra inner circles which also seems easy
and by looking at the picture it is clear that you can not draw an extra circle, however, I did not prove it.


text:
Q: floppy0: no floppy controllers found I am currently trying some Ubuntu-Server based projects and want to use some floppies for it. But after installing Ubuntu-server16.04 LTS on my machine, I got an error on start-up:
floppy0: no floppy controllers found

But I can't solve the problem... afaik there could be an kernel error, but I just started using Ubuntu and am just at the beginning.

A: *

*sudo gedit /lib/udev/rules.d/80-udisks.rules (in my Xubuntu 16.04 - 80-udisks2.rules)

*search strings and replace them with 0 to 1
# PC floppy drives
 #
 KERNEL=="fd*", ENV{ID_DRIVE_FLOPPY}="0"
# USB floppy drives
 #
 SUBSYSTEMS=="usb", ATTRS{bInterfaceClass}=="08",
 ATTRS{bInterfaceSubClass}=="04", ENV{ID_DRIVE_FLOPPY}="0"

*Create folger

sudo mkdir /media/floppy
sudo chmod 777 /media/floppy

*sudo gedit /etc/fstab

*add a line to the end:
/dev/fd0 /media/floppy auto rw,user,noauto,exec,utf8 0 0

*sudo gedit /etc/modules

*add a line to the end:
floppy

*then either reboot the system or perform

sudo modprobe floppy
Edit: I supplemented my answer

*

*check if the floppy module is loaded:

lsmod | grep -i floppy
If it returns floppy then you have the floppy module loaded

*

*load the floppy module:

sudo modprobe -v floppy
lsmod | grep -i floppy

*

*Try adding your username in the floppy group:

sudo adduser $USER floppy

*

*Try

udisks --mount /dev/fd0
PS. Floppy WILL NOT auto launch a window when inserted, they were made before that! You will need to go to nautilus and double click on it. You need to unmount before inserting a new floppy disk. Your next floppy you insert won't mount.

*

*another way:

udisks --mount /dev/fd0
if not at all - try to install fdutils
and fdmount seems useful. Try: sudo fdmount -l
more ways I do not know and have not tried:)

A: After I tried all your suggestions yesterday, I finally found an entry in my BIOS, which said: Floppy Legacy: Disabled. Changed it to 1.44 MB, now everything is fine.


text:
Q: Getting all text in logs between two timeframes Pls help me getting all text in logs between two timeframes.
example of log file
2014-10-23 00:24:37 .....some data
2014-10-23 00:25:37......some data
2014-10-23 00:26:37.......some data
Error code HO5006
2014-10-23 00:27:37...some data

I am using below awk command to get the text between 2014-10-23 00:25:37 & 2014-10-23 00:27:37:
awk '$0>=from && $0<=to' from="$1" to="$2" logfile

Output which i am getting is
2014-10-23 00:26:37.......some data
2014-10-23 00:27:37...some data

But my expected output shld be
2014-10-23 00:26:37.......some data
Error code HO5006
2014-10-23 00:27:37...some data

A: There may be a more elegant method in awk to do this, but this will do the trick:
awk 'BEGIN {capture="no"};{if ($0>=from) capture="yes"} {if (capture=="yes") print $0} {if ($0<=to) capture="no"};' from="$1" to="$2" logfile

This will set capture to "no" until it it finds a line that is greater than or equal to your from, it toggles capture to "yes", then prints lines until it the to variable is hit.

A: The problem is that Error code HO5006 string is greater then the date string (almost any string starting with no number). So the lines not matching with date pattern should be printed if the from date is passed.
So my suggestion is:
awk --posix -v from="2014-10-23 00:26:37" -v to="2014-10-23 00:27:37" '
  {dt=$1" "$2}
  dt~/^[0-9]{4}-/{if(dt>=from)++s;if(dt>to)exit}
  s
' << EOT
2014-10-23 00:24:37 .....some data
2014-10-23 00:25:37 ......some data
2014-10-23 00:26:37 .......some data
Error code HO5006
2014-10-23 00:27:37 ...some data
2014-10-23 00:28:37 ...some data
2014-10-23 00:29:37 ...some data
EOT

(date pattern can be made more exact if really needed)
Output:
2014-10-23 00:26:37 .......some data
Error code HO5006
2014-10-23 00:27:37 ...some data

I hope this helps!