text:
Q: How to upload 50gb file through SFTP efficiently? I want to implement SFTP client using JSCH java library. I have below queries. Please suggest your ideas.

*

*How to upload very big files( around 50gb) to SFTP server in best way?

*While doing above operation, there is a high chance of getting error "session timeout". Is there any best way to solve it other than setting the time explicitly?

A: Transfer very large files at once is always not the best idea.
One option is to use a bigger buffer, if the upload/download is not used to max.
But my suggested option is: split up the file automatically or use a tempfile mechanic, which can handle interruptions at transfer (like e.g. jdownloader does)


text:
Q: Querying on Bigquery repeated fields Below is the schema of my BigQuery table. I am selecting the sentence_id, store and BU_model and inserting data into another table in BigQuery. The datatypes for the new table generated are integer, repeated and repeated respectively.
I want to flatten/unnest the repeated fields so that they are created as STRING fields in my second table. How could this be achieved using standard sql?
+- sentences: record (repeated)
|  |- sentence_id: integer
|  |- autodetected_language: string
|  |- processed_language: string
|  +- attributes: record
|  |  |- agent_rating: integer
|  |  |- store: string (repeated)
|  +- classifications: record
|  |  |- BU_Model: string (repeated)

The query that I am using to create the second table is as below. I would want to query on the BU_Model as a STRING column.
SELECT sentence_id ,a.attributes.store,a.classifications.BU_Model
FROM staging_table , unnest(sentences) a

Expected Output should look like:
Staging table:
41783851    regions     Apparel
            district    Footwear
12864656    regions
            district

Final Target Table:
41783851    regions     Apparel
41783851    regions     Footwear
41783851    district    Apparel
41783851    district    Footwear
12864656    regions
12864656    district

I tried the below query and it seems to work as expected, but this means that i would have to unnest every expected repeated field. My table in Bigquery has 50+ columns which are repeated. Is there a easier way around this ?
SELECT
sentence_id,
flattened_stores,
flattened_Model
FROM `staging`
left join unnest(sentences) a
left join unnest(a.attributes.store) as flattened_stores
left join unnest(a.classifications.BU_Model) as flattened_Model

A: Assuming you want still three columns in your output - with arrays being flattened into string
SELECT sentence_id ,
  ARRAY_TO_STRING(a.attributes.store, ',') store,
  ARRAY_TO_STRING(a.classifications.BU_Model, ',') BU_Model
FROM staging_table , unnest(sentences) a

UPDATE to address recent changes in question

In BigQuery Standard SQL - use of LEFT JOIN UNNEST() (as you did in your last query) is the most reasonable way to do what you want to get as a result
In BigQuery Legacy SQL - you can use FLATTEN syntax - but it has same drawback of needing to repeat same for all 50+ column
Very simplified example:
#legacySQL
SELECT sentence_id, store, BU_Model
FROM (FLATTEN([project:dataset.stage], BU_Model))

Conclusion: I would go with LEFT JOIN UNNEST() approach

redpajama_set_name: RedPajamaStackExchange


text:
Q: Uncountability of basis of $\mathbb R^{\mathbb N}$ Given vector space $V$ over $\mathbb R$ such that the elements of $V$ are infinite-tuples. How to show that any basis of it is uncountable?

A: Take any almost disjoint family $\mathcal A$ of infinite subsets of $\mathbb N$ with cardinality $2^{\aleph_0}$.
Construction of such set is given here.
I.e. for any two set $A,B\in\mathcal A$ the intersection $A\cap B$ is finite.
Notice that
$$\{\chi_A; A\in\mathcal A\}$$
is a subset of $\mathbb R^{\mathbb N}$ which has cardinality $2^{\aleph_0}$.
We will show that this set is linearly independent. This implies that the base must have cardinality at least $2^{\aleph_0}$. (Since every independent set is contained in a basis - this can be shown using Zorn lemma. You can find the proof in many places, for example these notes on applications of Zorn lemma by Keith Conrad.)
Suppose that, on the contrary,
$$\chi_A=\sum_{i\in F} c_i\chi_{A_i}$$
for some finite set $F$ and $A,A_i\in\mathcal A$ (where  $A_i\ne A$ for $i\in F$). The set $P=A\setminus \bigcup\limits_{i\in F}(A\cap A_i)$ is infinite.
For any $n\in P$ we have $\chi_A(n)=1$ and $\sum\limits_{i\in F} c_i\chi_{A_i}(n)=0$. So the above equality cannot hold.

You can find a proof about dimension of the space $\mathbb R^{\mathbb R}$ (together with some basic facts about Hamel bases) here: Does $\mathbb{R}^\mathbb{R}$ have a basis?
In fact, it can be shown that already smaller spaces must have dimension $2^{\aleph_0}$, see Cardinality of a Hamel basis of $\ell_1(\mathbb{R})$.

A: I like the following solution (a colleague of mine told me about it):
For any $a\in\mathbb R$ we have a sequence $\widehat a=(1,a,a^2,\dots,a^k,\dots)$.
The set $\{\widehat a; a\in\mathbb R\}$ is linearly independent. (To see this just notice that if you choose $n$ sequences from this set then the first $n$ coordinates of these sequences form Vandermonde matrix.)
Thus we have a linearly independent of cardinality $\mathfrak c$. Hence cardinality of any Hamel basis is at least $\mathfrak c$.
At the same time, the cardinality of the whole space is $|\mathbb R^{\mathbb N}|=\mathfrak c^{\aleph_0}=\mathfrak c$, so the basis cannot have more than $\mathfrak c$ elements. Thus the Hamel dimension of this space is $\mathfrak c$.


text:
Q: how to store gzipped files on server with .htaccess setting (apache 2)? i'm looking for a rule to set on my .htaccess for store a gzipped file on the server when it will gzipped from the server. If is it possible i can save the cpu from always gzip the same files and the server could simply send the gzipped file instead of gzipped it "on the fly".
This is my .htaccess configuration
    # BEGIN Compress text files
    <ifModule mod_deflate.c>
      <filesMatch "\.(css|js|x?html?|php)$">
        SetOutputFilter DEFLATE
      </filesMatch>
    </ifModule>
    # END Compress text files

    # BEGIN Expire headers
    <ifModule mod_expires.c>
      ExpiresActive On
      ExpiresDefault "access plus 1 seconds"
      ExpiresByType image/x-icon "access plus 2592000 seconds"
      ExpiresByType image/jpeg "access plus 2592000 seconds"
      ExpiresByType image/png "access plus 2592000 seconds"
      ExpiresByType image/gif "access plus 2592000 seconds"
      ExpiresByType application/x-shockwave-flash "access plus 2592000 seconds"
      ExpiresByType text/css "access plus 604800 seconds"
      ExpiresByType text/javascript "access plus 216000 seconds"
      ExpiresByType application/javascript "access plus 216000 seconds"
      ExpiresByType application/x-javascript "access plus 216000 seconds"
      ExpiresByType text/html "access plus 600 seconds"
      ExpiresByType application/xhtml+xml "access plus 600 seconds"
    </ifModule>
    # END Expire headers

    # BEGIN Cache-Control Headers
    <ifModule mod_headers.c>
      <filesMatch "\.(ico|jpe?g|png|gif|swf)$">
        Header set Cache-Control "max-age=2592000, public"
      </filesMatch>
      <filesMatch "\.(css)$">
        Header set Cache-Control "max-age=604800, public"
      </filesMatch>
      <filesMatch "\.(js)$">
        Header set Cache-Control "max-age=216000, private"
      </filesMatch>
      <filesMatch "\.(x?html?|php)$">
        Header set Cache-Control "max-age=600, private, must-revalidate"
      </filesMatch>
    </ifModule>
    # END Cache-Control Headers

    # BEGIN Turn ETags Off
    <ifModule mod_headers.c>
      Header unset ETag
    </ifModule>
    FileETag None
    # END Turn ETags Off

    # BEGIN Remove Last-Modified Header
    <ifModule mod_headers.c>
      Header unset Last-Modified
    </ifModule>
    # END Remove Last-Modified Header

thanks


text:
Q: Problems in Unsupervised Aspect Based Sentiment Analysis I'm working on unsupervised aspect based sentiment analysis. I tried using Vader for it, which gave me good result but the problem is if the topic is negative like 'food waste' then the sentiment is always coming as negative even though content is saying 'and i really hate food waste'.
Can someone help me in tackling this issue, or even suggest me a method better than Vader.
I've also tried using 'Flair' but its' results are not as promising as Vader.

A: Probably the rule-based model VADER uses is not a good approach in this case, in that phrase you have 3 words that will surely get a negative score (hate food waste), remember that VADER is optimized for succint social media data and it cannot get a very good grasp of the "context" of the phrases.
A similar approach to VADER is us in TextBlob, wich you can try withuot much work: https://textblob.readthedocs.io/en/dev/
Usually the supervised route gives better results, but you need a good pretrained model and good data.
Naive Bayes classifier in scikit-learn:
https://www.datacamp.com/community/tutorials/simplifying-sentiment-analysis-python
Random Forest approach, always using scikit-learn:
https://stackabuse.com/python-for-nlp-sentiment-analysis-with-scikit-learn/
Here is a recap on various approaches to sentiment analysis:
https://towardsdatascience.com/fine-grained-sentiment-analysis-in-python-part-1-2697bb111ed4


text:
Q: How to show more lines in wordpress homepage? On my Wordpress homepage, the post is showing only one line of description. How do I add new lines?

I want to show more lines. So how can I do it?

A: Add below shared code in your theme function.php file:-
/**
 * Filter the except length to 100 words.
 *
 * @param int $length Excerpt length.
 * @return int (Maybe) modified excerpt length.
 */
add_filter( 'excerpt_length', 'wpdocs_custom_excerpt_length', 999 );
function wpdocs_custom_excerpt_length( $length ) {
    return 100;
}


text:
Q: Set MySQL field according to substring comparison I`m working on a data extraction from MySQL server and in several situations I'm using onquery substitutions. In example if I have a null field, it will assign an empty string for some fields, like:
ifnull(`negotiation_type`, "") AS negotiation_type

Now my need is to make similar test, but using substrings. I have a url field, and based on it`s value I want to set another field value, called property_type.
All the URLs will have the substring house or apartment, like:
http://www.example.com/?pics=true/tree-house-over-the-tree
http://www.example.com/?pics=true/blue-apartment-under-the-tere

