text:
Q: Variety acquiring rational point over any quadratic extension Does there exist a variety $X$ over $\mathbb{Q}$ (or a number field) such that it has no rational points over $\mathbb{Q}$ but acquires points over any quadratic extension $\mathbb{Q}(\sqrt{d})$?
If there is an example, how often can this happen?
Can we generalize to an extension of fixed degree?
(This might be a stupid question and I'm guessing answer is no, but I couldn't show it)

A: According to this answer by Laurent Moret-Bailly, the set of rational non-squares is diophantine over the rationals (a result of Bjorn Poonen):
there is a polynomial $P(a,x_1,\dots,x_n)$ which for $a\in\mathbb{Q}$ has a rational solution
iff $a$ is a rational non-square. For the variety, take the hypersurface with equation $P^2+(x_{n+1}^2-a)^2=0$ in $n+2$ coordinates $(a,x_1,\dots,x_{n+1})$.

A: Per Gazerun's comment answer to related question which leads
to relaxation of the OP.
This is possible over the integers for all $d$
and the question can be relaxed
by allowing finitely many points over the rationals.
First we define the set $\{1,-1\}$ with the equation $(m-1)(m+1)=0$.
The only integers solutions to $x^2-m n^2y^2=1$ are
$x=\pm 1, ny=0$ and $y=\pm 1,x=0$ and $n=\pm 1,x=0$.
Over $\mathbb{Z}[\sqrt{d}]$ for $n=\sqrt{d}$ this is
Pell equation $x^2 \pm ny^2=1$ with infinitely many solutions and if $d$
is square we are in the above case.
So we must get rid of the bad points $x=\pm 1,0$.
Use the following cheap trick: $ (x^2-1)x z = 1$. This is linear in $z$
unless $(x^2-1)x=0$ which leads to $0=1$.
So our final system of equations is
$(m-1)(m+1)=0,x^2-m n^2y^2=1, (x^2-1)x z = 1$ which doesn't have integer solutions
but have infinitely many over $\mathbb{Z}[\sqrt{d}]$ for all
$d$. If $d$ is negative chose $m=-1$ otherwise $m=1$

Partial result, some one could try to extend it.
It is possible to define variety the complement of $x=y^2$,
that is $x \ne y^2$:
$$ zt=1 \qquad (1)$$
$$ (x-y^2) z=1 \qquad (2)$$.
In (1) and (2) $z$ can be any nonzero rational. $x\ne y^2$ for
obvious reasons and $x-y^2=1/z$.
Appears to me this allows to describe the complement of variety
given by single equation.

A: Consider a hyperelliptic curve $y^2=f(x)$. I think by Falting's theorem on subvarieties of abelian varieties, we know that all but finitely many points of this over quadratic subfields have $x \in \mathbb Q$.
So this curve is such a variety if and only if the equation $y^2 D = f(x)$ has solutions for all but finitely many squarefree $D$.
Heuristically this shouldn't happen as the squarefree part of a random number $n$ is rarely much smaller than $n$, so the squarefree parts of $f(x)$ should grow quickly with $x$, because $f(x)$ has degree at least $3$, and so most numbers should not appear. In other words, because most hyperelliptic curves have no rational points, we expect the family $y^2 D = f(x)$ to mostly have no rational points, unless there is something strange going on with $f$.
But can this property actually be established for hyperelliptic curves?

A: Will Sawin and Michael Stoll have noted that, as a consequence of Faltings's "Big Theorem," a hyperelliptic equation $y^2 = f(x)$ with $\deg{f} > 6$ (genus $> 2$) and not admitting a degree $2$ non-constant map to an elliptic curve, has all but finitely many of its quadratic solutions $x, y \in \mathbb{Q}(\sqrt{d}), \, d \in \mathbb{Z}$, satisfy $x \in \mathbb{Q}$. We may add to this an argument due to Granville in Rational and integral points of quadratic twists of a given hyperelliptic curve to show:
Claim. The ABC conjecture implies, for a fixed $f$ having $\deg{f} > 6$ and no repeated roots, that the number of squarefree $d$ in $|d| \leq D$ for which the equation $dy^2 = f(x)$ has a rational solution with $y \neq 0$, is $O(D^{2/3+o(1)})$.
This answers Will's question under ABC. Hence ABC takes care of the problem for most $y^2 = f(x)$ - save for the ones of genus one or two or those doubly covering an elliptic curve. (For rational curves $C/\mathbb{Q}$ the problem is easy: Hasse's theorem shows that $C(\mathbb{Q}) = \emptyset$ is only possible when $C(\mathbb{Q}_p) = \emptyset$ for some prime $p$, but then $C$ will not have points in any quadratic field $\mathbb{Q}(\sqrt{d})$ split by $p$.) It seems to me that the case of hyperelliptic curves of genus $> 2$ doubly covering an elliptic curve can be settled under ABC by similar methods (Faltings's theorem and a modification of Granville's argument), whereas the genus one case should be solved unconditionally by Kolyvagin's theorem and non-vanishing results, cf. Chris Wurthrich's comment in the linked question. I am not sure about the genus two case though - it is barely missed by the argument below.
Proof of the claim. (Granville). M. Langevin has noted (cf. Thm. 12.2.12 in Heights in Diophantine Geometry by Bombieri and Gubler) that Elkies's construction for "ABC $\Rightarrow$ Roth" via Belyi maps yields in fact much more than Roth's theorem:
Lemma. Let $\varepsilon > 0$ and let $F \in \mathbb{Z}[X,Y]$ be a homogeneous polynomial with distinct linear factors over $\mathbb{C}$. Then for all co-prime $m,n$ with $F(m,n) \neq 0$, the (strong) ABC conjecture implies $\mathrm{rad}(F(m,n)) \gg_{\varepsilon,F} \max(|m|,|n|)^{\deg{F}-2-\varepsilon}$.
The ABC conjecture is recovered as the special case $F(X,Y) = XY(X+Y)$, whereas Roth's theorem is just the weakening of this statement dropping the radical.
We apply this is follows. Consider the $\asymp T^2$ rational values $x = m/n \in \mathbb{Q}$ with $T \leq \max(|m|, |n|) < 2T$, $(m,n)=1$, $n > 0$, and $f(x) \neq 0$. Writing $du^2 = F(m,n)$ with $F$ the homogenization of $f$, the above quoted form of ABC yields
$$
(DT^{\deg{f}})^{1/2} \gg_f |dF(m,n)|^{1/2} = |du| \geq \mathrm{rad}(F(m,n)) \gg_{\varepsilon,F} T^{\deg{f} - 2 - \varepsilon},
$$
or $D > T^{\deg{f} - 4 - o(1)}$, in $|d| \leq D$. As the irreducible fraction $x$ uniquely determines the squarefree part $d$, we get what we want by splitting the range $T < D^{1/(\deg{f}-4-o(1))}$ into dyadic intervals.


text:
Q: What is numerical overflow? I came across an error of numerical overflow when running a maximum likelihood estimation on a log-linear specification.
What does numerical overflow mean?

A: It means that the algorithm generated a variable that is greater than the maximum allowed for that type of variable. That is due to the fact that computers use a finite number of bits to represent numbers, so it is not possible to represent ANY number, but only a limited subset of them.
The actual value depends on the type of variable and the architecture of the system.
Why that happens during a MLE I'm not sure, my best call would be that you should change the starting parameters.

A: You can probably avoid your overflow problems by working with the log of the likelihood function rather than the likelihood function itself.  Both have the same maximum.

A: As stated by nico, numerical overflow is when computation finds a number that is too great for the limited number of bits allocated by software to store the number. For example, if your software uses 32 bits to store integers, then computing an integer that is greater than 2,147,483,648 (or smaller than -2,147,483,648) will cause overflow.
One common reason for numerical overflow is trying to divide by a very small (close to zero) number. If the absolute values of your numbers are not too large, Look at your data and try to figure out where you might be dividing by a very small number.

redpajama_set_name: RedPajamaStackExchange


text:
Q: JQuery make BootStrap DropDown menu open class Go Away / Collapse I am trying to make my AJAX JQuery code to close the BootStrap dropdown menu after clicking on the link element that nested inside the dropdown menu,
Note: I only want to close the dropdown that has the link I clicked on!!!
This is the code snippet of my HTML :

GPU

Brands

                <form id="gpu_form" action="create/" method='POST'>
                {% csrf_token %}
                <input name='manuf' value="amd" class="gpu_form_input">
                <input name='manuf' value="nvidia" class="gpu_form_input">

AMD

NVIDIA

                </form>

This is my AJAX CODE . IT IS NOT WORKING:
/*GPU FORM click on input event*/
                $('.gpu_form_input').on('click',function(event){
                    console.log('this.serialize=',$(this).serialize());

                    $.ajax({
                        method: 'POST',
                        url: 'findGPU/',
                        data: {csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value,data:$(this).serialize()},
                        success: function(serverResponse){
                            console.log('success, testing', serverResponse);
                            $('.placeholder').html(serverResponse);

                            $(this).parent().parent().parent().parent().parent().parent().toggleClass("open");
                            console.log('end of success action.');
                        }
                    })

                });

Basically once the ajax update the part of the home page, I want the open drop down to go away by removing the 'open' class from the bootstrap, apparently it is not going anywhere...
This makes me feel like a little kid being mad when he cannot assemble his Lego.


text:
Q: Card Detect Pin of SDHC Interface I am working on a design with a processor which has I2C SCL line & SDHC_CD(Card Detect) pins multiplexed. I need to use I2C line. I am giving SD Card for boot code of processor. I have below doubts :-

*

*Is it mandatory to connect Card Detect pin to the Host?

*If I dont use SDHC_CD, Will the Processor be able to read from SD Card?

*If I need to use CD pin, Is there any way to use both functionalities?

Can anyone please share the link for SDHC protocol?

A: *

*Is it mandatory to connect Card Detect pin to the Host?

*

*No. If you use MMC protocol (or 1 bit SD protocol), the bare minimum pins that need to be connected are just these three: CMD, CLK and DAT0. And power and ground, of course. If you use SPI protocol, then you need the Chip Select pin also.

*If I dont use SDHC_CD, Will the Processor be able to read from SD Card?

*

*Yes. The Card Detect pin isn't actually connected to the card at all, it's a mechanical switch at the slot.

*If I need to use CD pin, Is there any way to use both functionalities?

*

*Maybe. It depends on how the Card Detect pin is connected in your system. If it's a hard pull-down to ground when the SDHC card is connected, then it's stuck low and you can't do anything about it (except desolder it from the connector). If not, then there is some hope.

*Can anyone please share the link for SDHC protocol?

*

*This is the public, official, simplified specification, which is freely available: https://www.sdcard.org/downloads/pls/simplified_specs/. But you might benefit more from some software examples, as the specification is tedious reading and the real life is in some parts simpler than the spec. But there are a lot of pitfalls also...


text:
Q: Build SQL query from logger table I have a logger table with the following fields: timestamp, point_id, value.
An external application is using this table and every time a value of point_id is changing, the application writes a record with the timestamp, point_id and value.
I want to create a query that returns me values of several point_id's (for example - 'point_id='AA1' or point_id='AA2') and their values in a timestamp window ('where timestamp between @start and @end').
Can anyone please help me build an SQL statement to run this query?

