text:
Q: Why is this frame morphism equivalent to a preframe morphism Situation: I am trying to understand the proof of proposition 5.2 of Preframe Presentations Present by Johnstone and Vickers. The proposition states that the lower and upper power locale constructions commute.
Definitions: Let $D$ be a locale and write $\Omega D$ for the corresponding frame. The upper and lower power locale are defined via
$$
\Omega P_U D = \operatorname{Fr}\langle \Box a \; (a \in \Omega D) \; \mid \Box \text{ preserves finite meets and directed joins} \rangle
$$
and
$$
\Omega P_U D = \operatorname{Fr}\langle \Diamond a \; (a \in \Omega D) \; \mid \Diamond \text{ preserves all joins} \rangle.
$$
As a reminder: a frame homomorphism preserves finite meets and all joins, a sup-lattice is a poset with all joins and a sup-lattice homomorphism preserves all joins. Preserving all joins is equivalent to preserving both finite and directed joins.
In the proof:
In order to show that $\Omega P_UP_L D = \Omega P_LP_UD$ the authors define maps
$$
\Omega\theta : \Omega P_LP_UD \to \Omega P_UP_LD : \Diamond\Box a \mapsto \Box\Diamond a
$$
and similar the other way round. Let's focus on the proof that $\Omega\theta$ is a frame homomorphism.
Question 1: The map $\Omega\theta$, the authors claim, must be equivalent with a sup-lattice morphism $\eta : \Omega P_U D \to \Omega P_UP_L D : \Box a \mapsto \Box\Diamond a$. Why is this true? (I can see that the generators of both $\Omega P_U D$ and $\Omega P_LP_UD$ correspond. Maybe we can view $\Omega\theta$ as the concatenation $\eta \circ \pi$, where $\pi : \Diamond\Box a \mapsto \Box a$, but would this be well-defined?)
Question 2: The authors proceed to show that $\Box a \mapsto \Box\Diamond a$ preserves directed joins, and then conclude that $\Omega\theta$ must be a frame homomorphism. Don't we need to show that $\Omega\theta$ also preserves finite meets and finite joins? (Or is this "easy"?)

A: For any locale X the frame $\Omega P_L X$ is the free frame on $\Omega X$ qua suplattice; that is, frame homomomorphisms from $\Omega P_L X$ to $\Omega Y$ are in bijection with suplattice homomorphisms $\Omega X \rightarrow \Omega Y$. The bijection, one way round, is pre-composition with $\diamond_X : \Omega X \rightarrow \Omega P_L X$.
To get the $\theta$ of the proof we are looking at the case $X=P_U D$ and $Y =\Omega P_L P_U X$. The map $\Omega \theta$ corresponds, under the bijection, to a suplattice map $\eta: \Omega P_U D \rightarrow \Omega P_U P_L D$.
Now by Johnstone's coverage theorem we know that $\Omega P_U D$ is the free suplattice on $\Omega D$ qua directed joins. So to define a suplatice homomorphism from $\Omega P_U D$ to any $\Omega Y$ we must defined a directed join preserving map from $\Omega D$ to $\Omega Y$ (no need to preserve meets). The map that they use to define $\eta$ is $\square_X : \Omega X \rightarrow \Omega P_U X$ followed by $\diamond_{P_U X} : \Omega P_U X \rightarrow \Omega P_L P_U X$ (both of these preserve directed joins so their composition preserves directed joins).
Follow much the same logic to define a frame homomorphism in the other direction, reversing the finitary data; though you'll need the preframe coverage theorem rather than Johnstone's coverage theorem. That you have an isomorphism follows by the naturality of the bijections involved.
Comment
Not only do the upper and lower power locale functors commute but so too do their monads. This means that another monad can be defined as their composition, in either order: we get the double power locale monad whose points can be given an entirely categorical characterization as certain natural transformations.
It's great that someone is looking at this proof as it is the birth place of the double power locale monad, in my thinking at least. These power monads came from computer science as power domains but they can also be used to characterise geometric morphisms so potentially have a deep role in mathematics.


text:
Q: Is there a way to get all IP addresses of YouTube to block it with Windows Firewall? I want to programme my own anti-distraction tool. I can not / do not want to use the hosts file or third-party apps. When using IPsec or Windows Firewall, it only accepts IP addresses. There is
youtube.[264 TLD]
www.youtube.[264 TLD]
subdomains.youtube.[264 TLD]
Apparently, there is no way any more to get a complete list of YouTube sub domains.
Is there a way to somehow obtain all YouTube IP addresses and block them on the IP address level other than using brute force subdomain pinging?

A: If you have your own DNS server you can block domains from resolving. Here is a guide to block domains in a BIND DNS server.
To get all the IP addresses there isn't any way. You can install dig. It's available on Linux, but not on Windows.
Then it is to time enter dig youtube.com. It'll show you all the resolved IP addresses from the DNS cache.
See my result of dig youtube.com A:
; <<>> DiG 9.7.0-P1 <<>> youtube.com A
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 13442
;; flags: qr rd ra; QUERY: 1, ANSWER: 16, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;youtube.com.                   IN      A

;; ANSWER SECTION:
youtube.com.            83      IN      A       74.125.235.47
youtube.com.            83      IN      A       74.125.235.46
youtube.com.            83      IN      A       74.125.235.45
youtube.com.            83      IN      A       74.125.235.44
youtube.com.            83      IN      A       74.125.235.43
youtube.com.            83      IN      A       74.125.235.42
youtube.com.            83      IN      A       74.125.235.41
youtube.com.            83      IN      A       74.125.235.40
youtube.com.            83      IN      A       74.125.235.39
youtube.com.            83      IN      A       74.125.235.38
youtube.com.            83      IN      A       74.125.235.37
youtube.com.            83      IN      A       74.125.235.36
youtube.com.            83      IN      A       74.125.235.35
youtube.com.            83      IN      A       74.125.235.34
youtube.com.            83      IN      A       74.125.235.33
youtube.com.            83      IN      A       74.125.235.32

;; Query time: 0 msec
;; SERVER: 127.0.0.1#53(127.0.0.1)
;; WHEN: Sat Feb 18 22:26:58 2012
;; MSG SIZE  rcvd: 285

A: This may help: Obtain Google IP address ranges
Which points to:
https://www.gstatic.com/ipranges/goog.json

A: The way to find all the IP addresses associated with a URL is first to find the AS Number. You can get it in Networktools: asinfo Reverse IP Lookup, Whois, Ping, RBL Check, DNS Records, Traceroute, Host information.
For YouTube, get it on Networktools: asinfo youtube.com
There you get the AS number (ASN):

Primary ASN          : 15169

Now, type this in the terminal:
whois -h whois.radb.net -- '-i origin AS15169' | grep ^route

And there you will get all the IP addresses. The list is long, but you can find similar addresses that can be grouped in a subnet.

A: The YouTube current address list is:

*

*64.18.0.0/20

*64.233.160.0/19

*66.102.0.0/20

*66.249.80.0/20

*72.14.192.0/18

*74.125.0.0/16

*173.194.0.0/16

*207.126.144.0/20

*209.85.128.0/17

*216.58.208.0/20

*216.239.32.0/19

redpajama_set_name: RedPajamaStackExchange


text:
Q: recommended , suggests, mandatory
The tribunal recommends that the dept reassesses the appellant within 18 months.

Is this obligatory, a suggestion or  mandatory?
Is the department obligated to reassess within the limited time?
Or is it just a suggestion and the department can reassess anytime, even after 6 years?

A: A recommendation is a suggestion. Unlike an order or direction, it does not have to be obeyed. If a court (tribunal) decides that something must be done, and has the power to require it, then it issues an order. Failure to comply could lead to a penalty. If the court has no power to issue an order, or does not wish to, it may make a recommendation, with which the recipients are free to comply or not.

recommendation
noun
advice about what is the best thing to have or do

While we are not free to disregard an order, we can ignore advice.
Recommendation

A:
recommended , suggests, mandatory Is the department obligated to reassess within the limited time?
or is it just a suggestion? & the department can reassess anytime after that recommended time frame. even if the reassessment is after 6 ;years of the time
   frame?

Unfortunately due to comments I have had to add more and more technical detail, So to summarise before presenting my Answer.
The question references an appellant. The decision has therefore been made and appealed against and upheld. So there is no doubt about the decision. A tribunal is not a court but is a legal institution so the definition of Recommended is the legal one. LEGAL DICTIONARY It is also worth noting that in some Tribunals recommendations can only be made in favour of the claimant. So we are looking at the "Dept" as the receiver of the recommendation, which is the way it reads. The inclusion of a time limit suggests the Recommendation is binding or time limit would not be needed.

Example A memorandum of appeal shall be presented in the Form annexed to these rules by the Appellant

My Answer
Obviously we have not been given all the facts.

According to C.E.D. the meaning of recommended; suggested an action that should be done:

So yes in a grammatical sense this needs to be complied with especially as it has been decided by a Tribunal

Legal; Recommendation Definition: Legal Dictionary
  Advice or counsel which although presented as such, the recipient is free to take or leave, or which may be binding in the context.

In this case "The tribunal recommends that the dept reassesses the appellant within 18 months" must be the second legal definition " binding in the context" or the application of a time limit would be superfluous
To put a little more strongly and in layman's terms. You would have to be either very arrogant, ignorant or stupid to not comply with a Tribunal's recommendation. Especially after an appeal.
You will probably find it irrelevant anyway as most Tribunal recommendations usually end up in statute. It is interesting to read the EU's definition of Recommendations.

recommendation Free Legal a form of Act of the EUROPEAN UNION that has no binding force. It has been held that recommendations should still be taken into account by the national courts, especially if the recommendation assists with interpretation of some European law. Nonetheless, it is not possible to have them reviewed nor to seek a preliminary ruling upon them.

So here we have a recommendation that initially seems to have no power. However, it is fact extremely powerful. Courts should comply with the recommendation and the recommendation has no process of review or interpretation.
However as stated earlier these comments are made without context.

recommended Cambridge English Dictionary adjective suggested as being good or suitable for a particular job or purpose, or suggested as an action that should be done:
tribunal noun Cambridge English Dictionary a special court or group of people who are officially chosen, especially by the government, to examine (legal) problems of a particular type:


text:
Q: Expected Expression Error Xcode I am running into one error when building my project and I can't seem to find a fix anywhere. The error is showing up on this line: ;:CGFloat = info[UIKeyboardAnimationDurationUserInfoKey] as! CGFloat. Here is my code:
func keyBoardWillShow(notification: NSNotification) {
    let info:NSDictionary = notification.userInfo!
    let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue()

    let keyboardHeight:CGFloat =  keyboardSize.height - 40

    // Error is on this line
    _;:CGFloat = info[UIKeyboardAnimationDurationUserInfoKey] as! CGFloat

    let contentInsets: UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardHeight, 0.0);
    self.tableView.contentInset = contentInsets
    self.tableView.scrollIndicatorInsets = contentInsets
}

