text:
Q: Libgdx - finding objects attributes from another class I have a class Sword that is instantiated to create several objects in my game and hold them in an Array structure. How do I find the attributes each object of Sword class from another class ?
How my spawned swords look
This code allocate and generate the Sword(s) Renderer class:
private List<Sword> swords = new ArrayList<Sword>();

Then in public Renderer() method I do:
for (int i = 0; i<10 ; i++ ) {
            swords.add(new Sword());
        }

In the  render() they are displayed on the screen:
for (Sword sword : swords) {
    sword.createMe();
}

And here is my Sword class:
 public class Sword {
    private TextureRegion sprite;
    private static int xx;
    private static int yy;
    private int x;
    private int y;
    private int size;
    private Random r;
    public Sword() {
        r = new Random();
        x = (r.nextInt(10))*GameRender.tilesize;
        y = (r.nextInt(10))*GameRender.tilesize;
        size = GameRender.tilesize;
        sprite =getSprite();
    }

    private TextureRegion getSprite() {
        int id = r.nextInt(2);
        System.out.println(id);
        if(id==1){
            sprite=AssetLoader.s1;
        }else sprite=AssetLoader.s2;
        return sprite;
    }

    public void createMeShape(){
        GameRender.shapeRenderer.rect(x, y, size, size);
    }

    public void createMe() {
        GameRender.batch.draw(sprite, x, y, size, size);
    }

    public static void Update() { }
}

So how do i find the value of  x, y from the Render class (I cant use static because it will only find one swords position) for collision detection or how i check if swords x,y is same like playerx, playery (ints from GameRenderer class)?

A: Add a getter in your Sword class.
// Returns the sword x location
public int getLocX()
{
    return this.x;
}

There's many ways you can go about this, i.e. using a Vector instead. The implementation is up to you.
On a side note, I would highly recommend you use Box2D for collision detection in libgdx.


text:
Q: Asyncpg cannot fetch data from the database I am writing my API using aiohttp, asycpg and asyncpgsa.
I create my application:
async def create_app():
    app = web.Application(client_max_size=1024 ** 2 * 70)

Then I execute these lines:
async def on_start(app):
    app['db'] = asyncpgsa.create_pool(dsn="postgresql://127.0.0.1:5432/backend")

async def on_shutdown(app):
    app['db'].close()

app.on_startup.append(on_start)
app.on_cleanup.append(on_shutdown)

In general, in the example where I got it from, it is written like this:
app['db'] = await asyncpgsa.create_pool(dsn="postgresql://127.0.0.1:5432/backend")

But if I write like this, then an error is thrown "ConnectionRefusedError: [Errno 10061] Connect call failed ('127.0.0.1', 5432)"
But that's okay. Now, when the user visits the URL I need, this function should be triggered:
async def post(request):
    async with request.app["db"].acquire() as conn:
        query = select([datab.post])
        result = await conn.fetch(query)

The datab file says this:
from sqlalchemy import Table, Text, VARCHAR, Integer, MetaData, Column

meta = MetaData()

post = Table(
    "post", meta,
    Column("id", Integer, primary_key=True),
    Column("title", VARCHAR, nullable=True),
    Column("body", Text))

But when I go to the URL I want, the site gives me "500 Internal Server Error Server got itself in trouble "
And Pycharm: Error handling request           asyncpg.exceptions._base.InterfaceError: pool is not initialized
Very little has been written on the Internet about asyncpg (sa), so I will be immensely grateful if you can help me fix the problem.
I'll add my own code.
main.py
from aiohttp import web
from demo import create_app
import argparse
import sqlalchemy
import asyncpgsa

async def post_handler(request):
    body1 = await request.json()
    print(body1)
    return web.json_response(data=body1, status=201)

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--host", help="IPv4/IPv6 address API server would listen on", default="0.0.0.0")
    parser.add_argument('--port', help='TCP port API server would listen on', default=8080, type=int)
    args = parser.parse_args()

    app = create_app()
    web.run_app(app, host=args.host, port=args.port)

if __name__ == '__main__':
    main()

app.py
from aiohttp import web
import asyncpgsa
from .routes import setup_routes

async def on_start(app):
    app['db'] = asyncpgsa.create_pool(dsn="postgresql://127.0.0.1:5432/backendyandex")

async def on_shutdown(app):
    app['db'].close()

async def create_app():
    app = web.Application(client_max_size=1024 ** 2 * 70)
    setup_routes(app)
    app.on_startup.append(on_start)
    app.on_cleanup.append(on_shutdown)
    return app

If you write
app['db'] = await asyncpgsa.create_pool(dsn="postgresql://127.0.0.1:5432/backend")

Then an error occurs
unhandled exception during asyncio.run() shutdown
task: <Task finished coro=<_run_app() done, defined at C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\aiohttp\web.py:287> exception=ConnectionRefusedError(10061, "Connect call failed ('127.0.0.1', 5432)")>
Traceback (most recent call last):
  File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\aiohttp\web.py", line 508, in run_app
    loop.run_until_complete(main_task)
  File "C:\Users\lisgl\AppData\Local\Programs\Python\Python37\lib\asyncio\base_events.py", line 587, in run_until_complete
    return future.result()
  File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\aiohttp\web.py", line 319, in _run_app
    await runner.setup()
  File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\aiohttp\web_runner.py", line 275, in setup
    self._server = await self._make_server()
  File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\aiohttp\web_runner.py", line 375, in _make_server
    await self._app.startup()
  File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\aiohttp\web_app.py", line 416, in startup
    await self.on_startup.send(self)
  File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\aiohttp\signals.py", line 34, in send
    await receiver(*args, **kwargs)  # type: ignore
  File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\demo\app.py", line 11, in on_start
    app['db'] = await asyncpgsa.create_pool(dsn="postgresql://127.0.0.1:5432/backendyandex")
  File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\asyncpg\pool.py", line 407, in _async__init__
    await self._initialize()
  File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\asyncpg\pool.py", line 435, in _initialize
    await first_ch.connect()
  File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\asyncpg\pool.py", line 127, in connect
    self._con = await self._pool._get_new_connection()
  File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\asyncpg\pool.py", line 482, in _get_new_connection
    **self._connect_kwargs)
  File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\asyncpg\connection.py", line 1997, in connect
    max_cacheable_statement_size=max_cacheable_statement_size,
  File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\asyncpg\connect_utils.py", line 677, in _connect
    raise last_error
  File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\asyncpg\connect_utils.py", line 668, in _connect
    record_class=record_class,
  File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\asyncpg\connect_utils.py", line 634, in _connect_addr
    tr, pr = await compat.wait_for(connector, timeout=timeout)
  File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\asyncpg\compat.py", line 103, in wait_for
    return await asyncio.wait_for(fut, timeout)
  File "C:\Users\lisgl\AppData\Local\Programs\Python\Python37\lib\asyncio\tasks.py", line 442, in wait_for
    return fut.result()
  File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\asyncpg\connect_utils.py", line 547, in _create_ssl_connection
    host, port)
  File "C:\Users\lisgl\AppData\Local\Programs\Python\Python37\lib\asyncio\base_events.py", line 962, in create_connection
    raise exceptions[0]
  File "C:\Users\lisgl\AppData\Local\Programs\Python\Python37\lib\asyncio\base_events.py", line 949, in create_connection
    await self.sock_connect(sock, address)
  File "C:\Users\lisgl\AppData\Local\Programs\Python\Python37\lib\asyncio\selector_events.py", line 473, in sock_connect
    return await fut
  File "C:\Users\lisgl\AppData\Local\Programs\Python\Python37\lib\asyncio\selector_events.py", line 503, in _sock_connect_cb
    raise OSError(err, f'Connect call failed {address}')
ConnectionRefusedError: [Errno 10061] Connect call failed ('127.0.0.1', 5432)

site.py
from aiohttp import web
from sqlalchemy import select
from . import datab

async def post(request):
    async with request.app["db"].acquire() as conn:
        query = select([datab.post])
        result = await conn.fetch(query)

    return web.Response(body=str(result))

And here is the error that crashes if you go to the URL I need:
Error handling request
Traceback (most recent call last):
  File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\aiohttp\web_protocol.py", line 422, in _handle_request
    resp = await self._request_handler(request)
  File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\aiohttp\web_app.py", line 499, in _handle
    resp = await handler(request)
  File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\demo\site.py", line 13, in post
    async with request.app["db"].acquire() as conn:
  File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\asyncpg\pool.py", line 785, in __aenter__
    self.connection = await self.pool._acquire(self.timeout)
  File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\asyncpg\pool.py", line 622, in _acquire
    self._check_init()
  File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\asyncpg\pool.py", line 745, in _check_init
    raise exceptions.InterfaceError('pool is not initialized')
asyncpg.exceptions._base.InterfaceError: pool is not initialized

A: Your dsn is incorrect, so you can't connect to your database.
postgres://user:pass@host:port/database?option=value is the correct format. You forgot the user and the password.
Also asyncpgsa.create_pool() should be awaited, if not. You don't get the error, because you only assign a coroutine to the variable app['db']. So the connection pool is also not created.
Your second error (from site.py) is caused by not initizalising the connection pool.
More about that you can find in the documentation of asyncpg here (because asyncpgsa's connection pool is based on asyncpg's connection pool).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Use DB connection in programming languages I have a question that I can't seem to find the answer to so I'll try here at stackoverflow.
I see when people is programming in different languages (eg. Java, C#, etc.) they type db info directly in the source.
I have allways used an api (in my case, php backend), because I don't trust the end-user.
Wouldn't anyone with the correct skills be able to reverse enginer the executable file and read the source? I know you can obfuscate your code, but is this secure enough?
A good example: Someone who creates a application in C#, containing a db connection. They use .NET reactor to obfuscate the file. I know there exists deobfuscators for .NET reactor obfuscated files. So.. ? Should we allways use some sort of api because we only trust our own server with db info?

A: If you let me download a program, you should assume that I can reverse-engineer what exactly the program does. Various kinds of obfuscation and encryption can make this harder, but they will never make it impossible.
So, if you put your DB information into your application, you should assume that a malicious user will be able to access the database with the credentials from the application. If that is not okay (it might be, for example if the credentials give read-only access), then don't do it.
Having some kind of intermediary server with an API that sits between the application and the database is a reasonable approach. But it doesn't completely solve the issue by itself: now you should assume that the malicious user can access the API and you have to make sure that that is okay.
A similar solution is to move not just the DB code to server you control, but move (almost) all your code there and make your application into a web site.
Yet another solution might be to distribute the application only to users you trust (e.g. employees of your company).


text:
Q: How to use maven dependency:copy goal? I have 2 artifacts that I'd like to copy from my local repository to a directory in filesystem.
I think dependency:copy does this job. But, it requires an argument artifactItems.
http://maven.apache.org/plugins/maven-dependency-plugin/examples/copying-artifacts.html
Can any one help me with using this goal in command line. Unfortunately, maven doesnt show the usage of this goal in command line.

A: Rather than trying to figure out how to provide an artifactItem by command line, I'd configure the command line execution for the dependency plugin.  Do that by specifying default-cli as the execution ID.  If you always want to copy the same dependencies, you could hardcode the GAV coords in the artifact item(s).  Or, hardcode any values that remain constant between commands.
To copy different artifacts via command line, use properties as element values and specify the values on the command line.  For example, if configuration for artifactItem included <artifactId>${copy.artifactId}</artifactId> then
mvn dependency:copy -Dcopy.artifactId=myArtifact
would copy myArtifact (example assumes other elements have hardcoded values).
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <version>2.4</version>
    <executions>
    <execution>
    <id>default-cli</id>
    <configuration>
      <artifactItems>
        <artifactItem>
          <!-- hardcode values, or use properties, depending on what you want to do -->
          <groupId>[ groupId ]</groupId>
          <artifactId>[ artifactId ]</artifactId>
          <version>[ version ]</version>
          <type>[ packaging ]</type>
          <outputDirectory>/the/filesystem/dir</outputDirectory>
        </artifactItem>
      </artifactItems>
      <!-- other configurations here -->
    </configuration>
    </execution>
    </executions>
  </plugin>

A: Not sure if you want to do this from within a Maven project or without one. In case of the former, you can use this:
mvn dependency:copy -Dartifact='group.id:artifact.id:your.version'

In case you define the version of the artifact in your pom.xml using properties, you can also have it use that version like this:
mvn dependency:copy -Dartifact='group.id:artifact.id:${version.property}'

A: If you do not want to write artifactItems in your pom.xml, you could just use the command: "mvn dependency:copy-dependencies" instead of "mvn dependency:copy".


text:
Q: Can localized wavepackets have mass? Page 31 of David Tong's notes on QFT (also in Srednicki's book while discussing LSZ reduction formula), talks about Gaussian wavepackets $$|\varphi\rangle=\int \frac{d^3\textbf{p}}{(2\pi)^{3}}e^{-i\textbf{p}\cdot\textbf{x}}\varphi(\textbf{p})|\textbf{p}\rangle$$ with $\varphi(\textbf{p})=\exp[-\textbf{p}^2/2m^2]$ such that the state is somewhat localized in position space and somewhat localized in momentum space. My question is whether such state satisfy relativistic dispersion relation (RDR) $E^2-\textbf{p}^2=m^2$, if the one-particle Fock states $|\textbf{p}\rangle$ satisfy, $E^2-\textbf{p}^2=m^2$. If not, can it faithfully represent a real physical particle?
EDIT: Is it possible to consider a different function than $\varphi(\textbf{p})=\exp[-\textbf{p}^2/2m^2]$ so that the state is at the same time somewhat localized and also has a mass $m$?