A: Are you looking for something like the following?
DECLARE @startDatetime DATETIME = '2018-03-01 10:00:00'
DECLARE @endDatetime DATETIME = '2018-03-20 12:00:00'

IF OBJECT_ID('tempdb..#Points') IS NOT NULL
  DROP TABLE #Points

CREATE TABLE #Points (point_id VARCHAR(100) PRIMARY KEY)

INSERT INTO #Points (point_id)
VALUES
  ('AA2'), -- your point IDs
  ('A10')

SELECT
  L.point_id,
  L.timestamp,
  L.value
FROM
  LoggerTable AS L
  INNER JOIN #Points AS P ON L.point_id = P.point_id
WHERE
  L.timestamp BETWEEN @startDatetime AND @endDatetime
ORDER BY
  L.point_id,
  L.timestamp


text:
Q: Unable to upload APK with Google Play Services 6.1 to the Play Store I updated the Play Services SDK because I heard there were new Chromecast features, but when I try to upload an APK built with the latest Google Play Services I get the following error:
You uploaded an APK that uses Google Play services version 6111000. You need to use version 5100000 or lower.

I tried changing the meta-data to use an older version (5100000) and the app just crashes with an error that says Expected 6111000 but found 5100000
So what are my options?

A: We have pushed a fix for that, please try again and see if that is fixed or not; it may take a little while for the fix to propagate globally but should be there very soon.

A: Same thing happens to me too. Personally I am going to wait for a few days until google fix this. But you can download an older version here


text:
Q: SQL Server DB Engine Memory Leakage We have a Windows Form Application and the back-end of the application is SQL Server Express 2005/2008. Our application can be installed on Windows XP SP3/ Windows Vista/ Windows 7.
We have observed huge memory leakage in SQL Server Express.
Normally, there are two process running even if the application is not used by the user:

*

*A polling process to check the availability of files. (If files are not available then, only one query is fired to check some configuration setting)

*A Scheduling process. (This process fires a query every minute to check for any scheduled task)
We have observed that the memory usage of the SQL Server (sqlsrvr.exe) keeps on increasing.  In around an hour, the memory usage reaches upto 1GB and it never comes down.
We have also noticed that, if the interval of the polling process is increased, then the memory usage increases gradually but, it does increase.
The higher memory usage by SQL server downgrades the machine performance and  the performance of all other applications running on the machine.
Please provide suggestions to control the memory usage of SQL server in this case.
PFB the details:

*

*Software causing issue :SQL Server 2005/2008 Express editions (named instance)

*Operating Systems on which issue can be simulated  : Windows XP SP3/ Windows Vista/ Windows 7
Regards,
Abhineet

A: SQL Server is designed to take all the memory on the system and use it for its internal cache. You should never run anything else on the same machine as SQL Server. This is not a leak, is the intended and desired behavior. By design. See Memory Manager Architecture
As a special case SQL Server Express edition limits its internal buffer pool size to 1Gb. The buffer pool is not the only memory consumed by SQL Server though. You can further limit the SQL Server buffer pool size by specifying a value for max server memory.


text:
Q: Creating summed summary rows in pandas dataframe with specific criteria Lets say I have the following pandas dataframe, and I am trying to post process the results to generate my (now blank) summary rows:
    code    entry_type  value1  value2  value3  value4
1   A       Holding     1.1     1.2     1.3     1.4
2   A       Holding     2.1     2.2     2.3     2.4
3   B       Holding     3.1     3.2     3.3     3.4
4   C       Holding     4.1     4.2     4.3     4.4
5   C       Holding     5.1     5.2     5.3     5.4
6   A       Summary     nan     nan     nan     nan
7   C       Summary     nan     nan     nan     nan
8   B       Summary     nan     nan     nan     nan

Essentially, I would like the value1-value4 in the summary lines to be the sum of the holdings in each of the code:
    code    entry_type  value1  value2  value3  value4
1   A       Holding     1.1     1.2     1.3     1.4
2   A       Holding     2.1     2.2     2.3     2.4
3   B       Holding     3.1     3.2     3.3     3.4
4   C       Holding     4.1     4.2     4.3     4.4
5   C       Holding     5.1     5.2     5.3     5.4
6   A       Summary     3.2     3.4     3.6     3.8
7   C       Summary     9.2     9.4     9.6     9.8
8   B       Summary     3.1     3.2     3.3     3.4

I have tried a few group-by lines of code, and came up with the following:
set = df[df['entry_type']=="Holding"].groupby('code')[['value1', 'value2', 'value3', 'value4']].sum()

Which yields:
        value1  value2  value3  value4
code
    A   3.2     3.4     3.6     3.8
    B   3.1     3.2     3.3     3.4
    C   9.2     9.4     9.6     9.8

