text:
Q: how to keep the same amount of a background image visible as screen sizes change? Is it possible using only CSS to replicate how as screen sizes change but the same amount of image is seen? I have been able to scale the image but the amount of the image seen changes as screen sizes change. I am fairly new to learning CSS and appreciate any help.
I am trying to replicate this site. Just the initial section and first image.
https://ayesha.dropletthemes.com/home-beauty-salon/


text:
Q: Nextjs dynamic routing exclude Is there a way of excluding some dynamic routs in next.
Header component:
export const DynamicCatPageLinks = () => {
  const router = useRouter();

  const relPath = router.route
  const { tv } = router.query

  return (
    <Query query={CategoryList}>
      {({ loading, error, data }) => {
        if (loading) return
Loading...
;
        if (error) return
Error fetching the post!
;
        return (
          <>
            {data.category.map(cat => (

                <Link href=
                    {`/${tv}/category/page/${cat.slug}`}
                >
                  {cat.name}
                </Link>

            ))}
          </>
        );
      }}
    </Query>
  );
};

Page Hierarchy
-pages
  -[tv]
   -category
   ...

So the url is: [tv]/category/page/...
Is there a way of limiting the values that can be passed to the [tv] route
So that the url can be, example:
television1/category/page/...
television2/category/page/...
television3/category/page/...
...

But if you do something like this:
unknown/category/page/...
It renders a different page like 404 as example?
Thank you.

A: There is an RFC to allow custom Routes and regex with NextJS router
For now you can get the value in your component rendering and redirect if it doesn't fit the list of your whitelisted params
To do that you can create a custom hook so that you don't have to duplicate the logic
const whiteList = ['television1', 'television2, 'television3'];
const useWhiteListParams = () => {
   const router = useRouter();
   const { tv } = router.query;
   useEffect(() => {
       if(!whiteList.includes(tv)) {
           router.push(/404);
       }
   }, [tv])

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Execute asynchronously a sync function inside AJAX (Javascript) This is the sync function.I call it inside an Ajax, but how is synchronous it´s deprecated. ¿Is there any way to run it as if it were asynchronous?
Or to make it asynchronous? Thanks.
function fetchHeader(url, hdr) {
  try {
    var req=new XMLHttpRequest();
    req.open("HEAD", url, false);
    req.send(null);
    if(req.status== 200){
    return req.getResponseHeader(hdr);
    }
    else return false;
} catch(er) {
    return er.message;
}

I've tried that, but it says: response is not defined and callback is not a function.

function fetchHeader(url, hdr, callback) {
 try {
  var req=new XMLHttpRequest();
  req.onreadystatechange = function() {

    if(this.status == 200) {

      callback(req.getResponseHeader(hdr), req);
    }else{
        console.log("callback is not called");
    }
 }
 req.open("HEAD", url, true);
 req.send(null);

 } catch(er) {
  return er.message;
 }
 }

And I call it:

 fetchHeader(dirGen+json[i],'Last-Modified', function(header, request) {
 if (response.statusCode == 200) {
 return header;
 console.log(header);

 }else {
 console.log("Failed answer");
 }
 });

A: You don't need to micromanage XMLHttpRequest anymore. Just listen for the 'load' event. Actually I suggest you switch to fetch. fetch returns a promise which will help you build cleaner code for this type of thing. But here is basics of how to call one XHR and then start another after you get a response.
var url1 = 'path/to/file'
var url2 = 'path/to/differentfile'

function onXhrError() {
  // ... handle errors
}

xhr1 = new XMLHttpRequest()

xhr1.addEventListener('load', onXhrLoad1)
xhr1.addEventListener('error', onXhrError)

xhr1.open('GET', url1)
xhr1.send()

function onXhrLoad1 (){
  var res = this.responeText

  function onXhrLoad2 (){
    var res2 = this.responeText
    // ... do stuff with second response
  }

  var xhr2 = new XMLHttpRequest()
  xhr1.addEventListener('error', onXhrError)
  xhr2.addEventListener('load', onXhrLoad2)
  xhr2.open('GET', url2)
  xhr2.open()

  // ... do other stuff with first resoponse
}


text:
Q: Plugging in Regression Coefficients back into Cox PH Model I am trying to plug the regression coefficients back into the cox ph model to manually find the partial hazard of the model, but am getting mixed results. I am using the lifelines python library for Cox PH.

For one observation:
The partial_hazard is the product the lifelines python library outputted.
Each variable below is the sum of the observed value for xi * coefficient B.
partial_hazard = 0.606
n1 = 29835.02039 * 0.398
n2 = 3.949135 * 0.145
n3 = 0.477231 * 0.18
n4 = 123.658238 * -0.21
n5 = -0.771495 * 0.134
n6 = 0.750476 * -0.124

If I plug in the values from above it returns inf
np.exp(n1 + n2 + n3 + n4 + n5 + n6)

The baseline hazard = 0.001 according to the lifelines library.
To get the hazard h(t|x):
0.001 * np.exp(n1 + n2 + n3 + n4 + n5 + n6)

However, the sum (above) does not equal partial_hazard = np.log(0.606)
Is this logic correct? Any practical input would be appreciated.

A: I can't speak to lifelines-specific issues (software per se is generally off-topic on this site), but there are a few things you need to double-check and understand in general.
First, your n1 predictor has an outrageously high contribution to the log-partial hazard sum (the linear predictor from the model), leading to the overflow. Check that for a coding or scaling error, along with n4 (which is only extremely high). (A summed linear predictor value of only 2 means a hazard ratio greater than 7, which is quite high in my experience. On that basis, there's something terribly wrong with n1 and n4, maybe something like perfect separation in logistic regression.)
Second, the baseline hazard is a function of time. The only exception is if you have an exponential survival curve, in which case the baseline hazard is constant over time. I'm not sure just what the single value you report for "baseline hazard" represents.
Third, calculations involving baseline hazard for a Cox model typically originate in practice from the cumulative hazard over time rather than the instantaneous hazard at a specific time (even if explanation of the Cox model is typically done from the perspective of instantaneous hazard). A baseline cumulative hazard over time is straightforward to get once you have your Cox model. The (unsmoothed) instantaneous baseline hazard is then 0 except at an event time, when it's the change in cumulative baseline hazard at that time. See for example this answer, whose symbols are defined more fully in this answer.


text:
Q: CORS ERROR http://localhost:3000/ net::ERR_FAILED 200 I'm getting cors error
const api = getAPI(); // HERE's ERROR

function getAPI() {
    return (fetch('http://localhost:3000')); // returns a promise
}

register.html:1 Access to fetch at 'http://localhost:3000/' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
register.js:103 GET http://localhost:3000/ net::ERR_FAILED 200
getAPI @ register.js:103
register @ register.js:97
register.js:103   Uncaught (in promise) TypeError: Failed to fetch
    at getAPI (register.js:103)
    at HTMLButtonElement.register (register.js:97)

Here's my main app, app.js (api)
const express = require('express')
const app = express()
const port = 3000
const mysqlConObj = require('./config/mysql.js')
const db = mysqlConObj.init()
const cors = require('cors');
mysqlConObj.open(db)
app.get('/', (req, res) => res.send('MyAPIName'))
app.listen(port, () => console.log('Server Running. . .'))
app.use(cors({origin: "http://localhost:3000", credentials: true})); // CORS SETUP

Also, this doesn't work. (Both of
app.use(cors({origin: "http://localhost:3000", credentials: true}));

and
app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Credentials", true);
    res.header("Access-Control-Allow-Origin", "http://localhost:3000");
    res.header("Access-Control-Allow-Headers",
        "Origin, X-Requested-With, Content-Type, Accept, Authorization, X-HTTP-Method-Override, Set-Cookie, Cookie"); // select only the ones you need
    res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");

    next();
});

doesn't work.)
I already do cors setup.
Can anyone tell me what's wrong?
I imported CORS well.
Thanks in advice


text:
Q: When using celery, SQLAlchmey keeps suffering from database connection issues On our dev environment, we started exploring the use of celery. The problem is when a task is launched, SQLAlchemy often has a hard time connecting to our Amazon/AWS RDS instance. This tends to happen after a period of time regardless of what settings I've tried but it's hard to say just how long. Our database is a snapshot of our production database on AWS RDS with all of the same parameters/settings.
The errors include...
OperationalError: (_mysql_exceptions.OperationalError) (2013, 'Lost connection to MySQL server during query')...(Background on this error at: http://sqlalche.me/e/e3q8)
...or...
OperationalErrorOperation : MySQL Connection not available.

Our engine...
engine = sa.create_engine(SA_ENGINE, echo=False, pool_recycle=90, pool_pre_ping=True)

(I've tried tons of variations of pool_recycle)
On the database side, I've changed the following parameters (though some are extreme, I've tried all sorts of variations)...
interactive_timeout = 28800
wait_timeout = 28800
max_heap_table_size = 32000000000

I tried wrapping each query to reconnect and this didn't work either. Note this code is taken from a StackOverflow answer on similar topics...
def db_execute(conn, query):
    try:
        result = conn.execute(query)
        print(result)
    except sa.exc.OperationalError:  # may need more exceptions here (or trap all)
        conn = engine.connect()  # replace your connection
        result = conn.execute(query)  # and retry
    return result

This has been a three day wheel spin and I'm stuck... I hopes someone out there has some insight or guidance?
UPDATE
I've completely removed celery from the equation and now it's still randomly dropping out and even in between queries within the same function flow. On the production server, the software is nearly identical now.


text:
Q: PHP Get value of a level in multidimensional array using function arguments as "path" I have a multidimensional array with N levels like this:
$a = array(
'a'=>1,
'b'=>array(
    'x'=>array(
        'p'=>array(
            't'=>2
        )
    )
),
'c'=>3
);

How can I get the value by "path" using an array of arguments in a function?
function get(){
   $args = func_get_args();
   $b = (global) $a;
   // ????
}
$v = get('b','x','p'); // expected: Array ( [t] => 2 )

A: function get() {
    global $a;
    $current = $a;
    $args = func_get_args();
    foreach($args as $key) {
        $current = $current[$key];
    }
    return $current;
}

A: Bit more php-way of doing this:
function array_get_path(array $array, $path) {
  $current = $array;

  if(!empty($path)) {
    foreach($path as $elem) {
      if(isset($current[$elem])) {
        $current = &$current[$elem];
      } else {
        return $current;
      }
    }
  }

  return $current;
}

A: Walk down your arguments array one element at a time:
function get() {
    global $a;
    $args = func_get_args();
    $currentElement = $a;

    foreach ($args as $index) {
        $currentElement = $currentElement[$index];
    }

    return $currentElement;
}


text:
Q: Placing View Underneath Action Bar I have a custom camera activity in my Android app.  For android devices using KitKat, I needed to account for the visible navigation bar at the bottom of the screen.  To do this, I use the following line to ensure my views are below the navigation bar:
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN );

However, when I do this, one of my views becomes hidden behind the action bar.  I'm trying to account for the height of the action bar by adding a top margin to this view, but it doesn't appear to be correct.
What am I doing wrong?
This is what I would like the view to look like (works on pre-KitKat devices):

And this is what it currently looks like on Kit Kat devices (you can see that the top of my view is cut off):

Here is my layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="left"
    android:orientation="vertical" >

    <HorizontalScrollView
        android:id="@+id/gallery_scroll_view"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:scaleType="fitXY" >

        <com.example.helperClass.PictureHorizontalLayout
            android:id="@+id/mygallery"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:scaleType="fitXY" >
        </com.example.helperClass.PictureHorizontalLayout>
    </HorizontalScrollView>

    <FrameLayout
        android:id="@+id/camerapreview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="@color/black" />

    <LinearLayout
        android:id="@+id/button_holder_customized_cam"
        android:layout_width="match_parent"
        android:layout_height="55dp"
        android:layout_alignParentBottom="true"
        android:background="#838B8B"
        android:gravity="bottom"
        android:orientation="horizontal"
        android:weightSum="0.9"
        >

        <ImageButton
            android:id="@+id/gallery_customized_camera"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginRight="1dp"
            android:layout_weight="0.3"
            android:adjustViewBounds="true"
            android:background="@null"
            android:contentDescription="@string/add"
            android:maxWidth="75dp"
            android:scaleType="center"
            android:src="@drawable/ic_action_picture" >

            <!-- android:background="@drawable/custom_button_blue" -->

        </ImageButton>

        <ImageButton
            android:id="@+id/shutter_customized_camera"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginRight="1dp"
            android:layout_weight="0.3"
            android:adjustViewBounds="true"
            android:background="@drawable/custom_button_blue"
            android:contentDescription="@string/add"
            android:maxWidth="75dp"
            android:scaleType="center"
            android:src="@drawable/ic_action_camera" >
        </ImageButton>

        <ImageButton
            android:id="@+id/video_customized_camera"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="0.3"
            android:adjustViewBounds="true"
            android:background="@null"
            android:contentDescription="@string/add"
            android:maxWidth="75dp"
            android:scaleType="center"
            android:src="@drawable/ic_action_video" >

            <!-- android:background="@drawable/custom_button_blue" -->

        </ImageButton>
    </LinearLayout>

    <TextView
        android:id="@+id/camera_timer"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@id/button_holder_customized_cam"
        android:layout_alignParentRight="true"
        android:padding="15dp"
        android:text="@string/no_time"
        android:textColor="@color/red"
        android:textSize="20sp"
        android:visibility="invisible" >
    </TextView>

</RelativeLayout>

And here is how I set margins for the HorizontalScrollView:
  myHorizontalLayout = (PictureHorizontalLayout) findViewById(R.id.mygallery);
  // apply margin to horizontal scroll view to take into account height of status bar
    TypedValue tv = new TypedValue();
    int actionBarHeight  = 0;
    if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))
    {
        actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
        Log.d(TAG, "actionbarHeight before: " + actionBarHeight);
        FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) myHorizontalLayout.getLayoutParams();
        Log.d(TAG, "actionbarHeight after: " + actionBarHeight);
        params.setMargins(0, actionBarHeight, 0, 0);
        Log.d(TAG, "ADJUST MARGINS OF HORIZONTAL LAYOUT");
        myHorizontalLayout.setLayoutParams(params);
    }