A: $$P^2 \, \int \text d ^3 \mathbf p f(\mathbf p ) \vert \mathbf p \rangle = \int \text d ^3 \mathbf p f(\mathbf p ) P^2 \vert \mathbf p \rangle = m^2\int \text d ^3 \mathbf p f(\mathbf p )  \vert \mathbf p \rangle$$
All these states are by definition on the mass shell (for each wavefunction $f$). Note that the localization in position is just a heuristic concept,  if they have not introduced a relativistic position operator. It means that $$\intop \text d ^3 \mathbf p f_1(\mathbf p )^* f_2(\mathbf p)\approx 0$$ irrespective of the momentum distributions $\vert f_{1,2}(\mathbf p)\vert ^2$.


text:
Q: QUrl parsing in QT 5 I have a QUrl as this:
https://www.example.com/index.html#token=SomeToken&user=guest
and I want to obtain the value of the token i.e. SomeToken. I know about method QUrl::queryItemValue,so this code must work:
void MainWindow::get_token(QUrl url)
{
    url = url.toString().replace("?","#");
    QString token = url.queryItemValue("token");
}

but in Qt5 i can't use this method,how can I parse url?

A: There is new QUrlQuery class in Qt5. New QUrl doesn't support this method yet, so you should use QUrlQuery for parsing (it has this and other methods). Use
QUrlQuery query(url);
qDebug() << query.queryItemValue("token");

Note: be carefull with replace because QUrlQuery gives you correct result with
?token=SomeToken not a #token=SomeToken
http://qt-project.org/doc/qt-5/qurlquery.html

A: QUrlQuery queryItemValue method does not work properly in Qt 5.9 So i wrote my own function to parse GET parameters
#include <QCoreApplication>
#include <QUrlQuery>
#include <QDebug>
#include <QMap>
#include <QUrl>

QMap<QString,QString> ParseUrlParameters(QString &url)
{
QMap<QString,QString> ret;
if(url.indexOf('?')==-1)
{
    return ret;
}

QString tmp = url.right(url.length()-url.indexOf('?')-1);
QStringList paramlist = tmp.split('&');

for(int i=0;i<paramlist.count();i++)
{
    QStringList paramarg = paramlist.at(i).split('=');
    ret.insert(paramarg.at(0),paramarg.at(1));
}

return ret;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QString url = "http://test1.ru/?token=test&email=test1";

    QUrlQuery query(url);
    qDebug() << "queryItemValue does not work in Qt 5.9.0 with dynamic QString" << query.queryItemValue("token") << "("<< endl;

    qDebug() << "ParseUrlParameters(...) works fine..."<< endl;

    QMapIterator<QString, QString> i(ParseUrlParameters(url));
    while (i.hasNext())
    {
        i.next();
        qDebug() << i.key() << ":" << i.value();
    }

    return a.exec();
}

A: I know this post is old but if my answer can help someone, I share :)
Tested under QT 5.15.2 and under QT 6.4.2
#include<QUrl>
#include<QUrlQuery>
#include<QDebug>

int main (int nbArg, char* listArg[])
{
  // Initialization
  QString myString = "https://www.factice.fr/demo.php?thing=123&subject=456&artificial=789";
  QUrl myUrl(myString);
  QUrlQuery myQuery(myUrl);
  QMap<QString,QString> paramList;  // Associative Array to Store Keys and Values

  // For Each QPair
  for(int i=0;i<myQuery.queryItems().size();i++)
  {
   // Information Display
   qDebug() << myQuery.queryItems().at(i).first << " : " << myQuery.queryItems().at(i).second;

   // Or Storage of Information for futur use
   paramList.insert(myQuery.queryItems().at(i).first,myQuery.queryItems().at(i).second);
  }
  // End - For Each QPair

  // Examples of Displaying Stored Information
  qDebug() << paramList;
  qDebug() << paramList["thing"];
}


text:
Q: Moving site columns and content types between farms I can't seem to find the codeplex solution that helps export site columns, content types and import back to another sc or farm.
Idea is to retain the guid for these. I know create wsp vs project is the way to go but I am the only developer and dont have time create projects.

A: I found these two PowerShell posts from Phil Childs quite helpful in my attempts (I presume you are looking for a PowerShell approach) -

*

*Export and import/create site columns in SharePoint using PowerShell

*Export and import/create site content types in SharePoint using PowerShell


text:
Q: Find the roots of a given polynomial Let $f=X^{10}-5X^{8}+a_{7}X^{7}+ a_6X^6+...+a_{1}X+a_{0}$ be a polynomial with real coefficients.
We are asked to determine its roots $x_{1},x_{2},...,x_{10}$, where $|x_{1}|\geq 3$ and $x_{1},x_{2},...,x_{10}\in \mathbb{R}$.
I know that $x_{1}+...+x_{10}=0$, $x_{1}x_{2}+...+x_{9}x_{10}=-5$ and $x_{2}^{2}+...+x_{10}^{2}\leq 1$, but I haven't found anything meaningful besides this yet.
Thank you!


text:
Q: Dash Plotly - How to make 2 conditions to plot a histogram? I'm looking for a way to graph a histogram for data respecting 2 Dropdown. I have to choose the value of firstcalland the value of the secondcall in order to plot the histogram. I don't find lot of literature on this subject I hope one of you have already face to this.
Please find an excel file with some data and the code I try bellow:
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
import pandas as pd

df = pd.read_excel(
    "/Users/appelexcel.xlsx"
)

mgr_options = df["premierappel"].unique()
mgr_options_second = df["secondappel"].unique()

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

colors = {
    'background': '#FDFFFF',
    'text': '#0A25DC'
}

app.layout = html.Div(style={'backgroundColor': colors['background']},children=[
    html.H1(children='Call',
     style={
            'textAlign': 'center',
            'color': colors['text']
        }
        ),

    html.Div(
        [
            dcc.Dropdown(
                id="premierappel",
                options=[{
                    'label': i,
                    'value': i
                } for i in mgr_options],
                value='All First Call'),
        ],
        style={'width': '25%',
               'display': 'inline-block'}),
    dcc.Graph(id='secondcallgraph'),
 #The first plot just give the 2nd call

    html.Div(
        [
            dcc.Dropdown(
                id="secondappel",
                options=[{
                    'label': i,
                    'value': i
                } for i in mgr_options_second],
                value='All Second Call'),
        ],
        style={'width': '25%',
               'display': 'inline-block'}),
    dcc.Graph(id='thirdcallgraph'), # second figure
])

@app.callback(
    dash.dependencies.Output('secondcallgraph', 'figure'),
    [dash.dependencies.Input('premierappel', 'value')])
def update_graph(premierappel):
    if premierappel == "All First Call":
        df_plot = df.copy()
    else:
        df_plot = df[df['premierappel'] == premierappel]

    #func=(lambda x: round(100*x.count()/df_plot.shape[0] ,2))
    pv = pd.pivot_table(
        df_plot,
        index=['Age_1_2'],
        columns=['secondappel'],
        values=['frequency_1_2'],
        aggfunc=sum,
        fill_value=0)

    trace1 = go.Bar(x=pv.index, y=pv[('frequency_1_2', 'modification')], name='Modification')
    trace2 = go.Bar(x=pv.index, y=pv[('frequency_1_2', 'informations')], name='Informations')
    trace3 = go.Bar(x=pv.index, y=pv[('frequency_1_2', 'autres')], name='Autres')
    trace4 = go.Bar(x=pv.index, y=pv[('frequency_1_2', 'achat')], name='Achat')

    return {
        'data': [trace1, trace2, trace3, trace4],
        'layout':
        go.Layout(
            title='Appel 2 / {}'.format(premierappel),
            xaxis=dict(
                title='Days after 1st Call'),
            yaxis=dict(
                title='Count'),
            barmode='stack')
    }

Second graph (on third call)
My problem appears here, how can I tell him to take into account 2 conditions (one on first call and one on the second call qualification) ?
@app.callback(
    dash.dependencies.Output('thirdcallgraph', 'figure'),
    [dash.dependencies.Input('premierappel', 'value'), dash.dependencies.Input('secondappel', 'value')])
def update_graph(premierappel,secondappel):
    if premierappel & secondappel == "All Second Call":
        df_plot = df.copy()
    else:
        df_plot = df[(df['premierappel']==premierappel) & (df['secondappel']==secondappel)]

    #func=(lambda x: round(100*x.count()/df_plot.shape[0] ,2))
    pv = pd.pivot_table(
        df_plot,
        index=['Age_2_3'],
        columns=['troisiemeappel'],
        values=['frequency_2_3'],
        aggfunc=sum,
        fill_value=0)

    trace1 = go.Bar(x=pv.index, y=pv[('frequency_2_3', 'modification')], name='Modification')
    trace2 = go.Bar(x=pv.index, y=pv[('frequency_2_3', 'informations')], name='Informations')
    trace3 = go.Bar(x=pv.index, y=pv[('frequency_2_3', 'autres')], name='Autres')
    trace4 = go.Bar(x=pv.index, y=pv[('frequency_2_3', 'achat')], name='Achat')

    return {
        'data': [trace1, trace2, trace3, trace4],
        'layout':
        go.Layout(
            title='Appel 2 / {}'.format(secondappel),
            xaxis=dict(
                title='Days after 2nd Call'),
            yaxis=dict(
                title='Count'),
            barmode='stack')
    }

