text:
Q: oracle.jbo.NoObjException: JBO-25003: Object  of type DataControl is not found I get the following exception when I am trying to run Oracle ADF on Tomcat 8.5.24 and JRE 1.8.0_201.
oracle.jbo.NoObjException: JBO-25003: Object <ObjectName> of type DataControl is not found.
    at oracle.adf.model.binding.DCIteratorBinding.getCheckedDataControl(DCIteratorBinding.java:2880)
    at oracle.adf.model.binding.DCIteratorBinding.internalGet(DCIteratorBinding.java:5206)
    at oracle.adf.model.binding.DCExecutableBinding.get(DCExecutableBinding.java:119)
    at javax.el.MapELResolver.getValue(MapELResolver.java:62)
    at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
    at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
    at oracle.adf.share.el.VariableResolverELContext$1.getValue(VariableResolverELContext.java:51)
    at org.apache.el.parser.AstValue.getValue(AstValue.java:169)
    at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:184)
    at oracle.adf.share.el.OracleExpressionEvaluatorImpl.evaluate(OracleExpressionEvaluatorImpl.java:148)
    at oracle.adf.share.el.OracleExpressionEvaluatorImpl.evaluate(OracleExpressionEvaluatorImpl.java:103)
    at oracle.adf.share.el.OracleExpressionEvaluatorImpl.evaluateHandleNull(OracleExpressionEvaluatorImpl.java:84)
    at oracle.adf.model.binding.DCUtil.elEvaluate(DCUtil.java:847)
    at oracle.adf.model.binding.DCBindingContainer.evaluateParameterWithElCheck(DCBindingContainer.java:1529)
    at oracle.adf.model.binding.DCParameter.internalEvaluateExpresion(DCParameter.java:276)
    at oracle.adf.model.binding.DCParameter.evaluateValue(DCParameter.java:80)
    at oracle.adf.model.binding.DCParameter.getValue(DCParameter.java:115)
    at oracle.adf.model.binding.DCBindingContainer.getChildByName(DCBindingContainer.java:2818)
    at oracle.adf.model.binding.DCBindingContainer.internalGet(DCBindingContainer.java:2870)
    at oracle.adfinternal.view.faces.model.binding.FacesCtrlSearchBinding.internalGet(FacesCtrlSearchBinding.java:5769)
    at oracle.adf.model.binding.DCExecutableBinding.get(DCExecutableBinding.java:119)
    at javax.el.MapELResolver.getValue(MapELResolver.java:62)
    at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
    at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
    at oracle.adf.share.el.VariableResolverELContext$1.getValue(VariableResolverELContext.java:51)
    at org.apache.el.parser.AstValue.getValue(AstValue.java:169)

When I print the keys of the BindingContext.keySet(), I see the <ObjectName> that is not found but it has the following name structure <ObjectName>@<Path_to_databindings>_DataBindings_cpx. Any help would be appreciated.

A: I found a small workaround for this error programmatically using the Following Code;
BindingContext bc = // Load BindingContext
for (Object k:bc.keySet()) {
    if(k.toString().endsWith("@<Path_to_databindings>_DataBindings_cpx")) {
        String newKey = k.toString().substring(0, k.toString().indexOf('@'));
        bc.put(newKey, bc.get(k));
    }
}


text:
Q: Web scraping with login page I'm trying to use python to scrape a webpage with a login page. I've tried using a few examples from stackoverflow that have been accepted as working examples, but none seem to work for me
Attempt 1:
import requests
from lxml import html

USERNAME = "my username"
PASSWORD = "my password"
TOKEN = "my token"

LOGIN_URL = "https://example.com/admin/login"
URL = "https://example.com/admin/tickets"

session_requests = requests.session()

# Get login csrf token
result = session_requests.get(LOGIN_URL)
tree = html.fromstring(result.text)authenticity_token = list(set(tree.xpath("//input[@name='_token']/@value")))[0]

# Create payload
payload = {
"name": USERNAME,
"password": PASSWORD,
"_token": TOKEN
}

# Perform login
result = session_requests.post(LOGIN_URL, data = payload, headers = dict(referer = LOGIN_URL))

# Scrape url
result = session_requests.get(URL, headers = dict(referer = URL))
tree = html.fromstring(result.content)
bucket_names = tree.xpath("//div[@class='a']/a/text()")

print(bucket_names)

Attempt 2:
import requests
from bs4 import BeautifulSoup

username = 'my username'
password = 'my password'
scrape_url = 'https://example.com/admin/tickets'

login_url = 'https://example.com/admin/login'
login_info = {'name': username,'password': password}

#Start session.
session = requests.session()

#Login using your authentication information.
session.post(url=login_url, data=login_info)

#Request page you want to scrape.
url = session.get(url=scrape_url)

soup = BeautifulSoup(url.content, 'html.parser')

for link in soup.findAll('a'):
print('\nLink href: ' + link['href'])
print('Link text: ' + link.text)

The first example prints the result:
[]

The second give me links from the login page, not links from the main scrape url
I'm really not sure what the problem is, any pointers would be greatly appreciated
Thanks
Ryan

redpajama_set_name: RedPajamaStackExchange


text:
Q: Login into a website from a different website I have two websites. Both websites have a login form.
From Website A I want to login to Website B.
From Website A in my form which posts to Website B. This works and can log me in! However, if anything goes wrong I get the login form on website B telling me the error.
<form action="http://websiteB.mycompany.com/login" method="post">

What I am trying to do now is
    <form action="login" method="post">

This now hits controller on WebSite A. I am then trying the following.

 [HttpPost]
        public async Task<IActionResult> Index(string username, string password)
        {
            var request = (HttpWebRequest)WebRequest.Create("http://websiteB.mycompany.com/login");

            var postData = $"username={username}&password={password}";
            var data = Encoding.ASCII.GetBytes(postData);

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;

            using (var stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }

            var response = (HttpWebResponse)request.GetResponse();

            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

            return View(); // Here I would redirect to website B or show an error message on website A
        }

The following code hits website B. The user authentication code runs without a problem but it doesn't seem that the session cookie is being sent back. Without this when you hit http://websiteB.mycompany.com you get directed to the login page.
The session cookie from website B has the following

On my test/production server, the cookie is secure.
Is there anything I can do to login to the site?


text:
Q: Binding variable in Service with variable in Controller I try to do some databindings between a controller and a service.
I just want my variable userIsConnected, which is into my controller, has to change as soon as the function getUserIsConnected returns an other value.
Maybe I have to add an attribute userIsConnected into my service?
Here the example :

app.service('UserService', function($http){

    var user = null;
    this.getUser = function (){
        return user;
    };
    this.setUser = function (user){
        user = user;
    };
    this.getUserIsConnected = function (){
        if(user)
            return true;
        else
            return false;
    };

});

app.controller("NavBarCtrl", function($scope, $http, $location, $rootScope, UserService) {

    $scope.signInIsDisabled = true;
    $scope.userIsConnected = UserService.getUserIsConnected();

});

Thanks for your help

A: The problem with this:
 $scope.userIsConnected = UserService.getUserIsConnected();

...is that $scope.userIsConnected becomes whatever getUserIsConnected() outputs in the moment the Controller is initialized. If you want it to continue updating, you should try something like this instead:
 $scope.userIsConnected = UserService.getUserIsConnected;

And then in your view, you would use {{userIsConnected()}}.
HOWEVER, from my experience, this sort of watcher is very expensive on rendering. Because when the view is rendered, it will actually run userIsConnected() 10 times before finally giving-up (because in AngularJS, the stack overflow limit is capped at 10).
I used that method in my applications when I first started using AngularJS. But now, I have a directive called "myDynamicMenu", and it detects when a route event has fired using $routeChangeSuccess (ie. when user changes page from login to dashboard, or from dashboard to logout to home).
At this event, my menu directive will check the user authentication state (logged-in or logged-out), and it will then display the proper menu (ie. the user menu [dashboard, my settings, logout], or the guest menu [login, register]). This method is much faster at rendering.
Edit: Example directive:
  app.directive('myDynamicMenu', function ($rootScope, UserService) {
    return {
      restrict: 'E',
      templateUrl: 'my-dynamic-menu.html',
      link: function (scope) {
        $rootScope.$on('$routeChangeSuccess', updateMenuWhenRouteChanges);

        ////////////////////////////////////////////////////////////

        function updateMenuWhenRouteChanges () {
          scope.isLoggedIn = UserService.getUserIsConnected() ? true : false;
        }
      }
    };
  });

Your template would be something like:

   I am a logged-out guest!

   I am a logged-in member!

And drop the menu into your layout using <my-dynamic-menu></my-dynamic-menu>.


text:
Q: Script to list Power Query source dependencies in multiple Excel files I use Power Query (PQ) for quite complex data flow. Many queries in single file gradually lengthen  computing times, so I split PQ to multiple Excel files.
I want to know, what files are dependent on the others. I have found something like this for cell references.
Question: how can I get list of referenced sources (filenames for Excel files) in PQ over multiple files in specified directory?
I have thought of solutions:

*

*VBA - I am able to update cited script to traverse files, but I don't know proper methods to access Power Query sources.

*python - my brute force approach would be to temporarily unzip XLS? file and parse XML for used sources.

Is there any framework or working sample, that would list all PQ sources from specific XLS? file?

A: You can access powerQuery sources like this:
Set t = ThisWorkbook.Queries("Table1")
tf = t.Formula


