text:
Q: Compare/Diff Multiple (>Millions) Arrays I'm not sure if this is possible; but I have millions of "lists" in a MySQL database, and would like develop a system where I take one of the lists; and compare it against all of the other lists in the database and return:
1.) Lists that closely resemble the primary list (some sort of % would be great)
2.) Given a certain items in a list; it would return a list of of items that are included in the majority of all the other lists (ie. autocomplete a list based on popular options).
I would've intially thought this would've been possible if I could create some sort of 'loose hash' that I can compare lists mathematically, but I haven't been able to find a solution that scales (since this is exponential when tackled head-on).
Any new ideas/solutions would be greatly appreciated. Thanks!

A: Your basic MD5 is a (somewhat) loose hash, supported by both php and mysql and quite fast in these kind of things.  Just get an MD5 of what ever data and compare it to others.
Do it in PHP, store the MD5 of the data in array key an use if isset().

A: Your part 2) Given a certain items in a list; it would return a list of of items that are included in the majority of all the other lists (ie. autocomplete a list based on popular options).
is not very clear, but I interpret it as: Given few items, find all lists that contain all or most of the items.
This should be easy once you create an index on your list elements, essentially like a hash table. The exact query will depend on your requirement, length of lists (whether that is a factor in defining the specs, etc).

A: If you're saying there are millions of lists, itnis really not an option to load them all into a php script.
You could get the values of the list you are comparing the others to, and then run an SQL query similar to this:
SELECT list_id, COUNT(value) as c FROM lists WHERE value IN (a,b,c) GROUP BY list_id
ORDER BY c DESC

I'm not sure the sql is correct, but the idea is to select the ids of the lists that have the same members in them and then sort the output by the number of list items that intersect with the original list. The percenage of item correspondence is easily obtained in this case.


text:
Q: Javascript - Error: 102 bad type for inQuery Parse.com When I run this code in the cloud I get bad inner query error when it should be matching results. Do the objectId's of the objects have to match?
Here is the code:
Parse.Cloud.define("itemsInfo", function(request, response) {

var TestItems = Parse.Object.extend("TestItem");
var UserFavorites = Parse.Object.extend("UserFavourite");

var testItemsQuery = new Parse.Query(TestItems);
var userFavoritesQuery = new Parse.Query(UserFavorites);
var installationQuery = new Parse.Query(Parse.Installation);

testItemsQuery.exists('item');
testItemsQuery.equalTo('school', 'Union College (NY)');

userFavoritesQuery.include('item'); //This makes sure to pull all of the favorite item data instead of just the pointer object
userFavoritesQuery.matchesQuery("item", testItemsQuery); //This will run this second query against the TestItems
//userFavoritesQuery.limit(1000); //limit results to 1000
//userFavoritesQuery.ascending('userId'); //group the user id's together in your array

userFavoritesQuery.find({
    success: function(results) {
        console.log(results);

     },
    error: function(error) {
            alert("Error: " + error.code + " " + error.message);
     }

});

A: Would you try this? This will tell the query to compare the item object rather than the objectId. If it doesn't work, let me know.
userFavoritesQuery.matchesKeyInQuery('item', 'objectId', testItemsQuery);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using bottom navy bar flutter to navigate pages I'm using this package to navigate via the bottom navigation bar, I did not understand how to manage to navigate between my screens. How can I navigate between my screens via bottom navigation bar icons?
import 'dart:async';
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:bottom_navy_bar/bottom_navy_bar.dart';

class HaberScreen extends StatefulWidget {
  @override
  _HaberScreenState createState() => _HaberScreenState();
}

class _HaberScreenState extends State<HaberScreen> {
  final Completer<WebViewController> _controller =
      Completer<WebViewController>();

  @override
  void initState() {
    super.initState();
    if (Platform.isAndroid) WebView.platform = SurfaceAndroidWebView();
  }

  int _currentIndex = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PreferredSize(
        preferredSize: Size.fromHeight(60.0),
        child: AppBar(
          backgroundColor: Colors.white,
          automaticallyImplyLeading: true,
          leading: IconButton(
            icon: Icon(
              Icons.arrow_back_ios,
              color: Colors.red,
            ),
            //onPressed:() => Navigator.pop(context, false),
            onPressed: () => Navigator.pop(context),
          ),
          title: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                'Haberler',
                style: TextStyle(color: Colors.red, fontSize: 25.0),
              )
            ],
          ),

          // This drop down menu demonstrates that Flutter widgets can be shown over the web view.
          actions: <Widget>[
            NavigationControls(
              _controller.future,
            ),
          ],
        ),
      ),
      body: Builder(builder: (BuildContext context) {
        return WebView(
          initialUrl: 'https://www.google.com',
          javascriptMode: JavascriptMode.unrestricted,
          onWebViewCreated: (WebViewController webViewController) {
            _controller.complete(webViewController);
          },
          onProgress: (int progress) {
            print("WebView is loading (progress : $progress%)");
          },
          javascriptChannels: <JavascriptChannel>{
            _toasterJavascriptChannel(context),
          },
          navigationDelegate: (NavigationRequest request) {
            if (request.url.startsWith('https://www.youtube.com/')) {
              print('blocking navigation to $request}');
              return NavigationDecision.prevent;
            }
            print('allowing navigation to $request');
            return NavigationDecision.navigate;
          },
          onPageStarted: (String url) {
            print('Page started loading: $url');
          },
          onPageFinished: (String url) {
            print('Page finished loading: $url');
          },
          gestureNavigationEnabled: true,
        );
      }),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
      floatingActionButton: favoriteButton(),

      bottomNavigationBar: BottomNavyBar(
        selectedIndex: _currentIndex,
        showElevation: true,
        itemCornerRadius: 24,
        curve: Curves.easeIn,
        onItemSelected: (index) => setState(() => _currentIndex = index),
        items: <BottomNavyBarItem>[
          BottomNavyBarItem(
            icon: Icon(Icons.apps),
            title: Text('Haberler'),
            activeColor: Colors.red,
            textAlign: TextAlign.center,
          ),
          BottomNavyBarItem(
            icon: Icon(Icons.pie_chart),
            title: Text('Sektörler'),
            activeColor: Colors.red,
            textAlign: TextAlign.center,
          ),
          BottomNavyBarItem(
            icon: Icon(Icons.monetization_on),
            title: Text(
              'Kurlar',
            ),
            activeColor: Colors.red,
            textAlign: TextAlign.center,
          ),
          BottomNavyBarItem(
            icon: Icon(Icons.plagiarism_sharp),
            title: Text('Raporlar'),
            activeColor: Colors.red,
            textAlign: TextAlign.center,
          ),
          BottomNavyBarItem(
            icon: Icon(Icons.settings),
            title: Text('Ayarlar'),
            activeColor: Colors.red,
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }

  JavascriptChannel _toasterJavascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'Toaster',
        onMessageReceived: (JavascriptMessage message) {
          // ignore: deprecated_member_use
          Scaffold.of(context).showSnackBar(
            SnackBar(content: Text(message.message)),
          );
        });
  }

  Widget favoriteButton() {
    return FutureBuilder<WebViewController>(
        future: _controller.future,
        builder: (BuildContext context,
            AsyncSnapshot<WebViewController> controller) {
          if (controller.hasData) {
            return FloatingActionButton(
              onPressed: () async {
                final String url = (await controller.data!.currentUrl())!;
                // ignore: deprecated_member_use
                Scaffold.of(context).showSnackBar(
                  SnackBar(content: Text('Favorited $url')),
                );
              },
              child: const Icon(
                Icons.favorite,
                color: Colors.white,
              ),
            );
          }
          return Container();
        });
  }
}

class NavigationControls extends StatelessWidget {
  const NavigationControls(this._webViewControllerFuture)
      : assert(_webViewControllerFuture != null);

  final Future<WebViewController> _webViewControllerFuture;

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<WebViewController>(
      future: _webViewControllerFuture,
      builder:
          (BuildContext context, AsyncSnapshot<WebViewController> snapshot) {
        final bool webViewReady =
            snapshot.connectionState == ConnectionState.done;
        final WebViewController controller = snapshot.data!;
        return Row(
          children: <Widget>[
            IconButton(
              icon: const Icon(
                Icons.arrow_back_ios,
                color: Colors.red,
              ),
              onPressed: !webViewReady
                  ? null
                  : () async {
                      if (await controller.canGoBack()) {
                        await controller.goBack();
                      } else {
                        // ignore: deprecated_member_use
                        Scaffold.of(context).showSnackBar(
                          const SnackBar(content: Text("Geçmiş Bulunamadı")),
                        );
                        return;
                      }
                    },
            ),
            IconButton(
              icon: const Icon(
                Icons.arrow_forward_ios,
                color: Colors.red,
              ),
              onPressed: !webViewReady
                  ? null
                  : () async {
                      if (await controller.canGoForward()) {
                        await controller.goForward();
                      } else {
                        // ignore: deprecated_member_use
                        Scaffold.of(context).showSnackBar(
                          const SnackBar(content: Text("Geçmiş Bulunamadı")),
                        );
                        return;
                      }
                    },
            ),
          ],
        );
      },
    );
  }
}

A: you have provided only one widget as a body, so changing _currentIndex does not affect the displayed body. According to the example of this package ( in the Use with PageView and PageController section), you can use PageView for changing the display image! Or you can use a list of widgets and show the item that is related to the _currentIndex. so you have two solutions:

*

*using PageView
in your body section use PageView as follow:

  child: PageView(
          controller: _pageController,
          onPageChanged: (index) {
            setState(() => _currentIndex = index);
          },
          children: <Widget>[
            Container(color: Colors.blueGrey,),
            Container(color: Colors.red,),
            Container(color: Colors.green,),
            Container(color: Colors.blue,),
          ],
        ),
      ),

don't forget to create and dispose page controller:
PageController _pageController;

  @override
  void initState() {
    super.initState();
    _pageController = PageController();
  }

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

*using a list of widgets
create a list of widgets:

List<Widget> bodyList = [widget1, widget2, ...]

then provide it as body:
body: bodyList[_currentIndex]


text:
Q: Elastic Search - Failed to parse query I am using python-elasticsearch client - elasticsearch.py and elastic search fails to parse query when I try to update a document using update_by_query method.
My update body is as follows:
{
  'script': {
    'inline': 'ctx._source.viewers += info',
    'params': {
      'info': {
        'time': datetime.datetime(2017, 3, 7, 18, 8, 50),
        'viewer': 'abc@xyz.com'
      }
    }
  }
}

Elastic Search is called as follows::
update = es.update_by_query(index=index_el,
                            doc_type='1',
                            q='delivery_reference_id:' + str(cam_id) +'',
                            body=doc)

A sample value for cam_id is:
CAM_10_DATA_4_2017-03-07 18:02:07