if __name__ == '__main__':
    app.run_server(debug=True)

Thanks for your time !
Age_._. : time between calls.
Frequence : should be frequency but it's really random just to see how it's working.
Please find the data above.
https://docs.google.com/spreadsheets/d/1u7E6GwJj1nsjOwIQIntcCWCKsczw36_iHPiEV2bjMcs/edit?usp=sharing

A: I can't wrap my head around what it is supposed mean. But here is what I can assume from the error messages I am getting:
File "pandas\_libs\index.pyx", line 672, inpandas._libs.index.BaseMultiIndexCodesEngine.get_loc

KeyError: ('frequency_2_3', 'modification')

That's it.
In your second callback you are assigning four traces. But the variable (pandas.Series()) pv will only hold a single column (during my debugging trials).
Assuming that the second callback is supposed to work as a filter:
The solution might involve a If ... elif ... else block.


text:
Q: Jquery .load() with data from form I am trying to load a page into a modal window "checkout.php" after submitting a form, but I need it to load with the results of the form. Normally, one would just set the action of the form to the url and the data gets passed, but in this case, the page needs to be loaded into a modal with that data which requires the use of more jQuery than I know.
HTML
<form id="shippingform" name="shippingform" method="post" action="#">

        USPS Option
        Price
        Select

  Ground:
  <?php echo "$" . sprintf("%01.2f", $groundTotal) ?>
  <input name="shipping" type="radio" id="radio" value="<?php echo $groundTotal ?>" checked="checked" />

  Priority:
  <?php echo "$" . sprintf("%01.2f", $priorityTotal) ?>
  <input type="radio" name="shipping" id="radio2" value="<?php echo $priorityTotal ?>" />

  Express:
  <?php echo "$" . sprintf("%01.2f", $expressTotal) ?>
  <input type="radio" name="shipping" id="radio3" value="<?php echo $expressTotal ?>" />

submit
</form>

JS

What I have above will load the checkout.php page into the modal after clicking the submit button for the form. I AM NOT asking why the page isnt loading with the information sent with the form. I completely understand that what I am doing here is simply executing a function to load "checkout.php" into the div that is the modal. I need someone to explain to me how I can edit my function so that "checkout.php" gets loaded like if it were the action of the form, the data would be passed through.
Thanks in advance for the help!
EDIT BELOW
<form id="shippingform" name="shippingform" method="post" action="#">

JS
$('#shippingform').submit(function(event){
var data = $(this).serialize();
$.post('/ash/shop/checkout.php', data)
    .success(function(result){
        $('#cartdialog').html(result);
    })
    .error(function(){
        console.log('Error loading page');
    })
return false;
});

THE CHECKOUT.PHP PAGE WHERE IT CALLS THE INPUT "shipping"
<?php
//total up price of all items
$subtotal = ($subtotal + ($row_rsMyCart['price'] * $row_rsMyCart['quantity']));
$myTotal = ($subtotal + $_POST['shipping']);

} while ($row_rsMyCart = mysql_fetch_assoc($rsMyCart)); ?>

<?php
//development
echo "
";
echo "Subtotal: $" . sprintf("%01.2f", $subtotal);
echo "
";
echo "Total: $" . sprintf("%01.2f", $myTotal);
?>

A: Use $.post() to submit the form using ajax.
$('#shippingform').submit(function ()
{
    var $this = $(this);

    $.post('/ash/shop/checkout.php',
    {
        data: $this.serialize()
    }, function (response)
    {
        $('#cartdialog').html(response);
    });

    return false;
});

A: Bind to the submit event on your form, instead of using the onClick attribute.
On submit, serialise the form values, post to your url and insert the result into the target div.
$('#myform').submit(function(event){
    var data = $(this).serialize();
    $.post('/ash/shop/checkout.php', data)
        .done(function(result){
            $('#cartdialog').html(result);
        })
        .fail(function(){
            console.log('Error loading page');
        })
    return false;
});

EDIT 1: Given your html, you need to replace
submit

with
<input type="submit" name="submit" value="Submit">


text:
Q: In Python, how to automatically import all nested packages without namespace override? I have a 2-layer package:
package1
|--package2
|  |--function1
|  |--function2
|--package3

I'm trying to avoid name/import conflict as much as possible, so I import all members in a package without changing there namespaces, then use the functions by their full name:
import package1 as package1

package1.package2.function1(...)

However, the interpreter gave me the following error:
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'package2'

This seems to be illogical since package2 is definitely in the namespace of package1, which I have already imported. If I would like to keep using my function call format, what kind of import should I use WITHOUT referring to package2 and package3?
I've also tried the following:
import package1.*               (doesn't work)
from package1 import * as package1.* (obviously doesn't work)
from package1 import *          (works but bad practice, causes naming conflict)

But non of them fulfils my need.


text:
Q: I am having the error when trying to convert the field character to Uppercase using select case I am having the error below when trying to convert the field character to Uppercase when the length of the country name is greater than the length of the currency name.
ORA-00923: FROM keyword not found where expected
00923. 00000 -  "FROM keyword not found where expected"

This is the SQL statement I used:
 select
 countryname.country, countryname.currencycode, currency.currencyname
 case(
 when length(countryname.country)> length (currency.currencyname)
 then UCASE(countryname.country)
 else
 LCASE(countryname.country)
 )end
 from  currency,countryname
 where currency.currencycode=COUNTRYNAME.currencycode;

A: Try adding a comma after the first currencyname, and removing the brackets after the case keyword:
select
 countryname.country, countryname.currencycode, currency.currencyname,
 case
 when length(countryname.country)> length (currency.currencyname)
 then UCASE(countryname.country)
 else
 LCASE(countryname.country)
 end
 from  currency,countryname
 where currency.currencycode=COUNTRYNAME.currencycode;

A: You're missing a comma after currency.currencyname

A: Im not familiar with oracle, but the error seems to specify a different issue.
Could it be that you just forgot to put an "," after currencyname?


text:
Q: Brightness on laptop MSI GT72VR in Ubuntu 18.04 with NVIDIA GTX 1060 Mobile doesn't work I can't adjust brightness
I've got a MSI GT72VR laptop with ONLY 1 graphic card, a NVIDIA GeForce GTX 1060 Mobile and 2 audio card, a NVIDIA GP106 and a Intel CM238.
The problem is that I can't adjust the brightness of my screen. Always is 100%. I've got Ubuntu 18.04 clean install and nouveau drivers (Xorg.org)

There aren't brightness slider at the top of bar:

Also, the keys Fn + Bright Up and Fn + Bright Down doesn't do anything
Things I've already tried that don't work [1 May 2018]

*

*Change driver to NVIDIA driver 390

*Install and use redshift, xbacklight Link

*Edit with sudo vi /etc/default/grub

*

*GRUB_CMDLINE_LINUX_DEFAULT="quiet splash acpi_backlight=vendor"

*GRUB_CMDLINE_LINUX_DEFAULT="quiet splash acpi_backlight=native"

*GRUB_CMDLINE_LINUX_DEFAULT="quiet splash acpi_backlight=video"

*GRUB_CMDLINE_LINUX_DEFAULT="quiet splash acpi=off"

*And then update-grub and reboot Link Link
Output for some commands
lspc | grep NVIDIA:
01:00.0 VGA compatible controller: NVIDIA Corporation GP106M [GeForce GTX 1060 Mobile] (rev a1)
01:00.1 Audio device: NVIDIA Corporation GP106 High Definition Audio Controller (rev a1)

ll /sys/class/backlight:
total 0
drwxr-xr-x  2 root root 0 may  1 12:32 ./
drwxr-xr-x 67 root root 0 may  1 12:10 ../

dmesg | grep -i vga:
[    0.148024] pci 0000:01:00.0: vgaarb: setting as boot VGA device
[    0.148024] pci 0000:01:00.0: vgaarb: VGA device added: decodes=io+mem,owns=io+mem,locks=none
[    0.148024] pci 0000:01:00.0: vgaarb: bridge control possible
[    0.148024] vgaarb: loaded
[    0.969601] fb0: EFI VGA frame buffer device
[    1.349219] fb: switching to nouveaufb from EFI VGA
[  543.049571] snd_hda_intel 0000:01:00.1: Handle vga_switcheroo audio client

uname -a:
Linux laptop 4.15.0-20-generic #21-Ubuntu SMP Tue Apr 24 06:16:15 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux

journalctl -b | grep -i nvidia:
may 01 12:19:27 laptop kernel: nouveau 0000:01:00.0: NVIDIA GP106 (136000a1)
may 01 12:19:28 laptop kernel: input: HDA NVidia HDMI/DP,pcm=3 as /devices/pci0000:00/0000:00:01.0/0000:01:00.1/sound/card1/input16
may 01 12:19:28 laptop kernel: input: HDA NVidia HDMI/DP,pcm=7 as /devices/pci0000:00/0000:00:01.0/0000:01:00.1/sound/card1/input17
may 01 12:19:33 laptop /usr/lib/gdm3/gdm-x-session[1171]: (II) NOUVEAU driver for NVIDIA chipset families :
may 01 12:19:33 laptop /usr/lib/gdm3/gdm-x-session[1171]: (--) NOUVEAU(0): Chipset: "NVIDIA NV136"
may 01 12:19:38 laptop /usr/lib/gdm3/gdm-x-session[1171]: (II) config/udev: Adding input device HDA NVidia HDMI/DP,pcm=3 (/dev/input/event15)
may 01 12:19:38 laptop /usr/lib/gdm3/gdm-x-session[1171]: (II) config/udev: Adding input device HDA NVidia HDMI/DP,pcm=7 (/dev/input/event16)

inxi -SMCGAx:
System:    Host: laptop Kernel: 4.15.0-20-generic x86_64 bits: 64 gcc: 7.3.0
           Desktop: Gnome 3.28.1 (Gtk 3.22.30-1ubuntu1) Distro: Ubuntu 18.04 LTS
Machine:   Device: laptop System: Micro-Star product: GT72VR 7RD v: REV:1.0 serial: N/A
           Mobo: Micro-Star model: MS-1785 v: REV:1.0 serial: N/A
           UEFI: American Megatrends v: E1785IMS.30E date: 10/27/2017
CPU:       Quad core Intel Core i7-7700HQ (-MT-MCP-) arch: Skylake rev.9 cache: 6144 KB
           flags: (lm nx sse sse2 sse3 sse4_1 sse4_2 ssse3 vmx) bmips: 22464
           clock speeds: max: 3800 MHz 1: 1046 MHz 2: 3165 MHz 3: 3164 MHz 4: 3139 MHz 5: 3093 MHz 6: 3190 MHz
           7: 3056 MHz 8: 3046 MHz
Graphics:  Card: NVIDIA GP106M [GeForce GTX 1060 Mobile] bus-ID: 01:00.0
           Display Server: x11 (X.Org 1.19.6 ) drivers: fbdev,nouveau (unloaded: modesetting,vesa)
           Resolution: 1920x1080@120.00hz
           OpenGL: renderer: NV136 version: 4.3 Mesa 18.0.0-rc5 Direct Render: Yes
Audio:     Card-1 Intel CM238 HD Audio Controller driver: snd_hda_intel bus-ID: 00:1f.3
           Card-2 NVIDIA GP106 High Definition Audio Controller driver: snd_hda_intel bus-ID: 01:00.1
           Sound: Advanced Linux Sound Architecture v: k4.15.0-20-generic

sudo lshw -C display:
  *-display
       description: VGA compatible controller
       product: GP106M [GeForce GTX 1060 Mobile]
       vendor: NVIDIA Corporation
       physical id: 0
       bus info: pci@0000:01:00.0
       version: a1
       width: 64 bits
       clock: 33MHz
       capabilities: pm msi pciexpress vga_controller bus_master cap_list rom
       configuration: driver=nouveau latency=0
       resources: irq:131 memory:de000000-deffffff memory:c0000000-cfffffff memory:d0000000-d1ffffff ioport:e000(size=128) memory:c0000-dffff

A: I have an Asus GL502VM with Nvidia 1060 and a gsync display. I faced the same issue, haven't found a permanent fix but the workaround from here
worked for me.
In order to use it you need to install the nvidia driver instead of xorg one and modify the DP-0 value according to your setup, in my case according to xrandr --verbose my display is connected to DP-2 port.
Also night light option will change the brightness level so I disabled it.
Brightness seems to be working in unity on 18.04 though.
The bug is reported https://bugs.launchpad.net/ubuntu/+bug/1767001

A: Try acpi_osi=
On upgrading to Bionic today, I encountered the same problem (same graphics card and the same problem with an empty /sys/class/backlight).
In working through the backlight debugging procedure, I discovered a workaround via kernel parameters.  Mimicking your instructions above:

*

*Change driver to NVIDIA driver 396.

*Edit with sudo vi /etc/default/grub:

*

*GRUB_CMDLINE_LINUX_DEFAULT="quiet splash acpi_osi="

*And then sudo update-grub and reboot.

(Bug reported here.)


text:
Q: Simple Android Wifi Connection My code was returning Null Bss. Anyone knows how to implement it to work? Just want to connect to an Wifi NetWork from my home.
Thanks.
public class Scan extends AppCompatActivity {

public String ssid;
public String password;
public String security;

public EditText nome, senha, tipo;
public Button connectar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_scan);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    nome = (EditText) findViewById(R.id.etSSID);
    senha = (EditText) findViewById(R.id.etPASS);
    tipo = (EditText) findViewById(R.id.etTIPO);

}

public void connectar(View view){
    //Toast.makeText(Scan.this, "Conectado", Toast.LENGTH_SHORT).show();
    String ssidC = nome.getText().toString();
    String senhaC = senha.getText().toString();
    String tipoC = tipo.getText().toString();

    connect(ssidC, senhaC, tipoC);
}

public void connect(String ssid, String password, String security){

    WifiConfiguration wfc = new WifiConfiguration();

    wfc.SSID = "\"".concat(ssid).concat("\"");
    wfc.status = WifiConfiguration.Status.DISABLED;
    wfc.priority = 40;

    if(security.equals("WPA2")){
        wfc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
        wfc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
        wfc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
        wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
        wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
        wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
        wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
        wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
        wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);

        wfc.preSharedKey = "\"".concat(password).concat("\"");

    }

    WifiManager wfMgr = (WifiManager)getSystemService(Context.WIFI_SERVICE);
    int networkId = wfMgr.addNetwork(wfc);
    if (networkId != -1) {
        wfMgr.enableNetwork(networkId, true);
    }

}

}

