text:
Q: How to make a bar graph that sticks the "groupby"s together UPDATED to include a sample of the data:

I have a bar graph that takes the data I have, grouped by starting location (five boroughs of NYC), ad then within that, grouped by data of two different companies X and Y.
As of now the data shows 10 bars all separated equally (each borough and each company), and instead I want it to have 10 bars, but each borough sticks both companies together, so that I have 5 different sections, instead of 10.
Also, I would like to show the percentage overall within the bars if possible, but I don't know how to design it as such.
Lastly, what method would I use to add titles to the axis within the code?
I'm relatively new to Jupyter Notebooks and Data Analytics, so any help would be greatly appreciated, thank you so much!
(Note: It's not actually the five boroughs, but it's close enough - that's just for the purposes of the explanation, as the solution would be the same.)
My current code and graph:
df_stacked = df.groupby(['Starting Location', 'Company Chosen']).count()
# df_stacked['Customer_ID'].plot(kind = 'bar', stacks = df['BREAKDOWN', SUCCESSFUL TRIP])

df_stacked.drop(df_stacked.columns.difference(['Unavailable Scooter', 'BREAKDOWN', 'Successful Trip']), 1, inplace = True)

df_stacked.plot.bar(stacked = True, figsize = (10, 5))

This is what I would like it to look like:

A: I changed my previous answer to use random data exactly based on your data format (next time it would be helpful to provide your data sample as a text instead of an image!). And I added an example to put a text on the plot with or without an arrow.
Also when you use groupby, are you sure that you want to use count() and not sum() ? now you have the same count for each color on a given bar.
import matplotlib.pyplot as plt  #...

df_stacked = df.groupby(['Starting Location', 'Company Chosen']).count()  # sum()?
df_stacked.drop(df_stacked.columns.difference(['Unavailable Scooter', 'BREAKDOWN', 'Successful Trip']),
            axis=1, inplace = True) # add axis= to avoid the warning
df_stacked.reset_index(inplace=True)
df_stacked['X'] = df_stacked['Starting Location'] + '/' + df_stacked['Company Chosen']

fig, ax = plt.subplots(figsize = (10, 5))
ax.bar(df_stacked['X'], df_stacked['Unavailable Scooter'], label='Unavailable Scooter', edgecolor='black',
       color='b', width=0.5)
ax.bar(df_stacked['X'], df_stacked['BREAKDOWN'], label='BREAKDOWN', edgecolor='black',
       color='r', width=0.5, bottom=df_stacked['Unavailable Scooter'])
ax.bar(df_stacked['X'], df_stacked['Successful Trip'], label='Successful Trip', edgecolor='black',
       color='g', width=0.5, bottom=df_stacked['Unavailable Scooter']+df_stacked['BREAKDOWN'])

# Example of text/arrow on the (x,y) plot coordinates. Using ax.grid(True, which='both') would help
ax.annotate('my text', xy = (6.5, 4), xytext = (7, 5), arrowprops =
            dict(facecolor = 'black', width = 0.5, headwidth = 3))

lab = df_stacked['Starting Location'].unique()
lab = [lab[i//2] if i%2==0 else '' for i in range(2*len(lab))]
ax.set_xticks(range(8))
ax.set_xticklabels(labels=lab, rotation=0)

ax.tick_params(bottom=False)
ax.set_ylabel('Count')
ax.set(title='My title')

for cont in range(3):
    for i, bars in enumerate(ax.containers[cont].get_children()):
        bars.set_x(bars.get_x() - (0.75 if i%2 else 0.25))

plt.legend()
plt.show()

Output:


text:
Q: jenkins responds "HTTP/1.1 302 Found" when trying to access /lastBuild/api/json I'm trying to access jenkins (v2.177) API using curl. For instance, I try to get the lastbuild number as follows :
curl -v -u user:pass http://myjenkins:port/job/myjob/lastBuild/api/json

Insted of giving me a json, I get a "302 Found" with Content-Length egal to zero ! :
`*   Trying 11.90.1.9...
* TCP_NODELAY set
* Connected to 11.90.1.9 (11.90.1.9) port 8484 (#0)
* Server auth using Basic with user 'user7'
> GET /job/myjob/lastBuild HTTP/1.1
> Host: 11.90.1.9:8484
> Authorization: Basic dGVzdGl.../blc2Y...
> User-Agent: curl/7.58.0
> Accept: */*
>
< HTTP/1.1 302 Found
< Date: Tue, 14 May 2019 13:01:12 GMT
< X-Content-Type-Options: nosniff
< Location: http://11.90.1.9:8484/job/myjob/
< Content-Length: 0
< Server: Jetty(9.4.z-SNAPSHOT)
<
* Connection #0 to host 11.90.1.9 left intact`

Any idea why I don't get the JSON ?

A: Okay ...
I had to specify the branch like that :
curl -v -u user:pass http://myjenkins:port/job/myjob/job/mybranch/lastBuild/api/json

Now it works

redpajama_set_name: RedPajamaStackExchange


text:
Q: Creating a dictionary in an existed dictionary by keeping keys python I have this dictionary:
Dialogues = {
   "dialogue_id": "000001",
   "dialogue_turns": [
      { "turn_number": 0,
        "interlocutor_id": "0001",
        "turn_text": "Hi, how are you?" },
      { "turn_number": 1,
        "interlocutor_id": "0002",
        "turn_text": "Hi, I'm fine thanks. And you?" },
      { "turn_number": 2,
        "interlocutor_id": "0001",
        "turn_text": "I am good too, are you coming to the class today" },
      { "turn_number": 3,
        "interlocutor_id": "0002",
        "turn_text": "Yes, see you soon.bye" },
      { "turn_number": 4,
        "interlocutor_id": "0001",
        "turn_text": "bye" }
   ]
}

And I want to add a nested dictionary inside it by doing some counting on data as this:
Dialogues_analyzed = {
   "dialogue_id": "000001",
   "dialogue_analysis": [
      {"interlocutor_id": "0001",
       "total_turns":"3",
       "total_words":"number of words in all turns of id=1"},
      {
         {"interlocutor_id": "0002",
          "total_turns":"2",
          "total_words":"number of words in all turns of id=2"}
      }
   ]
}

How can I get the output without nested for loops? I tried to make a new dictionary and then merge it to primary dictionary. However, I lost the keys in new dictionary.

A: If you had
# [ just copied from your example ]
Dialogues = {'dialogue_id': '000001', 'dialogue_turns': [
  {'turn_number': 0, 'interlocutor_id': '0001', 'turn_text': 'Hi, how are you?'},
  {'turn_number': 1, 'interlocutor_id': '0002', 'turn_text': "Hi, I'm fine thanks. And you?"},
  {'turn_number': 2, 'interlocutor_id': '0001', 'turn_text': 'I am good too, are you coming to the class today'},
  {'turn_number': 3, 'interlocutor_id': '0002', 'turn_text': 'Yes, see you soon.bye'},
  {'turn_number': 4, 'interlocutor_id': '0001', 'turn_text': 'bye'}]}

and tried
dKey, iKey = 'dialogue_turns', 'interlocutor_id' ## [ just to shorten lines ]
dt_grouped = [
    (iid, [d for d in Dialogues[dKey] if d[iKey]==iid])
    for iid in set(dt[iKey] for dt in Dialogues[dKey])
] ## group turns by interlocutor_id
dialogue_analysis = [{
    'interlocutor_id': iid, 'total_turns': len(dt_list),
    'total_words': sum(len(dt['turn_text'].split()) for dt in dt_list)
} for iid, dt_list in dt_grouped]

Dialogues_analyzed = {  'dialogue_id': Dialogues['dialogue_id'],
                        'dialogue_analysis': dialogue_analysis  }

then Dialogues_analyzed would look like

{'dialogue_id': '000001',
 'dialogue_analysis': [
  {'interlocutor_id': '0002', 'total_turns': 2, 'total_words': 10},
  {'interlocutor_id': '0001', 'total_turns': 3, 'total_words': 16}]}

If you want to add dialogue_analysis into Dialogues, you can do so with Dialogues['dialogue_analysis'] = dialogue_analysis; or, if you wanted to leave the original Dialogues unchanged, you could instead unpack it (with **) into a new dictionary which would also contain dialogue_analysis:
Dialogues_with_Analysis = {**Dialogues, 'dialogue_analysis': dialogue_analysis}

and Dialogues_with_Analysis (or Dialogues if analysis was added to it) would look like:

{'dialogue_id': '000001',
 'dialogue_turns': [
  {'turn_number': 0, 'interlocutor_id': '0001', 'turn_text': 'Hi, how are you?'},
  {'turn_number': 1, 'interlocutor_id': '0002', 'turn_text': "Hi, I'm fine thanks. And you?"},
  {'turn_number': 2, 'interlocutor_id': '0001', 'turn_text': 'I am good too, are you coming to the class today'},
  {'turn_number': 3, 'interlocutor_id': '0002', 'turn_text': 'Yes, see you soon.bye'},
  {'turn_number': 4, 'interlocutor_id': '0001', 'turn_text': 'bye'}],
 'dialogue_analysis': [
  {'interlocutor_id': '0002', 'total_turns': 2, 'total_words': 10},
  {'interlocutor_id': '0001', 'total_turns': 3, 'total_words': 16}]}

You can also wrap the logic in a function:
def analyse_dialogue(dialogue_turns:list):
    dt_grouped = [
        (iid, [d for d in dialogue_turns if d['interlocutor_id']==iid])
        for iid in set(dt['interlocutor_id'] for dt in dialogue_turns)
    ]
    return [{
        'interlocutor_id': iid, 'total_turns': len(dt_list),
        'total_words': sum(len(dt['turn_text'].split()) for dt in dt_list)
    } for iid, dt_list in dt_grouped]

# dialogue_analysis = analyse_dialogue(Dialogues['dialogue_turns'])

so that if you had a list of dialogues like Dialogues_list = [{'dialogue_id': '000001', ...}, {'dialogue_id': '000002', ...}, ...] then you could either build a list of analyses with
dKey = 'dialogue_turns'
dialogues_analyses = [analyse_dialogue(d[dKey]) for d in Dialogues_list]

or build a new list of dialogues with analysis included with
dialogues_with_analyses = [{
    **d, 'dialogue_analysis': analyse_dialogue(d['dialogue_turns'])
} for d in Dialogues_list]

or add analysis into each dialogue dictionary in Dialogues_list with
dKey, aKey = 'dialogue_turns', 'dialogue_analysis'
for di, d in enumerate(Dialogues_list):
    Dialogues_list[di][aKey] = analyse_dialogue(d[dKey])


text:
Q: Numbers of elements in field The question is list all those integers $n$ such that $1 \leq n \leq 10$ and there exists a field with $n$ elements.
My approach:
Of course $n$ can take values $2,3,5,7$ since they are prime and we know $ \mathbb Z_p$ is a field iff $p$ is a prime.
Next I will use the concept that if $p(x)$ is a irreducible polynomial then the ideal $<p(x)>$ is maximal, and if $I$ is a maximal ideal of a ring $R$ then $R/I$ is a field.
Now I consider the ideal $<x^2+x+1>$ over $\mathbb  F_2(x)$, since $x^2+x+1$ is irreducible in $\mathbb F_2(x)$ then $\mathbb F_2(x)/<x^2+x+1>$ is a field. Any element of this field will have a form $ax+b$, where $(a,b) \in \mathbb F_2$, this implies this field has $4$ elements.
By the same type of argument, I have found the fields $\mathbb F_2(x)/<x^3+x^2+x+1>$ and $\mathbb F_3(x)/<x^2+x+1>$  have $8$ and $9$ elements respectively.
However I cannot find any field containing $6$ or $10$ elements. How to confirm whether there really are fields containing $6$ or $10$ elements?
Now I found that there are fields with $2,3,4,5,7,8,9$ elements. My method is a bit tedious. Are there any simple and direct computation to find so?

A: A finite field has prime characteristic.
If $R$ is any unital ring then there is a unique unital ring homomorphism
$\phi:\Bbb Z\to R$. Either $\phi$ is injective ($R$ has characteristic zero) or $\ker R=n\Bbb Z$ ($n\in\Bbb N$); in this case $R$ has
characteristic $n$. Then $\Bbb Z/n\Bbb Z$ is a subring of $R$.
If $R$ has composite characteristic $n=ab$ (a proper factorisation)
then $n1_R=0$ in $R$ but $n1_R=(a1_R)(b1_R)$ and $a1_R\ne0$
and $b1_R\ne0$. Therefore $R$ has zero-divisors and is not a field.
Therefore every finite field has prime characteristic. It
has a subfield $\Bbb Z/p\Bbb Z$, and as it is a vector space
over this subfield, it has $p^d$ elements for some $d\in\Bbb N$.


text:
Q: graphviz - prevent nodes and edges overlapping without splines I have a simple fdp graph laid out in graphviz, with a bunch of nodes (rectangle and diamond shaped) having fixed positions, and some of those nodes have child nodes (oval shaped) that I want to be arranged around them automatically.
I want all edges in it to be straight, with no curves or polylines or anything (i.e. as given by splines=false), but I also want those child nodes to not overlap with edges between nodes with fixed positions. The fixed positions are used as I need edges between the fixed nodes to be fully vertical or horizontal. This is something that I probably can achieve by iterating over different start values and hoping that the next one will not have overlaps, but so far this is a bit tiresome.
digraph G {

###GRAPH
layout=fdp
overlap=false
dpi=150
splines=false
inputscale=0.4
# fdp specific:
K=0.50
maxiter=2000
start=1251

###OBJECTS
node[shape=rectangle width=1.0 height=0.4 fixedsize=true]

vendor[label="Поставщик" pos="3,1!"
]

item[label="Товар" pos="0,2!"
]

post[label="Поставка" pos="2,2!"
]

check[label="Чек" pos="1,1!"
]

prod[label="Продажа" pos="0,0!"
]

###SUBOBJECTS
node[shape=oval width=1.5 height=0.5]
edge[arrowhead=none]

{
vendork[label=<ID поставщика>] "Название\nпоставщика" "Контакт\nдля связи"
}->vendor

{
itemk[label=<ID товара>]
Название Тип Подтип Характеристики "Розничная цена"
}->item

{
postk[label=<ID записи>] post1[label="ID товара"]
post2[label="Кол-во"]       post3[label="Цена поставки"]
post4[label="Дата"]     post5[label="Квитанция"]
}->post

{
prodk[label=<ID продажи>]    prod1[label="ID товара"]
prod2[label="Кол-во"]           prod3[label="Цена\nпродажи"]
prod4[label="Чек"]
}->prod

{
checkk[label=<ID чека>] Дата Кассир "Сумма" "НДС" "Итого" "Вид оплаты"
}->check

###CONNECTIONS
node[shape=diamond]
edge[arrowhead=open]

vendorpost[label="Поставляет" pos="3,2!"
]
vendorpost->vendor
vendorpost->post[arrowhead=openopen]

postitem[label="Поставлен" pos="1,2!"
]
postitem->item
postitem->post[arrowhead=openopen]

itemprod[label="Продан" pos="0,1!"
]
itemprod->item
itemprod->prod[arrowhead=openopen]

prodcheck[label="Включает" pos="1,0!"
]
prodcheck->prod[arrowhead=openopen]
prodcheck->check
}

(forgive the cyrillics)
I am compiling with no additional parameters (i.e. dot -Tpng graph.gv > graph.png). So far, I get this.

I've tried using neato instead as well, but, in most cases, it gives a pretty weird result, where it seems like it completely ignores the fixed node positions, and draws the child nodes whereever it wants:

I went through the list of attributes in the documentation, and so far none seem to address node/edge overlapping besides splines (unless I've missed something). What should I do to achieve the result I'm looking for?

A: There are several issues:

*

*layout=fdp causes the fdp layout engine to be used, no matter what the command line says

*Use neato -n if you want to nail down the node position (see below)

*by adding a ! to the position you are nailing down the pos (it won't change)

*dot is not useful here, it is directional (top-down)

If you remove all the !, I think you will get what you want.

A: So far, one solution I've found is by adding invisible stretched out nodes that cover each edge that is fixed(i.e. between two nodes with fixed positions) by appending this to the graph:
###NO VERTICAL/HORIZONTAL EDGE/NODE INTERSECT HACK
node[style=invis]
node[width=0.1 height=2.0]
t1[label="" pos="0,1.5!"]
t2[label="" pos="0,0.5!"]
t3[label="" pos="1,0.5!"]
t4[label="" pos="3,1.5!"]
node[width=2.0 height=0.1]
t5[label="" pos="2.5,2!"]
t6[label="" pos="1.5,2!"]
t7[label="" pos="0.5,2!"]
t8[label="" pos="0.5,0!"]
node[style=normal]

And this does what I want, i.e. removes all overlaps with fixed edges:

However, this is limited only to edges that are perfectly vertical/horizontal(note that there is still at least 1 overlap in "child" nodes), and overall seems like a really hacky solution as I have to add/change those "support beams" every time I add/change any more nodes to my graph. Is there a better solution to this?


text:
Q: javascript onclick with animation and iframes First of all, I'm not an expert in web development !
I need some help to improve my little web application.
You can see it here : https://jsfiddle.net/s9ysfc2b/2/
My functions :
    function rollout(id) {
  var height = document.getElementById(id).height;

  if(height <= 0) {
    document.getElementById(id).height = 450;
  } else {
    document.getElementById(id).height = 0;
  }
}

  function videotitle(texte){

  document.getElementById('txt').innerHTML = texte;

  }

  function go(loc) {
    document.getElementById('music').src = loc;
  }

The css transition :
iframe {
  transition: 0.3s height;
}

The html

  <form method="post">
    <input name="musicSelection" id="1" type="button" value="" onclick="go('https://www.youtube.com/embed/videoseries?list=PLg46y7jCyHx57PG6pE_UZ46r8PPSDCxnK'); videotitle('
Coucou!
'); rollout('music');" />
    <input name="musicSelection" type="button" value="" onclick="go('https://www.youtube.com/embed/videoseries?list=PLg46y7jCyHx6TNKaZ3auFYw5fT0qWiw67'); videotitle('
C\'est moi...
'); rollout('music')" />
    <input name="musicSelection" type="button" value="" onclick="go('https://www.youtube.com/embed/Di78xYSR0T0?list=PLO-2Biv8vPGPkkVV7LQZUguKkbwCA6qsg'); videotitle('
Tu te souviens?
'); rollout('music')" />

  </form>

When you click on emoji, a youtube video is rolling out.
If you want to click on another emoji, the video is rolling in and you have to click another time on emoji to roll the video out.
How can I roll in and out the video when I click on another emoji ? Without click one time to open it and one time to close it.
Please be free to suggest what I could do to improve whatever parts of my project
(sorry for my english..)
Thanks !

A: I have completely started again my project in jQuery, it's easier. I don't know how to solve it in pure JS.. now it works.
https://jsfiddle.net/gf3h6a42/
    $(function () {
    $(".playlistTitle").on("click", function (e) {
        $("#genericTitle").text($(this).data("text"));
        $('p').text($(this).data("desc"));
    });
});

$(document).ready(function(){
    $("a").click(function(e) {
        e.preventDefault();

        $("#playlist").attr("src", $(this).attr("href"));
    })
});

$(document).ready(function(){
  $('.button').click(function() {
        if ($('#roll').is(':visible')) {
              $('#roll').slideUp();
            if ($("#roll").data('lastClicked') !== this) {
               $('#roll').slideDown();
            }
        }
    else {
      $('#roll').slideDown();
    }
        $("#roll").data('lastClicked', this);
  });
});

$(document).ready(function(){
    $('.button').click(function() {
        $('.button').not(this).removeClass('buttonactive');
        $(this).toggleClass('buttonactive');
    });
});


text:
Q: Python: piping pcap file to stdout gives error I am trying to pipe the output of xz to a custom python script:
xz -cd file.pcap.xz | myscripy.py

However, I get an error when the script attempts to run this line:
  #!/usr/bin/env python2.7
from __future__ import print_function

import pcap
import io
STDIN_ALIAS = '/proc/self/fd/0'

pcap.pcap(io.open(STDIN_ALIAS, 'r'))

and received an error
    pcap.pcap(io.open(STDIN_ALIAS, 'r'))
  File "pcap.pyx", line 196, in pcap.pcap.__init__
TypeError: expected string or Unicode object, _io.TextIOWrapper found

I am on Ubuntu 18.04 and running under python 2.7.

A: You can't use Python to pass in packets from a file to pcap.pcap(). The pypcap library you are using is a thin wrapper around the pcap_open_offline() and pcap_create() C functions, and offers no facilities for passing in a Python file object. This wrapper only accepts a filename or a network interface name, nothing else.
The pcap_open_offline() function does accept - as an alias for stdin, so just pass that in directly:
import pcap

sniffer = pcap.pcap('-')

A: The error message already tell you what happened. You need a string to the pcap() function, not a file object. To fix this, try
pcap.pcap(io.open(STDIN_ALIAS, 'r').read())

But I am not sure this will work as your file might be binary instead of text. In such case, you may want to open with 'rb' instead of 'r' flag, and do some conversion afterwards (especially if you use Python 3 instead of Python 2.7).
I see another issue: your code is not portable as it depends on this:
STDIN_ALIAS = '/proc/self/fd/0'

A pythonic way to read the stdin is the follows (see  Reading binary data from stdin)
import sys
string = sys.stdin.read()

A: Have you tried upgrading PyPcap to work on Python 3? This could help, since Unicode handling is a lot cleaner and less prone to surprises on Python 3. The appropriate package is available, at least on Debian (and probably derived distros as well). Look for: python3-pypcap.


text:
Q: How to get longitude and latitude values without using the Internet from the phone? If possible can i get code and i am using API 26 I want to get location using GPS only. I don't want to use internet and GPRS in this application. My code is below; tell me where I'm wrong in this.
code:
MainActivity.java contains the reference to the layout
MainActivity.java
public class MainActivity extends AppCompatActivity {

private Button GetLocation;
private TextView coor;
private LocationManager locationManager;
private LocationListener locationListener;
GPSTracker gps;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    GetLocation = (Button) findViewById(R.id.GetLocation);
    coor = (TextView) findViewById(R.id.text);
    gps = new GPSTracker(MainActivity.this);
    GetLocation.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (gps.canGetLocation()) {
                double latitude = gps.getLatitude();
                double longitude = gps.getLongitude();
                coor.append("\n" + latitude + "" + longitude);
            } else {
                gps.showSettingsAlert();
            }
        }
    });

}}

GPSTracker contains main logic to obtain longitude and latitude points
GPSTracker.java
public class GPSTracker extends Service implements LocationListener{

private final Context mContext;

// flag for GPS status
boolean isGPSEnabled = false;

// flag for network status
boolean isNetworkEnabled = false;

// flag for GPS status
boolean canGetLocation = false;

Location location; // location
double latitude ; // latitude
double longitude; // longitude

// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

// Declaring a Location Manager
protected LocationManager locationManager;

public GPSTracker(Context context) {
    this.mContext = context;
    getLocation();
}

public Location getLocation() {
    try {
        locationManager = (LocationManager) mContext
                .getSystemService(LOCATION_SERVICE);

        // getting GPS status
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {
            // no network provider is enabled
        } else {
            this.canGetLocation = true;
            // First get location from Network Provider
            if (isNetworkEnabled) {

                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return location;
}

/**
 * Stop using GPS listener
 * Calling this function will stop using GPS in your app
 * */
public void stopUsingGPS(){
    if(locationManager != null){
        locationManager.removeUpdates(GPSTracker.this);
    }
}

/**
 * Function to get latitude
 * */
public double getLatitude(){
    if(location != null){
        latitude = location.getLatitude();
    }

    // return latitude
    return latitude;
}

/**
 * Function to get longitude
 * */
public double getLongitude(){
    if(location != null){
        longitude = location.getLongitude();
    }

    // return longitude
    return longitude;
}

/**
 * Function to check GPS/wifi enabled
 * @return boolean
 * */
public boolean canGetLocation() {
    return this.canGetLocation;
}

/**
 * Function to show settings alert dialog
 * On pressing Settings button will lauch Settings Options
 * */
public void showSettingsAlert(){
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

    // Setting Dialog Title
    alertDialog.setTitle("GPS is settings");

    // Setting Dialog Message
    alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

    // On pressing Settings button
    alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog,int which) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            mContext.startActivity(intent);
        }
    });

    // on pressing cancel button
    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });

    // Showing Alert Message
    alertDialog.show();
}