NOTE: I also tried adding android:layout_marginTop="?attr/actionBarSize" to the HorizontalScrollView in my layout file, but this didn't work either (the vertical offset was still incorrect)

A: The best way to do what you want, is to use ActionBar in Overlay Mode.
Then, you can use the following margin in your view to make sure it does not hide behind the action bar.
<!-- Support library compatibility -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="?attr/actionBarSize">
    ...
</RelativeLayout>

A: Change your RelativeLayout to use the android:fitsSystemWindows="true" attribute.
From the View.SYSTEM_UI_FLAG_LAYOUT_STABLE docs:

When using other layout flags, we would like a stable view of the
  content insets given to fitSystemWindows(Rect).

Also, the attribute android:orientation isn't inherited by RealtiveLayout and android:scaleType isn't inherited by HorizontalScrollView.


text:
Q: Question on the uniqueness of LU decomposition Let $A \in \mathbb{K}^{n \times n}$ a matrix, and suppose that we can run the Gaussian elimination on $A$ without row or column interchange, so there exist the $LU$ decomposition of $A$.
We define the $LU$ decomposition as $U \in \mathbb{K}^{n \times n}$ is an upper triangle matrix, and $L \in \mathbb{K}^{n \times n}$ is a lower triangle matrix, with $\ell_{i,i}=1$ main diagonal elements, and $A=LU$.
We know, that if $\det(A) \neq 0$, so $A$ is invertible, then the $LU$ decomposition is unique. Quite easy to show that by contradiction.
Questions.
$(1)$ Is there any other condition for the uniqueness of $LU$ decomposition, even if $\det(A)=0$?
$(2)$ Is there a necessary and sufficient condition for uniqueness of $LU$ decomposition?


text:
Q: set encoding in XML Declaration I have one var newMenuRoot = parseXML(SvgString,contextMenu), In this contextMenu (by default variable for svg) is Document type and which value is like
some child nodes inside this node so I want to add encoding="utf-8" to this xml by javascript so that my svg supprot UTF-8 characters .
It should be like that  for default contextMenu
provide me solutions

A: You're going to need to provide a bit more information than that if anyone is going to help you.  Can you provide an example of the XML you're passing into parseXML() (e.g. the value of SvgString or contextMenu) and whether or not that's something you can control directly (e.g. is SvgString or contextMenu something you've written or is it some third party plugin or something).
I'd guess, from the small amount of information you've got there, that you'll just want to do a string replace or a RegEx replacement on the value of SvgString or contextMenu to replace whatever the current encoding is for the encoding you're after, but I don't think that will affect the ability of your SVG to handle additional characters etc.


text:
Q: Definition of Connection Does anyone know what constitutes an official connection to a workstation? I have a reasonably small scale operation where I am using a WORKSTATION, not server, as a server. For the most part, it works fine, but there is a 10 connection limit and I was toying with some new functionality and ended up causing some problems as the 10 connection limit kept getting hit.
From trial and error, I am pretty sure using a web service on a workstation counts as a connection as would surfing web pages served by the workstation. What if I set-up a MySql database? Everytime a PC connects or replicates data from the MySql server, would THAT count as a connection? What about connecting to the PC via mapping a drive?

A: These two articles should help:

Understanding IIS7 Request Restrictions on Windows Vista
IIS limits imposed by Operating System version

Basically from Vista on the number of connections are unlimited. It's the number of of concurrent requests that IIS can process that are restricted. So in theory you could have 15 concurrent connections to IIS but five of them are queued.


text:
Q: Preventing SQL deadlocks when database is updated by two different processes We have a system with two different processes that update the same sql server tables.    One process has high transaction volume and is initiated by a scheduled task that runs 24 X 7.   The other is a low transaction volume process that is initiated by user volume.   The second process database transactions are frequently being killed because of deadlocks.    I'm not sure how to fix this.   Ideally, I would want the user instantiated transactions to have priority and for the scheduled task transactions to essentially wait until the database was free.

A: Well for us, the solution was to change the isolation level from Read Committed to Read Comitted Snapshot.   What this does is cause all Selects to snapshot the table its reading before doing the select.   It thus prevents selects from colliding with each other causing the deadlock   An alternative would have been to use (NOLOCK) query hints on all select statements.   However, we have a lot of sql and we were looking at rewriting a lot of code.   Changing the isolation level was easy and quick and did not require a lot of regression testing.


text:
Q: convergence of $\sum_{n≥ 1}\left(\frac{2\cdot3\cdot4\cdot\cdot\cdot(n+2)}{5\cdot6\cdot7\cdot\cdot\cdot(n+5)}\right)^{\frac{1}{2}}$ I want to determine if the series converges, to do this I apply the ratio criterion as follows
$$\frac{a_{n+1}}{a_n}=\frac{\left(\frac{2\cdot3\cdot4\cdot\cdot\cdot(n+3)}{5\cdot6\cdot7\cdot\cdot\cdot(n+6)}\right)^{\frac{1}{2}}}{{\left(\frac{2\cdot3\cdot4\cdot\cdot\cdot(n+2)}{5\cdot6\cdot7\cdot\cdot\cdot(n+5)}\right)^{\frac{1}{2}}}}=\left(\frac{\left(\frac{2\cdot3\cdot4\cdot\cdot\cdot(n+3)}{5\cdot6\cdot7\cdot\cdot\cdot(n+6)}\right)}{{\left(\frac{2\cdot3\cdot4\cdot\cdot\cdot(n+2)}{5\cdot6\cdot7\cdot\cdot\cdot(n+5)}\right)}}\right)^{\frac{1}{2}}$$
If I am not mistaken, this limit tends to one, so I could use Raabe's criteria to arrive at something concrete, but I am not entirely sure. Any suggestions? thanks


text:
Q: NSMutableAttributedString on iOS 3.1.3 I'm dealing with a very odd situation. I'm implementing Attributed Strings into my iOS application, and I had the warning going in that they are available iOS 3.2 and above. Because I still support 3.1.3 on iPhones, I knew I had to weakly link CoreText and probably so some compile time OS check before using them.
I weakly linked the framework, but out of curiosity I just used the class as is and ran it on a 3.1.3 device... and it works. What am I missing here, I'm so confused why this isn't crashing. I'm 100% sure this is a 3.1.3 device, but is NSMutableAttributedString a hidden class on 3.1.3, and thus actually does work because of the dynamic nature of objective-c ?

A: I am the author of the OHAttributedLabel class.
Thanks for using it!
The behavior you have is strange, as OHAttributedLabel uses the CoreText framework to draw the NSAttributedStrings on screen.
As CoreText is only available since iOS 3.2, I can't see how it would be possible for this to work under iOS 3.2, especially iOS 3.1.3…?

A: Did it really work, instead of just not crashing?
Depending on the setting, a non-existent class becomes just nil. Note that in Objective-C you can send a message to a nil. Then it just returns nil or 0. Then [[NSAttibutedString alloc] init] might just return nil, without crashing.

A: CoreText was introduced with iOS 3.2. If you weak link against it the app will start, but it will crash on the first instance on calling a CoreText function.
To still be compatible with earlier versions you CAN weak link and avoid CT code by drawing the text with Quartz instead. You would detect if CT exists on the device and use it if yes, otherwise you would have a crude fallback mechanism for your drawing.