I am passing the SSID, PASSWORD and WPA2 on my EditText.
The logcat was saying BSS was null.


text:
Q: How can I view the main form in a Visual Studio Visual C++ Win32 Project so I can edit it? I am migrating a C++ Builder program to a Visual Studio 2013 C++/Win32/Win32 Project.
Try as I may, however, after I create a new project (C++/Win32/Win32 Project), I can't see how to view/edit the main form which is created automatically when Visual Studio creates the project.  I know how to view/edit forms in C#, C++ Builder, and Delphi, but I'm not seeing how to view the form so that I can add to it in VS 2013 for a C++ Windows application.
What is it that I do not understand? What rock is the main form hidden under in the IDE?
I know the form is there, with a simple menu and an about box, because it is displayed when the newly created project/program is run.
By form I mean the main window for the newly created application.

A: Sounds to me like you created a straight Win32 project (non-MFC). In that case, there isn't a form designer like you are accustomed to. Much is created by code.
You'll find something like:
case IDM_ABOUT:
    DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
    break;

Open the Resource Files, Win32Project1.rc, and open the Dialog subfolder, you'll see a dialog designer. Besides that, you won't find a Form that is editable the way C++ Builder allows. At first glance you'll think you have a form designer, but shortly you'll find it is pretty lacking. To design complex UIs requires more.
The bad news, if you are coming from a C++ Builder background, you will find Visual C++ not so RAD / WYSIWIG. There are several ways to do it, not all of which involve design time form wizards. Much of traditional Visual C++ programming creates the UI dynamically.
If you want true RAD with Visual Studio, you'll need to move to C# / .NET and Winforms or WPF.
If you are sticking with C++, I recommend you recreate your project and choose the MFC option, or look at Qt or another 3rd party UI framework. MFC (Microsoft Foundation Classes) and the MFC Project Wizard will give you more controls to choose from, and more of a jump start by helping you create an app skeleton with Single/Multiple Document Interface, etc.

A: There is a big paradigm change between a "Winforms" application and a standard Visual C++ Windows application:

*

*Winforms applications use managed code, which can be C#, VB or C++/CLI.

*In Winforms, the programmer doesn't have to know about the Windows message pump to write code for forms, controls and events.

*Visual C++ applications do not typically use managed code, and these programs run without the .Net framework.

*If you want, you can use Winforms in your Visual C++ project, but that action will convert the project to a managed code project (C++/CLI).

*Visual C++ uses resource files to store the layout of the forms, whereas winforms application uses designer classes (For example, myForm.designer.cs)
Unfortunately there is no editor available in Visual studio to edit the main window. You have to do that using code.
Debug this method in your project to see how the Windows message system works.
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    int wmId, wmEvent;
    PAINTSTRUCT ps;
    HDC hdc;

    switch (message)
    {
    case WM_COMMAND:
        wmId    = LOWORD(wParam);
        wmEvent = HIWORD(wParam);
        // Parse the menu selections:
        switch (wmId)
        {
        case IDM_ABOUT:
            DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
            break;
        case IDM_EXIT:
            DestroyWindow(hWnd);
            break;
        default:
            return DefWindowProc(hWnd, message, wParam, lParam);
        }
        break;
    case WM_PAINT:
        hdc = BeginPaint(hWnd, &ps);

    // TODO: *****************Add any drawing code here...*****************

        EndPaint(hWnd, &ps);
        break;
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
    }
    return 0;
}

A: Open the resource files where you can edit the "about box" & menu items. The window is created using the API CreateWindow & the parameters passed to the functions defines the view of the window. In win32, only dialog boxes can be edited in the resource file while the view of your window requires writing code in the win32 message i.e WM_PAINT to draw the window according to your requirement. If your looking for a form window like interface than you can call the dialogbox api in the winmain & remove all code to window creation. That would be much easier to add buttons, list & other controls.


text:
Q: Let the author of the question highlight bits and pieces from answers Could you let the author of a question highlight bits and pieces from one or more answers? This is

*

*to show why he/she chose this answer

*to highlight good points/ideas from other answers

Or let him/her make some kind of summary or even the summary could be worked out collectively.

A: The question asker can already do this in a number of different ways:

*

*answer the question themselves, and synthesize the best parts of the existing answers in their own answer, wiki style (should be community wiki, and sources should be attributed)

*edit the question with a summary at the bottom, indicating what the author feels is the best "synthesized" answer

*accept an answer, then edit it to taste (ideally as a separate section below the original answer)

*do nothing, let the vote order determine the best responses


text:
Q: Сортировка свойства массива по возрастанию Есть массив arRelated у которого есть свойства RELATED_SORT, которое нужно отсортировать по возрастанию
   for($i=0; $i<(count($arRelated)-1); $i++){
        if(!empty($arRelated[$i]["RELATED_SORT"])){
            var_dump(sort($arRelated[$i]["RELATED_SORT"],SORT_STRING));
        }
        var_dump($arRelated[$i]["RELATED_SORT"]);
    }

Печатаю var_dump выдаёт:

bool(false) string(4) "1000" bool(false) string(3) "555" bool(false)
  string(1) "5" bool(false) string(2) "10" bool(false) string(3) "200"

Подскажите, как исправить?

A: usort($arRelated, function($a, $b){
    if ($a["RELATED_SORT"] == $b["RELATED_SORT"]) return 0;
    return ($a["RELATED_SORT"] < $b["RELATED_SORT"]) ? -1 : 1;
});

Сортировка с использованием пользовательской функции

A: Можешь воспользоваться php функцией natsort. Она сортирует массив, используя алгоритм "natural order".
То есть можно попробовать вот так
natsort($arRelated[$i]["RELATED_SORT"],SORT_STRING));


text:
Q: Bluetooth driver for Intel® Dual Band Wireless-AC 7260 Wi-Fi and Bluetooth is not getting installed?
My OS is 64 bit Windows 7 ultimate.
I tried many drivers for the INTEL ac7260 dual band wifi + bluetooth card but not able to get this done.


text:
Q: Как нарисовать пиксель в picture box? Ковыряюсь в Windows Forms. По итогу мне нужно будет имея какую-то функцию (математическую) строить график. В связи с этим хочется понять, как изобразить на форме точку.

A: С помощью Bitmap, а именно функцией Bitmap.SetPixel().
Но если вы хотите рисовать графики, то это не лучший способ. В Windows Forms есть элемент Chart. Пользоваться им можно примерно так:
chart->Series[0]->Points->AddXY(x, f(x));

Там можно настроить тип интерполирования функции. Думаю, spline будет наиболее подходящий для вас.

A: Этот ответ был в английском so
e.Graphics.FillRectangle(aBrush, x, y, 1, 1);

A: В Windows Forms для построения графиков используется инструмент Chart.
Для выбора типа "График" выберите в Properties -> Series -> Revenue property -> ChartType. В выпадающем списке выберите необходимый тип графика.
Методы Chart рассмотрим на примере следующего кода по построению функций косинуса и синуса с комментариями:
private void buttonCalc_Click(object sender,

EventArgs e)

{

// Считываем с формы требуемые значения

double Xmin = double.Parse(textBoxXmin.Text);

double Xmax = double.Parse(textBoxXmax.Text);

double Step = double.Parse(textBoxStep.Text);

// Количество точек графика

int count = (int)Math.Ceiling((Xmax - Xmin) / Step)

+ 1;

// Массив значений X – общий для обоих графиков

double[] x = new double[count];

// Два массива Y – по одному для каждого графика

double[] y1 = new double[count];

double[] y2 = new double[count];

// Расчитываем точки для графиков функции

for (int i = 0; i < count; i++)

{

// Вычисляем значение X

x[i] = Xmin + Step * i;

// Вычисляем значение функций в точке X

y1[i] = Math.Sin(x[i]);

y2[i] = Math.Cos(x[i]);

}

// Настраиваем оси графика

chart1.ChartAreas[0].AxisX.Minimum = Xmin;

chart1.ChartAreas[0].AxisX.Maximum = Xmax;

// Определяем шаг сетки

chart1.ChartAreas[0].AxisX.MajorGrid.Interval = Step;

// Добавляем вычисленные значения в графики

chart1.Series[0].Points.DataBindXY(x, y1);

chart1.Series[1].Points.DataBindXY(x, y2);

}