And I`m wondering if composing the LOCATE function with any other mySQL function I will be able to make the property_type value assignment on SELECT.
Anyone have an idea?
Thanks

A: This one would do it I presume:
SELECT IF(LOCATE('HOUSE', `url`) > 0, 'HOUSE',IF(
LOCATE('APPARTEMENT', `url`) > 0, 'APPARTEMENT', 'OTHER')) AS property_type


text:
Q: What are good design patterns for dynamic visualforce components for a data-driven input form? I am designing a custom input form that will be data-driven and will display things like input fields, input text components, custom inputs that I create, etc. The elements on the form will be largely data-driven so I could create it with dynamic vf binding like so:
<apex:repeat... var="inputobj">
  <apex:outputpanel rendered="{!inputobj.type == 'standardinputfield'}"
    <apex:inputField required="{!inputobj.isRequired}" value="{!inputobj.data[f.apiName]}"
  </apex:outputpanel}"
  <apex:outputpanel rendered="{!inputobj.type == 'something'}"
  ...
  </apex:outputpanel}"
  <apex:outputpanel rendered="{!inputobj.type == 'something else'}"
  ...
  </apex:outputpanel}"
  ...
</apex:repeat>

I've used this pattern in the past and it works reasonably well but the vf becomes quite unwieldy as you create more types (both from a development and performance perspective) and you can't really reuse and extend the vf like you can with abstract and virtual classes.
My idea is that the inputobjects will have a method which generates a dynamic vf component for itself and then just repeat over those components. Has anyone built something similar or run into any issues with this?
My main concern is ending up with an unholy mess of UI mixed in with business logic or running into performance issues with dynamic vf components.

A: I think the first things you should look to use are Dynamic Visualforce Components. The introduction of this feature was meant to address some of the challenges that you are facing. This allows you to simplify your Visualforce markup by moving the logic of the markup (view) rendering to your Apex Controller. Some will argue that this is bad because it mixes View responsibilities into your Controller, thus breaking the MVC design, but this can also be a really powerful feature if used appropriately.
There is a good example here of returning a outputPanel from the controller.
Aside from this, you can also look to create some of your own Visualforce Components to keep your markup pages a little cleaner.

A: In a solution I'm building, I adopted the following as pattern.
In the controller, I have a couple of publicly visible elements:

*

*A public Map<String,Object> returned from a method called getViewBag().

*a public method named getControlTree() that returns the dynamically generated control tree.
The page looks like this:
<apex:page controller="MyPageController">
  <apex:sectionHeader title="My Section Title" />
  <apex:pageMessages id="pageMessages" />
  <apex:form id="theForm">
    <apex:dynamicComponent id="dynComp" componentValue="{!ControlTree}" />
  </apex:form>
</apex:page>

In the getControlTree Method, I first check if my Map is null. If it is, I initialize it by adding field names and objects. These field names are read from another custom object. The values are chosen based on a "type" of the field, so I add a boolean for example if the field is a checkbox.
With the Map built, I then build the control tree. My getControlTree method returns a PageBlock component which is the container for the hierarchy of form controls.
The knack is configuring the right binding expression on the dynamically created forms. For example, I do this:
Component.Apex.InputText ctl = new Component.Apex.InputText();
ctl.label = field.label;
ctl.expressions.value = buildBindingExpression(field.name);

with the helper function:
private string buildBindingExpression(string fieldName) {
  String expr = '{!ViewBag[\'' + fieldName + '\']' + '}';
  return expr;
}

So the binding expression {!ViewBag['Surname']} refers to the object obtained by m_viewBag.get('Surname')
I encountered four main problems:
Firstly, SelectLists required special handling. The options part has to be bound to a List<SelectOption> and cannot be bound to List<String> or string[] as I expected. The value part of the SelectList must be bound to a String. If you choose to make the SelectList multiselect, the value might have to be a String[] or a List<String>. Haven't tried. Don't know.
Secondly, the list of possible controls seems limited to Checkbox, Radio, SelectList and Textbox and there doesn't seem to be a way of marking a control as mandatory (prove me wrong).
Thirdly, validation. If a textbox is numeric only, or an email address - or if a field is a datepicker, there doesn't seem to be a way of rendering the right control. Component.Apex.InputField will render the right control(s) but can only be bound to sObjects.
Fourthly, there doesn't seem to be a way of programmatically setting html5 pass-through attributes, so I can add an InputText and set the type to "email", for example.
For the above reasons, I'll probably soon re-write my dynamic page to do the control-tree generation on the client with heavy JavaScript support.
It just occurred to me I could create a custom object with a property for every type of possible property, and bind InputField instances to the appropriate property on instances of my custom object - but that would be desperate and possibly a bit dumb.

A: Another thing to watch out for is that input fields do not retain their field values upon your controller receiving an error. More information can be seen here. I actually had to go back with VisualForce because the client didn't want to re-enter information if an error occurred. So that is a major issue for me.


text:
Q: firestore vue.js: auth() is not a function I have a firebase config file like this:
import { firebase } from "@firebase/app";
import "@firebase/firestore";

const firebaseApp = firebase.initializeApp({
    apiKey: "myKey",
    authDomain: "myDomain",
    databaseURL: "myURL",
    projectId: "myProject",
    storageBucket: "myBucket",
    messagingSenderId: "999999999"
});

export const db = firebaseApp.firestore();
export const firebaseApp = firebaseApp;

I am trying to authenticate a user but keep getting firebaseApp.auth() is not a function.
let me = db.collection('staff').where('email', '==', this.current_user.email)
    .get()
    .then((querySnapshot) => {
        querySnapshot.forEach((doc) => {
           this.fbUser = doc.id;
           let email = doc.data().email;
           let pw = doc.data().key;

           firebaseApp.auth().onAuthStateChanged(user => {
              if (user) {
                 //console.log('Already authenticated.');
              } else {
                 firebaseApp.auth().signInWithEmailAndPassword(email, pw)
                    .then(liu => {
                        //console.log('Logged in', liu.uid);
                        let uid = liu.uid;
                        this.$localStorage.set('fbId',this.fbUser, 0);
                        this.$localStorage.set('fbAuthId', uid, 0);
                        me.update({
                           is_active: true
                        });
                  });
              } // end if
          });
      });

Don't I have to configure the app? There's no auth functionality in @firebase.
Any help is appreciated.

A: You should add the auth Firebase service in your initialization, as follows:
import { firebase } from "@firebase/app";
import "@firebase/firestore";
import "@firebase/auth";  // <- NEW

const firebaseApp = firebase.initializeApp({
    apiKey: "myKey",
    authDomain: "myDomain",
    databaseURL: "myURL",
    projectId: "myProject",
    storageBucket: "myBucket",
    messagingSenderId: "999999999"
});

export const db = firebaseApp.firestore();
export const auth = firebaseApp.auth();  // <- NEW
export const firebaseApp = firebaseApp;

Then, in your component, you do:
auth.onAuthStateChanged(user => {})

and
auth.signInWithEmailAndPassword(email, pw)


text:
Q: What are the best ways to get beta testers? I have several projects coming up soon for public release, both commercial and open source. The projects are all downloadable, not web apps. I've worked on them alone and would like to get feedback during a beta period, but I don't currently have a large audience (though the markets are large). What are the best ways to get participation in the betas? Are there any existing sites or communities that specialize in software testing that I can reach out to? At this point, I'm specifically looking for technical testers who aren't intimidated diving into the code and can help spot security bugs, logical errors, etc.
Edit: I'm looking for websites or communities similar to Invite Share. Invite Share itself would be perfect, but there doesn't seem to be any public information about how to submit a beta.
Bounty Explanation:
While Joel's article on running a beta is helpful, I wonder if there isn't an existing community available for beta testing of any sort, technical or user. As a self-taught and sole developer, I don't have a lot of technical contacts that would be appropriate approaching for testing. I did propose a Beta Testing site in Area 51 a few months ago, but it seems as if it either got buried, there wasn't a whole lot of interest, or it's a poor fit for StackExchange. If you know of existing testing communities, sites like InviteShare, or other ways to get testers, please share.

A:
What are the best ways to get participation in the betas?

Joel (on Software) has an excellent article on this: Top Twelve Tips for Running a Beta.

Are there any existing sites or communities that specialize in software testing that I can reach out to?

I don't think there will be much "We Test Your Code" sites so you will have to start a webpage yourself and advertise it to the right audience...

At this point, I'm specifically looking for technical testers who aren't intimidated diving into the code and can help spot security bugs, logical errors, etc.

This seems more like a job description that you need technical testers in your company and is less like beta testing, perhaps it can still be alpha testing... But those aren't always technical either.
Test-Driven Development helps you prevent bugs and errors, thinking about the security can help too...

A: Invite Share handles invites for 37 different services, that's why you can't submit a beta to it... I don't think there is any open beta testing service, I guess it's the best thing to send your beta to several software sites. Sites like FileHippo even allow users to show/hide betas and their updates...

A: While I still haven't come across quite as comprehensive as what I'm looking for, many of the websites in this article provide feedback for a design.


text:
Q: communication between 2 fragments framentA calls fragmentB via an mother activity. FragmentA is no longer in memory. FragmentB calls fragmentA(go back to previous screen). FragmentB has some data to share with FragmentA. But, how?
here is what I tried:
static variable - it worked, but a bad habit, I can not use it
viewModel - each fragment creates it's OWN instance of view model. Therefore the 2 instances of the viewModel will not work.
DB - not a good pattern. Therefore I cant use it.

A: I think what you need is to store the fragments in Fragment Manager, when you do that you are basically trying to maintain a back stack of your fragments:
FragmentManager fragmentManager = getSupportFragmentManager();
//or FragmentManager fragmentManager = getFragmentManager();

fragmentManager.beginTransaction()
                     .add(FragmentToBeAdded, "textRelatedtoFragment")
                     .addToBackStack(null)
                     .commit();

Adding to the backstack helps in saving the state of the fragment.

A: My suggestion would be:
For Fragment Navigation use: https://developer.android.com/guide/navigation/navigation-getting-started
It will greatly simplify your in-app navigation.
For passing parameters between Fragments/Activities:

*

*First solution is to use ViewModel with scoping of Activity using by activityViewModels(). Read More here: https://developer.android.com/jetpack/guide This will give you an indirect way of passing arguments.

*Use SafeArgs (part of Navigation component) to directly pass needed data.
More information can be found here: https://developer.android.com/guide/navigation/navigation-getting-started#ensure_type-safety_by_using_safe_args


text:
Q: use str.format() witch class in python I have a class with __getitem__() function which is subscribable like a dictionary. However, when I try to pass it to a str.format() i get a TypeError. How can I use a class in python with the format() function?
>>> class C(object):
      id=int()
      name=str()

      def __init__(self, id, name):
        self.id=id
        self.name=name

      def __getitem__(self, key):
        return getattr(self, key)

>>> d=dict(id=1, name='xyz')
>>> c=C(id=1, name='xyz')
>>>
>>> #Subscription works for both objects
>>> print(d['id'])
1
>>> print(c['id'])
1
>>>
>>> s='{id} {name}'
>>> #format() only works on dict()
>>> print(s.format(**d))
1 xyz
>>> print(s.format(**c))
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    print(s.format(**c))
TypeError: format() argument after ** must be a mapping, not C

A: As some of the comments mention you could inherit from dict, the reason it doesn't work is that:

If the syntax **expression appears in the function call, the expression must evaluate to a mapping, the contents of which are treated as additional keyword arguments. In the case of a keyword appearing in both expression and as an explicit keyword argument, a TypeError exception is raised.

For it to work you need to implement the Mapping ABC. Something along the lines of this:
from collections.abc import Mapping

class C(Mapping):

    id=int()
    name=str()

    def __init__(self, id, name):
        self.id = id
        self.name = name

    def __iter__(self):
        for x in self.__dict__.keys():
            yield x

    def __len__(self):
        return len(self.__dict__)

    def __getitem__(self, key):
        return self.__dict__[key]

This way you should just be able to use s = '{id}{name}'.format(**c)
 rather than s = '{id}{name}'.format(**c.__dict__)
You can also use MutableMapping from collections.abc module if you want to be able to change your class variables like in a dictionary. MutableMapping would also require the implementation of __setitem__ and __delitem__


text:
Q: type 'Null' can't be assigned to CustomClass type I had been working after a long time with flutter and this new null safety is just breaking my code.
I had created a data model class to store values as an object as follows:
class MyClass{
  int x;
  String y;
  MyClass({this.x, this.y});
  .. .. ..rest of the code
}

Now in a provider I am having a list of MyClass objects to store data from the db.
Over here I am using the firstWhere() to search for the required object by id.
MyClass getObj(int id){
   return list.firstWhere((obj) => obj.id == id, orElse: ()=>null);
}

But this keeps giving the error:

type 'Null' cant be assigned as it isn't a subtype of MyClass

I tried firstWhereOrNull and also other solutions but to no avail.

A: You are trying to return null in non-nullable function. Try make MyClass nullable by adding? After MyClass like that

MyClass? getObj(int id){ return list.firstWhere((obj) => obj.id == id, orElse: ()=>null); }

A: The error message you're getting is because the return type of the orElse function must be non-nullable (in the docs, the signature is E and not E?).
If returning null from getObj is expected and you're prepared to handle that case elsewhere in code that calls getObj, then change the return type of the method to MyClass? (instead of MyClass) and use firstWhereOrNull, as you mentioned:
MyClass? getObj(int id){
  return list.firstWhereOrNull((obj) => obj.x == id);
}


text:
Q: QML Loader strange behavior I'm having issues rendering using OpenGL with a QQuickItem.
The setup:
I've partitioned the app window into a status bar and a display area. The display area will be used to render output from various Qt plugins. I'm using the QML Loader object to dynamically load the objects from the plugins as needed.
The problem:
I've duplicated the opengl rendering with qml example. If I load it into the display area directly it works perfectly. If I load it into the display area using a Loader it displays nothing. I've logged debugging messages and it's definitely running. I've debugged the app using GDebugger and it appears to be sending OpenGL calls.
Does the loader object mess with the window context?
Any suggestions on how to get this to work?
Is source for the loader object available somewhere?

A: The problem was not that the custom control wasn't drawing. It was my misuse of QML.
The dynamic loader was adding the content to a 'column' control. The layout controls exhibit 'undefined behavior' if you use them incorrectly. Changing to manual layout using anchors corrected the issue.


text:
Q: How do I run uvicorn in a docker container that exposes the port? I am developing a fastapi inside a docker container in windows/ubuntu (code below). When I test the app outside the container by running python -m uvicorn app:app --reload in the terminal and then navigating to 127.0.0.1:8000/home everything works fine:
{
  Data: "Test"
}

However, when I docker-compose up I can neither run python -m uvicorn app:app --reload in the container (due to the port already being used), nor see anything returned in the browser. I have tried 127.0.0.1:8000/home, host.docker.internal:8000/home and localhost:8000/home and I always receive:
{
   detail: "Not Found"
}

What step am I missing?
Dockerfile:
FROM python:3.8-slim

EXPOSE 8000

ENV PYTHONDONTWRITEBYTECODE=1

ENV PYTHONUNBUFFERED=1

COPY requirements.txt .
RUN python -m pip install -r requirements.txt

WORKDIR /app
COPY . /app

RUN adduser -u nnnn --disabled-password --gecos "" appuser && chown -R appuser /app
USER appuser

CMD ["gunicorn", "--bind", "0.0.0.0:8000", "-k", "uvicorn.workers.UvicornWorker", "app:app"]

Docker-compose:
version: '3.9'

services:
  fastapitest:
    image: fastapitest
    build:
      context: .
      dockerfile: ./Dockerfile
    ports:
      - 8000:8000
    extra_hosts:
      - "host.docker.internal:host-gateway"

app.py:
from fastapi import FastAPI

app = FastAPI()

@app.get("/home") #must be one line above the function fro the route
def home():
    return {"Data": "Test"}

if __name__ == '__main__':
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000)

A: The issue here is that when you specify host="127.0.0.1" to uvicorn, that means you can only access that port from that same machine. Now, when you run outside docker, you are on the same machine, so everything works. But since a docker container is (at least to some degree) a different computer, you need to tell it to allow connections from outside the container as well. To do this, switch to host="0.0.0.0", and then you should be able to access your dockerized API on http://localhost:8000.


text:
Q: WordPress Date with ACF I am using Advanced Custom Fields using the Relationship field type and I am struggling to get the date of the post to come through.
https://www.advancedcustomfields.com/resources/relationship/
Here is my code:
<?php

$posts = get_field('blha');

if( $posts ): ?>

<?php foreach( $posts as $p ): // variable must NOT be called $post (IMPORTANT) ?>
    <li class="latest-stories-excerpt <?php echo (++$j % 2 == 0) ? 'evenpost' : 'oddpost'; ?>">

<?php if( get_post_field('topic_selector') ) echo get_post_field('topic_selector') . ','; ?>

            <?php echo get_the_date( $p->ID ); ?>

                <?php echo get_the_post_thumbnail( $p->ID, 'latest-two-stories' ); ?>

<a href="<?php echo get_permalink( $p->ID ); ?>" class="anImgNew">
                <?php echo get_the_title( $p->ID ); ?>

<?php echo get_the_excerpt( $p->ID ); ?>

<?php endforeach; ?>

I've also tried this:
<?php $pfx_date = get_the_date( $format, $post_id ); ?>

And I have tried this too:
<?php $date = get_the_date('jS F Y', $p->ID); ?>

But nothing. I am lost  at this point. I've ready all the ACF docs but nothing and have asked the ACF support forum and again nothing hence I am here to ask you!
Anyone have a idea?
Cheers


text:
Q: sed - insert lines when text found / not found I have issue with sed, i need to accomplish two things with a csv file

*

*in front of each line that does not start UNES I need to add tag "BF2;"

*at the start of the file (after UNES if present) I need to add a tag "UNH;"

Example (no UNES;)
50000024;IE15;041111;113901;verstuurd;Aangift;
50000024;IE15;041111;113901;verstuurd;Aangifte;
50000024;IE15;041111;113901;verstuurd;Aangifte;

Example (with UNES;)
UNES;
50000024;IE15;041111;113901;verstuurd;Aangift;
50000024;IE15;041111;113901;verstuurd;Aangifte;
50000024;IE15;041111;113901;verstuurd;Aangifte;

so far I have this:
sed -e 's/^\([^"UNES"]\)/BF2;\1/' | sed '/UNES/ a\UNH;'

THis works as long as a UNES; tag is present - I can't seem to figure out how to insert the UNH; when UNES is not present!
Any help much appreciated
Sample output:
UNES;
UNH;
BF2;50000024;IE15;041111;113901;verstuurd;Aangifte;
BF2;50000024;IE15;041111;113901;verstuurd;Aangifte;
BF2;50000024;IE15;041111;113901;verstuurd;Aangifte;

A: Here's how you could do it using awk:
awk 'NR==1 {if(f=/^UNES;/)print; print "UNH;"} !f{print "BF2;" $0} {f=0}' file

On the first line, if /^UNES;/ is matched, print it and set the flag f. Always print "UNH;". If the f flag has been set, don't do the next action, which works for the rest of the lines. Always reset f to 0 after the first line so all further lines have "BF2;" added to the start.
Testing it out:
$ cat file
UNES;
50000024;IE15;041111;113901;verstuurd;Aangift;
50000024;IE15;041111;113901;verstuurd;Aangifte;
50000024;IE15;041111;113901;verstuurd;Aangifte;
$ awk 'NR==1 {if(f=/^UNES;/)print; print "UNH;"} !f{print "BF2;" $0} {f=0}' file
UNES;
UNH;
BF2;50000024;IE15;041111;113901;verstuurd;Aangift;
BF2;50000024;IE15;041111;113901;verstuurd;Aangifte;
BF2;50000024;IE15;041111;113901;verstuurd;Aangifte;
$ cat file2
50000024;IE15;041111;113901;verstuurd;Aangift;
50000024;IE15;041111;113901;verstuurd;Aangifte;
50000024;IE15;041111;113901;verstuurd;Aangifte;
$ awk 'NR==1 {if(f=/^UNES;/)print; print "UNH;"} !f{print "BF2;" $0} {f=0}' file2
UNH;
BF2;50000024;IE15;041111;113901;verstuurd;Aangift;
BF2;50000024;IE15;041111;113901;verstuurd;Aangifte;
BF2;50000024;IE15;041111;113901;verstuurd;Aangifte;

A: You can use this sed command:
sed '/^UNES;$/{i\
UNH;
n};s/^/BF2;/;' file.txt

details:
/^UNES;$/i\
UNH; insert a new line when UNES; is the whole line.
n replaces the pattern space with the next line

A: Try this, its works for me
sed '/^UNES;$/{i\
UNH;
n};s/^[0-9]*/BF2;&/;'


text:
Q: Is there a way to represent the function unpack on Showable in GHC's Haskell? I have a type named Showable like this:
    {-# LANGUAGE ExistentialQuantification #-}
    {-# LANGUAGE ExplicitForAll #-}
    data Showable = forall a . Show a => Showable a

Then making a function that packs it is trivial. I just have to write:
    pack :: forall a . Show a => a -> Showable
    pack x = Showable x

However it seems impossible to create the inverse function that would unpack the data from Showable. If I try to just invert what I wrote for pack and write:
    unpack :: exists a . Show a => Showable -> a
    unpack (Showable x) = x

then I get an error from GHC.
I have looked into the docs on GHC Language extensions and there seems to be no support for the exists keyword. I have seen that it might be possible in some other Haskell compilers, but I would prefer to be able to do it in GHC as well.
Funnily enough, I can still pattern match on Showable and extract the data from inside it in that way. So I could get the value out of it that way, but if I wanted to make a pointfree function involving Showable, then I would need unpack.
So is there some way to implement unpack in GHC's Haskell, maybe using Type Families or some other arcane magic that are GHC extensions?

A: Your unpack, as you have typed, cannot be written. The reason is that the existential variable a "escapes" the scope of the pattern match and there is no facility to track that behavior. Quote the docs:

data Baz = forall a. Eq a => Baz1 a a
         | forall b. Show b => Baz2 b (b -> b)

When pattern matching, each pattern match introduces a new, distinct, type for each existential type variable. These types cannot be unified with any other type, nor can they escape from the scope of the pattern match. For example, these fragments are incorrect:
f1 (MkFoo a f) = a

What is this "a" in the result type? Clearly we don't mean this:
f1 :: forall a. Foo -> a   -- Wrong!

The original program is just plain wrong. Here's another sort of error
 f2 (Baz1 a b) (Baz1 p q) = a==q

It's ok to say a==b or p==q, but a==q is wrong because it equates the two distinct types arising from the two Baz1 constructors.

You can however rewrite the unpack type equivalently so that the existential does not escape:
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE RankNTypes                #-}

module Lib where

data Showable = forall a. Show a => Showable a

pack :: Show a => a -> Showable
pack = Showable

unpack :: Showable -> (forall a. Show a => a -> r) -> r
unpack (Showable a) a2r = a2r a


text:
Q: Excel: Sort cell base on specific text Let's say I have something like this.

I want to sort it to be something like;

is there a function to do this in excel? Like sorting the data base on the x?

A: You can do that, using a helper column. However, you seem to have two criteria in your question:

*

*Count the amount of x characters. This, you can achieve using a CountIF().

*Sort, according to the location of the x character (in case there is only one).

You can achieve the second, using the following system (imagine that, instead of x, there's the number 1):
=G1 * 2^4 + F1 * 2^3 + E1 * 2^2 + D1 * 2^1 + C1 * 2^0

This will create the following numbers for your cases:
8 : Some Text :  1
9 : Some Text :  2
1 : Some Text :  4
...

Combining both calculations gives you what you want.


text:
Q: AddClass to group without removing it from similar groups I've built a group of buttons that work like radio buttons. When you click on a button inside a given group the radio is selected and a class should be added to the button selected in that group.
The radios are working fine but my class isn't isolated to the button group - it's only adding the class to the button clicked in the selected group. I'm trying to keep the class on the button clicked inside that group.
What am I doing wrong?
$('.radio-group .radio-btn .btn').click(function () {
    $('.radio-group .radio-btn .btn').removeClass('btn-primary');
    $(this).addClass('btn-primary');
});

http://jsfiddle.net/vcx0f8xc/

A: Try the below code
$('.radio-group .radio-btn .btn').click(function () {
    $(this).closest('ul').find('.btn-primary').removeClass('btn-primary');
    $(this).addClass('btn-primary');
});

but just to remind you that the click over the '<p>' element changes the color but the radio button does not get checked.

A: try this
$('.radio-group .radio-btn .btn').click(function () {
  $(this).parent().parent().find('.btn').removeClass('btn-primary');
  $(this).addClass('btn-primary');

});

A: Just you need to use parent() to find the btn...use as
$('.radio-group .radio-btn .btn').click(function () {
  $(this).parent().parent().find('.btn').removeClass('btn-primary');
  $(this).addClass('btn-primary');
});

Demo
My internet is lagging ..I think some one posted the same beforehand


text:
Q: VPhantom does not work in overleaf I tried to use vphantom{...} and overleaf does not take breaqn package, so I still have the question:
I have the following formula, but I get an error with it that I can't fix. What is wrong here really?
 \begin{equation}
 \begin{split}
     \psi(x)=\sum_{j=1}^l\sum_{v=0}^{m_j-1}U_v(x,\mu)V_{m_j-1-v}(\psi,\mu)\left|_{\mu=\mu_j}\\
     +\int_{-\infty}^{\infty}\frac{\sqrt{\mu}}{\pi\alpha(\sqrt{\mu})\alpha(-\sqrt{\mu})}\left\{e^+(x,\sqrt{\mu})e^+(\psi,-\sqrt{\mu})\\+e^-(x,\sqrt{\mu})e^-(\psi,\sqrt{-\mu})\right\}d\mu
  \end{split}
 \end{equation}

The preamble is:
\documentclass{article}
\usepackage{hyperref}
\usepackage{amssymb}
\usepackage{MnSymbol}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}
\newcommand{\norm}[1]{\left\lVert#1\right\rVert}
\newcommand{\R}{\mathbb{R}}
\newcommand{\C}{\mathbb{C}}
\newcommand\Setst[3][big]{\csname #1l\endcsname\{ #2 :
  \begin{array}[t]{@{}l@{}}#3\csname #1r\endcsname \}\end{array}}
\usepackage{amssymb}
\usepackage{amsfonts}
\usepackage{mathtools}
\usepackage[mathscr]{euscript}
\usepackage{mathrsfs}
\usepackage{yfonts}
\usepackage{setspace}
    \doublespacing
\usepackage{imakeidx}
\makeindex[columns=1, title=Alphabetical Index]

\newcommand{\footremember}[2]{%
    \footnote{#2}
    \newcounter{#1}
    \setcounter{#1}{\value{footnote}}%
}
\newcommand{\footrecall}[1]{%
    \footnotemark[\value{#1}]%

and the comment by overleaf is:
 Extra }, or forgotten \right.
    Missing \right. inserted.
    Missing } inserted.
    Extra \right.
    Missing { inserted.
    Thanks

equations

A: Please always post complete documents. As noted in comments on your earlier questions, you cannot use \left and \right across cells of the alignment; use \Bigl and \Bigr instead.
Also, since you're using a split environment, do insert & alignment points (one per line). If you don't provide alignment points, all rows will be typeset flushright -- probably not what you intend.
This really is a duplicate but I'm answering as you haven't followed previous duplicate references.

\documentclass{article}
\usepackage{amsmath} % for "split" environment
\begin{document}
\begin{equation}
  \begin{split}
     \psi(x) &=\sum_{j=1}^l \sum_{v=0}^{m_j-1} U_v(x,\mu)
       V_{m_j-1-v}(\psi,\mu) \biggr|_{\mu=\mu_j}\\
     &\quad +\int_{-\infty}^{\infty}
       \frac{\sqrt{\mu}}{\pi\alpha(\sqrt{\mu})\alpha(-\sqrt{\mu})}
       \Bigl\{  e^+(x,\sqrt{\mu})e^+(\psi,-\sqrt{\mu})\\
     &\qquad +e^-(x,\sqrt{\mu})e^-(\psi, \sqrt{-\mu})
       \Bigr\} d\mu
  \end{split}
\end{equation}
\end{document}


text:
Q: Material UI Text Field, Current Cursor Position How can I get the current cursor (caret) position in a materialUI text field?
https://material-ui.com/components/text-fields/
Basically, I have a need to modify the string contents at a particular index (for example, insert a char X between char #3 and char #4).
I understand that using the onChange, onClick and onFocus events will flag that a position change may have taken taken place (ie click mouse, or, say move using left/right arrow buttons, or type something), but then if I have a reference to the text-field object, which method or property would then permit me to determine where the caret is exactly positioned (index value 0 .. n-1)?
In jQuery, I think this can be obtained via the selectionStart property, so how exactly is the best way for a MaterialUI textfield?
Many thanks.

A: You can use the inputRef prop to get a ref to the input DOM element. That ref can then be used to get the selectionStart property of the DOM element.
Working example:
import React from "react";
import ReactDOM from "react-dom";

import TextField from "@material-ui/core/TextField";

function App() {
  const inputRef = React.useRef();
  const [selectionStart, setSelectionStart] = React.useState();
  const updateSelectionStart = () =>
    setSelectionStart(inputRef.current.selectionStart);
  return (

      <TextField
        onSelect={updateSelectionStart}
        inputRef={inputRef}
        defaultValue="Initial Text"
      />

      selectionStart: {selectionStart}

  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);


text:
Q: Binaryreader in 2 threads and infinite loop c# I am writting client-server communicator.
Now I reached the point where I don't know what to do. So...
In my Client I have 2 threads.
In those 2 threads I am using this same BinaryReader- in one thread for example when adding new contact  and in second thread in infinite loop (waiting for new message from server).
When I am adding contact, my application is not working properly because BinaryReaders in separated threads are reading reply alternately.
I realized that I have to use mutex.
Here is my code of client.class:
Adding contact:
      bw.Write((int)Codes.AddContact);
        bw.Write(login);
        mutex.WaitOne();
        int ans = br.ReadInt32(); // waiting for 'ok'
        mutex.ReleaseMutex();

Second thread (infinite loop):
            while (logged)
                {
                    mutex.WaitOne();
                    var action = (Codes)br.ReadInt32(); //stucks here
                    dp.Handle(action, bw, br);// dispatcher
                    mutex.ReleaseMutex();

                }

And my problem now is that this line:
  var action = (Codes)br.ReadInt32();

is waiting infinitly for some message form the server, mutex is in waiting-state so when I am trying to add a new contact, my client freezes here:
  mutex.WaitOne();

Is there any way to interrupt this reading or maybe do you know better solution?
Thanks in advance.


text:
Q: Remove garbage characters in arabic I needed to remove all non Arabic characters from a string and eventually with the help of people from stack-overflow was able to come up with the following regex to get rid of all characters which are not Arabic.
preg_replace('/[^\x{0600}-\x{06FF}]/u','',$string);

The problem is the above removes white spaces too. And now I discovered I would need character from A-Z,a-z,0-9, !@#$%^&*() also. So how do I need to modify the regex?
Thanking you

A: assume you have this string:
$str = "Arabic Text نص عربي test 123 و,.m,............ ~~~ ٍ،]ٍْ}~ِ]ٍ}";

this will keep arabic chars with spaces only.
echo preg_replace('/[^أ-ي ]/ui', '', $str);

this will keep Arabic and English chars with Numbers Only
echo preg_replace('/[^أ-يA-Za-z0-9 ]/ui', '', $str);

this will answer your question latterly.
echo preg_replace('/[^أ-يA-Za-z !@#$%^&*()]/ui', '', $str);

A: Add the ones you want to keep to your character class:
preg_replace('/[^\x{0600}-\x{06FF}A-Za-z !@#$%^&*()]/u','', $string);

A: In a more detailed manner from Above example, Considering below is your string:
$string = '
This..
 is hello world ! هذا هو مرحبا العالم! !@#$%^&&**(*)<>?:";p[]"/.,\|`~1@#$%^&^&*(()908978867564564534423412313`1`` "Arabic Text نص عربي test 123 و,.m,............ ~~~ ٍ،]ٍْ}~ِ]ٍ}"; ';