text:
Q: creating gin index in postgreqsql I am using "PostgreSQL 9.1.5",i am trying to create gin index for the text column.It is showing  error message.
CREATE TABLE users (
    first_name text,
    last_name text
)

CREATE INDEX users_search_idx ON users USING gin (first_name,last_name)

I am having column values like this(first_name)
"456fc0470a95c02bb42ef3e35fc81852"

i am trying to query the data like this.
SELECT count(*) FROM users where first_name like '%aeb%'

A: If you want to make use of a trigram search, you need to first install the pg_trgm extension:
create extension pg_trgm;

(This needs to be done as the superuser)
Then you need to provide the operator class to be used in the index:
CREATE INDEX users_search_idx
   ON users USING gin (first_name gin_trgm_ops, last_name gin_trgm_ops);

But a combined index on both columns would not support e.g. where last_name like%aeb%'`. If you need to search on the two column individually, you need two indexes.


text:
Q: Trying to get request header cookies and response cookie I'm trying to send build my API, but I have to login first.
When I hit login, there's response header and request header. They set cookies, as shown in pictures.
How could I get these cookies into a variable to use it in other file or something like that?
reqested header
responed header
my code
$file = 'cookies.txt';
$buffer = "__RequestVerificationToken=$ver;";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.xxxx.org/L/DoLogin");
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0');
curl_setopt($ch, CURLOPT_HEADER  ,array("Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3"));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "__RequestVerificationToken=$buffer&username=xxxx&pw=xxxx&rememberMe=true&loginAcc=");