Вот ссылка на пример.


text:
Q: Adding element to Iframe I am creating a page which contains iframe. My aim is to create a javascript that will add  to the head of the iframe content.
But I always get the error implying iframe.contentDocument is null.
Code for main page

<title>Sample "Hello, World" Application</title>

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

    test

A: I suggest you try
ifrm.contentWindow.document.getElementById("id")

A: Use the frame window name to create your element as you do in the main window like the following
ContentFrame.document...

In other word access the window name.
In addition your iframe window does not has any element with id value equals to "id".


text:
Q: How do I use Python request to make a POST response upload to a database and wait for a POST success before making another POST? I am using a scraper to upload json data to a database but I noticed that my uploads are not in order yet my local json data file FILE_PATH mirroring the database has my json data in order, meaning that the culprit is in how I use python's request module.
def main():
    if not FILE_PATH.is_file():
        print("initializing json database file")
        # intialize and reverse the dictionary list in one go, [start:stop:step]
        ref_links = getArchivedCharacterList()[::-1]
        index =0 # counting up the roster size for assignReleasedate
        for link in ref_links:
            char_details = getCharacterDetails(link['ref_id'],link['game_origin'],index)
            index +=1
            saveCharacterInfo(char_details)
            postRequest(POST_CHARA_DETAILS_URL,char_details,headers)
        print(f"Done! Updated the file with all previously released and archived units as of: \n {datetime.datetime.now()} \n See {FILE_PATH} for details!")

From the above, I initially scrape a page for a list of links using getArchivedCharacterList(), then for each link, I grab more information for individual pages and then I post them into my local file FILE_PATH using saveCharacterInfo and I POST it into my database with the postRequest function.
postRequest function
def postRequest(url,json_details,headers):
    r = requests.post(url, json=json_details, headers=headers)
    while r.status_code != 201:
        time.sleep(0.1)
        print(r.status_code)

I tried doing a while function to wait for the 201 POST success response. Didn't work. I looked up async/await tutorials and it doesn't seem like something I want... unless I am supposed to bundle up all my request posts in a single go? I did this before in javascript where I bundled up all my posts in a promise array is there a promise equivalent for python from javascript so that I do my uploads in order? Or is there another method to achieve a sequential upload?
Thank you in advance!


text:
Q: Dynamically load the components Angular 2 I am trying to load an array of components dynamically. I have an array which contains all the components that need to be load on run time. Following piece of code loops over the array and creates a factory for components.
`
gAfterViewInit() {
      this.loadcomponents();
  }
loadcomponents() {
      for (let i = 0; i < this.components.length; i++) {
          //this.sidetext[i] = this.components[i].sidetext;
          //this.section_ttile[i] = this.components[i].section_ttile;
          for (let j = 0; j < this.components[i].components.length; j++) {
              let termItem = this.components[i].components[j];
              let componentFactory = this.componentFactoryResolver.resolveComponentFactory(termItem.component);
              let viewContainerRef = this.termHost.viewContainerRef;
              viewContainerRef.clear();
              let componentRef = viewContainerRef.createComponent(componentFactory);
              (<TermComponent>componentRef.instance).data = termItem.data;
          }
      }

`
And here is my template

                    <ng-template term-host></ng-template>

But the problem is that dynamically loaded components appears on top of previous loaded component component. I want each component to be in a its own seperate div. Any suggestions on how to achieve this?
Following is th current output.

Expected output is two such input fields but it is only second one which actually overlapped first one completely.

A: You need to use @ViewChildren so you get a query list of containers.
Your template could be like this:

And your code will instance components like this:
@ViewChildren('target', {read: ViewContainerRef}) container: QueryList<ViewContainerRef>;

ngAfterViewInit(){
  this.container.toArray().map((viewContainerRef, i) => {
    let componentFactory = this.resolver.resolveComponentFactory(this.components[i]); // actually that should be this.components[i].components[j] something in your case
    let componentRef = viewContainerRef.createComponent(componentFactory);
  });
}


text:
Q: Comparing Phrases to whole text I have two text files. The first user inputs a paragraph of text. The second is a dictionary of terms gotten from an owl file. Like so:
Inferior salivatory nucleus
Retrosplenial area
lateral agranular part

I have coded the bits to make these files. I am stuck as to compare the files so that any whole phrases that appear in the dictionary and the paragraph of text are printed out in the command line in Java.

A: Try following code, it will help you. Correct your file path in fileName and enter your search condition into the while loop:
public class JavaReadFile {
    public static void main(String[] args) throws IOException {
        String fileName = "filePath.txt";

        //read using BufferedReader, to read line by line
        readUsingBufferedReader(fileName);
    }

    private static void readUsingBufferedReader(String fileName) throws IOException {
        File file = new File(fileName);
        FileReader fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);
        String line;
        while((line = br.readLine()) != null){
            //process the line
            System.out.println(line);
        }
        //close resources
        br.close();
        fr.close();
    }
}

A: You could write the file to a string and iterate over the keys in your dictionary and check if they are present in the paragraph with contains. This probably isn't a particularly efficient solution, but it should work.
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.Set;

public class Test {

    public static void main(String[] args) throws IOException {
        String fileString = new String(Files.readAllBytes(Paths.get("dictionary.txt")),StandardCharsets.UTF_8);

        Set<String> set = new HashSet<String>();
        set.add("ZYMURGIES");

        for (String term : set) {
            if(fileString.contains(term)) {
                System.out.println(term);
            }
        }
    }
}

A: Here's a Java 8 version of the contains checking.
package insert.name.here;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class InsertNameHere {
    public static void main(String[] args) throws IOException {
        String paragraph = new String(Files.readAllBytes(Paths.get("<paragraph file path>")));
        Files.lines(Paths.get("<dictionary file path>"))
                .filter(paragraph::contains)
                .forEach(phrase -> System.out.printf("Paragraph contains %s", phrase));
    }
}


text:
Q: Can I place a multipart form inside another form? File uploading My customer currently has a single form of text inputs and select boxes etc.  They now would like to have a field where the user can upload a file( they would like this placed pretty much right in the middle of the other form fields).
I was just going to use a multipart form to do the upload however this would place a form inside of a form.  From what I've read having a form inside a form is not recommended and only works on some browsers. Is this true? What would my best option for this situation?
Thanks -Ray

A: Answering my own question.   Answer: No, this is a very bad Idea.


text:
Q: Why does not working version in asp.net core controller I want to use api version in my .net core project.Then search web and find that's solution.
Even though do exactly all solutions,but I can't get desired result.
So if any can help me,Please show me..
I add Microsoft.AspNetCore.Mvc.Versioning 4.0.0 Package in my project and ..
StartUp.cs

Then in my Controller Add Rout Attribute as Shown :
[ApiController]
[Authorize]
[Route("v{version:apiVersion}/[Controller]")]
[ApiVersion("1.0")]
public class SellerController : Controller
{
    private readonly IBus _client;
    private readonly string AppBaseUrl = MyHttpContext.AppBaseUrl;
    //private readonly IGetUrl _globalUrl;

    public SellerController(IBus client/*, IGetUrl globalUrl*/)
    {
        _client = client;
        //_globalUrl = globalUrl;
    }

    [HttpGet("/Sellers/{SellerId}")] // Dashboard
    public async Task<IActionResult> Info(long SellerId)
    {
           ...
    }
}

With these code I expected that I can send request to 'Info' method by this url :

But that's not working and get 404 error code status.. when I delete "/v1.0" from url and send request, that's working. I will be glad to help me .. Thanks

A: In your code, we can find that you applied [HttpGet("/Sellers/{SellerId}")] with route
template begin with / to Info action method, which don't get combined with route templates applied to the controller. To make request to 'Info' method, you could use below URL.
https://localhost:5090/sellers/17

I expected that I can send request to 'Info' method by this url : https://localhost:5090/v1.0/sellers/17

To achieve your requirement, you can try to modify the code like below.
[HttpGet("/v{version:apiVersion}/Sellers/{SellerId}")]
public async Task<IActionResult> Info(long SellerId)
{
    //...
    //for testing purpose

    return Ok(SellerId);
}

Test Result

