text:
Q: ActionListener and ActionEvent issue I'm having a technical issue with my ActionListener. You see, I have one button that has several Actions possible, depending on which MenuItem was clicked before. So I created an ActionListener with an ActionEvent e. "e" is supposed to verify one of 3 conditions (because I have 3 MenuItems - Add, Delete, and Modify) and depending on which one is chosen, the actions that happen are different from one each other.
The problem is that neither of the e.getSource() conditions never get verified (even though I've checked several times that they were)
 private void buttonValidateActionPerformed(java.awt.event.ActionEvent evt){
    // TODO add your handling code here:
  ActionListener l = (ActionEvent e) -> {
     if(e.getSource()==menuItemAdd)
     {
         System.out.println("eureka!");
         buttonResearch.setEnabled(false);
      if (evt.getSource()== buttonValidate)
        {

        DataTransac dt = new DataTransac();
        dt.ajouterProgrammeurs("...");

        }
     }
     if(e.getSource()==itemDelete)
     {
         if(evt.getSource()== buttonValidate)
         {

        DataTransac dt = new DataTransac();
        dt.deleteProgrammers("...");

         }
     }
     if(e.getSource()==itemModify)
     {
         if(evt.getSource()==buttonValidate)
         {

        DataTransac dt = new DataTransac();
       dt.modifyProgrammeurs("...");

         }
     }

  };

  menuItemAdd.addActionListener(l);
  itemDelete.addActionListener(l);
  itemModify.addActionListener(l);

  /*

   */

}

I tried the ".equals()" method, however it did not work as well.
ActionListener l = (ActionEvent e) -> {
     if(e.equals(menuItemAjouter))
     {
         System.out.println("eureka!");
         buttonResearch.setEnabled(false);
      if (evt.getSource()== buttonValidate)
        {

        DataTransac dt = new DataTransac();

        dt.addProgrammers("...");

        }
        ...

After testing the hashing method, I've stumbled accidentally on a weird bug. At first when I click on the "Add" MenuItem then the "Validate" button, nothing happens. However, if I click on the "Validate" button then the "Add MenuItem, the code works... I'm going to try different conditions.

A:
I have one button that has several Actions possible, depending on which MenuItem was clicked before.

The source of an ActionEvent fired in response to a button click is the button that was clicked.  You cannot use that to inquire about controls with which the user previously interacted. At least, not directly.
The control flow in your GUI is not entirely clear to me, but your alternatives come in several categories:

*

*Use different buttons instead of making the same one responsible for diverse actions.

*If you want to continue with setting some kind of mode via your menu items, then store the current mode in some shared variable accessible to the button's event handler, and have it use that instead of the action source.

*Or perhaps have your menu items alter which of several for-purpose ActionListeners is installed on the button, so that the choice of effect can be driven by the listener invoked.

Either of the first two is much preferable to the last, which I offer mainly for completeness.

A: That's a very confusing question.
I am going to start by saying that using getSource is usually a bad idea. It couples that action to the component - exactly the problem listeners were introduced to get away from. It's like going back to JDK 1.00 and nobody wants that, only now we've added additional complication. Also Swing tends to use composite components (it's the Composite design pattern).
Let's look at your code.
private void buttonValidateActionPerformed(java.awt.event.ActionEvent evt){
    // TODO add your handling code here:
  ActionListener l = (ActionEvent e) -> {
What is going on here. Would the real action listener please stand up. Put some printfs in (or use a debugger) to make sure the control flow is as expected.
 if(e.getSource()==menuItemAdd)
 {
     System.out.println("eureka!");
     buttonResearch.setEnabled(false);
  if (evt.getSource()== buttonValidate)

I assume somewhere you have also written.
buttonValidate = menuItemAdd;
It's worth checking in your listener that you have everything set up correctly. Try a few printfs at the top.
System.err.println("e.getSource(): "+System.identityHashCode(e.getSource());
System.err.println("buttonValidate: "+System.identityHashCode(buttonValidate));
System.err.println("menuItemAdd: "+System.identityHashCode(menuItemAdd));
System.err.println("itemDelete: "+System.identityHashCode(itemDelete));
System.err.println("itemModify: "+System.identityHashCode(itemModify));

If you've messed up some assignment somewhere this should show up as unexpected object hash codes.
I suggest backing the code out and adding one action listener per action. You shouldn't need these if statements all over the place. Within each listener they may then check state if necessary.


text:
Q: Remove permissions on list item change in sharepoint Is there any chance I can remove survey permissions on List item change?
Can i somehow set workflow on list item change to remove survey permissions?

A: What are you actually trying to accomplish (i.e. the reason behind changing the permissions)?  detailing the actual "requirement" will net you a better answer. But I will give you some possible routes that may solve different problems.
OOTB with SP Designer the answer is no.
If you all you want to do is limit the number of times a survey can be submitted than that can be set in the survey itself.
You could use Visual Studio can create a new action that does that or code a workflow directly in VS to accomplish this, because it requires the use of the API.
Additionally you could use InfoPath web forms (if you have enterprise edition CALs) and create your own survey.  You can use a combination of tracking columns and forms to show / hide the information you want. If you don't have InfoPath Webforms available, you can still achieve similar results with custom list pages and JavaScript, but it is a bit more work.
I'm assuming as well that all your users are authenticated and not anonymous. You have to make some farm level changes to allow Anon. users access to submit InfoPath forms.

redpajama_set_name: RedPajamaStackExchange


text:
Q: "shell" or "shell-scripting"? In reference to the accepted answer on Where questions about linux shell commands go?,
questions about Linux shell scripting should be asked on Stack Overflow and general questions about Linux shell should be asked on Super User.
If questions are asked on Stack Overflow, they will be about scripting, so are shell and shell-scripting redundant?
Tags:
shell 2330
shell-scripting 1122
shell && shell-scripting 264

A: I'm of the camp where the language is called "shell" (well, actually "Bourne shell", "c-shell", "bash"...) but the language group is "shell").
We write [c] and not [c-programming], so we should write [bash] or [shell] and not [bash-scripting] or [shell-scripting].


text: Q: IBM ODM Rules - JUnit Excel Scenario File Testing I am new to IBM ODM. We are planning to test the excel sheet scenarios using JUnit from Rule Designer(DVS Testing with JUnit).Am using ODM Version 8.8. I would like to know the advantages of this approach. We are already trying the test scenarios from Decision Center UI.Any help is appreciated.I also tried the sample project through Sample Console.Thank you.


text:
Q: Change the font color and size of UISegment Control I want to change the font color and font size of uisegment control. is is possible ?
if any one has do this and any one has solution please tell me or share any helpful link
Thanks.

A: As some other answers mention, you can also use setTitleTextAttributes:forState:
UIFont *font = [UIFont boldSystemFontOfSize:12.0f];
NSDictionary *attributes = [NSDictionary dictionaryWithObject:font
                                                       forKey:UITextAttributeFont];
[segmentedControl setTitleTextAttributes:attributes
                                forState:UIControlStateNormal];

A: better use image for the same
- (void)insertSegmentWithImage:(UIImage *)image  atIndex:(NSUInteger)segment animated:(BOOL)animated;

A: Check This
NSArray *ary=[sgmntControl subviews];
NSInteger intCount=0;
for (id seg in ary)
for (id label in [seg subviews])
if ([label isKindOfClass:[UILabel class]])
{
    if(intCount==1)
    {
        [label setTextColor:[UIColor blackColor]];
        [label setShadowColor:[UIColor whiteColor]];
    }
    else {
        [label setTextColor:[UIColor whiteColor]];
        [label setShadowColor:[UIColor blackColor]];
    }
    [label setFont:[UIFont boldSystemFontOfSize:16]];
    [label setShadowOffset:CGSizeMake(0,1)];

}

Thanks


text:
Q: send sms periodically in Android I have to send sms periodically through my android application to a certain group of people (friends). The messages to be sent will be stored in a database in the application only.
I have seen following threads:
How to send sms programmatically?
Show compose SMS view in Android

A: Use a Service:
import java.util.Timer;
import java.util.TimerTask;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.IBinder;
import android.os.Message;
import android.widget.Toast;

public class SrvSMSSender extends Service {

    Timer timerSendSMS = new Timer();

    class taskSendSMS extends TimerTask {
        @Override
        public void run() {
            hSendSMS.sendEmptyMessage(0);
        }
    };

    final Handler hSendSMS = new Handler(new Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            procSendSMS();
            return false;
        }
    });

    public void procSendSMS() {
        try {
            // send your SMS here

        } catch (Exception e) {

        }
    }

    @Override
    public void onCreate() {
        super.onCreate();

    };

    @Override
    public void onStart(Intent intent, int startId) {
        try {
            long intervalSendSMS = 10*60*1000;

            timerSendSMS = new Timer();

            timerSendSMS.schedule(new taskSendSMS(), 0, intervalSendSMS);

        } catch (NumberFormatException e) {
            Toast.makeText(this, "error running service: " + e.getMessage(),
                    Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(this, "error running service: " + e.getMessage(),
                    Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onDestroy() {

        timerSendSMS.cancel();
        timerSendSMS.purge();

    }
}


text:
Q: How to submit form using href with javascript? How to submit form using href with javascript ?
i try this code but not work, How can i do that ? thank you.

<form id="fid" method="post" action="main.php" ENCTYPE = "multipart/form-data" style=" display: none; ">
    <input type="text" name="test" value="1"/>
</form>

Windows

A: Javascript is case sensitive.
Do this instead:
Windows

A: For a link in body: Windows

A: You should actually avoid using inline JS entirely, if ever possible. We can give your anchor element an ID:
<form id="fid" method="post" action="main.php" ENCTYPE="multipart/form-data" style="display: none;">
    <input type="text" name="test" value="1"/>
</form>
Windows

...and attach a click event handler to it, using jQuery (make sure you have the library loaded):
$(function() {
    $('#form-submit').click(function(e) {
        // Prevent default link behavior
        e.preventDefault();

        // Submit form
        $('#fid').submit();
    });
});

Otherwise, there is always native JS that you can work with:
var btn = document.getElementById("form-submit");
btn.addEventListener('click', function() {
    document.fid.submit();
} , false);


text:
Q: How to convert a 'Featureset' object to Python DataFrame My api query returned a table. I tried to convert it to df. However, it produced AttributeError saying 'Featureset' object has no attribute. Here is the information about the API. Below are the query codes.
import wbgapi as wb
wb.source.info()

A: The problem is solved by converting the 'Featureset' object into a dictionary then extract data from the dictionary.
import wbgapi as wb
import pandas as pd

table = wb.source.info()
table_dict = vars(table)

df_source = pd.DataFrame(table_dict.get('items'))


text:
Q: How to get the AddRowTable values I am using jQuery to add the values in the table Using AddrowPlugin. I need to get the dynamic values of Row1, Row2, Row3, etc.
My Code
Enter code here

Your Name
        Your Age

            <input type="text" id="one" size="25"/>

        <input type="text" "two" size="25"/>

        <input type="button" value="Delete" class="delRow"/>

            <input type="button" class="addComment" value="submit"/>

Here I get a dynamic column of "one" inputfield and "two" input field  submit. How do I extract the "one" value & "two" for all dynamic rows?

A: $(".addComment").btnAddRow({inputBoxAutoNumber:true}, function(row){
    if(row)
        var t = $("input[name=one1]").val();
    var t2 = $("input[name=one2]").val();

    // Retrieves the one field as I set the default inputBoxAutoNumber:
    //   true, it keeps on increments as it adds.
});


text:
Q: Write response of a request into json file several times during execution with python I have an application that makes GET requests to an API to get data every given seconds. What I want to do is to write every response I get into a single (ideally json) file to process that data so I can then send a json POST request to a different API. I have the following function that when called by a scheduler only writes the first response and not a single more. How can I achieve a way to write all the responses into a single file for later use.
def send_request():
    url = "API URL"

    try:
        # sending get request and saving the response as response object
        r = requests.get(url = url)

    except (requests.Timeout, requests.ConnectionError, requests.HTTPError) as err:
        print("Error while trying to GET data")
        print(err)

    print(r.content)

    data = json.loads(r.content)

    #Json file writer
    with open('data.json', 'w') as outfile:
        json.dump(data, outfile,indent=4, sort_keys=True)
        outfile.flush()

The scheduler looks something like this:
from apscheduler.schedulers.blocking import BlockingScheduler as scheduler

if __name__ == '__main__':
    sched = scheduler()
    print(time.time())
    sched.add_job(send_request, 'interval', seconds=60)
    sched.start()

I am aware that this scheduler may be overkill for the task but it is okay if it isn't the part causing the issue.

A: It seems that you see only the last response in your file as you rewrite it every time.
You should append to your file and not rewrite it:
#Json file writer
with open('data.json', 'a') as outfile:
    json.dump(data, outfile, indent=4, sort_keys=True)
    outfile.flush()

Note the a parameter in open('data.json', 'a') which stands for "append"


text:
Q: How to filter different parameter using If Else (Python) I have different parameter and condition to be filter before executing a function.
For example: An email subject must contain Emergency and does not contain hehe. In the meantime, the text of the same email must contain alert and do not contain haha to execute a function.

Currently I'm just using a hard-coded if else to filter the request, but it can only process a single rules. What I want to achieve is all the rules will be parse before executing a function.
My Py script (This script is just checking if the Email subject have "Consent" in it)
import datetime
import email
import imaplib
import mailbox
import smtplib

while True:
    EMAIL_ACCOUNT = "xxx@gmail.com"
    PASSWORD = "xxx"

    mail = imaplib.IMAP4_SSL('imap.gmail.com')
    mail.login(EMAIL_ACCOUNT, PASSWORD)
    mail.list()
    mail.select('inbox')
    result, data = mail.uid('search', None, "UNSEEN")  # (ALL/UNSEEN)
    i = len(data[0].split())

    for x in range(i):
        latest_email_uid = data[0].split()[x]
        result, email_data = mail.uid('fetch', latest_email_uid, '(RFC822)')
        # result, email_data = conn.store(num,'-FLAGS','\\Seen')
        # this might work to set flag to seen, if it doesn't already
        raw_email = email_data[0][1]
        raw_email_string = raw_email.decode('utf-8')
        email_message = email.message_from_string(raw_email_string)

        # Header Details
        date_tuple = email.utils.parsedate_tz(email_message['Date'])
        if date_tuple:
            local_date = datetime.datetime.fromtimestamp(email.utils.mktime_tz(date_tuple))
            local_message_date = "%s" % (str(local_date.strftime("%a, %d %b %Y %H:%M:%S")))
        email_from = str(email.header.make_header(email.header.decode_header(email_message['From'])))
        email_to = str(email.header.make_header(email.header.decode_header(email_message['To'])))
        subject = str(email.header.make_header(email.header.decode_header(email_message['Subject'])))

        # Body details
        for part in email_message.walk():

            if part.get_content_type() == "text/plain":
                body = part.get_payload(decode=True)
                print("From:", email_from)

                print("Email To:", email_to)
                print("date:", local_message_date)
                print("Subject:", subject)
                print("body:", body.decode('utf-8'))

                '''If subject have "Consent" it will send specific email to recipient'''
                if "Consent" in subject:
                    server = smtplib.SMTP('smtp.gmail.com', 587)
                    server.starttls()
                    server.login(EMAIL_ACCOUNT, PASSWORD)

                    msg = "ALERT NOTICE!"
                    server.sendmail(EMAIL_ACCOUNT, "xxx@gmail.com", msg)
                    server.quit()
                else:
                    print("no email");

            else:
                continue

A: Solution 1: Doing checks on the same line
if ("Emergency" in subject) and ("Alert" in email_message):
   ***your logic goes here***

Solution 2: Using Modularized checks
def subject_check(subject):
   if "Emergency" in subject:
       ***logic**
   elif <some_check> :
       ***logic***
   else:
       ***logic***

Create separate functions for other checks, so that you can reuse the check logic somewhere else too.


text:
Q: android backup agent and SherlockMapActivity I try to implement a Backup Agent in my Android app, and I've got a weird issue every times it restore (at first launch) :
Unable to resolve superclass of Lcom/actionbarsherlock/app/SherlockMapActivity; (916)
Link of class 'Lcom/actionbarsherlock/app/SherlockMapActivity;' failed
Unable to resolve superclass of Lnet/myapp/activity/impl/MapActivity; (674)
Link of class 'Lnet/myapp/activity/impl/MapActivity;' failed
Could not find class 'net.myapp.activity.impl.MapActivity', referenced from method net.myapp.helper.SlidingMenuHelper.<clinit>

VFY: unable to resolve const-class 1520 (Lnet/myapp/activity/impl/MapActivity;) in Lnet/myapp/helper/SlidingMenuHelper;
VFY: replacing opcode 0x1c at 0x0081
     Exception Ljava/lang/NoClassDefFoundError; thrown while initializing Lnet/myapp/helper/SlidingMenuHelper;

Complete log here : https://gist.github.com/romainguefveneu/1acc78cabbed65fba4b7
The restore process works just fine, when I open a second time the app, my data are correctly restored.
It seems to be an issue with the loading of SherlockMapActivity, I use all those libs in my project :

*

*actionbarsherlock-plugin-maps-4.2.0.jar

*bugsense-3.0.1.jar

*commons-io-2.0.1.jar

*gson-2.2.2.jar

*joda-time-2.1.jar

*ocpsoft-pretty-time-1.0.7.jar

Does someone has an idea ?


text:
Q: How to find the best-fit transformation between two sets of 3D observations Let us assume that I have two sets of observations, A and B. Each of them is a list of 3D points. They describe the same set of world 3D points at the same order.  However, they are given in different coordiante systems (so that they might be different in rotation, translation and scale), and they also contain noise so there's no "perfect" fit between them. What would be the best way to find a transformation between them such that the transformed version of B would minimize the least-squares difference from A?

A: Long answer short: Let $A =(a_1, a_2, \ldots, a_n)$ and $B=(b_1, b_2, \ldots, b_n)$. Define the centroids
$$\overline{a}=\frac{1}{n}\sum_{k=1}^na_k$$
$$\overline{b}=\frac{1}{n}\sum_{k=1}^nb_k$$
and matrices (where each $a_k$ and $b_k$ is considered a column vector)
$$P=\left(\frac{1}{n}\sum_{k=1}^nb_k\,b_k^t\right)-\overline{b}\,\overline{b}^t$$
$$Q=\left(\frac{1}{n}\sum_{k=1}^na_k\,b_k^t\right)-\overline{a}\,\overline{b}^t$$
Then the map with a least squares fit is
$$b\mapsto QP^{-1}(b-\overline{b}) + \overline{a}.$$


text:
Q: Error: Could not find or load main class src.klase.Main Eclipse SVN I downloaded a project from SVN onto my laptop and, when I try to run it, it says
 Error: Could not find or load main class src.klase.Main .

I tried Project>Cleanup, restarting, everything I could think of.
My .classpath file is:
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
    <classpathentry kind="src" path="src"/>
    <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/jre1.8.0_65"/>
    <classpathentry kind="output" path="bin"/>
</classpath>

There are no problem with the classes, I created a new project, added them in it and it run successfully.
Any help would be great, thanks.


text:
Q: changing display size of android app My developed Android app works well on my phone, and I have used linear layout, and set the pixel as dp.
However, there is a setting in my phone, which can change the screen display size, I set it to large, and some of my layout is outside of the screen.
I tried to look up at the official document, but I found that it said usually setting change won't affect.
How can I resolve it?

A: You can create dimension xml file for different screen density pixels. Refer this link for more details
How to define dimens.xml for every different screen size in android?


text:
Q: Getting "Error" while trying to connect Ionic App with Mobile first server 7.1 version I am New to Ionic + Mobile first.I have developed my Ionic App. In there i have to connect my App with mobile first server 7.1 version.
While connecting the server using "WL.Client.connect()" Method, i am not getting any alert either "success or fail" in the method callback.
 WL.Client.connect({
       onSuccess: successCallback,
       onFailure: failureCallback
   });
   function  successCallback()
   {
       alert("success");
   }

   function  failureCallback()
   {
       alert("fail");
   }

My sample,
https://github.com/Smohanapriya/Ionic-with-Mobile-first-7.1-version/blob/master/www/js/app.js
Everyone help will be Appreciated!!!

A: WLAuthorizationManager is v8.0 beta API.
If you use 7.1, use WL.client.connect().
Please, you are asking very basic questions.
You need to read the tutorials. It does not matter if you develop a Hybrid or Cordova or Ionic or with Studio or CLI. You need to learn the basics, from there it is all the same.
https://mobilefirstplatform.ibmcloud.com/tutorials/en/foundation/7.1/hello-world/connecting-to-mobilefirst-server/


text:
Q: Changing the contents of a text file and making a new file with same format I have a big text file with a lot of parts. Every part has 4 lines and next part starts immediately after the last part.
The first line of each part starts with @, the 2nd line is a sequence of characters, the 3rd line is a + and the 4th line is again a sequence of characters.
Small example:
@M00872:462:000000000-D47VR:1:1101:15294:1338 1:N:0:ACATCG
TGCTCGGTGTATGTAAACTTCCGACTTCAACTGTATAGGGATCCAATTTTGACAAAATATTAACGCTTATCGATAAAATTTTGAATTTTGTAACTTGTTTTTGTAATTCTTTAGTTTGTATGTCTGTTGCTATTATGTCTACTATTCTTTCCCCTGCACTGTACCCCCCAATCCCCCCTTTTCTTTTAAAAGTTAACCGATACCGTCGAGATCCGTTCACTAATCGAACGGATCTGTCTCTGTCTCTCTC
+
BAABBADBBBFFGGGGGGGGGGGGGGGHHGHHGH55FB3A3GGH3ADG5FAAFEGHHFFEFHD5AEG1EF511F1?GFH3@BFADGD55F?@GFHFGGFCGG/GHGHHHHHHHDBG4E?FB?BGHHHHHHHHHHHHHHHHHFHHHHHHHHHGHGHGHHHHHFHHHHHGGGGHHHHGGGGHHHHHHHGHGHHHHHHFGHCFGGGHGGGGGGGGFGGEGBFGGGGGGGGGFGGGGFFB9/BFFFFFFFFFF/

I want to change the 2nd and the 4th line of each part and make a new file with similar structure (4 lines for each part). In fact I want to keep the 1st 65 characters (in lines 2 and 4) and remove the rest of characters. The expected output for the small example would look like this:
@M00872:462:000000000-D47VR:1:1101:15294:1338 1:N:0:ACATCG
TGCTCGGTGTATGTAAACTTCCGACTTCAACTGTATAGGGATCCAATTTTGACAAAATATTAACG
+
BAABBADBBBFFGGGGGGGGGGGGGGGHHGHHGH55FB3A3GGH3ADG5FAAFEGHHFFEFHD5A

I wrote the following code:
infile = open("file.fastq", "r")
new_line=[]
for line_number in len(infile.readlines()):
    if line_number ==2 or line_number ==4:
        new_line.append(infile[line_number])

with open('out_file.fastq', 'w') as f:
    for item in new_line:
        f.write("%s\n" % item)

but it does not return what I want. How to fix it to get the expected output?

A: This code will achieve what you want -
from itertools import islice
with open('bio.txt', 'r') as infile:
    while True:
        lines_gen = list(islice(infile, 4))
        if not lines_gen:
            break
        a,b,c,d = lines_gen
        b = b[0:65]+'\n'
        d = d[0:65]+'\n'
        with open('mod_bio.txt', 'a+') as f:
            f.write(a+b+c+d)

How it works?
We first make a generator that gives 4 lines at a time as you mention.
Then we open the lines into individual lines a,b,c,d and perform string slicing. Eventually we join that string and write it to a new file.

A: I think some itertools.cycle could be nice here:
import itertools

with open("transformed.file.fastq", "w+") as output_file:
    with open("file.fastq", "r") as input_file:
        for i in itertools.cycle((1,2,3,4)):
            line = input_file.readline().strip()
            if not line:
                break
            if i in (2,4):
                line = line[:65]
            output_file.write("{}\n".format(line))

A: readlines() will return list of each line in your file. You don't need to prepare a list new_line. Directly iterate over index-value pair of list, then you can modify all the values in your desired position.
By modifying your code, try this
infile = open("file.fastq", "r")
new_lines = infile.readlines()
for i, t in enumerate(new_lines):
    if i == 1 or i == 3:
        new_lines[i] = new_lines[i][:65]

with open('out_file.fastq', 'w') as f:
    for item in new_lines:
        f.write("%s" % item)


text:
Q: Find Middle Object in Nested Has Many I have setup an association where my entities are defined such that
Project has many Teams, Team has many Users
I have a project object and I need to find which team a user belongs to. So if I were in the console, I would like to be able to do this:
project = Project.find(5)
project.team_id_for_user_id(7)

Is there a simple rails way to do this or do I need to iterate through the project teams and then iterate through each of the team users until I find the user's ID and then return the team ID for the current team?
My terminology is probably not correct here which is likely the reason I haven't been able to find an answer elsewhere.

A: It depends on the association between Team and User.
Can a User belong to more than one team? If yes, what if the teams are linked to the same project?
Option 1, simple:
class Project
  has_many :teams
end

class Team
  belongs_to :project
  has_many :users
end

class User
  belongs_to :team
end

user_id = 7
@team = User.find_by(id: user_id).team

Option 2, more complex:
class Project
  has_many :teams
end

class Team
  belongs_to :project
  has_and_belongs_to_many :users
end

class User
  has_and_belongs_to_many :teams
end

@project = Project.find_by(id: 5)
user_id = 7
@user = User.find_by(id: user_id)
@team = @user.teams.where(project_id: @project.id).first

On the last line, the query @user.teams.where(project_id: @project.id) will return a single Team record if the user is part to a single team per project (you need to have some custom validation in place).
However, if users can be part of different teams for the same project, that query can return more than one record.


text:
Q: Copy vs photocopy difference? IS there any difference between copy and photocopy of original document?
I need to make 1 original copy and 3 photocopies but I don't know is there any difference between them. Could you explain me?

A: A photocopy is specifically the product/result of scanning a piece of paper on a copy machine or printer.
A copy can mean this if context strongly suggests, but can mean different things.  For example, you can copying files on your computer's desktop, but those aren't photocopies (even if you print them).
Original copy would refer to the document you are scanning on the copy machine/printer.  This is common with documents that originated purely electronically (like Word documents) and are only just now getting around to being on paper for the first time.
If you have to make this original copy, it probably means you have to print it from the computer and retain this copy for your own records - also implying the other photocopies will be sent out and not retained.

A:
IS there any difference between copy and photocopy of original document

Copy can be a difficult word to pin down as to meaning in English.
The Latin word from which the English Copy derives, copia means "a lot of", a great quantity", or "an abundance" Oxford Living Dictionaries.
Copia came to mean "transcript" Ibid (something written from something else) Cambridge Dictionary online. That was by reducing copy (copia) to use as a singular to provide a word for one of an abundance.
Photocopy is much easier to define. There is the term copy in the definition A thing made to be similar or identical to another. Oxford Living Dictionaries with photo accomplished by photographic means. Merriam Webster online
The issue in the question is what copy means. It might mean one of several printed, or otherwise reproduced, instances of the document that originated as a printing, or reproduction, or, the first, or only, instance of a document; both could be an original copy.

1 original copy

does not really describe what is required.
I believe it would be best for you to inquire of the person giving the instructions as to what  "1 original copy " means in this context.


text:
Q: Spectral signatures chart in Google Earth Engine I have been reading the documentation and some related questions online, but I cannot seem to make it work.
I use Google Earth Engine to access an old Landsat 5 image, and classify later on.
I want to plot the spectral signatures on a chart in earth engine, but I cannot seem to make it work.
This is the error code I keep getting:

Error generating chart: Data column(s) for axis #0 cannot be of type string

As far as I know, all the properties in the FeatureCollection are numeric. I don't know where the strings might come from.
Can anyone explain what is exactly going wrong?
The code:
// Query satellite image  26.996813, 14.395989
var aoi = ee.Geometry.Rectangle([14.38, 26.98, 14.49, 27.87]);
var collection = ee.ImageCollection('LANDSAT/LT05/C01/T1_SR').filterDate('1995-01-01', '1995-01-30').filterBounds(aoi).filterMetadata('IMAGE_QUALITY', 'equals', 9).select(['B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7']);

//var rgbImage = collection.sort('CLOUD_COVER').first().select(['B3', 'B2', 'B1']);
var image_ = collection.sort('CLOUD_COVER').first();

// Load training data
var trainData = ee.FeatureCollection('users/jneujens/trainData');

// Property containing land cover labels
var label = 'classname';

// Get training from polygons on image
var training = image_.sampleRegions({
  collection: trainData,
  properties: ['classvalue'],
  scale: 30
});

print(training)

// Graph of spectral signatures training data
var options = {
  title: 'Landsat 5 surface reflectance spectral signatures',
  hAxis: {title: 'Wavelength (micrometers)'},
  vAxis: {title: 'Reflectance'},
  lineWidth: 1,
  pointSize: 4,
  series: {
    0: {color: 'grey'}, // impervious
    1: {color: 'green'}, // vegetation
    2: {color: 'red'}, // soil
}};

// Define a list of Landsat 8 wavelengths for X-axis labels.
var wavelengths = [0.47, 0.56, 0.66, 0.83, 1.56, 2.2, 11.4];

// Create the chart and set options.
var spectraChart = new ui.Chart.image.regions(
    image_, training, ee.Reducer.mean(), 30, 'classvalue', wavelengths)
        .setChartType('ScatterChart')
        .setOptions(options);

print(spectraChart)

A: Try providing trainData as the regions argument to ui.Chart.image.regions() instead of training. The .sampleRegions() step is unnecessary and it may be altering your original collection.

A: try using remap function to convert the class values from string to integers


text:
Q: Not able to find "KeyVaultKeyReference" I am trying to run this script in Powershell, but I am encountering the following error when I do so:
PS C:\Users\knandan\work\DigitalSolutions\RnD> .\Copy-keys.ps1
At C:\Users\knandan\work\DigitalSolutions\RnD\Copy-keys.ps1:245 char:6
+     [Microsoft.Azure.Management.Compute.Models.KeyVaultSecretReferenc ...
+      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unable to find type [Microsoft.Azure.Management.Compute.Models.KeyVaultSecretReference].
At C:\Users\knandan\work\DigitalSolutions\RnD\Copy-keys.ps1:250 char:6
+     [Microsoft.Azure.Management.Compute.Models.KeyVaultKeyReference]$ ...
+      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unable to find type [Microsoft.Azure.Management.Compute.Models.KeyVaultKeyReference].
    + CategoryInfo          : ParserError: (:) [], ParseException
    + FullyQualifiedErrorId : TypeNotFound

I checked my dotnet version and that is "2.1.507"
PS C:\Users\knandan\work\DigitalSolutions\RnD> dotnet --version
2.1.507

I also checked the dotnet framework version and its 4.7.2.

What could be the problem here?
For the background, this is what I am trying to do:
https://learn.microsoft.com/en-us/azure/site-recovery/azure-to-azure-how-to-enable-replication-ade-vms#copy-disk-encryption-keys-to-the-dr-region-by-using-the-powershell-script

A: do you have the required dll? it is not part of your .net install.
dotnet add package Microsoft.Azure.Management.Compute --version 28.3.0

A: Use the following code to install this package, in which the Microsoft.Azure.Management.Compute.xml initializes a new instance of the KeyVaultSecretReference.
Install-Module -Name AzureRM.Compute

Hope this helps.


text:
Q: PHP strpos not working on substrings? I am stuck on this and need help...
I have a string like this one: VG412-FR-B5W20X24
I am getting different results when using strpos() in PHP5.6 if I am searching for a single char or a substring:
var_dump(strpos("VG412-FR-B5W20X24","FR")); // output: bool(false)
var_dump(strpos("VG412-FR-B5W20X24","F")); // output: int(13)

note that both F and FR are present in the string but one evaluates as an int with location 13 and the other evaluates to false...
can anyone help or have an idea how I can find the location of the substring?

A: Works in my PHP 5.5.9 environment.
Try using mb_strpos http://php.net/manual/en/function.mb-strpos.php instead.
If that doesn't work can you attach output from your php -i?


text:
Q: How do I correctly use the ansible hostname module? I am trying to use ansible to modify the hostnames of a dozen newly created Virtual Machines, and I am failing to understand how to loop correctly.
Here is the playbook I've written:
---
- hosts: k8s_kvm_vms
  tasks:
  - name: "update hostnames"
    hostname:
      name: "{{ item }}"
    with_items:
      - centos01
      - centos02
      ...

The result is that it updates each host with each hostname. So if I have 12 machines, each hostname would be "centos12" at the end of the playbook.
I expect this behavior to essentially produce the same result as:
num=0
for ip in ${list_of_ips[*]}; do
    ssh $ip hostnamectl set-hostname centos${num}
    num=$((num+1))
done

If I were to write it myself in bash
The answer on this page leads me to believe I would have to include all of the IP addresses in my playbook. In my opinion, the advantage of scripting would be that I could have the same hostnames even if their IP changes (I just have to copy the ip addresses into /etc/ansible/hosts) which I could reuse with other playbooks. I have read the ansible page on the hostname module, but their example leads me to believe I would, instead of using a loop, have to define a task for each individual IP address. If this is the case, why use ansible over a bash script?
ansible hostname module

A: You can create a new variable for each of the servers in the inventory like
[k8s_kvm_vms]
server1 new_hostname=centos1
server2 new_hostname=centos2

Playbook:
---
- hosts: k8s_kvm_vms
  tasks:
  - name: "update hostnames"
    hostname:
      name: "{{ new_hostname }}"

A: I think you need to sudo to change the hostname thus you should add "become: yes"
---
- hosts: k8s_kvm_vms
  become: yes
  tasks:
  - name: "update hostnames"
    hostname:
      name: "{{ new_hostname }}"


text:
Q: Comment wizardry I am not a level 60 wizard yet, so I've got a question based on the following sentence in the Wikipedia article on magic:

Any comment that has an effect on the code is magic.

How is that? In what languages is such a thing possible? More specifically, what effect can a comment have on the code?

A: Magic comments take various forms. In Ruby, a comment can be placed at the top of the file, which specifies an encoding that the interpreter will use when reading in the file:
# -*- coding: UTF-8 -*-

more

In Unix systems, the first line can be a shebang. In any language with octothorpes for comments, this ammounts to a comment that the OS reads to decide how to interpret the file
#!/bin/bash
echo hello from bash

more

In Haskell, certain types of comments known as pragmas can be used to switch on (or off) language features.
{-# LANGUAGE OverlappingInstances, NoTypeFamilies #-}

more

A: I wouldn't worry too much about that remark in Wikipedia. I think the intention is just to say that a comment "should not" affect behavior (since that's what comment means), so if it does then it must be some kind of special case and hence is "magic" by the definition in use in that section of the article. The author of that line of the article didn't necessarily have any particular language in mind.
If you fancy being pedantic, then a comment can easily affect program behavior in C (in this example by containing a number of line breaks):
#include <stdio.h>

int main() {
    /* If this multi-line comment were deleted, then
       the line-numbers in the remainder of the file
       would be smaller. Boring magic.
    */
    printf("%d\n", __LINE__);
}

I'm pretty sure that this is not what the author of the remark intended, so the remark isn't precise. It's special cases of the comment syntax that are "magic".

A: You do also get those "magic" comments...
That commented out section where everything works fine if you leave those comments in. You remove them and then poof, nothing works. (These are usually caused by having one line in the middle of the commented section uncommented)
(Commentting is Magic)


text:
Q: Function that returns structure giving bad return values This is my first post so don't go rough on me if I happened to skip something I should have mentioned.
I am working on a program that simulates a tennis championship, and the outcome of an individual match via a rand() function to distribute the points among the 2 players currently in said match.
I have scanned the program and did my best to fix the issues but there is still a problem I can not fix, it is the function that determines the outcome of the matches. The problem is that the function returns strange values, nothing they should look like.
I first thought there is a problem with the declaration of the variables and the way I did operations with them but that did not seem to be the case, so I ran out of ideas and come to you.
Here is the code:
jucatori meci(jucatori jucator1,jucatori jucator2 )
{
   int u =0;   //scor jucator 1
   int o=0;    //scor jucator 2

   int p;     //aux j1
   int l;     //aux j2
   int i;

   do
   {
     //first loop, where player 1 serves
     p= rand() % jucator1.sansaServire;  //generate a number for player1
     l= rand() % jucator2.sansaPrimire;  //generate a number for player2

     if(l>p)
     {
        o=o+1;

        do
        {
           //going into the second loop, in this loop, here, player 2 serves
           p = rand() % jucator1.sansaPrimire;
           l = rand() % jucator2.sansaServire;
           if(p>l) u = u+1;
           if(l>p) o = o+1;
           else break; //iese din bucla 2, juc1 va servi iarasi
        }while(l>p);
    }
    else if(p>l) u = u+1;
  }while(u + o < 51);   //inchidem prima bucla

  if(u > o && u - o > 10)
  {
      jucator1.meciurijucate++;
      jucator2.descalificat = 1;
      jucator1.scor1 = u;
      jucator1.scor2 = o;
      return jucator1;
  } //return player 2, add 1 to the number of matches played and mark player 1 as out of the game
  else if(o > u && o - u > 10)
  {
      jucator2.meciurijucate++;
      jucator1.descalificat = 1;
      jucator2.scor1 = o;
      jucator2.scor1 = u;
      return jucator2;
  }//return player 1, add 1 to the number of matches played and mark player 2 as out of the game
  else return meci(jucator1,jucator2); //call function again if the match is a draw
}

I will provide the full program if needed, just thinking that it would be pretty bulky to post the whole thing.


text:
Q: Set Static IP Address on all Physical (Wired) Adapters Using PowerShell, we can easily set a static IP address on an adapter where the InterfaceIndex is known like this:
New-NetIPAddress -InterfaceIndex 17 -IPAddress 192.168.0.1 -PrefixLength 24 -DefaultGateway 192.168.0.254

We would like to be able to set the static IP address on any physical wired adapter. We can get the physical adapters like this:
Get-NetAdapter –Physical

That will return something like this:

Name                      InterfaceDescription                    ifIndex Status       MacAddress             LinkSpeed
----                      --------------------                    ------- ------       ----------             ---------
Ethernet                  Intel(R) Ethernet Connection (5)        17      Disconnected 00-11-22-33-44-55      1 Gbps
Wi-Fi                     Intel(R) Wireless LAN                   7       Disconnected 00-11-22-33-44-56      72 Mbps

*

*Is there any way to get only the wired adapters and not the wireless
adapters, other than by name (which could be anything)?

*Since there may be multiple wired adapters (however rare), and
since we don't know which physical adapter might be used, we would
like to set the static IP address to each wired adapter. What can
we do (something like a "for/each" loop) to set the IP address on
each wired adapter on the PC?

EDIT: In reading some more, it seems that since Windows 8 that the wired adapter may be configured to be statically-named "Ethernet". Since we're only targeting Windows 10, can we really just add a query to get only adapters whose name is like 'Ethernet%?

A: Have you tried something like
Get-NetAdapter -Physical | Where-Object { $_.Name -match "^Ethernet" }

A: I would use
Get-NetAdapter -Physical | Where-Object { $_.PhysicalMediaType -eq "802.3" }

This seems to be a good indicator of physical ethernet only adapters, and it will get adapters that don't have "Ethernet" in the Description/DisplayName. WLAN devices will have Native 802.11 (or otherwise indicative of a Wireless Adapter).
Do Get-NetAdapter | Export-CSV C:\Path\To\CSV to get all properties for all adapters on the system. You may find more properties to leverage in your filtering.
As for setting the IP Address on all ethernet adapters, this should work fine (although I caution that setting the same IP Address on multiple adapters may cause trouble in the however unlikely event that multiple ethernet adapters are in use simultaneously):
$ethernetAdapters = @(Get-NetAdapter -Physical | Where-Object {$_.PhysicalMediaType -eq "802.3"})
$staticIPAddress = "0.0.0.0"
$gateway = "0.0.0.0"
$prefixLength = "24"

foreach ($adapter in $ethernetAdapters) {
    New-NetIPAddress -IPAddress $staticIPAddress -AddressFamily IPV4 -DefaultGateway $gateway -PrefixLength $prefixLength -InterfaceIndex $adapter.InterfaceIndex
}

Remember to replace the variables with information for your environment, and specifically the IP address you'll use for the adapters.
You may wish to figure a way to generate a new IP Address for each $adapter, maybe in succession (*.200, *.201 etc.), with a portion that calls out to a centralized file with ip addresses, mac addresses and serial numbers for record keeping.


text:
Q: Avoid function call in binding I know that i should avoid function calls in a binding, as they're called on every change cycle. I have the following problem where i would like to avoid the function call but i can't find a way around it.
This is only a simplified example but it should show the problem:
some-template.html
<ng-container *ngFor="let control of group.Controls">
    <div [ngSwitch]="control.ControlTypeName" >
        <input *ngSwitchCase="'int'" type="text" [formControlName]="getFormControlName(control.PropertyName)">
        ...
    </div>
</ng-container>

some-component.ts
public getFormControlName(propertyName: string) {
    return this.someArray.find(x => x.key === propertyName).formControlName;
}

The problem is that the property i need for the [formControlName] input, is not in the 'control' object i loop over with *ngFor. The property is in a different array and i'm only able to find it by calling a function.
Is there a way to avoid this?

A: To avoid this, you should have a look-up table (hash table / map / object), indexed by array element key with formControlName as value:
some-component.ts
some_array = [{key: 'a', formControlName: 'b'}, ...];
control_name = this.some_array.reduce(
                   (obj, el) => ((obj[el.key] = el.formControlName), obj), {});

some-template.html
<input *ngSwitchCase="'int'" [formControlName]="control_name[control.PropertyName]" type="text">


text:
Q: How to use code repo so that same user from multiple PCs can access it in Netbeans IDE I am planning to work on a software project using Netbeans-- now I want to work across multiple PCs - how can I set up Netbeans and the Git/Mercurial repo so that I can for eg-- make code changes in one pc, commit to code repo, and then when I go to second pc i can see the updated code?

A: Netbeans.org has a great tutorial on setting up the git repository on your machine. Simply replicate the process across your PCs and git will take care of the versioning and history.
(https://netbeans.org/kb/docs/ide/git.html)


text:
Q: Excel add hyperlink to another table in excel I am trying to add a hyperlink from one sheet to a named table on another sheet. I know that if I name the range then I can use the hyperlink, but ideally, I would like to keep it as just a table.
I have a table on SHEET 2 named MySpa - I would like to have a link from SHEET 1 to that table.
I tried this - =HYPERLINK(MySpa, "Link to MySpa Table") but when I click on the link in the cell it doesn't seem to do anything. How can I link from one sheet to a table on another sheet?

A: If the table is named and is in the same sheet, prepend a hash (#) and wrap in double quotes as shown below:
=HYPERLINK("#TableName", "Click to view")

If the table is in another sheet, prepend the sheet name as shown:
=HYPERLINK("#SheetName!TableName", "Click to view")

The trick is in wrapping the reference in double quotation marks and including the hash sign.

A: Right click on the cell you wish to have the link, hyperlink, place in this document. If you have named the table you should see it there. If not, make it a named range.

A: (Tables don't show up (at least in Excel 2010), but it's still possible...)

*

*You can create a named reference pointing to the (named) table, e.g. name it LnkMyTab and let it point to =MyTab. Now LnkMyTab should appear in the hyperlink dialog under Current Document and it will be automatically updated as the table may change :)

*Another kind of workaround (at least in Excel 2010) based on static nature of hyperlink formulas is this:
(glossary: T: my table,  A: some (temporary) anchor,  L: my hyperlink)

*

*rename your tab MyTab to MyTab_ (T)

*create some temporary named reference MyTab to some arbitrary range or cell, e.g. =B10 (A)

*create your hyperlink using MyTab (L)

*delete the temporary MyTab (A)

*

*(the hyperlink's formula will not be updated and would bring an error if clicked now. this is the "feature" we are using here :))

*rename your tab MyTab_ back to MyTab (T)

*voilá - the hyperlink should work now

A: Excel does not recognize a full table in hyperlink, howver there is a simple workaround provided you want to show a single cell from a table, you can use it's cell address to point as a hyperlink.
Suppose your table is named MyTable
=HYPERLINK(CELL("address",INDIRECT("MyTable"),"Click")
It will show the first row and column intersection in the table, and it will not be static if you cut paste the table to anywhere it will not get affected since it is based on table object name.
If you are having a call from a different table with same number or rows and want to call the corresponding cell of another table then just add [@ColumnName](the column name you have) inside INDIRECT() along with table name like
=HYPERLINK(CELL("address",INDIRECT("MyTable[@ColumnName]"),"Click")
Now it will reference to the same row number as is called from the requesting sheet.


text:
Q: Entity Framework Linq to Object Mapping I have one problem.
Database Shema
==================
|parts           |
==================
| partId |textId |
==================

========================
texts                  |
========================
|TextId|LanguageId|text|
========================

============================
languages                  |
============================
|LanguageId|LanguageIsoCode|
============================

I want to map this result to the following object
public long PartId { get; set; }
public Dictionary<string,string> Name { get; set; }

eg.
{
  PartId: 32020
  Name: {["en": "Blah", "es": "Blah2"]}
}

this is what I have tried, but Im running into TimeOut with this query.
var query = (from p in _context.epc_parts
         select new //select first dynamic object
         {
             PartId = p.PartID,
             Code = p.PartName,
             Name = (from trans in _context.epc_texts
                     join lang in _context.epc_languages on trans.LanguageID equals lang.LanguageID
                     where p.TextID == trans.TextID
                     select new
                     {
                         LanguageId = lang.shortname.ToLower(),
                         Caption = trans.Caption
                     })

         }).AsEnumerable().Select(x => new SearchPartModel //transform it here when we can use dictionary
         {
             Code = x.Code,
             PartId = x.PartId,
             Name = x.Name.ToDictionary(t => t.LanguageId, t => t.Caption)
         });

The parts table has about 60k rows for every row there are 7 translations. Navigation properties cant be used because the Shema doesn't use foreign keys and the model is generated from db.

A: I have solved it with this query. For the whole query it took about 20s to load everything what is ok for this purpose. Im using group by first.
(from p in _context.epc_parts
                     join trans in _context.epc_texts on p.TextID equals trans.TextID
                     join lang in _context.epc_languages on trans.LanguageID equals lang.LanguageID
                     select new
                     {
                         PartId = p.PartID,
                         Code = p.PartName,
                         Caption = trans.Caption,
                         LanguageId = lang.shortname.ToLower()
                     }).AsEnumerable().GroupBy(x => x.PartId).Select(g => new SearchPartModel
                     {
                         Code = g.Select(x => x.Code).FirstOrDefault(),
                         PartId = g.Key,
                         Name = g.Select(x => new
                         {
                             x.LanguageId,
                             x.Caption
                         }).Distinct().ToDictionary(y => y.LanguageId, y => y.Caption)
                     });

A: from p in _context.epc_parts
join trans in _context.epc_texts on p.TextID equals trans.TextID
join lang in _context.epc_languages on trans.LanguageID equals lang.LanguageID

select new {
             PartId = p.PartID,
             Code = p.PartName,
             Name = new
                 {
                     LanguageId = lang.shortname.ToLower(),
                     Caption = trans.Caption
                 }

}

That should be better, otherwise in your current implementation for each part you're querying the texts table


text:
Q: When are real limits used for calculating z score? I'm taking an introductory statistics course. At first, the textbook talks about real limits in the context of continuous variables and frequency distribution table, that is all clear. But on what conditions are real limits used for calculating the z score? Only when we are working with approximation of binomial distribution, because categories of scores are discrete (e.g. coin flip, p=1/2, can't get 2.5 heads in 4 tries)? In such case when we look for p(X > 3), we take X = 2.5, get deviation from mean, divide by std. dev. to convert to z score.
2nd contextual question. E.g. we have data of income per household. When we look for p(X > 50000), we take X = 50000, find z score of 50000, and proportion in tail from the unit normal table is the answer (e.g. if mean was 40k, std. deviation is 10k, then z = (50k - 40k) / 10k = 1. What about when we look for p(X >= 50000), do we find z score from X= 49999.5 (e.g. z = (49999.5 - 40k) / 10k = 0.99995)?
EDIT:
Definition of real limits from the textbook (tl;dr continous (not discrete) variable has possible values in between, e.g. 1 and 2 can have 1.3, 1.2 in between, so measurement of score e.g. X = 2 represents an interval between 1.5 - 2.5):

A: Suppose $X \sim \mathsf{Binom}(n=75,\, p=0.2)$ and you want to find
$P(X \le 12).$ You have several choices.
Binomial formula:  Use the formula for the binomial PDF (or PMF) to evaluate
each of 13 individual terms. A somewhat tedious task.
$$P(X \le 12) = P(X = 0) + P(X = 1) + \cdots + P(X = 12) =
\sum_{k=0}^{12} {75 \choose k}(.2)^k(.8)^{75-k}.$$
Tables: Some books have tables for binomial probabilities. Your textbook
may have a few such tables in an appendix for various (smallish) values of $n$ and a few values of $p.$ Typically, $n = 75$ and $p=0.2$ will not be found there. Before the computer era, there were entire books of binomial probabilities, but
those have mainly disappeared now.
Software: Maybe you have a statistical calculator that will do such
computations. But nowadays there is good software that will do the job easily. One
type of software that will handle this problem is R.  In R, the function
pbinom is a binomial CDF function. The CDF consists of probabilities of
the form $P(X \le k).$ The R code below shows that, for $X \sim \mathsf{Binom}(n=75,\, p=0.2),$ we have $P(X \le 12) = 0.2397,$ correct to four places,
with more places of accuracy available if needed.
pbinom(12, 75, .2)
[1] 0.2396826

Normal approximation: For $n$ sufficiently large and $p$ not too near $0$ or $1,$ the distribution $\mathsf{Binom}(n,p)$ can be approximated by using a normal distribution with matching mean and variance: $\mathsf{Norm}(\mu, \sigma),$ where
$\mu = np$ and $\sigma = \sqrt{np(1-p)}.$
An often-useful rule of thumb is that
the normal approximation gives about two-place accuracy if both $np > 5$ and $n(1-p) > 5.$ Both are satisfied for $n=75$ and $p = 0.2.$
So we find $\mu = np = 15$ and $\sigma = \sqrt{np(1-p)} = 3.4641.$
Because the binomial distribution is discrete and the normal distribution is continuous, we have to be a little careful in order to get best results from
the normal approximation. For $\mathsf{Binom}(75,\,0.2)$, we have
$$P(X \le 12) = P(X < 12.5) = P(X < 13).$$
But for $\mathsf{Norm}(\mu = 15,\, \sigma=0.6928),$ these are three different
probabilities. Briefly put, the 'continuity correction' uses the second of
the three because it (usually) gives the best approximation.
$$P(X \le 12.5) =
P\left(\frac{X-\mu}{\sigma} \le \frac{12.5-15}{3.461}\right)
\approx P(Z \le  -0.7217
) \\ \approx P(Z \le -0.72) = 0.24,$$
where $Z \sim \mathsf{Binom}(0,1).$ The second approximation is necessary
if you are using printed tables of the standard normal distribution because
(without interpolation) these tables provide z-values to only two places.
pnorm(-0.7217);  pnorm(-0.72)
[1] 0.2352395
[1] 0.2357625

In the figure below, the exact binomial probability $P(X \le 12)$ is the sum of the
heights of the vertical black bars to the left of the broken red line.
The normal approximation is the area under the blue normal density curve to the left of the red line.

Notice that, according to the normal curve, the probability $P(X = 12)$
is represented by the area under the curve and above the interval $(11.5, 12.5].$
By using the normal approximation, we have included this entire probability--instead of just part of it.


text:
Q: How to restrict "Remote Login" (ssh) access to only certain IP ranges? Can someone please tell me how to restrict SSH access only to certain IP ranges (e.g. local network) and not the whole Internet? I guess this has to be done via firewall.

A: I did not test this, but I'd try this in terminal:
sudo ipfw add allow src-ip 10.0.0.0/8,172.16.0.0/16,192.168.0.0/16 dst-ip me dst-port 22
sudo ipfw add reject src-ip any dst-ip me dst-port 22

A: From man sshd:
/etc/hosts.allow
/etc/hosts.deny
Access controls that should be enforced by tcp-wrappers are defined here.
Further details are described in hosts_access(5).

https://debian-administration.org/article/87/Keeping_SSH_access_secure offers these examples:
# /etc/hosts.allow
sshd: 1.2.3.0/255.255.255.0
sshd: 192.168.0.0/255.255.255.0

# /etc/hosts.deny
sshd: ALL

The TCP wrapper program in Mac OS X is: tcpd

A: If you are behind a router and didn't map the port to your computer, that effectively disables SSH access from the internet.


text:
Q: Auth0 Additional properties not allowed: memberships I am using Auth0 Delegated Administration Extension to manage users. When I am trying to create user, I am getting this error.

Oh snap! You got an error!
An error occurred while creating the user:
  {"statusCode":400,"error":"Bad Request","message":"Payload validation
  error: 'Additional properties not allowed: memberships (consider
  storing them in app_metadata or user_metadata. See \"Users Metadata\"
  in https://auth0.com/docs/api/v2/changes for more
  details)'.","errorCode":"invalid_body"}

How could I solve this and create users?

A: In your create hook, try the following:

return cb(null, {
  ...
  app_metadata: {
    memberships: memberships
  }
});

You have to construct the object that is sent to the API. Some people want to store it in app_metadata.groups others in app_metadata.departments ...


text:
Q: Passing two images to a page control I have a TableViewController and a DetailViewController. I put a page control in the DetailViewController and i want this page control to display two images passed from the TableViewController. The images that the page control will display depends on the cell selected in the TableViewController.
So my problem is passing two images at the same time from the TableViewController to the page control in the DetailViewController and make the page control display the two images passed.
PD: I want my page control to display only 2 images no more.
Below you can see what i have been trying so far to solve my problem.
My TableViewController.m
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    if ([segue.identifier isEqualToString:@"detailView"]) {

         KTDetailViewController *dvc = [segue destinationViewController];

         NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];

         dvc.passedDetailImage = [UIImage imageNamed:[self.tableImgArray objectAtIndex:indexPath.row]];

         ***THIS IS MY ATTEMPT WHERE I PUT A ARRAY INSIDE ANOTHER***

         dvc.passedPagePropImg = @[ @[[UIImage imageNamed:@"receta.png"], [UIImage imageNamed:@"cachorrita1.jpg"]],
                                    @[[UIImage imageNamed:@"saiya3.jpg"], [UIImage imageNamed:@"goku.jpg"]] ];
         }
    }

My DetailViewController.h
#import <UIKit/UIKit.h>

@interface KTDetailViewController : UIViewController

@property (nonatomic) NSArray *passedPagePropImg;

@end

My DetailViewController.m
@interface KTDetailViewController ()

 // Page Control
 @property (weak, nonatomic) IBOutlet UIImageView *imView;
 @property (weak, nonatomic) IBOutlet UIPageControl *pageProp;
 - (IBAction)imageChange:(UIPageControl *)sender;

@end

@implementation KTDetailViewController

- (IBAction)imageChange:(UIPageControl *)sender {

    ***THIS IS MY HEADACHE WHERE MY APP CRASHES***
    self.imView.image = [self.passedPagePropImg objectAtIndex: self.pageProp.currentPage];

    [self.pageProp updateCurrentPageDisplay];
}
@end

A: Your passing an array of two Arrays, and trying to headache it as it is one.
Try :
self.imView.image = [[self.passedPagePropImg objectAtIndex: self.pageProp.currentPage] objectAtIndex:0];

Hope this helps


text:
Q: Why is pandas.grouby.mean so much faster than paralleled implementation I was using the pandas grouby mean function like the following on a very large dataset:
import pandas as pd
df=pd.read_csv("large_dataset.csv")
df.groupby(['variable']).mean()

It looks like the function is not using multi-processing, and therefore, I implemented a paralleled version:
import pandas as pd
from multiprocessing import Pool, cpu_count

def meanFunc(tmp_name, df_input):
    df_res=df_input.mean().to_frame().transpose()
    return df_res

def applyParallel(dfGrouped, func):
    num_process=int(cpu_count())
    with Pool(num_process) as p:
        ret_list=p.starmap(func, [[name, group] for name, group in dfGrouped])
    return pd.concat(ret_list)

applyParallel(df.groupby(['variable']), meanFunc)

However, it seems that pandas implementation is still way faster than my parallel implementation.
I am looking at the source code for pandas groupby, and I see that it is using cython. Is that the reason?
def _cython_agg_general(self, how, alt=None, numeric_only=True,
                        min_count=-1):
    output = {}
    for name, obj in self._iterate_slices():
        is_numeric = is_numeric_dtype(obj.dtype)
        if numeric_only and not is_numeric:
            continue

        try:
            result, names = self.grouper.aggregate(obj.values, how,
                                                   min_count=min_count)
        except AssertionError as e:
            raise GroupByError(str(e))
        output[name] = self._try_cast(result, obj)

    if len(output) == 0:
        raise DataError('No numeric types to aggregate')

    return self._wrap_aggregated_output(output, names)

A: Short answer - use dask if you want parallelism for these type of cases.  You have pitfalls in your approach that it avoids.  It still might not be faster, but will give you the best shot and is a largely drop-in replacement for pandas.
Longer answer
1)  Parallelism inherently adds overhead, so ideally the operation you're paralleling is somewhat expensive.  Adding up numbers isn't especially - you're right that cython is used here, the code you're looking at is dispatch logic.  The actual core cython is here, which translates down to a very simple c-loop.
2)  You're using multi-processing - which means that each process needs to take a copy of the data.  This is expensive.  Normally you have to do this in python because of the GIL - you actually can (and dask does) use threads here, because the pandas operation is in C and releases the GIL.
3) As @AKX noted in the comments - the iteration before you parallelize (... name, group in dfGrouped) is also relatively expensive - its constructing new sub data frames for each group.  The original pandas algorithm iterates over the data in place.


text:
Q: Button element not working in IE JQuery/AJAX I have a simple HTML button element that looks like this
< type='button' class='cancelButton' id='cancelMe' name='cancelMe' value='cancel' >
This calls JQuery and then AJAX
    $(document).ready(function() {
$(".cancelButton").click(function() {
var cancelVals = "cancel=" + $(this).attr("value");
//RUN AJAX
  $.ajax({
    url: "save.php",
    type: "POST",
    data: cancelVals + "&page=" + currentPage + "&jobNum=" + jobNum,
    success: function (response) {alert(response);}
        });
     });
  });

I cannot get IE to return a response no matter what I do. I tried using a < button > element and even a submit button but no dice.
Can anyone tell me why?

A: HTML will be
<input type='button' class='cancelButton' id='cancelMe' name='cancelMe' value='cancel'>

Did you define currentPage  and jobNum yet?
Try this:
$(document).on('click', '#cancelMe', function(){
  var cancelVals = "cancel=" + $(this).attr("value");
  //RUN AJAX
  $.ajax({
    url: "save.php",
    type: "POST",
    data: cancelVals + "&page=" + currentPage + "&jobNum=" + jobNum,
    success: function (response) {alert(response);}
  });
});


text:
Q: What to use for onClick on mobile? It seems like onClick doesn't quite work with mobile, however it works fine on a desktop browser. What is the best way to do this on mobile - know when an element is pressed?
Here's how I'm using it in my return statement:
    ...
    return (

{this.props.data.busNumber}

{this.props.data.fullRoute}

        {destinations}

    )
    ...

A: You will have to use touch events. In order to enable touch events, you will have to run the following before rendering any component.
React.initializeTouchEvents(true)

More information here. There are similar questions on SO asking the same question - one of them here shows an example usage.


text: Q: Generate DeviceId and DevicePassword for crmsvctutil I am trying to generate code using crmsvcutil. I have CRM Online. I have used DeviceRegistration project present in SDK for device id and device password generation. But the generated device id is of length 26, while using this device id in crmsvcutil, it throws error that the device id length should be between 12 and 22 characters.


text:
Q: Excel formula, IF certain day of week then add "x" number of days I'm having trouble figuring out how to write a formula for the following scenario.  I need to calculate date based on another column but need to add days based on day of the week of original column.
If day of week equals 'Mon/Wed/Fri/Sat' then add 5 days.
If day of week equals 'Tue' then add 6 days.
If day of week equals 'Thur" then add 4 days.

For example,
Column A  Column B
3/11/17   (Show date based on above scenario)
3/13/17
3/18/17

A: Use Choose:
=A1+CHOOSE(WEEKDAY(A1,2),5,6,5,4,5,5,0)

So the Weekday(A1,2) converts the weekday to its position in the week starting with Monday being 1 and Sunday being 7.
The numbers are the number of days to add per day.
It then adds the chosen day to the date.


text:
Q: Sql Model Codeigniter This appears mensagem: Severity: Notice Message: Array to string conversion
my model
public function get_parcelasvencidas ()  {
    $today = date('Y-m-d');
    $id = $this->session->userdata('user_id');
$query = $this->db->query("SELECT * FROM parcelas, aluguel WHERE id_aquiler_parcelas = id_alug");
return $query->result();}

A: First of all, your query is seems wrong. Change with this :
$this->db->query("SELECT * FROM parcelas, aluguel WHERE id_aquiler_parcelas = 'id_alug'");

Because id_alug is value, not variable.
Second, you get an error like this :

Message: Array to string conversion

Because your return type in model is an object. To get the result use foreach instead, like this :
foreach($this->my_model->get_parcelasvencidas() as $row)
{
    echo $row->id;
    echo $row->name;
}

A: Only one little change is,
$this->db->query("SELECT * FROM parcelas, aluguel WHERE id_aquiler_parcelas = 'id_alug'");


text:
Q: LINES TERMINATED BY '\n' not working when store mysl result in txt file When I try to store mysql result in txt file lines terminated is not working
select * from users INTO OUTFILE '/var/lib/mysql-
files/users.txt'
FIELDS TERMINATED BY '|'
ENCLOSED BY '"'
LINES TERMINATED BY '\n';---> not working

the result are all in one line
    "1"|"John@test.com"|"20"|"John"|"test"/"2"|"omar@test.com"|"21"|"Omar"|"test2""3"|"Mytest@test.com"|"30"|"Mytest"|"test3"


text:
Q: How do I fix the width and height of my latex math term? How do I fix the width and height of my latex math term?
I am currently coding an interactive web function where I can click on the latex math term and it'll cancel to zero. However, right now, it is a bit jumpy/glitchy because the size of the first math term changes (highlighted in orange as shown in the picture) once the user clicks on it.

Is there a way where I can set the width and height of the orange box to constant width before and after clicking?

Mass Continuity Equation:
\({{\partial \rho} \over {\partial t}}\)
\(+\)
\({{\partial u} \over {\partial x}}\)
 \(+\)
 \({{\partial v} \over {\partial y}}\)
\(+\)
 \({{\partial w} \over {\partial z}}\)
\(= 0\)

After user clicks the first term, this will be rendered:

Mass Continuity Equation:
\(\require{cancel}\cancelto{0} {{\partial \rho} \over {\partial t}}\)
\(+\)
\({{\partial u} \over {\partial x}}\)
 \(+\)
 \({{\partial v} \over {\partial y}}\)
\(+\)
 \({{\partial w} \over {\partial z}}\)
\(= 0\)

CSS code:
p { font-size: 30px;}

Codepen:
CODEPEN LINK

A: You can use \phantom{} to make a space that is the size of the canceled expression and use \llap{} to place the uncanceled expression on top of it, as in
\require{cancel}
\phantom{\cancelto{0}{\partial\rho \over \partial t}}
\llap{{\partial\rho \over \partial t}\kern .7em}

(The \kern .7em is to get the derivative placed properly within the space of the canceled term, and was determined experimentally.)
Note that you can use the action extension to handle toggling between the uncanceled sand canceled versions, so you really don't need javascript to accomplish this particular example.
Here is an example that uses \toggle actions to flip between uncanceled and canceled versions:

$$
\require{cancel}\require{action}
\def\dd#1#2{{\partial#1 \over \partial#2}}
\def\Cdd#1#2{\cancelto{0}{\dd{#1}{#2}}}
\def\Tdd#1#2{
  \toggle
    {\phantom{\Cdd{#1}{#2}}\llap{\dd{#1}{#2}\kern.6em}}
    {\color{red}{\Cdd{#1}{#2}}}
  \endtoggle
}
\Tdd \rho t + \; \Tdd u x + \; \Tdd v y + \; \Tdd w z
$$


text:
Q: In Word or PPT, how to batch insert pictures in an a array, fitting to cell size? I am writing reports everyday in which I have to attach 9 images in a 3x3 array format, each cell of the same size. Every time, I have to import and resize all images one by one to be squares (6x6cm) and then align them properly as follows:
Array of pictures:

This is highly repetitive and time consuming. My pictures shouldn't be cropped but rather fit the cell fixed size. The resolution and proportions are not an issue as they are almost squares from the start.
Is there any way to batch import those 9 images all at once and get them resized and inserted into my array ? I have tried with both Word and PowerPoint placeholders but I cannot find a way around apart from importing them 1 by 1 using SmartArt.


text:
Q: disable (or change port) for web interface of neo4j embedded? I have a number of small web service projects which use embedded neo4j 2.x.
Any combination of them might be deployed on a single tomcat instance, and therefore I need them NOT to all attempt to start a web service on port 7474.
Acceptable solution is either to disable web interface on all of them, or have each use a separate port. Is the first option doable via Spring configuration? If so, how?
I've tried with a config map:
    <util:map id="config">
        <entry key="enable_remote_shell" value="false" />
        <entry key="org.neo4j.server.webserver.port" value="7475" />
    </util:map>

    <bean id="graphDbFactory" class="org.neo4j.graphdb.factory.GraphDatabaseFactory" />

    <bean id="graphDbBuilder" factory-bean="graphDbFactory"
        factory-method="newEmbeddedDatabaseBuilder">
        <constructor-arg value="${neo4j.database.path}" />
    </bean>

    <bean id="graphDbBuilderFinal" factory-bean="graphDbBuilder"
        factory-method="setConfig">
        <constructor-arg ref="config" />
    </bean>

    <bean id="graphDatabaseService" factory-bean="graphDbBuilderFinal"
        factory-method="newGraphDatabase" destroy-method="shutdown" />

    <bean id="serverWrapper" class="org.neo4j.server.WrappingNeoServerBootstrapper"
        init-method="start" destroy-method="stop">
        <constructor-arg ref="graphDatabaseService" />
    </bean>

but there's Jetty still binding the web service to port 7474... so I guess that

*

*disabling the remote shell doesn't also disable the web admin interface?

*org.neo4j.server.webserver.port is the wrong key, or

*i've got the wrong recipe for the configuration (although this one seems consistent with all the neo4j 2.x Spring configuration examples I can find online)

If not, what do I set in the configuration to give each a distinct port number for the web interface? Thanks.

A: Remove this part
<bean id="serverWrapper" class="org.neo4j.server.WrappingNeoServerBootstrapper"
    init-method="start" destroy-method="stop">
    <constructor-arg ref="graphDatabaseService" />
</bean>


text:
Q: Parsing expressions with suffixes using pyparsing I want to parse the following (simplified) recursive expressions using PyParsing:
foo
(foo + bar)
foo'attribute
foo + bar'attribute
foo.field
(foo'attribute + foo.field)'attribute

I came up with the following parser which works for all of the above expressions:
        identifier = Word(alphas)
        expr = (
            infixNotation(
                identifier,
                [
                    (Literal(".") + identifier, 1, opAssoc.LEFT),
                    (Literal("'") + identifier, 1, opAssoc.LEFT),
                    (Literal("+"), 2, opAssoc.LEFT),
                ],
            )
            + StringEnd()
        )

What fails, however, are expressions that involve .field and the 'attribute suffix together. While foo.field'attribute is accepted, foo'attribute.field yields
pyparsing.ParseException: Expected end of text (at char 13), (line:1, col:14)

When exchanging the tuples for attribute and field of the infixNotation, the second expression parses and the first doesn't. Seems like the order/precedence is relevant.
Any ideas how to parse arbitrary recursive appearances of different suffixes?

A: Each tuple in the list defines its own level of precedence. When one operator has a higher precedence than another, the lower precedence operator can only be used as an operand of the higher precedence one by using parentheses (note that (foo'attribute).field parses fine).
For unary operators, you usually want a single level of precedence for all postfix operators (and another for all prefix operators if you had any). The way you do that in pyparsing is by using a tuple containing a single rule that can match both operators:
(oneOf(". '") + identifier, 1, opAssoc.LEFT),


text:
Q: How to obtain an Azure Active Directory's B2C Custom attribute using GraphServiceClient? I have an ADB2C list of users, for which a Custom attribute is attached. I need to programmatically obtain the attribute.
First, when I query the entry using powershell AzureAD extension, I can see the attribute like so (GUIDs abridged):
> Get-AzureADUser -ObjectId 00000e9b... | select *
ExtensionProperty              : {[odata.type, Microsoft.DirectoryServices.User], [createdDateTime, 24.09.2021 6:55:48], [employeeId, ], [onPremisesDistinguishedName, ]...}
DeletionTimestamp              :
ObjectId                       : 00000e9b...
ObjectType                     : User
... some other keys ...

>> Get-AzureADUser -ObjectId  00000e9b... | select *  -ExpandProperty ExtensionProperty

Key                                                   Value
---                                                   -----
odata.type                                            Microsoft.DirectoryServices.User
createdDateTime                                       24.09.2021 6:55:48
... some other keys ...
extension_05700734c8154786b58d437faf3d30c7_customerId 501cd02e...

So there is the extension_05700734c8154786b58d437faf3d30c7_customerId with the value  501cd02e... that I am willing to retrieve alongside ObjectId for some further processing using C# and GraphServiceClient.
In a close resemblance to this example from Microsoft I made the following code:
var result = await graphClient.Users
      .Request()
      .Select("id,Identities,DisplayName,extension_05700734c8154786b58d437faf3d30c7_customerId")
      .Top(999)
      .GetAsync();

Dumping the result to JSON, I expect to see some values of extension_05700734c8154786b58d437faf3d30c7_customerId inside a property. What I get is an array of entries like
{
   ... many NULL fields ...
  "Identities": [ ... meaningful data of user's email etc...],
  "Id": "00000e9b... ",
  "AdditionalData": {
    "extension_05700734c8154786b58d437faf3d30c7_customerId": {
      "ValueKind": 3
    }
  }
}

Simply put, I get the obscure "AdditionalData": {"extension_05700734c8154786b58d437faf3d30c7_customerId": {"ValueKind": 3}} but not the value of the Custom attribute. There are plenty of other fields which are typically null.
How can I modify the request in my code to obtain the value of the extension_05700734c8154786b58d437faf3d30c7_customerId in C#?

A: The extension property is probably what you are looking for.
More specifically the list extension property.
Example
var result = await graphClient.Users.ExtensionProperties

If you are looking for a specific extension property you can modify your query by adding the id of the extension property.
var result = await graphClient.Users.ExtensionProperties["{extensionProperty-id}"]


text:
Q: How to prevent Eclipse from displaying error dialogs My Eclipse displays an error every several seconds (!) during my work. Here is a screenshot: http://i.stack.imgur.com/wYmwB.png.
I want to completely prevent Eclipse from displaying errors in a separate windows and thus distracting me from the work. I want all the errors silently go to the logs. How can I do this?

A: Eclipse Help states that in the Runtime Options there is an option:
  -launcher.suppressErrors (Executable)

"If specified the executable will not display any error or message dialogs.  This is useful if the executable is being used in an unattended situation."
so just set that


text:
Q: Shuffling php array without same value before or after To shuffle an array in php is easy but my problem is when i try to shuffle it without getting the same result before of after that key.
Example:
Array ( 0 => 1, 1 => 2, 2 => 3, 3 => 3 )

I must have a result without 3 coming together.
Example of some array i want:
Array ( 0 => 2, 1 => 3, 2 => 1, 3 => 3 )

I've tryed to check each item of the array, if that happens i shuffle it again, and check another time. But that seems to be waste both on time and process.
EDIT:
Here is the code i use:
do
{
    $not_valid=false;
    for($i=0;$i<sizeof($arr_times)-1;$i++){
        if($arr_times[$i]==$arr_times[$i+1])
            $not_valid=true;
    }
    if($not_valid)
        shuffle($arr_times);
}while ($not_valid);

A: Even though php has really a lot of strange functions - it doesn't have any for described situation.
So you have to do that manually.
PS: also it would be a good idea to check if it's even possible to shuffle input array in an expected way so you wouldn't get into an infinite loop.

A: From Shuffle list, ensuring that no item remains in same position
<?php
$foo = array(
    0,
    1,
    2,
    3,
    4,
);

for ($i = 0, $c = sizeof($foo); $i < $c - 1; $i++) {
    $new_i = rand($i + 1, $c - 1);
    list($foo[$i], $foo[$new_i]) = array($foo[$new_i], $foo[$i]);
}

var_export($foo); // Derangement


text:
Q: Renaming hundreds of long file names with Python I want to loop through hundreds of file names and rename them.  The issue is that the file names are over 260 characters and contain characters that make os.rename not usable.
The code below runs with regular filenames but not with the files described earlier:
import os
filepath = "path"
path = os.chdir(filepath)
count = 1
for filename in os.listdir(path):
   new_file_name = f"{count}.csv"
   os.rename(filename,new_file_name)
   count += 1

When I run with the long file names, I get:
Traceback (most recent call last):
  File "C:\Users\sarah\Desktop\Python\program.py", line 7, in <module>
    os.rename(filename,new_file_name)
FileNotFoundError: [WinError 3] The system cannot find the path specified:

Is there a way of looping through these file names and renaming them?

A: Filenames cannot exceed 255 characters in Windows of Linux.
Linux:
touch 'zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz'

touch: cannot touch 'zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz': File name too long

Windows:
c:\Users\cp>echo 'foo' > zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz

The filename, directory name, or volume label syntax is incorrect.

A: [Windows specific]
To overcome the issue with MAX_PATH limitation, replace
os.rename(filename,new_file_name)

with
os.rename("\\\\?\\" + filename, "\\\\?\\" + new_file_name)

A: why not try linux shell?
c=0
a="a"
t=".txt"
for file in `ls key*`; do
    newfile="$a$c$t"
    mv $file $newfile
    let c=c+1
done


text:
Q: Getting past Auth1.0a of Twitter API using fetch in JavaScript I'm trying to change my banner on Twitter using 'node-fetch' library, but I can't get past Authentification 1.0a which is needed to post something on Twitter. My last try was using headers.Authorization = "OAuth ACCESS_TOKEN ACCESS_SECRET" but it was a failure. So my question is, what is the correct way of using Auth1.0a in 'node-fetch'?
Thank you in advance!
Btw. the ACCESS_TOKEN and ACCESS_SECRET in the code are not mine, but randomly typed in.
fetch(`https://api.twitter.com/1.1/account/update_profile_banner.json`, {
    method: 'POST',
    body: {
        banner: b64,
    },
    headers: {
        Authorization: "OAuth 2123123415-kbZfcGdHqKxTLlazrgQtzhzhKgHhjgtrLZq6789gui th67jz27z7gh3xhr5ghhgjj1gjHNMthtzuthfnOp3hJwhS5frx"
    }
}).then(results => results.json()).then(data => console.log(data))

A: This is a sample Authorization header from their docs:
Authorization: OAuth oauth_consumer_key="xvz1evFS4wEEPTGEFPHBog", oauth_nonce="kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg",oauth_signature="tnnArxj06cWHq44gCs1OSKk%2FjLY%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1318622958", oauth_token="370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb", oauth_version="1.0"
As you can see there are many more fields to consider, I suggest you read the docs carefully.
The placement of your Auth header is correct.


text:
Q: Android widget Relative Layout I spent the last couple of days trying to make a layout.
They layout looks great on my phone with 480x800 screen, but is messed up on my phone with 540x960 screen.
I used dp expecting it would scale by density.
What is going wrong?
Here is my code for the layout xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent"

  android:layout_margin="15dip"
  android:background="@drawable/gshock5">

    <TextView
        android:id="@+id/widgetday"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:layout_marginRight="50dip"
        android:layout_marginTop="95sp"
        android:layout_centerInParent="true"
        android:text="DAY"
        android:textColor="#003300"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:textStyle="bold"/>

    <TextView
        android:id="@+id/widget1label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/widgetday"
        android:layout_centerHorizontal="true"
        android:clickable="true"

        android:textColor="#003300"
        android:text="Error"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textStyle="bold"/>

     <RelativeLayout
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"

         android:layout_centerHorizontal="true"
         android:layout_marginTop="210dip">

         <Button android:text="Click Me!"
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        />

     </RelativeLayout>

</RelativeLayout>

A: Try using a linear layout. Cause when the device is changed, sure it is scaled. But, when using a relative layout, they are arranged relatively, and then scaled, which probably messed things up.

A: <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="15dip"
    android:background="@drawable/gshock5"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/widgetday"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_marginRight="50dip"
        android:layout_marginTop="95dip"
        android:text="DAY"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:textColor="#003300"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/widget1label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/widgetday"
        android:layout_centerHorizontal="true"
        android:clickable="true"
        android:text="Error"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#003300"
        android:textStyle="bold" />

    <Button
        android:id="@+id/button"
        android:layout_centerHorizontal="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/widget1label"
        android:text="Click Me!" />

</RelativeLayout>

This may solve your problem. Try to use minimal layout for the UI.


text:
Q: Javascript in Pentaho doesn't perform row by row operation? I have the following data:

I use this javascript:
var primary_phone ;
if (inter1.length == 10 && inter2.length == 10 && inter3.length == 0) {
    primary_phone = inter1;
}
else if (inter1.length == 10 && inter2.length == 10 && inter3.length == 10) {
    primary_phone = inter1;
}
else if (inter1.length != 10 && inter2.length == 10 && inter3.length == 0) {
    primary_phone = inter2;
}
else if (inter1.length != 10 && inter2.length != 10 && inter3.length != 10) {
    primary_phone = "+000000000000";
}
else if (inter1.length == 10 && inter2.length == 0 && inter3.length == 0) {
    primary_phone = inter1;
}

And what I get is:

Instead of:

Do you have an idea?

A: Simplified:
var primary_phone;

if ( inter1.length == 10 && (inter3.length == 0 || inter3.length == 10) {
    primary_phone = inter1;
} else if ( inter2.length == 10 && inter3.length == 0 ) {
    primary_phone = inter2;
} else if ( inter3.length != 10 ) {
    primary_phone = "+000000000000";
}
if ( primary_phone != undefined ) {
//primary_phone was assigned a value
}

A: The Javascript is not initialized per row, it (and the variables you assign) persists for the runtime of the transformation. In fact, you can have separate tabs for the start, per-row and end scripts.
To make it work, you need to set reset primary_phone either at the start of the script or in the else clause:
else {
    primary_phone = null;
}


text:
Q: Is there a way to offset / limit and count Pilosa query results? I am doing queries like:
response = client.query(
    index.intersect(
        category.row(1),
        location.row(1),
    )
)
result = response.result
columns = result.row.columns

And as I have a lot of columns, I can sometimes get millions of results, i.e.
len(result.row.columns) > 1000000

I can't find a way to apply an offset+limit to the results or count them on the pilosa side and it seems quite inefficient to transfer the whole bulk of results into python and process it there.

A: Pilosa has a Count query, used in the python client like this:
response = client.query(
    index.count(
        index.intersect(
            field1.row(0),
            field2.row(0),
        )
    )
)
result = response.result
column_count = result.count

This corresponds to a PQL query like Count(Intersect(Row(field1=0), Row(field2=0))).
There is not yet a general way to handle offset+limit for row results. One option that may work for you is to handle the results per-shard, by passing a second argument like shards=[0, 1] to the query function. Limiting the results to a single shard will produce a result set of no more than ShardWidth values (default 220 = 1,048,576).
This corresponds to an HTTP request like curl localhost:10101/index/index1/query?shards=0,1 -d "Intersect(Row(field1=0), Row(field2=0))"
The relevant section of the python client docs would benefit from solid examples and further explanation.


text:
Q: Modify column names in rhandsontable Is it possible to change the column names manually in rhandsontable? Also why cant I add a new row or column here?
## app.R ##
library(shiny)
library(shinydashboard)
library(rhandsontable)
ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(

  ),
  dashboardBody(
    rHandsontableOutput('table')
    )
)

server <- function(session,input, output) {

  output$table <- renderRHandsontable({
    rhandsontable(iris, width = 550, height = 300) %>%
      hot_context_menu(allowRowEdit = FALSE, allowColEdit = FALSE)
  })

}

shinyApp(ui, server)


text:
Q: Why is my Flink streaming job on AWS EMR running on local mini cluster? I'm quite new to Flink and Kafka and I wrote a simple flink streaming job to test out Flink on EMR. The Scala code looks like this
object KafkaStreamingJob {
  def main(args: Array[String]) {
    val senv = StreamExecutionEnvironment.getExecutionEnvironment
    val bootstrapServers = ... // Kafka bootstrap servers
    val properties = new Properties
    properties.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers)
    properties.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "test-consumer-group")
    properties.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest")

    val consumer = new FlinkKafkaConsumer[String]("test", new SimpleStringSchema, properties)
    val kafkaDataStream = senv.addSource(consumer).print

    senv.execute("Demo Flink App")
  }
}

pom.xml
...
        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-scala_${scala.binary.version}</artifactId>
            <version>${flink.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-streaming-scala_${scala.binary.version}</artifactId>
            <version>${flink.version}</version>
        </dependency>
        <dependency>
            <groupId>org.scala-lang</groupId>
            <artifactId>scala-library</artifactId>
            <version>${scala.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-connector-kafka_${scala.binary.version}</artifactId>
            <version>${flink.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.7</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
            <scope>runtime</scope>
        </dependency>
...

Then I submitted the job to EMR with the suggested argument flink-yarn-session -n 2 -d, but for some reason my job is always started on "local embedded Flink mini cluster"
org.apache.flink.streaming.api.environment.LocalStreamEnvironment (main): Running job on local embedded Flink mini cluster

and the error log says:
#
# java.lang.OutOfMemoryError: Java heap space
# -XX:OnOutOfMemoryError="kill -9 %p"
#   Executing /bin/sh -c "kill -9 6282"...

I think the OOM error might have something to do with the fact I'm running job on "mini cluster". But I couldn't find anything related to not running "mini cluster" in AWS documentations. Can anyone help me please?


text:
Q: How to Use Custom Errors in Go Rpc I am using the rpc package in the go standard library and I want to be able to return my custom errors with the RPC calls.
I have the custom error class below:
const (
    UNAVAILABLE = "unavailable"
    GETERROR    = "get-error"
    OTHER = "generic-error"
)

type CustomError struct {
    ErrorCode string
    Msg       string
}

func (e *CustomError) Error() string {
    return fmt.Sprintf("Error type: %s, Msg: %s", e.ErrorCode, e.Msg)
}

And the following RPC endpoint:
func (service *RpcService) Get(args *Args, reply *string) error {
    ....
    do something
    ...

    if err != nil {
        return CustomError{ErrorCode: GETERROR, Msg: ""}
    }

    return nil
}

The problem is that when I retrieve the error on the client side I get a rpc.ServerError. I tried to cast it to my custom error type but I get a panic saying interface conversion: error is rpc.ServerError, not *CustomError. Basically my question is: how can I propagate my custom error type from the RPC call.

A: The standard lib return the error as a string, rpc.ServerError.
So in your code the error you get from client will be something like:
"Error type: unavailable, Msg: "

If you want distinguish the error from client.Get, you could make your CustomError.Error() more simple, eg: Unavailable: something wrong, then you can treat it as a string.
Or you could add an extra string return value to distinguish the result.


text:
Q: Firebase Remote Config Cache Expiration Handling Issue Summary
We're seeing some issues in our app where some users launch the app and see the default config values instead of the ones expected. Restarting the application fixes the issue for those users and they see the correct values as expected.
Longer Description
We're using Strategy #3 as described here. https://firebase.googleblog.com/2017/01/firebase-remote-config-loading.html
On launch, we first do activateFetched and then do fetch, with nothing in the completion handler.
Sometimes, after activateFetched RemoteConfig falls back to default values even though they were seeing the correct values on the previous launch. Restarting the app and calling activateFetched fixes this issue and we see the correct expected values.
To me, it looks like the RemoteConfig cache is expiring at some point and falls back to default values instead. Desired behavior is that we always use the cached values and fetch new ones the first chance we get.
We would love some input about the best way for us to be handling cache expiration for Firebase Remote Config.


text:
Q: fatal: ']' does not appear to be a git repository fatal: Could not read from remote repository i am trying to Push my code up to the dashboard. but it shows the fatal error.
git push ionic master
The above command is not working...


text:
Q: Cin() pretype "y" for user cout << "CONFIRM EXIT [y/n]: ";
cin >> inputChar

Console should say:
CONFIRM EXIT [y/n]: y

I've seen:
int number(20);
string numStr;
cout << "Please give a number [default = " << number << "]: ";
getline(cin, numStr);
number = ( numStr.empty() ) ? number : strtol( numStr.c_str(), NULL, 0);
cout << number << endl;

^^ User input(cin) - Default value
- By: Component 10
Any nicer ways to do this?
Thanks!

A: Something like this?
std::string askUser(const std::string& question, const std::string& default_answer)
{
    std::cout << question << ": " << default_answer << '\r';
    std::cout.flush();
    std::cout << question << ": ";

    std::string answer;
    std::getline(std::cin, answer);
    answer = answer.empty() ? default_answer : answer;
    return answer;
}

int main()
{
    std::string answer = askUser("CONFIRM EXIT [y/n]", "y");
    std::cout << "Answer is '" << answer << "'" << std::endl;
    system("PAUSE");
}