curl_setopt($ch, CURLOPT_RETURNTRANSFER  ,1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION  ,1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$content = curl_exec($ch);

// get cookies
$cookies = array();
preg_match_all('/Set-Cookie:(?<cookie>\s{0,}.*)$/im', $content, $cookies);

print_r($cookies['cookie']); // show harvested cookies

// basic parsing of cookie strings (just an example)
$cookieParts = array();
preg_match_all('/Set-Cookie:\s{0,}(?P<name>[^=]*)=(?P<value>[^;]*).*?expires=(?P<expires>[^;]*).*?path=(?P<path>[^;]*).*?domain=(?P<domain>[^\s;]*).*?$/im', $content, $cookieParts);
print_r($cookieParts);


text:
Q: How to kill processes launched by "&" in bash? I wanted to run script ./startMegaTrolling.sh 100000000000000000000000 in bash:
#!/bin/bash
if [ "$#" -ne 0 ];then
    let "LAST = $1 - 1"
    for i in `seq 0 $LAST`
    do
        php trolling.php --processNumber=$1 &     #here
    done
fi

But how to get pid of all launched processes by this method?
I tried put the >> pids.txt #here, but it does not work. I want to have got second script to kill all launched processes.

A: Use $! to access the pid of the most recently launched background process. Thus:
#!/bin/bash
# ^- shebang is mandatory since we use bash-only features
if (( $# )); then
  for (( i=$1; i>0; i-- )); do
    php trolling.php --threadNumber="$1" &
    echo "$!" >>pids.txt
  done
fi

A: You can collect the process ids as you start the processes, then kill them all later.
#!/bin/bash
if [ "$#" -ne 0 ];then
    LAST=$(( $1 - 1 ))   # let is a bit antiquated
    for i in `seq 0 $LAST`
    do
        php trolling.php --threadNumber=$1 &
        pids="$pids $!"
    done
fi

# Later on
kill $pids

Technically, an array is a better than a space-separated string for collecting
a series of items, but since a process ID is guaranteed to be a simple integer,
it works fine here.

For full POSIX compliance (which isn't required by the question, based on the bash tag), you can't use either seq or a C-style for loop, and will have to use a while loop instead.
if [ "$#" -ne 0 ]; then
    LAST=$(( $1 - 1 ))
    i=0
    while [ "$i" -ne "$LAST" ]; do
        php trolling.php --threadNumber="$1" &
        pids="$pids $!"
        i=$((i+1))
    done
fi

A: You can try something like this:
pid: ps aux | grep <NAME_OF_YOUR_APP> | awk '{print $2}'
then:
kill -9 $pid  > /dev/null 2>&1 &


text:
Q: using -fno-objc-arc still gives me Convert to ARC errors I am trying to update my project to use ARC and I use JSONKit so I went in the 'Build Phases' tab under 'Compile Sources' and added the argument '-fno-objc-arc' but I still get errors all over the place.  I thought that was suppose to prevent this from happening?
What am I missing on this?

A: That is correctly how you implement it. What files did you include that flag on.
I am using AFNetworking and I had to put that flag on each file that AFNetworking had me include.

Adding to each file allowed the arc processor to ignore these files.
are you sure it is all lower case and that there are no spaces in the wrong places?


text:
Q: How do I get the json data from this HttpURLConnection implementation converted from cURL? Hi I have the following cURL
curl -X GET --header "api-key: sOmE-API-kEy" "https://api.data.gov.sg/v1/environment/uv-index?date=2016-06-01"

which I got from the website that provides data for smart nation their website returns proper json data using their forms but i would like to do this via code using an HttpURLConnection so far I am following the code references i found online but it's not working and I couldnt see what's wrong, i get the NetworkOnMainThreadException which I solved by implementing it as an AsyncTask but when I step in android studio debug its now returning with an FileNotFoundException. i also tried using the TrustedManager etc suggested below and it still has the same error. one thing i noticed is when I go to the website and click on the button and look at it in firebug the following is the one that is processessed ...
https://apiconsole-prod.apigee.net/smartdocs/v1/sendrequest?targeturl=https%3A%2F%2Fapi.data.gov.sg%2Fv1%2Fenvironment%2Fuv-index%3Fdate%3D2016-06-01&_=1469245322558

but if i type directly from the browser the response has something like this...
steps.oauth.v2.FailedToResolveAPIKey%22%7D%7D%7D", "responseStatusCode": "401"
    URL url = new URL("https://api.data.gov.sg/v1/environment/uv-index?date=2016-06-01");
    urlConn = (HttpURLConnection)url.openConnection();
    urlConn.setRequestMethod("GET");
    urlConn.setDoInput(true);
    urlConn.setDoOutput(true);
    urlConn.setRequestProperty("Content-Type", "application/json");
    urlConn.setRequestProperty("Accept", "application/json");
    urlConn.setRequestProperty("api-key", "sOmE-API-kEy");

    in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
    String line;
    StringBuilder buffer = new StringBuilder();
    while ((line = in.readLine()) != null) {
        buffer.append(line).append('\n');
    }
    // Chomp the last newline
    buffer.deleteCharAt(buffer.length() - 1);

**note apikey renamed for privacy
so in short looking at the header data from firebug how to i complete my http code implementation
Accept
*/*
Accept-Encoding
gzip, deflate, br
Accept-Language
en-US,en;q=0.5
DNT
1
Host
apiconsole-prod.apigee.net
Origin
https://developers.data.gov.sg
Referer
https://developers.data.gov.sg/datagovsg-apis/apis/get/environment/uv-index
User-Agent
Mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0
api-key: sOmE-API-kEy

A: Solved with the following...

You should probably have urlConn.setDoOutput(false); for a GET request
  – Yuri Schimke 3 mins ago

Thanks so much for all the suggestions!


text:
Q: Refresh the whole page after submit (Fancybox) I have a page where the user will click the button then a fancybox popup will appear and in there is a php file that has all the fields you can update. What I want to happen is that after I press the update button the whole page will refresh and will close the popup. But what's happening is that after I press update only the popup refreshes. How could I do that?
in this page is where I echo all of the user info
emp_refer.php
       <a id="various5" href="http://i-refer.elitebpocareers.com/refer/updateInfo.php">
                    <button class="button">Edit Personal Information</button>
                </a>

        <SCRIPT TYPE = "text/javascript">

        $("#various5").fancybox({
         'width'             : '75%',
         'height'            : '75%',
         'autoScale'         : false,
         'transitionIn'      : 'none',
         'transitionOut'     : 'none',
         'type'              : 'iframe'
        });

        </SCRIPT>

Then in the page 2 after the update I do this code and the popup only refreshes
echo "<meta http-equiv='refresh' content='0; url=emp_refer.php'>";

A: What you could do is :
In page 2, after the update run the fancybox.close() method instead of the meta tag like :
echo "<script>parent.jQuery.fancybox.close();</script>";

Then, in your fancybox initialization script (emp_refer.php page) add the onClosed callback to your API options and run location.reload() within it like :
$("#various5").fancybox({
    'width': '75%',
    'height': '75%',
    'autoScale': false,
    'transitionIn': 'none',
    'transitionOut': 'none',
    'type': 'iframe',
    'onClosed': function () {
        location.reload();
        return;
    }
});

NOTE: if you are using fancybox v2.x use the afterClose callback


text:
Q: How to reload a component without refreshing the entire page? Any help would be greatly appreciated, I've built out a simple quote generator project in React and would like the new quote to load without rendering the entire page. Currently, im using hooks and the quotes state resides in one component is it possible to reload/refresh state from another component using a click handler?
Project link: https://codesandbox.io/s/quote-generator-czffn?file=/src/components/buttons/Buttons.js
How it's currently reloading, using a refreshPage function.
Thanks!
import React from 'react';

const Buttons = ({ quotes, getNewQuote }) => {
  const twitterUrl = `https://twitter.com/intent/tweet?text=${quotes.joke}`;
  //   console.log(twitterUrl);

  function refreshPage() {
    window.location.reload(false);
  }

  return (

      <button
        onClick={() => window.open(twitterUrl, '_blank')}
        className='twitter-button'
        id='twitter'
        tittle='Tweet This!'
      >

      </button>
      <button id='new-quote' onClick={refreshPage}>
        New Quote
      </button>

  );
};

export default Buttons;

A: If the quote is to show a new quote without refreshing the entire page, remove the axios request from the hook and put it in its own function.
  const getQuotes = () => {
    axios
      .get("https://geek-jokes.sameerkumar.website/api?format=json")
      .then(res => {
        setQuotes(res.data);
        // console.log(res.data);
      })
      .catch(err => console.log(err));
  }

// ...

<Buttons onClick={getQuotes} quotes={quotes} />

Then adjust the button to get use this function when it's clicked:
const Buttons = ({ quotes, getNewQuote, onClick }) => {

// ...

<button id="new-quote" onClick={onClick}>
  New Quote
</button>

You might want to add an animation while it's retrieving things as well with a useState for loading, but this should be a good start.
======= UPDATE =======
Here's also an example code to see how it could work.
Click Run code snippet to see it working.

const { useState, useEffect } = React;

const Quote = props => {
  return

      {JSON.stringify(props.quote)}

    <button onClick={props.onClick}>Get Quote</button>

}

const App = () => {
  const [quotes, setQuotes] = useState(null);
  const [loading, setLoading] = useState(true);

  const getQuotes = () => {
    setLoading(true);
    axios
      .get("https://geek-jokes.sameerkumar.website/api?format=json")
      .then(res => {
        if (res.data && res.data.joke) {
          setQuotes(res.data.joke);
        }
        setLoading(false);
      })
      .catch(err => {
        console.log(err);
        setLoading(false);
      });
  }

  useEffect(() => {
    getQuotes();
  }, []);

  return loading ?
Loading...
 : <Quote quote={quotes} onClick={getQuotes} />
}

ReactDOM.render(<App />, document.querySelector('#root'));
body {
  background: #efefef;
  font-family: Arial, sans-serif;
  padding: 20px;
  margin: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

section {
   background: white;
   border-radius: 6px;
   display: block;
   padding: 10px;
}

blockquote {
  padding: 10px;
  margin: 0 0 10px 0;
  border-bottom: 1px solid #efefef;
  font-size: 21px;
}

button {
border-radius: 4px;
background: blue;
color: white;
border: none;
height: 40px;
padding: 0 12px;
font-size: 14px;
}

p {
  display: block;
  max-width: 80px;
  background: white;
  border-radius: 6px;
  padding: 20px;
}

A: Codingwithmanny beat me to it.
Put the axios call in it's own function, and passdown the function to the button component.
Quote.js:
import React, { useState, useEffect } from "react";
import Buttons from "../buttons/Buttons";
import axios from "axios";

const Quote = () => {
  const [quotes, setQuotes] = useState("");

  const fetchQuotes = () => {
    axios
      .get("https://geek-jokes.sameerkumar.website/api?format=json")
      .then(res => {
        setQuotes(res.data);
        // console.log(res.data);
      })
      .catch(err => console.log(err));
  };
  useEffect(() => {
    console.log("new quote requested");
  }, [quotes]);

  return (

       {quotes.joke}
      <Buttons quotes={quotes} getNewQuote={fetchQuotes} />

  );
};

export default Quote;

Buttons.js
import React from "react";

const Buttons = ({ quotes, getNewQuote }) => {
  const twitterUrl = `https://twitter.com/intent/tweet?text=${quotes.joke}`;
  //   console.log(twitterUrl);

  return (

      <button
        onClick={() => window.open(twitterUrl, "_blank")}
        className="twitter-button"
        id="twitter"
        tittle="Tweet This!"
      >

      </button>
      <button id="new-quote" onClick={getNewQuote}>
        New Quote
      </button>

  );
};

export default Buttons;

Codesandbox: https://codesandbox.io/s/quote-generator-heufm

A: You Should call New Qoute API on button click.
you button Component
import React from "react";

const Buttons = ({ quotes, getNewQuote }) => {
  const twitterUrl = `https://twitter.com/intent/tweet?text=${quotes.joke}`;
  //   console.log(twitterUrl);

  return (

      <button
        onClick={() => window.open(twitterUrl, "_blank")}
        className="twitter-button"
        id="twitter"
        tittle="Tweet This!"
      >

      </button>
      <button id="new-quote" onClick={getNewQuote}>
        New Quote
      </button>

  );
};

export default Buttons;

Your Qoute component:
import React, { useState, useEffect } from "react";
import Buttons from "../buttons/Buttons";
import axios from "axios";

const Quote = () => {
  const [quotes, setQuotes] = useState("");
  useEffect(() => {
    axios
      .get("https://geek-jokes.sameerkumar.website/api?format=json")
      .then(res => {
        setQuotes(res.data);
        // console.log(res.data);
      })
      .catch(err => console.log(err));
  }, []);

  const getNewQuote = () => {
    axios
      .get("https://geek-jokes.sameerkumar.website/api?format=json")
      .then(res => {
        setQuotes(res.data);
        // console.log(res.data);
      })
      .catch(err => console.log(err));
  }

  return (

       {quotes.joke}
      <Buttons quotes={quotes} getNewQuote={getNewQuote}/>

  );
};

export default Quote;

A: You can do something like this.
In the Quote.js create getNewQuote function and call that function inside the useEffect.
Then, pass the getNewQuote function to the Button component and on New Quote button onClick set getNewQuote.
Here is your upgraded sandbox -> link
Quote.js
const Quote = () => {
  const [quotes, setQuotes] = useState("");
  useEffect(() => {
    getNewQuote();
  }, []);

  const getNewQuote = () => {
    axios
      .get("https://geek-jokes.sameerkumar.website/api?format=json")
      .then(res => {
        setQuotes(res.data);
        // console.log(res.data);
      })
      .catch(err => console.log(err));
  };

  return (

       {quotes.joke}
      <Buttons getNewQuote={getNewQuote} quotes={quotes} /> // here you pass the getNewQuote function to the Buttons component

  );
};

Buttons.js
const Buttons = ({ quotes, getNewQuote }) => {
  const twitterUrl = `https://twitter.com/intent/tweet?text=${quotes.joke}`;
  //   console.log(twitterUrl);

  return (

      <button
        onClick={() => window.open(twitterUrl, "_blank")}
        className="twitter-button"
        id="twitter"
        tittle="Tweet This!"
      >

      </button>
      <button id="new-quote" onClick={getNewQuote}> // here onClick you call the getNewQuote function
        New Quote
      </button>

  );
};


text:
Q: Is there a way to communicate to the standard tabset component in FlexiPage to add a tab or switch a tab? Is there a way to communicate to the standard tabset component in FlexiPage to add a tab or switch a tab?
We deliver a FlexiPage as a part of a managed package. Inside that FlexiPage we provide options to customize it and add a different LWC to it. On a click of button in one LWC we would like to switch the tab in the Flexi Page or add a new tab dynamically.
Is this possible?

A: Looks like this is not possible.
Also it is not possible to change active tab.
If we set activeTabValue then the tab is not shown as selected.
However, there is a lwc counterpart example here
which can be used and extended to support the necessary functionality in a custom tabset component


text:
Q: Is there an easy way with (T-)SQL to transform rows into columns like this? So let's say I have 3 tables like
       Questions
========================
 id |     qtext
========================
 1  | "What is 3 x 23?"
------------------------
 2  | "Your age?"

      Registrants
========================
 id |    name
========================
 1  | "Jason"
------------------------
 2  | "Subhasish"

               Answers
======================================
 registrant_id | question_id  | val
======================================
      1        |       1      |  69
--------------------------------------
      2        |       2      |  45
--------------------------------------
      1        |       2      |  26

Is there a way to create from this a table like
                  AnswersByPartner
==================================================
     Name     |   "What is 3 x 23?" | "Your age?"
==================================================
   "Jason"    |         69          |    26
--------------------------------------------------
  "Subhasish" |        NULL         |    45

A: Yes! Here you go (Please check the column names for typo's):
DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX);

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.qtext)
            FROM Questions c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

set @query = 'SELECT Name, ' + @cols + ' from
            (
                select r.name, a.val,q.qtext from
                registrants r
                inner join answers a
                on r.id = a.registrant_id
                inner join questions q
                on q.id = a.question_id
           ) x
            pivot
            (
                 max(val)
                for qtext in (' + @cols + ')
            ) p '

execute(@query)

A: I always liked doing it like this:
select
   R.name as Name,
   A1.val as [What is 3 x 23?],
   A2.val as [Your age?]
from Registrants R
left join Answers A1 on R.id = A1.registrant_id and A1.question_id = 1
left join Answers A2 on R.id = A2.registrant_id and A2.question_id = 2


text:
Q: Random error on application run alright, weird problem here.
Cant figure out how to solve it...
My app has been running awesome until it randomly said there was an error while running. Like, it will be fine but as soon as i hit run, it will stop and say the project contains errors. But it doesn't. I have even cleaned and closed the project. See pic below...
Any ideas!?!?

A: Check your error log. It should be in one of the tabs where LogCat is. It should tell you exactly where the problem is.
Alternatively, expend your projects folders until you locate the file that has the red X box on it, that file contains an error if it's


text:
Q: Deriving a formula for an arbitrary term in $1, 2, 3, 3, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, \ldots$ A sequence of numbers is given as:
$$1, 2, 2, 3, 3, 3, 4, 4, 4, 4, \text{and so on}$$
(Each integer $n$ is repeated $n$ times.) What will be the 50th term of that sequence?
Let's say $x=50$. Then solving $x=n(n+1)/2$ gives the value of $n$ (rounded off to nearest integer).
My question is: If I make a small change in the above pattern, can we have a direct formula to calculate $n$?

The new pattern is :
  $$1, 2, 3, 3, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, \ldots$$
  i.e., $1$ and $2$ are repeated once, and $n$ is repeated $(n-1)$ times.
How can we derive a formula for this pattern?

A: Using JMoravitz hint above, you can replace $x$ with $x-1$ and $n$ with $n-1$ and now your formula is $x-1=(n-1)(n)/2$.  Whatever you get for n should be rounded up to the nearest integer if it isn't an integer already.
For example for $x=5$, we have $4 = (n-1)(n)/2 \to 8 = (n-1)(n) \to n^2-n-8=0 \to n=3.37$ which rounds up to 4.


text:
Q: Segmentation fault (11) in MPI Program I am creating a program to calculate the mean and standard deviation as well as print the array. When I am running the program, I am getting a segmentation fault error.
***Process received signal***
Signal: Segmentation fault(11)
Signal code: Address not mapped(1)
Failing at address: 0x1da8000

I cannot see any error in my code:
void printArray(int *array, int array_size){
for(int i = 0; i <array_size; i++){
    std::cout<<array[i]<<", ";
    if(i%10==9)
        std::cout<<std::endl;
    }
}

std::cout<<std::endl;
int sumArray(int *array, int array_size){
    int sum = 0;
    for(unsigned int i = 0; i < array_size; i++)
       sum += array[i];
    return sum;
}

float sumDifferences(int *array, int size, int average){
    float sumDifference;
    for(int i = 0; i<size; i++){
        float differenceSquare = (array[i]-average)*(array[i]-average);
        if(i==0)
            sumDifference = differenceSquare;
        else
            sumDifference = sumDifference= differenceSquare;
    }
    return sumDifference;
}
double fRand(double min, double max){
     double f = (double)rand() / RAND_MAX;
     return min + f * (max - min);
}
void coordinator(int world_rank, int world_size){
    int array_size = 100000;
    int array[array_size];
    int totalDiffSum;
    int totalMean;

    for(unsigned int i = 0; i <array_size; i++)
        array[i]=fRand(0, 51);
    int partition_size = array_size/world_size;
    std::cout<<"coordinator rank 0 partition size is " <<partition_size << std::endl;

    int *partition = new int[partition_size];
    MPI_Bcast(&partition_size, 1, MPI_INT, 0, MPI_COMM_WORLD);
    MPI_Scatter(array, partition_size, MPI_INT, partition, partition_size, MPI_INT, 0, MPI_COMM_WORLD);

    int sum = sumArray(partition, partition_size);
    int mean = sum / partition_size;
    MPI_Reduce(&mean, &totalMean, 1, MPI_LONG_LONG_INT, MPI_SUM, 0, MPI_COMM_WORLD);
    int average = totalMean / world_size;

    MPI_Bcast(&average, 1, MPI_INT, 0, MPI_COMM_WORLD);
    int sumDiff = sumDifferences(partition, partition_size, average);

    MPI_Reduce(&sumDiff, &totalDiffSum, 1, MPI_LONG_LONG_INT, MPI_SUM, 0, MPI_COMM_WORLD);
    double standardDeviation = sqrt(totalDiffSum / array_size);

    printArray(array,array_size);
    std::cout<<"Mean = "<<mean<<std::endl;
    std::cout<<"Standard Deviation = "<<standardDeviation<<std::endl;
    delete partition;
}

void participant(int world_rank,int world_size){
    int partition_size = 0;
    int totalMean;
    int totalDiffSum;
    int* array;

    MPI_Bcast(&partition_size, 1, MPI_INT, 0, MPI_COMM_WORLD);
    int *partition = new int[partition_size];

    MPI_Scatter(&array, partition_size, MPI_INT, partition, partition_size,MPI_INT, 0, MPI_COMM_WORLD);
    int sum = sumArray(partition, partition_size);
    int mean = sum / partition_size;

    MPI_Reduce(&mean, &totalMean, 1, MPI_LONG_LONG_INT, MPI_SUM, 0, MPI_COMM_WORLD);
    int overallAverage = 0;

    MPI_Bcast(&overallAverage, 1, MPI_INT, 0, MPI_COMM_WORLD);
    int sumDiff = sumDifferences(partition, partition_size, overallAverage);

    MPI_Reduce(&sumDiff, &totalDiffSum, 1, MPI_LONG_LONG_INT, MPI_SUM, 0, MPI_COMM_WORLD);
    delete partition;
 }
int main(int argc, char **argv){
    MPI_Init(NULL,NULL);
    int world_size,world_rank;
    MPI_Comm_size(MPI_COMM_WORLD, &world_size);
    MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);

    if(world_rank==0)
        coordinator(world_rank,world_size);
    else
        participant(world_rank,world_size);
    MPI_Finalize();
}

I would really appreciate any advice as I am new to c++ and I have never encountered this error before. Thanks in advance.


text:
Q: spring autowired aop circular dependency I'm using java config with @ComponentScanin order to initialize my beans
and @EnableAspectJAutoProxy(proxyTargetClass=true)to use cglib proxies.
In this project we have a lots of generated services autowired between them using @Autowired. It works pretty well.
But, for some of these services I've added @Async (I've also added @EnableAsync(proxyTargetClass = true)on my @Configurationclass).
After that, I'm getting:
Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'ConversationUserLocalService': Bean with name 'ConversationUserLocalService' has been injected into other beans [ConversationUserHistoryLocalService] i
n its raw version as part of a circular reference, but has eventually been wrapped. This means that said other beans do not use the final version of the bean. This is often the result of over-eager type matching - consider using 'getBeanNamesOfType' with the 'a
llowEagerInit' flag turned off, for example.

I guess this is because Spring is injecting the service with @Asyncmethod BEFORE AOP creates the proxy.
Could this be the problem?
How I should fix it?
In order to try to clarify my problem, let's say I have:
@Service A, B & C;
A has autowired B & C, B has autowired A & C, C has autowired A & B;
C has a method marked as @Async.
When Spring initialize applicationContext, it tries to initialize A, but needs B & C, so it initializes them. But after all, AOP tries to make a proxy of C (because @Async) and then it detects that autowired C into B and A is not the same as proxy of C so it fails.
I hope this can explain a little more what is happening.

A: Finally I sorted it out using @Lazyon services (with methods annotated with @Async), and also, where they were autowired.
This way I guess Spring only initialize and autowires those services when they're required instead of on application context initialization.

A: I have same issue and I solved this issue:

*

*I identified which @Autowired property is reason for circular dependency.
Eg:
@Autowired
private TestService testService;

(Tips to identified just try to comment and find out which property is reason to break the application)

*Once identified just use @Lazy on top of this @Autowired variable.
Eg :
@Lazy
@Autowired
private TestService testService;

And Application worked smoothly.

A: AsyncConfigurer configuration classes get initialized early in the application context bootstrap. If you need any dependencies on other beans there, make sure to declare them @Lazy as far as possible in order to let them go through other post-processors as well.
Reference JavaDoc: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/annotation/EnableAsync.html

A: I managed to fix a similar issue by adding @Qualifier together with @Autowire, for example:
@Autowired
@Qualifier("publisher")
private Publisher publisher;


text:
Q: How can authenticate user by only ip address in spring security? I have table with users. There is "ip_address" column in this table.
I have server - java server
I have web app on spring boot.
Spring boot communicates with java server by rest.
I need realize authonticate user in system by ip.
Whem user open web page - spring boot app get remoteIpAddress(String ipAddress = request.getRemoteAddr();) and pass it to java server in url. java server ckeck this ip in db in table users and if user can login return this user to spring boot app.
I want realize this with spring security. But when i open web page, in browser opened dialog window for input login and password. But I do not need login and password. I need if user is not null - give access to pages and save the user.
and if I input login and password and press "ok" button I move to my IPAddressBasedAuthenticationProvider
@Component
public class IPAddressBasedAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    AuthService authService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String ipAddress = request.getRemoteAddr();
        AuthLkUser authLkUserByIp = authService.getAuthLkUserByIp(ipAddress);

        if (authLkUserByIp == null) return null;

        boolean b = authService.checkAuthLkUser(authLkUserByIp);
        if (b) return null;
        final List<GrantedAuthority> grantedAuths = new ArrayList<>();
        GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_ADMIN");
        grantedAuths.add(grantedAuthority);
        UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(authentication.getName(), authentication.getCredentials(), grantedAuths);
        result.setDetails(authentication.getDetails());
        return result;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}

And in this class saved user to session. And after that when I open web pages i not need input login and password. it contains in session. but my wep page not openned with error
Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.
Mon Jul 11 14:27:59 ALMT 2016
There was an unexpected error (type=Forbidden, status=403).
Access is denied

A: For Spring Boot applications that run with the embedded Apache Tomcat container,  you can use the org.apache.catalina.filters.RemoteAddrFilter  from Apache Tomcat.
 @Bean
 public FilterRegistrationBean remoteAddressFilter() {
  FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
  RemoteAddrFilter filter = new RemoteAddrFilter();
 // filter.setAllow("127.0.0.1");
  filter.setAllow("127\\.0\\.0\\.1");
  filterRegistrationBean.setFilter(filter);
  filterRegistrationBean.addUrlPatterns("/gs/serving-web-content/testParameters");
  return filterRegistrationBean;
 }

allow :    A regular expression (using java.util.regex) that the remote
  client's IP address is compared to. If this attribute is specified,
  the remote address MUST match for this request to be accepted. If this
  attribute is not specified, all requests will be accepted UNLESS the
  remote address matches a deny pattern.

You can refer this article - How do I restrict access to my application by IP address?

A: You can use Expression-Based Access Control provided by Spring. To secure individual URL, you are able to do something like this:
<http use-expressions="true">
    <intercept-url pattern="/admin*"
        access="hasRole('admin') and hasIpAddress('192.168.1.0/24')"/>
    ...
  </http>

Where you created expression like if he has role admin and his IP address is xxx.xxx.x.x, then it is allowed. So you are looking for hasIpAddress.
More about expression-based access control is in their docs.
If you want to create this restrictions for Spring Boot and if you are using Apache Tomcat, then you are able to  to enable a Servlet Filter (here is description) and then you can just enable Remote Address Filter and then set addresses which you want to allow. More abouy this filter is in Apache Tomcat docs.
And another one option is that if you will use Spring Security. There is class WebAuthenticationDetails which provide method getRemoteAddress().


text:
Q: Can we manage MS Word formats using HTML? I am going to generate a word document according to html page. I need some formatting like page break and customize heading of the document such as .can i achieve them using html?

A: I'm not sure how you would go about customizing the header using HTML. In general, what you're planning on doing is probably a bad idea. I would look at libraries that let you generate regular .docx files (the Word XML format).
With that said, I think you can get your page breaks with:
<br clear="all" style="mso-special-character:line-break; page-break-before:always" />

A: Pure HTML would be hard. But keep in mind the current Word-Dokument-Format is OPENXML (or sort of Microsoftish).
I bet there are libraries that could help you assemble or compile word doxs with javascript.
Generate office open XML excel file from javascript
http://openxmldeveloper.org/blog/b/openxmldeveloper/archive/2012/08/02/working-with-open-xml-documents-using-javascript.aspx
http://openxmldeveloper.org/wiki/w/wiki/open-xml-and-javascript.aspx
as far as I know a page-break in OpenXml could be acomplished like this...
    <w:p>
  <w:r>
    <w:br w:type="page" />
  </w:r>
</w:p>

HTH

A: Maybe. Select the page in the browser and use cut&pase. Word does recognize HTML in the clipboard and then tries its best to preserve the formatting.
If you need something more complex, you need to write a program that converts HTML to the OOXML format.


text:
Q: Joining two JSON objects in Node-RED it's pretty simple. I have two flows in Node-RED, each of them carrying a JSON object.
As you can see here:

Originally on the first path, I created a new JSON object using the Template Node, which then was passed to the next node. Which works just fine.
Now, I have two flows from which I want to extract data.
Problem: The Template node only takes one input at a time.
The result is two separated new JSON objects.
But, my target case is this combined JSON object:
{
    "followupEventInput": {
        "name": "{{response.prevIntent}}-{{response.utterances_tone.0.tones.0.tone_id}}",
        "parameters": {
            "tone_id": "{{response.utterances_tone.0.tones.0.tone_id}}"
        },
        "languageCode": "en-US"
  }
}

response.utterances_tone.0.tones.0.tone_id coming from the first flow.
response.prevIntent coming from the second flow.
It's not possible to pass the information I need through the first flow, because the information gets lost when passing the Tone Analyzer node.
I tried to work with Split & Join nodes but it just gets messy.
Have you any idea how this could be implemented smoothly?

A: Have a look at the join node.
This node has a number of modes, but you want the one that counts incoming messages before the outputting and object.
This will output a message with all the fields available, but you will probably need to use a function or change node to rearrange the structure to the one you want.

A: The simplest method is to "chain" your two functions together into one flow -- it sounds like you tried to do this already, without success:

It's not possible to pass the information I need through the first
  flow, because the information gets lost when passing the Tone Analyzer
  node.

So it seems that the Tone Analyzer node's output replaces the previous payload, instead of merging it together -- which is to be expected.
A solution is to put a change node after each function -- use it to Move: msg.response to another property, say msg.response1 and msg.response2. Then you can use a template node to build the output structure you need. The "mustache" syntax you showed should work, if you pull the text from the response1 and response2 properties, like so:
{
    "followupEventInput": {
        "name": "{{response2.prevIntent}}-{{response1.utterances_tone.0.tones.0.tone_id}}",
        "parameters": {
            "tone_id": "{{response1.utterances_tone.0.tones.0.tone_id}}"
        },
        "languageCode": "en-US"
    }
}

Just make sure the set the template node to "Output as: Parsed JSON".
Oh, btw, you can probably replace your "Parse JSON" function node with the core json node, which does the parsing for you...


text:
Q: About array of objects I made an application that takes the map coordinates and shows them on the map. I'm getting coordinates (in lng and lat) from a file with a Json extension. I assigned the relevant key values to the row in the row (called markers). but the problem is this: I want to do this with the help of the for loop and I want to put the relevant keys in the index. so when I open the program I do not want to manually assign the markers' items according to the number of information in the .json extension file. I want to read information from .json file and assign values to the keys (by loop) in the markers' directory. Could you help me with this problem?
<script type="text/javascript" src="data.json"></script>
<script type="text/javascript">
var mydata = JSON.parse(data);
    var markers = [
        {
            "title": mydata[0].yer,
            "lat": mydata[0].lat,
            "lng": mydata[0].lng,

        }
    ,
        {
            "title": mydata[1].yer,
            "lat": mydata[1].lat,
            "lng": mydata[1].lng,

        }
    ,
        {
            "title": mydata[2].yer,
            "lat": mydata[2].lat,
            "lng": mydata[2].lng,
        }];

my json file:
    data = '[{"yer" : "Besiktas", "lat" : "41.044161", "lng" : "29.001056"},{"yer" : "Eminönü", "lat" : "41.017513", "lng" : "28.970939"},{"yer" : "Zeytinburnu", "lat" : "40.990828", "lng" : "28.895325"}, {"yer" : "Aydın Üniv.", "lat" : "40.995836", "lng" : "28.797562"}]';

A: var markers = mydata.map(function(location) {
  return {
    title: location.yer,
    lat: location.lat,
    lng: location.lng
  };
});

map is a useful method for achieving what you're trying to do here.  The above should work and give the desired result.


text:
Q: Query to get roles and permissions granted to Azure SQL Database? I executed the following script to create mydb_user and mydb_admin with limited permissions.
STEP1: Ran these scripts on azure masterdb
CREATE LOGIN mydb_admin
WITH PASSWORD = 'nnn'
GO
CREATE LOGIN mydb_user
WITH PASSWORD = 'nnnnnnnnn'
GO

Step2: Ran the below scripts on the actual azure db  eg., mydb
CREATE USER mydb_admin  FROM LOGIN mydb_admin ;
EXEC sp_addrolemember 'db_datareader', 'mydb_admin';
EXEC sp_addrolemember 'db_datawriter', 'mydb_admin';
GRANT CONNECT TO mydb_admin;
GRANT SELECT TO mydb_admin;
GRANT EXECUTE ON [dbo].[procDumpRowsInto_De_Common] TO [mydb_admin] AS [dbo]

CREATE USER mydb_user FROM LOGIN mydb_user;
EXEC sp_addrolemember 'db_datareader', 'mydb_user';
EXEC sp_addrolemember 'db_executor', 'mydb_user';
GRANT CONNECT TO mydb_user;
GRANT SELECT TO mydb_user;

Now I want to see if the roles and permissions are set correctly. Is there a query that I can run to see this? For instance, I want to see the effective roles and permissions for dbusers mydb_user,mydb_admin on my database myDb?

A: You are right, fn_my_permissions is not there on Azure SQL DB. You can call select HAS_PERMS_BY_NAME (db_name(), 'DATABASE', 'SELECT'), or other permission you want to check for, to check whether a specific permission is granted or not either directly or via a role.


text:
Q: flutter web blank screen after importing cloud firestore dependency flutter web blank screen after importing cloud firestore dependency
and work well after removing it
and by running with debugging this error appears

web_entrypoint.dart
// @dart=2.12
// Flutter web bootstrap script for package:booky/main.dart.

import 'dart:ui' as ui;
import 'dart:async';

import 'package:booky/main.dart' as entrypoint;
import 'package:flutter_web_plugins/flutter_web_plugins.dart';
import 'package:booky/generated_plugin_registrant.dart';

typedef _UnaryFunction = dynamic Function(List<String> args);
typedef _NullaryFunction = dynamic Function();
Future<void> main() async {                                       **// this is the error**
  registerPlugins(webPluginRegistrar);
  await ui.webOnlyInitializePlatform();
  if (entrypoint.main is _UnaryFunction) {
    return (entrypoint.main as _UnaryFunction)(<String>[]);
  }
  return (entrypoint.main as _NullaryFunction)();
}

pubspec.yaml
environment:
  sdk: ">=2.12.0 <3.0.0"

dependencies:
  cloud_firestore: "^2.5.3"
  firebase_auth: ^3.1.4
  firebase_core: ^1.8.0
  cloud_firestore_web: ^2.4.4
  flutter:
    sdk: flutter

  flutter_test:
    sdk: flutter


text:
Q: The political parties expressed support to / for the strike
The politicians  expressed   their support  to  the  strike / to  the  trade  unions

The  English  professor  I  know  told  me  that  we  exprees  our  support  for something but  not  express support  to  the  strike  or  to  the  trade  unions.
I  think :

The  politicians  extended  their  support  to  the  strike  or  to  the  trade  unions   is  correct.

We  find  the  expression  The political  parties  expressed  their  support to  the  strike  or  to  the  trade unions  in some  English  news  papers  in India.

I would  like to  know  whether  both  the  expressions  express support  to/ extend  support  to  the  strike  are  correct or  only  extend  support  to  the  strike  is  correct?

A: You express support for a cause. You can express that support to a particular person or group.

Alice expressed to Bob her support for the new policy.

*

*Alice expressed her support for the new policy. (To whom Alice expressed her support is not stated.)

*Alice expressed her support to Bob. (What Alice supports is not stated.)

Alice supports the new policy, and communicated that fact to Bob.

To "extend" support has a more narrow usage: it is only appropriate when the subject is taking specific action to directly aid a specific person or group of people. If you "extend your support to the local food kitchen" it means you give them a donation or put in some volunteer hours. If your support is simply ideological, you are not "extending" support.
That said, Indian dialects of English are well-known for using words in ways that speakers of older varieties of English (e.g., American and British English) would find odd, awkward or even incorrect. Such could conceivably be the case here.


text:
Q: How can I connect my flutter app to my azure database? I made a database in Azure and it is updated every day with more data. But now I want to retrieve some data from the azure database to my flutter app. But do not know how to make a connection between flutter and azure DB.
Thank you!

A: Your flutter app cannot connect to the Azure SQL database. You need to create a REST API, which will expose data from your database to your mobile app.
You can create an API with ASP.NET CORE, Node.JS, Python, etc.
Here are some resources that can help you :
https://www.tutorialspoint.com/flutter/flutter_accessing_rest_api.htm
https://flutter.dev/docs/cookbook/networking/fetch-data
https://learn.microsoft.com/en-us/azure/azure-sql/database/connect-query-nodejs


text:
Q: Tcl script to search strings and store in variable Loop = (
      {
        Value = (
          {
           {
            Key :
            {
              A = "B";
              C = "D";
              Class = (
                {
                  section = "section_a";
                  Pairs = (
                    {
                      Name = "Ram";
                      Mark = "80";
                    },
                    {
                      Name = "Latha";
                      Mark = "70";
                    },
                    {
                      Name = "Mohan";
                      Mark = "90";
                    },
                    {
                      Name = "David";
                      Mark = "76";
                    } );
                } );
              Id = 1;
            };
            Absent :
            {
              DAYS = "Two days";
            };
          },
           {
            Key :
            {
              A = "B";
              C = "D";
              Class = (
                {
                  section = "section_b";
                  Pairs = (
                    {
                      Name = "Ram";
                      Mark = "30";
                    },
                    {
                      Name = "Latha";
                      Mark = "45";
                    },
                    {
                      Name = "Mohan";
                      Mark = "100";
                    },
                    {
                      Name = "David";
                      Mark = "76";
                    } );
                } );
              Id = 2;
            };
            Absent :
            {
              DAYS = "Four days";
            };
          },
          } );
      } );

I am new to tcl script. I have a txt file in a above format. Using tcl script I have to store strings(section, Name , mark and Absent days) in a different variables to store in a csv file.
I tried below code to search the word Key
set search "Key"
set file [open "Marks.txt" r]
 while {[gets $file data] != -1} {
    if {[string match *[string toupper $search]* [string toupper $data]] } {
        puts "Found '$search' in the line '$data'"
    } else {
        puts "does not match"
    }
 }

It is working to find the word key and printing whenever it matches. It works for that line which has the word Key. But, here I want to find the word Loop then I want search for the word Key in side loop. If it sees the word Key then it has to copy some strings present in the loop to variables. The word Key will be repeated in the files multiple times. After the word Key there will be {..} all over there file has some content. The script has to read the content and store it in some variable.
Exp: The script need to find the word Key in the text file, then look for the
section if present then section_b need to be stored in variable temp1(exp. temp1=section_a), Like wise:
If it sees Ram then Mark below the line needs to be stored in temp2 (exp. temp2=80).
If it sees Latha then Mark below the line needs to be stored in temp3 (exp. temp3=70).
then find id and need to to store the value 1 need to be stored in temp4(exp. temp4=1).
then Days meed to be stored in temp5(exp. temp5=Two days)
These temp values need to be written in the csv file everytime when it sees the word Key in the text file in below format.
section     Ram  Latha   id    Days
Section_a    80   70     1    Two days
Section_b    30   45     2    Four days

Can you help me in writing the tcl script to get this. Thank you.

A: This is the kind of thing that awk is really good for:
awk '
    function quoted(string,     a) {
        split(string, a, /"/)
        return a[2]
    }
    BEGIN { OFS="\t"; print "section", "Ram", "Latha", "id", "Days" }
    $1 == "section" {section = quoted($0); delete marks}
    $1 == "Name" {name = quoted($0)}
    $1 == "Mark" {marks[name] = quoted($0)}
    $1 == "Id" {id = gensub(/;/, "", 1, $3)}
    $1 == "DAYS" {print section, marks["Ram"], marks["Latha"], id, quoted($0)}
' file

Translating that as a Tcl "one-liner", I'd write
echo '
    proc trim {str} {string trim $str {"}}
    puts "section\tRam\tLatha\tid\tdays"
    set fh [open [lindex $argv end]]
    while {[gets $fh line] != -1} {
        if {[regexp -- {(\S+) = ("[^"]+"|\d+);} $line -> key value]} {
            switch -exact -- $key {
                section {set section [trim $value]; array set marks {}}
                Name    {set name [trim $value]}
                Mark    {set marks($name) [trim $value]}
                Id      {set id $value}
                DAYS    {puts [join [list $section $marks(Ram) $marks(Latha) $id [trim $value]] \t]}
            }
        }
    }
' | tclsh - file


text:
Q: Ad cell after every five cells in tableview I need add an ad cell with only image after every five news cells in table view.
If I will add second section for ad cells, an ad cell will be shown after all news cells.
If I will add an ad cell when indexPath.row == 4, my fifth news cell won't appear because of cell.details = news[indexPath.row].
Any suggestions how can I do that? Thanks.

A: In the method cellForRowAtIndexPath of UITableViewDataSource do next:
if (indexPath.row % 5 == 0) {
// configure ad cell
} else {
// configure usual cell with news[indexPath.row - (indexPath.row / 5)]
}

A: You need to figure out a system to get the right data for your cells:

0 NEWS
1 NEWS
2 NEWS
3 NEWS
4 NEWS
5 AD     <----- "5." => (currentRow % 5 == 0)
6 NEWS    <----- "6." => (6 - (currentRow / 5)

You see a system?
You can do something like:
if ((row % 5) == 0) {
    //Ad stuff here
} else {
    data = tabledata[row - (row/5)];
    //news stuff here using data
}

A: do like this ..
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 5;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;//add your own number, might be totalNumberOfNewsItems/5
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
 {
   int reqIndex = indexPath.section*(5) + indexPath.row;
   // get data from array like news[reqIndex];
 }
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
  // return your ad view based on section value
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 44; // change to your required value
}

A: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row % 5 == 0) {
       //configure ad cell
    } else {
       //configure usual cell
    }
}


text:
Q: How to jump to a specific ride over the deep link API is there a way to jump directly to a specific ride over the Uber deep link API? With the setPickup action I can directly request a new ride. Is there an action like 'showPickup' which would open the Uber app and jump directly to a specific ride?
Thanks for a reply
Jean-Marc

A: No, it is not currently possible to go to a specific ride id. That said, it shouldn't ever be needed as Uber only support a single ride per rider at any given time so if you open the app while the user is on-trip it will always open to the existing ride.


text:
Q: Is there a way/hint to extract dictionary in between in a given condition? Given a dictionary:
{0: 'Hello', 1: 'Bob', 2: '!', 3: 'Hello', 4: 'Bob', 5: '?', 6: 'Hello', 7: 'Bob', 8: '!', 9: 'Hello', 10: 'Jane', 11: '!', 12: 'Hello', 13: 'Rob', 14: '?'}

I wanted to extract these texts, inclusively, in between the pairs 'Hello' and '!' and ignore pairs 'Hello' and '?' but I am currently stuck. I just need a nudge in the right direction will do.
So far I have attempted to slice them and got the following result:
{0: 'Hello', 2: '!', 3: 'Hello', 5: '?', 6: 'Hello', 8: '!', 9: 'Hello', 11: '!', 12: 'Hello', 14: '?'}

but now I have no clue how to pair the values. For example pairs 0,2 then pairs 7,8 then finally 9,11.
Here is the method I made
def split(array):
    print(array)
    names = {'Hello','?','!'}
    lst = {key:value for key, value in array.items() if value in names}
    print(lst)

A: If the dictionary is based on 3 value sequence, like 'Hello', then a name the '!' or '?' then the solution is quite simple. But first you must not assume order upon the dictionary. So I first convert it to a list of pairs and sort them:
>>> lst = sorted(d.items())
>>> lst
[(0, 'Hello'), (1, 'Bob'), (2, '!'), (3, 'Hello'), (4, 'Bob'), (5, '?'), (6, 'Hello'), (7, 'Bob'), (8, '!'), (9, 'Hello'), (10, 'Jane'), (11, '!'), (12, 'Hello'), (13, 'Rob'), (14, '?')]

Next, I need only the names. The indexes are implied:
>>> names = [name for num, name in lst]
>>> names
['Hello', 'Bob', '!', 'Hello', 'Bob', '?', 'Hello', 'Bob', '!', 'Hello', 'Jane', '!', 'Hello', 'Rob', '?']

Finally, extract the indexes you need:
>>> indexes = [i for i in range(0, len(names), 3) if names[i] == 'Hello' and names[i+2] == '!']
>>> indexes
[0, 6, 9]


text:
Q: Is it possible to plot model so that convolution kernel sizes also displayed in Keras? I want to plot Keras deep learning model but found that plot_model does not show convolution kernel sizes. Is it possible to show them somehow?

A: As far as i know it is not possible currently, but you can always adjust the code itself. Just copy the code from https://github.com/fchollet/keras/blob/master/keras/utils/vis_utils.py and program an additional parameter like show_shapes that outputs the kernel size.


text:
Q: Send string from thread bluetooth service to textView in main activity I want to send value from string (distance to obstacle) to my TextView in main activity.
I tried to use Handler, but still not working (crash) or receive nothing.
A part code which receive data from HC-05 (screen where you see in debug value assignet to variable)
enter image description here
@Override
        public void run() {
            byte[] buffer = new byte[1024];
            int bytes;
            while(true){
                try {
                    bytes = inputStream.read(buffer);
                    final String comingMsg = new String(buffer,0,bytes);
                    Log.d(TAG,"InputStream: " + comingMsg);
                    /*mHandler2.post(new Runnable() {
                        @Override
                        public void run() {
                            Message message = new Message();
                            message.obj = comingMsg;
                            mHandler2.sendMessage(message);
                        }
                    });*/
                }catch (IOException e){
                    Log.e(TAG,"Write: Error reading input." + e.getMessage());
                    active=false;
                    break;
                }
            }
        }

Here It's parts of code from MainActivity where I tried put something to get values from service.
[I add, that for this moment i want to see something values from bluetooth in textView. Later I want to create parse string and send custom text to custom TextView - example: FL: (Front Left)- to one textView, FR: (Front Right) - to second textView]
There is method implementThreads(), because I wanted to do 6 Threads to 6 TextView which every time is refreshing value from string in Services (there I tried get value from Bluetooth Service)
Log.d(TAG,"Check intent - result");
    if(getIntent().getIntExtra("result",0)==RESULT_OK){
        mDevice = getIntent().getExtras().getParcelable("bonded device");
        myBluetoothService = new MyBluetoothService(getApplicationContext());
        startConnection(mDevice,MY_UUID);
        Log.d(TAG,"Check is active service");
        checkIfActive();
    }

    Log.d(TAG,"Check intent - connect_to_paired");
    if(getIntent().getIntExtra("connect_to_paired",0)==RESULT_OK){
        mDevice = getIntent().getExtras().getParcelable("bonded_paired_device");
        myBluetoothService = new MyBluetoothService(getApplicationContext());
        startConnection(mDevice,MY_UUID);
        Log.d(TAG,"Check is active service");
        checkIfActive();
    }

}

@Override
public void onStart(){
    super.onStart();
    myBluetoothService = new MyBluetoothService(getApplicationContext());
}

public void checkIfActive(){
    Log.d(TAG,"CheckIfActive: Started");
    if(myBluetoothService.active){
        Log.d(TAG,"CheckIfActive: Running method implementThreads()");
        implementThreads();
    }
}

public void implementThreads(){
    Log.d(TAG,"ImplementThreads: Started");
    Thread thread = new Thread(){
        @Override
        public void run() {
            try{
                sleep(100);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    };
    thread.start();
}

public void startConnection(BluetoothDevice device,UUID uuid){
    Log.d(TAG,"StartConnection: Initializing connection");
    myBluetoothService.startClient(device,uuid);
}

Thanks all for help, because It's very important for me !

A: Use this to interect with UI Thread for operations like updating textviews etc.
new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    //YOUR CODE HERE
                        Message message = new Message();
                        message.obj = comingMsg;
                        mHandler2.sendMessage(message);
                }
            });


text:
Q: Is it normal for a Graphics card to operate in 90 degree temperature? Is it quite normal that GPU operates under 90+ degrees?
I have two boxes which has nVidia Quadro 580 and 4000.
The first heats up to 60 degrees but Quadro 4000 goes like 70-90 degree. Is this quite normal?

A:
Is this quite normal?

Apparently it is.  From multiple different posts around the internet, it appears that this is considered a video card that runs hot.  Don't worry, there are a bunch of different video cards that are known to run hot.  Since this is a professional grade card, it apparently is configured to run quiet, as opposed to having the fan run loud and cool better.
You may be able to use MSI Afterburner or EVGA Precision or any other overclocking/underclocking software suite to crank the fan up.  Some have had luck doing it this way.
You may also have to remove the heat sink, and repaste the processor.
You may also shave a couple of degrees by adjusting the position of the heat sink.  One screw having been overtightened can make the heat sink sit improperly on the processor... which can result in temps a little higher than expected.
However.... load temps of 70-80c are expected for this card.


text:
Q: Asp.net Windows Authentication Deny Anonymous Access When I RDP to the web server (customer) I enter my user name as domain/username. Which tells me that I am in the AD.
I set the web.config authentication mode="Windows" and Authorization deny="?" (my understanding is that this means deny all who are not authenticated by Windows.)
Then I am trying to open a test page (test.aspx).  And I get Access Denied.
If I set the Authorization to allow users="*", the page opens. But the environment.UserDomainName returns "IIS APPPOOL".  And I would like to see that the environment.UserDomainName would return actual domain name.
What do I need to do? Or what am I missing?

A: If I am understanding your question, you are trying to get the current user. If so you can use something like this:
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;


text:
Q: How to copy remote build files localy as needed? I have a remote server that has cpp header files and endstates (lib/dll/exe) needed to compile projects.  Using the remote server when compiling takes a lot of time with the added overhead of going over the network.  I would like to copy the files locally, but most of the files on the remote server I do not need in order to compile my projects.  Ideally, I would like to setup a locally mounted drive that uses the remote server file setup, but copies the files I need locally as I try to read them.  This way over the corse of a day/week, I can build a local cache of only the files I need.
Is there a way to achieve this or something similar?  My goal is to have a local cache without too many extra files that I won't ever need to compile.
Current, I have a script that uses robocopy to copy what I need locally, but it is difficult to identify what I actually need so I end up pulling more files than nessisary, taking up extra hard-drive space.

A: Have you tried using a back-up program?  Most of them will quickly copy defined directories/files to defined locations.
Cobian back-up (freeware) would do exactly what you need, but there must be dozens of others, so just pick a UI that you like.


text:
Q: Template Doesnot Exist at in Django I am trying to render a template inside a function. Below is my settings.py
TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': ['E:\Django\googlemaps\templates\waypoints'],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
        ],
    },
},

]
and views.py
from django.shortcuts import render_to_response