However I am not sure how I would apply this back to the original DataFrame, specifically due to the fact that the code order is not necessarily the same as the original DataFrame.  Any thoughts on how to apply this?  Or a better approach?  (Note- there is a bunch of additional data in the summary rows in other columns that already exists, so I can't just generate the new rows inline).

A: It seems concat can helps:
df1  = df[df['entry_type']=="Holding"]
         .groupby('code')[['value1', 'value2', 'value3', 'value4']].sum()
#print (df1)

#if need filter `df` for only rows with Holding use boolean indexing
print (pd.concat([df[df['entry_type']=="Holding"].set_index('code'), df1])
         .fillna({'entry_type':'Summary'})
         .reset_index())

  code entry_type  value1  value2  value3  value4
0    A    Holding     1.1     1.2     1.3     1.4
1    A    Holding     2.1     2.2     2.3     2.4
2    B    Holding     3.1     3.2     3.3     3.4
3    C    Holding     4.1     4.2     4.3     4.4
4    C    Holding     5.1     5.2     5.3     5.4
5    A    Summary     3.2     3.4     3.6     3.8
6    B    Summary     3.1     3.2     3.3     3.4
7    C    Summary     9.2     9.4     9.6     9.8

Another possible solution with combine_first for replace NaN by df1 with align by index values of df:
print (df.set_index('code')
         .combine_first(df1)
         .sort_values(['entry_type'])
         .reset_index())

  code entry_type  value1  value2  value3  value4
0    A    Holding     1.1     1.2     1.3     1.4
1    A    Holding     2.1     2.2     2.3     2.4
2    B    Holding     3.1     3.2     3.3     3.4
3    C    Holding     4.1     4.2     4.3     4.4
4    C    Holding     5.1     5.2     5.3     5.4
5    A    Summary     3.2     3.4     3.6     3.8
6    B    Summary     3.1     3.2     3.3     3.4
7    C    Summary     9.2     9.4     9.6     9.8


text:
Q: Azure Managed Application Is there any extensibility/functionality in Azure Managed Applications to publish a custom administration UI (used by the customer after the deployment of the Managed Application to their tenant)? I'm looking to basically expose a custom admin UI embedded in the Azure management portal.

A: There are a few ways a managed application authors can customize their UX:

*

*CreateUIDefinition: This is a mandatory file that is part of the managed app package that customizes the customer's onboarding experience. You can utilize different controls we've made available to take whatever input needed from the customer to be used within the mainTemplate.json for deploying the application resources.

o   Creating CreateUIDef
o   Testing CreateUIDef

*Custom Actions & ViewDefinition: Managed Applications can utilize another resource called an Azure Custom Provider that allows them to define custom actions that can be taken on the Azure Managed Application itself. You can combine this with a ViewDefinition to provide buttons and UI on the Managed Application that can invoke these actions, such as restarting or stopping the app.

o   A tutorial of Custom Providers and View Definitions: Tutorial: Create managed application with custom actions and resources
o   Overview of ViewDefinition and what is possible with it today: Concept: ViewDefinition
o   All documentation for Azure Custom Providers: https://learn.microsoft.com/en-us/azure/azure-resource-manager/custom-providers/overview


text:
Q: input slider in react
I have to create a slider as values are male, female and other based on slider on left, middle and right and highlight the value based on slider value. Help me as I am not getting any help from internet. Any help will be appreciated.


text:
Q: background flashes during image swap cross disolve, CATransition Currently I have a CATransistion that should swap out the _backgroundImageView.image with a new one.  It works great... And works quickly, however the previous image will glitch during this transition randomly... Aka flash the full image for one frame somewhere in the duration of the transition and then finish the transition.
Here is the code:
[CATransaction begin];

CATransition *transition = [CATransition animation];
transition.type = kCATransitionFade;
transition.duration = 0.3;
transition.delegate = self;
[transition setValue:@"swipe" forKey:@"tag"];
[_backgroundImageView.layer addAnimation:transition forKey:nil];

 _backgroundImageView.image = [_backgroundImages objectAtIndex:pageControl.currentPage];
[CATransaction commit];

If I add this before the code then the glitch doesnt happen but other UI stuff gets choppy because the image comparison seems to block the main thread (which it has to as the animation is a main thread thing too)
if ([UIImagePNGRepresentation(_backgroundImageView.image) isEqualToData:UIImagePNGRepresentation([_backgroundImages objectAtIndex:pageControl.currentPage])]) {
    return;
}

BTW flickering doesn't happen on the device.... at least so far I can see... so maybe this question is moot... I have seen crashes during transitions... but that might be another issue.


text:
Q: Restructure csv file Here is an example of the data I'd like to modify:
John,,
bim,bam,boom
tim,tam,toom
lam,loom,lim
Mary,,
pam,pim,poom
dam,dim,doom*

I try to achieve this:
John,bim,bam,boom
John,tim,tam,toom
John,lam,loom,lim
Mary,pam,pim,poom
Mary,dam,dim,doom

When a name is alone on a line, it becomes a new column in all the rows below til the next name with the same pattern occurs.
I wonder if awk or another tool could help but I'm a bit lost.
I try to make a condition (if columns 2 and 3 are empty, do something) but that looks a bit complicated for me right now.

A: You are thinking on the right lines:

I try to make a condition (if columns 2 and 3 are empty, do something)

Specifically,

*

*if columns 2 and 3 are empty, save the value of column 1 and continue

*otherwise, prepend the saved value to the line and print it (there are several awkish ways to do this)

So for example
awk -F, '$2=="" && $3=="" {pfx=$1; next} {print pfx "," $0}' file.csv

or more idiomatically using the FS field separator variable
awk -F, '$2=="" && $3=="" {pfx=$1; next} {$0 = pfx FS $0; print}' file.csv

or (since the default action - when a rule evaluates true or 1 - is to print the record)
awk -F, '$2=="" && $3=="" {pfx=$1; next} {$0 = pfx FS $0} 1' file.csv
John,bim,bam,boom
John,tim,tam,toom
John,lam,loom,lim
Mary,pam,pim,poom
Mary,dam,dim,doom

A: Perl alternative:
$ perl -F',' -lane 'if(@F == 1){$prefix = sprintf("%s,",@F);next;};print $prefix . $_' input.csv
John,bim,bam,boom
John,tim,tam,toom
John,lam,loom,lim
Mary,pam,pim,poom
Mary,dam,dim,doom

This operates on the premise that each line is split into array of elements using , as operator, and if there's only one item in that array,we use that line as prefix and go to next line. Other lines that are longer than 1 element will get prefix appended to them. Naturally, the prefix changes if and only if the array is of length 1.
Or shorter, using shift as suggested by Glenn Jackman:
$ perl -F',' -lane 'if(@F == 1){$prefix = shift @F;next;};print $prefix . "," . $_' input.csv

Or
$ perl -F, -lane '$,=","; if (1 == @F) {$name = shift @F} else {print $name, @F}' input.csv


text:
Q: Dependency injection with Guice for several implementations of same interface I'd like to try to use Guice in my project, and stucked on simple(from my point of view) problem.
Assume that i have interface
public interface TradeService {
        public boolean buy(Player player, ProductID productId);
}

which have several implementations with it's dependencies:
 public CarsTradeService implements TradeService {
      //...implementation here...
    }

    public BoatsTradeService implements TradeService {
      //...implementation here...
    }

    public AirplanesTradeService implements TradeService {
      //...implementation here...
    }

I understand how to configure implementations and provide needed dependencies for them - to do this i need to create guice "modules" which will look like
public class CarsTradeModule extends AbstractModule {
    @Override
    protected void configure() {
     bind(TradeService.class).to(CarsTradeService.class).in(Singleton.class);
    }
}

And similar modules to rest two services. Ok, modules builded. But later, when i need to inject this implementations to some class - how could i inject exactly needed implementation?
For example, if i need to get instance of CarsTradeService - how could i get exactly this instance?

A: You can use annotatedWith and @Named for doing exactly that.
bind(TradeService.class).annotatedWith(Names.named("carsTradeService")).to(CarsTradeService.class).in(Singleton.class);

And in the class you want to inject this bean you need to use
@Inject
@Named("carsTradeService")
private TradeService tradeService;

This will inject the exact class you need.

A: You can use guice multi binding. It is a guice extension.
https://github.com/google/guice/wiki/Multibindings

@Override
public void configure() {
  Multibinder.newSetBinder(binder(),TradeService.class)
  .addBinding()
  .to(CarsTradeService.class);

  Multibinder.newSetBinder(binder(),TradeService.class)
  .addBinding()
  .to(BoatsTradeService.class);

  Multibinder.newSetBinder(binder(),TradeService.class)
  .addBinding()
  .to(AirplanesTradeService.class);
}


text:
Q: How to pass props into an exported function? //App.js

import React from 'react';
import Form from './Form'

class App extends React.Component{

render(){

return

<Form something={true}>

}

}

//Form.js

import React from 'react';
export default class Form extends React.Component{

render(){

return()

}
}

//Index.js
import Form from './Form';
import React from 'react';

export default (props)=>{

<Form {...props} />

}

The directory structure:
(Components
->App.js
->(Form -> Form.js, Index.js))
In App.js which component would Form be referring to because im importing from a folder? Both files insider this folder have a default export.
So why is the prop passed into index.js instead of form.js?


text:
Q: Retrieving config from a blueprint in Sanic app I have a Sanic application, and want to retrieve app.config from a blueprint as it holds MONGO_URL, and I will pass it to a repository class from the blueprint.
However, I could not find how to get app.config in a blueprint. I have also checked Flask solutions, but they are not applicable to Sanic.
My app.py:
from sanic import Sanic
from routes.authentication import auth_route
from routes.user import user_route

app = Sanic(__name__)
app.blueprint(auth_route, url_prefix="/auth")
app.blueprint(user_route, url_prefix="/user")

app.config.from_envvar('TWEETBOX_CONFIG')
app.run(host='127.0.0.1', port=8000, debug=True)

My auth blueprint:
import jwt
from sanic import Blueprint
from sanic.response import json, redirect
from domain.user import User
from repository.user_repository import UserRepository
...

auth_route = Blueprint('authentication')
mongo_url = ?????
user_repository = UserRepository(mongo_url)
...

@auth_route.route('/signin')
async def redirect_user(request):
    ...

A: I would suggest a slightly different approach, based on the 12 Factor App (very interesting read which, among others, provides a nice guideline on how to protect and isolate your sensitive info).
The general idea is to place your sensitive and configuration variables in a file that is going to be gitignored and therefore will only be available locally.
I will try to present the method I tend to use in order to be as close as possible to the 12 Factor guidelines:

*

*Create a .env file with your project variables in it:
MONGO_URL=http://no_peeking_this_is_secret:port/
SENSITIVE_PASSWORD=for_your_eyes_only
CONFIG_OPTION_1=config_this
DEBUG=True
...

*(Important) Add .env and .env.* on your .gitignore file, thus protecting your sensitive info from been uploaded to GitHub.

*Create an env.example (be careful not to name it with a . in the beginning, because it will get ignored).
In that file, you can put an example of the expected configuration in order to be reproducible by simply copy, paste, rename to .env.

*In a file named settings.py, use decouple.config to read your config file into variables:
from decouple import config

MONGO_URL = config('MONGO_URL')
CONFIG_OPTION_1 = config('CONFIG_OPTION_1', default='')
DEBUG = config('DEBUG', cast=bool, default=True)
...

*Now you can use these variables wherever is necessary for your implementation:
myblueprint.py:
import settings

...
auth_route = Blueprint('authentication')
mongo_url = settings.MONGO_URL
user_repository = UserRepository(mongo_url)
...

As a finisher, I would like to point out that this method is framework (and even language) agnostic so you can use it on Sanic as well as Flask and everywhere you need it!

A: The Sanic way...
Inside a view method, you can access the app instance from the request object. And, therefore access your configuration.
@auth_route.route('/signin')
async def redirect_user(request):
    configuration = request.app.config

2021-10-10 Update
There are two newer ways to get to the configuration values (or, perhaps more accuratlely getting the application instance from which you can get the configuration). The first version might be more on point to answering the question of how to get to the config from the blueprint. However, the second option is probably the preferred method since it is precisely intended for this kind of use.
Alternative #1
Blueprints have access to the Sanic applications they are attached to beginning with v21.3.
Therefore, if you have a blueprint object, you can trace that back to the application instance, and therefore also the config value.
app = Sanic("MyApp")
bp = Blueprint("MyBlueprint")

app.blueprint(bp)

assert bp.apps[0] is app

The Blueprint.apps property is a set because it is possible to attach a single blueprint to multiple applications.
Alternative #2
Sanic has a built-in method for retrieving an application instance from the global scope beginning in v20.12. This means that once an application has been instantiated, you can retrieve it using: Sanic.get_app().
app = Sanic("MyApp")

assert Sanic.get_app() is app

This method will only work if there is a single Sanic instance available. If you have multiple application instances, you will need to use the optional name argument:
app1 = Sanic("MyApp")
app2 = Sanic("MyOtherApp")

assert Sanic.get_app("MyApp") is app1

A: There is a variable named current_app in Flask. You can use current_app.config["MONGO_URL"].
But I am not familiar with Sanic.

A: I think you can create a config.py to save your configuration, just like
config.py
config = {
    'MONGO_URL':'127.0.0.1:27017'
}

and use it in app.py
from config import config

mongo_url = config['MONGO_URL']


text:
Q: Button value not sent in formdata to servlet I am using multiple buttons and only one of them can be selected (like a group of radio buttons). I am trying to get the value of the button which is selected in my servlet, but it is returning null. I have attached my code below.
JS PAGE
$.each($('.radio-btn'), function(key, value) {
  $(this).click(function(e) {
    $('.radio-btn-selected').removeClass('radio-btn-selected').addClass('radio-btn');
    $(this).removeClass('radio-btn').addClass('radio-btn-selected');

    // do whatever you want on click
  });
});

CSS PAGE
.radio-btn {
  background-color: #FFFFFF;
  border: 1px solid #4A4A4A;
  color: #4A5362;
  font-size: 14px;
  line-height: 26px;
  outline: none;
  padding: 7px;
  cursor: pointer;
}

.radio-btn-selected {
  background-color: #FFFFFF;
  border: 1px solid #55BC7E;
  color: #55BC7E;
  font-size: 14px;
  line-height: 26px;
  outline: none;
  padding: 7px;
  cursor: no-drop;
}

JSP PAGE
<form action="<%=request.getContextPath() %>/BookAppointment" method="POST">

          <button id="bt1" class="radio-btn" name="slot" type="button" value="10:00 AM">10:00 AM</button>

          <button id="btn2" class="radio-btn" name="slot" type="button" value="10:30 AM">10:30 AM</button>

          <button id="btn3" class="radio-btn" name="slot" type="button" value="3:00 PM">03:00 PM</button>

          <button id="btn4" class="radio-btn" name="slot" type="button" value="3:30 PM">03:30 PM</button>

<input type="submit" class="submit" value="Book Appointment">

</form>

Servlet Page
package com.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/BookAppointment")
public class BookAppointment extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public BookAppointment() {

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String date=request.getParameter("date");
        String slot=request.getParameter("slot");
        System.out.println(date+" "+slot1);
    }
}

Any suggestions would be appreciated.

A: You seem to be expecting the value of the 'selected' button to be sent in the form submission - this is not how buttons work. To fix this you will need to amend either your JS or HTML.
The first approach would be to include a hidden field which you update when a button is selected. Note in your jQuery that you don't need the $.each() loop; click() will be applied to all elements in the jQuery object.

$('.radio-btn').click(function(e) {
  $('.radio-btn-selected').removeClass('radio-btn-selected').addClass('radio-btn');
  $(this).removeClass('radio-btn').addClass('radio-btn-selected');

  $('#slot').val(this.value);
});
.radio-btn-row {
  display: flex;
  flex-direction: row;
  margin-top: 20px;
}

.radio-btn-wrapper {
  margin: 0px 4px;
}

.radio-btn {
  background-color: #FFFFFF;
  border: 1px solid #4A4A4A;
  color: #4A5362;
  font-size: 14px;
  line-height: 26px;
  outline: none;
  padding: 7px;
  cursor: pointer;
}

.radio-btn-selected {
  background-color: #FFFFFF;
  border: 1px solid #55BC7E;
  color: #55BC7E;
  font-size: 14px;
  line-height: 26px;
  outline: none;
  padding: 7px;
  cursor: no-drop;
}

.radio-btn-disabled {
  cursor: no-drop;
}

.submit {
  margin-top: 10px;
  padding: 5px;
  background-color: #33b5e5;
  border: 2px solid black;
  cursor: pointer;
}

<form action="<%=request.getContextPath() %>/BookAppointment" method="POST">

          <button id="bt1" class="radio-btn" name="slot-button" type="button" value="10:00 AM">10:00 AM</button>

          <button id="btn2" class="radio-btn" name="slot-button" type="button" value="10:30 AM">10:30 AM</button>

          <button id="btn3" class="radio-btn" name="slot-button" type="button" value="3:00 PM">03:00 PM</button>

          <button id="btn4" class="radio-btn" name="slot-button" type="button" value="3:30 PM">03:30 PM</button>

<input type="submit" class="submit" value="Book Appointment">

  <input type="text" id="slot" name="slot" />

</form>

The alternative approach would be to amend your HTML so that instead of using button elements, which don't send a value in the request, change them to actual radio inputs which do. In addition it means you don't need the JS to add/remove classes as the styling can all be done through CSS.


text:
Q: How to make a line spread from the center to the sides upon hover? I created a set of buttons which upon hovering will have a line under them appear from the right side going on till it reaches the extent of the button's width. But what I really want is for the line's origin of appearance to begin, not from the right side, but from the center and then end on both ways. How to do that? Can you guys plz help me?
HTML

          <button class="nav-button">Products</button>
          <button class="nav-button">Solutions</button>
          <button class="nav-button">Resources</button>
          <button class="nav-button">Academy</button>
          <button class="nav-button">Partners</button>
          <button class="nav-button">Company</button>