Update:
If you'd like to include v{version:apiVersion} in route template of controller level attribute routing, you can try to apply [HttpGet("{SellerId}")] to Info action method and make request with https://localhost:5090/v1.0/seller/17.
[ApiController]
[Authorize]
[Route("v{version:apiVersion}/[Controller]")]
[ApiVersion("1.0")]
public class SellerController : Controller
{
    [HttpGet("{SellerId}")] // Dashboard
    public async Task<IActionResult> Info(long SellerId)
    {
        //...


text:
Q: How do I perform UPDATE command in Databricks SQL? I am migrating SQL commands to Azure Databricks SQL. While running the below Update command in databricks SQL:
UPDATE three as t1
SET prod = WEB_TRFC_VISIT_SMRY.PRDCT_ID
where exists (
(SELECT SVC_TAG_ID, max(supp_sys_ID) as PRDCT_ID
FROM WEB_TRFC_VISIT_SMRY
GROUP BY  SVC_TAG_ID)
WHERE     t1.SVC_TAG_ID = SVC_TAG_ID)
I am getting below error:
"no viable alternative at input 'exists (\n(SELECT SVC_TAG_ID, max(supp_sys_ID) as PRDCT_ID\n      FROM WEB_TRFC_VISIT_SMRY\nGROUP BY  SVC_TAG_ID)\nWHERE'(line 7, pos 0)"
Could someone help me find a solution for this. Everything I try is throwing an error.


text:
Q: Convert Equilateral triangle to Isosceles triangle Let an equilateral triangle have the length of each side an integer $N$. I need to find if it is possible to transform the triangle keeping two sides fixed and alter the third side such that it still remains a triangle, but the altered side will have its length as an even integer, and the line drawn from the opposite vertex to the mid-point of the altered side is of integral length, i.e. it becomes an isosceles triangle.
Example : If $N=5$ then the answer is YES while if $N=3$ answer is NO.
It's a computer graphics problem that is a sub-part of bigger problem, I have been racking brains about maths and the concept behind it, to solve my problem.

A: To restate your question more clearly, you are asking what kind of integer number $N$ can be the hypothenuse of a right-angled triangle, so that the other two sides are of integer length too.
The answer is well known: $N$ must be (the multiple of) the sum of two perfect squares: $N=a^2+b^2$ (or $N=k(a^2+b^2)$). If so, the other two sides (which in your problem are half the modified side and "the line drawn from the opposite vertex to the mid-point of the altered side") are given by $a^2-b^2$ and $2ab$ (multiplied by $k$ if needed).
Example: $5=2^2+1^2$, $3=2^2-1^2$, $4=2\cdot(2\cdot1)$.

A: This is a question from CodeChef October Challange. Please dude dont lie


text:
Q: How do I fix "malformed line" errors when trying to run commands in apt? Is it that i am missing cretin functions that Debian had, this is just Ubuntu on a 64 bit Intel processor when running any apt scrip like an sudo apt-get install
$ sudo apt-get install python-setuptools python-virtualenv python-dev

E: Malformed line 2 in source list /etc/apt/sources.list.d/100-ubnt-unifi.list (type)
E: The list of sources could not be read.
E: Could not get lock /var/lib/dpkg/lock-frontend - open (11: Resource temporarily unavailable)
E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), is another process using it?

I had this same problem with my ARM processor and the dpkg files but it was different. what going on because because i am not sure if it just missing something about the Debian interface or maybe some bash scripting but i would like to know .
i saw that the fix isnt hard but last time i did a fix from what i saw cold be done i lost the ability to go on youtube. but that just might be the internet i have that allows me to surch for the answer. i cant really connect to the wifi, i need an inscription key. it on the wifi box but i not sure where it is located in the house and i am not quite sure if i need it. im leaving soon, nut im just looking for a apt-get fix for any other insulation of any 64 bit programs to run like virtual box.
--update--
i already did something to where the text editor doesnt come up the same but you are supposed to put these command first.
sudo cp /etc/apt/source.list  /etc/apt/source.list.old
sudo cat -n /etc/apt/source.list | grep 2
sudo gedit /etc/apt/source.list
on the second command right where it says "grep 2" you are supposed to put the number of lines you have that are malformed into the command. and i believe you are supposed to put a number sine where the link starts in the test editor followed but a space and then hit save. on your terminal it should say something like this..
$ sudo gedit /etc/apt/source.list
** (gedit:3452): WARNING **: 21:16:30.900: Set document metadata failed: Setting attribute metadata::gedit-position not supported
once it does that exit out of text editor and start a new terminal and start a apt-update && upgrade to see if you can source code an update. but beacuse i fail to put in the right code at the right time i was wondering if i could just copy and past what it should look like in the text editor and save after i put in a
$ sudo gedit /etc/apt/source.list
after the command or maybe i should just uninstall and reinstall the OS to see if i can fix my issue.
$ sudo cp /etc/apt/source.list  /etc/apt/source.list.old
cp: cannot stat '/etc/apt/source.list': No such file or directory
$ sudo cat -n /etc/apt/source.list | grep 2
cat: /etc/apt/source.list: No such file or directory
$ sudo gedit /etc/apt/source.list

A: Read the error messages.
The first one tells you which file, and which line has the error. Fix that error.
The second error was caused by the first error, and will probably go away when you fix the first error.
The third and fourth error messages indicate a different problem.
Either you're running a package installer program in a different terminal, or as a detached process, or you killed an installer process so rudely that it didn't release the look.
You can see if any current process has the lock file open by
sudo lsof /var/lib/dpkg/lock-frontend

If a process has the file open, consider killing it.
If no process is shown, simply remove the file.
sudo rm /var/lib/dpkg/lock-frontend

If rm can't find the file, the process that had the file open ("holding the lock") has released the lock and exited. This is the temporally unavalible part of the messages.


text:
Q: Why does YUI transitions use fixed heights? So I'm trying to add animations/transitions using YUI and I'm wondering why on earth it uses fixed heights?
http://yuilibrary.com/yui/docs/transition/transition-basic.html
What's the deal with that?

A: The examples you mean? They do not have to, they are just poor examples. YUI Transition can use all possible values, it even support completely dynamic animations like so:
// Will create a slideDown effect on #thing

Y.one('#thing').transition({
    height: function(node) {
        return node.get('scrollHeight') + 'px';
    },
    duration: 0.1,
    easing: 'ease-out',
    on: {
        start: function() {
            var overflow = this.getStyle('overflow');
            if (overflow !== 'hidden') { // enable scrollHeight/Width
                this.setStyle('overflow', 'hidden');
                this._transitionOverflow = overflow;
            }
        },
        end: function() {
            if (this._transitionOverflow) { // revert overridden value
                this.setStyle('overflow', this._transitionOverflow);
                delete this._transitionOverflow;
            }
        }
    }
});

This example will expand an element that was previously 0px high to its expected height.


text:
Q: Getting N points of a Bezier Curve How can I calculate N points along a Bezier curve that has 2 control points? I have a similar way of getting N points along an Arc/Circle with the function below. Is there a similar way to do this with a Bezier curve? Unfortunately path.addArc() and path.addCurve() don't return enough points for my shapes to be smooth in Spritekit, so getting an abundance of points and using path.addLine() between them is a good enough workaround.
func getCirclePoints(centerPoint: CGPoint, radius: CGFloat, startAngle: CGFloat, endAngle: CGFloat, clockwise: Bool) -> [CGPoint] {
    let n : CGFloat = clockwise ? -1 : 1
    let points: [CGPoint] = stride(from: startAngle - n, through: endAngle + n, by: n).map {

        let degreesToRadians = CGFloat($0) * .pi / 180

        let x = centerPoint.x + radius * cos(degreesToRadians)
        let y = centerPoint.y + radius * sin(degreesToRadians)

        return CGPoint(x: x, y: y)
    }
    return points
}

A: I figured it out:
func getCurvePoints(p0: CGPoint, p1: CGPoint, p2: CGPoint, p3: CGPoint) -> [CGPoint] {
    let n : CGFloat = 0.005
    let points: [CGPoint] = stride(from: 0 - n, through: 1 + n, by: n).map {

        let x = pow(1 - CGFloat($0), 3) * p0.x + 3 * pow(1 - CGFloat($0), 2) * CGFloat($0) * p1.x + 3 * (1 - CGFloat($0)) * pow(CGFloat($0), 2) * p2.x + pow(CGFloat($0), 3) * p3.x
        let y = pow(1 - CGFloat($0), 3) * p0.y + 3 * pow(1 - CGFloat($0), 2) * CGFloat($0) * p1.y + 3 * (1 - CGFloat($0)) * pow(CGFloat($0), 2) * p2.y + pow(CGFloat($0), 3) * p3.y

        return CGPoint(x: x, y: y)
    }
    return points
}


text:
Q: CK editor CKFinder, Drag en drop image is undefined I have a problem when integrating CKFinder to CKeditor.
I change Base Dir and Base Url in something like
http://localhost:8080/Appli/userfiles/
C:\Files\Appli\WebContent\userfiles
and in JS
filebrowserBrowseUrl: './pages/js/libJS/ckfinder/ckfinder.html',
    filebrowserImageBrowseUrl: './pages/js/libJS/ckfinder/ckfinder.html?type=Images',
    filebrowserUploadUrl: './pages/js/libJS/ckfinder//core/connector/java/connector.php?command=QuickUpload&type=Files&currentFolder=/help/',
    filebrowserImageUploadUrl: './pages/js/libJS/ckfinder/core/connector/java/connector.php?command=QuickUpload&type=Images&currentFolder=/help/',

When I Dragged my image on CKEditor, the image appears a few second with (upload with success) but it disappeared after and I have a "undefined" with a little red cross.
Is There something with my baseURL and it didn't find "userfiles " ?
Thanks for your Help

A: Please see: https://docs-old.ckeditor.com/CKFinder_2.x/Developers_Guide/Java/CKEditor_Integration
You should not have java/connector.php unless you have changed it in web.xml where this virtual path is defined:
<servlet-mapping>
    <servlet-name>ConnectorServlet</servlet-name>
    <url-pattern>
        /ckfinder/core/connector/java/connector.java
    </url-pattern>
</servlet-mapping>

If you have default setup, it should be e.g.
filebrowserUploadUrl: './pages/js/libJS/ckfinder/core/connector/java/connector.java?command=QuickUpload&type=Files&currentFolder=/help/'

There is also a mistake in path (double slash) - filebrowserUploadUrl: './pages/js/libJS/ckfinder//core


text:
Q: Java JDK - possible lossy conversion from double to int So I have recently written the following code:
    import java.util.Scanner;

public class TrainTicket
{
      public static void main (String args[])
      {

         Scanner money = new Scanner(System.in);
         System.out.print("Please type in the type of ticket you would like to buy.\nA. Child B. Adult C. Elder.");
         String type = money.next();
         System.out.print("Now please type in the amount of tickets you would like to buy.");
         int much = money.nextInt();
         int price = 0;
         switch (type)
          {
            case "A":
            price = 10;
            break;
            case "B":
            price = 60;
            break;
            case "C":
            price = 35;
            break;
            default:
            price = 0;
            System.out.print("Not a option ;-;");
           }
          if (price!=0)
          {
            int total2 = price* much* 0.7;
            System.out.print("Do you have a coupon code? Enter Y or N");
            String YN = money.next();
            if (YN.equals("Y"))
            {
             System.out.print("Please enter your coupon code.");
             int coupon = money.nextInt();
             if(coupon==21)
             {
              System.out.println("Your total price is " + "$" + total2 + ".");
             }
             else
             {
              System.out.println("Invalid coupon code, your total price is " + "$" + price* much + ".");
             }
            }
            else
            {
            System.out.println("Your total price is " + "$" + price* much + "." );
            }
          }

       money.close();
      }
}

When I try and run it with cmd, it keeps displaying this:
TrainTicket.java:31: error: incompatible types: possible lossy conversion from double to int
            int total2 = price* much* 0.7;

Can someone help and explain the error that I have made?

A: You are trying to assign price* much* 0.7, which is a floating point value (a double), to an integer variable. A double is not an exact integer, so in general an int variable cannot hold a double value.
For instance, suppose the result of your calculation is 12.6. You can't hold 12.6 in an integer variable, but you could cast away the fraction and just store 12.
If you are not worried about the fraction you will lose, cast your number to an int like this:
int total2 = (int) (price* much* 0.7);

Or you could round it to the nearest integer.
int total2 = (int) Math.round(price*much*0.7);

A: When you convert double to int, the precision of the value is lost. For example, when you convert 4.8657 (double) to int, the int value will be 4. Primitive int does not store decimal numbers, so you will lose 0.8657.
In your case, 0.7 is a double value (floating point treated as double by default unless mentioned as float - 0.7f). When you calculate price*much*0.7, the answer is a double value and so the compiler wouldn't allow you to store it in a type integer since there could be a loss of precision. That's what is "possible lossy conversion", you may lose precision.
So what could you do about it? You need to tell the compiler that you really want to do it. You need to tell it that you know what you are doing. So explicitly convert double to int using the following code:
int total2= (int) price*much*0.7;
 /*(int) tells compiler that you are aware of what you are doing.*/
 //also called as type casting

In your case,since you are calculating the cost, I'll suggest you to declare variable total2 as the type double or float.
double total2=price*much*0.7;
 float total2=price*much*0.7;
 //will work


text:
Q: PDF report not showing in Internet Explorer In my project after saving the data into db it will show report (pdf ) in a new page.It working fine on all browsers expect
IE .it will show like below pic
Code
 private string CreateLE_ANEZ()
    {
        try
        {

            ReportDocument oRPT = new ReportDocument();
            oRPT.Load(System.Web.HttpContext.Current.Server.MapPath("Reports/LE-Einzel.rpt"));
            ReportDocument subreportArtikel = new ReportDocument();
            SubreportObject subreportObjectArtikel;
            subreportObjectArtikel = oRPT.ReportDefinition.ReportObjects["Subreport1"] as SubreportObject;
            subreportArtikel = subreportObjectArtikel.OpenSubreport("LE-Artikel-SubRepoert.rpt");
            CTemplate objTemp = new CTemplate();
            DataTable dtTemplate = objTemp.SelectLETemplate("ANEZ");
            oRPT.SetDataSource(dtTemplate);

            DataTable dtArtikelData = SelectLEArtikel();
            subreportArtikel.SetDataSource(dtArtikelData);
            #region set parameter values
            //AAddressen objCust = new AAddressen();
            //objCust=new CAddressen().SelectAddressen(AddressenID);
            CUsers objUser = new CUsers();
            objUser.UserID = UserID;
            AUsers objAUser = objUser.SelectUserProfile();
            CLand objLand = new CLand();
            objLand.ID = objAUser.Land;
            objLand.SelectLandById();
            objAUser.LandName = objLand.Lnd_Name;
            CUtilities objUtil=new CUtilities();
            string strDate = LEDate.Day.ToString() + "." + LEDate.Month.ToString() + "." + LEDate.Year.ToString();
            string strLands = SelectLELand();

            /* Requirement No ::  18895       ::: Commented By Jyotheena Jose      :1/30/2014 11:21:17 AM
               string strSender = objAUser.Ort + " : " + strDate + " , " + " " + objAUser.FirmaName +  " " + objAUser.PLZ +" " + objAUser.Street + " , " + objAUser.FirstName + " " + objAUser.LastName;*/
            string strSender = objAUser.Ort + " : " + strDate + " , " + objAUser.FirmaName + ", " + objAUser.Street + ", " + objAUser.PLZ + " " + objAUser.Ort + " , " + objAUser.FirstName + " " + objAUser.LastName + " , " + objAUser.Position;
            string strLEDate = LEDate.ToString("yyyyMMdd") + "-";
            string strCum = "";
            string strNoCum = "";
            if (IsCumulation == "T")
                strCum = "X";
            else
                strNoCum ="X";

            switch (LENumber.Trim().Length)
            {
                case 1: strLEDate += "00" + LENumber;
                    break;
                case 2: strLEDate += "0" + LENumber;
                    break;
                default: strLEDate += LENumber;
                    break;
            }
            ParameterDiscreteValue pDescValue;
            ParameterFieldDefinitions pFielddDefs;
            ParameterFieldDefinition pFieldLoc = null;
            ParameterValues pValues = new ParameterValues();
            pFielddDefs = oRPT.DataDefinition.ParameterFields;
            pDescValue = new ParameterDiscreteValue();
            CreateParameterFields(pDescValue, pFielddDefs, pFieldLoc, pValues, "pLandList", strLands);
            CreateParameterFields(pDescValue, pFielddDefs, pFieldLoc, pValues, "pSender", strSender);
            CreateParameterFields(pDescValue, pFielddDefs, pFieldLoc, pValues, "pLEDate", strLEDate);
            CreateParameterFields(pDescValue, pFielddDefs, pFieldLoc, pValues, "pBemerkungen", Bemerk);
            CreateParameterFields(pDescValue, pFielddDefs, pFieldLoc, pValues, "pCum", strCum);
            CreateParameterFields(pDescValue, pFielddDefs, pFieldLoc, pValues, "pNoCum", strNoCum);
            CreateParameterFields(pDescValue, pFielddDefs, pFieldLoc, pValues, "pCumtext", Cumulation);
            #endregion

            string strFileName = "Pdf/" + UserID.ToString().Trim() + "Einzel.pdf";

            if (!Directory.Exists(System.Web.HttpContext.Current.Server.MapPath("Pdf")))
                Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath("Pdf"));
            if (File.Exists(System.Web.HttpContext.Current.Server.MapPath(strFileName)))
                File.Delete(System.Web.HttpContext.Current.Server.MapPath(strFileName));
            oRPT.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, System.Web.HttpContext.Current.Server.MapPath(strFileName));
            return strFileName;
        }
        catch (Exception ex)
        {
            throw new Exception("CLE->CreateLE_ANEZ", ex);
        }
    }