Code:
echo preg_replace('/[^\x{0600}-\x{06FF}A-Za-z0-9 !@#$%^&*().]/u','', strip_tags($string));

Allows: English letters, Arabic letters, 0 to 9 and characters !@#$%^&*().
Removes: All html tags, and special characters other than above


text:
Q: OData JSON & ATOM Formats I have this question on OData based services. As a consumer of OData Service, can I assume that any OData compliant data service would expose its data in ATOM and JSON format.
Is it possible that there is a OData service that expose its feeds in ATOM but not in JSON format?
In my application as a consumer of OData (OData CLient) we are always fetching the data in JSON format. This would fail when the OData Service only supports ATOM.

A: The specification has changed again in OData Version 4.0:

An OData service MUST support at least one of [OData-JSON] or [OData-Atom], and MAY support additional formats for both request and response bodies.

A: The specification talks about both ATOM and JSON, but in reality not all services support both. I've seen a couple which only supports ATOM for now. So yes, it is possible to expose an OData services which only supports for example ATOM. Whether such service complies with the specification is kind of not interesting, since if you can't consume ATOM you won't be able to talk to such service regardless of the specification.

A: From the specification, I think the ATOM is default way for OData data feed. and it can be easy to convert to JSON with ?$format=json
may be you can try to use ?$format=atom