@Override
public void onLocationChanged(Location location) {
}

@Override
public void onProviderDisabled(String provider) {
}

@Override
public void onProviderEnabled(String provider) {
}

@Override
public void onStatusChanged(String s, int i, Bundle bundle) {

}

@Override
public IBinder onBind(Intent arg0) {
    return null;
}}


text:
Q: How to include dependencies from tests classes and main executable class in one jar I am trying to create an executable jar that will launch my selenide test.
TestClass
public class TestClass {

    @Test
    public void openBrowser(){
        System.setProperty("webdriver.chrome.driver", "chrome location");
        open("google.com");
    }
}

Test Executor
public class TestExecutor {
     public static void main(String[] args) {
        TestListenerAdapter tla = new TestListenerAdapter();
        TestNG testng = new TestNG();
        testng.setTestClasses(new Class[] { TestClass.class });
        testng.addListener((ITestNGListener) tla);
        testng.run();

    }
}

build.gradle
plugins {
    id 'java'
}
repositories {
    maven {
        url = 'jfrog artifactory url'
    }
}
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
task testJar(type: ShadowJar) {
    manifest {
        attributes 'Implementation-Title': 'Gradle',
                'Implementation-Version': project.version,
                'Main-Class': 'TestExecutor'
    }
    from sourceSets.test.output
    configurations = [project.configurations.testRuntime]
}