After IN New page (ViewPdf1.aspx)
rotected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["rpt"] == null)
                return;
            else
            {
                string strValues = Session["rpt"].ToString();
                string[] strData = strValues.Split(',');
                //Session.Remove("rpt");
                //ViewState["rpt"] = strData[1].Trim();
                //ViewState["LENo"] = strData[0].Trim();
                //string strUrl = ViewState["rpt"].ToString();
                string strUrl = strData[1].Trim();
                dvPdfLoader.InnerHtml = "<object data='" + strUrl + "' type='application/pdf'  width='100%' height='468px'></object>";
                string strQuery = Request.QueryString["s"];
                if (strQuery != null && CUtilities.Decrypt(strQuery.Trim()) == "mailsent")
                {
                    lblMessage.Text = "E-Mail erfolgreich gesendet";
                }
            }
        }
    }

please help to solve this error..
Regards
Jithesh

A: HERE IS THE SOLUTION :)
Internet Explorer 10 & 11 are considered as the best possible versions of Microsoft's proprietary browser; Internet Explorer. With Windows 8 as well as Windows 7, you can use IE 10 and IE 11. Well in both these iterations, some users have reported facing a problem that, whenever they try to download and open PDF file, Internet Explorer will not open PDF files.
http://www.thewindowsclub.com/pdf-files-will-open-internet-explorer


text:
Q: SymPy `solve` fails to solve Matrix equation A*x = b when symbols are replaced by values with `subs` I have linear equation I want to solve, as Ax = b. I want to show step by step only in symbols and at the end insert numbers and show problem's solution in numbers. I have problems with inserting in numbers. If previously calculated values are whole numbers everything works fine. When I put in something with decimals it prints
[]

This is simplified code to illustrate my problem:
Force = 100 #If I try to put in value of lets say 100.23 the problem happens
x_t = 15
L = 20
A, x, b = sym.symbols('A, x, b')
A_x, A_y, B_y = sym.symbols('A_x, A_y, B_y')
b, F, xt, l = sym.symbols('b, F, xt, L')

A = sym.Matrix([[1, 0, 0],
            [0, 1, 0],
            [0, 0, 1]])
b = sym.Matrix([[0],
            [F],
            [F*xt/l]])
x = sym.Matrix([[A_x],
            [A_y + B_y],
            [B_y]])

linear_eq = sym.Eq(A * x, b)
solution = sym.solve(linear_eq, x) #This always works fine(only symbols)
solution = sym.solve(linear_eq.subs( {F: Force, xt: x_t, l: L }), x )
solution

A: Hmm, I'm not sure why solve doesn't work at all. You could use LUsolve, though. Which works for F: 100.23, too:
from sympy import *

A, x, b = symbols("A, x, b")
A_x, A_y, B_y = symbols("A_x, A_y, B_y")
b, F, x_t, L = symbols("b, F, x_t, L")

A = Matrix([
    [1, 0, 0],
    [0, 1, 0],
    [0, 0, 1]
])
x = Matrix([
    [A_x],
    [A_y + B_y],
    [B_y]
])
b = Matrix([
    [0],
    [F],
    [F * x_t / L]
])

solution = A.LUsolve(b.subs({
    F: 100.23,
    x_t: 15,
    L:20
}))
print(solution)

Which prints:
Matrix([[0], [100.230000000000], [75.1725000000000]])


text:
Q: Progress for LongPressureGesture on a Button I got a button with a LongPressureGesture, and i would like to have a small ProgressView on top of this button as visual feedback for the user that the longPressureGesture is recognized.
I'm stuck on how to detect the beginning of the longPressure and the duration of the longPressure to be able to set the setProgress() on my ProgressView.
EDIT: So i inspired myself from the answers, thank you. Here is what i made. Feel free to comment the following code, maybe there is a better solution.
private var lpProgress:Float = 0
private var startTouch: NSTimer!

@IBAction func pauseJogButtonTouchDown(sender: AnyObject) {
    self.startTouch = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "updateLPGestureProgressView", userInfo: nil, repeats: true)
}

func updateLPGestureProgressView() {
    self.lpProgress += 0.1
    self.lpGestureProgressView.setProgress(self.lpProgress, animated: true)
    if self.lpProgress >= 1 {
        self.startTouch.invalidate()
        self.pauseBarButton.hidden = true
        self.lpGestureProgressView.setProgress(0.0, animated: false)
        self.toolbarHomeMadeView.hidden = false
        self.switchToState(.Paused)
    }
}

@IBAction func pauseJogButtonTouchUpInside(sender: AnyObject) {
    self.lpProgress = 0
    self.startTouch.invalidate()
    self.lpGestureProgressView.setProgress(0.0, animated: false)
}

A: You do not need the LongPressureGesture in this case.
Use "Touch Down" IBAction of UIButton to start NSTimer, and "Touch Up Inside" to stop timer and check if the delay was right.
ProgressView you can fill by timer progress.

A: Set up an NSTimer on touchesBegan.
At the same time start your animation to animate the view.
When touchesEnded is triggered then stop the animation if the NSTimer has not triggered yet and cancel the timer.
When the timer finishes run your desired action.
Long Press isn't really designed for this sort of thing.


text:
Q: Handle huge array with php and mongo These are my current tools: PHP, Mongo, Mongo in memory.
We have a feature that could reach at its peak to 2 arrays of 20M emails.
Now we need to compare those 2 arrays and find the diffs between them.

*

*How would you suggest storing this list of emails in mongo?

*

*one document with a big array inside it (not valid, 16mb limit)

*or several documents that each has an email

*How would you suggest doing the comparison of the 2 lists?
If I do it in memory on php code, 1M emails in an array is approx 140mb
so 20M emails will be huge 2.8GB of memory
For the comments below:
These are lists of usernames, ie:

*

*['john', 'dan', 'sarah']

*['dan', 'samantha', 'donald']
I want to compare those lists and remove the duplicate, so I'll get:

*

*['john', 'sarah']

*['samantha', 'donald']
You can see Dan was removed, as he is on both lists.

A: Don't store and compare strings itself.

*

*Add a new column in your table, call it hash.

*This hash column must be able to keep at least uint32 number (unsigned integer, 32 bits).

*Use crc32 as a hash.

*Load/compare hashes instead of strings now.


text:
Q: How to code a double navbar with bootstrap? Could someone please help me with this, I'm trying to create the following:

With the below code:

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

 <input type="text" class="form-control" placeholder="¿Que Buscas?">

 <input type="text" class="form-control" placeholder="Ciudad">

 <button type="button" class="btn bg-danger text-white">Buscar</button>

I´ve ben trying to create this by using BootStrap´s classes.

A: Here is an example that you can use as a basis.
You can try to play with the borders of your 2 inputs. (border-left / border-right). You should also modify the border-radius of these two inputs.
With this, it will form a single input.
As for putting icons or buttons in the input, you can use the relative/absolute positions.
Now it's up to you to modify it (like modifying the shadow boxes, input focus, adding your other icons, ...) and to adapt it according to your needs.

<!DOCTYPE html>

    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/css/bootstrap.min.css"
      integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
      crossorigin="anonymous"
    />

        <input
          type="text"
          class="form-control buscando shadow-none focus-none"
          placeholder="¿Que Buscas?"
        />

        <input
          type="text"
          class="form-control ciudad shadow-none "
          placeholder="Ciudad"
        >

      </input>
      <button
      type="button"
      class="btn bg-danger text-white position-absolute"
      >
      Buscar
    </button>