A: The V3 documentation is unambiguous:

*

*OData Services MUST support the ATOM encoding.

*OData services SHOULD support a JSON encoding.


text:
Q: Upsample pandas data right index inclusive I have the following data which I want to resample (upsample) into sometimes 30 minute intervals, sometimes 15 minute intervals, sometime 5 minute intervals
                 TIME              VALUE
0 2023-01-02 01:00:00              94.73
1 2023-01-02 02:00:00              95.30
2 2023-01-02 03:00:00              67.16

However, if I use pandas .resample() method, upsampling on the last index is not performed. Is there some way to achieve this?
What I have tried:
>>> df.set_index('TIME').resample('30T').ffill()
                   TIME              VALUE
0  2023-01-02 01:00:00              94.73
1  2023-01-02 01:30:00              94.73
2  2023-01-02 02:00:00              95.30
3  2023-01-02 02:30:00              95.30
4  2023-01-02 03:00:00              67.16

What I want:
                   TIME              VALUE
0  2023-01-02 01:00:00              94.73
1  2023-01-02 01:30:00              94.73
2  2023-01-02 02:00:00              95.30
3  2023-01-02 02:30:00              95.30
4  2023-01-02 03:00:00              67.16
5  2023-01-02 03:30:00              67.16

A: Simply do this:
import pandas as pd