CSS
button{
  background:none;
  border:none;
  outline: none;
}

.nav-buttons{
  display: flex;
  align-items: center;
  column-gap: 30px;
}

.nav-button{
  font-size: 1rem;
  cursor: pointer;
  position: relative;
}

.nav-button::after{
  content: '';
  height: 3px;
  width: 0;
  background-color: #009688;
  position: absolute;
  left: 0;
  bottom: -20px;
  transition: width 0.5s;
}

.nav-button:hover::after{
  width: 100%;
}

A: Please try with this cod.

button{
  background:none;
  border:none;
  outline: none;
}

.nav-buttons{
  display: flex;
  align-items: center;
  column-gap: 30px;
}

.nav-button{
  font-size: 1rem;
  cursor: pointer;
  position: relative;
}

.nav-button::after{
  content: '';
  height: 3px;
  width: 0;
  background-color: #009688;
  position: absolute;
  left: 0;
  bottom: -20px;
  -webkit-transform: scaleX(0);
          transform: scaleX(0);
  -webkit-transition: -webkit-transform 250ms ease-in-out;
  transition: -webkit-transform 250ms ease-in-out;
  transition: transform 250ms ease-in-out;
  transition: transform 250ms ease-in-out, -webkit-transform 250ms ease-in-out;
  visibility: hidden;

}

.nav-button:hover::after{
  width: 100%;
  visibility: visible;
  -webkit-transform: scaleX(1);
          transform: scaleX(1);
}

  <button class="nav-button">Products</button>
  <button class="nav-button">Solutions</button>
  <button class="nav-button">Resources</button>
  <button class="nav-button">Academy</button>
  <button class="nav-button">Partners</button>
  <button class="nav-button">Company</button>


text:
Q: GET parameters on ajax call (into modal dialog) On an html page i click on a link and i get a dialog which loads server content through an ajax call.
I cannot change the javascript that created this dialog neither the ajax callbacks .
I have the need to access the href of the clicked link from another javascript to change some content loaded into the dialog from the ajax call. This after the dialog shows up.
As i can only read the window.location of the current page (the page containing the dialog, not the page loaded into the dialog itself), is there a way to get the href of the clicked link that caused the dialog to show up ? (ie. the GET parameters of the ajax call)
Attaching a callback for every clicked link doesn't work reliably because i have to catch just the last one that caused the dialog to open...
-- edit --
Well i'm using jquery, but i don't think it's implementation dependant.
The question more generally is: if i cannot access the ajax callback, is there a way to obtain the url in the GET request that caused a div (some content) to update ? (assuming you can call a javascript function after the div is loaded, inside it).
ie. if it was a popup (window.open) i just have to read window.location to get the page called, but as it's a div loaded from an ajax request, how i can get the url called ?
thanks anyway~

A: *

*Install Firefox (if you do not have it already)

*Install Firebug extension

*Enable firebug for your site

*Click the Link that launches the dialog (reproduce the situation)

*Open the firebug window (bottom right corner of firefox)

*Under Net - >XHR tab you can see the exact URL call with all GET/POST parameters that was triggered.

Then explore firebug some more to see what other possibilities it offers!


text:
Q: php store array in array by reference I have the following problem. There are some php lines.
In the var_dump of $testArrayA, the "def" entry with test2 is NOT there because it was added
after $testArrayB was added to $testArrayA.
It seems to me that in my case, that $testArrayB is not stored by reference in $testArrayA. How can I store it per reference, what do I have to make to have "def" entry in the var_dump?
Thanks alot in advance
$testArrayA = [];
$testArrayB = [];
$testArrayB["ghi"] = "test1";
$testArrayA["abc"] = $testArrayB;
$testArrayB["def"] = "test2";

The var_dump:
array(1) {
  ["abc"]=>
    array(1) {
       ["ghi"]=>
       string(5) "test1"
      }
}

A: This is simply a matter of passing by reference:
$testArrayA = [];
$testArrayB = [];
$testArrayB["ghi"] = "test1";
$testArrayA["abc"] = &$testArrayB;
$testArrayB["def"] = "test2";

var_dump($testArrayA);
array (size=1)
'abc' => &
array (size=2)
  'ghi' => string 'test1' (length=5)
  'def' => string 'test2' (length=5)

A: Use:
$testArrayA["abc"] = &$testArrayB;

Note:
Different with C's pointer, references in PHP are a means to access the same variable content by different names.

A: in the php manual
Array assignment always involves value copying. Use the reference operator to copy an array by reference.

A: $testArrayA = null;
$testArrayB = null;
$testArrayB["ghi"] = "test1";
$testArrayA["abc"] = $testArrayB;
$testArrayB["def"] = "test2";
print_r($testArrayA);
echo ("<br>");
print_r($testArrayB);

Array ( [abc] => Array ( [ghi] => test1 ) )
Array ( [ghi] => test1 [def] => test2 )

The 'def' entry is a different reference with the 'ghi',
but they all belong testArrayB.
$testArrayA["abc"] = $testArrayB;
This code only is value reference ,not address reference.


text:
Q: C++ undefined reference to ... and also warning: deprecated conversion from string constant to 'char*' in C++ i am getting these two errors
undefined reference to 'Employee::Employee'
warning: deprecated conversion from string constant to 'char*'

in the following two parts of my code. I know there are many topics about that but i can't solve it by my own.... What do I have to do to fix this?
1.
Employee::Employee(SymbolStr sstr, int* egn, int* cd)
{
    sbstr=sstr;
    for(int i = 0; i < 10; i++)
        id[i] = egn[i];
    for(int i = 0; i < 4; i++)
        code[i] = cd[i];
}

2.
int main()
{
    ofstream fileout("LuboHW.txt");
    cout << "Please, enter how many entries of employee's information would you like to make?" << endl;
    int count;
    cin >> count;
    //cin.ignore();
    Employee* emp = new Employee[count];
    for(int i = 0; i < count; i++)
    {
        cout << "Entering information about employee number " << i << ": " << endl;
        emp[i].read();
    }
    cout << "Please, enter the code of the desired employee position: " << endl;
    int cd[4];
    for(int i = 0; i < 4; i++)
        cin >> cd[i];
        //cin.ignore();
    //writing information about employee in fileout.txt, searching by code
    for(int i = 0; i < count; i++)
    {
        for(int j = 0; j < 4; j++)
        {
            if(*emp[j].getCode() == cd[i])
                continue;
            if(j == 3)
                fileout << emp[i] << endl;
        }
    }
    system("PAUSE");
    return 0;
}

A: To call new Employee[count] you need an Employee default constructor (Employee::Employee()).
Employee::Employee(SymbolStr sstr, int* egn, int* cd) isn't  a default constructor.


text:
Q: HTML Required Field Validation Issues I have a small HTML form created that has a required input field; when I hover the mouse over the field, it shows the message "Please fill in this field" but when I click the button to submit, the error message does not display.
Here is the section of code containing the input field and button:
    Web Word Count App

    <textarea id="paragraph" rows="5" cols="35" placeholder="Enter the paragraph here..." value="" required="true" >Enter the paragraph here...
    </textarea>

    <input  type="text" id="word"  placeholder="Enter the keyword here..." value="" required="true" >

    <input type="text" class="display" id="display-1" readonly=1 placeholder="Total word count = 0 " value="">

    <input type="text" class="display" id="display-2" readonly=1 placeholder="Keyword does not exist!" value="">

    <input type="text" class="display" id="display-3" readonly=1 placeholder="Total keyword appearances = 0" value="">

    <button class="wwcbutton" onclick="Word_count();">Total words?</button>

    <button class="wwcbutton" onclick="Check();">Check keyword appearance</button>

    <button  class="wwcbutton" onclick="keyword_count();">Total keyword appearances?</button>

    <button class="wwcbutton-clear" onclick="Clear();">Clear</button>

Could someone please advise me as to what might be wrong here. Thanks


text:
Q: Selecting Circle Segements I am creating a wheel / dial selector in windows using java, that would popup on a button press for the user to select one of the different segments to do what ever they have specified previously on creation of that segment.
I am stuck with how to select different segments of a circle, currently I have JLabels created around the circle using a custom layout but their interactive area is limited to a rectangle around the text.
How can I change this area to a triangle / pi segment?
Is there a better way to achieve this?
Here is an image where segment 4 has the area (highlighted in blue) that I want to achieve.

A: To be honest, there are any number of ways you might do this.  One of the simplest ways I can think of is to take advantage of the 2D Graphics Shape API.
The following example simply uses a Arc2D for simplicity, but the general concept should work for Path based shapes as well (if you want to get that complicated)

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Arc2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private Arc2D segment;

        private Arc2D selected = null;

        public TestPane() {
            segment = new Arc2D.Double(0, 0, 190, 190, -11.75, 23.5, Arc2D.PIE);
            addMouseMotionListener(new MouseAdapter() {
                @Override
                public void mouseMoved(MouseEvent e) {
                    Point p = e.getPoint();
                    p.translate(-5, -5);
                    selected = null;
                    if (segment.contains(e.getPoint())) {
                        selected = segment;
                    }
                    repaint();
                }
            });
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.translate(5, 5);
            if (selected != null) {
                g2d.setColor(Color.BLUE);
                g2d.fill(selected);
            }
            g2d.setColor(Color.RED);
            g2d.draw(segment);
            g2d.dispose();
        }

    }

}

Have a look at Working with Geometry for more details

A: If jfreechchart is acceptable, a PiePlot may serve. Starting from PieChartDemo1, included in the distribution, the following changes produce the plot shown below. A ChartMouseListener highlights the indicated section as the mouse is moved.

public static JPanel createDemoPanel() {
    …
    PiePlot plot = (PiePlot) chart.getPlot();
    PieDataset data = plot.getDataset();
    panel.addChartMouseListener(new ChartMouseListener() {
        @Override
        public void chartMouseMoved(ChartMouseEvent e) {
            ChartEntity ce = e.getEntity();
            if (ce instanceof PieSectionEntity) {
                for (int i = 0; i < data.getItemCount(); i++) {
                    plot.setExplodePercent(data.getKey(i), 0);
                }
                PieSectionEntity item = (PieSectionEntity) ce;
                plot.setExplodePercent(item.getSectionKey(), 0.25);
            }
        }
        @Override
        public void chartMouseClicked(ChartMouseEvent e) {}
    });
    return panel;
}


text:
Q: Checking if a list of arbitrary inequalities are satisfied I am writing some code in C++ and need to check whether or not a list of inequalities in two unknown variables are satisfied.
For example, one possible list could be P = Q, Q < S, P = S which should NOT be satisfied
Another example, P = Q, Q < S, R = P, S > R should be satisfied
I have thought long and hard how to do this but I cannot seem to find any method other then a long, tedious one which involves checking if every new inequality added satisfies all the previous ones.

A: This is more of an exercise in boolean logic than C++. If you know Python use it.
A faster way would be to construct an "ordering" (in the maths sense) one statement at a time. That is where you have a sequence, a b c suppose and a

Suppose now each thing in the sequence is a vector of things equal to each other. In the above example:
P=Q
Our ordering looks like:
[P,Q]
Next Q