text:
Q: passing old value back to javabean from javascript I have this piece of javascript:
<script type="text/javascript">
function show_confirm()
{

var type = '<%= nameBean.getTxnType() %>';
var old_cd = '<%= nameBean.getCode() %>';
var new_cd = document.getElementById("tbCode").value;
var cd;

if (type == "Update")
  {
    if(old_cd != new_cd)
    {
        var response = confirm("Code already exists. Do you want to replace it?");
        if (response){
                    document.NameUpdate.submit();
        }
        else{
            cd = old_cd;

    }
  }
</script>

and this is what i am doing in my jsp page to invoke this script:
<INPUT TYPE=SUBMIT NAME="action" onclick="show_confirm()" VALUE="Save Changes">

Its working fine when I hit ok.. but my question is how can i pass the value of old_cd back to the bean so it wont update it with the new code that was entered by the user in the tbcode box.. when user hit cancel i want to ignore what value was entered in textbox and not to update that field in database

A: I'm not entirely clear on the use case here, but here are a couple of answers:
If the question is, "how do I stop the form from submitting when the user hits cancel?", then the answer is, return false in the click handler:
if (response){
    document.NameUpdate.submit();
}
else{
    cd = old_cd;
    return false;
}

If you need to submit the form no matter which one the user clicks, then you probably need to submit the old value in a hidden input field and have a way to tell the server that user hit "cancel" (probably another hidden field), e.g.:
<!-- html -->
<input type="hidden" name="old_cd" value="<%= nameBean.getCode() %>">
<input type="hidden" id="canceled" name="canceled" value="0">

and javascript:
// js snippet
if (response){
    document.NameUpdate.submit();
}
else{
    document.getElementById("canceled").value = 1;
    return true;
}


text:
Q: Java SE or Java EE (standard or enterprise)? I'm starting to do a lot of Java EE dev work. Is it ok to install Java EE on my home machine instead of a JRE?
Also, can GlassFish run on a JRE or does it need Java EE?

A: Java EE is an abstract API. GlassFish is one of the available concrete Java EE implementations. The Java EE download from Oracle.com is basically just GlassFish along with some documentation/examples and optionally also NetBeans. So if you download Java EE from Oracle.com, you've already GlassFish :)
It only requires a Java SE JDK (not just JRE!) already on your machine which has to be downloaded and installed separately. If you intend to develop with JSF, you may find this tutorial useful as well. It covers installing JDK, GlassFish and Eclipse from the zero beginning in detail.
See also:

*

*https://stackoverflow.com/questions/165230/is-the-offical-sun-java-ee-tutorial-the-best-way-to-learn-how-to-make-java-web-ap

A: You still need a JRE (Java Runtime Environment).  Actually, you really need a JDK (Java Development Kit) so you can compile.
GlashFish includes the Java EE libraries.  It runs on a JRE or JDK.  If you are using JSPs, you have to run GlassFish against a JDK (because JSP technology does code generation/compilation at run-time.


text:
Q: React PerfectScrollbar causes my react web crashes This is my code snippet, pls help

                    {allMemberList !== null && !loadingAllMemberList && (
                    <>

                            {allMemberList.data.map(item =>(
                                <PerfectScrollbar className="card-body dz-scroll" >

                                             {item.user.display_name}
                                            {item.user.username}

                                </PerfectScrollbar>
                            ))}
                    </>

                    )}

Error message=> Warning: React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.


text:
Q: Exclude one day data from time series xarray dataset I am trying to drop one day data '2020-01-30' from xarray time series dataset ds using Python. Following code doesn't work:
ds_1 = ds.where(ds.time != '2020-01-30', drop=True)

The code runs but returns the same result.
Any help highly appreciated.

A: I found a solution from this link.
ds_1 = ds.drop([np.datetime64('2020-01-30')], dim='time')


text:
Q: Downsample signal with nan values I am trying to downsample time series data using scipy.signal.decimate.  My data has NaN values so the result is an array with just NaN values.  I think this is actually a result of the lowpass filter the algorithm applies before decimating the data.
How do I appropriately handle the NaN values?  I have considered throwing out the NaN values but I need some data for each time step.  I am leaning toward using the average of the nearest non-NaN values, though I don't know if there are negative consequences of this naive approach.  Is there an option to ignore the them, similar to np.nanmean()?


text:
Q: Flutter- detect memory leak I'm little bit confused because I was thinking there are no memory leak in flutter since there is no concept of weak (if I'm correct).
I'm running this on iOS device.
I'm trying to play videos and initialize some videos beforehand so that user can see it without delay.
To do that I prepared six VideoPlayerController and make those always being initialized while current video is playing.
There are three more initialized VideoPlayerController next to current one and two more initialized ones before current one like image below.

With this logic I play video very smoothly back and forth. But after play about ten videos, app crush because of memory issue.
I tried every function Future, async, await but still eats lots of memories.
I'm not sure but it might be NotificationListener?
Since onNotification returns bool not Future or
is this something to do with main thread or something?
Does anyone know how to fix this memory issue?
Code:
    class _SwiperScreenState extends State<SwiperScreen> {
      VideoPlayerController _firstController;
      VideoPlayerController _secondController;
      VideoPlayerController _thirdController;
      VideoPlayerController _fourthController;
      VideoPlayerController _fifthController;
      VideoPlayerController _sixthController;
      List<VideoPlayerController> _controllers;
      List<String> urls = [
        'https://firebasestorage.googleapis.com/v0/b/waitingboy-34497.appspot.com/o/video%2F8-21%2F1534825377992OsfJfKsdf90K8sf?alt=media&token=12245ee4-1598-4f7e-ba28-a9eb72ca474e',
        'http://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_20mb.mp4',
        'https://firebasestorage.googleapis.com/v0/b/waitingboy-34497.appspot.com/o/video%2F8-21%2F1534825377992OsfJfKsdf90K8sf?alt=media&token=12245ee4-1598-4f7e-ba28-a9eb72ca474e',
        'http://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_20mb.mp4',
      ];
      int currentIndex = 0; //refer to current playing controller index
      int videosIndex = 0; //refer to current playing urls index

      bool _didGetNotification(ScrollNotification notification) {
        if (notification is UserScrollNotification) {
          if (notification.direction.toString() == 'ScrollDirection.reverse') {
        //swipe to left so add one more video
            videosIndex++;
        //modify index so that always in the range of 0 ~ 5.
            if (currentIndex <= 2) {
              final int prepareIndex = currentIndex + 3;
              urls.add(
                  'https://firebasestorage.googleapis.com/v0/b/waitingboy-34497.appspot.com/o/video%2F8-21%2F1534825377992OsfJfKsdf90K8sf?alt=media&token=12245ee4-1598-4f7e-ba28-a9eb72ca474e');
              _initVideo(urls[videosIndex], prepareIndex);
            } else {
              final int prepareIndex = (currentIndex + 3) - 6;
              urls.add(
                  'http://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_20mb.mp4');
              _initVideo(urls[videosIndex], prepareIndex);
            }
          }
          if (notification.direction.toString() == 'ScrollDirection.forward') {
       //swipe to right so back one more video
            videosIndex--;
       //modify index so that always in the range of 0 ~ 5 .
            if (currentIndex >= 2) {
              final int videoIndex = videosIndex - 2;
              final int prepareIndex = currentIndex - 2;
              _initVideo(urls[videoIndex], prepareIndex);
            } else {
              final int videoIndex = videosIndex - 2;
              final int prepareIndex = 4 + currentIndex;
              _initVideo(urls[videoIndex], prepareIndex);
            }
          }
        }
        return true;
      }

      Future _initVideo(String url, int initIndex) async {
        if (_controllers[initIndex] != null) {
          await _controllers[initIndex].dispose();
        }

        _controllers[initIndex] = new VideoPlayerController.network(url);
        await _controllers[initIndex].initialize().then((_) async => await _controllers[initIndex].setLooping(true));
        setState(() {});
      }

      Future _initFirstThree() async {
         for  (int i = 1; i < urls.length; i++) {
          await _initVideo(urls[i], i);
        }
      }

      @override
      void initState() {
        _controllers = [
          _firstController,
          _secondController,
          _thirdController,
          _fourthController,
          _fifthController,
          _sixthController
        ];
        _initVideo(urls[0], 0).then((_) => _controllers[0].play());
        _initFirstThree();
        super.initState();
      }

      @override
      void deactivate() {
        _controllers[currentIndex].setVolume(0.0);
        _controllers[currentIndex].pause();
        super.deactivate();
      }

      @override
      void dispose() {
        _controllers.forEach((con) {
          con.dispose();
        });
        super.dispose();
      }

      @override
      Widget build(BuildContext context) {
        return new Scaffold(
          appBar: new AppBar(
            title: new Text('Swiper'),
            actions: <Widget>[
              new IconButton(
                icon: new Icon(Icons.disc_full),
                onPressed: () {
                  Navigator
                      .of(context)
                      .push(MaterialPageRoute(builder: (context) => Dissmiss()));
                },
              )
            ],
          ),
          body: new NotificationListener(
            onNotification: _didGetNotification,
            child: new Swiper(
              itemCount: 6,
              itemBuilder: (BuildContext context, int index) {
                return _controllers[index].value.initialized
                    ? new AspectRatio(
                        aspectRatio: _controllers[index].value.aspectRatio,
                        child: new VideoPlayer(_controllers[index]),
                      )
                    : new Center(child: new CircularProgressIndicator());
              },
              loop: urls.length > 6 ? true : false,
              onIndexChanged: (i) async {
                currentIndex = i;
                final int pauseIndex = i == 0 ? 5 : i - 1;
                await _controllers[pauseIndex].pause().then((_) async {
                  await _controllers[i].play();
                });
              },
            ),
          ),
        );
      }
    }


text:
Q: How to return a function with variable different than variable used in Module I have a module function where I am calculating an interpolated polynomial using Newton's method. The end of this module is what is actually forming the function. Currently, in the module, I have the last line having a function which is what I want returned from the module function. Instead, I am getting x$ as the variable. Here is the code:
NewtonInterpolation[xList_, yList_] :=
 Module[{n, aList, NewtonInterPoly, x},
  n = Length[xList];
  aList = Table["", n];
  aList[[1]] = yList[[1]];
  Do[aList[[k]] = (yList[[k]] -
       Sum[aList[[i]]*
         Product[xList[[k]] - xList[[j]], {j, 1, i - 1}], {i, 1,
         k - 1}])/(Product[
       xList[[k]] - xList[[j]], {j, 1, k - 1}]), {k, 2, n}];
  NewtonInterPoly[x_] =
   Sum[aList[[i]]*Product[x - xList[[j]], {j, 1, i - 1}], {i, 1, n}]]
xList = {1, 2, 3};
yList = {1, 4, 9};
Poly[y] = NewtonInterpolation[xList, yList];
Print[Expand[Poly[y]]]

which returns x$^2, but I want it to return y^2. What am I doing wrong?

A: one approach is to have your module return a pure function. Replace the last line with :
Evaluate[Sum[
   aList[[i]]*Product[# - xList[[j]], {j, 1, i - 1}], {i, 1, n}]] &

aside, for this example you might want to do :
Simplify@Evaluate ...

(Then you wont need to Expand the result )
the usage is:
Poly[y_] = NewtonInterpolation[xList, yList]@y;

or simply:
Poly=NewtonInterpolation[xList, yList]

(Note starting your own symbols with caps is not  good practice)

A: There are few small mistakes in the code you posted:
1) The table iterator should be in brackets.
 aList = Table["", n];

Should be
 aList = Table["", {n}];

2) I'm not sure what this line was intended to do:
  NewtonInterPoly[x_] =

but the way you are using it, it does nothing; you are using the result returned by the assignment, which is just the value from right hand side.
To answer your question:
x should not be declared by the module, it should be passed in. There are two ways you could do this: add to the pattern, like so:
NewtonInterpolation[xList_, yList_, x_] :=

or (I would prefer):
NewtonInterpolation[xList_, yList_][x_] :=

The other option is to have NewtonInterpolation create a function, like so:
NewtonInterpolation[xList_, yList_] :=
  Function[{x},
    Module[ ...

And, if you change the pattern defining NewtonInterpolation, you should be sure to call
  ClearAll[NewtonInterpolation]


text:
Q: The cardinality of an algebraic extension $E$ of a field $F$ cannot exceed the cardinality of $F[X]$ I want to show that let $F \subseteq E$ be an algebraic extension of a field $F$, then the cardinality of $E$ cannot exceed the cardinality of $F[X]$.
The proof this assertion as follows. Let $S$ be the set of all ordered pairs $(f,\alpha)$, where $f\in F[X]$ is nonzero and $\alpha \in E$ with $f(\alpha)=0$. Since for each polynomial f, the number of $\alpha$ such that $(f,\alpha)$ lies in $S$ is finite, we have $|S| \leq \aleph_0|F[X]|=|F[X]|$.
My question is how can I verify the last in equality?

A: We can write $S$ as a union of the following sets:
$$
\bigcup_{f\in F[X]\setminus\{0\}}\{\alpha\in E\colon f(\alpha)=0\}.
$$
Each of the sets appearing in the union is finite. Symbolically, we may write
$$
\bigl|\{\alpha\in E\colon f(\alpha)=0\}\bigr|<\aleph_0.
$$
Now we use the fact that cardinality is subadditive, so that
$$
|S|\leq \sum_{f\in F[X]}\aleph_0.
$$


text:
Q: How to get the current location temperature in android I am new in Android Development. I have created app on Geocoding to get current location. Now I want to get the temperature of the current location too. I found in stackoverflow that there is no thermometer in any Android device to calculate the room or location temperature and it can be only made by getting temperature from internet. I am unable to implement this portion. Please give me any idea or code snippet to achieve this. Thank you in advance.

A: Best way of doing this is accuweather API. I also used it in weather widget. Its very simple to use. Just follow the link http://api.accuweather.com/developers/weatheralarmsAPIguide


text:
Q: Есть ли смысл ставить индекс на 2 столбца? Есть таблица где есть стобцы
id
type

И поиск ведется так
WHERE id = 500 AND type=2

Таблица состоит из 2 млн записей.
вариантов id может быть много, а вот type только 4 разных (1,2,3,4).
Вопрос в том, нужно ли создавать индекс только на столбец id либо же двойной индекс id и type? Чтобы скорость поиска была выше. Или не будет разницы?


text:
Q: Runtime frequency scaling on target machine in Simics I'm working with a scheduling and resource management framework that essentially maps out the most energy efficient execution place and frequency for different types of applications.
When attempting to use the framework on my Simics target machine, however, I've noticed that the system file structure seems to be a bit different than what I expected.
An essential part of the framework is the ability to dynamically change the frequency of the machine at runtime.
Scaling the CPU frequency would usually be done by editing files in the /sys/devices/system/cpu/cpuX/cpufreq/ directory, but it doesn't seem to be present on Simics target machines. I'm aware that the target machine frequency may be edited in the system configuration files on the host machine, but I can't make heads of how frequency scaling should be done when the system is up and running.
How could I go about solving this problem?

A: That the file system nodes are missing is most likely due to the target hardware system not having processor frequency/power management functionality exposed to the target software. The QSP does not have that implemented, as it is a slightly simplified model.  Supporting it might also need updates to the UEFI, not entirely clear from a quick look just how Linux does cpufreq handling.
If you boot the QSP with the "client core" script to get a more modern processor, the default Linux will report that it cannot start the cpufreq driver. Due to missing device.
To change the frequency of a processor, you can use the frequency interface on the processors to change it dynamically.  But that is indeed done inside the model, not from target software.


text:
Q: Parquet Datatype Issue I have a bunch of parquet files and I've created external tables using Impala's CREATE EXTERNAL TABLE....
However when I issued
select * from my_table

it returned

ERROR: File 'hdfs://xyz..' has an incompatible Parquet schema for column 'xyz'. Column type: DECIMAL(5, 2), Parquet schema:optional int32 final_apr [i:4 d:1 r:0].

So I closely looked at the output of command
parquet-tools schema my_parquet

and observed that all the columns which are INT64 but not fixed_len_byte_array having this issue.
So I manually executed the command
ALTER TABLE schema.table_name CHANGE old-column new_column BIGINT;

to change the column type whatever it created by default to BIGINT per https://www.cloudera.com/documentation/enterprise/5-6-x/topics/impala_parquet.html, then I was able to execute the select * from my_table;
I've exercised the above in scala using spark, i.e I was able to read parquet file and store it as impala table and also can able to issue "select * from my_table" query programmatically.
However I tried to manually query from impala shell, I'm encountering the same error shown above.
Instead of manually updating the columns to change the datatype of all INT64 non-fixed-length byte array, is there any better way to handle this? May be something like after reading parquet file as Dataframe, find out all INT64 non-fixed-length byte array column convert them to BIGINT then save the dataframe as table?
BTW, I'm not able to execute select * from my_from; query in hive shell even after changing the column's data type. I'm getting errors msg

Error: Error while compiling statement: FAILED: ParseException line 1:30 extraneous input 'limit' expecting Number near '' (state=42000,code=40000).

I tried with couple tables, all of them are having the same issue with hive shell.
Appreciate your help!

A: Parquet schema's warning int32 means that your impala column type should be int not bigint. When you alter table column to int, it should work.
Btw, spark and impala parquet read methods are different. Impala follows a more conservative way to read parquet files. For example; spark does not control the number of values in different column indices while the impala do.

A: I had a similar issue copying parquet data from s3 to redshift with a decimal column.  I was getting
  code:      15001
  context:   File 'https://s3.us-east-1.amazonaws.com/bucket/filename.snappy.parquet
             has an incompatible Parquet schema for column
             's3://bucket/filename/.column_name'. Column type: DECIMAL(9

The column in redshift was a DECIMAL(9,5).  The column in parquet was a double.  I couldn't change the database because production.  I ended up modifying the parquet output like so:
val nineFive =  DataTypes.createDecimalType(9,5)
val df2 = df.withColumn("column_name", $"column_name" cast nineFive)


text:
Q: keen query not working on json with arrays? I am trying to do a very basic query from the explorer which looks like this:
var sensorFilter = [];
sensorFilter.push({
  property_name: "uuid",
  operator: "eq",
  property_value: "1234"
});

var avg_sensor_pm = new Keen.Query("average", {
  eventCollection: "status_update",
  targetProperty: "sensors[0].properties[0].value",
  filters: sensorFilter
});

The query returns nothing, I am wondering if the syntax to access indexed element in an array is not correct?
Anybody with the same problem?

A: The problem is that doing averages on values within an arrays is technically hard. I would recommend sending separate events for each status_update for each sensor and then doing an average on sensor.value.
You can definitely store arrays in Keen IO, but arrays of objects are not recommended. For more info: https://keen.io/docs/streams/data-modeling-guide/#arrays
Since I don't know anything about your data model, I should say that there might be other ways to do it too. Feel free to share it if the way I suggested wouldn't work for your use case.
Also this may be helpful: https://keen.io/docs/streams/data-modeling-guide-200/#avoid-trapping-your-data-lists


text:
Q: How to get a json array of the text within a class? The html snippet in a url (www.foo.com/index.html):
...

foo

...

bar

...

baz

......

I would like to get, through php all the text inside the class .name and convert it to JSON
So that it ends up like:
{"names":["foo","bar","baz"]}

This is what I have tried:
function linkExtractor($html){
    $nameArr = array();
    $doc = new DOMDocument();
    $doc->loadHTML($html);
    $names = //how do i get the elements?
    foreach($names as $name) {
        array_push($nameArr, $name);
    }
    return $imageArr;
}

echo json_encode(array("names" => linkExtractor($html)));

A: try this ...
$html = "http://www.foo.com/index.html"; //is this right?
function linkExtractor($html, $classname){
    $nameArr = array();
    $doc = new DOMDocument();
    $doc->loadHTML($html);

    $names = $doc->xpath("//*[@class='" . $classname . "']");

    foreach($names as $name) {
        array_push($nameArr, $name);
    }
    return $imageArr;
}

echo json_encode(array("names" => linkExtractor($html,".name")));

A: So just this has an end:
$names = function($html) {
    $doc  = new DOMDocument();
    $last = libxml_use_internal_errors(TRUE);
    $doc->loadHTML($html);
    libxml_use_internal_errors($last);
    $xp     = new DOMXPath($doc);
    $result = array();
    foreach ($xp->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' name ')]") as $node)
        $result[trim($node->textContent)] = 1;
    return array_keys($result);
};

echo json_encode(array("names" => $names($html)));

Output:
{"names":["foo","bar","baz"]}

Required PHP version: 5.3+


text:
Q: Run make with Makefile in memory Suppose I have an encrypted Makefile on hand, I want to write a Perl program to decrypt it and run make -f with it. Is this possible without writing the decrypted Makefile back to harddisk?

A: Have your program write the decrypted Makefile to stdout and pipe it to make -.
See man make, the part that says:

If makefile is `-', the standard input is read.

A: You could try setting LD_PRELOAD when you run make to give make some fake fopen/fclose functions that read the makefile out of memory.

A: make -f <(decrypt file)

This will work on linux and some other systems. It does not rely on make supporting this functionality. It is done in the OS. See http://www.gnu.org/software/bash/manual/bashref.html#Process-Substitution
P.S. you will want to consider swap space, telling make not to swap.
Also this will not help with files included by the first.

A: You could use an encrypted file system. A shell script could launch a key agent, for the file system then the make can run retrieving and saving everything to/from the encrypted file system. I have done successfully done this with sshfs (not an encrypted file system, but an encrypted connection to a remote file system locked in a room).


text:
Q: Launchpad dailybuild source in subdirectory of branch I have a repo branch that i have mirrored in Launchpad that I am trying to setup a daily build. The problem is that the source directory of the package is a subdirectory in the branch.  When building locally it's no problem because I can just change to that directory. However with launchpad's bzr-builder it does everything from the top directory in the branch.
My current build recipe is:
# bzr-builder format 0.3 deb-version {debupstream}-{revno}-{revno:packaging}
lp:kegbot
nest-part packaging lp:~szechyjs/kegbot/kegbot_debian debian debian

Ideally I would use lp:kegbot/pykeg but this is not possible in bzr.
Is there a easy way I can build the package in the kegbot/pykeg directory, by setting it up in my recipe or some kind of source directory variable in the rules file?

A: Unfortunately the bzr-builder plugin currently doesn't support what you need.
In principle you could perhaps workaround it by making a branch of lp:pykeg that moves pykeg/ to the root of the tree, and moves the old root to ignored/.  You could then add merge workaround lp:…/workaround-branch to your recipe.  Unfortunately pivoting the root of a tree like that isn't especially easy either.
It would be worth filing a bug on Launchpad and/or bzr-builder about this use-case.


text:
Q: scale_fill_brewer custom labels with ggplot2 I made the following plot:

I used this code:
library(XML)
library(ggplot2)
library(scales)
library(plyr)
library(maps)

unemp <-
  readHTMLTable('http://www.bls.gov/web/laus/laumstrk.htm',
                colClasses = c('character', 'character', 'numeric'))[[2]]

names(unemp) <- c('rank', 'region', 'rate')
unemp$region <- tolower(unemp$region)

us_state_map <- map_data('state')
map_data <- merge(unemp, us_state_map, by = 'region')

map_data <- arrange(map_data, order)

states <- data.frame(state.center, state.abb)

p1 <- ggplot(data = map_data, aes(x = long, y = lat, group = group))
p1 <- p1 + geom_polygon(aes(fill = cut_number(rate, 5)))
p1 <- p1 + geom_path(colour = 'gray', linestyle = 2)
p1 <- p1 + scale_fill_brewer('Unemployment Rate (Jan 2011)', palette  = 'Set1')
p1 <- p1 + coord_map()
p1 <- p1 + geom_text(data = states, aes(x = x, y = y, label = state.abb, group = NULL), size = 2)
p1 <- p1 + theme_bw()
p1

I want to show scale_fill_brewer custom labels after some manipulation like after multiplying each label by 100 or 1000.

A: While the ggplot helper functions are handy, I prefer doing data wrangling outside of the plotting idiom. This uses cut to add 1% breaks with custom labels and also uses a proper US projection and has a sequential color scale which is far more appropriate for this data and (finally) removes a ton of chart junk:
library(XML)
library(ggplot2)
library(scales)
library(plyr)
library(maps)
library(ggthemes)

unemp <-
  readHTMLTable('http://www.bls.gov/web/laus/laumstrk.htm',
                colClasses = c('character', 'character', 'numeric'))[[2]]

names(unemp) <- c('rank', 'region', 'rate')
unemp$region <- tolower(unemp$region)

# gain granular control of the breaks outside of ggplot
unemp$brk <- cut(unemp$rate, 0:9, labels=c("0%", sprintf("≥%d%%", 1:8)))

head(unemp)
##   rank       region rate brk
## 1    1     nebraska  2.6 ≥2%
## 2    2 north dakota  3.1 ≥3%
## 3    3         utah  3.5 ≥3%
## 4    4      vermont  3.6 ≥3%
## 5    5         iowa  3.8 ≥3%
## 6    5    minnesota  3.8 ≥3%

us_state_map <- map_data('state')
map_data <- merge(unemp, us_state_map, by = 'region')

map_data <- arrange(map_data, order)

states <- data.frame(state.center, state.abb)

p1 <- ggplot(data = map_data, aes(x = long, y = lat, group = group))
p1 <- p1 + geom_polygon(aes(fill = brk))
p1 <- p1 + geom_path(colour = 'black', linestyle = 2, size=0.25)
# use a sequential color scale since that's appropriate for the data
p1 <- p1 + scale_fill_brewer('Unemployment Rate (Jan 2011)', palette  = 'YlGnBu')
# use a proper projection for the U.S.
p1 <- p1 + coord_map("albers", lat0=39, lat1=45)
p1 <- p1 + geom_text(data = states, aes(x = x, y = y, label = state.abb, group = NULL), size = 2)
p1 <- p1 + labs(x=NULL, y=NULL)
p1 <- p1 + theme_map()
p1 <- p1 + theme(legend.position="right")
p1

You still need to deal with Alaska & Hawaii.


text:
Q: Issues accessing command prompt from python script I am trying to open twitch streams in VLC using python and livestreamer. When I open up a normal command prompt and type in:
livestreamer twitch.tv/*stream_here* best

It works completely fine.  However, when I add:
os.system('livestreamer twitch.tv/%s best' %(streamName))

to my python script, the command prompt that is opened by the python script says that livestreamer is not recognized as an internal or external command.  Livestreamer has definitely been added to my path, so I'm a bit confused.


text:
Q: How can I copy values from one dataframe column to another based on the difference between the values I have two csv  mirror files generated by two different servers. Both files have the same number of lines and should have the exact same unix timestamp column. However, due to some clock issues, some records in one file, might have asmall  difference of a nanosecond than it's counterpart record in the other csv file, see below an example, the difference is always of 1:
dataframe_A                                          dataframe_B

|          | ts_ns              |            |          | ts_ns              |
| -------- | ------------------ |            | -------- | ------------------ |
| 1        | 1661773636777407794|            | 1        | 1661773636777407793|
| 2        | 1661773636786474677|            | 2        | 1661773636786474677|
| 3        | 1661773636787956823|            | 3        | 1661773636787956823|
| 4        | 1661773636794333099|            | 4        | 1661773636794333100|

Since these are huge files with milions of lines, I use pandas and dask to process them, but before I process, I need to ensure they have the same timestamp column.
I need to check the difference between column ts_ns in A and B and if there is a difference of 1 or -1 I need to replace the value in B with the corresponding ts_ns value in A so I can finally have the same ts_ns value in both files for corresponding records.
How can I do this in a decent way using pandas/dask?

A: If you're sure that the timestamps should be identical, why don't you simply use the timestamp column from dataframe A and overwrite the timestamp column in dataframe B with it?
Why even check whether the difference is there or not?

A: You can use the pandas merge_asof function for this, see https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge_asof.html . The tolerance allows for a int or timedelta which should be set to the +1 for your example with direction being nearest.

A: Assuming your files are identical except from your ts_ns column you can perform a .merge on indices.
df_a = pd.DataFrame({'ts_ns': [1661773636777407794, 1661773636786474677, 1661773636787956823, 1661773636794333099]})
df_b = pd.DataFrame({'ts_ns': [1661773636777407793, 1661773636786474677, 1661773636787956823, 1661773636794333100]})

df_b = (df_b
    .merge(df_a, how='left', left_index=True, right_index=True, suffixes=('', '_a'))
    .assign(
        ts_ns = lambda df_: np.where(abs(df_.ts_ns - df_.ts_ns_a) <= 1, df_.ts_ns_a, df_.ts_ns)
    )
    .loc[:, ['ts_ns']]
)

But I agree with @ManEngel, just overwrite all the values if you know they are identical.


text:
Q: Delphi resources for existing .NET developer Can anyone recommend some decent resources for a .NET developer who wishes to get a high level overview of the Delphi language?
We are about acquire a small business whose main product is developed in Delphi and I am wanting to build up enough knowledge to be able to talk the talk with them.
Books, websites etc all appreciated.
Thanks.

A: *

*DelphiBasics gives a good overview of basic syntax, library functions etc.

*Essential Delphi is a free e-book by Marco Cantu that should give a good overview, also of the VCL

Feel free to ask around here as well, or in the Delphi newsgroups, if you encounter specific issues :)

[edit] @Martin:

*

*There's a free "Turbo" edition available at the Codegear/Embarcadero website. I guess it has some limitations, so you could also try downloading the trial version.

A: There's also a Delphi wiki
This even has a "Beginning Delphi" page with lots of external links on it. (some of them already mentioned)

A: http://www.delphifeeds.com/ is a good place to start, it has most news about what is going on in the delphi community.

A: There are a number of videos by Alister Christie at codegearguru - check them out :)
edit... @Martin, check out the Turbo products at CodeGear

A: @Martin there is a free version.
Turbo Delphi
If you are comfortable with c# you will see many similarities with Delphi.
I also found the community surrounding the newsgroups to be active and helpful. They have a smilar concept to MVPs they were called Team B (but as Borland doesn't own them the name may have changed now).


text:
Q: Phonegap SQLite Error 23 Not Authorized Resources:
http://docs.phonegap.com/en/2.9.0/cordova_storage_storage.md.html#database_version
Device/Framework Info:

*

*Nexus 4 - Android 4.2.2

*Phonegap 2.9.0

*Also using the bootstrap library for UI

I have followed the PhoneGap tutorial for version 2.9 on creating, and managing a database. So far I have found little to no places where people are talking about the specific error 23 when trying to write to a database.
I get this error after trying to write to a database after the insertBtn's click function, which executes the insertTemplate function.
The same thing happens when trying to delete a row when the deleteBtn event is fired, which executes the deleteTemplate function.
Any recommendations?
Controller File:
var databaseName = "blackbriar";
var version = 1;
var displayName = "lctv";
var size = 2097152; // two megabytes
var db = null;

$(document).ready(function(event){
    // Gets shell for database
    db = window.openDatabase("Database", "1.0", "Cordova Demo", 200000);
    db.transaction(populateDb, errorCb, successCb);
    db.transaction(loadTemplates, errorCb, successCb);

    $('#insertBtn').click(function(event){
        db.transaction(insertTemplate, errorCb, successCb);
    });

    $('#back').click(function(event){
        $('#templates').show();
        $('#templateEdit').hide();
        $('#back').hide();
    });
    $('#deleteBtn').click(function(event){
        db.transaction(deleteTemplate, errorCb, successCb);
        $('#back').click();
    });
});

$(document).on('click', '.pill', function(event){
    // If window width is greater than 480px, isMobile variable is false
    var isMobile = $(window).width() > 480 ? false : true;

    $('#currentId').text($(this).attr('tempid'));
    db.transaction(getTemplateById, errorCb, successCb);

    if($('#currentId').text() == "-1"){
        $('#insertBtn').show();
        $('#saveBtn').hide();
        $('#deleteBtn').hide();
        $('#clearBtn').show();
    } else {
        $('#insertBtn').hide();
        $('#saveBtn').show();
        $('#deleteBtn').show();
        $('#clearBtn').hide();
    }

    // Checks if pill is active for UI changes
    if($(this).hasClass('active')){
        $(this).removeClass('active');
        if(!isMobile){$(this).find('.temp').attr('style', 'color: black;');}
    } else {
        $('.pill').removeClass('active');
        $('.pill').find('.temp').attr('style', 'color: black;');
        $(this).addClass('active');
        if(!isMobile){$(this).find('.temp').attr('style', 'color: white;');}
    }
    if(isMobile) {
        $('#templates').hide();
        $('#templateEdit').show();
        $('#back').show();
    }
});

My function file:
function getShell(databaseName, version, displayName, size) {
    return window.openDatabase(databaseName, version, displayName, size);
}

function populateDb(tx) {
    tx.executeSql('CREATE TABLE IF NOT EXISTS templates (id INTEGER PRIMARY KEY AUTOINCREMENT, templateName, description, campus, account, department, programName, projectId, taskId)');
}

function errorCb(error) {
    alert("Error processing SQL: "+error.code);
}

function successCb() {
    alert("Success!");
}

function insertTemplate(tx) {

    var templateName = $('#templateName').val();
    var description = $('#descriptionField').val();
    var campus = $('#campusField').val();
    var account = $('#accountField').val();
    var department = $('#departmentField').val();
    var programName = $('#programNameField').val();
    var projectId = $('#projectIdField').val();
    var taskId = $('#taskIdField').val();

    tx.executeSql('INSERT INTO templates (templateName, description, campus, account, department, programName, projectId, taskId) VALUES ('
            +'"'+templateName+'"'+', '
            +'"'+description+'"'+', '
            +'"'+campus+'"'+', '
            +'"'+account+'"'+', '
            +'"'+department+'"'+', '
            +'"'+programName+'"'+', '
            +'"'+projectId+'"'+', '
            +'"'+taskId+'"'
            +')');
}

function loadTemplates(tx) {
    tx.executeSql('SELECT * from templates', [], templatesSuccess, errorCb);
}

function templatesSuccess(tx, results) {
    var length = results.rows.length;
    $('#templateUl').html('');
    $('#templateUl').append('
<text class="temp"> Create</text>
');
    for(var i = 0; i < length; i++) {
        $('#templateUl').append('
<text class="temp">'+results.rows.item(i).templateName+'</text>
');
    }
}

function getTemplateById(tx) {
    var currentId = $('#currentId').text();
    tx.executeSql('SELECT * FROM templates WHERE id = '+currentId, [], loadTemplateSuccess, errorCb);
}

function loadTemplateSuccess(tx, results) {
    if(results.rows.length > 0){
        var template = results.rows.item(0);
        var templateName = $('#templateName').val(template.templateName);
        var description = $('#descriptionField').val(template.description);
        var campus = $('#campusField').val(template.campus);
        var account = $('#accountField').val(template.account);
        var department = $('#departmentField').val(template.department);
        var programName = $('#programNameField').val(template.programName);
        var projectId = $('#projectIdField').val(template.projectId);
        var taskId = $('#taskIdField').val(template.taskId);
    } else {
        var templateName = $('#templateName').val('');
        var description = $('#descriptionField').val('');
        var campus = $('#campusField').val('');
        var account = $('#accountField').val('');
        var department = $('#departmentField').val('');
        var programName = $('#programNameField').val('');
        var projectId = $('#projectIdField').val('');
        var taskId = $('#taskIdField').val('');
    }
}

function deleteTemplate(tx) {
    var currentId = $('#currentId').text();
    alert(currentId);
    tx.executeSql('DELETE FROM templates', [], templatesSuccess, errorCb);
    alert("Authorize!!!");
}

A: Just came into this, i had to uninstall the app and re made it (Also changed the version but i dont think that did it).
Followed this so i uninstall the app everytime i debug. This can be annoying if you have to insert items each time, but atleast solved it.


text:
Q: JQuery-UI Datepicker() click event seems to conflict with a custom event I'm a bit confused by some behavior on the frontend. Im using the datepicker() method from the JQuery UI libraries, and when a date is first selected, I want the calendar to slide left to display the rest of a form.  That works fine unless the previous/next month elements are clicked first.  Then the DOM changes(possibly unrelated) and nothing else happens. The calendar stays in its original position and the form never shows up.  It's like the event listener that I wrote is being overridden.  I'm assuming I just have a fundamental misunderstanding of event handling with javascript/jquery.  Im a backend developer with only the slightest frontend experience, so if anyone could explain to me what im doing wrong, I'd be greatly appreciative.
Here's a super simplified example that creates the same behavior:
HTML:

CSS:
#calendar {
    position:relative;
    left:10em; }

JS:
$(document).ready(function () {
    $("#calendar").datepicker();
    $("#calendar tbody td").click(function () {
        $("#calendar").animate({
            left: "-30px",
            easing: 'swing'
        });
    });
});

And here is a fiddle: http://jsfiddle.net/HM9ea/

A: Try this with onSelect:
$("#calendar").datepicker({
    onSelect: function () {
        $(this).animate({
            left: "-30px",
            easing: 'swing'
        });
    }
});

Demo

Issue with your code is that you were trying to animate a object which was not presenet at the state of document ready. so your event does not get fired, instead you can use the builtin method of select onSelect.


text:
Q: Commons exec: Launch, send to child process, and read back on stdin/stdout How can I achieve the following in Apache Commons Exec? (There doesn't seem to be any documentation for this use case).

*

*Launch a child process.

*Pass the child process a string on its stdin.

*Wait for the child process to terminate.

*Collect the stdout from the child process as a string.

A: Use Executor#setStreamHandler(...) to handle input/output redirection.


text:
Q: AJAX drag and drop I have created an AJAX drag and drop file upload form. But when the upload is complete it shows file upload done. But I want it to be redirected to another page. How can I do this?
This is my code
function sendFileToServer(formData,status)
    {
        var uploadURL ="upload.php"; //Upload URL
        var extraData ={}; //Extra Data.
        var jqXHR=$.ajax({
            xhr: function()
                {
                    var xhrobj = $.ajaxSettings.xhr();
                    if (xhrobj.upload)
                        {
                         xhrobj.upload.addEventListener('progress', function(event)
                         {
                            var percent = 0;
                            var position = event.loaded || event.position;
                            var total = event.total;
                            if (event.lengthComputable)
                                {
                                percent = Math.ceil(position / total * 100);
                                }

                            status.setProgress(percent);
                      },     false);
                     }
            return xhrobj;
            },
            url: uploadURL,
            type: "POST",
            contentType:false,
            processData: false,
            cache: false,
            data: formData,
            success: function(data){
            status.setProgress(100);

            $("#status1").append("File upload Done<br>");
        }
    });

    status.setAbort(jqXHR);
}

A: To redirect to another page, use window.location.
window.location = "http://www.yoururl.com";


text:
Q: HowTo: Teamcity + GitHub Has anybody successfully configured Teamcity to monitor, extract, and build from GitHub?
I can't seem to figure how where and how to configure the SSH keys for Teamcity.  I have Teamcity running as a system service, under a system account.  So where does Teamcity stash its SSH configuration?
EDIT
To get this to work, I needed to stop the agent from running under a system account.

A: I got "Default Private Key" to work with agents running as the SYSTEM user on Windows. For me, the answer was having the identity file at
C:\Windows\SysWOW64\config\systemprofile\.ssh\id_rsa
instead of at
C:\Windows\System32\config\systemprofile\.ssh\id_rsa

A: Your question is specific to SSH, but it is certainly easier and quicker to use HTTP over TLS, as GitHub and TeamCity both now support HTTP authentication. Furthermore, GitHub also supports personal api tokens with limited permissions, that you may configure to your liking, or create a new user if you prefer.
See image below of our TeamCity settings.

A: Ok...  I got this to start working on my Windows server.  Here are the steps I took to configure TeamCity 4.5 Professional:

*

*Downloaded the JetBrains Git VCS Plugin

*Copied the downloaded zip file to .BuildServer\plugins

*In the Administration > Edit Build Configuration > Edit VCS Root configuration screen, I selected "Git (JetBrains)"

*Entered my Clone Url from the GitHub project page

*Set for authentication method "Default Private Key" -- this is IMPORTANT

*

*The TeamCity BuildAgent should be running as a standard user, with the SSH installation configured properly for that user.

*Follow the GitHub SSH directions for SSH configuration

*Leave the username blank.  This should already be provided for in your GitHub clone URL

A: Since TeamCity 8.1, there is an official support for SSH key management, please read this docs: https://confluence.jetbrains.com/display/TCD9/SSH+Keys+Management

A: for private key, username must be blank.

A: (This is a up to date answer to an old question)
I got ssh based builds working with github/gitlab and teamcity 7 like this:
Log onto the teamcity machine and use puttygen/ssh-keygen to generate a rsa key pair and save the openssh key somewhere sensible.
(Gotcha - Using puttygen? Make sure the private key is in openssh format - puttygen > conversions > export openssh key)
I suggest you save the private key in
C:\.ssh\id_rsa

Now setup "default private key" in teamcity - create a file
C:\.ssh\config

And in it place this:
Host * IdentityFile c:\.ssh\id_rsa

Login to your gitlab/guthub account and paste in the openssh public key for your teamcity private key.
You should now be able to create a git vcs root in teamcity that can use the default private key to pull your source.

A: You may need a third party plugin like this

A: I don't know why but choosing Default Private Key failed to me.
Then I choose to Custom Private Key as screen shot below:

The Username field has to be empty.
The Passphrase field is the password of the your private key
(Assume you have added the public key of this private key in git already.)
Hope no one got stuck like me !


text:
Q: Why does using Technic Launcher modpacks slow Minecraft down? I can play normal Minecraft at 60 FPS, on the highest settings. When I launch a Technic Launcher modpack, Minecraft will run at a maximum of 4 FPS.
I have a Qosmio gaming computer, running Java 7 64-bit. It will not run at all with Java 8 64-bit. I have allocated 7GB of RAM, and tried setting all the settings to the lowest possible configurations;

*

*Render distance: tiny.

*Clouds: off.

*Particles: minimal.

*Smooth lighting: off.

Can someone please tell me what I am doing wrong, and how to fix it?

A: Have you checked your RAM allocation? I haven't used Technic in years, but I assume it still defaults to 1GB. Try upping that (there should be an options menu before on the launcher)

A: We released with a bug that causes Technic to eat up CPU on one core while Minecraft is running.  Depending on how many cores your machine has, this could have very serious consequences for playing Minecraft.  There is a fix on the Beta stream, so you can try Launcher Options -> Launcher Build -> Beta Stream and see if your performance improves.

A: Launch Technic Launcher, then click on launcher options at the top right. Explore the options until you find RAM, The most RAM you can use is 5 GB on technic. Hope this helps :)

A: Same thing happened to me, just install Java Offline x64.


text:
Q: Is it possible to embedd this web app to my website I am trying to embedd this website into my own website I have tried so using Iframe but the page is just blank.
The link I want to embedd is - https://www.zillow.com/homedetails/1-Anchorage-Way-APT-1505-Freeport-NY-11520/2094629656_zpid/?fullpage=true
Or - https://www.zillow.com/homedetails/1-Anchorage-Way-APT-1505-Freeport-NY-11520/2094629656_zpid?skinver=8&view=owner&fromapp=true&p=ios&appType=PA
My Iframe :

Thanks in advance.

A: It may not work if the Zillow's server block being requested through iFrame. (You may check this at your console. Most big websites do block).
There is no  way to you do that using an iFrame. But in cases like this, I like to create a pop-up (triggered by a click, so browser will not block). Something like this:
Open


text:
Q: Converse of the exterior angle bisector theorem How to prove the following theorem?
In triangle ABC the point P divides the extension of the line AB in the following ratio
AP:BP=AC:BC.
Prove that the line CP is the bisector of the exterior angle C.
Trigonometric solution is possible.

A:
$\mathrm{Fig. 1}$ shows the triangle $ABC$ and the line $CP$ mentioned in your question.
We need to draw the line $BD$ parallel to $PC$ to facilitate our proof. We can write right away,
$$\frac{AP}{BP}=\frac{AC}{CD}. \tag{because PC $\backslash\backslash$ BD}$$
But, it is given that,
$$\frac{AP}{BP}=\frac{AC}{BC}.$$
Therefore,
$$\frac{AC}{CD}=\frac{AC}{BC},$$
which means $CD=BC$. That makes $BCD$ an isosceles triangle and , as a consequence,
$$\measuredangle DBC=\measuredangle CDB.\tag{1}$$
Because they are alternate angles, The two angles $\measuredangle BCP$ and $\measuredangle DBC$ are equal, i.e.
$$\measuredangle PCB=\measuredangle DBC.$$
The two angles $\measuredangle ECP$ and $\measuredangle CDB$ are corresponding angles. That makes them equal angles too, i.e.
$$\measuredangle ECP =\measuredangle CDB.$$
Finally, because of the identicalness seen in the equation(1), we have,
$$\measuredangle PCB =\measuredangle ECP.$$
$\underline{Note}$:
You could have refer to a good book on elementary geometry for this proof, because they usually provide the proofs of the
 exterior angle bisector theorem and its converse side by side under the heading $Euclid\space VI\space 3$. If you have done that, you could have avoided this days-long waiting.


text:
Q: How to call function in a screen from another screen using Actions in react native router flux Hi I have 2 page in my Project .When I go from the first page to the second page (using Action), then I return to the First page with the command Action.pop() ,At this time I want to call function in first page, how can I do it?
in first page :
.....
BacktoFirstPage(){
    //my code
}
render(){
    return(
        <TouchableOpacity onPress={()=>Actoin.secondPage()}>
            <Text>go to second page</Text>
        </TouchableOpacity>
    )
.....

in second page:
render(){
    return(
        <TouchableOpacity onPress={()=>Actoin.pop()}>
            <Text>back to first page</Text>
        </TouchableOpacity>
    )
}

now ,  how to call BacktoFirstPage

A: What you can do is to pass the function you want to run as a parameter to next screen and then run it before pop the screen.
Example
....
BacktoFirstPage(){
    //my code
}
render(){
    return(
        <TouchableOpacity onPress={()=>Actoin.secondPage({onPop: this.BacktoFirstPage.bind(this)})}>
            <Text>go to second page</Text>
        </TouchableOpacity>
    )
.....

render(){
    return(
        <TouchableOpacity onPress={()=>{ this.props.onPop(); Actoin.pop()}>
            <Text>back to first page</Text>
        </TouchableOpacity>
    )
}

OR
componentWillUnmount() {
  this.props.onPop();
}

render(){
    return(
        <TouchableOpacity onPress={()=>{ Actoin.pop()}>
            <Text>back to first page</Text>
        </TouchableOpacity>
    )
}


text:
Q: How can I do the inference for a trained neural network using C/C++? For my master's thesis, I will have to do an inference with a pre-built / pre-trained (with TensorFlow) deep neural network model. I received it in two different formats (hdf5 / h5 and frozen graph = .pb). The inference shall be done on a cluster, so far we only have a GPU-version (with TensorRT and a uff Model) running. So my first job seems to be to do inference on one CPU before making a usage possible on the cluster.
We are using the model within computational fluid dynamics (CFD) simulations – that is also my academic background, and as you can therefore imagine I have only a little knowledge about deep learning. Anyway, it is not my job to change/train the model but just to use it for inference. Our CFD-Code is written in C++, which is the only programming language I am using on an advanced level (obviously it is no problem to use C, but I have no idea of python).
After going through many Google searches I recognized that I do not have a real idea how to start things off. I thought it would be possible to skip all the training and TensorFlow stuff. I know how neural networks work and how they calculate their output values from their input values. I also have the most important theoretical knowledge, but no programming knowledge in this field. Is it somehow possible to use the model they gave me (so either hdf5/h5 or frozen graph) and build an inference code using exclusively C or C++? I already found the C API and installed it within a docker container (where I also have Tensorflow), but I am really not sure what the next step is. What can I do with the C API? How would you write a C/C++-Code for inference with a DNN-model that is prepared to inference with it?

A: Opencv provided tools to run deep learning models but they are just limited to computer vision field. See here.
You can perform classification, object detection, face detection, text detection, segmentation, and so on by using the API provided by opencv. These examples are fairly straightforward.
There are both python version and c++ version available.


text:
Q: Correct word order of "An article you are a co-writer of"? I am having trouble with the wording of a sentence in a formal letter. I came up with this, but, for me, it feels somewhat twisted and incorrect. How would you pharse this?

During my research, I found the article "Carbon fiber material in
  musical instrument making" at ScienceDirect (link) you are a co-writer of.

A: It's fine, but some people still complain, particularly in formal writing, about ending a sentence with a preposition. (The injunction against doing so was made up out of nowhere a couple of centuries ago, but a lot of people used to believe in it, and some still do).
An alternative I would suggest is "that you co-wrote".


text:
Q: How to know what android:id Android expects? In some android classes you can set a custom layout. As far as my understanding goes, these custom layouts need certain android:ids to work.
For example, for the ListActivity a ListView with @android:id/list has to be provided and this is specified in the documentation.
What about other views? For example, I was checking the API Demos and came across
<CheckBoxPreference
                android:key="child_checkbox_preference"
                android:dependency="parent_checkbox_preference"
                android:layout="?android:attr/preferenceLayoutChild"
                android:title="@string/title_child_preference"
                android:summary="@string/summary_child_preference" />

There's a layout specified for the preference. That layout seems to be preference_child.xml, in which there's @+android:id/title and @+android:id/summary, which I assume the view will use to provide the title and the summary, but is this documented anywhere?
How do I know what resource IDs I have to use so that everything automagically works?

A: AFAIK, there's no trick to find out but to know the documentation or open the android's id.xml and look for references.
P.S.
Your code demonstrates how to use a specific attribute out of an entire style (the use of "?"), it has nothing to do with ID's


text:
Q: Can grant command in mysql create a new user? Can grant command in mysql create a new user?

A: If you check out the MySQL documentation on the GRANT syntax, you'll see a section regarding Privileges Supported by MySQL that mentions all the permissions you can grant including CREATE USER:

CREATE USER
Enable use of CREATE USER, DROP USER, RENAME USER, and REVOKE ALL PRIVILEGES. Level: Global.


text:
Q: Push Notification from Web based application to Android I have developed web based application using yii2 framework and MySQL database and my plan is i want to make an android app that can receive notification from my web based application real time and can pull data from it too. but i'm not sure how can make it works and using which methods i can implement this. can you give me some advise and source to learn it?
thanks

A: You have to follow below steps to implement push notification
1) You have to register on google developer consol
https://accounts.google.com/ServiceLogin?service=cloudconsole&osid=1&passive=true&continue=https://console.developers.google.com/dcredirect/
2)enable the GCM api from api list that available in api lists further instruction you will get on site when you create account.
3)Generate key for GCM web/ android.
4) Use this GCM key from android app and write the the GCM notification receiver
program in android app and using notification manager show on notification bar.
5)Using server side key you can write the program to push notification from web site.


text:
Q: Address Book: custom phone number labels when Exchange set up I have an app with partial copying of native Contacts app functionality. Then, I meet such bug: on some devices, I create new contact, add phone number with kABPersonPhoneIPhoneLabel, save it and read later, the number has no label! When investigated, I found that issue occurs only if Exchange account contacts sync (Google in my case) is turned on. Also, check the list of labels to choose in cases when Exchange sync is ON and OFF. (please note, that you should have no contacts in address book)
Exchange is OFF, phone numbers available labels are:

*

*mobile, iPhone, home, work, main, home fax, work fax, other fax,
pager, other

and user can add custom labels.
Exchange is ON, the labels are:

*

*mobile, home, work, home fax, work fax, pager, assistant, car,
company main, radio

and user CAN NOT add custom labels
My app handle only standard labels, mentioned in first case.
So, the question is: how can I retrieve available labels list, and how to know is user allowed to add custom labels or no?
Thank you for answer, or any related info about this.

A: You can add labels with:
bool ABMultiValueAddValueAndLabel (
   ABMutableMultiValueRef multiValue,
   CFTypeRef value,
   CFStringRef label,
   ABMultiValueIdentifier *outIdentifier
);


text:
Q: Bijection from $\mathbb Z$ to $\{\pm2+\frac1{n+1}\}$ Let $A=\{ 2+\frac{1}{n+1} ,\quad -2+\frac{1}{n+1} \mid\quad n=0,1,\ldots \}$.
Find a bijection from $\mathbb{Z}$ to $A$.
I try to set $f : \mathbb{Z} \to A $ where $f(k)=2+\frac{1}{k+1}$ if $k\geq 0$ and $f(k)=-2+\frac{1}{k+1} $ if $k <0 $. But this does not work.
Can you give some ideas?
Thank you!

A: Hints:

*

*Can you find a bijection between $\{m\in\mathbb{Z}\mid m\geq 0\}$ and $\{2 + \frac{1}{n+1}\mid n=0,1,2,\ldots\}$?

*Can you find a bijection between $\{m\in\mathbb{Z}\mid m\geq 0\}$ and $\{-2+\frac{1}{n+1}\mid 0,1,2,\ldots\}$?

*Can you find a bijection between $\{k\in\mathbb{Z}\mid k\lt 0\}$ and $\{m\in\mathbb{Z}\mid m\geq 0\}$?

A: Your idea almost works. Make no change when $k \ge 0$. When $k<0$, send $k$ to $-2+\frac{1}{|k|}$.
Comment: Before we get to formulas, let's think about what the set $A$ looks like. It consists of
$2+\frac{1}{1}$, $2+\frac{1}{2}$, $2+\frac{1}{3}$, and so on, together with
$-2+\frac{1}{1}$, $-2+\frac{1}{2}$, $-2+\frac{1}{3}$, and so on.
It seems reasonable to send $0$ to $2+\frac{1}{1}$, to send $1$ to $2+\frac{1}{2}$, to send $2$ to $2+\frac{1}{3}$, and so on.  The definition of $f(k)$ for $k \ge 0$ is then clear.
Then it seems natural to send $-1$ to $-2+\frac{1}{1}$, to send $-2$ to $-2+\frac{1}{2}$, to send $-3$ to $-2+\frac{1}{3}$, and so on.  The definition of $f(k)$ for $k < 0$ is then clear. (Instead of writing $2-\frac{1}{|k|}$ we could write $f(k)=-2-\frac{1}{k}$.  But I feel more comfortable with positive numbers.)
The fact that $f$ is bijective is intuitively absolutely obvious, and (almost) does not require proof. However, if proof is asked for, it is easy to write down.


text:
Q: Animating a DIV automatically http://jsfiddle.net/AndyMP/fVKDy/
This fiddle illustrates a problem I am trying to solve. The container DIV accommodates two DIVs which are animated across. The second DIV has a smaller height than the first because there is less content. What I am trying to do is get the bottom DIV to slide up automatically according to the height of the content in the second DIV when it is visible. But it slides up and over the second DIV.
Any thoughts on how to solve this?
$(function() {
    $(".left_slide").click(function() {
        $(".block1").stop(true, true).animate({ left: -400 }, 500).hide(1000);
        $(".block2").stop(true, true).animate({ left: 0 }, 500);
    });
});
$(function() {
    $(".right_slide").click(function() {
        $(".block2").stop(true, true).animate({ left: 400 }, 500);
        $(".block1").stop(true, true).animate({ left: 0 }, 500);
    });
});

CSS
#blog_slide_container {
position: relative;
width: 400px;
z-index: 5;
overflow: hidden;
border: 1px solid #000;
}
.block1 {
position: relative;
top: 0px;
left: 0px;
width: 400px;
z-index: 6;
background-color: #333;
color: #FFF;
}
.block2 {
position: absolute;
top: 0px;
left: 400px;
width: 400px;
z-index: 6;
background-color: #CCC;
color: #FFF;
}
#bottom_container {
position: relative;
float: left;
width: 100%;
height: 280px;
z-index: 3;
background-color: #000;
}

A: Edit:
Check my updated fiddle
Added code to dynamically change the container height.
Check animated version http://jsfiddle.net/skram/fVKDy/17/
Another version.. http://jsfiddle.net/skram/fVKDy/16/ <-- Difference is that the left/right shift happens after the bottom blocks slides up/down.

Check the updated fiddle demo.
Two things,

*

*Added a fixed height to the #blog_slide_container. When you animate, the position of the animating div becomes absolute and so the container re-sizes itself to 0 height.

*Added show on block1 when right is clicked.

A: This is it... i guess -> http://jsfiddle.net/fVKDy/13/
Both parts are working here.
Just put another wrapper to your blocks and delete those position relatives. The only non static positioning you need is on the additional wrapper.

Here is another version. http://jsfiddle.net/fVKDy/5/
Iam going to tweak it a bit more..

A: I believe this is what you're looking for.
http://jsfiddle.net/fVKDy/11/
I will come back shortly and edit in an explanation (have to run).  But basically I added an inner container which is animated instead of the elements themselves.


text:
Q: Accurate sleep duration AutoIt I'm using an AutoIt program to manage the placement of a few windows at the moment, and I need to implement a way to cycle between activated windows at specific time intervals (on the order of every ~2 seconds).
This needs to be fairly regular, though extraordinary precision is not necessary. My initial concern is that if I just implement a simple sleep command in my main GUI's while loop, it might not be regular - for instance, if another action is executed at any point while the timer is going, it will delay the time until the sleep command is run again.
I looked through SO and the AutoIt forums and didn't see any simple way to address this. I think using a run command to launch a separate AutoIt program to do the timing would work reasonably well (in a messier way than I would prefer) because it would spawn a new process, but again, this is a messier solution than I would prefer.
Does anybody know of a better way to do this? Even a way to spawn a new process or thread within the same AutoIt program would be wonderful. Thanks

A: Okay, have a look at _Timer_SetTimer in the helpfile.
For creating a second process have a look here:
https://www.autoitscript.com/forum/topic/103630-time-control/


text:
Q: Disk Partition in Linux Hi guys I made partitions in my HDD during the installation of parrot security. The problem is that I cannot see those Partitions anywhere. They exist physically, I checked via  (sudo fdisk -l) and the output is :

Is there something wrong? In my file manager it shows 3 drives

*

*CD ROM

*TOSHIBA MQ01ABD100 (My HDD)

*File System (Here it shows 100 gb which I declared bootable)

When I try to open my HDD (toshiba MQ...) it says : Unable To Mount File Location  Any Idea why this is happening? Did I partition my disk wrong?

A: The output from fdisk shows you have 4 partitions on one drive, the first one is bootable (likely where your system has been installed to) and the third one is useable as swap.
fdisk only shows the partitions, not the filesystems on those partitions. To see the filesystems use sudo parted -l /dev/sda or sudo blkid -c /dev/null /dev/sda*. If they do not have a filesystem you first need to format them with one. This can be done with the mkfs.* tools (warning these tools will destroy any data on the partitions they format). For example, to format your second drive as ext4 run the following; only if you are sure there is nothing on that partition already.
sudo mkfs.ext4 /dev/sda2

Linux, unlike windows, has a global directory tree where filesystems can be mounted. By default linux distros mount your system partition to the root of this directory tree (aka /, or the root filesystem). Other partitions can be mounted anywhere you want. You can see a list of mounted filesystems and where they are mounted by running mount. On modern distros this will show a lot of virtual filesystems, you can filter these out by running mount | grep '^/dev'.
To mount a filesystem to the directory tree you can run the following:
sudo mount /dev/sdXY /path/to/mount/point

For example, to mount your second partition (assuming it has a file system on it) to /mnt/p2 (this is a typical location you that internal/manually mounted filesystems are placed; but it can be any path of your choosing) run
sudo mkdir /mnt/p2
sudo mount /dev/sda2 /mnt/p2

Now any file you write to /mnt/p2 will be written to your second partition. This will only last until you reboot, to make your system remount it at boot add the following line to /etc/fstab (assuming it is formated with ext4).
/dev/sda2               /mnt/p2           ext4            defaults    0 0

To test this entry you can unmount it with unmount /mnt/p2; if it is mounted. Then run mount -a to mount everything listed in /etc/fstab.
Traditionally internal drives are setup with way on linux as such only root is allowed to do this by default so your gui file browser cannot, but the feature that lists partitions is included for removable media, which users are allowed to mount on modern linux distros. It also gives you quick access to the root of your filesystems once mounted. It is far easier to just configure the drives to mount at boot then to allow users to mount them at will.

A: I think you only created the partition, i.e. you reserved the disk space.
Now you should prepare the partitions (formatting them), e.g. with mkfs and mkswap. Only after this phase, you can mount the partitions.

A: Run command "lsblk". It will show your device with mount point. Try to manually mount them.


text:
Q: Audio assets in Rails brings No route matches I'm trying to use an audio file in rails. I created a folder audios under app\assets\. I would like to use the assets precompile so that I don't have to put the file under app\public
Right now I'm getting
ActionController::RoutingError (No route matches [GET] "/audios/audio_file.wav")

If I change the url from URL/audios/audio_file.wav to URL/assets/audio_file.wav it works. How can I fix the problem? What is the right way?

A: First, in case you didn't realize it already: your new app/assets/audios folder is already in the load path... you just need to restart your server for Sprockets to pick it up.
In development, assets are available at the relative url: /assets/<asset file name>.
For example, assuming your wav file is located at /app/assets/audios/audio_file.wav in the filesystem, it would be accessible at the relative url /assets/audio_file.wav in the browser. This is because Sprockets/Dev-Rails knows to search the /app/assets folder and its subdirectories when locating assets.
In production, assets precompilation (typically) happens on deploy. At this time, your wav file is copied to e.g. /public/assets/audio_file-<MD5 fingerprint>.wav and is accessible at the relative url: /assets/audio_file-<MD5 fingerprint>.wav.
Because of the different naming styles used between development and production, any time you want to refer to an asset you should do so using a helper method (even in CSS!). That is, production includes the MD5 fingerprint, whereas development does not. But you don't have to worry about any of that so long as you use a helper:

*

*For images: <%= image_tag('homes/logo.png') %> -- given an image file that lives in /app/assets/images/homes/logo.png on the file system.

*For non-standard assets, such as audio files: <%= asset_path('audio_file.wav') %>, which would produce a relative path of /assets/audio_file.wav.


text:
Q: How to make a simple post request with HttpClient Say I have the below method
    [HttpPost()]
    [Route("Api/IsUserValid/{username}/{password}")]
    public string ValidateUser(string username, string password)
    {
        var user = _context.USERS.FirstOrDefault(x => x.U_NAME.Equals(username) && x.U_PASSWORD.Equals(password));

        var jsonIzedUser = JsonConvert.SerializeObject(user);

        return jsonIzedUser;
    }

I would like to make a post request from the xamarin project and below is my code to make the post request
using (var httpClient = new HttpClient())
{
    var content = new FormUrlEncodedContent(new[]
           {
        new KeyValuePair<string, string>("username","ASIM"),
        new KeyValuePair<string, string>("password","xxxx")
    });
    var response = await httpClient.PostAsync("http://10.0.2.2:44342/Api/IsUserValid", content);
     string result = await response.Content.ReadAsStringAsync();

}

and Finally the error I get
StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  Date: Sun, 15 Mar 2020 17:02:46 GMT
  Server: Microsoft-IIS/10.0
  Transfer-Encoding: chunked
  X-Android-Received-Millis: 1584291766080
  X-Android-Response-Source: NETWORK 404
  X-Android-Selected-Protocol: http/1.1
  X-Android-Sent-Millis: 1584291765810
  X-Powered-By: ASP.NET
}

What is it that I'M missing here?

A: Here, you declared the route parameters for username and password, which is dangerous!
[Route("Api/IsUserValid/{username}/{password}")]
public string ValidateUser(string username, string password)

At least you need to use form. So, change the code to
[Route("Api/IsUserValid")]
public string ValidateUser([FromForm] string username, [FromForm] string password)

then your code to post from the xamarin project should work without any changes


text:
Q: LocationManager inconsistent I am using core location to store lat/long coordinates. I have the following code in viewDidLoad.
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationManager.distanceFilter = kCLDistanceFilterNone;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
    [self.locationManager startUpdatingLocation];

Here is my delegate method.
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    [self.locationManager stopUpdatingLocation];
    CLLocation* loc = [locations lastObject]; // locations is guaranteed to have at least one object
    float latitude = loc.coordinate.latitude;
    float longitude = loc.coordinate.longitude;
    self.lat = [NSString stringWithFormat:@"%.8f",latitude];
    self.longString = [NSString stringWithFormat:@"%.8f",longitude];
}

I'm using GPS to track these coordinates and it seems inconsistent. Upon launching the app, the location services icon does not show up often. However, if I toggle my wifi, it'll work. Or, if I open the Maps app and prompt it to obtain my current location, and then switch to my app, it'll work. Sometimes, it'll just work irregardless. If the location services icon doesn't show up then my lat/long values are null. Any ideas? Thanks in advance!

A: The problem is that you are immediately stopping updating locations when the very first update arrives. That's like flicking a light switch on and off so fast that there's no time for the light bulb to start glowing. It takes time and several updates for all the sensors to warm up and get a decent fix, especially the GPS. You need to allow enough updates to arrive until you do in fact have a location (and you probably want to check the accuracy to make sure it is a reasonably accurate location).


text:
Q: jQuery autocomplete from PHP mySQL query displaying improperly I am using this autocomplete tut: http://www.jensbits.com/2010/03/29/jquery-ui-autocomplete-widget-with-php-and-mysql/ .
The jQuery aren't displaying. You can actually click the grey line (shown in picture) and it will load everything. I just can't see the names for some reason.
I thought it could be a css problem, but I couldn't find anything relevant.

        <form action='' method="POST">

Exisiting Guest
            <input type="text" class="auto" name="guests" id="guests"/>

First Name<input readonly="readonly" type="text" id="firstname" name="firstname"/>

Last Name<input readonly="readonly" type="text" id="lastname" name="lastname"/>

Address<input readonly="readonly" type="text" id="address" name="address"/>

Phone<input readonly="readonly" type="text" id="phone" name="phone"/>

        </form>

autocomplete_guests.php
<?php
//open connection
require_once('../config/db.php');
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);

$return_arr = array();

/* If connection to database, run sql statement. */
if ($con)
{
    $fetch = mysqli_query($con, "SELECT * FROM guests WHERE lname like '%".mysqli_real_escape_string($con, $_GET['term'])."%'");

    /* Retrieve and store in array the results of the query.*/
    while ($row = mysqli_fetch_array($fetch, MYSQL_ASSOC)) {
        $row_array['id'] = $row['id'];
        $row_array['lname'] = $row['lname'];
        $row_array['fname'] = $row['fname'];
        $row_array['gender'] = $row['gender'];
        $row_array['address'] = $row['address'];
        $row_array['city'] = $row['city'];
        $row_array['state'] = $row['state'];
        $row_array['phone'] = $row['phone'];
        $row_array['email'] = $row['email'];
        $row_array['dob'] = $row['dob'];
        $row_array['zip'] = $row['zip'];

        array_push($return_arr,$row_array);
    }
}

/* Free connection resources. */
mysqli_close($con);

/* Toss back results as json encoded array. */
echo json_encode($return_arr);
?>

A: You should
1) write script tags like


text:
Q: How to override operator and (&&) for generic predicate in swift? I have a class that has information about data filtering before this data. I want to save the filtering predicate to use it in the future stage when data will be given. The filtering predicate is a combination of other predicates, and I found that it will be useful to create the function for combining them as I will need.
func and<T>(_ lth: @escaping (T) -> Bool,
            _ rth: @escaping (T) -> Bool) -> (T) -> Bool {

    return { o in lth(o) && rth(o) }
}

Example of use:
func xIsNot(_ x: Int) -> (Int, Int) -> Bool {
    return { x1, _ in x != x1 }
}

func yIsNot(_ y: Int) -> (Int, Int) -> Bool {
    return { _, y1 in y != y1 }
}

let predicate = someCondition
    ? and(and(xIsNot(7), xIsNot(8)), yIsNot(9))
    : and(xIsNot(2), yIsNot(3))

let points: [(Int, Int)] = ...
let actualPoints = points.filter(predicate)

It works fine but hasn't good readability. The following looks much better:
let predicate = someCondition
    ? xIsNot(7) && xIsNot(8) && yIsNot(9)
    : xIsNot(2) && yIsNot(3)

Is it possible to override operator && to replace and? How?

A: You may try this :
infix operator &&& : AdditionPrecedence
func &&&<T>(_ lth: @escaping (T) -> Bool,
        _ rth: @escaping (T) -> Bool) -> (T) -> Bool {
return { x in lth(x) && rth(x) }
}

let predicate = true
? xIsNot(7) &&& xIsNot(8) &&& yIsNot(9)
: xIsNot(2) &&& yIsNot(3)

let points: [(Int, Int)] = [(1,2),(7,3)]
let actualPoints = points.filter(predicate)

The following && is also working.
infix operator && : AdditionPrecedence
func &&<T>(_ lth: @escaping (T) -> Bool,
        _ rth: @escaping (T) -> Bool) -> (T) -> Bool {
return { x in lth(x) && rth(x) }
}

let predicate = true
? xIsNot(7) && xIsNot(8) && yIsNot(9)
: xIsNot(2) && yIsNot(3)


text:
Q: Error at if else condition parsing I am trying to fetch JSON data from an url and storing in sqlite db.From sqlite db i am converting the data in to JSON array of objects and using that values i am tryinf to perform if and else condition I have n no of objects in JSON created_at and field3 is the data to be performed in this if field3 is 0 i have to ignore and if field3 is 1 we have to calculate the date n time diff from that obj date n time to the next obj where field3 end with 1.My code is as follows.
function renderList1(tx,result){
    newJson = [ ];
    if (result != null && result.rows != null) {
        for (var k = 0; k < result.rows.length; k++) {
            var row = result.rows.item(k);
            newJson[k] = { created_at:row.Created_at,entry_id:row.entry_id,field1:row.Field1,field2:row.Field2,field3:row.Field3 };
        }
    }
    var jsonAll = JSON.stringify(newJson);
    console.log(jsonAll);
    var feeds = $.parseJSON(jsonAll);
    console.log(feeds);

    power();
    function power(){
    for (var i=0;i<feeds.length;i++) //feeds contain the JSON data
    {
        if(feeds[i]["field3"] === "1"){
        //Start Time
        var d1 = new Date(feeds[i]["created_at"]);
        console.log(d1);
        for (var j=i+1;j<feeds.length;j++) //compare objects starting from 'i' till next "1" is found
        {
            if(feeds[j]["field3"] === "0")
            {
                //End Time
                var d2 = new Date(feeds[j]["created_at"]);
                console.log(d2);
                j=feeds.length;
            }
        }
        //Time difference in milli seconds
        var diff = d2.getTime() - d1.getTime();
        var diffInHours= diff / 1000diff/ 3600 / 1000;
        console.log(diffInHours);
        var pow = Powercon * diffInHours;
        console.log(pow);
    }else{
        console.log("Field3 is 0");
        }
    }
}

JSON Data:
[
{
    "created_at": "2017-04-12T08:53:46Z",
    "entry_id": 37368,
    "field1": "14",
    "field2": "0",
    "field3": "0"
},
{
    "created_at": "2017-04-12T09:03:54Z",
    "entry_id": 37369,
    "field1": "14",
    "field2": "0",
    "field3": "0"
},
{
    "created_at": "2017-04-12T09:14:02Z",
    "entry_id": 37370,
    "field1": "14",
    "field2": "0",
    "field3": "0"
},
{
    "created_at": "2017-04-12T09:24:03Z",
    "entry_id": 37371,
    "field1": "15",
    "field2": "0",
    "field3": "0"
},
{
    "created_at": "2017-04-12T09:34:06Z",
    "entry_id": 37372,
    "field1": "15",
    "field2": "0",
    "field3": "0"
},
{
    "created_at": "2017-04-12T09:44:09Z",
    "entry_id": 37373,
    "field1": "15",
    "field2": "0",
    "field3": "0"
},
{
    "created_at": "2017-04-12T09:54:12Z",
    "entry_id": 37374,
    "field1": "15",
    "field2": "0",
    "field3": "0"
},
{
    "created_at": "2017-04-12T10:04:20Z",
    "entry_id": 37375,
    "field1": "15",
    "field2": "0",
    "field3": "0"
},
{
    "created_at": "2017-04-12T10:24:20Z",
    "entry_id": 37376,
    "field1": "15",
    "field2": "0",
    "field3": "0"
},
{
    "created_at": "2017-04-12T10:44:27Z",
    "entry_id": 37377,
    "field1": "15",
    "field2": "0",
    "field3": "0"
},
{
    "created_at": "2017-04-12T10:54:30Z",
    "entry_id": 37378,
    "field1": "15",
    "field2": "0",
    "field3": "0"
},
{
    "created_at": "2017-04-12T11:04:34Z",
    "entry_id": 37379,
    "field1": "16",
    "field2": "0",
    "field3": "0"
},
{
    "created_at": "2017-04-12T11:14:37Z",
    "entry_id": 37380,
    "field1": "16",
    "field2": "0",
    "field3": "0"
},
{
    "created_at": "2017-04-12T11:24:40Z",
    "entry_id": 37381,
    "field1": "15",
    "field2": "0",
    "field3": "0"
},
{
    "created_at": "2017-04-12T11:34:43Z",
    "entry_id": 37382,
    "field1": "15",
    "field2": "0",
    "field3": "0"
},
{
    "created_at": "2017-04-12T11:44:46Z",
    "entry_id": 37383,
    "field1": "15",
    "field2": "0",
    "field3": "0"
},
{
    "created_at": "2017-04-12T11:54:49Z",
    "entry_id": 37384,
    "field1": "16",
    "field2": "0",
    "field3": "0"
},
{
    "created_at": "2017-04-12T12:04:53Z",
    "entry_id": 37385,
    "field1": "15",
    "field2": "0",
    "field3": "0"
},
{
    "created_at": "2017-04-12T12:14:56Z",
    "entry_id": 37386,
    "field1": "15",
    "field2": "0",
    "field3": "0"
},
{
    "created_at": "2017-04-12T12:25:00Z",
    "entry_id": 37387,
    "field1": "16",
    "field2": "0",
    "field3": "0"
}
]

I tried above code when i run the i got a problem at if and else conditions if field3 is equal to 1 it should perform if condition but it is going to else condition.Can anyone help me where it is going wrong???Thankyou

A: if(feeds[i]["field3"] === 1){

Should solve the problem. Its treated as an integer. Also you should consider using higher order functions or lodash.js which would be very helpful in array manipulation and make your code more easy to manage and readable.


text:
Q: Sencha Touch 2 instantiating a component with a background image I'm working with Sencha Touch 2 components now.
I'm facing the following issue:
I set a background image to my components using stylesheets. My whole scene is made up of several components / containers having background images. When I instantiate my scene - the image loading process is asynchronous - i.e. my scene is displayed and then later images in the scene are loaded and displayed.
I would like to know how to wait until all my images are loaded and then display my scene. In fact, I can use Ext.Img class and its load event, but this is what I don't want to do. I need to style my images (as backgrounds) using stylesheets.
Thanks a lot.

A: If the images are small try embedding them as base64 encoded strings. And use them like
background: transparent url(data:image/png;base64,LONG-STRING-OF-BASE64-TEXT)

in the css.

A: For adding background image on different components/containers define your CSS like this:-
 .x-panel{
   background:url(image.jpg)no-repeat center;
  }

 .x-scroll-container{
  background:url(image.jpg)no-repeat center;
  }
  .x-tab.panel{
   background:url(image.jpg)no-repeat center;
  }

Include this CSS in your index.html in the head section :-
  <link rel="stylesheet" type="text/css" href="style.css"/>

Hope this helps.


text:
Q: how to send a data between two android app one of them is unity game I am trying to make an android game (using unity game engine) and I want this game to have a speech recognition feature.
I want to make speech recognition using android application which uses google API, but I want to send the result of recognition to another app which is the unity game.
How can I do it ? Is it valid ?
P.S.: I know that google provides a plugin for unity but I do not want to use it.

A: You can use Services.  Bounded services with a Messenger that will serve as the mediator between the remote and local process or with AIDL interface. You can also create a receiver on the remote process to receive the service obtained and a service(the sender).  Here is a good link for step by step: http://jeanmeyblum.weebly.com/scripts--tutorials/communication-between-an-android-app-and-unity


text:
Q: Random string from a set of available strings in Excel but exclude specific Cell Value I'm using Excel 2010.  I'm using an INDEX and RANDBETWEEN function to lookup a list of available strings and return one of them.  However, I have a specific value, D3, (in this instance but will change with each row D4, D5 etc) that I need to exclude from the random results - what is the best way to achieve this?  This is my current formula:
=IFERROR(INDEX($A:$D,MATCH($B3&"|"&LEFT($C3,SEARCH("-",$C3))&L3,$A:$A,0)+RANDBETWEEN(0,S3-1),4),"")

Thanks

A: Please remove those code parts not relevant to your issue and reduce everything to the problem you actually need to solve. The IFERROR(), MATCH(), LEFT() and SEARCH() calls are not related to your issue but make it hard to understand your code.
To simplify, I assume:

*

*range D1:D199 is filled with (potentially duplicate) strings

*each cell in column E1:E199 is supposed to draw a random string from the whole of D1:D199, except those that are identical to the cell on its left (in D)

Copy + paste the following code into E1, then enter it as an array formula with Ctrl+Shift+Enter.
=INDEX(D:D,LARGE(IF((D1:D200<>"")*(D1:D200<>D1),ROW(D1:D200),-1),RANDBETWEEN(1,SUM((D1:D200<>"")*(D1:D200<>D1)))))

You can then copy cell E1 to E2:E199
Updated code with Dirk Reichel's suggestions.


text:
Q: LinkedHashSet appears to be leaving a duplicate element I am curious if anyone knows why the first element in my LinkHashSet seems to be allowing duplicates? I am doing a code challenge from CodeEval and when I input values 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 6 the output from my program displays 2, 2, 3, 4, 5, 6 It's only the first element that is causing the problem.
I am using jre 1.8.0_45. I got tired of troubleshooting the issue and checked in the challenge and the website accepted my solution, so I am wondering if there is a bug in my version of Java. I searched and have seen no other posts of anyone having issues with LinkHashSet producing duplicates.
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;

public class UniqueElements
{

    public static void main(String[] args) {
        Scanner  s = new Scanner(System.in);
        String line = s.nextLine();

        List<String> list = Arrays.asList(line.trim().split(","));

        Set<String> string = new LinkedHashSet<>(list);

        Iterator<String> iter = string.iterator();

         while (true)
         {
             System.out.print(iter.next());

             if (iter.hasNext()) {
                 System.out.print(",");
             } else {
                 System.out.println();
                 break;
             }
         }

    }
}

A: Your problem is here:
List<String> list = Arrays.asList(line.trim().split(","));

It creates a list where the first element is "2" and the second is " 2" (note the leading space).
You need to remove the spaces from the input or split on ", " or "\\s*,\\s*" to allow for spaces before and after the commas.

A: You've wisely used the trim() method, but you're not getting all the whitespace from between the list entries. Did you notice that your output list has spaces between the numbers, but your output println doesn't insert any?
The first "2" has no leading whitespace. The second " 2" has a leading space. That makes them different Strings. Get rid of the space, get rid of the problem.
Using a different regular expression on your split() would help. How about .split(",\\s*")?
Another option: why are you using String values in the first place? If they are all numeric and guaranteed to be so (and the challenge would state that), then converting to Number (or even Integer, if that's the guarantee) would make the extraneous spaces irrelevant.