test {
    useJUnitPlatform()
 }

dependencies {
    testCompile  'org.seleniumhq.selenium:selenium-java:3.141.59'
    testCompile   'org.apache.poi:poi:4.1.0'
    testCompile   'org.apache.poi:poi-ooxml:4.1.0'
    testCompile  'org.slf4j:slf4j-simple:1.7.5'
    testCompile   group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: '5.5.2'
    testCompile  group: 'org.junit.jupiter', name: 'junit-jupiter-params', version: '5.5.2'
    testCompile   group: 'com.codeborne', name: 'selenide', version: '5.1.0'
    testCompile   group: 'com.aventstack', name: 'extentreports', version: '4.0.9'
    testCompile  group: 'org.junit.jupiter', name: 'junit-jupiter-engine', version: '5.5.2'
    testCompile group: 'org.testng', name: 'testng', version: '6.14.3'

    compile  group: 'org.testng', name: 'testng', version: '6.14.3'
}

group 'groupId'
version '1.0-SNAPSHOT'
sourceCompatibility = 1.8

when building the jar it cannot find the test dependencies.
I have tried adding the testRuntimeClasspath to the jar like so
  from {
        configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
        configurations.testRuntimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
    }

but then I receive an error saying Could not find or load main class
I've been going at trying to get this running for 2+ weeks. I don't know what I need to do really because all this is new to me. SEND HELP.

A: I would recommend you to use Gradle Shadow JAR plugin, instead of creating a JAR with all transitive dependencies youself. They even have the exact example for this case in the docs:
// Shadowing Test Sources and Dependencies
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar

task testJar(type: ShadowJar) {
    classifier = 'tests'
    from sourceSets.test.output
    configurations = [project.configurations.testRuntime]
}

This way you'll be 100% sure that your final JAR will have all the needed dependencies to run without hassling with collects.
And don't forget to specify the main class, like described here.
shadowJar {
    manifest {
        attributes 'Main-Class': 'a.b.C' // FQDN!
    }
}


text:
Q: Friends and users table I want to join users table and friends table.
My users ta le have username and password
While friends table have  user_id1 and friend_id .problem is that i will recieve user id from sessions using username but how will i recieve the id of a friend that i want to add/follow.for example the user click on add friend button.i want to recieve two parameters user parameter and friend parameter.also please help me with the joining code of pivot table,how would i joinfriend table  user and friend id column with the user table..any hint will be helpful.

A: Tables
Users

id | name | email | details
----------------------------
 1 | abc  | a@b.c | some detail
 2 | def  | d@e.f | some detail

Friendship

id | user_id | friend_id
-----------------------------
 1 |  1      | 2
 2 |  2      | 1

In the view where you have displayed users along with add to friend link. you will also pass the id of that user from the loop which you have used to iterate the users e.g
<?php foreach($users as $user) {?>

<?php echo $user->name?>

  <a href="<?php echo base_url().'users/addtofriend/'.$user->id?>" class="btn btn-info"> Add to Friend
<?php } ?>

In your Controller function you can get the user id from session and the user to be added to friend from url like
function addtofriend()
{
  $userId=$this->session->userdata['id'];
  $friendId=$this->uri->segment(3);
  // Call your model function
  $this->user_model->addFriend($userId,$friendId);
}


text:
Q: Match Exactly column name in a data frame I have the following
for col in Features:
     My_Features = pd.merge(My_Features,Drug.ix[:,[col]], left_index = True,right_index=True)

which produces the following
My_Features.columns
Out[373]: Index([u'**PCBD1_x**', u'**PCBD1_y**', u'KLK8', u'TNFSF13 /// TNFSF12-', u'RIPK5', u'SVIL'], dtype='object')

while it should match exactly Features which is
Features
Out[375]: ['PCBD1', 'KLK8', 'TNFSF13 /// TNFSF12-', 'RIPK5', 'SVIL']

how can I change the "col" match when creating the data frame above .in other words something to avoid  the BOLD column matches. it is a regular expression problem.
Update
I am trying to extract the columns listed in "Features" from "Drug". Before the
for col in Features:
 My_Features = pd.merge(My_Features,Drug.ix[:,[col]], left_index = True,right_index=True)enter code here

I have the following line to create the structure for My_Features
My_Features =  pd.DataFrame( Drug.ix[:,Features[0]] , index = Drug.index , columns=[Features[0]])

so the whole code will look like
My_Features =  pd.DataFrame( Drug.ix[:,Features[0]] , index = Drug.index , columns=[Features[0]])
iterfeatures = iter(Features)
next(iterfeatures)
for col in Features:
    My_Features = pd.merge(My_Features,Drug.ix[:,[col]], left_index = True,right_index=True)

A: You can use pandas.DataFrame.filter(). It has a regex argument [as well as a "like" argument]. http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.filter.html


text:
Q: How to remove rows with uncorrect id in pandas dataframe I'm using python3. I would like to remove incorrect id's from my dataframe column.
Example:
d = {'name': ['a', 'b', 'c', 'd'], 'id': [9356622,9030321,9408530, 1112200]}
df = pd.DataFrame(data=d)

I need to verify id by multiplying each of the first six digits by a factor of 2 to 7 corresponding to their position from right to left. For example, for id 9356622:
(9×7) + (3×6) + (5×5) + (6×4) + (6×3) + (2×2) = 152. So in this case last number 2 so it's correct since the last number of id 9356622 is 2. I need to check with the last number after preforming this calculation.

A: Input data:
>>> df
  name       id
0    a  9356622
1    b  9030321
2    c  9408530
3    d  1112200

Explode the id numbers to digits:
df1 = df['id'].astype(str).map(list).apply(pd.Series).astype(int)

>>> df1
   0  1  2  3  4  5  6