So now as we have an ordering:
[P,Q],[S]
We know [P,Q]<[S]
So P=S is an obvious contradiction.

A: First, remove all equalities P = Q by replacing all occurrences of Q with P.
This reduces P = Q, Q < S, R = P, S > R to R < S, S > R.
Second, build a directed graph with the variables as vertices and an edge from P to Q if your list constains P < Q or Q > P.
Third, check if the graph contains cycles. The inequalities are satisfiable iff the graph contains no cycles.
You might want to google for 2-SAT, which is related to this problem.


text:
Q: python - good places to check out example prog / code online? there is a year old, similar question - but in case there have been changes afoot:
i'm an intermediate c++ programmer just starting out on python, post some online tuts etc i can do some basic pythoneering, but was wondering if there are good places i can look online for simple(ish) --pref console based-- code that i can learn from, ideally with some sort of commentary.
anything come to mind?
thanks

A: The standard library is an excellent place to the start. It's maintained by the core python team and is of high quality with a lot of interesting idioms. I'd recommend the newer modules since they don't have much backward compatibility cruft and are more representative of the language as it is now. The older ones were written for earlier versions of Python and have some restrictions when it comes to API changes etc.
The list of modules in the standard library is described at http://docs.python.org/library/. You can go through it and decide which one you want to look at (area of interest etc.).
Their sources are viewable at the mercurial repo here http://hg.python.org/cpython/file/d7e85ddb1336/Lib (as of today). These are for the mainline 2.6 release. You can also checkout the repo and browse it on your local machine.
You can also start up your interpreter, import a module (say os) and do a print os.__file__ to see where the source file is if you want to look at the code in your local editor.

A: ActiveState Recipes is a good source for all kinds of Python scripts. But if you want to learn the basics of Python, you might just want to look at the standard library that ships with Python ("lib" directory").

A: i came across This The other day, Probably you can learn some python basics and have a laugh too!
Anyways, look at the libs as they said above, they are very useful

A: If you enjoy riddles:
www.pythonchallenge.com
If you're an intermediate C++ programmer, you're already equipped to handle to programming concepts.  I like it because it gives me a reason to learn each part of the language, without being mundane 'Hello World' tasks.
However, some of the riddles are pretty tough and/or unrelated to programming.  Either way, doing the first few will probably be enough to get your confidence up with Python syntax.


text:
Q: Bootstrap 3 Image sized by column This would be easy with just CSS, but I can't figure out how to do it using by using Bootstrap.
I want to have an image where the text wraps around it, either floated left or right.  However I want it 3 columns wide for md and lg sized screens, and fill the single column for xs and sm sized screens.
So on larger screens, something like this (worst sketch ever right here):

Now, I sort of have it working...though it seems to only span 2 columns and I'm not sure why:

About Them Guys

Home is where you hang your hat.  Flank shank bacon, fatback boudin ham tongue beef ribs pig brisket pancetta frankfurter. Jerky pig biltong, chicken hamburger swine corned beef beef ribs beef jowl.

Bacon ipsum dolor sit amet short loin jerky salami sausage, hamburger t-bone doner filet mignon sirloin beef. Tail short ribs jerky leberkas prosciutto pastrami fatback jowl turkey t-bone bacon. Hamburger tail tri-tip, ribeye ham hock leberkas meatball pig short ribs jerky meatloaf. Flank shank bacon, fatback boudin ham tongue beef ribs pig brisket pancetta frankfurter. Jerky pig biltong, chicken hamburger swine corned beef beef ribs beef jowl. Kevin cow turducken, pancetta fatback swine pig boudin ball tip kielbasa venison. Pig salami capicola chuck pancetta pork.

If that entire paragraph is offset by a column is the image col-md-3 counting that first column offset as "1"?  If I use col-md-4 then it does span the 3 columns - wanting to make sure there's something I'm not missing.
Thanks!

A: This shoud work

About Them Guys

Home is where you hang your hat.  Flank shank bacon, fatback boudin ham tongue beef ribs pig brisket pancetta frankfurter. Jerky pig biltong, chicken hamburger swine corned beef beef ribs beef jowl.

Bacon ipsum dolor sit amet short loin jerky salami sausage, hamburger t-bone doner filet mignon sirloin beef. Tail short ribs jerky leberkas prosciutto pastrami fatback jowl turkey t-bone bacon. Hamburger tail tri-tip, ribeye ham hock leberkas meatball pig short ribs jerky meatloaf. Flank shank bacon, fatback boudin ham tongue beef ribs pig brisket pancetta frankfurter. Jerky pig biltong, chicken hamburger swine corned beef beef ribs beef jowl. Kevin cow turducken, pancetta fatback swine pig boudin ball tip kielbasa venison. Pig salami capicola chuck pancetta pork.


text:
Q: Django getting a model from another model I have two models, a Author and a Article. Each Article is needs to refer back to its Author so I can access its values in my template. What is the most efficient way of doing this?
class Author(models.Model):
    name = models.CharField(max_length=256)
    picture = models.CharField(max_length=256)

class Article(models.Model):
    title = models.CharField(max_length=256)
    author = #The Author model that wrote this article
    date = models.DateTimeField(default=datetime.now)
    body = models.TextField()

A: You need to use the Foreign Key concept for it. The following is its implementation:
class Author(models.Model):
    name = models.CharField(max_length=256)
    picture = models.CharField(max_length=256)

class Article(models.Model):
    title = models.CharField(max_length=256)
    author = models.ForeignKey(Author)
    date = models.DateTimeField(default=datetime.now)
    body = models.TextField()

While saving it, you need to do the following in your views.py:
if form.is_valid():
    author = Author.objects.get(name="author name")
    form.save(author=author)

Hope it helps...

A: class Author(models.Model):
    name = models.CharField(max_length=256)
    picture = models.CharField(max_length=256)

class Article(models.Model):
    title = models.CharField(max_length=256)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    date = models.DateTimeField(default=datetime.now)
    body = models.TextField()

>>> r1 = Author(name='John',picture='johnpicture')
>>> r1.save()

>>> r2 = Author(name='John',picture='paulpicture')
>>> r2.save()

>>> from datetime import date
>>> a = Article(title="Article1", body="This is a test",date=date(2017, 7, 27), author=r1)
>>> a.save()
>>> a.reporter


text:
Q: Javapackager tool from command-line on OSX? javapackager and javafxpackager don't seem to be recognised on the command line for me.  They don't show up in the terminal, even after I installed the latest 1.8 SDK.  (Even 'echo $JAVA_HOME' seems to be drawing a blank, though java -version seems to work fine.)
If I look under /Library/Java/JavaVirtualMachines/jdk1.8.0_91.jdk/Contents/Home/bin/ I can see the javapackager and javafxpackager tools are present, but if I follow /usr/libexec/java_home back to it's origin in /System/Library/Frameworks/JavaVM.framework/Versions/A/Commands/ , there's no sign of them.
The only other discussions I could find on the subject were a blog post and mailing list from about a year and a half back:
https://devreboot.wordpress.com/2014/11/26/java-desktop-app-packaging-automation/
http://lists.apple.com/archives/java-dev/2015/Nov/msg00009.html
I realise OSX hasn't come with java 'by default' for some time, but that's kinda why I was hoping to release my application as a self-contained bundle with it's own VM.  Would it be standard procedure to update my bash profile to point at the tool explicitly?  Is there something screwy about my personal setup, or is there some gap in the tool support on OSX?

PS:  I realise there's an older thread on this subject below:
What is the best way to deploy JavaFX application, create JAR and self-contained applications and native installers
However, that describes javapackager as a .jar file, and whatever I've got doesn't seem to be a .jar file.  I'm legitimately confused about what I'm supposed to do with it.
EDIT:  Thanks to everyone for the tips- I think I have enough info to go on for now.

A: You could try this gist for building, packaging and running a test install on Java client apps from the OS X command line.  No guarantees it will work for you, it was just something I whipped up for personal development purposes a long time ago. But, the info in there may help in resolving packager tool locations from the command line and also in performing other packaging related functions.
The key part for locating (and using) the javapackager is:
# select java version
export JAVA_HOME=`/usr/libexec/java_home -v 1.8`
$JAVA_HOME/bin/java -version
...
# make an executable jar file
$JAVA_HOME/bin/javapackager -createjar -srcdir . -appclass start.HelloWorldSwing -srcfiles HelloWorldSwing.jar -outdir . -outfile HelloWorld.jar

# package the jar and java runtime as a native application with installer
$JAVA_HOME/bin/javapackager -deploy -srcdir . -srcfiles HelloWorld.jar -outdir . -outfile HelloWorld -appclass start.HelloWorldSwing -native -name HelloWorld

Note, the above is for packaging a Swing application.  Packaging a JavaFX application will use slightly different command line options for the packager.
Doing things this way from command line scripts is decidedly old school, usually maven or gradle is used.

My personal preference would be to just use Ant, but I guess that's only slightly less old-school?

Yes, not that there is anything wrong with that.  Documentation on using Ant to package java client applications is provided by Oracle.


text:
Q: Do arrays in C count blanks? Im learning for my upcoming exam and i wanted to ask if an Array counts blanks.
e.g in the Image below: does he count like the first row?

A: It's an array of characters yes it counts the spaces,
it should be in the 9 position the first blank/space and the first (i) should be in 10 position and etc and in the end of the array should be a /0..
p.s: null is a character also, that gets on the end of the array


text:
Q: Mongodb - convert the datetime to ISOdate format I want to convert the existing string date to new ISO date format. I used some scripts but they are not good enough to convert the time associated to the date. For ex: 2013-01-10 12:22:22 AM converted to ISODate("2013-01-10T06:00:00Z"). Here the time was not converting. Please help.
var cursor = db.customer.find({"created_at": {"$exists": true, "$type": 2 }});
while (cursor.hasNext()) {
      var doc = cursor.next();
      var parts = doc.created_at.split("-");
      var dt = new Date(
            parseInt(parts[0], 10), // year
            parseInt(parts[1], 10) - 1, // month
            parseInt(parts[2], 10)// day

        );
   db.customer.update(
    {"_id": doc._id},
    {"$set": {"created_at": dt}}
   )
}

A: Simply use new ISODate() :
new ISODate("2013-01-10 12:22:22 AM ")
ISODate("2013-01-10T12:22:22Z")

In your full example :
var cursor = db.customer.find({"created_at": {"$exists": true, "$type": 2 }});
while (cursor.hasNext()) {
   var doc = cursor.next();
   db.customer.update(
    {"_id": doc._id},
    {"$set": {"created_at": new ISODate(doc.created_at)}}
   )
}


text:
Q: Firebase automatic count based on another field I have a small app where i record votes and reorder a list based on those votes. The app has users and each user can only vote once.
For every record, when a user votes, i save the user id.
   var obj = {};
   obj[$scope.user.id] = {
       avatar: $scope.user.avatar,
       name  : $scope.user.name
   };
   myDataRef.child("sessions/"+sessionId+"/list/"+key+"/votes")
                            .update(obj, function(error){}

The update() protects me, and does not allow repeated ids.
With this i know that i have as many unique votes as voters.
So, i want a field called 'score' that would automatically count the users and set the 'score' field with that count.
How can i achieve this?
Tks


text:
Q: Change Javascript Variable without refresh I was wondering how i would go about changing "image.src" in the javascript without refreshing the page(well, without clearing the canvas).
I was thinking about using something like AJAX (i have never used it before) but i'm not sure if that is the right path to go. Could anyone help me out?
Here's my code:
<form>
Image URL:<input type="text" size="50" name="i" value="<?php echo $_REQUEST['i']?>" />
Background Color:<select name="color" >
<?php if($_REQUEST['color'] == "#000000"){ ?>
  <option value="#000000">Black</option>
  <option value="#ffffff">White</option>
  <?php }else{ ?>
    <option value="#ffffff">White</option>
    <option value="#000000">Black</option>
    <?php } ?>
</select>
<input type="submit"/> || Back to the Home Page
</form>

A: document.querySelector('input[name="i"]').addEventListener('blur', function() {
    image.src = this.value;
}, false);


text:
Q: awk or sed - delete specific lines I've got this
line1
line2
line3
line4
line5
line6
line7
line8
line9
line10
line11
line12
line13
line14
line15

I want this
line1
line3
line5
line6
line8
line10
line11
line13
line15

As you can see , the line to be deleted are going from x+2 then x+3 , x equals the line number to be deleted.
I tried this with awk but this is not the right way.
awk '(NR)%2||(NR)%3' file > filev1

Any ideas why?

A: If I decipher your requirements correctly, then
awk 'NR % 5 != 2 && NR % 5 != 4' file

should do.

A: Based on Wintermutes logic :)
awk 'NR%5!~/^[24]$/' file
line1
line3
line5
line6
line8
line10
line11
line13
line15

or
awk 'NR%5~/^[013]$/' file

How it works.
We can see from your lines that the one with * should be removed and other kept.
line1
line2*
line3
line4*
line5

line6
line7*
line8
line9*
line10

line11
line12*
line13
line14*
line15

By grouping data inn to every 5 line NR%5,
We see that line to delete is 2 or 4 in every group.
NR%5!~/^[24]$/' This divide data inn to group of 5
Then this part /^[24]$/' tell to not keep 2 or 4
The ^ and $ is important so line 12 47 i deleted too,
since 12 contains 2.  So we need to anchor it ^2$ and ^4$.

A: Using GNU sed, you can do the following command:
 sed '2~5d;4~5d' test.txt


text:
Q: SharePoint visual webparts for NewForm with client side coding I need to use visual web parts to create a new item form for a list.
I know I can do this by using SSOM..
But I want to reduce the load on the server
Can I use CSOM?.. Or is CSOM mainly for sandbox solution?
Right now I am trying to write JavaScript code on ascx page but I am having issues with client context
Please let me know if you have better ideas.
I am working with sp2010 visual web parts.
I do not want to use SharePoint designer and infopath
Thanks in advance...

A: There is a workaround to get the (C#) CSOM to work in a farm solution (the name for solutions that encompass code that needs to be installed on the server), there is an SP StackExchange answer on that here: CSOM in FarmSolution
You could also use a Sandbox solution as you mentioned; C# code in sandbox solutions is deprecated but you could create a webpart that used just the JavaScript Object Model (JSOM) to accomplish what you need. It's worth noting that you can create visual web parts in Sandbox solutions now as well.
As a final alternative, unless you need to leverage the webpart framework (passing values between web parts, or configuration properties) you could just create an HTML/CSS/JavaScript solution and implement it via source code on the aspx pages or something like the Content Editor Web Part -- this is the route that I currently use for light customization on SP2010.
For some more references on using the JSOM and JavaScript REST API see the following MSDN article on Javascript development in 2013 -- the vast majority of JSOM functionality is available in both versions, and 2010 supports ListData operations with REST:

*

*REST: http://msdn.microsoft.com/en-us/library/office/jj164022(v=office.15).aspx

*JSOM: http://msdn.microsoft.com/en-us/library/office/jj163201(v=office.15).aspx


text:
Q: Access denied when principal set to aws lambda.amazonaws.com I access a bucket with a lambda function and i get an "Access Denied" error, when i access it with a lambda function via boto3. If i set principal to "*" in the Bucket, all works fine. What is the issue?
 "Sid": "DenyIncorrectEncryptionHeader",
            "Effect": "Allow",
            "Principal": {
                "Service": "lambda.amazonaws.com"
            },
...

A: In the bucket policy, the principal to give allow permission to should be the lambda execution role and not the lambda service (lambda.amazonaws.com).
Adding more details, if the lambda execution role is in the same AWS account as the bucket, then an allow permission in the role should suffice. As long as there is no explicit deny in the bucket policy.
However, if the role and bucket are in separate accounts, the role has to have allow permission and the bucket policy has to give allow permission to the role.

A: The steps would be:

*

*Create an IAM Role with a use-case of Lambda (this creates a Trust Policy that allows the AWS Lambda service to assume the role)

*Add a Policy to the IAM Role that grants the required Amazon S3 permissions

*Configure the AWS Lambda function to use this IAM Role

There is no need to use an Amazon S3 Bucket Policy for your stated requirements.
As a general rule, Bucket Policies are used when granting permission to everyone, and IAM policies should be used when granting access to specific Users or Groups. (However, there can be other situations for using Bucket Policies, such as granting cross-account access.)


text:
Q: Linq to xml query not returning any values I'm pulling an XML list of SharePoint site collection users and then trying to query the InnerXml. The InnerXml looks like this:
<Users xmlns="http://schemas.microsoft.com/sharepoint/soap/directory/">
<User ID="91" Name="Jane Smith" LoginName="domain1\jsmith" />
<User ID="814" Name="Brad Jones" LoginName="domain1\bjones" />
<User ID="1252" Name="Charles Johnson" LoginName="domain2\cjohnson" />
</Users>

Query is not returning anything (el is null), even though there is a user with ID 814.
XmlNode siteUsers = tempug.GetUserCollectionFromSite();
XElement root = XElement.Parse(siteUsers.InnerXml);
    IEnumerable<XElement> siteUsersElement =
        from el in root.Elements("User")
        where (string)el.Attribute("ID") == "814"
        select el;
foreach (XElement el in siteUsersElement)
Console.WriteLine("el: " + el);

root contains the InnerXml text, so I don't think the problem has anything to do with SharePoint.

A: You're not specifying the namespace in your Elements call. Fortunately this is easy in LINQ to XML:
XNamespace ns = "http://schemas.microsoft.com/sharepoint/soap/directory/";
...
from el in root.Elements(ns + "User");

If you know that the ID attribute will always be an integer, I'd actually make that clear, and also avoid using a query expression when it doesn't help you:
// TODO: Find a nicer way of doing this; you shouldn't need to parse it again
XElement root = XElement.Parse(siteUsers.InnerXml);
var siteUserElements = root.Elements(ns + "User")
                           .Where(el => (int) el.Attribute("ID") == 814);

foreach (XElement el in siteUserElements)
{
    Console.WriteLine("el: " + el);
}


text:
Q: Will wise owl obfuscate wpf projects properly? We are moving from windows forms to wpf for the next version of the product I work on. We are using wise owl to do our obfuscation and I am wondering if anyone has had experience with this.

A: Yes it can be done. You need to flag everything you don't want to bind to as don't obfuscate but it works.


text:
Q: using Twitter OAuth 1.1 in PHP without 3rd party library I am trying to display my Twitter feeds using Twitter API 1.1. I have been searching for this but didn't get a proper solution.I have tried this using Abraham/TwitterOAuth library and it works fine. But my new task is not to use any 3rd party libraries.
Here I tried using cURL,
<?php
  $options = array(
  CURLOPT_HTTPHEADER     => array('Authorization: OAuth oauth_consumer_key="aaaaaaa", oauth_nonce="bbbbbbb", oauth_signature="cccccc%ddddddd%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1426752199", oauth_token="eeeeeeeee-fffffffffffff", oauth_version="1.0"'),
  CURLOPT_HEADER         => false,
  CURLOPT_URL            => 'https://api.twitter.com/1.1/statuses/user_timeline.json?count=2&screen_name=myscreen_name',
  CURLOPT_RETURNTRANSFER => 1,
  CURLOPT_SSL_VERIFYPEER => false
);

  $feed = curl_init();
  curl_setopt_array($feed, $options);
  $json = curl_exec($feed);
  curl_close($feed);
  $twitter_data = json_decode($json);
  var_dump($twitter_data);
?>

and it returns with an error
 object(stdClass)#1 (1) {
 ["errors"]=>
    array(1) {
      [0]=>
      object(stdClass)#2 (2) {
        ["code"]=>
        int(215)
        string(24) "Could not authenticate you"
      }
    }
 }