text:
Q: Dejar activado o desactivado un boton al refrescar la página mi pregunta es si existe la manera de refrescar la página y dejar el estado de los botones como estan, por ejemplo si el botón esta desactivado y refresco la página que el botón se quede desactivado o si esta activado que el botón se quede activado.
Gracias.

A: Lo logre utilizando localstorage
        function inicio0(ida) {
            if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
            } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.open("GET","bd.php?idu="+idu+"&ida="+ida,true);
            xmlhttp.send();
            document.getElementById("btn0").disabled = true;
            document.getElementById("btn0.0").disabled = false;
            localStorage['btn0'] = 'true'
    }

El código al iniciar la página
        window.onload = function(){
                                          if(localStorage['btn0'] == 'true'){
                                                document.getElementById("btn0").disabled = true;
                                                if(localStorage['btn0.0'] == 'true'){
                                                        document.getElementById("btn0.0").disabled = true;
                                                }else {
                                                        document.getElementById("btn0.0").disabled = false;
                                                }
                                            }
                                    };

A: Creo que seteas y obtienes los datos de tu localStorage de manera incorrecta ademas que necesitas hacer tus if individualmente, hice un pequeño ejemplo de lo que necesitas, espero y te sirva:
<button id="btn0">
Test1
</button>
<button id="btn0.0">
Test2
</button>

<script>

localStorage.setItem('btn0', 'true');
localStorage.setItem('btn0.0', 'false');

  if(localStorage.getItem('btn0') == 'true'){
     document.getElementById("btn0").disabled = true;
  }else{
     document.getElementById("btn0").disabled = false;
  }
  if(localStorage.getItem('btn0.0') == 'true'){
     document.getElementById("btn0.0").disabled = true;
  }else{
     document.getElementById("btn0.0").disabled = false;
  }

</script>


text:
Q: How can I SELECT DISTINCT rows from two columns from the same table ignoring bidirectional similars? I have a table flight as follows:
arrive      | depart
-------------------
New York    | London
New York    | Paris
Washington  | Rome
London      | New York
Rome        | Washington
New York    | Washington
New York    | London
Rome        | New York
Washington  | Rome

And I would like to produce a distinct / unique output based on the distinct from depart/arrive and arrive/depart - but not those that are bidirectionally the same.  Therefore the outcome from above would be:
depart      | arrive
______________________
New York    | London
New York    | Paris
Washington  | Rome
New York    | Washington
Rome        | New York

Straightforward to get distinct basis depart/arrive, but can't get any JOIN, UNION etc. to ignore the bidirectional same (arrive/depart), but include bidirectional unique.
Pulling hair out, - need help.  Thanks

A: You can use a NOT EXISTS condition with a correlated subquery to remove duplicates.
However one thing to keep in mind is that, in order to get a consistent resultset, you need to define a rule to tell which of the two destinations is considered the depart, and which is the arrive. Since you did not provide a rule, I chose to have the value with lowest alphabetic order as depart.
Query:
SELECT
    LEAST(depart, arrive) depart,
    GREATEST(depart, arrive) arrive
FROM mytable t
WHERE NOT EXISTS (
    SELECT 1
    FROM mytable t1
    WHERE t1.arrive = t.depart AND t1.depart = t.arrive AND t1.depart > t.depart
)

Demo on DB Fiddle:
| depart   | arrive     |
| -------- | ---------- |
| New York | Paris      |
| London   | New York   |
| Rome     | Washington |
| New York | Washington |
| New York | Rome       |

One other solution would be to pick the first occurence of the duplicate in the table, using primary key id, which, as per the comments, is available in the table:
SELECT depart, arrive
FROM mytable t
WHERE NOT EXISTS (
    SELECT 1
    FROM mytable t1
    WHERE t1.arrive = t.depart AND t1.depart = t.arrive AND t1.id < t.id
)


text:
Q: Which command is needed to run a Java Application with Filepath argument I'm building a desktop app on Java (11) and compiled with Maven, but I need to send a Filepath as an argument to read it:
public class App {
public static void main(String[] args) {
    if (args.length == 0) {
        System.out.println("File name not specified.");
        System.exit(1);
    }
    System.out.println(args[0]);

    readFile(args[0]);
}
}

I don't know how to run the app sending that parameter or which command is needed in the Command Line


text:
Q: How to add a custom path to : " ls -d */ " Issue : The code works fine, it lists folders with "numerical names" in a reversed order, however I would have to be in the same directory. I would like to add a custom path to it so that I do not have to be in the same directory.
ls -d */ |  cut -d '/' -f 1 | sort -nr

I tried adding " /test/path " to the code above, but without success.
ls -d */ /test/path/ |  cut -d '/' -f 1 | sort -nr

Update : I do not know why "test2" is being printed at the bottom in this scenario. I am using SliTaz Linux 5.0 I can not figure out the shell version.
root@s1:/# mkdir /test
root@s1:/# mkdir /test/test2
root@s1:/# cd /test/test2/
root@s1:/test/test2# mkdir 1 2 3 10
root@s1:/test/test2# touch test.txt
root@s1:/test/test2# ls -d /test/test2/*/ | awk -F'/' '{print $(NF-1)}' | sort -nr
10
3
2
1
test2
root@s1:/test/test2#

Update 2 :
On my cloud server which uses "Alpine Linux" version "3" I believe, there does not seem to be a problem, the code works ok.
test:/# mkdir /test
test:/# mkdir /test/test2
test:/# cd /test/test2
test:/test/test2# mkdir 1 2 3 10
test:/test/test2# touch test.txt
test:/test/test2# ls -d /test/test2/*/ | awk -F'/' '{print $(NF-1)}' | sort -nr
10
3
2
1
test:/test/test2#

A: ls -d /test/path/*/ |  cut -d '/' -f 1 | sort -nr

Although cut won't work the way you intend to use it.
Instead use this:
ls -d /test/path/*/ | awk -F'/' '{print $(NF-1)}' | sort -nr

Also to avoid nullglob, set this before:
shopt -s nullglob

So that if no directories exist, it doesn't result into error.
I am not sure about the reason the above command doesn't work on SliTaz Linux 5.0, but as discussed, this can be done instead:
cd /test/path/ ; ls -d */ | awk -F'/' '{print $(NF-1)}' | sort -nr ; cd "$OLDPWD"

or
(cd /test/path/ ; ls -d */ | awk -F'/' '{print $(NF-1)}' | sort -nr)


text:
Q: Implementing SSO with .Net 4.0 webforms and Azure AD We are starting with Azure AD to implement SSO on a website developed with webforms and Office 365, so I was reading about it, and as far as I understand, we need to use some nuggets like these
PM> Install-Package Microsoft.Owin.Security.OpenIdConnect
PM> Install-Package Microsoft.Owin.Security.Cookies
PM> Install-Package Microsoft.Owin.Host.SystemWeb

Now, to install it, we need the 4.5 .NET framework on our project, but it was developed using 4.0 framework.
Does anyone know what's the best approach to connect a webform 4.0 web application to Azure AD? All the information I have found on Microsoft documentation is oriented to MVC and uses libraries like 4.5 OWINs
Thanks in advance

A: The Microsoft OWIN aka Katana require the .Net Framework 4.5 according to here:
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>

https://katanaproject.codeplex.com/SourceControl/latest#src/Microsoft.Owin/Microsoft.Owin.csproj
If you want to using the Katana in your project to integrate with Azure AD, you need to upgrade your project to .Net Framework 4.5.
Or you will need to implement the OpenId connect flow yourself in the web form app. You can refer the OpenId connect flow from link below about the detail:
Authorize access to web applications using OpenID Connect and Azure Active Directory


text:
Q: What is the difference between "asynchronousFetchRequest" and "create a private context"? 1.iOS8 provided asynchronousFetchRequest,and we can also create a 'private context' to fetch results, so what is the difference between asynchronousFetchRequest and 'create a private context'?
2.The type of NSFetchedResultsController's context must be MainQueueConcurrencyType?(block the UI?) Is there any solution to resolve this?

A: AsynchronousFetchRequest will create another context and perform the fetch on that context. Creating a private context yourself means that you can work on managedObjects on the background context without having to block the main thread while that work is being performed. If you have your own context though your going to have to transfer your managedObjects onto the main thread yourself though, while async fetch request is already doing that. FetchedResutlsControllers do not necessarily need a context that is MainQueueConcurrency, but do remember that if its PrivateQueueConcurrency, than the cache won't work and you will need to use performBlock: method in order to work with the objects. Your UI can get blocked while fetching objects for an FRC, but it shouldn't take a long time. IF you need speed from core data index your entities first. If you want to make sure you have data before a fetch, you can use an AsynchronousFetchRequest with a countForFetchRequest to just have a number returned and act accordingly.


text:
Q: Is browserHistory.push() an anti-pattern? So here's a case where I'm inclined to imperatively navigate someplace:
Page for a resource has button to delete resource. I want to navigate some other place only after resource is deleted, but if the delete fails I don't want to navigate. This requires the ability to say "make delete call, wait till it's done, check what happened, navigate accordingly"
This feels like a code smell to me. It doesn't jive with react-router's declarative approach. Am I wrong?
Is there a more idiomatic way to do this:
// this.props.resource from container
<Link onClick={_ => {
  deleteResource(this.props.resource).then(result => {
    if (!result) // don't navigate, dispatch an action
    else browserHistory.push("different/place/entirely") // <= totally imperative
}/>

A: Routing seems necessarily imperative, so I'm not sure you can work around that.
As to whether it's an anti-pattern--I can only opine on what's idiomatic in my own code base, but I use browserHistory.push wherever it's more convenient than Link (which is often).
That said:  I do think it's peculiar to use Link in concert w/ browserHistory.push. If there's no routing-related reason for doing so, you ought to use a generic component.
Lastly:  it is an anti-pattern to use arrow-functions in component JSX Props.


text:
Q: Unable to load project environment variable in Spring Boot Unit Test I have some variables defined in application-local.yml in my spring boot project and these variables are used in many of the services by using @Value annotation.
Now while trying to unit test these services, the service is unable to retrieve the value of the variable from the application-local.yml and instead is throwing NullPointer Exception.
What should I do?
application-local.yml :
variables:
    maxVal: 24

Service.java
@Value("${variables.maxVal:24}")
public Integer maxima;

FunctionA()
{
  return maxima+1;
}

Unit Test
@Test
testFunctionA()
{
  assert.assertEquals(25,FunctionA())
}

A: your properties file is not being loaded. the proper manner for test properties is to use a application-test.yaml, located under test/resources, it will be automatically loaded when you run your tests.

A: You can injecting the property in the context with Spring Boot in this simple way thanks to the properties attribute of @SpringBootTest :
@SpringBootTest(properties="property.value=dummyValue")
public class FooTest{

   @Autowired
   Foo foo;

   @Test
   public void doThat(){
       ...
   }
}

You could use as alternative @TestPropertySource but it adds an additional annotation :
@SpringBootTest
@TestPropertySource(properties="property.value=dummyValue")
public class FooTest{ ...}

With Spring (without Spring Boot), it should be a little more complicated but as I didn't use Spring without Spring Boot from a long time I don't prefer say a stupid thing.
As a side note : if you have many @Value fields to set, extracting them into a class annotated with @ConfigurationProperties is more relevant because we don't want a constructor with too many arguments.
Hope thats helped .