def index(request):
   'Display map'
    return render_to_response('waypoints\index.html')

And below is my error when i run the server.Please help me.
    http://dpaste.com/0SZAR4H

A: The template you are trying to access is according to the path:
waypoints\index.html

I think it should rather be
waypoints/index.html

A: The problem is that \t in \templates is being treated as a tab character.
The easiest fix is to always use forward slashes. This works, even on Windows.
'DIRS': ['E:/Django/googlemaps/templates/waypoints'],

Your other options are:

*

*use two backslashes, i.e. \\t

*use the r'' prefix i.e. r'E:\Django\googlemaps\templates\waypoints'.

A: I just replaced settings.py shown above by
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(os.getcwd(), "templates"),

)
It worked fine.
But i would like to know what makes the difference.


text:
Q: AWS DMS RDS MySQL 8 Can't initialize character set unknown I am trying to run a replication task (CDC) between a AWS RDS MYSQL 8.0.11 database and a Redshift cluster using DMS.
I run into the error :
Error 2019 (Can't initialize character set unknown (path: compiled_in)) connecting to MySQL server

Replication Instance engine version :   3.1.3
Char sets used by the RDS MySQL instance :
-- SHOW VARIABLES LIKE '%char%';
'character_set_client','utf8mb4'
'character_set_connection','utf8mb4'
'character_set_database','utf8mb4'
'character_set_filesystem','binary'
'character_set_results','utf8mb4'
'character_set_server','utf8mb4'
'character_set_system','utf8'
'character_sets_dir','/rdsdbbin/mysql-8.0.11.R2/share/charsets/'

A: I donot think DMS supports MYSQL 8.X as yet. Supported versions are explained here.

A: According to the AWS documentation:

AWS Database Migration Service (AWS DMS) 3.1.1 Release Notes AWS DMS
  now supports all 4-byte character sets, such as UTF8MB4, and so on.
  This feature works without any configuration changes.

https://docs.aws.amazon.com/dms/latest/userguide/CHAP_ReleaseNotes.html
Some people has gotten this to work using this method:
https://forums.aws.amazon.com/message.jspa?messageID=910772


text:
Q: `Window` `Width` and `Top` have local values My main window's Height, Left, Top, and Width are all bound to their respective viewmodel properties through a style. I can confirm that these four properties in the view model are only ever set to 1920, 1920, 118, 1080 respectively.
But when I launch the app, the Top and Width properties on the main window are set to something else (Width will be 1440 and Top will be a random number usually less than 300). What would cause this?
Here's what I see when I Snoop the app. Notice how Top and Width come from a Local Value Source:

Strangely, when I right-click on those properties in Snoop and tell it to "Clear/Reset", then those properties begin behaving. What is Snoop doing that fixes this?

Other facts:

*

*The getters for the Top and Width viewmodel properties are only called once while the main window is being initialized. The stack trace runs through framework binding initialization code.

*The setters for the Top and Width viewmodel properties are only called once from the viewmodel constructor as it sets those properties to 118 and 1080 respectively.

*The bindings for these four properties are all two-way.

*None of these things cause the view's properties to change/be correct:

*

*Changing the associated viewmodel properties at runtime, even after the view has been fully loaded.

*Calling UpdateLayout() on the view.

*Calling InvalidateArrange() on the view.

*Calling InvalidateMeasure() on the view.

*Calling InvalidateProperty(FrameworkElement.WidthProperty) on the view.

*Calling InvalidateVisual() on the view.

*I have searched and searched and do not see any code anywhere touching the view's Top or Width properties (other than the style bindings).

Here's the style:

Sorry I had to blank out type names and some other things—it's a company application. If it helps, the main window/the view is at the end of a long inheritance line with Window as its great-great grandaddy. I'm trying to make the main window more reusable by MVVM-ing it—formerly these layout properties were set in code-behind in the view, and the view had constructor parameters :'( That's related to why I need to key the style, and why the style is based on other stuff. But none of the inherited types manipulate layout properties.
P.S. I've seen other people complain about how hard it is to resize WPF's Window. The most commonly suggested solution is to bind MinWidth and MaxWidth as well as Width. When I do that then the Width is indeed forced to the value I want, but you can't resize the window, the Width property still has its Local Value Source, and Top is still incorrect.

A: Given that "[Top] cannot be set through a style", and given the complications with binding Window.Width, I solved this a different way.
I created this attached property called WindowLayout and bound it to a viewmodel property in my style:
public static class WindowLayoutBehavior
{
    public static readonly DependencyProperty LayoutProperty = DependencyPropertyHelpers.RegisterAttached(
        (Window x) => GetLayout(x),
        new PropertyMetadata(HandleLayoutChanged));

    private static void HandleLayoutChanged(
        DependencyObject d,
        DependencyPropertyChangedEventArgs e)
    {
        if (!(d is Window window))
            return;
        if (!(e.NewValue is Rect rect))
            return;
        window.Height = rect.Height;
        window.Left = rect.Left;
        window.Top = rect.Top;
        window.Width = rect.Width;
    }

    [AttachedPropertyBrowsableForType(typeof(Window))]
    public static Rect GetLayout(Window window) =>
        window.GetValue(LayoutProperty) is Rect rect
            ? rect
            : default;

    public static void SetLayout(Window window, Rect rect) =>
        window.SetValue(LayoutProperty, rect);
}

DependencyPropertyHelpers.RegisterAttached is a shorthand helper method for creating the attached property in the way you might expect.
Usage in the style:
<Setter
    Property="WindowLayoutBehavior.Layout"
    Value="{Binding WindowLayout, Mode=OneWay}"/>

Now when I Snoop the app, Height, Left, Top, and Width all show as having Local Value Sources, and they change when the viewmodel property changes, so that works for me.


text:
Q: Other than flagging a question should I do anything else with this user? I came across this https://stackoverflow.com/questions/18732485/python-did-gay-sperm-influence-the-python-terminlogy-tuple question which is somewhat offensive and certainly not a question that belongs on the site. I flagged it for a moderator to have a look at, but can't seem to find any guide on whether I should do anything further?
In this case, I am assuming that posting it here will get a mod on the case pretty quickly, but in future, is it just a case of flagging it as per normal and that is enough, or should I do something more?

A: You'll be seeing more questions like this in the future as they're coming from a known troll, so just flag them as offensive whenever you come across them. The idea is to get them deleted as soon as possible so we don't waste too much time.


text:
Q: keeping count and storing of text instances I would like to make a simple code that counts the top three most recurring lines/ text in a txt file then saves that line/ text to another text file (this in turn will be read into AutoCAD's variable system).
Forgetting the AutoCAD part which I can manage how do I in VB.net save the 3 most recurring lines of text each to its own text file see example below:
Text file to be read reads as follows:
APG
BTR
VTS
VTS
VTS
VTS
BTR
BTR
APG
PNG
The VB.net program would then save the text VTS to mostused.txt BTR to 2ndmostused.txt and APG to 3rdmostused.txt
How can this be best achieved?

A: Since I'm C# developer, I'll use it:
var dict = new Dictionary<string, int>();
using(var sr = new StreamReader(file))
{
   var line = string.Empty;
   while ((line = sr.ReadLine()) != null)
   {
     var words = line.Split(' '); // get the words
     foreach(var word in words)
     {
       if(!dict.Contains(word)) dict.Add(word, 0);
       dict[word]++; // count them
     }
   }
}

var query = from d in dict select d order by d.Value; // now you have it sorted
int counter = 1;
foreach(var pair in query)
{
   using(var sw = new StreamWriter("file" + counter + ".txt"))
     sw.writer(pair.Key);
}


text:
Q: Why does the voltage regulator not regulate when ac is around 200V AC? So the voltage regulator works well when the input of the primary winding transformer is at 220V or greater and the 12V regulator does output around 12V. Why is it that when I turn down the variable transformer to say 203V the voltage regulator does not output around 12V and in fact outputs less?
The transformer I have is VC 16/1/9 https://catalog.block-trafo.de/prodvardatasheet/393257-524506_EN and the voltage regulator is an L78S12CV

A: The transformer you've linked is rated for 9VAC at 230VAC input so you're already running under spec if you're trying to get 12V.  The transformer ratio is around 25:1 so 203V would give you around 8VAC.
The 12V variant of the L78S series of regulators has a minimum output voltage of 11.5V and a dropout voltage at 25°C between 1.5-2.5V depending on current draw which means your minimum input voltage would have to be at least 13.5VDC.  This doesn't take into account whatever rectification/smoothing you're doing from the transformer.

A: If we continue your logic, why does the voltage not give out 12 V when the AC voltage is zero?
The answer is that the 78xx series are voltage dropping regulators and need a certain amount of "headroom" to operate.  When you reduce the AC voltage then you also reduce the input voltage to the regulator below that required for correct operation.


text:
Q: TypeError: self.records.find(...) is undefined I inherited a Module Account.voucher to my module and I repeatedly performed onchange function to that field and It throws this error on the Web Browser.
TypeError: self.records.find(...) is undefined

http: //localhost:8069/web/webclient/js?db=sales:3798

I am not a master in JavaScript..
Please help in debugging this Issue

A:  self.Value(self.SelectedRecord(self.Records().find(x => x.record_code() === record_code));


text:
Q: Avoiding long compute acquisition time for sequential dataflows I am experiencing very long compute acquisition times when running flows in sequence (7-8 minutes). I have a pipeline with several flows all running the same integration runtime with TTL = 15 minutes. It was my understanding that several flows executed one after the other and running on the same integration runtime would only incur long acquisition times for the first and not for subsequent flows, but I experience very sporadic behavior with subsequent flows sometimes spinning up very fast and other times much slower (3-8 minutes). How can this be avoided?

A: If you are using sequential data flow activity executions against the same Azure IR in the same data factory using a TTL, then you should see 1-3 minute startup times for each compute environment. If you are experiencing longer latencies, then please create a ticket on the Azure portal.  Make sure you are following the techniques described here and here.