I am not getting where I am going wrong. How to make it work?

A: Ok. Here I found a solution. I found the below link very helpful. Posting it here so that it might help some other.
Twitter API returns error 215, Bad Authentication Data


text:
Q: Почему DiffUtill работает медленно? Для того, чтоб обновить данные в адаптере я использовал вот такой метод в адаптере
public void setData(@NotNull List<HomeScreenAdapterItem> iData)
{
    mHomeItems = iData;
    notifyDataSetChanged();
}

потом поменял имплементацию на DiffUtill
public void setData(@NotNull List<HomeScreenAdapterItem> iData)
{
    MyDiffUtil<HomeScreenAdapterItem> diff = new MyDiffUtil<>(mHomeItems, iData);
    DiffUtil.DiffResult result = DiffUtil.calculateDiff(diff, false);
    mHomeItems = iData;
    result.dispatchUpdatesTo(this);
}

Как это работает у меня. Есть экран с RecyclerView, когда нажимаю на элемент списка то открывается следующий экран и в нем есть возможность изменить данные списка, включая последовательность элементов.
Так вот при первом подходе при возвращении на первый экран замена элементов списка не заметна, сразу видны обновленные данные, а при подходе с использованием DiffUtill открывается экран и я вижу как стрые элементы меняются на новые.
Вопрос
Как сделать, чтоб второй метод работал со скоростью первого?

A: DiffUtill нужен для оптимального обновления элементов View в RecyclerView. Обновление происходит только тех View, в которых данные изменились.
Если вас смущает анимация, можно ее выключить:
((SimpleItemAnimator) RecyclerView.getItemAnimator()).setSupportsChangeAnimations(false);


text:
Q: Is delta temperature dependent on the initial temperature? All computer hardware testing sites i know test cooling solutions (CPU/GPU coolers) based on the temperature difference from the initial (room) temperature. This is a good way to compare, but i don't know if it's accurate.
So, two different systems that have been tested in different room temperatures can be comparable simply by the change in temperature? In other words, the same system will show the same temperature difference if tested in different room temperatures? And if not, how can we compare them?


text:
Q: Integration testing with FubuMvc I was thinking that it would be great to have something like this:
var mvc = new MyFullyConfiguredFubuMvc();
var response1 = mvc.Request("http://myawesomewebsite.com/page1");
var response2 = mvc.Request(new StringRequest {
    Url="http://myawesomewebsite.com/page1?q=asylum",
    CookieName=".aspauth",CookieBody="x=5;y=9",
    Method="get",
    Headers="y:6; z:qwerty"
});

So the Q is: how easy will it be to make this with FubuMvc?
Thanks!

A: Here's a simple example for you:
https://gist.github.com/4697920