data = {'TIME': ['2023-01-02 01:00:00', '2023-01-02 02:00:00', '2023-01-02 03:00:00'],
        'VALUE': [94.73, 95.30, 67.16]}
df = pd.DataFrame(data)

df.set_index('TIME', inplace=True)
df.index = pd.to_datetime(df.index)

df = df.resample('30T', closed='right', label='right').ffill()

last_index = df.index[-1]
if last_index + pd.Timedelta('30 min') not in df.index:
    last_row = pd.DataFrame({'VALUE': df.iloc[-1, 0]}, index=[last_index + pd.Timedelta('30 min')])
    df = pd.concat([df, last_row])

df = df.reset_index()

print(df)

which gives:
                index  VALUE
0 2023-01-02 01:00:00  94.73
1 2023-01-02 01:30:00  94.73
2 2023-01-02 02:00:00  95.30
3 2023-01-02 02:30:00  95.30
4 2023-01-02 03:00:00  67.16
5 2023-01-02 03:30:00  67.16


text:
Q: Passing database object in PHP functions Not sure if appropriate but here goes.
I have build a small system for online reservations of slots during a day.
Because I use a database and connect to it all the time to run some queries I created a simple class that creates the connection (using PDO) and running queries (preparing them, running them, if an error happens it manages and logs it, etc).
I also use AJAX a lot so basically, when a user wants to register, log in, get the schedule of the day, book a slot, cancel a booking and so one, I use AJAX to load a script that goes through the procedure for each action (I will call this the AJAX script) and in that script I include the relevant script that contains all the functions needed (I will call this the function script). The idea is that the AJAX script just gets the parameters, calls a list of functions which based on the results returns some kind of response. The function script contain all the code, that builds the queries, and gets the database data, makes any checks, creates new objects if needed etc.
The way I was doing it was that in the start of the AJAX script I create my database class instance and then just pass it through to the functions as needed (Mostly because I started with all the code in the AJAX script and then moved to creating the separate function in the second script and just leaving the minimum code needed to guide the action)...
So my question is, is it a good/better practise to remove the database class instance all together from the AJAX script and instead include the database class script in the function script and just instantiate inside each function? I am wondering about the idea of creating connections along with each function and then destroying them (most of the functions are small and usually have one query or two , there are some that have a lot in which i use transactions).
I have read about using a singleton as well but I am not sure how it would work in the web. My understanding is if there 2 users logged in the site and both try to fetch the schedule, then the script is called once for each user, making a diffrent connection - even if the parameters of the connection are the same ( I have a guest_user with select/insert/update privileges in my database). So even if I had a singleton, then I would still have two separate connection in the above scenario right? Hoever the difference is as I have it now I would have two connections, open for 1 sec but with change I ask about I would have 10 for each user let's say (10 functions called) for 100ms each time... Is this good or bad? Can it cause problems (if I extrapolate this to real world, with say 1000 users, usually 20-40 at the same time on the site)...
What about security, can these connections be used to steal the data that are exchanged (okay this is farfetched and not really an issue, the data are relatively harmless, other than phones but...)


text:
Q: Error in Foursquare API I'm currently working with the foursquare API. I downloaded the files from github right here https://github.com/jmathai/foursquare-async. But, when I put my credentials in like my clientId, my client secret, and my redirectUri, it doesn't quite work; it says that there's a redirect uri mismatch. The beginning of the code in the simpleTest.php file looks like this:
ob_start();
require_once 'EpiCurl.php';
require_once 'EpiFoursquare.php';
$clientId = 'CLIENT_ID';
$clientSecret = 'CLIENT_SECRET';
$code = 'CODE';
$accessToken = 'ACCESS_TOKEN';
$redirectUri = 'http://www.thered-line.com/foursquare/simpleTest.php';
$userId = '4855602';
$fsObj = new EpiFoursquare($clientId, $clientSecret, $accessToken);
$fsObjUnAuth = new EpiFoursquare($clientId, $clientSecret);

How to get my $code and $accessToken... ?

A: This library is for using Foursquare with oAuth. That means that you get your code and access token from part of the oAuth handshake. Foursquare provided you with the client information - the rest is done in the oauth handshake.
When you changed the URL and the user, but kept the code and access token from the original test, you ended up with a code and token that were invalid - you are using the tokens from a handshake that does not have the same data anymore. If you change the test back to how it was on Github, it should run.
Basically, all you need for this lib is the clientID and the Secret - the rest will be done with PHP function calls from the library.
More info


text:
Q: C# deploy, problems with folders I've finished my app and used the visual studio installer to create a package with all the files that aplication need.
But the problem is that, if the user install the program in ProgramFiles directory, it won't start because he needs admin Rigths (This because the program needs sqlServerCe).
How i can avoid this situation?
Another question, if the program has the sqlServer and sqlServerCe in prerequesites it needs the sqlServerCe.dll?
Thanks.

A: If I'm not mistaken, I believe it is because you need an application manifest. You can specify privilege information this way.
http://msdn.microsoft.com/en-us/library/bb756929.aspx

A: Problem solved.
I needes to ask for admin rigths in my application


text:
Q: Tracking black objects live streaming I'm trying to make a project that tracks the black objects on the ground with a harsh desert sunny environment and I tried to make some trials but it doesn't work. I tried converting the black pixels in the image to Red because the Red pixels is easy to track (higher intensity) but it doesn't result in what I want. I tried inverting the image (converting the black to white and white to black) but it doesn't give the desired result either. So any ideas?
Here is the code:
import cv2
import numpy as np
import os
from matplotlib import pyplot as plt
cap = cv2.VideoCapture(0)
while cap.isOpened():
    ret,frame = cap.read()
    warp = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    ORANGE_MIN = np.array([40, 40, 60], np.uint8)
    ORANGE_MAX = np.array([50, 70, 80], np.uint8)
    hsv_img = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    Conv_hsv_Gray = cv2.cvtColor(hsv_img, cv2.COLOR_BGR2GRAY)
    imf = np.float32(Conv_hsv_Gray) / 255.0  # float conversion/scale
    Desc = cv2.dct(imf)
    sub_to = Desc[0, 0]
    print sub_to
    result_frame = Desc - sub_to
    Fitr = cv2.blur(result_frame, (1, 1))
    Filter2 = cv2.GaussianBlur(Desc, (1, 1), 0)
    iddt1 = cv2.idct(Fitr)
    iddt2 = cv2.idct(Filter2)
    framethreshed = cv2.inRange(hsv_img, ORANGE_MIN, ORANGE_MAX)
    ret, mask = cv2.threshold(Conv_hsv_Gray, 100, 150, cv2.THRESH_BINARY)
    mask_inv = cv2.bitwise_not(warp)
    mask = cv2.erode(mask, None, iterations=2)
    mask = cv2.dilate(mask, None, iterations=2)
    res = cv2.bitwise_and(iddt1, iddt1, mask=mask)
    cv2.imwrite('output2.jpg', framethreshed)
    cv2.imshow("imgOriginal(1)", frame)  # show windows
    cv2.imshow("Masking res(3)", res)  # show windows
    cv2.imshow("mask_inv)", mask_inv)  # show windows
    if cv2.waitKey(60) & 0xFF == ord('q'):
           break
cap.release()


text:
Q: Modal NSWindow Notification after becoming visible again I am on objectiveC, OSX, not iOS. XCode 8.3
I have a preferences Window (custom NSWindow) that opens as a modal on my main window.
The preferences window itself contains a view with tabs. The tab height changes the windows size whenever one is clicked.
First Tab clicked:

Second Tab clicked:

Now if someone hides the application in the dock and activates it again, the preferences window becomes active with the height of tab 1, even if tab 2 is still active. So the content gets cut off.

What i need is some kind of notification that gets triggered on becoming active/visible again to trigger a resize of the window before it gets displayed.
I tried it with these notifications in my NSWindow subclass (with NSWindow delegate set).
- (void)windowDidResignMain:(NSNotification*)notification{
NSLog(@"windowDidResignMain");
}

- (void)windowDidResignKey:(NSNotification*)notification{
NSLog(@"windowDidResignKey");
}

- (BOOL)canBecomeKeyWindow{
    return YES;
}

- (BOOL)canBecomeMainWindow{
    return YES;
}

But none of them worked. Is it because it's a modal window?
Any help appreciated.

A: I found it. My mistake - my tabViewController triggered a resize on viewWillAppear with always the first tab. I changed that to the current selected tab and that was it.


text:
Q: ActiveModel::Serializer not returning valid JSON in rails console test I'm relatively new to Rails, and this is my first usage of ActiveModel:Serializer. I'm just trying to set up a simple serializer and test it in the rails console before continuing. It seems to be using the serializer, but not returning valid JSON format. From the instructions I'm working off of (I'm a student), it seems I should be receiving JSON. I've been researching for the past few hours, but everything seems unrelated or goes over my head.
My User model:
class User < ActiveRecord::Base
    # User has attributes: first_name, last_name, email, password
    has_many :lists

    def full_name
        first_name + " " + last_name
    end
end

My UserSerializer:
class UserSerializer < ActiveModel::Serializer
    attributes :id, :full_name, :email

    def full_name
        object.full_name
    end
end

Commands in the Rails console:
>> User.create(first_name: "Jane", last_name: "Doe", email: "test@fake.com")
>> UserSerializer.new(User.first).as_json

Console returns:
=> {"user"=>{:id=>1, :full_name=>"Jane Doe", :email=>"test@fake.com"}}

A: as_json constructs a Ruby Hash that can subsequently be "serialized" (converted to a string) by a serialization library.
Try calling to_json instead. This method will return a string that can be parsed.
>> User.create(first_name: "Jane", last_name: "Doe", email: "test@fake.com")
>> UserSerializer.new(User.first).to_json

=> "{\"user\":{\"id\":1,\"full_name\":\"Jane Doe\",\"email\":\"test@fake.com\"}}"

Use JSON.parse to deserialize the string back to a hash:
>> JSON.parse({"user"=>{:id=>1, :full_name=>"Jane Doe", :email=>"test@fake.com"}}.to_json)
=> {"user"=>{"id"=>1, "full_name"=>"Jane Doe", "email"=>"test@fake.com"}}


text:
Q: pointer non-type template parameter I don't really understand why the code below does not compile:
template<const char*>
struct Foo{};

constexpr const char s1[] = "test1";
constexpr const char* const s2 = "test2";

int main()
{
    Foo<s1> foo1; // ok
    // Foo<s2> foo2; // doesn't compile
}