0  9  3  5  6  6  2  2  # 152 -> modulo(10) = 2 -> True
1  9  0  3  0  3  2  1  # 91  -> modulo(10) = 1 -> True
2  9  4  0  8  5  3  0  # 140 -> modulo(10) = 0 -> True
3  1  1  1  2  2  0  0  # 32  -> modulo(10) = 2 -> False

Now check your math operation:
>>> df1.iloc[:, :6].mul(range(7, 1, -1)).sum(axis=1).mod(10) == df1.iloc[:, 6]
0     True
1     True
2     True
3    False
dtype: bool

A: def fun_IMO(string):

    try:
        pattern = r"([0-9][0-9][0-9][0-9][0-9][0-9][0-9])"
        regexFinder = re.compile(pattern)
        string = string.lower()
        res = regexFinder.search(string)
        if res.groups():
            try:
                nuberIMO = res.groups()[0]
                numberIMO_calc = (int(nuberIMO[0])*7) + (int(nuberIMO[1])*6) + (int(nuberIMO[2])*5) + (int(nuberIMO[3])*4) + (int(nuberIMO[4])*3) + (int(nuberIMO[5])*2)
                if str(numberIMO_calc)[-1] == nuberIMO[0]:
                    return True
                else:
                    return False
            except Exception as e:
                return e
    except Exception as e:
        return e


text:
Q: How do I use MYSQL WHERE LIKE with prepared statements? I have a table that stores cities
id | city         | player
1  | Miami        | Mark
2  | Miami Beach  | Tiffany
3  | New York     | John
4  | Boston       | Bette
5  | Boston       | Laura

I have a query that selects the city according to input
$select = $conn->prepare("SELECT player FROM game_table WHERE city LIKE=?");
$select->bind_param("s", $city);
$select->execute();
$select->close();

How do I use the query with a prepared statement and select everyone from the same city? Miami should return 2 players. How can I make sure the system recognizes Miami Beach as part of Miami?


text:
Q: Как через onCliсk передать в функцию сразу 2 значения с уникальными id. Игра "Угадай-ка для 2 игроков". JavaScript Проблема:

*

*Не могу реализовать при нажатии на клавишу "Угадать" обработку значений, введенных игроками в поля ввода .

1.2. JS-скрипт обрабатывает только первое поле ввода, единственный раз выдает ответ и далее скрипт замирает.
Что я хочу сделать (новичок, не знаю - как дальше):

*

*Нажатие на клавишу "Угадать" должно передать сразу два ответа в функцию на обработку.

*JS-скрпит должен обработать эти два ответа

*По каждому игроку ожидается ответ (возможно через .innerHTML) о результате попытки игрока (типа "не верно", "Игрок № ... угадал")

*Общее кол-во попыток угадать   = 4

Суть:
Игра на 2 персоны, надо одному из игроков угадать загаданную компьютером рандомную цифру.
Внешнее оформление:
Html+CSS.
2 поля ввода (input) для каждого игрока и одна кнопка "Угадать" (onClick = "...")

var vopros = parseInt(Math.random() * 10);
var igrok1 = '№1';
var igrok2 = '№2';
let otvet1, otvet2;

//забираю ответ из полей ввода

//вызов ф-ции от нажатия клавиши "Угадать"

function game(otvet, gamer) {

  for (let i = 1; i <= 1; i++) {

    function zaborOtveta(otvet) {
      if (igrok1) {
        otvet1 = +document.getElementById("otvet1").value;
        return otvet1;
      } else if (igrok2) {
        otvet2 = +document.getElementById("otvet2").value;
        return otvet2;
      }
    }

    //otvet = prompt("Выход клавиша q. Угадай число от 0 до 10. Ход игрока : " + gamer);
    otvet = zaborOtveta(otvet);

    if (otvet == "q" || otvet == 'esc' || otvet == null) {
      return false;
    }
    otvet = +otvet;

    if (otvet == vopros) {
      alert("Число угадал игрок " + gamer);
      return false;
    } else if (otvet > vopros) {
      alert("Чет-то много");
    } else if (otvet < vopros) {
      alert("Слишком мало");
    }
  } //for():end

  return true;
} //function (): end

let n = 0;
while (n < 4) {
  //искусственно ограничил кол-во попыток, чтоб не было бесконечного цикла

  n++
  if (!game(otvet1, igrok1))
    break;

  n++
  if (!game(otvet2, igrok2))
    break;

} //while ( ): end

alert("Было загадано:" + vopros);
@import url(https://fonts.googleapis.com/css?family=Roboto:400,100,100italic,300,300italic,400italic,500,500italic,700,700italic,900,900italic);
* {
  margin: 0;
  padding: 0;
}

body {
  background-color: #DA3725;
  font-family: 'Roboto', sans-serif;
}

.header {
  min-width: 1300px;
  border-bottom: 1px solid #b5b7ba;
  background-color: #F8F000;
  margin: 0 auto;
  height: 50px;
  text-align: center;
  padding-top: 18px;
}

.header .selected {
  color: #000;
}

.center {
  width: 1300px;
  margin: 0 auto;
}

.header a {
  color: #F90505;
  font-size: 25px;
  font-weight: 300;
  text-align: left;
  text-decoration: none;
  height: 30px;
  line-height: 30px;
  display: inline-block;
  padding-right: 40px;
}

.header span {
  padding: 0 38px;
}

.content {
  min-width: 1300px;
  margin: 0 auto;
  min-height: calc(100vh - 140px);
}

.content h1 {
  width: 100%;
  float: left;
  text-align: center;
  color: #2e353d;
  font-size: 40px;
  font-weight: 300;
  margin-top: 63px;
  margin-bottom: 75px;
}

.content h3 {
  color: #242424;
  font-size: 35px;
  font-weight: 300;
  text-align: left;
  margin-left: 41px;
  margin-bottom: 52px;
}

.content h5 {
  color: #242424;
  font-size: 24px;
  text-align: left;
}

.content img {
  margin-left: 17px;
  width: 389px;
  border-radius: 50%;
}

.content .box_text {
  width: 671px;
  background-color: #ffffff;
  float: right;
  padding: 49px 48px 51px 76px;
  margin-bottom: 100px;
  border-radius: 25px;
}

.content .box_text p {
  color: #242424;
  font-size: 24px;
  font-weight: 100;
  text-align: left;
  margin-bottom: 31px;
}

.content .box_text a {
  color: #40678a;
  font-size: 24px;
  font-weight: 100;
  text-align: center;
  text-decoration: none;
  padding-right: 30px;
}

.content .media {
  margin-right: 0;
}

.content .box {
  background-color: #A4A9A0;
  width: 800px;
  min-height: 500px;
  margin: 50px auto 50px auto;
  padding-top: 37px;
  padding-left: 38px;
  padding-bottom: 100px;
  border-radius: 25px;
}

.content .box p {
  color: #242424;
  font-size: 24px;
  font-weight: 100;
  text-align: left;
  margin-top: 37px;
  margin-bottom: 30px;
}

.content .box input {
  border: 1px solid #a0a0a0;
  background-color: #f5f5f5;
  width: 457px;
  height: 34px;
  padding: 0 20px;
  font-size: 20px;
  font-weight: 100;
  margin-bottom: 12px;
}

.content .box a {
  display: block;
  float: left;
  background-color: #8cbbd3;
  color: #ffffff;
  font-size: 24px;
  font-weight: 300;
  text-align: center;
  text-decoration: none;
  margin-top: 30px;
  padding: 11px 51px;
}

.content .box a:hover {
  background-color: #5ba1d3;
}

.footer {
  /* # == id */
  background-color: #434445;
  min-width: 1300px;
  /*float: left;*/
  height: 140px;
  text-align: center;
  color: #a4a4a4;
  font-size: 20px;
  font-weight: 100;
  line-height: 140px;
}

.footer a {
  color: inherit;
}

#a,
#b {
  font-weight: 400;
}

#otvet1,
#otvet2 {
  border: 1px solid;
  border-radius: 8px;
}

/*для Угадай-ка 2*/

.box_grid {
  display: grid;
  grid-template-columns: 300px 500px;
  grid-template-rows: 100px 100px 85px;
  align-content: center;
}

.box_grid #otvet1,
.box_grid #otvet2 {
  grid-column-start: 2;
  width: 150px;
  margin-left: 25px;
}

.box_grid #a,
.box_grid #b {
  font-weight: 400;
  margin-top: 0px;
}

.box_grid .btn {
  grid-column-start: 1;
  grid-row-start: 3;
}

    Главная
    Загадки
    Угадайка
    MinMax
    УгадайКа-2

Игра "Угадай-ка (2 игрока)"

Игрок №1 вводит число :

          <input type="text" id="otvet1">

Игрок №2 вводит число :

          <input type="text" id="otvet2">

          Угадать

  Copyright © #SamboRulit

A: Не стал заморачиваться с дизайном, думаю так понятно будет, как игру сделать.

const rand = (min, max) => Math.round(min - 0.5 + Math.random() * (max - min + 1))

const $form = document.forms[0];

let num;
const reset = () => {
  num = rand(1, 10);
  $form.round.value = 4;
  $form.p1.value = $form.p1.nextElementSibling.innerHTML = ``;
  $form.p2.value = $form.p2.nextElementSibling.innerHTML = ``;
  console.log(num);
}
reset();

const check = ($i, msg) => {
  const val = +$i.value;
  if (num === val) {
    alert(msg);
    return true;
  }
  $i.nextElementSibling.innerHTML = val < num ? `Маловато будет` : `Многовато будет`;
  return false;
}

$form.addEventListener(`submit`, e => {
  e.preventDefault();
  const p1 = +$form.p1.value;
  const p2 = +$form.p2.value;

  if (p1 === num && p1 === p2) {
    alert(`Оба игрока выиграли`);
    return reset();
  }

  if (check($form.p1, `Игрок 1 выиграл`)) return reset();
  if (check($form.p2, `Игрок 2 выиграл`)) return reset();

  $form.round.value = +$form.round.value - 1;
  if (+$form.round.value > 0) return;
  alert(`Все проиграли`);
  reset();
});

$form.addEventListener(`reset`, reset);
label {
  display: block;
  margin: 10px 0;
}
<form>
  Попыток<input type="number" name="round" value="4" autocomplete="off" readonly>
  Игрок 1<input type="number" name="p1" autocomplete="off">
  Игрок 2<input type="number" name="p2" autocomplete="off">
  <button type="submit">Угадать</button>
  <button type="reset">Сбросить</button>
</form>


text:
Q: How to proceed to make a software which tracks the function calls of another software? I wish to make a software which tracks the function calls of another software.
It should be like which function is being called from where "during run time".
Example:
int main ()
{
    a ();
    b ();
    c ();
    return 0;
}