A: The line where you are getting this problem has syntactical issues. Notice:
_;:CGFloat = info[UIKeyboardAnimationDurationUserInfoKey] as! CGFloat

First, you actually have two statements there, as semicolons break lines. So:
_;
:CGFloat = info[UIKeyboardAnimationDurationUserInfoKey] as! CGFloat

If you break the lines like this you'll now get two errors. The first one says '_' can only appear in a pattern or on the left side of an assignment, which makes sense because an underscore by itself accomplishes nothing. You should just delete this part.
The second line is missing a declaration, so the compiler is not being capable of parsing that line into anything that it understands, hence Expected expression. You'd want to store the result from that expression somewhere, and you need a declaration for that. You can to this:
let someName:CGFloat = info[UIKeyboardAnimationDurationUserInfoKey] as! CGFloat

Adjust someName to fit your needs. I'm assuming that you need the result from that expression for something, even though I don't see it used after the assignment. If you don't need it, just consider removing the whole expression.

A: It's because the line of code:
_;:CGFloat = info[UIKeyboardAnimationDurationUserInfoKey] as! CGFloat

is not a valid line of code.


text:
Q: jqGrid filterToolbar(): Cannot read property 'length' of undefined So I'm trying to upgrade the jquery on a site i'm working on from 1.4 to 3.3, and I'm having issues with my jqgrid. I have a html table that i'm converting to a jqgrid using the tableToGrid function, and everything is fine until I try and add the filterToolbar.
I'm also using jqGrid 5.3.1. Here's a snippet of the code

         Item
Number
         Order
Number
         WH Status
         Kit SKU
         Purchase
Source
         Store
         Effective
Date
         Production
Code
         Factory
Code
         Smart
Serial Number
         Actual
Serial Number
         Serial
Date
         Serial
Factory Code
         Registration
Date
         User ID
         Expiration
Date
         Warranty
Item
         Warranty
Type
         Warranty
Duration
         Edit
         Info

         S3101
         10000601-00
         Open Order

         F156

         08/29/18

         08/29/18
         sheldoN@fdm4.com
         03/05/20

         Make-it-right
         554

My grid still displays, the sorting/sizing/etc works, it just won't display the filter toolbar

A: Your code works perfect. You will need to check other things in it.
Here is jsfiddle of your code.
Bellow part of code
var _lastwarrantyrow;
tableToGrid('#warrantytable',{autowidth: true, forcefit: true  });
$('#warrantytable').each(function(){$('#warrantytable').jqGrid('setColProp','Edit',{search: false});
$('#warrantytable').jqGrid('setColProp','Edit',{sortable: false});
$('#warrantytable').jqGrid('setColProp','Info',{search: false});
$('#warrantytable').jqGrid('setColProp','Info',{sortable: false});
$('#warrantytable').jqGrid('setColProp','ItemNumber',{searchoptions: {clearSearch: false}});


text:
Q: EasyApache 4 Migration Issue One of server is hosting several domains with their wepages mostly in php. Server was running eayapache3 with php5.5. One of the domain asked to enable php5.6 recently. So we migrated the server from easyapache3 to easyapache4. Server hit full disk space today & apache stopped serving. Now we removed old backups to make space as a temporary measure. Now some domains are loading, and some are displaying http 500 error.
Please can someone guide us?
FYI: I've restarted all relevant services, especially http & mysql.

A: you need to check error_log for any messages being logged when you try to load the domain that shows error 500.
Issue tail -f /usr/local/apache/logs/error_log, and then try to load the domain, and see what messages are being logged when you are doing that, you might get some messages related to permissions, or missing php extensions.
If you have migrated from EasyApache 3 to EasyApache 4, then it is likely possible that some php extensions were not installed in EasyApache 4


text:
Q: Load Order: OrderRepository vs OrderFactory What is the difference between loading an order from OrderRepository & OrderFactory?

A: You need to understand the factory and repository patterns.
Factories are service classes that instantiate non-injectable classes, that is, models that represent a database entity. They create a layer of abstraction between the ObjectManager and business code.
Repositories are responsible for reading and writing your object information to an object store. In the Repository pattern, the data objects, the database logic, and the business logic connect to each other using interfaces.

Tip : Use repositories where possible and prefer them over factories.


text:
Q: how do I get my paint program to contenue after user inputs wall info in python 3.4 Im writing a paint program that's supposed to determine the cost of painting the walls of a shed with a rectangular floor. Im supposed to assume the shed has no windows and that the paint cost is $40 per gallon. One gallon covers 300 square feet. Im suppose to prompt the user to enter the dimensions of the shed. Im also supposed to use a function named paint_cost that takes the users input as arguments and returns the cost of painting the walls of the shed. Finally I have to express the cost in currency format.
I can get up to the point to were the user enters the dimensions but after they enter them and hit enter it goes to the >>> Im trying to figure out what ive done wrong here and how to fix it to run correctly.
def main():

    wall1 = float(input('enter length of wall 1: '))
    wall2 = float(input('enter length of wall 2: '))
    wall3 = float(input('enter length of wall 3: '))
    wall4 = float(input('enter length of wall 4: '))
    wall_height = float(input('enter height of walls: '))
    combine_walls1 = wall1 + wall2
    combine_walls2 = wall3 + wall4

def paint_cost(combine_walls1, combine_walls2):
    combined_walls = combine_walls1 + combine_walls2
    Square_foot = combined_walls * wall_height
    gallon = Square_foot / 300
    cost = gallon * 40

    print('total: $', format(paint_cost, ' ,.2f'))

main()

A: *

*paint_cost is not called.

*paint_cost should receive wall_height.

*Print cost instead of paint_cost in paint_cost.

def main():
    wall1 = float(input('enter length of wall 1: '))
    wall2 = float(input('enter length of wall 2: '))
    wall3 = float(input('enter length of wall 3: '))
    wall4 = float(input('enter length of wall 4: '))
    wall_height = float(input('enter height of walls: '))
    combine_walls1 = wall1 + wall2
    combine_walls2 = wall3 + wall4
    paint_cost(combine_walls1, combine_walls2, wall_height)  # 1 + 2

def paint_cost(combine_walls1, combine_walls2, wall_height):  # 2
    combined_walls = combine_walls1 + combine_walls2
    Square_foot = combined_walls * wall_height
    gallon = Square_foot / 300
    cost = gallon * 40
    print('total: $', format(cost, ' ,.2f'))  # 3

main()


text:
Q: Retrofit warning with Proguard I turned proguard on in my android project and got the warning below. Searched on Google but couldn't find much info.

Warning:retrofit.Platform$Java8: can't find referenced class
  org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement

I've put the retrofit2 proguard rules in my project.
-dontwarn retrofit2.**
-keep class retrofit2.** { *; }
-keepattributes Signature
-keepattributes Exceptions

-keepclasseswithmembers class * {
    @retrofit2.http.* <methods>;
}

A: Use following proguard rules for Retrofit 2.3.0 and okhttp 3.8.0
-dontnote retrofit2.Platform
-dontwarn retrofit2.Platform$Java8adapters.
-keepattributes Signature
-keepattributes Exceptions
-dontwarn org.xmlpull.v1.**
-dontwarn okhttp3.**
-dontwarn okio.**
-dontwarn javax.annotation.**

A: change it like this:
-dontwarn okio.**
-dontwarn retrofit2.Platform$Java8

Retrofit page has noted about this proguard build,when running on Java 8 VMs:
Why this happens?
Reason is:
Compiler tries to reference Java 8 classes,When u don't mention it through Proguard,After u explicitly mention it,Java 8 classes won't be used.
For example
Package java.nio.* of Java 8 isn't available on Android and will be never called


text:
Q: "After power is switched on router" - preposition or a part of the verb? In the manual of my router, I have found this sentence. I am quite unsure as to what it means and if it is correct

After power is switched on router XYZ starts internal wifi network.

A: Is this an accurate description of what happens when you flip the switch:  "After [the] power is turned on, [then] Router XYZ starts [the] internal wifi network"?
If so, then "on" is an adverb of position, telling where the switch is set.


text:
Q: mutation error, Unknown argument \"barcode\" on field \"createProduct\" of type \"Mutation\" - django I am doing tutorials online and trying to make mutation works on graphql but I kept on getting errors which I have no idea what where the real error comes from and how to start debugging where I have done wrong.
looking at this youtube for mutation
https://www.youtube.com/watch?v=aB6c7UUMrPo&t=1962s
and the graphene documentation http://docs.graphene-python.org/en/latest/types/mutations/
I noticed that because of different graphene version, that is why I have reading the documentation instead of following exactly as the youtube
I got things setup but then couldn't get it to work, when I execute the mutation query I get error.
I have a model like this.
class Product(models.Model):
    sku = models.CharField(max_length=13, help_text="Enter Product Stock Keeping Unit", null=True, blank=True)
    barcode = models.CharField(max_length=13, help_text="Enter Product Barcode (ISBN, UPC ...)", null=True, blank=True)

    title = models.CharField(max_length=200, help_text="Enter Product Title", null=True, blank=True)
    description = models.TextField(help_text="Enter Product Description", null=True, blank=True)

    unitCost = models.FloatField(help_text="Enter Product Unit Cost", null=True, blank=True)
    unit = models.CharField(max_length=10, help_text="Enter Product Unit ", null=True, blank=True)

    quantity = models.FloatField(help_text="Enter Product Quantity", null=True, blank=True)
    minQuantity = models.FloatField(help_text="Enter Product Min Quantity", null=True, blank=True)

    family = models.ForeignKey('Family', null=True, blank=True)
    location = models.ForeignKey('Location', null=True, blank=True)

    def __str__(self):
        return self.title

I have this for my Product schema
class ProductType(DjangoObjectType):
    class Meta:
        model = Product
        filter_fields = {'description': ['icontains']}
        interfaces = (graphene.relay.Node,)

class CreateProduct(graphene.Mutation):
    class Argument:
        barcode = graphene.String()

    # form_errors = graphene.String()
    product = graphene.Field(lambda: ProductType)

    def mutate(self, info, barcode):
        product = Product(barcode=barcode)
        return CreateProduct(product=product)

class ProductMutation(graphene.AbstractType):
    create_product = CreateProduct.Field()

class ProductQuery(object):
    product = relay.Node.Field(ProductType)
    all_products = DjangoFilterConnectionField(ProductType)

    def resolve_all_products(self, info, **kwargs):
        return Product.objects.all()

global schema looks like this
class Mutation(ProductMutation,
               graphene.ObjectType):
    pass

class Query(FamilyQuery,
            LocationQuery,
            ProductQuery,
            TransactionQuery,

            graphene.ObjectType):
    # This class extends all abstract apps level Queries and graphene.ObjectType
    pass

allGraphQLSchema = graphene.Schema(query=Query, mutation=Mutation)

as for trying out the querying...this is my query
mutation ProductMutation {
  createProduct(barcode:"abc"){
    product {
      id, unit, description
    }
  }
}

error returned
{
  "errors": [
    {
      "message": "Unknown argument \"barcode\" on field \"createProduct\" of type \"Mutation\".",
      "locations": [
        {
          "column": 17,
          "line": 2
        }
      ]
    }
  ]
}

Can someone please give me a hand on what I should try and do?
Thanks in advance for any help

A: Figured my own problem.
There are three things, which are Argument should be Arguments and under the mutate function, I should use a regular django create model so from product = Product(barcode=barcode) into product = Product.objects.create(barcode=barcode) last but not least class ProductMutation(graphene.AbstractType): should be class ProductMutation(graphene.ObjectType):
so the code should be
class ProductType(DjangoObjectType):
    class Meta:
        model = Product
        filter_fields = {'description': ['icontains']}
        interfaces = (graphene.relay.Node,)

class CreateProduct(graphene.Mutation):
    class Arguments:    # change here
        barcode = graphene.String()

    product = graphene.Field(lambda: ProductType)

    def mutate(self, info, barcode):
        # change here
        # somehow the graphene documentation just state the code I had in my question which doesn't work for me.  But this one does
        product = Product.objects.create(barcode=barcode)
        return CreateProduct(product=product)

class ProductMutation(graphene.ObjectType):  # change here
    create_product = CreateProduct.Field()

class ProductQuery(object):
    product = relay.Node.Field(ProductType)
    all_products = DjangoFilterConnectionField(ProductType)

    def resolve_all_products(self, info, **kwargs):
        return Product.objects.all()


text:
Q: Скрипт для базы данных php 1) Есть база данных в ней есть поля id title foregin
2) в title перечислены отечественные машины и иностранные
3) иностранные машины записаны в таблице на английском языке, отечественные на русском
4) в иностранных машинах foregin должен быть 1, а в отечественных 0
4) как мне в записи с иностранными машинами поместить foregin 1