Uncommenting the last line in main() makes g++ and clang++ emit the errors

error: 's2' is not a valid template argument because 's2' is a
variable, not the address of a variable

and

error: non-type template argument for template parameter of
      pointer type 'const char *' must have its address taken

respectively.
My questions are:

*

*Why is s1 instantiation OK and s2 not?

*Is there any sane situation where such pointer non-type template parameter is of any use?

A: In a comment above, vsoftco adds:

seems extremely weird, afaik string literals are not temporaries but are stored for the whole duration of the program, so their address is for sure a compile time constant (or at least that's what I believe)

That's true. However, the standard doesn't specify whether string literals have unique addresses.
Some linkers merge or deduplicate string literals. I have worked on systems where "ello" == "hello"+1 actually evaluates to true. Other linkers are so dumb that "hello" in foo.cc has a different address from "hello" in bar.cc. Heck, some tiny C compilers are so dumb that "hello" can have two different addresses within the same translation unit!
For such a dumb linker (or compiler), should Foo<"hello"> cause one instantiation or two? That is...
const char *sa = "hello world";
const char *sb = "hello world";
assert(sa != sb);  // this assertion is permitted to succeed

template<char*> struct F {};
F<"hello world"> fa;
F<"hello world"> fb;
assert(!is_same<decltype(fa), decltype(fb)>::value);
    // should we permit this assertion to succeed also?

The Committee admirably refused to open that can of worms, by simply prohibiting the construct.

Now, it's conceivable (to me, at the moment) that sometime in the future the Committee could mandate that all string literals be deduplicated by the same mechanism that implementations currently use for inline and template functions. That is, we can imagine a source-level transformation that turns
const char *sc = "yoo hoo";

into
inline auto& __stringlit_yoo_x20hoo() {
    static const char x[] = "yoo hoo";
    return x;
}
const char *sc = __stringlit_yoo_x20hoo();

Then there would be only a single instance of __stringlit_yoo_x20hoo (and only a single instance of that function's static array x) anywhere in the program, so the meaning of F<"yoo hoo"> would be unambiguous. The implementation would have to name-mangle the thing unambiguously as well, but that's a simple problem once you've already committed to name-mangling things like F<1+1> and F<FruitType,ORANGE> (which C++ compilers have been doing forever).
...But then you would still have problems with those extremely smart linkers (like the one I worked on) that allow
assert("hello" == "hello\0world");  // this assertion is permitted to succeed

assert(!is_same_v< F<"hello">, F<"hello\0world"> >);
    // should we permit this assertion to succeed also?
    // Surely this way lies madness.

A: For 1.:
From [temp.arg.nontype]

1 A template-argument for a non-type template-parameter shall be a converted constant expression (5.20) of the type of the template-parameter. For a non-type template-parameter of reference or pointer type, the value of the constant expression shall not refer to (or for a pointer type, shall not be the address of):
[...]
(1.3) — a string literal (2.13.5),

s2 holds the address of a string literal, and so cannot be used as the parameter here. s1 on the other hand is an array of char that has been initialized with a string literal, but the value of s1 (when converted to const char*) doesn't point to the string literal used in the initialization.
For 2.:
Function pointers perhaps? Still I can't say I've ever used a pointer as a non-type parameter.

A: There's a recent change in the relevant standard text, but the code is acceptable in neither version of the standard.
N4140 [temp.arg.nontype]/p1:

1 A template-argument for a non-type, non-template
  template-parameter shall be one of:

*

*for a non-type template-parameter of integral or enumeration type, a converted constant expression (5.19) of the type of the
  template-parameter; or

*the name of a non-type template-parameter; or

*a constant expression (5.19) that designates the address of a complete object with static storage duration and external or internal
  linkage or a function with external or internal linkage, including
  function templates and function template-ids but excluding
  non-static class members, expressed (ignoring parentheses) as & id-expression,
  where the id-expression is the name of an object or
  function, except that the & may be omitted if the name refers to a
  function or array and shall be omitted if the corresponding
  template-parameter is a reference; or

*a constant expression that evaluates to a null pointer value (4.10); or

*a constant expression that evaluates to a null member pointer value (4.11); or

*a pointer to member expressed as described in 5.3.1; or

*a constant expression of type std::nullptr_t.

N4296 [temp.arg.nontype]/p1:

A template-argument for a non-type template-parameter shall be a
  converted constant expression (5.20) of the type of the
  template-parameter. For a non-type template-parameter of reference or pointer type, the value of the constant expression shall not refer
  to (or for a pointer type, shall not be the address of):

*

*a subobject (1.8),

*a temporary object (12.2),

*a string literal (2.13.5),

*the result of a typeid expression (5.2.8), or

*a predefined __func__ variable (8.4.1).

The N4140 version is the one currently implemented by compilers. The N4296 version is somewhat more relaxed, but in neither case is the address of a string literal an acceptable template argument.
Presumably part of the reason for this is that template arguments must be mangled, and mangling a string literal in a sane way that would work across multiple translation units would be very difficult, if not impossible.


text:
Q: About min and max functions working with lists I'm trying to print min() and max() values from a list generated from list()
x = [list(range(1,11))]
print(min(x))
print(max(x))

That returns the raw list twice: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
But when i write
x = [1,2,3,4,5,6,7,8,9,10]
print(min(x))
print(max(x))

It returns the actual min and max values: 1 and 10
What am i missing?

A: x = [list(range(1,11))]

is making a list of lists; the list constructor converts the range to a list, and the square brackets then declare another list that contains that list. It's like doing:
x = [[1,2,3,4,5,6,7,8,9,10]]  # Note two brackets on each side

Obviously, the max and min of a list with only one element (the inner list) will be that single element. It's the everything-est of elements in that list. If you want it equivalent to:
x = [1,2,3,4,5,6,7,8,9,10]

just do:
x = list(range(1,11))  # No brackets needed; the list constructor makes a single unnested list

or if you really like the bracket syntax, you can use generalized unpacking like so:
x = [*range(1,11)]  # * unpacks the range as elements of the list literal

A: Change x like this;
x = list(range(1,11))

A: Your first case is a list with only one element: a sublist with the numbers 1-10
 x = [list(range(1,11))]

Thus the min and max can only be the one element...

A: It happens because in your first statement, you're creating a list inside another list. Modify the first statement to x = list(range(1,11)), by using the keyword list you're already telling your code that variable should be a list once, so no need for the brackets.


text:
Q: What is the time complexity of pandas' read_csv and display functions? I'm writing a python code and using pandas' read_csv and display functions, the code must have O(n) time complexity, when using these two functions, assuming the the rest of the code doesn't exceed this complexity, and with the fact that these two functions are not in any loop, is their complexity more than O(n) ?
Thank you

A: They are both O(n), where n is the length of the input.


text:
Q: Neo4J create has different results from .net client to webclient I have a method for "Likes" in my contrived social app.  It looks like this: (split it up for looking at the query text before I send it off to be executed (was using executewihoutresults)
var client = new GraphClient(new Uri("http://localhost:7474/db/data"));

client.Connect();

var q = client.Cypher.Start(new {n = string.Format("node({0})", nodeId)})
      .Match("(u:User)")
      .Where((User u) => u.ProviderUserKey == id)
      .Create("(n)-[:Liked_By]->(u)");
var res = q.Return(u => u.As<UserInfo>()).Results;

This produces something like this in cypher:
START n=node(31)
MATCH (u:User)
WHERE (u.ProviderUserKey = 9)
CREATE (n)-[:Liked_By]->(u)

When I execute it from the web console, it gives me the expected behavior of creating a relationship between a node (n) and a user node (u).  However when I execute it from .net, it creates a new node for user, and a new relationship for whatever node I started at.
I'm relatively new, so I'm hoping this is blindingly obvious!  How can I write this query so that it will create only a relationship between the node (which can be of any time) to the user node?
Full project available at https://github.com/fauxtrot/angular-ts-proto

A: What version of the .NET client are you using?
Given that your Cypher above is making use of labels, it looks like you're using a fairly recent version of Cypher/Neo4j, e.g. Cypher 2 and Neo4j 2.x.
If you're using Cypher 2 (and the .NET client supports it), see what happens when you update the query to something like this:
MATCH (u:User {ProviderUserKey: 9}), (n {id: 31})
CREATE (n)-[:Liked_By]->(u)

...and translate that to what the .NET client uses (I've not done much with the .NET Neo4j client at this point).
To be honest, if you're looking to only generate that relationship once, consider using MERGE instead of CREATE (again, if you're using Cypher 2).
To me, it sounds like the .NET statement isn't generating Cypher where the graph recognizes the User node, and so it's being created (hope that doesn't sound too obvious).
Let us know how it goes.

A: So this was a lesson learned on what the Merge keyword actually does.  In a previous query, I was Merging what I thought were two queries to get the likes for an item, after querying for the item.  The Merge statement was creating a new user node per like with a like relationship.
I did rewrite the query that I spoke of above and have something that looks like this:
client.Cypher
  .Start(new { n = string.Format("node({0})", nodeId) })
  .Match("(u:User {ProviderUserKey : {id}})")
  .WithParam("id", id)
  .Create("(n)-[:Liked_By]->(u)").ExecuteWithoutResults();

Which has the desired effect of only creating a relationship.  Thank you to @BtySgtMajor for getting my on the right track to figure this out (by mentioning the relationship.
For those playing along at home here was the offending query:
  var result = client.Cypher.Start(new { s = string.Format("node({0})", id) })
               .Match("(u:User)<-[mb:Created_By]-(c:Comment)-[o:On_Item]->(s:Session)")
               .Merge("(c)-[lb:Liked_By]->(lbu:User)")  //bad line here
               .Return((u, mb, c, s, o, lbu) =>
                     new { Comment = c.As<Comment>(), MadeByUser = u.Node<UserInfo>(),                  CommentNodeId = c.Id(), LikedByUsers = lbu.CollectAs<UserInfo>() })
                           .Results.Select(x =>
                           {
                               x.Comment.MadeBy = x.MadeByUser.Data;
                               x.Comment.MadeBy.NodeId = (int)x.MadeByUser.Reference.Id;
                               x.Comment.MadeBy.ProviderUserKey = x.MadeByUser.Reference.Id;
                               x.Comment.Id = (int)x.CommentNodeId;
                               x.Comment.LikedBy = x.LikedByUsers.Select(ui => new UserInfo { Username = ui.Data.Username, ProviderUserKey = ui.Reference.Id, NodeId = (int)ui.Reference.Id }).ToList();
                               return x.Comment;
                           });

I changed the Merge to an OptionalMatch and it was no longer creating the errant user nodes!
However, I feel this is not a clean implementation, and that there is a better way to write this query.  I'll raise it in another question.


text:
Q: What i need to add to automaticaly update textBox2 with a LineCounter for the textBox1 input? My goal is to get the line/rows counter of the textBox1 input into textBox2 and display/update it in real time.
So far it work's only if I click and type something in textBox2.
private void InitializeComponent()
    {
        this.textBox1 = new System.Windows.Forms.TextBox();
        this.textBox2 = new System.Windows.Forms.TextBox();
        this.SuspendLayout();
        //
        // textBox1
        //
        this.textBox1.Location = new System.Drawing.Point(288, 47);
        this.textBox1.Multiline = true;
        this.textBox1.Name = "textBox1";
        this.textBox1.Size = new System.Drawing.Size(301, 193);
        this.textBox1.TabIndex = 0;
        this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged);
        //
        // textBox2
        //
        this.textBox2.Location = new System.Drawing.Point(544, 265);
        this.textBox2.Name = "textBox2";
        this.textBox2.Size = new System.Drawing.Size(45, 20);
        this.textBox2.TabIndex = 1;
        this.textBox2.TextChanged += new System.EventHandler(this.textBox2_TextChanged);

And here is the Form()
private void textBox1_TextChanged(object sender, EventArgs e)
    {

    }

private void textBox2_TextChanged(object sender, EventArgs e)
    {
        string strtext = textBox1.Text;
        var textArr = strtext.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
        textBox2.Text = textArr.Length.ToString();
    }

A: This code:
string strtext = textBox1.Text;
var textArr = strtext.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
textBox2.Text = textArr.Length.ToString();

Should all be in the textBox1_TextChanged function and not in the textBox2_TextChanged function, because you want to execute that code when the text in textBox1 changes.

A: You might not need such a complex code. The textbox has a Lines property that returns an array of the lines:
lineCountLabel.Text = editorTextBox.Lines.Count.ToString();

but I recall that it performs the same as you do there; splits the content to an array, which is an incredibly expensive operation to perform every time the user presses a key especially if the textbox is long. The numbers of string allocations your program will perform, constantly splitting a string into an array and throwing it away, just to get a count, is incredible waste of resources
Instead I recommend you just count the newlines:
lineCountLabel.Text = editorTextBox.Text.Count(c => c == '\n').ToString();

And if your textbox has a lot of text only perform this when they stop typing: out a timer on the form with an interval of 1 second, disable and enable the timer in the TextChanged (it resets the timeout) and put the count code in the timer tick event. Also stop the timer in the tick event

ps: noticed you have a logic to remove empty entries which, if intended, I suppose means you're only counting sentences rather than lines. Consider, if that's what you want, something like:
int c = 0; int p = Environment.NewLine.Length; int s = lineCountLabel.Text; int n = Environment.NewLine.Last();

for(int x = p; x<s.Length-1; x++)
  if(s[x] == n && s[x-p] != n)
    c++;

lineCountLabel.Text = c.ToString();

This could be done with LINQ, but it's a bit messy


text:
Q: Button onclick event in VB I'm trying to build a cell within a table . The cell is going to be a button which should open the hyperlink(An email address) .How do i write the onclick event
Below is the code in VB for the cell that i'm building
 newCell = New TableCell
                newCell.ID = "celRptSelect" & rptRow & "F"
                newCell.Style("width") = rowRptSelectHeadF.Style("width")
                newCell.CssClass = "TableButton"
                newCell.Text = "SME"
                newCell.Attributes.Add("onclick", "rpt.SmeEmail")
                newCell.Attributes.Add("runat", "server")
                newRow.Cells.Add(newCell)

rpt.SmeEmail is the data that i'm getting from database
Thanks in advance

A: You can use this code
newCell.Attributes.Add( "onclick", "CellAction( me )" );

Add your script
<script type="text/vbscript">
Sub CellAction( tdControl )
  MsgBox tdControl.id
End Sub
</script>


text:
Q: Apex Bug (?) Null Field Values of Cloned Instances Don't Persist? I want to take the state of a source record, clone it, and apply the clone to a target record. But I'm encountering an issue in which a null field on the clone does not nullify the field on the target.
Account account1 = [select id, NumberofLocations__c from Account where NumberofLocations__c != null limit 1];
Account account2 = [select id, NumberofLocations__c from Account where NumberofLocations__c = null limit 1];

// Clone account2 and use it to alter state of account1.
Account template = account2.clone(false, true, false, false);
template.Id = account1.Id;

update template;

In the example above,

*

*two accounts are queried: the target, account1, has a defined value for NumberOfLocations__c, while the source,account2, has a null value in the same field.

*account2 is cloned, template and its Id set to account1's.

*template is updated.

Expected Result
account1's NumberOfLocations__c value to be nullified.
Actual Result
account1's NumberOfLocations__c value remains unchanged.
How do I resolve this?

A: Although I cannot find documentation to support it, from what I have found it appears this is not a bug but by design. What appears to be happening is Salesforce is removing the field all together since it has no value. You can see this in the logs if you debug all 3 variables by adding system debugs to your code:
system.debug('Acct1: ' + account1);
system.debug('Acct2: ' + account2);
system.debug('Template: ' + template);

If you explicitly set the field to null then redo the system debugs you will see the field and it's null value printed out.
Similar issue found here.


text:
Q: Breakable side by side tcolorbox My initial goal was to have a layout structure, where there comes blindtext, then tow textboxes side by side, then again blindetext and so on. I tried to put two minipages side by side, both with 0.5\textwidth, but unfortunately this does not do the task , since the minipages are not breakable. Now I encountered the tcolorboxpackage. It has an extra feature called side-by-side tcolorboxes, but those are never breakable. My current approach was to put two tcolorboxes side by side with the tcbraster environment. This works well until I assign the breakable property to both of the tcolorboxes.
My code
\section{A section}

\begin{tcbraster}[raster columns=2,raster equal height, nobeforeafter, boxrule=0pt,width=0.45\textwidth, colback=white]
\begin{tcolorbox}[breakable]
erste Spalte
\end{tcolorbox}
\begin{tcolorbox}
zweite Spalte
\end{tcolorbox}
\end{tcbraster}

produces  this

while
\section{A section}

\begin{tcbraster}[raster columns=2,raster equal height, nobeforeafter, boxrule=0pt,width=0.45\textwidth, colback=white]
\begin{tcolorbox}[breakable]
erste Spalte
\end{tcolorbox}
\begin{tcolorbox}[breakable]
zweite Spalte
\end{tcolorbox}
\end{tcbraster}

produces this

But I want that both textboxes' text can flow over more than one page.
By the way: How do I get rid of the borderline?

A: Reading the question it seems to me that you are not looking for actual boxed boxes but just want to have text side by side while allowing for page breaks. paracol supports such features.
\documentclass{article}
\usepackage{paracol}
\usepackage{lipsum}
\begin{document}
\section{A section}
\lipsum[1-4]
\begin{paracol}{2}
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
\switchcolumn[1]
Many more lines of text. Many more lines of text.
Many more lines of text. Many more lines of text.
Many more lines of text. Many more lines of text.
Many more lines of text. Many more lines of text.
Many more lines of text. Many more lines of text.
Many more lines of text. Many more lines of text.
Many more lines of text. Many more lines of text.
Many more lines of text. Many more lines of text.
Many more lines of text. Many more lines of text.
Many more lines of text. Many more lines of text.
Many more lines of text. Many more lines of text.
Many more lines of text. Many more lines of text.
\end{paracol}
\lipsum[4]
\end{document}

You can combine this with tcolorbox, if needed.
\documentclass{article}
\usepackage{paracol}
\usepackage{lipsum}
\usepackage[breakable]{tcolorbox}
\begin{document}
\section{A section}
\lipsum[1-4]
\begin{paracol}{2}
\begin{tcolorbox}[breakable]
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
\end{tcolorbox}
\switchcolumn[1]
\begin{tcolorbox}[breakable]
Many more lines of text. Many more lines of text.
Many more lines of text. Many more lines of text.
Many more lines of text. Many more lines of text.
Many more lines of text. Many more lines of text.
Many more lines of text. Many more lines of text.
Many more lines of text. Many more lines of text.
Many more lines of text. Many more lines of text.
Many more lines of text. Many more lines of text.
Many more lines of text. Many more lines of text.
Many more lines of text. Many more lines of text.
Many more lines of text. Many more lines of text.
Many more lines of text. Many more lines of text.
\end{tcolorbox}
\end{paracol}
\lipsum[4]
\end{document}

If you want to keep these boxes, you probably want to change their layout.
As you say that they should be invisible, here is a way to achieve this.
\documentclass{article}
\usepackage{paracol}
\usepackage{lipsum}
\usepackage[breakable]{tcolorbox}
\newtcolorbox{invbox}[1][]{breakable,boxrule=0pt,colback=white,colframe=white,#1}
\begin{document}
\section{A section}
\lipsum[1-4]
\begin{paracol}{2}
\begin{invbox}
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
Many lines of text. Many lines of text.
\end{invbox}
\switchcolumn[1]
\begin{invbox}
Many more lines of text. Many more lines of text.
Many more lines of text. Many more lines of text.
Many more lines of text. Many more lines of text.
Many more lines of text. Many more lines of text.
Many more lines of text. Many more lines of text.
Many more lines of text. Many more lines of text.
Many more lines of text. Many more lines of text.
Many more lines of text. Many more lines of text.
Many more lines of text. Many more lines of text.
Many more lines of text. Many more lines of text.
Many more lines of text. Many more lines of text.
Many more lines of text. Many more lines of text.
\end{invbox}
\end{paracol}
\lipsum[4]
\end{document}

However, in this case I'd probably just go with the plain paracol solution and change some indents if needed.


text:
Q: How to make additional window in wxpython on a click of a button I need to make an additional new window in wxpython on a click of a button (which is physically seperate from primary window). I want to do this without closing the last window.
This is what I have so far:
class Prototype(wx.Frame):
     def __init__(self, parent, title):
          wx.Frame.__init__(self, None, size=(1240,705))
          self.UI()
          self.Centre()
          self.Show()

     def UI(self):
          self.panel1 = wx.Panel(self, -1)
          self.sizer = wx.BoxSizer()
          self.sizer.Add(self.panel1, 1, flag=wx.EXPAND)
          b = wx.Button(self.panel1, label='second window', size=(180,100), pos=(650,25))
          b.Bind(wx.EVT_BUTTON, self.OnB)

          self.panel2 = wx.Panel(self, -1)
          self.sizer.Add(self.panel2,1,flag=wx.EXPAND)
          self.panel2.Hide()
          self.panel2.SetSizer(self.vbox)
          self.SetSizer(self.sizer)

     def OnB(self, event):
          self.panel2.Show()
          self.sizer.Layout()

app = wx.App()
Prototype(None, title='')
app.MainLoop()

A: Here's a working example:
 import wx

 ########################################################################
 class SecondFrame(wx.Frame):
      """"""

      #----------------------------------------------------------------------
      def __init__(self):
           """Constructor"""
           wx.Frame.__init__(self, None, title="Second Frame")
           panel = wx.Panel(self)
           txt = wx.StaticText(panel, label="I'm the second frame!")

 ########################################################################
 class Prototype(wx.Frame):

      #----------------------------------------------------------------------
      def __init__(self, parent, title):
           wx.Frame.__init__(self, None, title="First Frame", size=(1240,705))
           self.UI()
           self.Centre()
           self.Show()

      #----------------------------------------------------------------------
      def UI(self):
           self.panel1 = wx.Panel(self, -1)
           self.sizer = wx.BoxSizer()
           self.sizer.Add(self.panel1, 1, flag=wx.EXPAND)
           b = wx.Button(self.panel1, label='second window', size=(180,100), pos=(650,25))
           b.Bind(wx.EVT_BUTTON, self.OnB)

           self.SetSizer(self.sizer)

      #----------------------------------------------------------------------
      def OnB(self, event):
           frame = SecondFrame()
           frame.Show()

 #----------------------------------------------------------------------
 app = wx.App(False)
 Prototype(None, title='')
 app.MainLoop()

I don't really recommend mixing sizers and absolute positioning though. You should use one or the other. I recommend using sizers unless you plan to make frames that cannot be resized.

A: Just create a new wx.Frame as you already did in your app. Add something along the lines to your button event handler:
self.second_window = wx.Frame(None)
self.second_window.Show()


text:
Q: Merging three grayscale [R, G, B] images into a single color image in opencv I have 3 grayscale images that I created using the split function. Now I want to regenerate the color image back.
I tried the following code but it did not work. The resultant image I got was still grayscale.
        cv::Mat R = cv::imread("/home/r/secret_R.png",0);
        cv::Mat G = cv::imread("/home/r/secret_G.png",0);
        cv::Mat B = cv::imread("/home/r/secret_B.png",0);
        std::vector<cv::Mat> array_to_merge;
        array_to_merge.push_back(R);
        array_to_merge.push_back(G);
        array_to_merge.push_back(B);
        cv::Mat color;
        cv::merge(array_to_merge, color);

So then I tried the cvtColor function:
        cv::Mat color_converted;
        cv::cvtColor(color, color_converted, CV_GRAY2BGR);
        cv::imwrite("/home/r/color_secret.png",color_converted);

But apparently, it only works for source images that have only a single channel. I passed it one of my grayscale images:
cv::cvtColor(R, color_converted, CV_GRAY2BGR);

But I still could not get a color image back. The resultant image was still grayscale
What am I doing wrong ? How do I get my color image back ?

A: I can't see anything wrong with your code.  I suspect it may be the source data, or how it is being treated by the importer.  After you load the images, can you print out the image metadata to see what attributes OpenCV is reading?  They all must have the same dimensions and a single channel.
std::cout << "Red:   " << R.size().width << " x " << R.size().height << " x " << R.channels() << std::endl;
std::cout << "Green: " << G.size().width << " x " << G.size().height << " x " << G.channels() << std::endl;
std::cout << "Blue:  " << B.size().width << " x " << B.size().height << " x " << B.channels() << std::endl;

I just ran your program, just with the headers and main added.  I made one small change, to merge in B,G,R order (the default). I compiled it on Mac OS X 10.8 with:
g++ -o merge merge.cpp -lopencv_core -lopencv_highgui

against OpenCV version 2.4.3.
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/core/core.hpp>

int main(int argc, char* argv[])
{
    cv::Mat R = cv::imread("chan_dest_red.png", 0);
    cv::Mat G = cv::imread("chan_dest_green.png", 0);
    cv::Mat B = cv::imread("chan_dest_blue.png", 0);

    std::vector<cv::Mat> array_to_merge;

    array_to_merge.push_back(B);
    array_to_merge.push_back(G);
    array_to_merge.push_back(R);

    cv::Mat color;

    cv::merge(array_to_merge, color);

    imwrite("merged.png", color);

    return 0;
}

I had some single channel images from another project already split into files, and I just merged those into a single colour image and it worked just fine.  The source file info is as follows:
Red:   500 x 333 x 1
Green: 500 x 333 x 1
Blue:  500 x 333 x 1

A: One way would be to use cvtColor to create a color image from one channel, then replace the other two colors pixel-by-pixel in a loop using the at function.  There is probably a way to do this more easily with the matrix operators but I'm not familiar enough with openCV to know for sure.


text:
Q: Microsoft Bot Connector - get activity id from response after sending message I'm working on a bot for MS Teams using Microsoft's bot framework (using the .NET API). What I am trying to do right now is to retrieve the Activity.Id of a message the bot has just sent.  When the bot receives a message, an Activity.Id is included and I was hoping there was a way to retrieve that when sending a message.
I am currently sending using:
var response = connector.Conversations.SendToConversation((Activity)activity);
connector being an instance of Microsoft.Bot.Connector.ConnectorClient
This returns a ResourceResponse, which contains an Id, but this Id does not appear to be in the same format as that of the Activity.Id that comes with a message received.
Does anyone know if it is possible to get this information?
Thanks in advance!

A: Take a look at CreateConversationAsync. Here's a code snippet taken from our C# complete sample:
        try
        {
            var conversationResource = await connectorClient.Conversations.CreateConversationAsync(parameters);
            IMessageActivity message = null;

            if (conversationResource != null)
            {
                message = Activity.CreateMessageActivity();
                message.From = new ChannelAccount(botId, botName);
                message.Conversation = new ConversationAccount(id: conversationResource.Id.ToString());
                message.Text = Strings.Send1on1Prompt;
            }

            await connectorClient.Conversations.SendToConversationAsync((Activity)message);
        }
        catch (Exception ex)
        {

        }

A: What about saving the user activity and save the last activity id sent to user, and retrieve it when he sends a message again .to know more about saving user activity see this article Visit: https://blog.botframework.com/2017/05/05/saving-bot-actions-on-azure-sql-server/
I hope this could help you.


text:
Q: Как осуществить выравнивание блоков по ширине изменением их размеров? У меня есть код на https://codepen.io/osmanof-the-vuer/pen/ZErPezX.

.wrapper {
  display: flex;
  flex-wrap: wrap;
  width: 134px;
  height: 150px;
  background: #ccc;
}

.item {
  background: #abc;
  height: 20px;
  padding: 10px;
  margin: 5px;
}

Hello

world

my

dear

friends

На текущий момент блоки располагаются так:

Я бы хотел, чтобы было что-то подобное:

То есть, чтобы изменялась ширина крайних блоков.
Спасибо!

A: Могу предложить такой вариант:

.wrapper {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  column-gap: 5px;
  row-gap: 5px;
  padding: 5px;
  box-sizing: border-box;
  width: 134px;
  height: 150px;
  background: #ccc;
}

.item {
  background: #abc;
  height: 20px;
  padding: 10px;
  flex-grow: 2;
  text-align: center;
}

Hello

world

my

dear

friends


text:
Q: how could we calculate numerically $\hat{v} = α_{0}(I −P)^{-1}$, as the limit of the recurrence $v(t +1) = v(t)P +α_{0}$? I'm working with my colleague to introduce a potential therapeutic model. We use the framework of adaptive dynamics. But we are stuck at some steps of the continuous-time Markov chain.
In the appendix of this article (1), the author stated:

$c_{N,N'}=c^{0,+}_{N,N'}+c^{0,-}_{N,N'}+c^{+,0}_{N,N'}+c^{-,0}_{N,N'}+\mu.$
With the above-mentioned rates we obtain the forward Kolmogorov equations of
the Markov chain. Let A denote the corresponding matrix where all these rates are
collected, and note that the diagonal elements $−c_{N, N'}$
are negative. If we write the matrix A as A = L + U + D, where D is a diagonal
matrix, and L and U are lower and upper triangular matrices, we can
write the transition probability matrix P of the embedded
discrete-time chain as P =−D$^{−1}$(L+U). The probability distribution of
the Markov chain after t transitions is $α_{t} = α_{0}P^{t}$ , and the average
number of times that the Markov chain visits state i is  (17)
$\hat{v}=\sum_{t=0 }^{\infty }\alpha_{t}=\sum_{t=0}^{\infty }\alpha_{0}P^{t}.$
From (17) we observe that $α_{0} = \hat{v}− \hat{v}P = \hat{v}(I −P)$, and thus we obtain
(Kemeny and Snell 1960) $\hat{v} = α_{0}(I −P)^{-1}$, which can be calculated
numerically (Faddeev and Faddeeva 1963) as the limit of the recurrence
$v(t +1) = v(t)P +α_{0}$.

and in the appendix of another reference(2) for the same author he stated:

The initial state is  $ α_{n,1} = \hat{p_{n}} $  for $ 0\le n\le k-1 $
and otherwise  $α_{n,n'} = 0. $ The recurrence becomes
$v_{n,n'}^{} (t + 1) = \frac{c^{0,−}
 _{n,n'+1} }{c_{n,n'+1}} v_{n,n'+1}(t) + \frac{c^{+,0}
 _{n−1,n'} }{c_{n−1,n'}} v_{n−1,n'} (t)
 + \frac{c^{−,0}
 _{n+1,n'} }{c_{n+1,n'}} v_{n+1,n'} (t) + \frac{c^{0,+}
 _{n,n'−1} }{c_{n,n'−1}} v_{n,n'−1}(t) +  α_{n,n'} $
for $n\ge 0,n'\ge 1,n+n'\le k$ The boundary conditions are $
> v_{n,0}=0,v-_{1,n'}=0 $  and $ v_{i},k+1-i=0 $  because then the
population size $ n + n' = i + K + 1 − i = K + 1 $ is above the
maximum allowed.

My question is, if we already have the  transition probability matrix P, how could we calculate numerically  $\hat{v} = α_{0}(I −P)^{-1}$,  as the limit of the recurrence $v(t +1) = v(t)P +α_{0}$  ?
Any help would be much appreciated!
Thanks


text:
Q: Snapshot and Restore without give Permission for Backup Folder in Linux I need a elastic search backup in Linux and if i given to permission for that backup folder, repository it would be created.

*

*with create and give permission to backup folder.

*

*mkdir /home/user/ES

*chmod 777 /home/user/ES

*Query : curl -XPUT localhost:9200/_snapshot/myback -d '{"type":"fs","settings":{"location":"/home/user/ES","compress":true}}'

*Response : { acknowledge : true }...

*snapshot and restore works fine, But

*with out create backup folder(/home/user/ES) and give permission to that folder it shows error message

*

*Query : curl -XPUT localhost:9200/_snapshot/myback -d '{"type":"fs","settings":{"location":"/home/user/ES","compress":true}}'

*Response :
{"error":"RepositoryException[[myback] failed to create repository]; nested: CreationException[Guice creation errors:\n\n1) Error injecting constructor, org.elasticsearch.common.blobstore.BlobStoreException: Failed to create directory at [/home/bigdata/ES]\n  at org.elasticsearch.repositories.fs.FsRepository.<init>(Unknown Source)\n  while locating org.elasticsearch.repositories.fs.FsRepository\n  while locating org.elasticsearch.repositories.Repository\n\n1 error]; nested: BlobStoreException[Failed to create directory at [/home/bigdata/ES]]; ","status":500}
I need without create backup folder, and without give permisson for that folder.
please give as a possible solution..


text:
Q: Extract exe resource and run it (in Visual Basic) let's say i did add some exe file to the project's resources.
now if i want to run that file, i have to extract it from the resources as a new file and then i can run it
So please can someone help me with how to do it

A: Getting a resource as a stream from an assembly:
myAssembly.GetManifestResourceStream("TheNameSpacename.NameOfYourFile")

Copying the stream to a file: already described here:
 http://stackoverflow.com/questions/411592/how-do-i-save-a-stream-to-a-file

(example is in C#, porting to VB.NET should be easy).
Running the file: use System.Diagnostics.Process.Start:
 http://msdn.microsoft.com/en-us/library/system.diagnostics.process.start.aspx