text:
Q: Python sys.path - appending PYTHONPATH Before start
I have been trying to accomplish it for some time now, but I had no luck. I'm trying to create my own python package, which I will import the modules in it, in separate files in my project. I tried to add my project's directory to pythonpath via 'sys' but still the mod_wsgi do not recognize it:
import sys
sys.path.append('/var/www/')

from core.core import main

And when trying:

ImportError: No module named core.core

Any help would be appreciated

A: If you do not have the file __init__.py in your core folder, it will not be recognized as a package.
Therefore the solution is to add a file __init__.py in your core folder.
If you have already added the problem may be the absolute path ... the core folder that has absolute path:

*

*/var/www/core

*/var/www/YourProject/core

if the second option you have to do: sys.path.append('/var/www/YourProject')

A: You need to explicitly set PYTHONPATH with you root directory.


text:
Q: How to implement CloudKit Undo/Redo I was just wondering if anyone has a better idea how to implement undo/redo for the CloudKit transactions or if they see some obvious flaws in mine.
I made a Mac app in which I use CoreData as the local store and CloudKit. When CloudKit is not in use, I use CoreData's UndoManager for undo/redo and that works fine.
For CloudKit undo I listen for NSUndoManagerDidUndoChangeNotification, sent by the local UndoManager, and when I receive it, I send the opposite operation to the iCloud. So if the original was Add, I will send Delete for undo, if it was Delete, send Add and if it was Update, Update with previous version of data.
Similarly for redo. I listen for NSUndoManagerDidRedoChangeNotification and send appropriate transaction to cloud.
For each transaction that uses CloudKit, I call moc!.undoManager!.beginUndoGrouping() at the beginning of the local transaction and moc!.undoManager!.endUndoGrouping() when I receive completion of the same transaction from the iCloud.
However, often I get a situation when this seems to fall apart. Somehow, begin and end groupings fall out of sync. I tried to only include important changes for undo/redo with moc!.undoManager!.disableUndoRegistration() and moc!.undoManager!.enableUndoRegistration() but I still get errors, mainly "endUndoGrouping called with no matching begin"
So, it would be great if anyone has a comment on this.


text:
Q: How to handle client requests within server in C with socket programming I want to handle multiple client requests.
Should I call listen() just once and call accept() for every new client request?

A: You may want to check out D.J. Bernstein's tcpserver (see http://cr.yp.to/ucspi-tcp/tcpserver.html). Basically, you can simply run your C program under tcpserver, and tcpserver will handle everything as far as setting up the sockets, listing for incoming connections on whatever port you are using, etc. When an incoming connection arrives on the port that you specify, tcpserver will spawn an instance of your program and pipe incoming info from the client to your program's STDIN, and pipe outgoing info from your program's STDOUT back to the client. This way, you can concentrate on your program's core logic (and simply read/write to stdout/stdin), and let tcpserver handle all of the heavy lifting as far as the sockets, etc.


text:
Q: How does an hexagonal architecture help with async/await async-over-sync? In his book "Concurrency in C# Cookbook", Stephen Cleary writes:

If you can, try to organize your code along modern design guidelines, like Ports and Adapters (Hexagonal Architecture), which separate your business logic from side effects such as I/O. If you can get into that situation, then there's no need to expose both sync and async APIs for anything; your business logic would always be sync and the I/O would always be async.

However, I don't find that to be true in my design and I am wondering how it's supposed to be so I can have a sync domain and async infrastructure code.
For example, given the following:
public interface IContentRepository
{
  Content GetContent (Guid contentId);
}

public class MyDomainObject
{
  public void Foo (IContentRepository repo)
  {
    var content = GetContent(someId);
    ...
  }
}

public class ContentRepository : IContentRepository
{
  // Uh oh, either...
  // 1. implement it sync here or
  // 2. use sync-over-async or
  // 3. make IContentRepository return Task<Content> (and live with an async domain)
}

How's that supposed to be designed such that my domain can stay sync-only and can make use of async infrastructure code. Is that even possible? Have I misunderstood Stephen?

A: I guess Stephen Cleary expects a ports and adapters architecture to do all I/O in the outer layers and to pass in the results of these operations to the domain objects. In your example, this would be simple: pass in the content to the domain object rather than injecting IContentRepository:
public class MyDomainObject
{
  public void Foo (Content content)
  {
    ...
  }
}

However, this becomes more difficult when you have business rules that involve side effects.
Example:
public class ContentDomainObject
{
  public async void FinalizeContent(IContentRepository repository)
  {
    if (RequiresRule276aContent)
    {
      var content = CreateFinalRule276aContent();
      var contentId = await repository.AddContent(content);
      _contentId = contentId;
      ReportDomainEvent(new ContentFinalizedEvent(contentId));
    }
    else
    {
      ...
    }

  }
}

You could keep the inner layer oblivious of this async side effect by moving some of this to the outer layer:
// Outer layer
var content = contentDomainObject.CreateFinalContent();
var contentId = await repository.AddContent(content);
contentDomainObject.ProcessFinalContent(contentId);

However, I'm not sure if this is really better - now the domain operation has been split into two parts, whose names maybe don't really make sense from a business perspective. So, I'd probably choose to be pragmatic and just accept the async domain object methods.

A: It is true that if you start using async-await it spreads as a zombie along application pipeline and you will be forced to use async everywhere.
Try to approach design from a bit different angle - domain logic care only about data.
So we can put all IO related code outside of domain layers as close to the top layers as possible.
1 Load required data asynchronously
2 Pass data to the business logic
3 Process data synchronously
4 Return possible results
5 Save processed results asynchronously
public class MyDomainObject
{
    public MyDomainObject(DomainContent content) => _content = content;

    public ProcessedContent DoSomething()
    {
        // Process given content
    }
}

// This implementation belongs to the "infrastructure" layer
public class MyDomainProcessor
{
    public MyDomainProcessor(IContentRepository repository)
    {
        _repository = repository;
    }

    public async Task ProcessAsync(Guid contentId)
    {
        var content = await _repository.GetContentBy(contentId);

        var processedContent = new MyDomainObject(content).DoSomething();

        await _repository.Save(processedContent);
    }
}

A: You need to make the adapter call to your domain.
Async code can call both sync and async code. However, when sync code calls async you run into trouble.
Simplest way to fix this is to pass a callback.

How does the flow of execution on your project go?
The code that does your dependency injection can be async, so it can call both sync and async code. See also composition root. Right? You have async code in the boundary.
The async code in the boundary can easily call into your domain… then your domains returns instances※ that tells it what operation to do (e.g. get the repository contents).
※: Once passed, the code in the boundary should not be able to mutate those instances. Simplest way to accomplish this is passing a value type, immutable objects also work, or simply not holding a reference to them. See also Value/reference type, object and semantics.
When the boundary code gets what your code returned, it can go perform the async operation, and call back again into your domain.
In fact, if you do that, you do not need to do dependency injection at all.


text:
Q: Issue: Vue js file upload new FormData() append method is removing data from pay load submitFile(){
debugger
let formData =  new FormData();
formData.append('file_to_upload', this.Images);
console.log(".........",formData)
let data = {
name : this.Images.name,
category_id : this.fileUploadCategory,
file_to_upload :formData,
created_by : 1,
updated_by : 1,
}
DocumentDataServices.fileUpload(data).then((res)=>{
console.log(res)
})
},


text:
Q: How to draw electric circuits in LaTeX?
I need to do this in LaTeX, can someone help me, please?
This is what I have so far..... I'm having problems to identify, how to connect a resistor in the middle of a line coming from (opamp .-)
if you identify the first opamp from the left, you can see it
\documentclass{article}
\usepackage[free-standing-units]{siunitx}
\usepackage{circuitikz}
\usepackage{tikz}

\begin{document}
\begin{circuitikz}
\draw (0,0) node[op amp] (opamp) {}
(opamp.+) node[left, anchor=north] {$3$} to [R] (-5,-0.5)
(opamp.-) node[left] {$2$} to [short,*-] ++(0,4) to [short,*-] ++(0,2) to [R={$R1$}](18,6.5) {}
(opamp.out) node[right, anchor=north] {$6$} to (1.5,0) to [R={$R1$}](4,0) {}
(opamp.up) --++(0,1.5) node[anchor=east, *-o]{\textnormal{-Vcc}} (-0.2,1.3) node[anchor=east]{\textnormal{4}}
(opamp.down) --++(0,-1.5) node[anchor=west, *-o]{\textnormal{Vcc}} (0.2,-1.3) node[anchor=west]{\textnormal{7}};

\draw (8,0) node [op amp] {};

\end{circuitikz}
\end{document}

also need to connect Resistor R1 coming from (opamp.out) to (opamp.-)

A: Note, you can also use relative positioning using ++(x,y).
\documentclass{standalone}
\usepackage[free-standing-units]{siunitx}
\usepackage{circuitikz}
\usepackage{tikz}

\begin{document}
\begin{circuitikz}
\draw (0,0) node[op amp] (opamp) {}
(opamp.+) node[left, anchor=north] {$3$} to [R] (-5,-0.5)
(opamp.-) node[left] {$2$} to [short,*-] ++(0,4) to [short,*-] ++(0,2) to [R={$R1$}](18,6.5) {}
(opamp.out) node[right, anchor=north] {$6$} to (1.5,0) to [R={$R1$},*-*](4,0) {};
(opamp.up) --++(0,1.5) node[anchor=east, *-o]{\textnormal{-Vcc}} (-0.2,1.3) node[anchor=east]{\textnormal{4}}
(opamp.down) --++(0,-1.5) node[anchor=west, *-o]{\textnormal{Vcc}} (0.2,-1.3) node[anchor=west]{\textnormal{7}};
\draw (4,0) node [op amp,anchor=-] {};

\end{circuitikz}
\end{document}


text:
Q: a subclass calling the method of it's superclass(which is also a subclass) i've search this site, and others for a few hours to no avail. Currently, I'm working with inheritence and have hit a bump in the road. I have a super class called Plant, which has subclasses called Vegetable, and Flower. and a subclass called Tomato which extends the Vegetable class, now my problem is that my Tomato class cannot access methods of any classes above it.
So basically I am asking, if C extends B, and B extends A, why is C not syntactically able to accessing public methods from A or B in my program?
public class Tomato extends Vegetable{

private String breed;

public Tomato(String o, int s, String b)
{
    super();
    breed = b;
}

public String getBreed()
{
    return breed;
}

public String toString()
{
    return "[Owner: " + getOwner() + " , Sprouts: " + getSprouts()
            + " , Breed: " + getBreed() + "]";
}

public void water()
{
    if(breed.toLowerCase().contains("porterhouse"))
    {
        int numSprouts = getSprouts();
        setSprouts(numSprouts*3);
    }
} }

I receive errors on the method call getOwner() and getSprouts(), only the accessor methods. getOwner() is a public method in the plant class and getSprout() is a method in the Vegetable class, which is class directly above it in the hierarchy.

A: If I have understood it correctly : Tomato can access public methods of Vegetable and Plant.
public class Plant {
    public void getPlant(){
         System.out.println("In Plant");
    }

    public static void main(String[] args) {
        Tomato tomato = new Tomato();
        tomato.getTomato();

    }
}

class Vegetable extends Plant{
    public void getVegetable(){
        System.out.println("In Vegetable");
    }

}

class Flower extends Plant{
    public void getFlower(){
        System.out.println("In Flower");
        getPlant();
    }
}