a ()
{
   d ();
   e ();
}

b ()
{
   e ();
   f ();
}

Assuming I wish to write this currently in C for C, how should I keep a track of the calls at run time (starting from the first call) - with threads and without threads?
Hints?

A: You can do this before runtime by static analysis, or at runtime by dynamic analysis.
You have only two ways to do this at runtime, and they both amount to instrumenting code:
Instrument the source code
Modify ("instrument") the source code so it keeps track of what you want, e.g., modify
every call site to pass an additional argument effectively containing the calling function name, and every function entry to record the entry to that function (e.g., effectively the called function name) and the calling function name.  The instrumentation process needs to build a cross-reference from points that are instrumented, back to source file and line to enable later reporting.
You can do this in a completely automated way by using a Program Transformation System (PTS), which can parse source code to make ASTs, modify the ASTs, and then regenerate source.  Often a PTS will let you write the changes as source-level patterns of the form, "if you see this, replace it by that".  (No, regexes can't do this).
An extended example of how do this can be found in my technical paper, Branch Coverage for Arbitrary Languages.  The paper shows discusses what is in a PTS, and then shows typical instrumentation transformations.
Getting this done "right" for a language like C can be difficult, because you need as a foundation, a full C parser, which is a major technical feat in its own right.  Best to get such a beast in completed form  (some of the PTS have this, consider Concinnelle or DMS) or you'll never get around to doing the instrumentation part.  (Another answer suggests that GCC has much of this instrumentation functionality built-in).
Done reasonably, the execution cost of the additional instrumentation is pretty modest (10-30%).   This concept has been used to implement test coverage tools and timing profilers, which operate by tracking the dynamic set of calls, which seems to be exactly what you want.
Instrument the object code
Modify the execution engine that runs the code to keep track of the details you want.  Given that you want to do this with C programs, the execution engine is essentially the underlying instruction set.
Since you can't reasonably modify the processor chip itself, you'll have to either:

*

*modify the object code (using object-code equivalents of program transformations, see preceding paragraph for concepts, or see tools like PIN and Valgrind for details of implementation),

*or write some kind of clever instruction set interpreter that collects the information it needs as it encounters call-instructions (this is likely to be rather slow, because of its interpretive nature).
Implementing these for real instruction sets is complicated by the instruction sets themselves (Intel's X86 instruction set is huge), object file formats, etc.  Don't expect this path to be easier than the source instrumentation path; just expect it to have a different set of problems.
One standard problem is knowing what to instrument; the object code space is full of code (libraries, system routines, ...) that aren't part of the application of interest, and thus aren't interesting to collect test coverage data for.  For this, you need a symbol table ( pairs) to tell what is application code, and what is not.  You also need to be able to trace from the name to a point in the original source file(s),
in order to report the results.
One other difficulty with object code instrumentation is that it is difficult to tell if a function foo, which has been inlined, has been executed ("covered").  The source instrumentation scheme does not have this problem, because foo gets instrumented before it gets compiled/inlined, so the instrumentation gets inlined too.
Threads
Handling threads is an orthogonal issue.  At each place where you record a fact X-calls-Y, you simply attach the thread ID (or its equivalent) T, obtained from the OS, to produce X-calls-Y-in-T.  It isn't clear from your question why you want to do this.
Static Analysis
You could decide to skip all the hassles of runtime implementation, and build/get a static analyzer that can produce a call graph.   Getting of these for C might be possible using Clang or DMS.   Building it yourself is likely difficult; now you need a full C parser, complete data flow and points-to analysis, and call-graph construction. The details won't fit in this paragraph.

A: This is very much platform dependent. What you need is to do more or less what a debugger does.
The way I'd approach this (I actually implemented all this once when I had to debug tools needed to build gdb on an new architecture):
Read the symbol table of the program you want to debug. You said Linux in a comment, so to start you need a library that reads ELF files or read the ELF specification and implement something yourself.
Use the ptrace syscall to create a breakpoint at the function main. If you're lucky, your system has a ptrace facility to create breakpoints and keeps the bookkeeping in the kernel. If it doesn't, you need to figure out the breakpoint instruction for your cpu architecture and implement breakpoints yourself.
Next, you need to figure out the debugging hooks in your dynamic loader so that you know when shared libraries are loaded. You'll need the symbol tables of the libraries as well.
Now that you have all the symbols (admittedly this is after your program has run for a while, since it had to load the dynamic libraries, but we'll pretend that the program starts at main) create breakpoints at all functions you've gotten from the symbol table.
Let the program run. Every time you hit a breakpoint, reverse look up the instruction pointer in the symbol table. Save the name of the function to a file or wherever you want to save it. You can now track function calls.
Or just use a debugger. gdb can probably be scripted to do something like this.

A: I apologize that these are not open source tools, but I have used them for research in the past and they enable the functionality you require, so you might get some hints from playing with them.
On Linux, try taking a look at how Pin works.
On Windows, look at Detours.

A: I would use the instrumentation functionality built into GCC to do the source-code instrumentation for you.
Here is a link for a tutorial: http://balau82.wordpress.com/2010/10/06/trace-and-profile-function-calls-with-gcc/
Basically you tell the program to call an instrumentation-function before each function call and give two addresses as parameters.
You provide that instrumentation-function yourself, and it gets called with an from-address and a to-address.
The from-address tells you where the function at the to-address is being called from.
You then need to translate the addresses into function names (which can be done given line-numbers in a source-code file).
By using the GNU binutils tool addr2line you can convert the to- and from-address to line numbers, given the binary file was compiled with debug information (gcc -g ...).
It is very fast to get started with instrumentation using this approach.
EDIT:
If you do not have the source and only the binaries at hand, you can try disassembling or parsing the binaries into assembly. This way you can separate the program into logic blocks which are jumped to/from.
Function names cannot easily be recovered without the source-code, so you can risk to only be able to track jumps within the logic blocks you've previously divided the program into.
This is what several debuggers do AFAIK.
I think OllyDbg (Windows only) and IDA pro can give a visual flow chart sorta, or show a colored block-diagram or something like that.
You're really having to work hard without the source, whereas if you have the source code at hand, you have all means of doing exactly what you want. Adding just one step in between write code -> compile -> execute so it becomes write code -> insert instrumentation -> compile -> execute.

A: The laborious way is inserting a printf as the first and last line of a function. Or using a debugger.
A problem could be debuggers who set all variables to 0 / null, "solving" bugs in the code.
My solution was
using ctrace


text:
Q: Matrix norms and partitioning ON a practice exam http://math.berkeley.edu/~mgu/MA128B2012S/SampleMidTerm.pdf
I am unsure how we can begin #4. I know the definition of the matrix norm and the infinity norm, but they dont seem to work in this example

A: $\|\cdot\|_1$ is the $1$-norm, not infinity norm. It is defined by $\|(x_1,\ldots,x_n)^T\|_1=\sum_{i=1}^n|x_i|$. Note that
$$
\|A\|_{2,1}=\max\limits_{\sum\limits_i |x_i|=1}\|\sum_i x_ia_i\|_2.
$$
By triangle inequality, for every vector $x$ such that $\|x\|_1=1$,
\begin{equation}
\|\sum_i x_ia_i\|_2\le\sum_i \|x_ia_i\|_2=\sum_i |x_i|\|a_i\|_2
\color{red}{\le}\sum_i |x_i|\max_j\|a_j\|_2=\max_{1\le j\le n}\|a_j\|_2.\tag{1}
\end{equation}
Taking maximum over all $x$ with unit $1$-norm, we get $\|A\|_{2,1}\le\max_{1\leq j\leq n}\|a_j\|_2$. Now, show that there is a vector $x$ such that $\|x\|_1=1$ and equality in $(1)$ holds. (When does equality hold for the red inequality above?)

A: Another way to see this problem is that
$$
\|A\|_{2,1} = \max_{\|x\|_1=1}\|Ax\|_2.
$$
In other words, we're taking the largest vector that we get when we take all convex combinations (positive linear combinations where the coefficients sum to $1$) of the columns of $A$.
Suppose that we take the column with the largest norm ($a_j$). Then if we take a convex combination of $a_j$ with any other column, then the norm is decreased, because the combination lies on the line segment between $a_j$ and the other column.
Therefore
$$
\|A\|_{2,1} = \max_{1\leq j\leq n}\|a_j\|_2.
$$


text:
Q: How to make multiple threads use the same socket to read and write? **
There will be multiple clients sending messages to the server on port 6069.I am looking to handle multiple requests at the same time, but I am not sure the code below can do it.
There will be requests on socket's queue. Since there is only one thread it will execute its iteration on one request and then it will take next request from the queue. How can I serve multiple clients at the same time?
**
This is the class creating thread to listen on port 6069.
public class NetworkModule extends Thread {
  private ServerSocket serverSocket;

  public NetworkModule(int port) throws IOException {

    serverSocket = new ServerSocket(port);
  }

    public void run() {
      while (true) {

                /* Here I read strings from the inputstream and write
                  to outputstream corresponding to "serverSocket" and call
                functions from other classes*/
      }
    }

}

below is how Main class looks like

public class Main
{

   public static void main(String[] args)
   {
       try
          {
            int port=6069;
             Thread t = new NetworkModule(port);
             t.start();

          }
       catch(IOException e)
          {
             e.printStackTrace();
          }

   }

}

A: If you can isolate client handling method, say in a new class ClientHandler that also extends Thread where in run() you read and write to streams. Then in your run() of NetworkModule:
while (true) {
     Socket socket = serverSocket.accept(); // blocks until new client connects
     ClientHandler handler = new ClientHandler(socket); // pass reference to socket
     handler.start(); // start executing in new thread
}

Generally, it's better to implement Runnable instead of extending Thread, because you can implement many interfaces but extend only from a single class, due to Java inheritance model.

A: That is not a good way for writing a server program!
you'd better have two classes :

*

*1)client_handler :  a class that handles the clients and is responsible of serving the clients. let's name it client_handler.java .
One object of this class should be created for each client connected to the server.
Clients should get services in parallel , hence , this class should extend Thread or implement Runnable interface .

*2)Server : Another class that waits for clients to connect ! Let's name it : server.java
this class will implement the main method !
server class should make a new thread on each connection , so that clients can get services in parallel .
**********************************
below , there is some code to demonstrate the things I told above :
/*this is the server class i talked about : */
public class server{
   static void main (String args[]){
        ServerSocket ss = new ServerSocket (args[0]);
        while (true){
            Socket  s =  ss.accept();
            client_handler ch = new client_handler(s);
            Thread t = new Thread(ch);
            t.start();
        }
    }

}

and here is a sample code for client_handler :
public class client_handler implements Runnable{
    private Socket s ;
    private Scanner in ;
    print PrintWriter out;

    public client_handler(Socket s){
        this.s =s;
        in= new Scanner(s.getInputStream());
        out= new PrintWriter(s.getOutputStream());
    }

   public void run(){
      // this is the entry of your thread .
      // you can analyse the request received here . and send responses !

   }
}

A: You should change your code in such way to provide access from server side for more clients to access (process) data sent through port 6069.
Your client application which is second is just simple one with implemented logic to connect to active server (if any, or based on some rules, etc).
Server application makes the magic to provide access. This means each client to see each message sent by other clients and vice-versa.
I think is useful to read: Knock Knock Protocol. It will explain you a lot how things are managed and they work in your case.


text:
Q: oozie workflow to grant 777 permission on hive table ie directories I wanted to grant 777 permission to hive directories using OOzie workflow.
do we have any xml tags which will be used directly
FYI I am using Hadoop , Ambari , HUE.


text:
Q: converting from signed int to unsigned int without casting int isNegative(int x) {
  return ((unsigned) x)>> 31;
}

I'm writing a function that takes 32 bits and returns 1 if x<0, and 0 otherwise. How do I convert a signed int to an unsigned int without casting.

A: OP has different implied questions

a function that takes 32 bits and returns 1 if x<0, and 0 otherwise.

int isNegative(int x) {
  return x < 0;
}
// or maybe return bool/_Bool
bool isNegative(int x) {
  return x < 0;
}
// or pedantically
int isNegative(int_least32_t x) {
  return x < 0;
}
// or pedantically and nearly universally portable,
int isNegative(int32_t x) {
  return x < 0;
}

converting from signed int to unsigned int without casting (and)
  How do I convert a signed int to an unsigned int without casting.

Simply assign the value
 int i;
 unsigned u = i;

Attempting to use >> to combined these two risk implementation defined behavior and should be avoided unless compelling reasons are given.

EXAMPLE An example of implementation-defined behavior is the propagation of the high-order bit when a signed integer is shifted right. C11§3.4.2 2

A: In this case you don't need to.  If you get rid of the cast, right shifting retains the sign bit.
Assuming int is 32 bit, removing the cast results in -1 for negative numbers and 0 for nonnegative numbers.  While the actual return value differs for the nonnegative case, in a Boolean context it will work as you expect.

A: Your question is to write a function that takes 32 bits and returns 1 if x < 0
int isNegative(int x) {
    return x < 0;
}

This will work no matter what the size of int and does not invoke any type conversions. I suppose you have over-thought this problem.

A: There is a variety of operations that perform automatic type conversions, among them assignments, arithmetic operations under certain conditions, and function calls (conversion of certain argument values).
Thus, you could achieve conversion of (signed) int arguments to unsigned int simply by declaring that to be the parameter type:
int isNegative(unsigned x) {
  return x >> 31;
}

Admittedly, however, that function interface could be a little confusing.  You might therefore prefer to do this:
int isNegative(int x) {
  unsigned ux = x;
  return x >> 31;
}

However, I don't think either of those is as clear as your original version, with its cast.  Type conversion is the entire purpose of a cast, and when conversion is what you need (and all that you need), a cast is the right tool for the job.
Of course, I do overall prefer the even simpler family of approaches suggested by @chux.


text:
Q: Função para validar um CPF em R Por favor, preciso de uma função em R para validar um CPF, ou seja, verificar se um número passado como parâmetro é um CPF válido.

A: Bom, já que ninguém respondeu, apesar de concordar com os comentários acima, hoje é domingo, aqui vai.
Em primeiro lugar, podia de fato ter incluído alguma informação sobre esse tal de CPF. Leia o comentário do Rafael Cunha outra vez. Eu que sou Português nunca tinha sequer ouvido falar de semelhante coisa. Na Wikipedia encontrei toda a informação necessária incluindo o algoritmo que vou usar abaixo. Isso deveria ter sido o seu trabalho.
Código.
O código abaixo são três funções. A primeira, cpf_dig_controle calcula os dígitos de controle ou verificadores de um número de 8 dígitos. A função está vetorizada de modo a aceitar vetores numéricos como entrada. Se por acaso a entrada for de classe character a função em princípio também não se engasga mas não garanto isso.
cpf_dig_controle <- function(y){
    v1 <- 0L
    v2 <- 0L
    z <- as.integer(rev(strsplit(as.character(y), "")[[1]]))
    for(i in seq_along(z)){
        v1 <- v1 + z[i]*(9 - (i %% 10))
        v2 <- v2 + z[i]*(9 - ((i + 1) %% 10))
    }
    v1 <- (v1 %% 11) %% 10
    v2 <- v2 + v1*9
    v2 <- (v2 %% 11) %% 10
    c(v1, v2)
}

De seguida vêm duas funções, uma para gerar números CPF, com a devida formatação e outra para verificar a sua validade.
cpf_gerar <- function(x){
    g <- function(y, v){
        z <- strsplit(as.character(y), "")[[1]]
        z <- as.integer(c(z, v))
        res <- sprintf(fmt = "%d%d%d.%d%d%d.%d%d%d-%02d",
                             z[1], z[2], z[3], z[4], z[5],
                             z[6], z[7], z[8], z[9], z[10])
        res
    }
    v <- lapply(x, cpf_dig_controle)
    result <- sapply(seq_along(x), function(i) g(x[i], v[[i]]))
    result
}

cpf_validar <- function(x){
    f <- function(y){
        z <- unlist(strsplit(y, "\\."))
        v <- substr(z[3], 3, 6)
        v <- as.integer(unlist(strsplit(v, "-")))
        z[3] <- substr(z[3], 1, 2)
        z <- as.integer(paste(z, collapse = ""))
        list(x = z, v = v)
    }
    result <- lapply(x, f)
    valido <- lapply(result, function(r) unlist(lapply(r$x, cpf_dig_controle)))
    valido <- sapply(seq_along(valido), function(i)
                    result[[i]]$v[1] == valido[[i]][1] & result[[i]]$v[2] == valido[[i]][2]
                )
    valido
}

cpf <- cpf_gerar(c(12345678, 87654321))
cpf
#[1] "123.456.786-02" "876.543.210-07"

cpf_validar(cpf)
#[1] TRUE TRUE

cpf_validar(c("123.456.786-02", "876.543.211-07"))
#[1]  TRUE FALSE


text:
Q: What is the meaning of the semicolon in $f(x;\Theta)$? In section 6.2, in the second paragraph of p. 335 (image below) of "Probability and statistical inference 7e" by Hogg and Tanis states:

perhaps it is known that $f(x;\Theta)=(1/\Theta)e^{x/\Theta}$

where $x$ is data and $\Theta$ is a parameter.
What does "$;$" mean in this context, as opposed to "$,$" or "$|$", all three are used in different ways in the same textbook ("," and ";" are used on the same page, $|$ in the standard statement of Bayes' Theorem)?
I think I understand "$,$" and "$|$" and I read $f(x,\Theta)$ as "function of data and parameters" and $f(x|\Theta)$ as "function of the data given parameters".
Here is a scan of the page for more context:


text:
Q: Angular2 Router URL breaks at & After I updated to the latest angular v4.3.2 all my urls break at & value, for example I have an route /:value that I want to get the value from:

http://localhost:4200/one&two

but it redirects me to:

http://localhost:4200/one

And since the value from the url is dynamic, many can have & I cannot display the correct result.
Using an CustomUrlSerializer I managed to replace %26 to be & and navigating thru the router inside the app works but still at initial page load the url gets splitted:
import { UrlSerializer, UrlTree, DefaultUrlSerializer } from '@angular/router';

export class CustomUrlSerializer implements UrlSerializer {

  parse(url: any): UrlTree {
    const dus = new DefaultUrlSerializer();
    return dus.parse(url);
  }

  serialize(tree: UrlTree): any {
    const dus = new DefaultUrlSerializer();
    const path = dus.serialize(tree);
    return path.replace(/%26/g, '&').replace(/%2B/g, '+');
  }

}

Is there any solution to disable url breaking at & ?

A: Ok so I know that & is used as a special character inside router but if you need to get that value and not split it:
Edit: node_modules/@angular/router/@angular/router.es5.js
var SEGMENT_RE = /^[^\/()?;=&#]+/;
var QUERY_PARAM_RE =  /^[^=?&#]+/;
var QUERY_PARAM_VALUE_RE = /^[^?&#]+/;

Remove & from that regex and it should work.


text: Q: Looking for a collection of applications of the Open mapping theorem I am looking for various applications of the open mapping theorem (https://en.wikipedia.org/wiki/Open_mapping_theorem_(functional_analysis) )  other than only the closed graph theorem and that if two comparable norms make a space Banach then they are equivalent . Any Journal or Book reference or any links are highly appreciated . Please help . Thanks in advance


text:
Q: Hiding page loader only after completion of data load in the page view Currently am working with angularjs.
now i have an ng-click function,it is called when checkbox is checked or unchecked. i have a full page loader and when i click on the check box it will be displayed. It will be hidden only after loading the complete view. I tried this code and it is not working
here comes the click
<input type="checkbox"id="myId" ng-click="sampleClick(1)">

here is the js code
$scope.sampleClick = function(type) {

        var param       = new Object();
        param.type      = type;

        //side bar listing
        Data.post('url/testurl', param).then(function(data){
            $scope.all          = '';
            $scope.all          = angular.fromJson(data);

            console.log("Contents is trying to load.");
            $scope.$on('$viewContentLoaded',function(event, viewConfig){
                console.log("Contents did load.");
                $rootScope.setVariable = 1;
            });

        }, function (error) {
            $rootScope.setVariable = 1;
        });

    }

I want to set the $rootScope.setVariable = 1 only when the view section is completely loaded.(and each time when I click on the check box)
Note : when I use $viewContentLoaded at the time of page load, it works without any issue. But when I use the same along with the ng-click function, i don't get any response.

A: If the view is rendered using ng-repeat, why can't you use ng-repeat directive to handle the end of render and then initiate a function call.
for example
<div ng-repeat="i in things" repeat-done>
// here you use i to render your filter with checkbox
</div>

and directive will look like
app.directive('repeatDone', function($rootScope) {
  return function(scope, element, attrs) {
    if (scope.$last){
        //set your variables or do you job
    }
  };
})

A: You can set one flag you can set it value true/false.

for example(I am taking your example so you can understand it batter):-

$scope.loading = false;
$scope.sampleClick = function(type) {

        var param       = new Object();
        param.type      = type;

        //side bar listing
        Data.post('url/testurl', param).then(function(data){
            $scope.all          = '';
            $scope.all          = angular.fromJson(data);

            console.log("Contents is trying to load.");
              $scope.loading = true;
            $scope.$on('$viewContentLoaded',function(event, viewConfig){
              $scope.loading = false;
                console.log("Contents did load.");
                $rootScope.setVariable = 1;
            });

        }, function (error) {
            $rootScope.setVariable = 1;
        });

    }

here i have take $scope.loading variable which default value is false, when you click on checkbox then it will be set to true so at that time you can show the loader and when it get the data it will be set to false so it will stops loading.
I hope you understand.


text:
Q: How to use scheduleAtFixedRate for executing in each second in the below code send() function is executing many times in a second,i want to execute send() once in a second,how i change the code
timer.scheduleAtFixedRate(
            new TimerTask() {
                public void run() {
                    try {
                        send();

                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            },
            1000,
            1000);

send function is given below
void send() throws Exception, IOException
{
    s=new Socket("10.0.2.2",4200);
    r=new PrintWriter(s.getOutputStream());
    while(true)
    {
        Log.e("msg","hi send\n");
        r.print("hai");
    }
}

Logcat output is given below

A: I replaced timers with Runnables/Handlers recently, it's much easier
//declare at top of your activity
private Handler h = new Handler();

private Runnable myRunnable = new Runnable() {
   public void run() {
    //do stuff

        //run again in one second
    h.postDelayed(myRunnable, 1000);
   }
};

//trigger the runnable somewhere in your code e.g. onClickHander or onCreate etc
h.postDelayed(myRunnable, 1000);

A: It happened for me when I used a TaskTimer and the phone got into sleep mode. I think it is related to TimerTask using Thread.sleep() to provide the timing. This relies on uptimeMillis() which according to documentation -  'is counted in milliseconds since the system was booted. This clock stops when the system enters deep sleep (CPU off, display dark, device waiting for external input), but is not affected by clock scaling, idle, or other power saving mechanisms. This is the basis for most interval timing such as Thread.sleep(millls)'
Solution would be either to use AlarmManager or WakeLocks.

A: an easier approach would look like this:
new Thread() {
  public void run() {
     while(true) {
       send();
       try{
         Thread.sleep(1000); // pauses for 1 second
       catch(Exception e) {}
     }
  }
}.start();


text:
Q: Problem with python in Ubuntu 18.10 I recently upgraded to 18.10 from 18.04, but I am facing  a new problem.
When I type python, I am getting this

Python 3.7.3 (default, Apr  9 2019, 04:56:51)
[GCC 8.3.0] on linux

But when I type python3, I am getting an error

bash: /usr/lib/command-not-found: /usr/bin/python3: bad interpreter: No such file or directory

I couldnt opem ny terminal so I changed the very first line of /usr/bin/gnome-terminal  to:
!#usr/bin/python from #!usr/bin/python3 since then I am able to open my terminal.
Upon entering sudo apt-get update I am getting this error
sh: 1: /usr/lib/cnf-update-db: not found
Reading package lists... Done
E: Problem executing scripts APT::Update::Post-Invoke-Success 'if /usr/bin/test -w /var/lib/command-not-found/ -a -e /usr/lib/cnf-update-db; then /usr/lib/cnf-update-db > /dev/null; fi'
E: Sub-process returned an error code

No matter whether I enter

pip

or

pip3

I am getting this error
bash: /usr/local/bin/pip: /usr/bin/python3: bad interpreter: No such file or directory

I tried sudo update-alternatives --config python3
I got There is only one alternative in link group python3 (providing /usr/bin/python3.6): /usr/bin/python3.7
Nothing to configure.
But when I type sudo update-alternatives --config python I am getting
There are 2 choices for the alternative python (providing /usr/bin/python).

Selection    Path                Priority   Status
------------------------------------------------------------
0            /usr/bin/python3.6   2         auto mode
* 1            /usr/bin/python3.6   2         manual mode
2            /usr/bin/python3.7   2         manual mode
The Software&Updates and Software Updater are also not loading when I click on their icon

A: python from your command line must point to python2.7
You might have messed up your apt. Delete your symlink and replace with the default python
sudo rm /usr/bin/python
sudo ln -sf /usr/bin/python2.7 /usr/bin/python
Similarly for Ubuntu 18.10 python3 points to python3.6
sudo rm /usr/bin/python3
sudo ln -sf /usr/bin/python3.6 /usr/bin/python3


text:
Q: A simpler form of $\sin{(\frac{1}{2}\arcsin{x})}$ I've been wondering how to compute $$\sin{(\frac{1}{2}\arcsin{x})}, \quad|x|\le1,$$
I mean how to get rid of the sine and inverse sine function and acquire
$$\frac{-\sqrt{1 - x}}{2} + \frac {\sqrt{1 + x}}{2},$$ which is the answer Wolfram Alpha provides.
My idea would be to substitute $\frac{1}{2}\arcsin{x}=t$, hence $x=\sin{2t}$ and my goal is to express $\sin{(\frac{1}{2}\arcsin{x})}=\sin{t}$ in terms of $x$.
$$x=\sin{2t}=2\sin{t}\cos{t}, \quad ?=\sin{t}$$
Substituting from $\sin^2{x}+\cos^2{x}=1$ takes me nowhere, could you help?

A: By the half-angle formula,
$$|\sin(\theta/2)|=\sqrt{\frac{1-\cos(\theta)}2}$$
And by the Pythagorean theorem, assuming $\cos(\theta)\ge0$
$$\sqrt{\frac{1-\cos(\theta)}2}=\sqrt{\frac{1-\sqrt{1-\sin^2(\theta)}}2}$$
Now let $\sin(\theta)=x$ to finally get
$$|\sin(\arcsin(x)/2)|=\sqrt{\frac{1-\sqrt{1-x^2}}2}$$
This is a standard nested radical and decomposes into

$$\sin(\arcsin(x)/2)=\frac{\sqrt{1+x}-\sqrt{1-x}}2$$

Assuming $|x|\le1$.  (note the denesting process nicely came out to letting us drop the absolute value bars $\ddot\smile$)

A: Let $s=\sin\left(\frac12\arcsin x\right)$ and let $c=\cos\left(\frac12\arcsin x\right)$. Then $c^2+s^2=1$ and $2sc=\sin(\arcsin x)=x$. Solving the system$$\left\{\begin{array}{ll}c^2+s^2=1\\2sc=x,\end{array}\right.$$you get that $\displaystyle s=\frac{\sqrt{1-\sqrt{1-x^2}}}{\sqrt2}=\frac{\sqrt{1+x}-\sqrt{1-x}}2$.

A: Let $\arcsin x=y\implies-\dfrac\pi2\le y\le\dfrac\pi2,\sin y=x$
$\implies\cos\dfrac y2\ge0$ and $\cos y=+\sqrt{1-x^2}$
Now as $\cos y=1-2\sin^2\dfrac y2$
$\implies\sin\dfrac y2=\sqrt{\dfrac{1-\cos y}2}$ if $y\ge0$
else $\sin\dfrac y2=-\sqrt{\dfrac{1-\cos y}2}$


text:
Q: GitLab CI build multiple dockers + test end-to-end I want to build and test multiple dockers from one repo in GitLab. This monorepo holds a few microservices that work together.
We have have a working docker compose up to aid local dev, so thats a start.
Goal is move build + test to GitLab, run a E2E test (end-to-end) of these dockers, and let GitLab upgrade our staging environment.
The building of multiple dockers is just multiple jobs in build stage of the (one) pipeline, testing can happen per docker i guess, which leaves testing the whole with multiple dockers running in a (or the?) staging environment.

*

*How can GitLab run E2E tests on multiple dockers? (or is this unwise to begin with)

*Would we need Kubernetes for the inter-docker mapping (network, volumes, but also dependencies) that docker-compose now facilitates?
We are using a self-hosted GitLab CE instance.
Update: cut shorter, use proper terminology.

A: I haven't worked on PHP, and never done Docker build for multi module, although I tried out a quick example of multi module kind of thing for Nodejs. Check this Repo
Refer to .gitlab-ci.yml which builds two independent hello world kind of nodejs module.
I now adapted this to build docker images separately.
Original answer (question changed 12th July)
You haven't mentioned what documentation you are referring to. You should be able to configure using .gitlab-ci.yml
AFAIK Building docker image should be programming language agnostic. If you can run docker build . on your local. Following documentation should help
https://docs.gitlab.com/ee/ci/docker/using_docker_build.html
You can use Gitlab pipeline for testing < - > building images. Refer to https://docs.gitlab.com/ee/ci/pipelines.html
Refer to this for PHP build - https://docs.gitlab.com/ee/ci/examples/php.html

A: Answering my own question, 2 years of experience later.

*

*For a normal (single-project/service) repo the CI is straightforward.

*For a monorepo, an end-to-end test is straightforward.

You can combine these aspects by having a repo with submodules, its essentially both. But this can cause overhead if done continiously and mostly usefull for proofing beta/alpha and release-candidates.
If you know more options, feel free to add here.


text:
Q: Selection on Lookup to display name on UI and select RecId ax 2012 I have unbound field on a form. Right now i am showing a look-up on that field using a look-up method which shows All distinct values from a field in a table. Now i changed that name field in table to Recid field. Now i need to display look-up with names but when i select one value i want to show name on U I but i have to select Recid. I don't want recid to display in look-up.  How can i achieve that?
Before i used to get lookup of name  using this method like this
public void lookup()
{
SysTableLookup       sysTableLookup =   SysTableLookup::newParameters(tablenum(RTTable), this);
Query                query = new Query();
QueryBuildDataSource queryBuildDataSource;
;

sysTableLookup.addLookupfield(fieldnum(RTTable, AsstManager));
queryBuildDataSource = query.addDataSource(tablenum(RTTable));
queryBuildDataSource.addSortField(fieldnum(RTTable, AsstManager));
queryBuildDataSource.addRange(fieldNum(RTTable, AsstManager)).value(queryNotValue(''));
queryBuildDataSource.orderMode(ordermode::GroupBy);
sysTableLookup.parmQuery(query);
sysTableLookup.performFormLookup();

super();

}

A: You need .addSelectionField(...), and most likely to remove the super() line.
See these links for some examples:
https://daxbeginners.wordpress.com/tag/lookup-table/
http://dynamicsuser.net/forums/p/56634/303103.aspx
Ah, I forgot also you can specify the return field in the optional second argument of:
sysTableLookup.addLookupfield(fieldnum(RTTable, AsstManager), TRUE);
See second argument at https://msdn.microsoft.com/en-us/library/systablelookup.addlookupfield.aspx

A: You can do it by having a custom lookup form and using the CloseSelect() method on the form. There you can put in the code to return your recId


text:
Q: image load event on IE I am developing a site, and I have to set the src of the not found images, to an error image.
the methods .load() and .error() works always except in IE.
I have been searching, and I have found this:
Issue with IE not calling JQuery .load() function on page refresh - traced to image caching
Adding the query string to the image, always loads it from server, and .load() and .error() methods works properly, however the site is quite too big, and I really can't load all images in site every time from server, without loading it from cache.
Any ideas of how make work this methods, without load from server every time the images for IE, or other way to check if image has been loaded correctly or not that work in IE?
Thanks in advance

A: This is a very old bug that actually was fixed in all modern browsers except IE.
They didn't trigger onload event if image was obtained from cache.
But there is a workaround that is well-known by every person who tried to create an image gallery in javascript a couple of years ago:)
Image DOM element has a property .complete that indicates whether image was loaded or not. You can check this property on script load. If image is in the cache img.complete will return true right after page loaded:
$('img').each(function(){
    //this code will not run in IE if image is in the cache
    $(this).on('load', function(){
       checkImage(this);
    });

    //this code will run if image is already in the cache
    if (this.complete) checkImage(this);
});

function checkImage(){
   //your code for checking image
}

A: Do you have access to the server? A better method may be using .htaccess to rewrite all requests for images to a PHP script, and then if the image is not found, serve the image not found image


text:
Q: Control working directory within a function that is aborted in R I have a function that does a lot of repetitive calculations and at some point, it exports results in a working directory that is created by the function. A scheme of the function looks like this:
fun <- function (..., path){
# 1. create directory specified in the path argument
# 2. set directory from 1. as a working directory via setwd () function
# 3. do calculations
# 4. as 3. proceeds, the function exports results (several lists) in the new working directory
}

Sometimes, it happens that I need to abort the function at the stage 3. (e.g. after the function already created and set the working directory and possibly exported the part of the results to working directory).
Question: Is there a possibility to code a function so if it is aborted manually at stage 3, the function will set the working directory as it was before execution of the function (e.g. system default working directory)?

A: You could use on.exit()
So in the beginning of the code, store the working directory with home_dir <- getwd(), and directly after that call on.exit(setwd(home_dir)). Hope this helps!

Example:
testfun <- function()
{
  home_dir <- getwd()
  on.exit(setwd(home_dir))
  setwd(dirname(getwd()))
}

getwd()

testfun()

getwd()

The both getwd() statements will return the same working directory, because although it is changed in testfun to dirname(getwd()), it is reset by the on.exit() call in testfun.


text:
Q: XMLSerializer not serializing DateTime Input...note that comment is generated code from the xsd tool. It's in a 31,834 line file and proprietary, but I put a rough approximation in here.
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.1432")]
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public class comment
{
   private System.DateTime commentDateField;
   private bool commentDateFieldSpecified;
   [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
   public System.DateTime commentDate
   {
      get
      {
         return this.commentDateField;
      }
      set
      {
         this.commentDateField = value;
      }
   }
   [System.Xml.Serialization.XmlIgnoreAttribute()]
   public bool commentDateSpecified
   {
      get
      {
         return this.commentDateFieldSpecified;
      }
      set
      {
         this.commentDateFieldSpecified = value;
      }
   }
   //other fields omitted for clarity
}
comment c = new comment();
c.text = txtComment.Text;
c.commentDate = DateTime.Now;
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
XmlSerializer xs = new XmlSerializer(typeof(comment));
xs.serialize(sw as TextWriter, c);
string output = sb.ToString();

output->
<comment>
  <text>My Comment Text</text>
</comment>

Where's the date?

A: The following works, you need to show the definition of comment:
public class comment
{
    public string text { get; set; }
    public DateTime commentDate { get; set; }
}

XmlSerializer serializer = new XmlSerializer(typeof(comment));
comment comment = new comment { text = "test", commentDate = DateTime.Now };
using (MemoryStream stream = new MemoryStream())
using (StreamReader reader = new StreamReader(stream))
{
    serializer.Serialize(stream, comment);
    stream.Position = 0;
    Console.WriteLine(reader.ReadToEnd());
}

A: Pavel's comment was the correct answer.

Also, you say "omitted other fields
  for clarity". Is there, by chance, a
  field or property named
  commentDateSpecified among those
  fields?

A: You need to set in order to be included in XML
 c.commentDateSpecified = true;


text:
Q: Out of range value for column 'release_d' at row 2 First time to ask a question. Will do my best to follow the tips:
UPDATE albums
SET release_d = 1800
WHERE release_d < 1980;

or
UPDATE albums
SET release_d = '1800'
WHERE release_d <= '1980';

I receive the error exactly as this:
Out of range value for column 'release_d' at row 2
I just don't see it. Using Sequel Pro, MySQL 5.
Trying to change the year of the release date.
The possible answers found were far too complex for me.
Thanks for the kindness.


text:
Q: Getting unexpected results when refining DOM selection I have this very weird behavior that when I try to get the text of certain div elements, I get all previous "matches" when chaining multiple jQuery functions.
This is my code:
var rows = $("tr");
    var groups = [];
    for (var i = 0;i<rows.length;i++){
        if(rows.eq(i).html().toString().match(/TV/i)){
            groups += rows.eq(i).find(":first-child div").text();
        }
    }
    console.log(groups);

Now the output that I expect is just the text contained in the div that is contained in the first child of the matched table-row.
I do get that result in the console but before that I get the text of all tr's, all matched tr's (.eq(i)), all td's (:first-child is a td), all divs and THEN at the last bit of the output I get the text that is contained in the first div.
So groups is holding all things like I would have done something like this:
groups += rows.eq(i)
groups += rows.eq(i).find(":first-child")
groups += rows.eq(i).find("div")
groups += rows.eq(i).find("div").text();

I'm fairly new to jQuery and only used standard JavaScript selectors where getElementById("myID").getElementsByTagName("div")[0].innerHTML, would give me just the innerHTML of the first div in myID and nothing else.
Why is this happening and how can I get what I'm actually looking for?

A: After exploring your code, I think I finaly found you probleme. IT's hard to tell since we cant see the DOM output.
Anyway, using .find(':first-child div') will get every first-child inside the tr.
Example :
td
-tr <-- Is :first-child (of td)
--div <-- is also :first-child and :first-child div (will get the text of this div)
---div <-- is also :first-child and :first-child div (will get the text of this div)
-tr
--div Is :first-child (of tr)
---div <-- is also :first-child and :first-child div (will get the text of this div)

Try using this instead :
groups.push(rows.eq(i).children(":first-child").find('div').text());

Hope it help (and actually was your problem)!

A: jQuery can cycle for you...
$.each($("tr"), function($index, jsObj)
{
    $jQueryObj = $(jsObj);
    /* ... */
});

alternative usage of .each:
$("tr").each(function($index, jsObj)
{
    /* etc */
});

also I believe there was a functionality like .has(":content('TV')"), but I'm not 100% sure on that at the moment.


text:
Q: Is there anyway to hide menubar items in MacOS? I know I can "auto hide menu bar" in system preferences, however, what I like to do is hide items like this repository.
https://github.com/dwarvesf/hidden
This repository can hide items on right, but I wonder if I can hide left items (which are application menus).
Any idea is appreciated.

A: As for application menus on the left, those can't be hidden, I'm pretty sure.
Applications often have the option to enable or disable their menu bar helper app in the main preferences. If that doesn't help, e.g. if it's a full-fledged menu bar app, not just a helper, then to my knowledge the only solutions are Hidden Bar, which you mentioned, and Bartender.
I'm using the latter, and it does a very fine job. You have four options in Bartender's preferences:

*

*Show (default macOS behavior)

*Hide (menulet will be hidden in a special Bartender secondary menu bar, accessible via the triple-bullet icon ··· on the far right)

*Always show (menulet will be visible in the main macOS menu bar as well as the secondary Bartender menu bar at the same screen position)

*Always hide (menulet will be completely hidden)

Some older menulets seem to switch their position occasionally, e.g. after wake-from-sleep, and Bartender isn't yet able to fix the position of BitBar instances. But for the vast majority of menu bar apps and helpers it will work just fine.


text:
Q: node.js - need help choosing a templating engine valid both client & server side with express I want to code an application with Node.js where templates and rendering code out of json would be the same on client & server side.
I would have like to use jquery templates as there is a port of jquery templates to Node.js through https://github.com/kof/node-jqtpl.
Nevertheless, with this solution, the templates would be shared but not the rendering code.
Is there a templating solution where the template & rendering code would be the same ?
Thank you for your help
Jerome Wagner

A: https://github.com/janl/mustache.js/
Can be used on both server side and browser. Mustache is pretty awesome itself, never used it with Node.js per say, but had a go at it with Go, and it was nice.
Give it a try.

A: try ICanHaz.
It's really really beautiful and easy to use. you can find an introduction here.


text:
Q: logging how to control the times in which flush to log file I've to use logging module and wonder if there is a way to log into existing log file , by appending my data to the existing file and more important if I can control the times I flush into the file.
Currently I need to be able to flush all the time to the file because, there are cases in which the script running the logic with the logging can crash, so I need to know exactly where my program stopped.
Any ideas and code examples?
Thanks

A: If you use logging.FileHandler and choose an existing log file, by default it will append to that file.  The method that actually writes the log record is the emit() method on logging handlers.  If you look at the source code for the FileHandler, it flush's after every write, so it should be doing what you want by default.
import logging

log = logging.getLogger()
handler = logging.FileHandler('/path/to/log.txt')
log.addHandler(handler)

log.warning('This is a message')


text:
Q: Cannot import and export classes I am making a webpage with glitch.com, but this error keeps appearing:
Uncaught SyntaxError: Unexpected token {

This is the code from where the error appears:
import {Unit} from "./Unit.js";

This is how I export Unit: (Unit is a class)
export {Unit};

There aren't any errors in the Unit file.
EDIT: Just for reference, when I go to "Inspect" and then "Sources" I don't see the Unit file, could this be the reason?

A: You don't need curly brackets around the exported class
    export default Unit;
You shouldn't need them either in the import statement if Unit is the only class you're exporting in Unit.js
import Unit from '/Unit.js';


text: Q: Does Android support TLS compression? I'm trying to find a way for my app to use compression as per RFC 3749, but I don't find any options for enabling/specifying compression in Android's javax.net.ssl package.  I do see that OpenSSL, used by javax.net.ssl, supports DEFLATE compression.  Are there any open source libraries/implementations that allow this feature in Android?