A: Регулярным выражением проверьте, содержаться ли латинские символы.
update mytable set `foregin` = 1 where `title` REGEXP '[a-z\s\-]+';


text:
Q: Return only single column from Laravel hasOne relation I'm creating custom form fields and in one table I save the field types, ex:
CustomFieldTypes
-------------------------------
id |    type     | common_name
-------------------------------
1  | v-text-area | TextArea
-------------------------------

Then in another table I save the details of the created custom field, ex:
PageCustomFields
----------------------------------------------------------
id | page_id | custom_field_type_id | label | is_required
----------------------------------------------------------
2  |    2    |          1           | Name  | false
----------------------------------------------------------

When I retrieve the PageCustomFields model I want to include ONLY the CustomFieldType's "type" field, I don't need the other field. How can I accomplish this? I've tried something like this in the PageCustomFields model but it doesn't seem to work:
public function customFieldType(){
   return $this->hasOne(CustomFieldType::class, "id", "custom_field_type_id")->select('type');
}

Any advise?
Thanks!
EDIT:
To clarify, I'd like the final PageCustomFields model attributes to look something like this after retrieving the CustomFieldTypes's type field:
PageCustomFields
------------------------------------------------------------------------------
id | page_id | custom_field_type | custom_field_type_id | label | is_required
------------------------------------------------------------------------------
2  |    2    |    v-text-area    |          1           | Name  | false
------------------------------------------------------------------------------

A: I think you relation should be:
public function customFieldType(){
   return $this->belongsTo(CustomFieldType::class, "custom_field_type_id");
}

I prefer to define relationships without constraints, then apply needed constraints in controllers' code:
$value=PageCustomField::with('customFieldType:id,type')->get();

note this will select only id(needed for loading) and type.
anyway , if you want it that way you can use addSelect:
 public function customFieldType(){
       return $this->belongsTo(CustomFieldType::class, "custom_field_type_id")->addSelect(['CustomFieldTypes.id','CustomFieldTypes.type']);
    }

and if yow want it as normal select without nesting you can join the tables:
$values=PageCustomField::join('CustomFieldTypes','PageCustomFields.custom_field_type_id','=','CustomFieldTypes.id')->select('CustomFieldTypes.*')
->addSelect(['type']);

A: Out of my head; does this work?

public function customFieldType(){
   return $this->hasOne(CustomFieldType::class, "id", "custom_field_type_id")->type;
}

If not, assuming you're using Vue as a front end, perhaps you could use Laravel Resources to filter out only the information you want.


text:
Q: Injecting ViewModel into the Fragment with Dagger 2, with parameters I'm trying to use a single factory for creating ViewModels with constructor parameters.
I followed the recommendation in one of the open dagger issues by @matejdro
https://github.com/google/dagger/issues/1273
But the injection  doesn't work.
I"m getting an error:"error: [Dagger/MissingBinding] kotlin.Lazy cannot be provided without an @Provides-annotated method."
Any idea how to resolve the issue?
I uploaded my created project to github: https://github.com/davida5/daggerViewModelBestPractice

A: That's pretty simple, you should be using dagger.Lazy (include an import for it) instead of the kotlin.Lazy
Once that is fixed you will run into another issue though; AFAIK you can't use a qualified dependency without a corresponding qualified provider. You have a qualified UserManager instance being injected into AccountsViewModel. Either add a qualified provider method or remove the qualification from the AccountsViewModel.


text:
Q: Select SQL query FROM table, select using that query? I'm trying to do the following in SQL alone. In the end it will end up on a wso2 DSS server but if it can be done in sql alone even better :)
Sudocode
Array results=Array;
result = <sql>select id, query from definitions</sql>
foreach result.query
    r=<sql>query</sql>
        results.push(r)

I am trying to run a select on table a that returns 2 columns.
One of the two columns is named query, and I want to then execute that query returning
id, query_title, query_text
We can assume that the query column always returns the same columns (through aliases written in the query)
The other option would be doing this in WSO2 DSS however I though at least that it can only do what sql does. Maybe joining with the ESB I could get it if that doesn't work but really my goal would be to do it ALL in sql as I am going to insert insert information and then update it into another table anyway.

A: You cannot do this with a single select query.
One solution is to do this in two steps.  Fetch the query in the application using your SQL and then execute the second query from the application.
The second solution is to use a stored procedure and prepare/execute.  How you then fetch the results depends on the nature of the results


text:
Q: Test saving ggplots I'm creating bunch of tests for ggplots. I included things like checking labels, if the output object is ggplot etc. But I have no idea how to test if the plot was saved using testthat and ggsave. Do you have any idea how it can be done ?

A: Here is a way to test based on file size. If the file doesn't exist it is NA and if it does exist it should be > 0.
library(testthat)
library(ggplot2)

test_that("plot is saved to file", {
  file <- tempfile(fileext = ".png")
  expect_equal(file.size(file), NA_real_)

  plot <- ggplot(mtcars, aes(wt, mpg)) +
    geom_point()

  ggsave(file, plot, "png")

  expect_true(file.size(file) > 0)

  unlink(file)
})


text:
Q: How can I reply to email by sending a delivery failure message? Occasionally, I receive unwanted emails, particularly low-volume spam, or email messages falsely addressed to me (possibly due to typos). I don't want to spend the energy to write a personal message, but I do want to let the sender know that the message never arrived at its destination, and that resending it will be useless. In my opinion, a delivery error message to the sender will fill that need. So, the question is if there is an easy way to send error messages back to the sender.
Is there any email client out there which supports sending delivery failure messages as a reply to incoming email -- ideally in one click? (Or, which can be configured to do so?)
Alternatively, what is the best way to set up an environment that allows me to send delivery failure messages without too much effort per message sent?

A: 1) Spammers don't care about delivery failure messages, and sometimes by sending them you can be unintentionally spamming someone else due to the ability to forge the Reply-To field.
2) The type of delivery failure notification you're likely thinking about is generated when the server receives the email, if it reaches your inbox it's come too far. Aside from you sending your own custom "I did not receive this message" response..


text:
Q: Modal does opens but does not close? I am having Issues with the modal, it opens on loading and does not respond to clicks to close it. Not sure what the Issue is. Attached is the code I have. How do I make the modal open as I click the button and close when I click the x

    <meta chart="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewort" content="width=device-width, intial-scal=1">
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/style.css">

    <title>Bootstrap</title>

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#signupform">
Signup
</button>

            <button type="button" class="close" data-dismiss="modal">

                ×

            </button>

 Sign Up

                <form class="form-horizontal">

                        First Name:

                        <input type="text" class="form-control input-sm">

                        Last Name:

                        <input type="text" class="form-control input-sm">

                        Email:

                        <input type="email" class="form-control input-sm">

                        Password:

                        <input type="password" class="form-control input-sm">

                        Confirm Password:

                        <input type="password" class="form-control input-sm">

                        <input type="submit" class="btn btn-success" value="submit">

                </form>

A:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha256-7s5uDGW3AHqw6xtJmNNtr+OBRJUlgkNJEo78P4b0yRw= sha512-nNo+yCHEyn0smMxSswnf/OnX6/KwJuZTlNZBjauKhTK0c+zT+q5JOCx0UFhXQ6rJR9jg6Es8gPuD2uZcYDLqSw==" crossorigin="anonymous">

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

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

Modal title

        ...

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

ref:  getbootstrap.com/javascript/#modals


text:
Q: Flowplayer not displaying and Flowplayer cannot access element I have a code that will allow FlowPlayer to retrieve a Javascript array and run the video files when the user click it.
However, I have two problems:

*

*The player and the playlist was not display on the page.

*A error with regards to Flowplayer cannot access element.