class Tomato extends Vegetable{
    public void getTomato(){
        System.out.println("In Tomato");
        getVegetable();
        getPlant();

    }
}

Output:
In Tomato
In Vegetable
In Plant

A: What you are trying to describe is a multilevel inheritance. Here is an example of it. Yes, sub class can access any method of it's parents as long as they are public/protected.

A: You can create a "bridge" between classess:
class A {
    public String getA() {
        return "A";
    }
}

class B extends A {

    @Override
    public String getA(){
        return super.getA(); //uses getA from A class
    }
}

class C extends B {
    @Override
    public String getA(){
        return super.getA();  //uses getA from B class
    }
}

Test:
public static void main(String... args) {

    A a = new C();
    System.out.println(a.getA());
}

Prints: A


text:
Q: 1991 IMO shortlist problem $\#11$
Prove that $$\sum_{k=0}^{995} \frac{(-1)^k}{1991-k} {1991-k\choose k} = \frac{1}{1991}$$

As usual there isn't anything special about the number $1991$.Problem appears to hold for any odd numbers I have checked. I want to prove the general equation. We can manipulate expression and simplify a bit. Then the problem reduces to showing that $\sum_{k=1}^{n} \frac{(-1)^k}{2n-2k+1} {2n-k\choose k} = 0$ for some positive integer $n$. This is the equation I had been working on but it wasn't that fruitful.
I gave up and saw the solution on Aops but it was not a elementary one. Here is the link if any one wants to see it "https://artofproblemsolving.com/community/c6h34892p216919" ( There is another interesting thing about this link, that the last six digits form a prime number!! $216919$ ).In this link the solution poster says that the solution he had written isn't the solution the creators assumed the students to write. So what might be the solution that creators might have expected the students to write?

A: If you know generating functions, then here is a solution:
Let $s_n$ denote the sum $\sum_{k \geq 0} \frac{(-1)^k}{n - k}\binom{n - k}k$ and let $S(X)$ be the formal power series $S(X) = \sum_{n \geq 1} s_n X^n$.
We compute:
\begin{eqnarray}
S(X) &=& \sum_{n \geq 1} \frac 1 n X^n + \sum_{n \geq 1}\sum_{k \geq 1} \frac{(-1)^k}{n - k}\binom{n - k}k X^n\\
&=& -\log(1 - X) + \sum_{k \geq 1}\sum_{n \geq 2k}\frac{(-1)^k}k \binom{n - k - 1}{k - 1}X^n\\
&=& -\log(1 - X) + \sum_{k \geq 1}\frac{(-1)^k}k X^{2k}\sum_{n \geq 0}\binom{n + k - 1}{k - 1}X^n\\
&=& -\log(1 - X) - \sum_{k \geq 1}\frac{ (-1)^{k - 1}} k \left(\frac{X^2}{1 - X}\right)^k\\
&=& -\log(1 - X) - \log\left(1 + \frac{X^2}{1 - X}\right)\\
&=& -\log(1 - X + X^2)\\
&=& -\log(1 - \omega X) - \log(1 - \overline\omega X)\\
&=& \sum_{n \geq 1}\frac{\omega^n + \overline\omega^n}n X^n,
\end{eqnarray}
where $\omega = \frac{1 + \sqrt{-3}}2$ is a primitive sixth root of unity.
Thus we have $s_n = \frac 1 n \cdot 2 \operatorname{Re}(\omega^n)$.
Now $\omega^n$ only depends on $n \mod 6$. Therefore:
$$s_n = \begin{cases}
\frac 2 n, & n \equiv 0\mod 6;\\
\frac 1 n, & n \equiv 1, 5\mod 6;\\
\frac {-1} n, & n \equiv 2, 4 \mod 6;\\
\frac{-2} n, & n \equiv 3 \mod 6.
\end{cases}$$
And the answer to the original question follows from the fact that $1991 \equiv 5 \mod 6$.

A: For such problems (esp when you notice that there is a general pattern), some ideas are to find a recurrence relation, create something telescoping (or treat it as a generating function).
We'd use these ideas here.

Notice that $ \left(\frac{1}{n-m} - \frac{1}{n}\right) { n - m \choose m } =  \frac{m}{ n (n-m) } { n - m \choose m } = \frac{1}{n} {n-m-1 \choose m-1}$, or that
$$ \frac{ 1 } { n-m } { n-m \choose m } = \frac{1}{n} \left[ { n - m \choose m } + { n - m - 1  \choose m- 1 } \right]. $$
This is a good substitution, as it gets rid of the pesky $ \frac{1}{n-k}$ which makes recurrence hard, and also gives us a $\frac{1}{1991}$ on the RHS.
Thus, the goal is to determine $ \sum_{k=0}^{995 } (-1)^k \left[ {1991-k\choose k} + { 1991 - k - 1 \choose k - 1 }    \right] $.  (We will show that it equals to 1, and thus the desired sum is $\frac{1}{1991}.$)

Let $ S_n = \sum_{k=0}^{ \lfloor \frac{n}{2} \rfloor} (-1)^k  { n-k \choose k } $.
Notice that ${n-k \choose k } = { n-k - 1 \choose k } + { n-k - 1 \choose k - 1 }  $, so
$ S_n = \sum_{k=0}^{\lfloor \frac{n+1}{2} \rfloor} (-1)^k { n - k + 1  \choose k } \\
= \sum_{k=0}^{\lfloor \frac{n+1}{2} \rfloor} (-1)^k \left[ {n-k \choose k } + {n-k \choose k - 1 } \right] \\
= \sum_{k=0}^{\lfloor \frac{n}{2} \rfloor} (-1)^k {n-k \choose k } + \sum_{k=0}^{\lfloor \frac{n-1}{2} \rfloor} (-1)^k { n-k \choose k } \\
= S_{n} - S_{n-1}. $
(Take care in checking the indices, and remember those ${n \choose m } = 0 $ when $m > n $.)
Using this recurrence relation, and calculating some initial values, we get $S_n = 1 , 0, -1, -1, 0, 1, 1, 0, -1, \ldots$, which has period 6.
We thus want to determine $S_{1991} - S_{1990} = 0 - (-1) = 1$.

Notes

*

*I do wish there was a combinatorial argument here. For example, $S_n$ has an immediate interpretation as the difference between the even and odd permutations $p$ such that $|p(i) - i | \leq 1$. (IE Out of the first $n$ integers, there are ${n-k \choose k }$ ways to pick k pairs of consecutive integers (for a total of 2k). The perumatation which switches these pairs and keep the rest fixed has parity $k$.) However, I don't see an obvious way to show that this difference is $1, 0, -1, -1, 0, 1, \ldots $.

*WhatsUp's conclusion that about the value of $s_n$ also follows from the above.


text:
Q: Collision with A-Frame objects using JavaScript physics library So, I have been stumped on this for a while now. I need to be able to have my camera entity collide with shape entities within an A-frame scene stopping the camera from going through them. Essentially I want to create walls using the A-Frame physics engine that can be found here:
https://github.com/donmccurdy/aframe-physics-system
I have searched all over and am unable to find a simple example of how to obtain this function! I have already spent far too much time looking around online.
I have created a simple scene in A-Frame with the basics of Don's physics engine already included. I created this in order to try to test out a single walls function before adding it to my far more complex scene I am working on.
Any help with this would be greatly appreciated!

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://aframe.io/releases/1.0.3/aframe.min.js"></script>
    <script src="//cdn.rawgit.com/donmccurdy/aframe-physics-system/v4.0.1/dist/aframe-physics-system.min.js"></script>
    <title>Aframe Physics Demo</title>
</head>

<body>
    <a-scene physics="debug: true">

        <a-entity id="camera" position="0 1.6 0">
            <!-- Camera Entity -->
            <a-entity id="camera" acceleration="200w" camera look-controls wasd-controls></a-entity>
        </a-entity>

        <a-box static-body position="0 0 -3" color="#4CC3D9" width="8" height="5" depth="0.5"></a-box>

        <a-plane static-body rotation="-90 0 0" position="0 0 -4" width="10" height="10" color="#7BC8A4"></a-plane>
        <a-sky color="#ECECEC"></a-sky>
    </a-scene>
</body>

</html>

A: If you want to use the physics engine to detect collisions with the camera - it needs to be a part of the physics engine. It can't be a static-body because it needs to move around, and it can't be a dynamic-body for it needs to be controlled by the player, and not fall down (gravity) and spin around.
Don McCurdy created a kinematic-body component having the camera / player in mind. It is available as part of the physics extras

So having a camera:
<a-entity camera kinematic-body></a-entity>

You can detect any objects it collides with:
// inside an a-frame component - this is straight from the docs
this.el.addEventListener('collide', function(e) {
   console.log('Player has collided with ', e.detail.body.el);
   e.detail.target.el; // Original entity (camera).
   e.detail.body.el; // Other entity, which the camera touched.
   e.detail.contact; // Stats about the collision (CANNON.ContactEquation).
   e.detail.contact.ni; // Normal (direction) of the collision (CANNON.Vec3).
});

Check it out below:

<script src="https://aframe.io/releases/1.3.0/aframe.min.js"></script>
<script src="https://threejs.org/examples/js/deprecated/Geometry.js"></script>
<script src="https://cdn.jsdelivr.net/gh/donmccurdy/aframe-extras@v6.1.1/dist/aframe-extras.js"></script>
<script src="https://n5ro.github.io/aframe-physics-system/dist/aframe-physics-system.js"></script>

<script>
  AFRAME.registerComponent('foo', {
    init: function() {
      this.el.addEventListener('collide', function(e) {
        console.log('Player has collided with ', e.detail.body.el);
      });
    }
  })
</script>
<a-scene physics="debug: true">
  <a-entity id="rig" movement-controls kinematic-body foo>
    <a-entity id="camera" camera position="0 1.6 0" look-controls></a-entity>
  </a-entity>
  <a-box static-body position="0 0 -3" color="#4CC3D9" width="8" height="5" depth="0.5"></a-box>
  <a-sphere dynamic-body position="0 1 -2" color="#4CC3D9"></a-sphere>
  <a-box scale="20 0.01 20" static-body></a-box>
</a-scene>

If the shapes are simple consider using a box collider or a sphere collider. There is a simple example in this SO answer.


text:
Q: Exporting multiple images from R into 1 pdf So I have a function that produces 6 graphs into one image and then I have 24 images (all different graphs) from that function. I was wondering if there is a way to have all of those images exported onto one big pdf.
Here is my current code to obtain the graphs:
eemgraphs3<-eem_overview_plot(eem_list3,spp=6,contour=TRUE)
Currently I look at each one individually using this code:
eemgraphs3[2]
eemgraphs3[3]
and so forth until I hit my last data point.
If I could potentially compile them all into one pdf file then I think it would save a lot of time but I do not know how to do that. Thanks for your help!
I have tried these function which I found online to solve this but no results came out of this.
pdf("eemgraphs3.pdf")
eemgraphs3[1:24]
dev.off()

install.packages("ply")
library("ply")
pdf("plots.pdf", width = 7, height = 7)
d_ply(eemgraphs3, .(z), failwith(NA, function(x){plot(x$y,main=unique(z))}), .print=TRUE)
dev.off()

A: It can be something like this:
pdf("eemgraphs3.pdf")
par(mfrow = c(4,6))
eemgraphs3[1:24]
dev.off()