Internally, the following query is formed::
http://127.0.0.1:9200/user_tracker/1/_update_by_query?q=delivery_reference_id%3ACAM_10_DATA_4_2017-03-07+18%3A02%3A07
The error received is as follows:
TransportError(400, 'search_phase_execution_exception', 'Failed to parse query [delivery_reference_id:CAM_10_DATA_4_2017-03-07 18:02:07]')

The full error log is as follows:
Traceback (most recent call last):
  File "C:\Users\catch\AppData\Roaming\Python\Python34\site-packages\django\core\handlers\exception.py", line 42, in inner
    response = get_response(request)
  File "C:\Users\catch\AppData\Roaming\Python\Python34\site-packages\django\core\handlers\base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\catch\AppData\Roaming\Python\Python34\site-packages\django\core\handlers\base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\catch\AppData\Roaming\Python\Python34\site-packages\django\views\decorators\csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "C:\Users\catch\AppData\Roaming\Python\Python34\site-packages\django\views\generic\base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Python34\lib\site-packages\rest_framework\views.py", line 483, in dispatch
    response = self.handle_exception(exc)
  File "C:\Python34\lib\site-packages\rest_framework\views.py", line 443, in handle_exception
    self.raise_uncaught_exception(exc)
  File "C:\Python34\lib\site-packages\rest_framework\views.py", line 480, in dispatch
    response = handler(request, *args, **kwargs)
  File "C:\Users\catch\PycharmProjects\myproject\myproj\apis\views.py", line 516, in get
    viewer=viewer_email)
  File "C:\Users\catch\PycharmProjects\myproject\myproj\apis\views.py", line 541, in update_track_info
    doc=doc)
  File "C:\Users\catch\PycharmProjects\myproject\myproj\apis\views.py", line 553, in es_update
    body=doc)
  File "C:\Python34\lib\site-packages\elasticsearch\client\utils.py", line 73, in _wrapped
    return func(*args, params=params, **kwargs)
  File "C:\Python34\lib\site-packages\elasticsearch\client\__init__.py", line 680, in update_by_query
    doc_type, '_update_by_query'), params=params, body=body)
  File "C:\Python34\lib\site-packages\elasticsearch\transport.py", line 318, in perform_request
    status, headers, data = connection.perform_request(method, url, params, body, ignore=ignore, timeout=timeout)
  File "C:\Python34\lib\site-packages\elasticsearch\connection\http_urllib3.py", line 128, in perform_request
    self._raise_error(response.status, raw_data)
  File "C:\Python34\lib\site-packages\elasticsearch\connection\base.py", line 122, in _raise_error
    raise HTTP_EXCEPTIONS.get(status_code, TransportError)(status_code, error_message, additional_info)
elasticsearch.exceptions.RequestError: TransportError(400, 'search_phase_execution_exception', 'Failed to parse query [delivery_reference_id:CAM_10_DATA_4_2017-03-07 18:02:07]')

Would be nice if someone figured it out. Let me know if more info is needed.
Appreciate it. Thanks in advance.

A: I think your query syntax is not up to date.  I had good results with the following syntax:
{
  "query": {
    "bool": {
      "must": [
        { "match": { "MYFIELD": "myoldvalue" } }
      ]
    }
  },
  "script": {
    "inline": "ctx._source.MYFIELD = \"mynewvalue\"",
    "lang": "painless"
  }
}

HTH :)


text:
Q: I want to create a profile page that retrieve data by using id but i try link the page using button and i got error I'm trying to use button that link the profile using by using id
if($result-> num_rows > 0){
    while ($row = $result-> fetch_assoc()) {

        echo "
". $row["ic"] ."	". $row["name"] ."	". $row["jawatan"] ."
";

        echo "
<button onclick="location.href='testProfile.php?id= $row["ic"]';">quick view</button>
";

    }
    echo "
";
 }

A: use anchor tag
echo '
quick view
';

A: if($result-> num_rows > 0){
    while ($row = $result-> fetch_assoc()) {

        echo "
". $row["ic"] ."	". $row["name"] ."	". $row["jawatan"] ."
";

        echo "
quick view
";

    }
    echo "
";
 }


text:
Q: Clear form field after error is encountered On my react native form, after wrong input values are inputted into the field, I'd have to return to the previous page, and then back to the form page before my submit can work.
Typing data in the input field and submitting doesn't do anything at all until the process described above has been done. No errors, no progress.
I'd want immediately an error occurs, for my submit button to still be able to process data from the input fields.
Below is what my submit Handler looks like:
 const submitHandler = async (values, actions) => {
    const {name, password} = values
    const data = {
      username: name,
      password: password,
    };
    console.log("data", data);
      await login(data, navigation.navigate, actions)

A: you have to create a ref for your Textinput then call clear text on that ref
const inputRef = useRef(null)

const clearText = ()=> inputRef.current.clear();

     <TextInput
        name="last_name"
        placeholder="Last name"
        ref={inputRef}
      />


text:
Q: HTML5/CSS3 Guides or tutorials Are there any highly recommended resources for getting started with HTML5 and CSS3 for designing web applications?
Seems to be the wave of the future..Lets hear everyones thoughts

A: http://net.tutsplus.com/tutorials/html-css-techniques/html-5-and-css-3-the-techniques-youll-soon-be-using/
http://www.w3schools.com/html5/html5_reference.asp
http://www.w3schools.com/css3/css3_reference.asp

A: I saw this the other day and it is super awesome
http://html5boilerplate.com/

HTML5 Boilerplate is the professional badass's base HTML/CSS/JS template for a fast, robust and future-proof site.
After more than two years in iterative development, you get the best of the best practices baked in: cross-browser normalization, performance optimizations, even optional features like cross-domain Ajax and Flash. A starter apache .htaccess config file hooks you the eff up with caching rules and preps your site to serve HTML5 video, use @font-face, and get your gzip zipple on.
Boilerplate is not a framework, nor does it prescribe any philosophy of development, it's just got some tricks to get your project off the ground quickly and right-footed.

A: There are about 20 articles covering specific aspects of HTML5 and CSS3 on Dev.Opera. See http://dev.opera.com/articles/tags/open%20web/ for an overview.


text:
Q: forwarding refs to non children in react I have an event listener that should fire onClick, except for if you click on the navbar/an item in the navbar.
usually, I'd handle this like this:
document.addEventListener('mousedown', this.handleOutsideClick);

handleOutsideClick = e => {
  if(!this.navREF.current.contains(e.target)){
    //do my stuff
  }
}

The problem is that the nav is far away from my component that has this logic and I don't really feel like passing the ref through 10+ components. Since findDomNode is deprecated/discouraged to use I was wondering if there was another way to handle this.
Is there a quicker way to pass my ref? I'm using redux for my other dataflow.
My worst case solution is to add a data attribute to every single item in my  nav but there's probably a 50% chance that that would get me fired..
Edit:
Different from other questions about the topic as the external component is outside of the scope of my react component

A: I didn't find a way to pass the ref, so instead I adapted this abomination
  checkIfParent = e => {
    let node = e.target;
    while (node) {
      if (node.id && node.id === 'ParentId') {
        return true;
      }
      node = node.parentNode;
    }
    return false;
  };


text:
Q: How to return to the main application when done clicked from calendar(default)? Is there any method to close the calendar application when "done" is pressed and return to the main application?
I think startActivityForResult(intent, int) can be used, but i'm not clear about how to use it.
This is my code:
Intent intent = new Intent(Intent.ACTION_EDIT);
    intent.setType("vnd.android.cursor.item/event");
    intent.putExtra("title", header);
    intent.putExtra("allDay", false);
    intent.putExtra("beginTime", startTimeStamp);
    intent.putExtra("endTime", endTimeStamp);
    intent.putExtra(Events.EVENT_LOCATION, location);
    intent.putExtra("description", note);
    FragmentCaller.removeFragment(getActivity());
    startActivityForResult(intent, 1);

A: you need to add this code in first Activity :
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

  if (requestCode == 1) {

     if(resultCode == RESULT_OK){
         String result=data.getStringExtra("result");
     }

  }
}//onActivityResult

and in second Activity this :
Intent returnIntent = new Intent();
 returnIntent.putExtra("result",result); // u wanna return data
 setResult(RESULT_OK,returnIntent);
 finish();


text:
Q: Firestore- How to get the id of a user that contains a specific value? My firestore structure contains a collection called users, that contains documents. Each user's document contains collection named user-info that includes the filed email.
Here is a picture that describes the structure of the firestore:

How to get the User ID (in green) from a specific email (in red), which is in user-info?
The function I wrote in the ts file is:(Does not work)
...
export class UsersList implements OnInit {
  ...
  constructor(private router: Router, private authservice: AuthService,public crudservice:CrudService) {}
  ....
  get_UserID_from_email(someEmail)
  {
    let user;
    this.crudservice.get_AllUsers().subscribe(data => {
      user = data.map(c => {
        console.log(c.payload.doc.data()['user-info']['email']);
        if(c.payload.doc.data()['user-info']['email'] == someEmail)
          return c.payload.doc;
      })
    });
  }
  ...
}

and in crud.service.ts:
...
export class CrudService {
  constructor(private authservice: AuthService, public fireservices:AngularFirestore) { }
  ...
  get_AllUsers()
  {
    return this.fireservices.collection('users').snapshotChanges();
  }
  ...
}

A: Here I have wrote the function how to get the child collection data in firestore. Can you please try with this code?
  parentId: any;
  getUser(email) {
    let docRef = this.fireservices.collection('users');
    const users = docRef.snapshotChanges().pipe(
      map((actions) =>
        actions.map((a) => {
          //this.parentId is your parent documentId which is in your image green color
          this.parentId = a.payload.doc.id;
          return docRef.doc(this.parentId).collection('user-info', ref => ref.where('email', '==', email)).valueChanges();
        })
      )
    );
    users.subscribe(data => {
      data[0].subscribe(child => {
        //Here you can get the child data which is in your image red color
        console.log(child[0]);
      });
    });
  }

Or else second way you can try with this code
  parentId: any = null;
  getUser(email) {
    let docRef = this.fireStore.collection('users');
    docRef.snapshotChanges().pipe(
      map((actions) =>
        actions.map((a) => {
          //this.parentId is your parent documentId which is in your image green color
          let parentId = a.payload.doc.id;
          return docRef.doc(parentId).collection('user-info', ref => ref.where('email', '==', email)).snapshotChanges().pipe(map((child) => child.map((childData) => {
            const data = childData.payload.doc.data() as any;
            const childDocId = childData.payload.doc.id;
            return { parentId, ...data };
          })));
        })
      )
    ).subscribe(data => {
      data[0].subscribe(childData => {
        //Here you can got the parent document Id
        childData[0].parentId;
      })
    });
  }