(Just in case anyone ask, the full path of the video is http://mm.com/mmA/videoplayer/videos/591483.flv)
Below is the full code:
<%@ Page Language="C#" %>

<META name="WebPartPageExpansion" content="full">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled 1</title>

<form id="form1" runat="server">
</form>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>

Appreciate any help offer.

A: Manage to find the answer. The answer as follows (Just in case anyone need it.)
var myplaylist = [];

//... do stuff

myplaylist.push("first.flv");

//... do stuff

myplaylist.push({url: "second.flv", duration: 60});

//... do stuff

$f("playerContainer", "/path/to/flowplayer-3.2.7.swf", {
  clip: {
    // common clip properties
    scaling: "fit"
  },
  playlist: myplaylist
});


text:
Q: Django resync autoincrementing pk with restored database I am working on a feature that requires me to use pg_restore to restore a database so I have enough historical data to do what I need to locally. The problem with this is when I create a new instance of any model, I end up with an IntegrityError as the pk is not unique.
This has something to do with auto-incrementing behavior of pks when creating, but it doesn't seem like Django is using that last row to "resync" the next number so what I'm left with is Django trying to create a new instance with pk of 1361 despite there being 31k rows.
How can I set the next value to what the next value actually should be, and is there a reliable way to do this after every restore?

A: What I was looking for was sqlsequencereset in manage.py (https://docs.djangoproject.com/en/3.0/ref/django-admin/#sqlsequencereset) which will generate the necessary SQL statements for me to run to resync.
sqlsequencereset app_label [app_label ...]

Running the following command gives the following output:
> python manage.py sqlsequencereset api
System check identified some issues:

WARNINGS:
api.ArchivedStream.tags: (fields.W340) null has no effect on ManyToManyField.
api.ArchivedStream.viewer_counts: (fields.E010) ArrayField default should be a callable instead of an instance so that it's not shared between all field instances.
    HINT: Use a callable instead, e.g., use `list` instead of `[]`.
api.Stream.stream_data: (fields.W904) django.contrib.postgres.fields.JSONField is deprecated. Support for it (except in historical migrations) will be removed in Django 4.0.
    HINT: Use django.db.models.JSONField instead.
api.Stream.tags: (fields.W340) null has no effect on ManyToManyField.
api.Stream.viewer_counts: (fields.E010) ArrayField default should be a callable instead of an instance so that it's not shared between all field instances.
    HINT: Use a callable instead, e.g., use `list` instead of `[]`.
api.Video.tags: (fields.W340) null has no effect on ManyToManyField.
BEGIN;
SELECT setval(pg_get_serial_sequence('"tags"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "tags";
SELECT setval(pg_get_serial_sequence('"streamers"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "streamers";
SELECT setval(pg_get_serial_sequence('"streams_tags"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "streams_tags";
SELECT setval(pg_get_serial_sequence('"streams"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "streams";
SELECT setval(pg_get_serial_sequence('"videos_tags"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "videos_tags";
SELECT setval(pg_get_serial_sequence('"videos"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "videos";
SELECT setval(pg_get_serial_sequence('"archived_streams_tags"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "archived_streams_tags";
SELECT setval(pg_get_serial_sequence('"archived_streams"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "archived_streams";
COMMIT;

Now I just needed to run this with psql command line. In my case, my postgres instance is in docker, so I ran the following command to execute the statements in my container.
sudo docker-compose run app python manage.py sqlsequencereset | sudo docker-compose run db psql -U postgres -d postgres```


text:
Q: Java NIO: Sending large messages quickly leads to truncated packets and data loss I've got this nasty problem where sending multiple, large messages in quick succession from a Java (NIO) server (running Linux) to a client will lead to truncated packets.  The messages have to be large and sent very rapidly for the problem to occur.  Here's basically what my code is doing (not actual code, but more-or-less what's happening):
//-- setup stuff: --
Charset charset = Charset.forName("UTF-8");
CharsetEncoder encoder = charset.newEncoder();
String msg = "A very long message (let's say 20KB)...";

//-- inside loop to handle incoming connections: --
ServerSocketChannel ssc = (ServerSocketChannel)key.channel();
SocketChannel sc = ssc.accept();
sc.configureBlocking(false);
sc.socket().setTcpNoDelay(true);
sc.socket().setSendBufferSize(1024*1024);

//-- later, actual sending of messages: --
for (int n=0; n<20; n++){
  ByteBuffer bb = encoder.encode(CharBuffer.wrap(msg+'\0'));
  sc.write(bb);
  bb.rewind();
}

So, if the packets are long enough and sent as quickly as possible (i.e. in a loop like this with no delay), then on the other end it often comes out something like this:
[COMPLETE PACKET 1]
[COMPLETE PACKET 2]
[COMPLETE PACKET 3]
[START OF PACKET 4][SOME OR ALL OF PACKET 5]

There is data loss, and the packets start to run together, such that the start of packet 5 (in this example) arrives in the same message as the start of packet 4.  It's not just truncating, its running the messages together.
I imagine that this is related to the TCP buffer or "window size", or that the server here is just providing data faster than the OS, or network adapter, or something, can handle it.  But how do I check for, and prevent it from happening?  If I reduce the length of message per use of sc.write(), but then increase the repetitions, I'll still run into the same problem.  It seems to simply be an issue with the amount of data in a short amount of time.  I don't see that sc.write() is throwing any exceptions either (I know that in my example above I'm not checking, but have in my tests).
I'd be happy if I could programmatically check if it is not ready for more data yet, and put in a delay, and wait until it is ready.  I'm also not sure if "sc.socket().setSendBufferSize(1024*1024);" has any effect, or if I'd need to adjust this on the Linux side of things.  Is there a way to really "flush" out a SocketChannel?  As a lame workaround, I could try to explicitly force a complete send of anything that is buffered any time I'm trying to send a message of over 10KB, for example (which is not that often in my application).  But I don't know of any way to force a send of the buffer (or wait until it has sent).  Thanks for any help!

A: There are many reasons why sc.write() would not send some or all of the data. You have to check the return value and/or the number of bytes remaining in the buffer.
for (int n=0; n<20; n++){
  ByteBuffer bb = encoder.encode(CharBuffer.wrap(msg+'\0'));
  if(sc.write(bb) > 0 && bb.remaining() == 0) {
    // all data sent
  } else {
    // could not send all data.
  }
  bb.rewind();
}

A: You are not checking the return value of:
sc.write(bb);

This returns the number of bytes written, which might be less than the data available in your buffer. Because of how nio works you can probably just call remaining() on your bytebuffer to see if there are any left.

A: I haven't done any NIO programming, but according to the Javadocs, sc.write() will not write the entire ByteBuffer if the SocketChannel is in non-blocking mode (as yours is) and the socket's output buffer is full.
Because you are writing so quickly, it is very likely that you are flooding your connection and your network or receiver cannot keep up.

I'd be happy if I could programmatically check if it is not ready for more data yet

You need to check the return value of sc.write() to find out whether your output buffer is full.

A: Don't assume you have any control over what data ends up in which packet.
More here: What's the best way to monitor a socket for new data and then process that data?

A: You are using the non-blocking mode:  sc.configureBlocking(false);
Set blocking to true and your code should work as it is.  Suggestions made by others here to check send count and loop will also work.


text:
Q: Change variable in MySQL In MySQL, how to change a variable such as character_set_client?

mysql> show variables like 'character_set%';
-------------------------+-------
character_set_client     | latin1

to obtain

character_set_client     | utf8

A: When starting MySQL client you have to specify --default-character-set=charset_name
From manual:
       Use charset_name as the default character set for the client and
       connection.

       A common issue that can occur when the operating system uses utf8
       or another multi-byte character set is that output from the mysql
       client is formatted incorrectly, due to the fact that the MySQL
       client uses the latin1 character set by default. You can usually
       fix such issues by using this option to force the client to use the
       system character set instead.

For example:
$>mysql -uUser -pPassword --default-character-set=utf8

For an example of how to set it via connection string see here.


text:
Q: Toggling Blink Led Program on and off My aim: To make a button that turns on and off a "Blink LED" Program.
PortD only has output LED.
PORTBO has input button.
Microcontroller: Atmega328p
Problem: Currently when I press button case1 of switch runs so the "Blink LED" Program starts. But I cannot turn off LED with button push.
Note: I am a beginner, I think I may have to use an interrupt somehow, but not sure
#include <avr/io.h> // header file file for input output pins
#include <util/delay.h> // header file for delay.
#define DEBOUNCE_TIME 25 // time to wait while "de-bouncing" button

void init_ports_mcu()
{ /* set pin 5 of PORTB for output*/
    DDRD = 0xFF;
    PORTD = 0x00;
    PORTB |= (1 << DDB0);
}

unsigned char button_state()
{
    if( !(PINB & 0x01) )
    {
        _delay_ms( DEBOUNCE_TIME );
        if( (PINB & 0x01) ) return 1;
    }
    return 0;
}

int main( void )
{
    init_ports_mcu();
    unsigned char n_led = 1;

    while( 1 )
    {
        if( button_state() )
        {
            switch( n_led )
            {
                case 1:
                    while( 2 )
                    {
                        PORTD |= 0xFF;
                        _delay_ms( 1000 ); //delay 1 second

                        PORTD &= ~0xFF;
                        _delay_ms( 1000 );

                        if( button_state() ) // If the button is pressed break while loop
                        {
                            break;
                        }
                    }
                    break;
                case 2:
                    PORTD |= 0x00;
                    _delay_ms( 5000 ); //delay 1 second
                    n_led--; // swtiches back to case1 LED number
                    break;
            }
            //n_led ++;
        }
    }
    return 0;
}

A: There are a number of issue.  Your debounce logic seems flawed, it says:

if the button is not pressed, wait 20ms and then see if it is pressed.

Better to say:

If the button state has changed, wait 25ms and then see if remains changed

unsigned char button_state()
{
    static unsigned last_state = (PINB & 0x01) ;

    unsigned new_state = (PINB & 0x01) ;
    if( last_state != new_state )
    {
        _delay_ms( DEBOUNCE_TIME ) ;

        if( (PINB & 0x01) == new_state ) last_state = new_state ;
    }

    return last_state ;
}

It is still a rather crude debounce method, but probably adequate.  Using edge interrupts and a timer interrupt is a more robust solution (example pseudocode).
In your main body your biggest problem is that while you are delaying, you are processing nothing else - the delays are "busy-waits".  There are no doubt other flaws in the logic, but to be frank enumerating them all is unproductive.  A redesign is called for.
Without introducing library code or hardware resources not in your existing code, I would suggest a state-machine looping on a delay of 1 with a counter to keep track of time.  The states are flashing/not flashing and a sub-state of LED on/LED off:
int main( void )
{
    #define FLASH_INTERVAL 1000 ;

    init_ports_mcu();
    unsigned char flashing = 0 ;
    unsigned char led_state = 0 ;
    unsigned long tick = 0 ;
    unsigned flash_time = FLASH_INTERVAL ;
    unsigned char button_down = 0 ;

    for(;;)
    {
        // Toggle indication state on button-down event
        unsigned char btn = button_state() ;
        if( !button_down && btn )
        {
            button_down = 1 ;

            // Toggle LED mode
            flashing = flashing == 0 ? 1 : 0 ;

            // Initialise the flashing starting with LED on
            flash_time = FLASH_INTERVAL ;
            led_state = flashing ;
        }
        else if( !btn )
        {
            // Button released
            button_down = 0 ;
        }

        // If flashing "ON"...
        if( flashing )
        {
            // Set the LED state
            if( led_state )
            {
                PORTD |= 0xFF ;
            }
            else
            {
                PORTD &= 0xFF ;
            }

            // Toggle the LED state when the flash interval has elapsed
            flash_time-- ;
            if( flash_time == 0 )
            {
                flash_time = FLASH_INTERVAL ;
                led_state = led_state ? 0 : 1 ;
            }
        }
        else // flashing off
        {
            PORTD &= ~0xFF;
        }

        // Increment tick every ms
        _delay_ms(1) ;
        tick++ ;
    }

    return 0;
}

One problem wit the above is the tick count interval will be extended by however long the loop body takes to execute.  In the case of a button press or release, that will include the debounce delay, but in this case that is not an issue in particular.  In real-time / time critical applications it needs to be considered.
Improvements and simplifications are possible with perhaps a timer interrupt incrementing the tick count rather than relying on the delay and the loop body execution time.  Or you could use a timer interrupt to toggle the LED directly, and simply switch the timer on/off or set a flag that blocks it from toggling the LED on the button press event.
So yes you could use interrupts and timer hardware extensively to implement this, and there are many ways you might do that, but it is by no means necessary.


text:
Q: Non-English IE9 and CSS opacity Look at the HTML code below:
<!DOCTYPE html>

        <meta http-equiv="X-UA-Compatible" content="IE=9" />
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

Hello World

On English IE9 things go as expected and the "Hello World" div is shown with the desired (50%) opacity, but on German IE9 the div is hidden and by reviewing the DOM in the "F12 developer tools" I can see that the opacity evaluates to 0 instead of 0.5. Moreover after assigning any other value with a fractional part to the opacity property causes the latter to evaluate to the integer part only ignoring the fractional part (i.e. opacity:22.34 evaluates to 22). Any idea what can be the difference between the English IE9 and the German IE9 causing this strange CSS behavior and how can I work around it  (IMPORTANT: I don't want to use the alternative properties like filter:alpha or -ms-filter etc.)?

A: Very strange behaviour :S
The only idea I can think is about the decimal mark used in German and in English. In english it's a dot (0.5) and in german is a comma (0,5). You can try to put the comma to see what it happens. But if this is the problem, it's very very strange, because I suppose the notation depends on the CSS specification and not from the decimal mark used in each country. And I suppose as well that both IE share same core and there is only a L10n (localization) change.
Or look if both IE are exactly the same version (not only 9, but 9.whatever). Maybe is a bug in some version.


text:
Q: How to add percent sign in string format and using swift language? I want to get string like "99.99%" from Double,and I used format to get this:
let rate = 99.99999
let str = String(format: "%.2f%", rate)
// output 99.99

And \% is not allowed. So how to add percent sign in string format, please help me!

A: write % twice:
rate = 99.99
let str = String(format: "%.2f%%", rate)

A:
The % symbol has a special use in a printf statement. How would you
  place this character as part of the output on the screen?

You can do this by using %% in the printf statement. For example, you can write printf("10%%") to have the output appear as 10% on the screen.
Hope it help you :)


text:
Q: Alternative definition of physical states Suppose that we have a vertex operator algebra $V$ with a conformal element $\omega$  and the associated conformal field
$$
Y(\omega,z) = \sum_{k\in \mathbb{Z}} L_kz^{-k-2}\,,
$$
where $L_k$ satisfy the Virasoro commutation relations for come conformal weight $c$ and $L_{-1}=T$ is the translation operator. We can define the subspaces $P_i\subset V$ by requiring for $v\in P_i$ to satisfy
$$
L_k v = iv\delta_{k,0} \,.
$$
The Lie algebra of physical/primary states is then defined by $P_1/TP_0$.
Alternatively, there is a way of defining the Lie bracket $[-,-]: V\times V/TV\to V$ lifting the usual construction of Borcherds as
$$
[u,\bar{v}] = [z^{-1}]\big\{Y(u,z)v\big\}\,,
$$
which is independent of the choice of lift $v$ of $\bar{v}$. Then
$$
\ker\Big\{[\omega, -]\Big\}
$$
defines a Lie sub-algebra, which can be shown to be identical to the one of physical states in the case of lattice vertex algebras.
All I am asking is if this alternative construction is familiar to anybody and if there is some more or less standard reference where it is already noted down.


text:
Q: How can I improve this method of loading objects with ORMLite on Android? I am loading a set of objects (and their foreign objects) using ormlite 4.35 on Android. It takes (in the emulator) between 16 and 19 seconds for the timing in the getAllCragsWithLocation() method below.
There are 590 Crags in the database and 40 don't have a location.
There are several lines logged such as
03-19 11:03:54.441: I/dalvikvm(1156): Jit: resizing JitTable from 1024 to 2048
03-19 11:03:55.531: D/dalvikvm(1156): GC_CONCURRENT freed 544K, 37% free 5174K/8199K, external 731K/1109K, paused 6ms+11ms

Should I be loading the objects another way? Running the query at the sqlite3 command line takes around 100th of a second...
public List<Crag> getAllCragsWithLocation() {
        Log.i(TAG,"beginning db calls");
        long startQuery = System.currentTimeMillis();
        QueryBuilder<Crag,Integer> queryBuilder = helper.getCragDao().queryBuilder();
        List<Crag> results = new ArrayList<Crag>();
        try {
            queryBuilder.where().isNotNull("location_id");
            Log.i(TAG,queryBuilder.prepareStatementString());
            PreparedQuery<Crag> preparedQuery = queryBuilder.prepare();
            results = helper.getCragDao().query(preparedQuery);
        } catch (android.database.SQLException e) {
            Log.e(TAG,e.toString());
        } catch (SQLException e) {
            Log.e(TAG,e.toString());
        }
        Log.i(TAG,"ending query after "+((System.currentTimeMillis()-startQuery)/1000)+" seconds");
        return results;
    }

The crag object (simplified) is:
@DatabaseTable
    public class Crag {
        public Crag() {
            //ormlite requires a no-arg constructor?
            guidebooks = new ArrayList<Guidebook>();
        }

        @DatabaseField(id=true) private int id;
        @ForeignCollectionField(eager = true)
        private Collection<Guidebook> guidebooks;
        @DatabaseField(foreign=true, foreignAutoRefresh = true, index=true)
        private uk.co.bmc.rad.models.Location location;
        @DatabaseField(foreign=true,foreignAutoRefresh=true)
        private SubRegion subRegion;
    }

The foreign objects are much simpler classes than Crag. For the purposes of display only the location is necessary at the point the objects are loaded form the database but I use the foreign objects when comparing for equality so...
The return from the getAllCragsWithLocation() is iterated over to prepare for addition to a MapOverlay. Timing that process takes less than a second.

UPDATE:
I've just swapped in DB4O to compare and that loads all crags essentially instantly by comparison so I think I'll go with that.

UPDATED UPDATE:
Instead of quickly swapping in DB4O I've spent more time comparing the two.
In a JUnit 3 AndroidTestCase if I insert a single record into the database and then query for it directly then both ORMLite and DB4O take about a second (total) to insert and return the object.
If I run my process to insert 590 objects then ORMLite takes around 24 seconds and DB40 takes around 40.
Immediately after that insert if I call getAllCragsWithLocation() and then getAllCrags() DB40 takes 7 seconds and then 0 seconds to return a List of Crags so I'm guessing it has a cache that speeds the second query
While ORMLite takes around 7 seconds for both queries.
So there's actually very little in it

UPDATED UPDATE UPDATED:
Grabbed a Transformer Prime today and just ran the app on that and the crags loaded in 1 second as compared to the 7 on the emulator.
Since I've managed to grok ormlite's query syntax already; can fall back on raw sql and the sqlite table structure is more transferable I'm going to stick with ormlite over db4o.

A: I'm really surprised that it is taking that long.
    @ForeignCollectionField(eager = true)
    private Collection<Guidebook> guidebooks;
    @DatabaseField(foreign=true, foreignAutoRefresh = true, index=true)
    private uk.co.bmc.rad.models.Location location;
    @DatabaseField(foreign=true,foreignAutoRefresh=true)
    private SubRegion subRegion;

Each of those fields will generate another database query that would take time although I would not expect seconds.  ORMLite is not smart about using JOIN to satisfy eager fetched remote objects.
One thing to try is to use the table-config process to work around Android's dog, dog slow reflection implementation when generating DAO implementations.  See the docs for that:

http://ormlite.com/docs/table-config

I would be curious if you figure it out although I understand if you need to switch to some other package to get working.

A: I think you should consider using a ContentProvider. I have made an application manipulating 2k rows but the query and object regeneration is done in less than 10 sec on the emulator


text:
Q: Microsoft Access впервые столкнулся с задачей сделать выборку из базы данных micorosoft access и как бы я не пытался к ней подключится, вижу вот это:
Ошибка. (Не удается найти указанный поставщик. Вероятно, он установлен неправильно.)
Connection String которые я пробовал:
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Access.mdb
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Acccess.mdb
И несмотря на то, что я скачивал с сайта MS некий AccessDatabaseEngine.exe и ставил все подряд, что советовали из гугла, ничего не помгло, та же ситуация и на MS Server.

A: Исходя из ошибки, видно, что в ODBC отсутствует драйвер для баз Access.
А именно он нужен Вам для подключения к базе из стороннего кода.
Если отсутствует полнофункциональный Office, то установите Access Runtime - он должен установить и прописать драйвер в ODBC


text:
Q: Cubic spline interpolation results I have a set of data points on which i am trying to do cubic spline interpolation. Below is the snapshot of the curve with the input data points marked in green color. And the red color marked point is the test point.
Please click here : Curve with DataPoints
The steps i am following to interpolate is

*

*Form piecewise spline equations between points . cubic equation : ax^3 + bx^2 + cx + d = P(x)

*Form first derivative equations at interior points

*Form Second   derivative equations at interior points

*Set Second derivative equations at exterior points to zero

Get the equations created above in matrix form and solve for the coefficients(a,b,c,d) of each spline.
SpreadSheet : Calculation -SpreadSheet
But for any given test point (X) other than input points.... the spline equation does not yield proper (Y) .
As a test case in the above curve.....if i use X = 152.73 (red colour marked point on the curve) in the first spline equation ... then,
Y = (966.3375) * (152.73^3) + (-443577.902) * (152.73^2) + (67872238.9) * (152.73) + (-3461748870) = 613.07 which is wrong . Y should be returned as 699.92
can anyone explain what is going wrong in this?
I tried Quadratic spline interpolation as well, it also returns same kind of results. I hope i am following the correct steps .If not, Please direct me in doing so. I am very new to this stuff. Please help.
Sorry for my bad english and math terminologies

A: The problem was that the data looked kind of like this:

For this data, when an attempt was made to fit $y=a_ix^3+b_ix^2+c_ix+d_i$ between the spline points and it didn't work well because the data can't be expressed as a function of $x$; instead there can be multiple values of $y$ for each value of $x$. There are spline algorithms that can handle this, but if it is desired to use an equation as noted above, in this case we can instead fit $x=a_iy^3+b_iy^2+c_iy+d_i$ in each interval. For these data we anticipate good results just by looking at the data in that the graph seems to depict $x$ as a smooth function of $y$.

A: If you are set on keeping the data as-is and not flip x/y as others have pointed out, I might suggest using Catmull-Rom, maybe with a chordial (alpha=1) parameterization if you like keeping the "humps" large as in a cubic spline (though I prefer centripedal, though uniform is simplest to work with).
Here's an example from python i made using those points:
(http://imgur.com/CwMMou4)
(not enough rep to post images directly :/)
Here is another example with some more extreme points to show how the 3 parameterizations behave differently: View post on imgur.com
Notice 3 lines for different alpha values:
Green line = uniform (a=0)
Blue = Centripedal (a=0.5, no cusps or loops)
Red = Chordial (a=1)
Notice though that I had to arbitrarily create endpoints (I added custom endpoints that maintained slope between first and last 2 points), otherwise catmull rom won't be able to interpolate first and last two points, without knowing which tangent you want to use at the start/end.
My Python Code if you'd like:
# coding: utf-8

# In[1]:

import numpy
import matplotlib.pyplot as plt
get_ipython().magic(u'pylab inline')

# In[2]:

def CatmullRomSpline(P0, P1, P2, P3, a, nPoints=100):
  """
  P0, P1, P2, and P3 should be (x,y) point pairs that define the Catmull-Rom spline.
  nPoints is the number of points to include in this curve segment.
  """
  # Convert the points to numpy so that we can do array multiplication
  P0, P1, P2, P3 = map(numpy.array, [P0, P1, P2, P3])

  # Calculate t0 to t4
  alpha = a
  def tj(ti, Pi, Pj):
    xi, yi = Pi
    xj, yj = Pj
    return ( ( (xj-xi)**2 + (yj-yi)**2 )**0.5 )**alpha + ti

  t0 = 0
  t1 = tj(t0, P0, P1)
  t2 = tj(t1, P1, P2)
  t3 = tj(t2, P2, P3)

  # Only calculate points between P1 and P2
  t = numpy.linspace(t1,t2,nPoints)

  # Reshape so that we can multiply by the points P0 to P3
  # and get a point for each value of t.
  t = t.reshape(len(t),1)

  A1 = (t1-t)/(t1-t0)*P0 + (t-t0)/(t1-t0)*P1
  A2 = (t2-t)/(t2-t1)*P1 + (t-t1)/(t2-t1)*P2
  A3 = (t3-t)/(t3-t2)*P2 + (t-t2)/(t3-t2)*P3

  B1 = (t2-t)/(t2-t0)*A1 + (t-t0)/(t2-t0)*A2
  B2 = (t3-t)/(t3-t1)*A2 + (t-t1)/(t3-t1)*A3

  C  = (t2-t)/(t2-t1)*B1 + (t-t1)/(t2-t1)*B2
  return C

def CatmullRomChain(P,alpha):
  """
  Calculate Catmull Rom for a chain of points and return the combined curve.
  """
  sz = len(P)

  # The curve C will contain an array of (x,y) points.
  C = []
  for i in range(sz-3):
    c = CatmullRomSpline(P[i], P[i+1], P[i+2], P[i+3],alpha)
    C.extend(c)

  return C

# In[15]:

# Define a set of points for curve to go through
#Points = numpy.random.rand(12,2)
Points=array([array([153.01,722.67]),array([152.73,699.92]),array([152.91,683.04]),array([154.6,643.45]),
        array([158.07,603.97])])
x1=Points[0][0]
x2=Points[1][0]
y1=Points[0][1]
y2=Points[1][1]
x3=Points[-2][0]
x4=Points[-1][0]
y3=Points[-2][1]
y4=Points[-1][1]
dom=max(Points[:,0])-min(Points[:,0])
rng=max(Points[:,1])-min(Points[:,1])
prex=x1+sign(x1-x2)*dom*0.01
prey=(y1-y2)/(x1-x2)*(prex-x1)+y1
endx=x4+sign(x4-x3)*dom*0.01
endy=(y4-y3)/(x4-x3)*(endx-x4)+y4
print len(Points)
Points=list(Points)
Points.insert(0,array([prex,prey]))
Points.append(array([endx,endy]))
print len(Points)

# In[16]:

#Define alpha
a=0.

# Calculate the Catmull-Rom splines through the points
c = CatmullRomChain(Points,a)

# Convert the Catmull-Rom curve points into x and y arrays and plot
x,y = zip(*c)
plt.plot(x,y,c='green',zorder=10)

# Plot the control points
px, py = zip(*Points)
plt.plot(px,py,'or')

a=0.5
c = CatmullRomChain(Points,a)
x,y = zip(*c)
plt.plot(x,y,c='blue')

a=1.
c = CatmullRomChain(Points,a)
x,y = zip(*c)
plt.plot(x,y,c='red')

plt.grid(b=True)
plt.show()

# In[14]:

Points


text:
Q: Plex media server on Raspberry pi zero w not working I'm trying to install Plex media server on my raspberrypi zero w and i keep getting this error:
plexmediaserver.service - Plex Media Server for Linux
Loaded: loaded (/lib/systemd/system/plexmediaserver.service; enabled;
vendor preset: enabled)
Active: failed (Result: exit-code) since Thu 2018-09-06 18:22:09 UTC; 12s ago
Process: 1043 ExecStart=/bin/sh -c LD_LIBRARY_PATH=/usr/lib/plexmediaserver "/usr/lib/plexmediaserv
Process: 1039 ExecStartPre=/bin/sh -c /usr/bin/test -d "${PLEX_MEDIA_SERVER_APPLICATION_SUPPORT_DIR
Main PID: 1043 (code=exited, status=132)

Sep 06 18:22:04 raspberrypi systemd[1]: plexmediaserver.service: Unit entered failed state.
Sep 06 18:22:04 raspberrypi systemd[1]: plexmediaserver.service: Failed with result 'exit-code'.
Sep 06 18:22:09 raspberrypi systemd[1]: plexmediaserver.service: Service hold-off time over, scheduli
Sep 06 18:22:09 raspberrypi systemd[1]: Stopped Plex Media Server for Linux.
Sep 06 18:22:09 raspberrypi systemd[1]: plexmediaserver.service: Start request repeated too quickly.
Sep 06 18:22:09 raspberrypi systemd[1]: Failed to start Plex Media Server for Linux.
Sep 06 18:22:09 raspberrypi systemd[1]: plexmediaserver.service: Unit entered failed state.
Sep 06 18:22:09 raspberrypi systemd[1]: plexmediaserver.service: Failed with result 'exit-code'.

If anyone can help I'd really appreciate it, Thanks!
(btw I'm quite a noob when it comes to raspberry pi's)

A: As far as I know it is not supported anymore due to lots of API changes of Plex resulting in the discontinued support of ARM v61 (Pi Zero W has ARM v61) and only "supports" ARM v7 and v8 (v64)
See also: https://forums.plex.tv/t/pi-zero-w-problems/191899/7


text:
Q: Inserting a anchor with jquery to call a function I am fairly new to jQuery, what i am trying to do is once the document is ready, i am creating a field. in a div. At the moment it works like this:
$(document).ready(function()
{
    $("div.custom").eq(1).html("Download PDF");
});

Now this doesn't works because the arguments. But I can create something like this
$("div.custom a").click(function(e) {
    //alert('clicked');
    createPDF('Y');
    return false;
});

and in order to change this i change my creation to this
$(document).ready(function()
{
    $("div.custom").eq(1).html("Download PDF");
});

However, i personally believe because it first doesn't exist once the page is loaded, it doesn't connect the link with the click function. How can I proceed with it?
Thank you

A: You have to use on for binding event on dynamically created elements. You can use event delegation.
$("div.custom").on("click", "a", function(e) {
    //alert('clicked');
    createPDF('Y');
    return false;
});

Delegated events

Delegated events have the advantage that they can process events from
  descendant elements that are added to the document at a later time. By
  picking an element that is guaranteed to be present at the time the
  delegated event handler is attached, you can use delegated events to
  avoid the need to frequently attach and remove event handlers, reference.

A: $("div.custom").on("click", "a", function(event){
   //alert('clicked');
        createPDF('Y');
        return false;
});

see for details..on according to jquery

A: can you try this something like this:
$("div.custom").on('click', 'a', function(e) {
//alert('clicked');
createPDF('Y');
return false;
});

[edit]oups too late ;)

A: you can hook the event when you add the anchor tag like
$(document).ready(function () {
    $("div.custom").eq(1).html("Download PDF").find('a').click(function (e) {
        e.preventDefault();
        createPDF('Y');
    });
});

A: $(document).ready(function()
{
    $("div.custom").eq(1).html("DownloadPDF").find("a").click(function(e) {
        alert('clicked');
        createPDF('Y');
        return false;
    }); ;
});

You are right this is because the link doesn't exist. With the correction I gave you the event is added just after you create the link
Hope it helped


text:
Q: Group by in Power Pivot I have a table sitting in power pivot that I need to group the data in. I have looked online and tried ten or so methods but for some reason this just isn't working despite this being the simplest table you could think of.
Basically I have a list of rooms that I need a distinct count of i.e. Room1, Room2, Room3. Essentially I just want a distinct count of all of the rooms in column. The data is over a year, so would tell me how many days the room has been used. There is also a days column, but probably don't even need to use that.
I can do this in excel, and power query but struggling in Power Pivot (excel data model).
Current formula is;
=GROUPBY('ROOM.TBL',[ROOMS],"ROOM UTILIZATION",[COUNT])
I have also tried using sum instead of count but this isn't working.
I know you can do this in many different ways, including summarize, but for what ever reason it is not working.
Any help or alternatives appreciated.


text:
Q: why is the FFmpegPCMAudio not playing? in the following code of a discod bot (wrote in python) the FFmpegPCMAudio is not playing, the code and the mp3 audio are in the same folder, also, yesterday the bot worked well, but today when i write the command the bot enters the voice chat, but it doesn't play the mp3 audio, why?

import discord as ds
from discord.ext import commands
from discord import FFmpegPCMAudio

intents = ds.Intents.all()
bot = commands.Bot(command_prefix='$', intents = intents)

@bot.event
async def on_ready():
    print('bot online.')

@bot.command(pass_context = True)
async def outro(ctx):
    if (ctx.author.voice):
        channel = ctx.message.author.voice.channel
        voce = await channel.connect()
        source = FFmpegPCMAudio('outro.mp3')
        player = voce.play(source)

    else:
        await ctx.send('not in a voice chat')

@bot.command(pass_context = True)
async def esci(ctx):
    if (ctx.voice_client):
        await ctx.guild.voice_client.disconnect()
        await ctx.send('adios @everyone')
    else:
        ctx.send('not in a voice chat')

bot.get_command('outro')
bot.get_command('esci')

bot.run('MTAwNDA0MjQ1MjcxMTI0NzkwNQ.GjUNFS.LecuRh7QuWxrdpK-lqyH3npMUzCiIyzehCQfjU')

A: If you're running this on Replit, it's because Replit no longer supports ffmpeg. If not, then you don't have it installed properly on your system.


text:
Q: Why is this Javascript not triggering an Ajax event? I have a forum of sorts, and I want to automatically refresh the posts every so often. I am using Ajax when the page loads to start and later I will implement the auto refresh. The problem I am having is (I believe) inducing a Ajax request. I have an event handler for the Ajax request to take place when I click my header (for purposes of debugging). I won't post all of my code, just the most relevant sections here, but if you want you think there is probably a problem in my code elsewhere, feel free to check out www.ethoma.com/testhome.php which sends a request to www.ethoma.com/getposts.php.
Ajax requesting function:
function getPosts(category, page, sort)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
                      document.getElementById("postcontainer").innerHTML=xmlhttp.responseText;
        }
}
var queryString = "?category=" + category + "&page=" + page + "&sort=" + sort;
xmlhttp.open("GET","getuser.php" + queryString,true);
xmlhttp.send();
}

My PHP page should return the correct html code through an echo call. On a side note, it is okay to embed html tags within the code I return through my PHP page (novice question)?
If you think the problem is not in this code snippet, again feel free to browse those two pages. Thanks to everyone who views/answers this question -- everyone here is very helpful.

A: I've looked at the live version of your site and ran it with a breakpoint in onreadystatechange. The reason you don't see anything is that getuser.php 404's.
In particular the called URL is http://www.ethoma.com/getuser.php?category=[object%20HTMLAllCollection]&page=1&sort= (I'm quite sure the category is a bug) and yields 404, onreadystatechange is then called with readyState=2 and status=404


text:
Q: input for timestamp in sql I am taking input in the below table as
insert into friendship values(&req_id,&sender_id,&receiver_id,'&sent_at');

But i dont't know what syntax I should type for timestamp in the input window. When I am typing like 2013-12-01 11-01-01, it is not inserted.
create table friendship (
    req_id integer primary key,
    sender_id integer not null,
    receiver_id integer not null,
    sent_at timestamp
);

A: You can use Oracle function TO_TIMESTAMP() to convert a string to a TIMESTAMP datatype.
Consider:
insert into friendship values(
    &req_id,
    &sender_id,
    &receiver_id,
    TO_TIMESTAMP('&sent_at', 'YYYY-MM-DD HH24-MI-SS')
);

This will allow an input like 2013-12-01 11-01-01.


text:
Q: Passing TableViewCell to a new TableView (at the top) Swift What I want to do:
I have a feed (TableView( and once the user taps on a Post (TableViewCell), he should see a new Page (TableView) with the Post he tapped on first (the same TableViewCell) on top and a couple of comments below.
My Problem:
I dont get how to "clone" that TableViewCell.
Here two pictures for a better understanding:

Some complications:
I have multiple post types in the main feed, so the code would have to differentiate between them to see which cell type to use to display the content.
My code:
Main Feed
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0{
            return mixed.count
        }
        else if section == 1{
            return phots.count
        }
        else{
            return texttt.count
        }

    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        if indexPath.section == 0{
            let cell = tableView.dequeueReusableCell(withIdentifier: mixedTableViewCell.identifier, for: indexPath) as! mixedTableViewCell
            cell.configure(with: self.mixed[indexPath.row])
            return cell
        }
        else if indexPath.section == 1{
            let cell = tableView.dequeueReusableCell(withIdentifier: popularTableViewCell.identifier, for: indexPath) as! popularTableViewCell
            cell.configure(with: self.phots[indexPath.row])
            return cell
        }
        else{
            let cell = tableView.dequeueReusableCell(withIdentifier: textTableViewCell.identifier, for: indexPath) as! textTableViewCell
            cell.configure(with: self.texttt[indexPath.row])
            return cell
        }

    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let vc = storyboard.instantiateViewController(withIdentifier: "commentsVC")
        vc.modalPresentationStyle = .fullScreen

        self.navigationController?.pushViewController(vc, animated: true)
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

        return UITableView.automaticDimension
    }

My second ViewController
class CommentsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet var table: UITableView!

    var texty = [TextComment]()

    override func viewDidLoad() {
        super.viewDidLoad()

        table.register(popularTableViewCell.nib(), forCellReuseIdentifier: popularTableViewCell.identifier)
        table.register(featuredTableViewCell.nib(), forCellReuseIdentifier: featuredTableViewCell.identifier)
        table.register(textTableViewCell.nib(), forCellReuseIdentifier: textTableViewCell.identifier)
        table.register(mixedTableViewCell.nib(), forCellReuseIdentifier: mixedTableViewCell.identifier)
        table.register(textComTableViewCell.nib(), forCellReuseIdentifier: textComTableViewCell.identifier)

        table.delegate = self
        table.dataSource = self

    }

    func numberOfSections(in tableView: UITableView) -> Int {
        2
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0{
            return 1
        }
        else{
            return 15
        }
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0{
            let cell = tableView.dequeueReusableCell(withIdentifier: textTableViewCell.identifier, for: indexPath) as! textTableViewCell
            return cell
        }
        else{
            let cell = tableView.dequeueReusableCell(withIdentifier: textComTableViewCell.identifier, for: indexPath) as! textComTableViewCell
            return cell
        }
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0{
//            self.table.estimatedRowHeight = 250
//            self.table.rowHeight = UITableView.automaticDimension
//            return UITableView.automaticDimension
            return 300
        }
        else{
//            self.table.estimatedRowHeight = 150
//            self.table.rowHeight = UITableView.automaticDimension
//            return UITableView.automaticDimension
            return 150
        }
    }

Note
Right now the it isnt working at all, how I want it. I just have these "mock" posts as space-fillers in there.
Any help or ideas would be greatly appreciated!
My structs
struct PhotoPost {
    let numberOfComments: Int
    let username: String
    let timestampName: String
    let userImageName: String
    let postImageName: String
    let postID: String
}

struct TextPost {
    let numberOfComments: Int
    let username: String
    let timestampName: String
    let userImageName: String
    let textName: String
    let postID: String
}

struct MixedPhoto {
    let numberOfComments: Int
    let username: String
    let timestampName: String
    let userImageName: String
    let textName: String
    let postImageName: String
    let postID: String
}

Here my errors:

A: Each instance of UITableView has its own pool of cells, for this reason it would not be correct to "steal" an instance of the cell from one UITableView and put it into another. Also, as far as i can see you already have a convenient way to feed your cells with data, and dequeue corresponding types. Thus the only thing left here is to pass the required data from MainFeed under your tableView(_: didSelectRowAt:) function, something like that:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    guard let vc = storyboard.instantiateViewController(withIdentifier: "commentsVC") as? CommentsViewController else {
       return
    }
    switch indexPath.section {
        case 0:
            vc.mixedData = mixed[indexPath.row]
        case 1:
            vc.photoData = photos[indexPath.row]
        default:
            vc.textData = texttt[indexPath.row]
    }
    vc.modalPresentationStyle = .fullScreen

    navigationController?.pushViewController(vc, animated: true)
}

And then, under the CommentsViewController's tableView(_:, cellForRowAt:) function, implement pretty much the same stuff you did in MainFeed:
var mixedData: MixedPhoto?
var photoData: PhotoPost?
var textData: TextPost?

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if indexPath.section == 0 {
        let cell: UITableViewCell
        switch (mixedData, photoData, textData) {
        case (.some(let value), _, _):
            cell = tableView.dequeueReusableCell(withIdentifier: mixedTableViewCell.identifier, for: indexPath) as! mixedTableViewCell
            cell.configure(with: value)
        case (_, .some(let value), _):
            cell = tableView.dequeueReusableCell(withIdentifier: popularTableViewCell.identifier, for: indexPath) as! popularTableViewCell
            cell.configure(with: value)
        case (_, _, .some(let value)):
            cell = tableView.dequeueReusableCell(withIdentifier: textTableViewCell.identifier, for: indexPath) as! textTableViewCell
            cell.configure(with: value)
        default:
            fatalError("The data is not set")
        }
        return cell
    } else {
        let cell = tableView.dequeueReusableCell(withIdentifier: textComTableViewCell.identifier, for: indexPath) as! textComTableViewCell
        return cell
    }
}

Also I should say that it's a good idea to implement a common protocol for your data types, so you actually can define a single non-optional variable in the CommentsViewController instead of three optionals.


text:
Q: Bunding not working in ASP.Net MVC4 while same working in MVC 5? I have ASP.Net MVC4 site.
I am bundling all my css but its not working. But same thing is working in another application using ASP.Net MVC5
This is my folder structure:-
>>Styles
    >>Css
       >>Bootstrap_folder>>bootstrap.css
       >>site.css
       >>font.css

In my BundleConfig.css
bundles.Add(new StyleBundle("~/Styles/Css/cssBundle").Include(
                    "~/Styles/Css/Bootstrap_folder/bootstrap.css",
                    "~/Styles/Css/site.css",
                    "~/Styles/Css/fonts.css"
            ));

Now when I am running the application, site.css and font.css are included but the css files in bootstrap folder or other are not included.
But same thing is rendering fine in ASP.Net MVC5
I am in need that I should be free to include any subfolder files.

A: Remove the under score  in Bootstrap_folder. Rename it to Bootstrapfolder


text:
Q: Flink Completion Exception Couldn't acquire the minimum required resources Hi I have a flink Job that that every time there's an Exception, it will have after it around 7 additional Exceptions of
java.util.concurrent.CompletionException: org.apache.flink.runtime.jobmanager.schedular.NoResourceAvailableException: Could not acquire the minimum required resources.
For example the timing
5:47:40 - Exception
5:50:40 - NoResourceAvailableException
5:50:47 - NoResourceAvailableException
5:50:56 - NoResourceAvailableException
5:51:10 - NoResourceAvailableException
5:51:31 - NoResourceAvailableException
5:52:04 - NoResourceAvailableException
5:52:57 - NoResourceAvailableException
Only after around 5 min the job runned again.
The environment have 15 taskmanger and 30 taks slots.
And the job run on 28 task slots, we left 2 task slot so on fail the environment will have standby task slots.
As you can see it still doesn't help and the job takes 5 min until it's up again.
The environment run on kubernetes.
My guess is that the pods restart because of the Exception and that the jobmanger waits to the same pod to be restored. But I don't understand why it won't use the standby task slots.
The up time of the job is crucial so every minute count and we try to have minimal downtime.
I tried to change the number of task slots and task manager so it will have more weaker instances. But the job won't run in any diffrent configuration we get backpresure instead.
And adding more standby task slot in the current state is extremely expensive because each pods (task manager) have a lot of resources.
Tnx for anyone that can help.


text:
Q: MongoDB (Docker) Error 20 - IllegalOperation while trying to start transaction I'm using MongoDB docker (4.4.x) image as my DB for NestJS backend. One of the API is triggered by a webhook of my payment gateway. Since its a payment related DB ops, I use transactions for ACID. The problem is, after I start session, then transaction & try to find one document (the very first query in the transaction), It throws an error :
{
  "ok": 0,
  "code": 20,
  "codeName": "IllegalOperation",
  "name": "MongoError"
}

I then switched to the MongoDB Atlas dev server and the whole transaction works flawlessly. Which leads me to believe that, there is something wrong with my installation of mongo docker image.
My docker-compose.yaml file:
version: '3'
services:
    database:
        image: 'mongo'
        container_name: 'mongoDbDev'
        environment:
            - MONGO_INITDB_ROOT_USERNAME=root
            - MONGO_INITDB_ROOT_PASSWORD=789512346
        volumes:
            - ./mongo-volume:/data/db
        ports:
            - '27017:27017'

The mongo-volume directory is located in ~/Documents/Workspace/Docker/mongodb/
I tried this stackoverflow solution but did not work. Which TLDR; Changing permissions to the ./mongo-volume folder.
Additional info,

*

*I user docker-compose command without sudo (tried with sudo, did not
work)

*I have to use docker with sudo command, post installation steps did not work for me


text:
Q: Calculation of PI() and 3.14159265358979 in excel In Excel while Calculating =SIN(PI()) formula it returns 1.22515E-16.If the  PI() Value(3.14159265358979) is directly given like =SIN(3.14159265358979), it returns 3.23114E-15.
Please anyone can share your opinion about how the excel calculates differently, when 'PI' and 3.14159265358979 are passed as parameter.

A: Let's have the following example:

A2 is formula =PI().
A3 is value 3.14159265358979.
A5 is value copied from A2 and then paste-special: Values only.
Formula in column B is =SIN(A2) ... =SIN(A5).
So what is happening here?
While Microsoft justifies the truncating values to 15 digits with using double floating point precision according IEEE 754, this is not the whole truth. According IEEE 754 the possible count of decimal digits is not exactly 15 but 15.95 in average. So there are more digits possible in some cases. And if so, Excel stores up to 17 digits in its files although it shows only 15 digits in its sheet views and also only 15 digits can be input in its sheet views.
So =PI() will result in 3.1415926535897931 exactly and this value will also be stored. But manual input can only be 3.14159265358979. But if you copy/paste-special:Values the result of =PI(), then also 3.1415926535897931 will be stored although only 3.14159265358979 is shown.
Since *.xlsx files are simply ZIP archives, we can unzip them and look at /xl/worksheets/sheet1.xml. There we will find:
<row r="2" spans="1:2" x14ac:dyDescent="0.25">
 <c r="A2" s="1">
  <f>PI()</f>
  <v>3.1415926535897931</v>
 </c>
 <c r="B2">
  <f>SIN(A2)</f>
  <v>1.22514845490862E-16</v>
 </c>
</row>
<row r="3" spans="1:2" x14ac:dyDescent="0.25">
 <c r="A3" s="1">
  <v>3.14159265358979</v>
 </c>
 <c r="B3">
  <f>SIN(A3)</f>
  <v>3.2311393144413003E-15</v>
 </c>
</row>
<row r="5" spans="1:2" x14ac:dyDescent="0.25">
 <c r="A5" s="1">
  <v>3.1415926535897931</v>
 </c>
 <c r="B5">
  <f>SIN(A5)</f>
  <v>1.22514845490862E-16</v>
 </c>
</row>

q.e.d.

A: The reason you are seeing this is because of a rounding error.
Sin(PI()) is technically 0, as detailed in the Sin function documentation. However, excel returns 1.22515E-16 or 0.0000000000000001225148455
(i.e. approximately 0)
3.14159265358979 is a approximation of PI(), so it returns a different number that it also approximately 0. If you try 3.1415926535897, 3.141592653589 etc, you will get a different number each time.
This is likely related to working with floats, but I don't know enough about Excel and how it stores data to elaborate.

A: The SIN() function accepts the parameter in radians.
To convert an angle to radians, the value must be multiplied by PI()/180.
If you use =SIN(PI()), the PI is considered as a radian which is equal to RADIANS(180). Both =SIN(PI()) and =SIN(RADIANS(180)) returns the same result 0.
=SIN(3.14159265358979) is not actually equal to =SIN(PI()) because the PI in this context is different. And hence the different result.
The bottom line is to always use radians as a parameter for trigonometric functions.


text:
Q: JSF lifecycle, how can response complete happen in the middle of the life cycle? I am going through the article on JSF LifeCycles. I have the following doubt.

*

*In many phases, the Response Complete is happening. How it is happening in
the middle of the life cycle. Can anyone explain it in detail?

A: Quoting from the JSF 2.0 spec:

The responseComplete() method, on the other hand, signals the JSF implementation that the HTTP response for this request has been completed by some means other than rendering the component tree, and that the request processing lifecycle for this request should be terminated when the current phase is complete. For example, an event listener that decided an HTTP redirect was required would perform the appropriate actions on the response object (i.e. calling ExternalContext.redirect()) and then call this method.

Calling ExternalContext.redirect(String) in a JSF servlet application causes a 302 response to be sent to the browser via the underlying API. In this case, it would be an error (or at least futile) to emit data in the response body, so ExternalContext.redirect(String) calls responseComplete().

A: If you are asking how it is happening I guess they do multi threading.
In case you are asking why it is happening, it is for the ajax requests or for repsonses that have to be submitted immediately


text:
Q: What library does Google Chrome use to remove unnecessary stuff while converting an HTML page to PDF or just print it? WHen we try to print a document in Google Chrome, it shows It's preview without any advertisements and any dynamic content like comments that might have been there.
What does it use to get rid of the extra unnecessary stuff from the DOM and convert it to a PDf when we save it as PDF ?
Is it a C++ library ?

A: The library is pdfium, https://pdfium.googlesource.com/pdfium/+/master
This news article explains the library pretty well:
http://www.infoq.com/news/2014/06/google-chrome-pdf-engine-free


text:
Q: Javascript image fade? I have a basic JavaScript image slideshow which loops through 4 images with a 5 second delay.
Is there any way to make each image fade in as opposed to just appearing instantly? Perhaps using the css3 transition effects??
I don't want to use any pre-made slideshow addons or anything, I am trying to make this myself out of just JavaScript.
Here is a codepen link
Thanks in advance

A: Here you go: as talked about in previous comments. A jsFiddle that does what you want in Jquery.
http://jsfiddle.net/HhpW5/5/
You asked specifically how to change between the divs
I do that in this demo simply by using the XOR bitwise operator and concatenating to the prefix: "demo" resulting in: "demo0" or "demo1"
  toggle^=1;

Everything else is pretty self explanatory with my comments. Hope this helps.

A: Try this:-
See Transition
Play around with transtions
#demo {
  background: #969696;
  width: 400px;
  height:300px;
  color: white;
  font-size: 50px;
  font-family: verdana;
  -webkit-transition: background 300ms ease-in 200ms; /* property duration timing-function delay */
    -moz-transition: background 300ms ease-in 200ms;
    -o-transition: background 300ms ease-in 200ms;
    transition: background 300ms ease-in 200ms;
}


text:
Q: data structure in autocad drawings I have to read all the tags out of an autocad drawing with information about the model, the cell, the tagset etcetera in which they were found.
Are the following assumptions correct;
tags are only found in tagsets.
multiple tags within a tagset can have the same name.
tagsets are only found in cells.
the names of tagsets within a cell are unique.
cells are only found within models (and not nested in other cells)
multiple cells within a model can have the same name.
models are only found at the 'top level' in drawings.
the names of models within a drawing are unique.
thanks,
Coen

A: Go here: http://docs.autodesk.com/ACD/2010/ENU/AutoCAD%20.NET%20Developer%27s%20Guide/index.html and navigate to Basics of the AutoCAD .NET API --> Understand the AutoCAD Object Hierarchy to get an idea of the AutoCAD database structure.
For answers to specific questions search the forums at:

*

*http://forums.augi.com/forumdisplay.php?f=88

*http://www.theswamp.org/index.php

*http://forums.autodesk.com/t5/AutoCAD-Customization/ct-p/1002
By "tagsets" do you mean collections of attributes in a block or are you talking about tables ("cells")?


text:
Q: how can I simulate the MMA7361L? I wanted to know if there is a simulator that could include the model of the capcitive accelerometer NXP MMA7361L, and if there is a tool-box in matlab that could include it or should I find the transfert fonction first to simulate in matlab ?
Thanks in advence.


text:
Q: How can I get an immutable version of an object from store.getState()? I'm using react-redux for a project I'm working on. I noticed that when I grab an object from my store and edit it, the object in state changes without me dispatching the change (but doesn't trigger a re-render on the components attached to that reducer's object). How can I stop state from changing without a dispatch?
For example if I do:
    export function changeNeonGreenColourValue(colour) {
        return (dispatch) => {
             var neonColours = store.getState().colours.neon;
             neonColours.green = colour;
             dispatch(push('./home'));
        };
    }

And then in the layoutComponent I log:
console.log(this.props.state.colours.neon.green)

The output is still whatever I passed into changeNeonGreenColourValue() as "colour" but the page doesn't re-render to show that change. I know to get the page to re-render, all I have to do is dispatch the appropriate reducer case but I don't want the state object being altered at all unless I have an appropriate dispatch.

A: Apparently the 'standard' deep copying technique for solving this is to do a JSON stringifying and parse as so: const copiedObj = JSON.parse(JSON.stringify(sourceObj)); Unfortunately if you use this on large objects that will need parsing frequently you're going to have performance issues in your app as I do, if anyone has any suggestions for this I welcome them.
edit: so both jQuery and Loadash have their own implementations of deep cloning that are supposed to be better performance-wise:
https://lodash.com/docs/#cloneDeep
I personally implemented loadash to resolve my issue and it worked fine with little to no performance issues. I highly recommend it over JSON.stringify.


text:
Q: Pairs matrix with qq-plots It is helpful to be able to view your data.  When you have several variables, you can form a scatterplot matrix with, for example, pairs().  A scatterplot matrix gives you a set of 2D marginal projections of your data.
set.seed(8092)
X <- matrix(rnorm(80), ncol=4)
pairs(X)

You can also have data for different groups and want to compare their distributions.  Two such distributions can be compared with a qq-plot.
set.seed(4415)
group1 <- rnorm(20)
group2 <- rnorm(20)
qqplot(group1, group2)
abline(c(0,1))

When you have several groups, it would be convenient if there were a pairs-type plot that would display a matrix of qq-plots.
colnames(X) <- c("group1", "group2", "group3", "group4")
qq.pairs(X)

Is there such a function?  Is there a straightforward way to code it from scratch?

A: You can add whatever function you like via the *panel args. For example:
set.seed(8092)
X <- matrix(rnorm(80), ncol=4)

panel.qq <- function(x, y, ...) {
  usr <- par("usr"); on.exit(par(usr))
  par(usr = c(0, 1, 0, 1), new = TRUE)
  qqplot(x, y, xlab = deparse(substitute(x)), ylab = deparse(substitute(y)))
  abline(c(0,1), ...)
}

pairs(X, lower.panel = panel.qq)

Of course you can use panel=panel.qq to make all the squares qq plots

A: I got an error with just putting qqplot in the panel function which it appears @rawr solved by using 'new=TRUE'. My approach was to pull out the x and y values and use points:
panel.qq <- function(x,y, ...)
{    usr <- par("usr"); on.exit(par(usr))
    par(usr = c(usr[1:2], -2,2) )
    QQ <- qqplot(x,y, plot.it = FALSE)
    x <- QQ$x;
    y <- QQ$y;
    points(x, y, col = "cyan", ...)
    abline(0,1)
}

set.seed(8092)
X <- matrix(rnorm(80), ncol=4)
pairs(X, upper.panel=panel.qq)