A: Try this:
 get_AllUsers(){
      return await this.fireservices.collection('users').doc('user-info')
                       .where('email', '==', 'try1@gmail.com').get()
                       .then(doc => {
                          return doc;
                       }).catch(error => {
                          console.log(error);
                       });
}

A:     import { AngularFirestore, CollectionReference } from '@angular/fire/firestore';

    constructor(private firestore: AngularFirestore){}
    this.firestore
              .collection('collectionName', (collectionRef: CollectionReference) =>
                collectionRef.where('email', '==', 'email')
              )
              .snapshotChanges()
              .subscribe((res) => {
                if (res.length > 0) {
                  this.user = res.map((e) => {
                    return {
                      id: e.payload.doc.id,
                      ...(e.payload.doc.data() as any),
                    };
                  })[0];
You can get user list. And if u console the id. You got the firebase data id.


text:
Q: Jasper Report Variable printing zero value I am working on a jasper report in which I am using following SQL query:
select SOURCE, count(*) as total
from CASE_UPLOADS
where UPLOAD_DT >= '20150601'
and UPLOAD_DT <= '20150630'
group by SOURCE
order by SOURCE

and the result is:
SOURCE,TOTAL
"New Application";15
"Periodic Report";16
"RD/RC";25

I have created variable like:
<variable name="PR" class="java.lang.Integer" calculation="Sum">
    <variableExpression><![CDATA[($F{source} == 'Periodic_Report') ? $F{total} : 0]]></variableExpression>
</variable>

This variable is printing zero value each time.
If I change conditional clause as follow:
<variable name="PR" class="java.lang.Integer" calculation="Sum">
    <variableExpression><![CDATA[($F{source} == 'Periodic Report') ? 0 : $F{total}]]></variableExpression>
 </variable>

Then its printing SUM 56 of TOTAL column.
Field declaration:
<field name="source" class="java.lang.String"/>
<field name="total" class="java.lang.Long"/>

Can someone please tell me what is wrong here?


text:
Q: It looks like somebody is using my Mac OS X server to brute force attack another server which is LDAP. What can I do to stop it? An LDAP server on another is reporting an unusually large number of attempts to read the LDAP directory and attempting a number of users, all of which look like hacking attempts to read user/password information. These happen every minute. It reports that the originating IP is a Mac OS X 10.4 Tiger Server which is a file server on the network for iMacs.
When I run lsof -i:ldap +c 0 on the Mac server, it returns
COMMAND          PID USER   FD   TYPE    DEVICE SIZE/OFF NODE NAME
DirectoryService  60 root   11u  IPv4 0x38de228      0t0  TCP mymacserver.com:50106->myldapserver.com:ldap (ESTABLISHED)

Running ps -Aj gives
USER PID PPID PGID    SESS JOBC STAT TT     TIME COMMAND
[...]
root  60    1   60 290c7e4    0 Ss   ??  0:19.00 /usr/sbin/DirectoryService

Running cat /Library/Logs/DirectoryService/DirectoryService.server.log gives
2012-02-15 15:01:29 EST - DirectoryService 2.1 (v353.6) starting up...
2012-02-15 15:01:29 EST - Initializing TCP ...
2012-02-15 15:01:29 EST - Plugin <Configure>, Version <1.7>, processed successfully.
2012-02-15 15:01:29 EST - Plugin <NetInfo>, Version <1.7.4>, processed successfully.
2012-02-15 15:01:29 EST - Plugin <LDAPv3>, Version <1.7.4>, processed successfully.
2012-02-15 15:01:29 EST - Plugin <Search>, Version <1.7>, processed successfully.
2012-02-15 15:01:29 EST - Plugin "Active Directory", Version "1.5.8", is set to load lazily.
2012-02-15 15:01:29 EST - Plugin "AppleTalk", Version "1.3", is set to load lazily.
2012-02-15 15:01:29 EST - Plugin "Bonjour", Version "1.3", loaded successfully.
2012-02-15 15:01:29 EST - Plugin "BSD", Version "1.2.2", is set to load lazily.
2012-02-15 15:01:29 EST - Plugin "PasswordServer", Version "3.1.2", is set to load lazily.
2012-02-15 15:01:29 EST - Plugin "SLP", Version "1.3.1", is set to load lazily.
2012-02-15 15:01:29 EST - Plugin "SMB", Version "1.3", is set to load lazily.
2012-02-15 15:01:29 EST - Registered node /Configure
2012-02-15 15:01:29 EST - Registered node /Search
2012-02-15 15:01:29 EST - Plug-in Configure state is now active.
2012-02-15 15:01:29 EST - Registered node /Search/Contacts
2012-02-15 15:01:29 EST - Registered node /Search/Network
2012-02-15 15:01:29 EST - Plug-in Bonjour state is now active.
2012-02-15 15:01:29 EST - Plug-in Search state is now active.
2012-02-15 15:01:29 EST - Plug-in LDAPv3 state is now active.
2012-02-15 15:01:29 EST - Registered node /NetInfo/DefaultLocalNode
2012-02-15 15:01:29 EST - Plug-in NetInfo state is now active.
2012-02-15 15:01:32 EST - Network transition occurred.
2012-02-15 15:01:35 EST - Registered Locally Hosted Node /NetInfo/DefaultLocalNode
2012-02-15 15:01:41 EST - Network transition occurred.
2012-02-15 15:01:41 EST - Network transition occurred.
2012-02-15 15:01:41 EST - Network transition occurred.

(The time is when the server was rebooted several hours ago.) This has been going on for several days.
Is there a way to see what is calling the DirectoryService every minute?
I cannot use netstat -p, since Mac OS X 10.4 Tiger does not support the -p option.
I need to disable this malicious script, but I cannot disable the LDAP client completely, as users rely on this server for file storage and user ids.
EDIT:
I ran sudo killall -USR1 DirectoryService to enable to debug log, and it seems that memberd and lookupd are calling DirectoryService.

A: The usual studd:

*

*Pull server from network.

*Totally wipe it, start reinstalling from known safe sources (OS discs)

*Reinstall everything.

*Make sure you dont makemistakes and patche everything up.

*Restore data from backup.

it is not "a script", you dont know what other stuff a hacker may have installed.


text:
Q: CSS different when loaded inside a iframe I have a very basic html preview editor
When below html is typed in and preview button is clicked, the font-fmaily of css isnt loading in iframe
The expected output is

But my iframe shows as

Which means the font isnt loading properly in my iframe
This is the code that you need to paste in below editor
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">

    <meta name="suppress_site_styles" content="true"><meta name="auto_height" content="true"><meta name="auto_width" content="true">
      <link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">

Titles and headers

      Bold text

      Normal text

      Links

      Current navigation selection

      Form input errors

      Gray text

      Secondary text

PLEASE NOTE, THIS IFRAME WILL NOT SHOW IN STACKOVERFLOW SNIPPET EDITOR, YOU NEED TO DOWNLOAD THIS CODE TO YOUR SYSTEM

<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/somethinggoodone/cdn/AniketPradhan_bootstrap.css" />

                Preview

                HTML

            <textarea id="embody" class="m-0 p-0 border-0 mt-2" style="width:100%;resize: none;outline: none"><h3>Compose your email body text.</h3></textarea>

A: Populate the iframes body instead of the html root:
$("#showpreview").click(function () {
  $(this).hide();
  $("#embody-preview").contents().find("body").html(embody.value);
  $("#showhtml,#embody-preview").show();
  $("#embody").hide();
});

Otherwise it might be easier to append a general editor stylesheet to you iframe like so:
let iframe = document.getElementById("embody-preview");
let doc = iframe.contentDocument;
let style = doc.createElement("style");
let link = doc.createElement("link");
link.rel = "stylesheet";
link.href = "https://ssl.gstatic.com/docs/script/css/add-ons1.css";
style.textContent = `
body{
font-family:sans-serif;
color:red!important;
}
`;
doc.head.appendChild(link);
doc.head.appendChild(style);

Codepen Example


text:
Q: php pdo double quotes also getting escaped I am using php pdo->quote to before injecting values into database. but surprisingly double quotes (") are also getting escaped! tried disabling magic_quotes_gpc, magic_quotes_runtime, magic_quotes_sybase in php.ini .htaccess and also by ini_set. still out of luck. the double quotes are getting escaped along with the single quotes.
It's not only adding slashes while inserting values to database, even a simple echo $pdo->quotes('hi "this" is a test'); is giving me 'hi \"this\" is a test' as output. I dont want to escape the double quotes! Is there any workaround without switching to prepared statements? I avoided prepared statements because of many issues I was facing!
I am sure that i haven't used addslashes anywhere. is there any work around to fix this issue? im using xampp 1.8.2. Kindly help. Thanks!

A:
giving me 'hi \"this\" is a test' as output.

that's correct output. There is absolutely nothing wrong with it. You shouldn't worry of these slashes at all.

I dont want to escape the double quotes!

You do. At least as long as you are using this function.
Anyway, you should use prepared statements instead.


text:
Q: When is gcc evaluating functions at compile time? When I have the following code
int main(void) {
        printf("%zd\n", strlen("Hello World!"));

        return 0;
}

and compile it with -O3, strings will show that the string "Hello World!" is missing from the binary since it got evaluated at compile time.
If I instead use my own function
static inline size_t my_strlen(const char *s) {
        const char *tmp = s;

        while (*++tmp);

        return tmp - s;
}

int main(void) {
        printf("%zd\n", my_strlen("Hello World!"));

        return 0;
}

with the same options, the string can still be found in the binary.
Why is this?

A: Because it is an optimization permitted by the standard.
On some systems, strlen is finally expanded to _builtin_strlen which is known by the GCC compiler. On my machine /usr/include/x86_64-linux-gnu/bits/string.h (which is indirectly included by <string.h>) has
# define strlen(str) \
  (__extension__ (__builtin_constant_p (str)         \
                 ? __builtin_strlen (str)            \
                 : __strlen_g (str)))

So actually is it done by the mix of GNU glibc and gcc

A: GCC probably has an optimization somewhere that replaces the strlen() of a constant string with the length of that string.
When you use your own function, this optimization cannot be turned on. GCC does not know if the my_strlen has side-effects, so it has to run it each time.


text:
Q: Getting "ImportError: No Python documentation found for 'Type of operating system'." while running PyTest file I have installed latest PyTest version and created a basic test method as below:
import pytest

@pytest.fixture()
def setUp():
    print("Running demo1 setUp")

def test_demo1_methodA(setUp):
    print("Running demo1 method A")

def test_demo1_methodB(setUp):
    print("Running demo1 method B")

I'm trying to run PyTest file in pycharm terminal using below commands:
py.test -v -s pytestpackage/test_case_demo1.py

# pytestpackage is the package name
# test_case_demo1.py is the python file name

Getting error:
kshitij_thapar@Kshitijs-MacBook-Air ~ % cd Documents/workspace_python/PythonTutorial
kshitij_thapar@Kshitijs-MacBook-Air PythonTutorial % py.test -v -s pytestpackage/test_case_demo1.py
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.11/bin/py.test", line 8, in <module>
    sys.exit(console_main())
             ^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/_pytest/config/__init__.py", line 190, in console_main
    code = main()
           ^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/_pytest/config/__init__.py", line 148, in main
    config = _prepareconfig(args, plugins)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/_pytest/config/__init__.py", line 329, in _prepareconfig
    config = pluginmanager.hook.pytest_cmdline_parse(
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pluggy/_hooks.py", line 265, in __call__
    return self._hookexec(self.name, self.get_hookimpls(), kwargs, firstresult)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pluggy/_manager.py", line 80, in _hookexec
    return self._inner_hookexec(hook_name, methods, kwargs, firstresult)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pluggy/_callers.py", line 55, in _multicall
    gen.send(outcome)
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/_pytest/helpconfig.py", line 103, in pytest_cmdline_parse
    config: Config = outcome.get_result()
                     ^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pluggy/_result.py", line 60, in get_result
    raise ex[1].with_traceback(ex[2])
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pluggy/_callers.py", line 39, in _multicall
    res = hook_impl.function(*args)
          ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/_pytest/config/__init__.py", line 1058, in pytest_cmdline_parse
    self.parse(args)
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/_pytest/config/__init__.py", line 1346, in parse
    self._preparse(args, addopts=addopts)
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/_pytest/config/__init__.py", line 1248, in _preparse
    self.hook.pytest_load_initial_conftests(
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pluggy/_hooks.py", line 265, in __call__
    return self._hookexec(self.name, self.get_hookimpls(), kwargs, firstresult)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pluggy/_manager.py", line 80, in _hookexec
    return self._inner_hookexec(hook_name, methods, kwargs, firstresult)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pluggy/_callers.py", line 60, in _multicall
    return outcome.get_result()
           ^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pluggy/_result.py", line 60, in get_result
    raise ex[1].with_traceback(ex[2])
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pluggy/_callers.py", line 39, in _multicall
    res = hook_impl.function(*args)
          ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/_pytest/config/__init__.py", line 1125, in pytest_load_initial_conftests
    self.pluginmanager._set_initial_conftests(
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/_pytest/config/__init__.py", line 557, in _set_initial_conftests
    self._try_load_conftest(anchor, namespace.importmode, rootpath)
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/_pytest/config/__init__.py", line 574, in _try_load_conftest
    self._getconftestmodules(anchor, importmode, rootpath)
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/_pytest/config/__init__.py", line 603, in _getconftestmodules
    mod = self._importconftest(conftestpath, importmode, rootpath)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/_pytest/config/__init__.py", line 651, in _importconftest
    self.consider_conftest(mod)
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/_pytest/config/__init__.py", line 732, in consider_conftest
    self.register(conftestmodule, name=conftestmodule.__file__)
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/_pytest/config/__init__.py", line 489, in register
    ret: Optional[str] = super().register(plugin, name)
                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pluggy/_manager.py", line 115, in register
    hook._maybe_apply_history(hookimpl)
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pluggy/_hooks.py", line 300, in _maybe_apply_history
    res = self._hookexec(self.name, [method], kwargs, False)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pluggy/_manager.py", line 80, in _hookexec
    return self._inner_hookexec(hook_name, methods, kwargs, firstresult)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pluggy/_callers.py", line 60, in _multicall
    return outcome.get_result()
           ^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pluggy/_result.py", line 60, in get_result
    raise ex[1].with_traceback(ex[2])
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pluggy/_callers.py", line 39, in _multicall
    res = hook_impl.function(*args)
          ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/kshitij_thapar/Documents/workspace_python/PythonTutorial/pytestpackage/conftest.py", line 24, in pytest_addoption
    parser.addoption("--osType", help("Type of operating system"))
                                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<frozen _sitebuiltins>", line 103, in __call__
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/pydoc.py", line 2001, in __call__
    self.help(request)
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/pydoc.py", line 2057, in help
    elif request: doc(request, 'Help on %s:', output=self._output)
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/pydoc.py", line 1784, in doc
    pager(render_doc(thing, title, forceload))
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/pydoc.py", line 1758, in render_doc
    object, name = resolve(thing, forceload)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/pydoc.py", line 1744, in resolve
    raise ImportError('''\
ImportError: No Python documentation found for 'Type of operating system'.
Use help() to get the interactive help utility.
Use help(str) for help on the str class.

Any suggestions what am I missing here?

*

*Tried verifying the PYTHONPATHm in zprofile, it is set up correctly

*Tried re-installing pytest module, still getting same error

A: I'm pretty sure that the error is not in pytest
your script with path
"/Users/kshitij_thapar/Documents/workspace_python/PythonTutorial/pytestpackage/conftest.py"
is actually the problem. It says that you have a line
parser.addoption("--osType", help("Type of operating system"))

Where you probably wanted to do help=, but instead you call the function help() with the string argument.


text:
Q: node.js ERROR: connect EADDRINUSE 104.16.58.5:443 Full error:
    (node:8852) UnhandledPromiseRejectionWarning: Error: connect EADDRINUSE 104.16.58.5:443
    at Object._errnoException (util.js:1022:11)
    at _exceptionWithHostPort (util.js:1044:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1198:14)
(node:8852) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:8852) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Node modules I've installed:

*

*Canvas@next

*Sequelize

*discord.js

*sqlite3

Other information:

*

*Error occurs sometimes when someone interacts with the app, no matter what the app does.

A: As the error says EADDRINUSE - means that the port your app uses is already in use by other process (some http server using 443 as http default port)
You can change the port from 443 or you can find the process that uses this port and verify if this process is needed
For finding the process on Linux run:
netstat -an | grep :443

the second column will tell you which processId uses this port
On Windows:
netstat -aon | findstr 443

A: Since it is an connect EADDRINUSE 104.16.58.5:443 error you may have no free ephemeral TCP-Port on your source computer.
There might be to many (old) TCP connections in state TIME_WAIT.
Please try to increase your ephemeral port range.
For reference see https://github.com/nodejs/node-v0.x-archive/issues/3796 and https://github.com/nodejs/help/issues/434

A: Read the Oracle advise (click here)

Adjusting TCP Settings for Heavy Load on Windows

The underlying Search architecture that directs searches across multiple physical partitions uses TCP/IP ports and non-blocking NIO SocketChannels to connect to the Search engines. These connections remain open in the TIME_WAIT state until the operating system times them out. Consequently, under heavy load conditions, the available ports on the machine running the Routing module can be exhausted.
On Windows platforms, the default timeout is 120 seconds, and the maximum number of ports is approximately 4,000, resulting in a maximum rate of 33 connections per second. If your index has four partitions, each search requires four ports, which provides a maximum query rate of 8.3 queries per second.
(maximum ports/timeout period)/number of partitions = maximum query rate.
If this rate is exceeded, you may see failures as the supply of TCP/IP ports is exhausted. Symptoms include drops in throughput and errors indicating failed network connections. You can diagnose this problem by observing the system while it is under load, using the netstat utility provided on most operating systems.
To avoid port exhaustion and support high connection rates, reduce the TIME_WAIT value and increase the port range.
Note: This problem does not usually appear on UNIX systems due to the higher default connection rate in those operating systems.
To set TcpTimedWaitDelay (TIME_WAIT):
Use the regedit command to access the HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\ Services\TCPIP\Parameters registry subkey.
Create a new REG_DWORD value named TcpTimedWaitDelay.
Set the value to 60.
Stop and restart the system.
To set MaxUserPort (ephemeral port range):
Use the regedit command to access the HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\ Services\TCPIP\Parameters registry subkey.
Create a new REG_DWORD value named MaxUserPort.
Set this value to 32768.
Stop and restart the system.


text:
Q: kundera: java.lang.ClassCastException: java.lang.String cannot be cast to [B I want to insert an object into cassandra using kundera framework, but i receive this error:
java.lang.RuntimeException: java.lang.ClassCastException: java.lang.String cannot be cast to [B
        at org.apache.storm.utils.DisruptorQueue.consumeBatchToCursor(DisruptorQueue.java:448) ~[storm-core-1.0.0.jar:1.0.0]
        at org.apache.storm.utils.DisruptorQueue.consumeBatchWhenAvailable(DisruptorQueue.java:414) ~[storm-core-1.0.0.jar:1.0.0]
        at org.apache.storm.disruptor$consume_batch_when_available.invoke(disruptor.clj:73) ~[storm-core-1.0.0.jar:1.0.0]
        at org.apache.storm.daemon.executor$fn__8226$fn__8239$fn__8292.invoke(executor.clj:851) ~[storm-core-1.0.0.jar:1.0.0]
        at org.apache.storm.util$async_loop$fn__554.invoke(util.clj:484) [storm-core-1.0.0.jar:1.0.0]
        at clojure.lang.AFn.run(AFn.java:22) [clojure-1.7.0.jar:?]
        at java.lang.Thread.run(Thread.java:745) [?:1.7.0_99]
Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to [B
        at org.apache.storm.tuple.TupleImpl.getBinaryByField(TupleImpl.java:185) ~[storm-core-1.0.0.jar:1.0.0]
        at connector.bolt.PrinterBolt.execute(PrinterBolt.java:59) ~[Zorro-0.0.1-SNAPSHOT-jar-with-dependencies.jar:?]
        at org.apache.storm.daemon.executor$fn__8226$tuple_action_fn__8228.invoke(executor.clj:731) ~[storm-core-1.0.0.jar:1.0.0]
        at org.apache.storm.daemon.executor$mk_task_receiver$fn__8147.invoke(executor.clj:463) ~[storm-core-1.0.0.jar:1.0.0]
        at org.apache.storm.disruptor$clojure_handler$reify__7663.onEvent(disruptor.clj:40) ~[storm-core-1.0.0.jar:1.0.0]
        at org.apache.storm.utils.DisruptorQueue.consumeBatchToCursor(DisruptorQueue.java:435) ~[storm-core-1.0.0.jar:1.0.0]
        ... 6 more

my entity class
@Entity
@Table(name = "pieces", schema = "piece@cassandra_pu")
public class PieceEntitie implements Serializable{

    @Id private String IdPiece;
    @Column private double width;
    @Column private double height;
    @Column private double depth;
    public PieceEntitie() {
        // TODO Auto-generated constructor stub
    }
.
.
.
}

I followed the tutorial : https://github.com/impetus-opensource/Kundera/wiki/Getting-Started-in-5-minutes
have you any idea about the source of this problem, and how we can resolve it?
thank you

A: Problem in using Storm method TupleImpl.getBinaryByField() it throws exception wich says, that it can't get byte[] from String. Storm tuple have some string value inside and you are trying to get byte array instead.


text:
Q: RDS licensing servers HA I'm trying to understand the correct way to configure two licensing servers for high availability, in per user mode.
I have 100 users, and 100 Cal's in total.
I have two licensing servers; lic1 and lic2, and my understanding is lic2 would only ever be used if lic1 was unavailable (eg: server was turned off)
Which of the two options below is correct to use, and would not breach the Remote Desktop Services license terms?
Option 1:
Install 50 Cal's on lic1 and 50 on lic2.
lic1 would over-issue licences because I'm using per user, and issue 100 licences even though only 50 Cal's are installed, but this would be ok because in total we own 100 cal licences
Option 2:
Install all 100 licences on lic1.
If lic1 ever went offline, lic2 would over issue all 100 licences but this is ok because it is temporary while we fix lic1 or move the cal licences over to lic2
Or is there an option that I have not thought of which should be used?
Also, where can I actually find a copy of the Remote Desktop Services license terms online?


text:
Q: error when compiling kernel with some new features I am trying to compile kernel version 4.1 with some patches (adding some features to the GRO). I come from a hardware background and relatively new to network stack. I wish to know how to solve this problem or at least pointers to understand why it occurs.
This is what I did
# my temp location

mdkir kern
cd kern

# cloned the juggler and linux 4.1 tree

git clone https://github.com/gengyl08/juggler.git
wget https://www.kernel.org/pub/linux/kernel/v4.x/linux-4.1.tar.gz
tar -xvf linux-4.1.tar.gz

# copied just the essential files that were diffferent

cp juggler/linux-4.1/include/linux/netdevice.h linux-4.1/include/linux/netdevice.h
cp juggler/linux-4.1/include/linux/skbuff.h linux-4.1/include/linux/skbuff.h
cp juggler/linux-4.1/net/core/dev.c linux-4.1/net/core/dev.c
cp juggler/linux-4.1/net/core/net-sysfs.c linux-4.1/net/core/net-sysfs.c
cp juggler/linux-4.1/net/core/skbuff.c linux-4.1/net/core/skbuff.c
cp juggler/linux-4.1/net/ipv4/af_inet.c linux-4.1/net/ipv4/af_inet.c
cp juggler/linux-4.1/net/ipv4/tcp_offload.c linux-4.1/net/ipv4/tcp_offload.c

cd linux-4.1
make menuconfig   # generated the default .config file

# building the kernel

time make

When I try to compile them, I get the following error
drivers/net/ethernet/agere/et131x.c: In function 'nic_send_packet.constprop.43':
include/linux/compiler.h:412:20: error: call to '__compiletime_assert_2439' declared with attribute error: BUILD_BUG
    prefix ## suffix();    \
                    ^
include/linux/compiler.h:417:2: note: in expansion of macro '__compiletime_assert'
  __compiletime_assert(condition, msg, prefix, suffix)
  ^
include/linux/compiler.h:429:2: note: in expansion of macro '_compiletime_assert'
  _compiletime_assert(condition, msg, __compiletime_assert_, __LINE__)
  ^
include/linux/bug.h:50:37: note: in expansion of macro 'compiletime_assert'
 #define BUILD_BUG_ON_MSG(cond, msg) compiletime_assert(!(cond), msg)
                                     ^
include/linux/bug.h:74:2: note: in expansion of macro 'BUILD_BUG_ON_MSG'
  BUILD_BUG_ON_MSG(condition, "BUILD_BUG_ON failed: " #condition)
  ^
drivers/net/ethernet/agere/et131x.c:2439:2: note: in expansion of macro 'BUILD_BUG_ON'
  BUILD_BUG_ON(MAX_SKB_FRAGS + 1 > 23);
  ^
make[4]: *** [drivers/net/ethernet/agere/et131x.o] Error 1
make[3]: *** [drivers/net/ethernet/agere] Error 2
make[2]: *** [drivers/net/ethernet] Error 2
make[1]: *** [drivers/net] Error 2
make: *** [drivers] Error 2

real    22m3.067s
user    21m4.028s
sys     1m6.724s

A: It looks like MAX_SKB_FRAGS is too big and ethernet driver doesn't like it.
From drivers/net/ethernet/agere/et131x.c:
/* Part of the optimizations of this send routine restrict us to
 * sending 24 fragments at a pass.  In practice we should never see
 * more than 5 fragments.
 */

/* nr_frags should be no more than 18. */
BUILD_BUG_ON(MAX_SKB_FRAGS + 1 > 23);

From the patches you're using:
linux-3.18.5/include/linux/skbuff.h:
#if (65536/PAGE_SIZE + 1) < 16
#define MAX_SKB_FRAGS 16UL
#else
#define MAX_SKB_FRAGS (65536/PAGE_SIZE + 1)
#endif

linux-4.1/include/linux/skbuff.h:
#if (65536/PAGE_SIZE + 1) < 45
#define MAX_SKB_FRAGS 45UL
#else
#define MAX_SKB_FRAGS (65536/PAGE_SIZE + 1)
#endif

Note the difference.
I haven't analyzed this code, but from a very first look I see some inconsistency there.
Replacing 45 back to 16 should do the trick. Of course, there might be a reason why the patch author picked a higher value.


text:
Q: AWS Systems Manager is not resolving Automation Variable I have a simple aws Systems Manager Automation that is designed to rotate the local windows password for systems located at externalized sites. During Step 7 of the automation, AWS calls and executes a powershell command document that validates that the rotated password and outputs a string value of either True or False in JSON format. This string value is then passed back into the automation and sent to cloudwatch.
I am having an issue where the True or False value passed into the automation in step 7 via the validPassword variable is not getting resolved when passed into Step 8. Instead, only the Automation variable identifier is passed ({{CheckNewPassword.validPassword}})".
Does anyone know why this is this happening? I assume it has something to do with the command document not producing output in a format that Systems Manager likes.
Any assistance would be appreciated
Step 7 Output
{
  "validPassword": "True"
}

{"Status":"Success","ResponseCode":0,"Output":"{

    \"validPassword\":  \"True\"

}

","CommandId":"6419ba15-b0f3-4af4-86a2-c4693639fc9e"}

Step 8 Input Passed from Step 7
{"passwordValid":"{{CheckNewPassword.validPassword}}","siteCode":"LBZ1-20","num_failedValidation":1}

AWS Automation Document -- Step 7 and 8

  - name: CheckNewPassword
    action: 'aws:runCommand'
    inputs:
      DocumentName: SPIN_CheckPass
      InstanceIds:
        - '{{nodeID}}'
      Parameters:
        password:
          - '{{GenerateNewPassword.newPassword}}'
    outputs:
      - Name: validPassword
        Selector: validPassword
        Type: String
      - Name: dataType
        Selector: dataType
        Type: String
  - name: RecordPasswordStatus
    action: 'aws:invokeLambdaFunction'
    inputs:
      InvocationType: RequestResponse
      FunctionName: SPIN-CheckPassMetric
      InputPayload:
        passwordValid: '{{CheckNewPassword.validPassword}}'
        siteCode: '{{siteCode}}'
        num_failedValidation: 1

AWS Command Document (SPIN_CheckPass)
{
  "schemaVersion": "2.2",
  "description": "Check Rotated Password",
  "parameters": {
    "password": {
      "type": "String",
      "description": "The new password used in the password rotation."
    }
  },
  "mainSteps": [
    {
      "action": "aws:runPowerShellScript",
      "name": "rotatePassword",
      "inputs": {
        "runCommand": [
          "function checkPass {",
          "    param (",
          "    $password",
          "    )",
          "    $username = 'admin'",
          "    $password = $password",
          "    $computer = $env:COMPUTERNAME",
          "    Add-Type -AssemblyName System.DirectoryServices.AccountManagement",
          "    $obj = New-Object System.DirectoryServices.AccountManagement.PrincipalContext('machine',$computer)",
          "    [String] $result = $obj.ValidateCredentials($username, $password)",
          "",
          "    $json = ",
          "        @{",
          "            validPassword = $result",
          "        } | ConvertTo-Json",
          "",
          "return $json",
          "}",
          "checkPass('{{password}}')"
        ],
        "runAsElevated": true
      }
    }
  ]
}

I've tried changing the datatype of the validPassword variable to a bool, and Ive tried changing the format of the command document from JSON to YAML both of which have not worked.
Ive also attempted to capture another output element from the command document into a variable which also results in the variable name not resulting in inputs for subsequent Steps.

A: AWS Support confirmed that this is a bug they are now tracking.


text:
Q: What is Type of Enum when it stored into Expression I am getting Expression x=>x.SomeAttribute
Attribute can be of any type.
I am taking type of property from expression.
For normal primitive properties it gives me right values like int,string... etc.
But for Enum it give me MyEnum.
I want to execute getExpression method for Enum. So what to pass as TResult.
public enum TestEnum
    {
        first = 0,
        second = 1
    }

Public Class A
    {
         public int TestInt {get;set;}
         public string TestString {get;set;}
         public TestEnum EnumDemo { get; set; }
    }

    x=>x.TestInt;
    getExpression<TSource, int>(expression)// when SomeAttribute is integer

    x=>x.TestString;
    getExpression<TSource, string>(expression) // when SomeAttribute  is string

    x=>x.EnumDemo ;
    getExpression<TSource, Enum>(expression) // when SomeAttribute is Enum, It reruns null

private Expression<Func<TSource, TResult>> getExpression<TSource, TResult>(Expression expression)
     {
          var x = expression as Expression<Func<TSource, TMember>>;
           return x;
     }

A: int is the underlying type for enum therefore
getExpression<TSource, int>(expression);

Will work.


text:
Q: Elasticsearch. Full text search for the Russian language Right now I am using hunspell dictionary as my search engine in ES. It works weirdly and I don't understand why. For example, I have several entries in my index with the word "перец" in different forms:
1 ч. л. смеси перцев горошком;
2–3 колечка красного перца чили с семенами;
черный молотый перец;

and several entries with the word "колодец" in different forms:
несколько колодцев;
3 колодца;
1 колодец;

My index has the following settings:
PUT http://localhost:9200/ingredient
Content-Type: application/json

{
  "settings": {
    "analysis": {
      "analyzer": {
        "custom_analyzer": {
          "tokenizer": "standard",
          "filter": [
            "lowercase",
            "ru_RU",
            "my_stemmer"
          ],
          "char_filter": [
            "html_strip"
          ]
        }
      },
      "filter": {
        "my_stemmer": {
          "type": "stemmer",
          "language": "russian"
        },
        "ru_RU": {
          "type": "hunspell",
          "locale": "ru_RU"
        }
      }
    }
  },
  "mappings": {
    "properties": {
      "name": {
        "type": "text",
        "analyzer": "custom_analyzer"
      }
    }
  }
}

When I make my search query for "колодец" like this:
GET http://localhost:9200/ingredient/_search?pretty
Content-Type: application/json

{
  "query": {
    "query_string": {
      "query": "колодец",
      "default_field": "name"
    }
  }
}

I receive the following JSON:
{
  "took": 4,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": {
      "value": 3,
      "relation": "eq"
    },
    "max_score": 5.0841255,
    "hits": [
      {
        "_index": "ingredient",
        "_type": "_doc",
        "_id": "2940d2bc-59ca-4c41-98d6-803d50913d04",
        "_score": 5.0841255,
        "_source": {
          "name": "несколько колодцев",
          "id": "2940d2bc-59ca-4c41-98d6-803d50913d04",
          "_meta": {}
        }
      },
      {
        "_index": "ingredient",
        "_type": "_doc",
        "_id": "2940d2bc-59ca-4c41-98d6-803d50913d05",
        "_score": 5.0841255,
        "_source": {
          "name": "3 колодца",
          "id": "2940d2bc-59ca-4c41-98d6-803d50913d05",
          "_meta": {}
        }
      },
      {
        "_index": "ingredient",
        "_type": "_doc",
        "_id": "2940d2bc-59ca-4c41-98d6-803d50913d06",
        "_score": 5.0841255,
        "_source": {
          "name": "1 колодец",
          "id": "2940d2bc-59ca-4c41-98d6-803d50913d06",
          "_meta": {}
        }
      }
    ]
  }
}

Response code: 200 (OK); Time: 45ms; Content length: 1199 bytes

But when I make the similar request with "перец":
GET http://localhost:9200/ingredient/_search?pretty
Content-Type: application/json

{
  "query": {
    "query_string": {
      "query": "перец",
      "default_field": "name"
    }
  }
}

I only get this:
{
  "took": 1,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": {
      "value": 23,
      "relation": "eq"
    },
    "max_score": 3.1693017,
    "hits": [
      {
        "_index": "ingredient",
        "_type": "_doc",
        "_id": "9c72cba2-2986-40dd-b15b-0df0288e91f1",
        "_score": 2.8541024,
        "_source": {
          "name": "свежемолотый черный перец",
          "id": "9c72cba2-2986-40dd-b15b-0df0288e91f1",
          "_meta": {}
        }
      },
    ]
  }
}

I do not get neither 1 ч. л. смеси перцев горошком nor 2–3 колечка красного перца чили с семенами.
It seems strange to me because колодец and перец have a similar way of making their morphological forms. Do I have this problem because my hunspell dictionary is not full enough? If so where can I find the most complete hunspell dictionary or the other dictionary for the Russian language?


text:
Q: C++ QueryDosDeviceA() return 0 but COMX is connected so I'm doing a function to retrieve all the COM serial port names connected to the system using QueryDosDeviceA
I tried to use CreatFileA with "\\\\.\\COM6", and it doesn't throw me any errors.
But QueryDosDeviceA with "COM6" or "\\\\.\\COM6"
Function.cpp
std::vector<std::string> SerialPort::_SerialList()
{
    std::vector<std::string> serialList;
    std::string COMName("\\\\.\\COM"), queryName(COMName); //also tried with COMName("COM")
    CHAR bufferTragetPath[5000];
    std::string tmp;
    DWORD path_size(0);

    //test each COM name to get the one used by the system
    for (int i(0); i < 255; i++)
    {
        queryName = COMName + std::to_string(i);
        //Query the path of the COMName
        path_size = QueryDosDeviceA((LPCSTR)&queryName, (LPSTR)&bufferTragetPath, 5000);

        std::cout << std::endl << "Path for " << queryName << ":" << path_size;

        if (path_size != 0) {
            std::cout << "pushing..." << queryName << " on " << bufferTragetPath << std::endl;
            serialList.push_back(queryName);
        }
    }
    return serialList;
}

And here is the output :
Path for \\.\COM0:0
Path for \\.\COM1:0
Path for \\.\COM2:0
Path for \\.\COM3:0
Path for \\.\COM4:0
Path for \\.\COM5:0
Path for \\.\COM6:0
Path for \\.\COM7:0
Path for \\.\COM8:0
Path for \\.\COM9:0
...
Path for \\.\COM253:0
Path for \\.\COM254:0Port name: \\.\COM6
Hello World !

So it's finding nothing but the COM6 port can be used by CreateFileA

A: Thanks to @user253751, @JohnnyMopp, @dresscherjm
And @RemyLebeau
Here is the code that include the solution:
std::vector<std::string> SerialPort::_SerialList()
{
    std::vector<std::string> serialList;
    std::string COMName("COM"), queryName("");
    CHAR bufferTragetPath[5000];
    std::string tmp;
    DWORD path_size(0);

    //test each COM name to get the one used by the system and get his description name
    for (int i(0); i < 255; i++)
    {
        queryName = COMName + std::to_string(i);

        //Query the path of the COMName
        path_size = QueryDosDeviceA(queryName.c_str(), bufferTragetPath, 5000);
        std::cout << std::endl << "Path for " << queryName << ":" << path_size << "   " << queryName;
        if (path_size != 0) {
            std::cout << "pushing..." << queryName << " on " << bufferTragetPath << std::endl;
            serialList.push_back(tmp);
        }
    }
    return serialList;
}

Basically i change the convertion of queryName from string to LPCSTR
//LPCSTR => Long Pointer Const String(= const char)
queryName.c_str() //return queryName as const char*

I've also removed a cast from bufferTragetPath that was useless
//from
(LPSTR)&bufferTragetPath
//to
bufferTragetPath //cause bufferTragetPath is char *


text:
Q: A multivariate function, computable for any fixed first argument, is computable Claim: If $f:\mathbb N^{k+1}\to\mathbb N$ is a function such that for all $x_0\in\mathbb N$, $\lambda x_1,\dots,x_k.f(x_0,x_1,\dots x_k)$ is a partial recursive function then $f$ is also partial recursive.
Corollary: In particular, let $\mu$ be the minimization operator, and for all natural numbers $n$ let $\{f_i^{(n)}\}$ be a Gödel enumeration of the partial recursive functions of $n$ variables. Then the function $\mu_k:\mathbb N^{k+1}\to\mathbb N$ defined by $\mu_k(x_0,x_1,\dots,x_k)=\mu(f_{x_0}^{(k+1)})(x_1,\dots,x_k)$ is computable. Therefore, via the $S^m_n$ theorem, the minimization operator is effective, (as indicated in this CS.SE post).
Question: For all $i\in\mathbb N$, $\mu_k(i,x_1,\dots,x_k)=F(h(i),x_1,\dots,x_k)$, where $F$ is the universal function, and $h$ is a unique total function. Why is $h$ computable?
EDIT: Please note that I am working with a non-deciding minimization defined as follows:
$$\mu(f)(\overline x)=\mu y[f(y,\overline x)=0]=y\iff (f(y,\overline x)=0\land(\forall i<y) (f(i,\overline x)>0))$$

A: It is not clear to me what the current question is asking, because it has several false claims. This comment is too long for the "comments" section, so I have made it a community-wiki post.
1) The initial "Claim" is false. Let $K$ be a noncomputable set and let $f(n,i) = 1_K(n)$. Then for each $n$ the function $(\lambda i)f(n,i)$ is computable, but the overall function $f$ is not computable.
2)  Here is why minimization applied to partial functions can be noncomputable. Suppose that $A$ is a noncomputable r.e. set. Define a function $f(i,n)$ as follows:
$$
f(0,n) = 0 \quad \text{if $n \in A$}\\
f(0,n) = \,\,\uparrow \text{if $n \not\in A$}\\
f(i+1, n) = 0
$$
This function is partial computable if $A$ is r.e. What if we apply minimization to this partial function? We obtain a function
$$
g(n) = (\mu i)[f(i,n) = 0]
$$
Note that $g$ is a total function. Moreover, for all $n$, we have $g(n) = 0$ if and only if $n \in A$. So, if $g$ was computable, $A$ would be decidable, which contradicts the choice of $A$ as a noncomputable r.e. set. So the moral is that the partial computable functions are not closed under the $\mu$ operator, but they are closed under applying the $\mu$ operator to total computable functions. (It turns out that this is essentially exercise 4.24 in Soare's standard computability text.)
In particular, the operator $\mu_k$ in the question is not computable, and claim otherwise in the "corollary" is not correct.

A: After clarification, I think that the question asks how to prove that there is a computable function $h$ such that, for every partial computable function $f_e(q, i_1, \ldots, i_k)$, we have
$$
f_{h(e)}(i_1, \ldots, i_k) = (\mu m)[(\forall q < m)[f_e(q, i_1, \ldots, i_k) \mathord{\downarrow} \land f_e(q, i_1, \ldots, i_k) > 0] \land f_e(m, i_1, \ldots, i_k) = 0]
$$
Note that the function on the right is not the same as $(\mu m) f_e(m, i_1, \ldots, i_k) = 0$, which is a noncomputable function for some particular values of $e$. I will call the desired function $M(e)$.
The goal of the question is to show that $h$ is computable. The standard way to prove this is to convince oneself that there is a computable translator $T$ that, given the program (i.e. index) $e$ in some standard model of computation (e.g. Turing machines), produces a program (in the model) to compute $M(e)$.  This is a routine exercise in programming.
Once we know that this can be done for any particular standard model of computation, we then know that it can be done for any admissible indexing of the partial computable functions, using the definition of admissibility. In particular, let $\eta$ be our admissible numbering with associated functions $f$ and $g$ as in the Wikipedia article. Let $T$ be the computable function that, given an index $e$ in the standard model, produces an index for $M(e)$ in the standard model of computation. Then $h(e) = g(T(f(e))$ and this will solve the problem for the numbering $\eta$.

A: Before all I want to thank Carl Mummert for his answer. Here is another solution I found.
Let $F^n$ be the set of partial functions of $n$ natural variables. Consider without proof that an operator $\Gamma:F^{n_1}\times\dots\times F^{n_k}\to F^m$ is effective exactly when  the function $G$ defined bellow is computable.
$$G(a_1,\dots a_k,x_1,\dots,x_m)=\Gamma(f_{a_1},\dots,f_{a_k})(x_1,\dots,x_k)$$
Now if $M:=\lambda a,x_1,\dots,x_k.\mu(f_a^{(k+1)})(x_1,\dots,x_k)$ is computable then $\mu$ is effective. Indeed from the definition of $\mu$ we have:
$$M(a,\overline x)=\mu(f_a^{(k+1)})(x_1,\dots,x_k)=\mu y[f^{(k+1)}_a(y,\overline x)=(\Phi_{k+1}(a,y,\overline x)=0]$$
Since the universal function for the computable functions of $k+1$ arguments $\Phi_{k+1}$ is computable, $M$ is computable, because minimization preserves computability. q.e.d.


text:
Q: Getting input to an executable via stdin? I have an executable that I need to take input from a .wav file on my desktop. The executable expects input on stdin.
Let us use the example:
/Users/tomcruise/Desktop/executable

/Users/tomcruise/Desktop/music.wav

I am using Mac OS X.

A: What exactly is your question? stdin is not the same as command line arguments. The latter is a file descriptor that is available to the program on startup. The latter are a bunch of strings available as strings. Running
/Users/tomcruise/Desktop/executable /Users/tomcruise/Desktop/music.wav

will "give" the music.wav filename to your executable which you can process.

A: Open Terminal and do the following:
$ cd /Users/tomcruise/Desktop
$ ./executable < music.wav

A: If your executable is taking from command line arguments, it would be:
/Users/tomcruise/Desktop/executable /Users/tomcruise/Desktop/music.wav
If it is taking from stdin, it would be:
/Users/tomcruise/Desktop/executable < /Users/tomcruise/Desktop/music.wav

A: You write the argument just after the filename:
cd /Users/tomcruise/Desktop
./executable music.wav


text:
Q: element of array not found I have code to receive the object object and check if the value of property object.bedrijfsnaam is already in an array I declared before, called bedrijfsnamen. Object.bedrijfsnamen in fact is inside the array already, but unfortunately Javascript doesn't see that. I've tried bedrijfsnaam in object besides bedrijfsnamen.indexOf(bedrijfsnaam)!=-1, but they both don't work. I don't get the problem.
Anyone with decent Javascript knowledge who sees the problem?
socket.io version 2.1.1
//The data inside my event: object 'object', with property 'object.bedrijfsnaam', which has the value 'a' (but is not a string yet)
socket.on('event', function(object){
    //stringifying the data
    var bedrijfsnaam = "'"+object.bedrijfsnaam+"'";
    console.log(bedrijfsnaam);
    //output: 'a'

    if(bedrijfsnamen.indexOf(bedrijfsnaam)!=-1){
        console.log('yes');
    }else {
        console.log('no')
    }
    //output: yes

    console.log(bedrijfsnamen);
    //output: [ 'a', 'a' ]
});


text:
Q: Maven fails to compile java code (java.lang.ClassNotFoundException) with `mvn exec:java` call Trying to follow instructions to compile kafka sample streams app
https://github.com/timothyrenner/kafka-streams-ex/tree/master/not-looking-at-facebook
I'm using Oracle java8 @ Fedora25
➜  not-looking-at-facebook git:(master) java -version
java version "1.8.0_121"
Java(TM) SE Runtime Environment (build 1.8.0_121-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode)

mvn -X exec:java produces the following error:
java.lang.ClassNotFoundException: io.github.timothyrenner.kstreamex.notification.NotLookingAtFacebook
        at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        at org.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:281)
        at java.lang.Thread.run(Thread.java:745)
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.517 s
[INFO] Finished at: 2017-03-21T16:17:41-07:00
[INFO] Final Memory: 17M/481M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.4.0:java (default-cli) on project not-looking-at-facebook: An exception occured while executing the Java class. io.github.timothyrenner.kstreamex.notification.NotLookingAtFacebook -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.4.0:java (default-cli) on project not-looking-at-facebook: An exception occured while executing the Java class. io.github.timothyrenner.kstreamex.notification.NotLookingAtFacebook
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:212)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
        at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
        at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
        at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
        at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
        at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307)
        at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193)
        at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106)
        at org.apache.maven.cli.MavenCli.execute(MavenCli.java:863)
        at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:288)
        at org.apache.maven.cli.MavenCli.main(MavenCli.java:199)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
        at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
        at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
        at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: org.apache.maven.plugin.MojoExecutionException: An exception occured while executing the Java class. io.github.timothyrenner.kstreamex.notification.NotLookingAtFacebook
        at org.codehaus.mojo.exec.ExecJavaMojo.execute(ExecJavaMojo.java:345)
        at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:207)
        ... 20 more
Caused by: java.lang.ClassNotFoundException: io.github.timothyrenner.kstreamex.notification.NotLookingAtFacebook
        at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        at org.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:281)
        at java.lang.Thread.run(Thread.java:745)
[ERROR]
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

I had to fix it with mvn clean test and then mvn exec:java worked. What was the problem?
(I'm new to maven/java ecosystem)

A: Your invocation of mvn exec:java failed because nothing had been compiled - and therefore the main class in question was missing.
Running mvn clean test invokes the maven-compiler-plugin, meaning that subsequent attempts to use the exec-maven-plugin (which is what's called when you invoke the exec:java goal) succeed.
If you take a look at this question, you'll see that it's not overly simple to bind the compilation of your source code directly to the exec:java goal. However, you can chain goals together so something like this will probably work:
mvn clean test exec:java


text:
Q: How print all rows after select specific value in row by pandas? I select minimum low price from these dataframe
but I want print all rows after a row have minimum price.
I try something but the result only specific row.
data = client.get_historical_klines(symbol=i, interval="1h", start_str="24 hours ago",
                                    end_str=None)
df = pd.DataFrame(data)
df.columns = columns
df["Volume"] = df["Quote_Volume"]
for x in range(6, 12):
    del df[columns[x]]
df['Date'] =  pd.to_datetime(df['Date'],unit='ms')
df['Tiker'] = i
df = df.set_index('Tiker')
df["Close"] = pd.to_numeric(df["Close"])
df["Open"] = pd.to_numeric(df["Open"])
df["High"] = pd.to_numeric(df["High"])
df["Low"] = pd.to_numeric(df["Low"])
df["Volume"] = pd.to_numeric(df["Volume"])
df["LOW"] = df["Low"]==df["Low"].min()

print(df)

A: Use this
df_new = df[df["Low"]==df["Low"].min()] or
df_new= df.loc[df["Low"]==df["Low"].min()]
print(df_new)


text:
Q: Proca Lagrangian manipulation How can I show that the Lagrangian density
$$\mathcal{L} = -\frac{1}{2}\partial_\alpha \varphi_\beta \partial^\alpha \varphi^\beta + \frac{1}{2} \partial_\alpha \varphi^\alpha \partial_\beta \varphi^\beta + \frac{\mu^2}{2}\varphi_\alpha \varphi^\alpha$$
for the real vector field $\varphi^\alpha$ leads to the field equations
$$[g_{\alpha\beta}(\square+ \mu^2)-\partial_\alpha\partial_\beta]\varphi^\beta=0$$
I have done through lot of work, but I was wondering if there are some tricks or efficient ways to do it?
And second question, how can I show that the field satisfies the Lorenz condition $\partial_\alpha \varphi^\alpha = 0$?
Source: Mandl Shaw QFT problem 2.3

A: To derive the field equations more quickly, consider that all the terms in the Lagrangian are "squares": a tensor contracted with itself on all indices. The variation of a square is $\delta(F_{ab} F^{ab}) = 2 (\delta F_{ab}) F^{ab}$ in analogy with $d/dx\; f^2 = 2ff'$. Using this, we have for the variation of the Lagrangian $$\delta \mathcal L = - (\delta \partial_a \varphi_b) \partial^a \varphi^b + (\delta \partial_a \varphi^a) (\partial_b \varphi^b) + \mu^2 (\delta \varphi_a) \varphi^a.$$
We can swap variation and partial derivatives and find that the variation in the action is $$\delta S =\int \delta \mathcal L = \int (\delta \varphi_a )\partial_\nu \partial^\nu \varphi^a - (\delta \varphi^a)(\partial_a \partial_b \varphi
^b) + \mu^2 (\delta \varphi_a) \varphi^a$$
where we used integration by parts on the first two terms and relabeled the summation indices in the first. We see that the variation is $$\delta S = \int (\delta \varphi^a) (g_{ab}\square  \varphi^b - \partial_a \partial_b + \mu^2 g_{ab} )\varphi^b$$
which vanishes for an arbitrary variation $\delta \varphi^a$ if and only if the field equation $$(g_{ab}(\square + \mu^2) - \partial_a\partial_b ) \varphi^b = 0$$
holds. For the second part: apply $\partial^a$ to the equation. This yields $$(\partial_b (\square + \mu^2) - \partial^a \partial_a \partial_b) \varphi^b = \mu^2 \partial_b \varphi^b + (\partial_b\square - \square \partial_b) \varphi^b = 0,$$
which implies the Lorentz condition $\partial_b\varphi^b=0$ since the term with brackets vanishes by commutativity of partial derivatives.


text:
Q: assign string from list I've created a list with a lot of options, let's say for every character a different color.
string A = "#FFB97FC9";
string B = "#FF9BCC50";
// etc.
string answer1 = Options.Answer1;
answerRectangle.Fill = GetColorFromHexa(answer1);

now let's say that Options.Answer1 = A.
I want answerRectangle to have the color from the code #FFB97FC9
How can I achieve this?
NOTE: I want to have answer1 = #FFB97FC9

A: Use a dictionary instead of variables:
var colors = new Dictionary<string, string>();
colors["A"] = "#FFB97FC9";
colors["B"] = "#FF9BCC50";
// etc.
string answer1 = Options.Answer1;
answerRectangle.Fill = GetColorFromHexa(colors[answer1]);

A: Why not create a dictionary with options:
Dcitionary<string, string> colors = new Dictionary<string, string>();
colors.Add("A", "#FFB97FC9");
colors.Add("B", "#FF9BCC50");

and then:
answerRectangle.Fill = GetColorFromHexa(colors[answer1]);


text:
Q: Redimensioning an array within an Excel VBA function I am trying to write a function that takes an array as input, does some manipulations to it - among others, redimensioning it by adding an additional row - and then outputs the modified array. However, when I try to redim the array, I get an error "Subscript out of range".
To illustrate my problem, I have created a simplified coding framework, with one function...:
Function funcTestFunction(Number As Integer, Arr As Variant)

ReDim Preserve Arr(0 To Number, 0 To 4)
funcTestFunction = Arr

End Function

... and a subroutine:
Sub subTestSubroutine()

Dim Number As Integer
Dim Arr() As Variant

Number = 10
ReDim Arr(0 To Number - 1, 0 To 4)
Arr = funcTestFunction(Number, Arr)

End Sub

In this framework, when I execute subTestSubroutine, I get a "Subscript out of range" error, which is located at the ReDim line in function funcTestFunction.
What am I doing wrong here?

Edit #1:
Even the following code does not work:
Sub subTestSubroutine()

Dim Number As Integer
Dim Arr() As Variant

Number = 10
ReDim Arr(0 To Number - 1, 0 To 4)
ReDim Preserve Arr(0 To Number, 0 To 4)

End Sub

A: I would add a comment if I could...
One thing I did in this situation was use Application.Transpose. I wanted to add more rows to my 2D array, but you can really only add more columns with Redim Preserve. So you can transpose it once, add the number of columns, and then transpose it back.
transposeArr = Application.Transpose(Arr)
ReDim Preserve transposeArr(0 To 4, 0 To number)
funcTestFunction = Application.Transpose(transposeArr)

A: The error was caused by resizing Arr () to Number-1 in subTestSubroutine and you are sending it Number in funcTestFunction.
Try with this code should work:
Function funcTestFunction (Number As Integer, Arr As Variant)

  ReDim Preserve Arr (0 To Number - 1, 0 To 4)
  FuncTestFunction = Arr

End Function

Hope this can help!


text:
Q: Thread leak on Apache Camel asyncRequestBodyAndHeaders Apache-camel version:2.10
I'm generating async request to endpoint using below Apache camel template producer.
We are acknowledged thread leak on multiple concurrent consumer for template.asyncRequestBodyAndHeaders()
Please let me know how we avoid the thread leak
Note: There is no thread leak with single thread
ref_document:
template = exchange.getContext().createProducerTemplate();
Future<Object> result = template.asyncRequestBodyAndHeaders(endpoint, sendMessage, httpClient);


text:
Q: redirecting DNS to new webhost I am changing web host for an existing site and before redirecting the nameservers to the new host I want to install a php shopping cart.  I have uploaded the shopping cart to my new web host but when I enter the admin page for the cart (www.example.com/admin.php )I get a 404 error because the page is being served from my old web host. I am using the host file on windows to redirect the dns to the new host's IP and the redirect works for the HTML pages but not for the shopping cart even though it is the same domain.  The host file redirect I am using is: ##.##.##.##  example.com.  Hopefully this makes sense.  Kind of new at this.

A: A couple of things you can try:

*

*Flush your DNS cache (assuming your using windows), type ipconfig /flushdns

*Explicitly add www.example.com to your hosts file (instead of just example.com)


text:
Q: How to set alarm only for weekends using alarm manager in Kotlin( android studio)? ( Saturday and Sunday) Set alarm only for saturday and Sunday
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, timeInMillis,
AlarmManager.INTERVAL_DAY, pendingIntent);


text:
Q: Postgresql-9.3: extract data from not strict json Can I extract selected field from not strict JSON?
My table is:
CREATE TABLE testme (id integer primary key, b json not null);

INSERT INTO testme(id,b) values (1,'{"similarartists":{"artist":[{"name":"x"},{"name":"y"}],"@attr":{"artist":"2H Company"}}}');

INSERT INTO testme(id,b) values (2,'{"similarartists":{"artist":{"name":"z"},"@attr":{"artist":"2H Company"}}}');

INSERT INTO testme(id,b) values (3,'{"similarartists":{"artist":"junk string","@attr":{"artist":"2H Company"}}}');

My first idea is:
SELECT json_array_elements(b->'similarartists'->'artist')->'name' FROM testme;

But it is wrong.

A: Psychic intuition tells me that what you mean is how to extract a particular field when the JSON structure is not uniform for each row in the table.
The query you posted is not valid for any of the rows in your sample, because none of them have an array in the attribute 'similarartists'. However this query is valid for row 1 at least:
SELECT json_array_elements(b->'similarartists'->'artist')->name
FROM testme where id=1;

In your other two rows - the first row contains a single similar artist and the other contains a scalar ("junk string"). So, I am guessing (psychic powers again) that want you want to do is this:

*

*If the row constains an array of artists then retrieve these separately

*If the row contains a single artist then retrieve this

*Otherwise ignore the row

Using the JSON support available in 9.3, this is surprisingly hard to do. There does not seem to be an easy way to deduce the JSON type of an attribute of array element inside a JSON structure. The solution I present here seems to work, but it is far from elegant:
SELECT CASE substring((b->'similarartists'->'artist')::text,1,1)
    WHEN '[' THEN json_array_elements(b->'similarartists'->'artist')->>'name'
    WHEN '{' THEN b->'similarartists'->'artist'->>'name'
    ELSE NULL
  END AS artist
FROM testme;

SqlFiddle
The query is examining a string version of the extracted artist field, to see if it starts with a '[', '{' or neither. If a '[' it is an array of artists and you can use json_array_elements on it. If it is a '{' then it is a single artist. Otherwise, it is junk and the query substitutes NULL. Of course you could use a WHERE clause to remove the junk rows altogether if desired.


text:
Q: App Engine Blob Store URL Response in Production Differs From Development I am using Go SDK (1.9.34 - 2016-03-15) on App Engine. The blobstore api was working correctly in both dev and production but now it seems to return different results, which now breaks the upload.
When I use this code in dev (using goapp serve) and production I get different results. The GET request comes with a parameter, which I extract and add it to the upload URL.
c          := appengine.NewContext(r)
upUrl, err := blobstore.UploadURL(c, "/upload", nil)
c.Infof("Upload url = %+v", upUrl)

if (err != nil) { //error handling here }

param      := r.FormValue("param")
q          := upUrl.Query()
q.Set("param", param)
upUrl.RawQuery = q.Encode()
c.Infof("Upload url after query  = %+v", upUrl)

In Dev I get (this is the intended behavior):
Upload url = http://localhost:8080/_ah/upload/RANDOMSTRING
Upload url after query = http://localhost:8080/_ah/upload/RANDOMSTRING?param=99

In Prod I get (incorrect upload url is being constructed):
Upload url = https://www.example.com/_ah/upload/?param=99/RANDOMSTRING1/RANDOMSTRING2/
Upload url after query = https://www.example.com/_ah/upload/?param=99

I know it is recommended to use Cloud Storage instead of blobstore but this is a legacy code so I don't want to change it right now. It was working fine a couple of weeks back and just noticed a difference. I upgrade from an older SDK to newer one (the results are based on the latest SDK) but still made no difference.
Any suggestions on what could be going wrong?
Thanks!


text:
Q: Laravel consulta que antes tardaba mili-segundos ahora tarda segundos y el numero de registros es el mismo Bueno antes tenia esta consulta en una aplicación de Laravel y se ejecutaba en muy pocos mili-segundos, pero ahora esta misma consulta tarda en ejecutarse 40 segundos. El numero de registros en mi aplicación es el mismo. No se cual puede ser el motivo de que ahora tarde tanto tiempo en ejecutarse.
            $products = DB::Table('product_details')->whereActive(1)->whereFeatured(1)
            ->join('product_stock', 'product_stock.product_id', '=', 'product_details.product_id')
            ->join('products', 'product_details.product_id', '=', 'products.code')
            ->join('categories', 'categories.code', '=', 'products.category_id')
            ->join('manufacturers','manufacturers.code','=','products.manufacturer_id')
            ->take(4)
            ->get(['products.name', 'products.code', 'products.slug', 'products.id', 'product_stock.stock','product_details.img','product_stock.fecha','manufacturers.code','categories.code']);


text:
Q: Multiple double colon (::) in call stack of VS 2010 C++ I am from java/C# background and I am trying to understand some C++ code. I learned that a code like following is defining a function out of the class file
Some_Class::someFunction ( void ){
//SOME LINE
//OF CODE
//FOR THIS FUNCTION
}

I am using Visual Studio 2010 to build the project. However, when I debug it to understand the flow, I see something like abc::def::ghk::The_Class::theFunction() at line 999 in Call Stack of VS. Now, I am able to find The_Class::theFunction( void ){//SOME CODE} definition in a class file Strange.cxx.
Based on my learning I think abc, def and ghk are classes but I am unable to find a definition like class abc or class def.
My question is why Call Stack in VS show like this and what's their purpose/meaning?

A: :: is the scope resolution operator. I suppose this wont help you much, so I will try to put it in simple terms.
abc::def::ghk::The_Class::The_Function()

This is the full name (*) of The_Function(). Suppose it is a method of The_Class as in your snippet. Then this class might be nested inside another class called ghk:
struct ghk {
    struct The_Class {
        void The_Function();
    };
};

You can nest classes inside nested classes until the doctor comes.
Next, C++ uses namespaces to organize names. For example all standard library is in the namespace std, the boost library puts its names in the namespace boost. In this way you can have a foo in boost and a foo in the standard library and you can still tell them apart because their full name is boost::foo and std::foo. Namespaces can be nested as well.
One hypothetical declaration of The_Function could be
namespace abc {
namespace def {
struct ghk {
    struct The_Class {
        void The_Function();
    };
};
}
}

*

*= The technical term is "fully qualified name", but actually the fully qualified name has another :: in front. For example ::foo is the name of a foo declared in the global scope (it is not placed inside a namespace).

A:
My question is why Call Stack in VS show like this ...

Because the call stack shows you the fully qualified function symbol where you came from.

... and what's their purpose/meaning?

Multible appearance of symbol parts delimited by double colons ::, indicates that the class or function declaration is embedded into a namespace or another class, e.g.:
namespace abc {
    namespace def {
        namespace ghk {
            class The_Class {
                void The_Function();
            };
        }
    }
}

or
class abc {
    class def {
        class ghk {
            class The_Class {
                void The_Function();
            };
        };
    };
};

or mixed
namespace abc {
    namespace def {
        class ghk { // No namespace definitions allowed inside.
            class The_Class {
                void The_Function();
            };
        };
    }
}

I think Java has the same feature for exactly the same purpose:
Distinguish class names from appearing in different namespaces / packages.


text:
Q: Intra-URL parameters and ForwardResolution mapping When I've got an ActionBean with a UrlBinding like
@UrlBinding("/whatever/{foo}/{bar}")

then if in some other action I create and return a ForwardResolution to "/whatever/hello/world", I'd kind-of like it if, inside the target ActionBean, the "foo" parameter were set to "hello" and the "bar" parameter were set to "world".  As far as I can tell in Stripes 1.5.3, that does not happen.  Am I missing something?

A: This answer is due to Matthijs Laan on the Stripes users mailing list.  All I needed was to add a <dispatcher> element to the <filter-mapping> for Stripes in my web.xml file. Formerly it looked like this:
  <filter-mapping>
    <filter-name>StripesFilter</filter-name>
    <servlet-name>StripesDispatcher</servlet-name>
    <dispatcher>REQUEST</dispatcher>
  </filter-mapping>

I just added:
    <dispatcher>FORWARD</dispatcher>

and now it (seems to) work fine :-)


text:
Q: How to convert getColorStateList (JAVA->C# xamarin for android) this is java code-:
mText.setTextColor(getResources().getColorStateList(R.color.xml_color_selector))

i tried convert to C#(this code in getView)
mText.SetTextColor(parent.Context.Resources.GetColorStateList(Resource.Drawable.xml_color_selector));;

Unhandled Exception:

Android.Content.Res.Resources+NotFoundException: File res/drawable/xml_color_selector.xml from color state list resource ID #0x7f0200a3

how to convert to C# code?
ps. xml_color_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

  <item android:state_activated="true" android:drawable="@color/menu_item_background_color_pressed" />
  <!-- Pressed tab -->
  <item android:state_pressed="true" android:drawable="@color/menu_item_background_color_pressed" />
  <!-- Non Pressed tab -->
  <item android:state_pressed="false" android:drawable="@android:color/transparent" />

</selector>