text:
Q: Excel VBA - merge cells if values in columns equals I'm trying to figure out how to implement a macro to get results as follows:

I have no idea how to do it. This is what I've done so far.
I want to have additional column "Action" and if value in column "State" for e.g R1 is empty or "no_fix" then QM (green) else QA (red).
I have data with ~5000 rows

Hi, thanks it works as I expected. However, after testing of my data it turned out that I need to check additional conditions.
1.Additionally for QM and QA:
check in column G if value = "ST"
check in column H if value = 0
2.QA

check in column C if value = "No TC for LM"  check in column D if
  value = "no state" check in column E if value = "No IPIS" if any of
  values = true then QA

    Sub MergeSameCell()
    'area
    Dim Rng As Range, xCell As Range, Test As Range
    Dim Rng1 As Range
    Dim xRows As Integer
    xTitleId = "Merge duplicated cells"
    Set WorkRng = Application.Selection
    Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address,
    Type:=8)
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    xRows = WorkRng.Rows.Count
    For Each Rng In WorkRng.Columns
    For i = 1 To xRows - 1
        For j = i + 1 To xRows
            'If Rng.Cells(i, 1).Value > 0 And Rng.Cells(j, 1).Value > 0 Then
            If Rng.Cells(i, 1).Value <> Rng.Cells(j, 1).Value Then
                  Exit For
            End If
        Next
        'WorkRng.Parent.Range(Rng.Cells(i, 1), Rng.Cells(j - 1, 1)).Merge
        'Text = WorkRng.Parent.Range(Rng.Cells(i, 1), Rng.Cells(j - 1, 1))
        i = j - 1
        For Each Rng1 In Range(Rng.Cells(i, 1), Rng.Cells(j - 1, 1))
            For Z = 1 To 13
         'MsgBox i
        'MsgBox j
            If Rng1.Offset(Z, 1).Value = "no_to_fix" Or Rng1.Offset(Z,
        1).Value
       = "" Then

            'WorkRng.Parent.Range(Rng.Cells(i, 1), Rng.Cells(j - 1,
         1)).Merge
            Rng1.Cells.Offset(Z, 1).Interior.ColorIndex = 37
            'MsgBox "supcio"
            End If
            Next
        Next
    Next
    Next
    WorkRng.VerticalAlignment = xlCenter
    Application.DisplayAlerts = True
    Application.ScreenUpdating = True
    End Sub

A: The following code will do the merging you want and, if I understand what you mean by the second part of the question, will set the first column to be either "QM" (if the fourth column is never anything other than blank or "no_fix") or "QA".
Code assumes you will use the InputBox to select a range containing four columns, the first being the column that will contain "QM" or "QA", the second being the column that is your "Req" column, and the fourth being your "State" column.  (The code never looks at what is in the third column.)
Sub MergeSameCell()
    Dim WorkRng As Range
    xTitleId = "Merge duplicated cells"
    Set WorkRng = Selection
    Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8)

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

    Dim startRow As Long
    Dim endRow As Long
    Dim r As Long
    Dim isQM As Boolean
    'Use "startRow" to keep track of the start of each block
    startRow = 1
    With WorkRng
        'Loop through each row in the selected range
        For endRow = 1 To .Rows.Count
            If .Cells(endRow + 1, 2).Value <> .Cells(startRow, 2).Value Then
                'Only do something if the next row has a different value in the second column

                'merge rows in the first and second columns
                .Worksheet.Range(.Cells(startRow, 1), .Cells(endRow, 1)).MergeCells = True
                .Worksheet.Range(.Cells(startRow, 2), .Cells(endRow, 2)).MergeCells = True

                'Check for "no_fix" or blank
                isQM = True  ' Assume it is a "QM" until we determine it isn't
                For r = startRow To endRow
                    If .Cells(r, 4).Value <> "" And .Cells(r, 4).Value <> "no_fix" Then
                        'If the 4th column is not blank and is not "no_fix", it isn't a "QM"
                        isQM = False
                        Exit For
                    End If
                Next

                'Update column 1 to show QM or QA
                With .Cells(startRow, 1)
                    If isQM Then
                        .Value = "QM"
                        .Interior.Color = vbGreen
                    Else
                        .Value = "QA"
                        .Interior.Color = vbRed
                    End If
                End With

                'Point to start of next block
                startRow = endRow + 1
            End If
        Next
    End With

    Application.DisplayAlerts = True
    Application.ScreenUpdating = True
End Sub


text:
Q: How to solve You must specify |clientID| for |GIDSignIn| error in ios i am working in Gmail login features in unity. When the user clicks the sign in with google button the email id  stored in google play services will automatically populate in screen . Then user choose desired id and login it. In Android it is working. But when i
shift to ios  i am receiving the error
static void UncaughtExceptionHandler(NSException *exception)

{

NSLog(@"Uncaught exception: %@: %@\n%@", [exception name], [exception reason], [exception callStackSymbols]);

if (gsCrashReporterUEHandler)

    gsCrashReporterUEHandler(exception);

}

Thread 1: "You must specify |clientID| for |GIDSignIn|"

This is my pod file . I have changed google sign in less than 4 version.
pod 'Firebase'
pod 'Firebase/Auth'
pod 'GoogleSignIn', '~> 4.0'
pod 'GoogleUtilities'

I have changed the client id  for ios also. and i have downloaded the latest googleserviceinfo.list from firebase console also.  But it shows the error. So any one can help me . How to solve this error.
I have searched this  below forum. But it did nt solved my error.
You must specify |clientID| for |GIDSignIn| error when trying to sign in with Google
I have searched similar questions in stackoverflow. But no one gives the correct solutions.So dont mark my questions as a duplicate.

A: I have found a solution. In  Stackoverflow there are similar questions but the answers are Lengthy.
This is  the simplest solution.
After select the Google-Service-Info.plist file from the "Project navigator" window, you will see on the right the "Target Membership" section. Add the check mark to you application and try rebuild the app.
It works for me!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sorting and object by a parameter I have a class with some String parameters. I made a list of instances from this object. Then I made a comparator sort function to sort the list by different topics. For example by StartTime or EndTime. The time is defined in String format. Here is the compare function for sort:
if (sortType == Sort.STARTTIME){
    Collections.sort(routeList, new Comparator<Route>() {
        @Override
        public int compare(Route o1, Route o2) {
            if (Double.parseDouble(o1.getTimeS()) >= (Double.parseDouble(o2.getTimeS())))
                return 1;
            else
                return -1;
        }
    });
}

It works but when I change the comparator with > or < or <= sign it will not work! or when I compare them with endTime , then only works with <= and I cannot sort it in an increasing order!!!! Even I cannot change the place ot 1 and -1.
if (sortType == Sort.ENDTIME){
    Collections.sort(routeList, new Comparator<Route>() {
    @Override
    public int compare(Route o1, Route o2) {
        if ((Double.parseDouble(o1.getTimeE()) <= Double.parseDouble(o2.getTimeE()))))
            return 1;
        else
            return -1;
    }
});
}

I really don't know what is the matter with it!!!!!!!
public class Route extends Arc {
    private  String type;
    private int secId;
    private String tId;
    private int event;
    private String name;
    private String nameS;
        }
    private String nameE;
    private String timeS;
    private String timeE;
    .....
}

And here are some lines of data
57779.999999999985
57779.999999999956
57778.999999999985
57778.99999999994
57778.99999999993
57778.99999999988
57777.0
57777.0
57750.0
57749.99999999994
57734.99999999994
57734.99999999988
57719.999999999985
57719.999999999985

A: Your understanding of comparators is wrong.
They ought to return -1, 1, and 0 when things are equal. Thus you current comparison using <= and returning either -1 or 1 is incorrect.
Instead, you have to implement such logic that:
Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
In other words: your first implementation probably worked for that data you tested with; but it is incorrect; and reversing the logic doesn't fix that problem.
Finally: the easy answer here; simply use Double.compare() within your comparator. As comparing floating point numbers is actually a tricky business.

A: When use a comparator you implement the logic of comparison.
Then in the following code:
public int compare(Route o1, Route o2) {
        if (Double.parseDouble(o1.getTimeS()) >= (Double.parseDouble(o2.getTimeS())))
            return 1;
        else
            return -1;
    }

You are basically comparing doubles "Double.parseDouble". If you want compare strings you can use compareTo method as follows:
public int compare(Route o1, Route o2) {
        return o1.type1.compareTo(o2.type1);
}

Assuming that type1 attributes for o1 and o2 will never be null else you need to improve the code.
The point is: Inside compare method you must need provide the logic for compare two objects. Imagine that you have a class Student:
public class Student {
    public int id;
    public String name;
    public double score;
    public Student (int id, String name, double score) {
        this.id = id;
        this.name = name;
        this.score = score;
    }
}

And two instances:
Student foo = new Student(100,"Foo", 10.5);
Student bar = new Student(50,"Bar", 90.5);

For sorting purposes which of following is true?:
foo > bar
bar > foo
foo == bar

Java doesn't know you must provide the logic:
if you wat to order by id:
public int compare(Student s1, Student s2) {
    return s1.id - s2.id;
}

if you wat to order by name:
public int compare(Student s1, Student s2) {
    return s1.name.compareTo(s2.name);
}

if you wat to order by score in descendent way:
public int compare(Student s1, Student s2) {
    return (s2.score  - s1.score) * 100;
}

A: The right answer
public int compare(Route o1, Route o2) {
    if (Double.parseDouble(o1.getTimeS()) < (Double.parseDouble(o2.getTimeS())))
         return -1;
    else if (Double.parseDouble(o1.getTimeS()) == (Double.parseDouble(o2.getTimeS())))
        return 0;
    else
        return +1;
    }
});


text:
Q: Unable to insert data into mysql using android emulator via php Actually, am newbie in android and trying to insert record into mysql table using android via php page. Am using wamp server but. I using IP address 10.0.2.2 instead of 127.0.0.1 and I also used IP address with 10.0.0.2:8676 for my port number also but none of them is working and I always find this is error Invalid IP address. Am unable to understand where am I wrong. Although this code is working on live server host and values are inserting into live server but not in localhost. Am using wamp server and my Operating System is Windows XP 3 . Am using Eclipse . Android SDK 17 android version 4.2. Below is my code:
Thanks in advance.
public class MainActivity extends Activity {

String name;
String id;
InputStream is=null;
String result=null;
String line=null;
int code;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(com.example.buddyproject.R.layout.activity_main);

    final EditText e_id=(EditText) findViewById(R.id.editText1);
    final EditText e_name=(EditText) findViewById(R.id.editText2);
    Button insert=(Button) findViewById(R.id.button1);

    insert.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        id = e_id.getText().toString();
        name = e_name.getText().toString();

        insert();
    }
});
}

public void insert()
{
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

nameValuePairs.add(new BasicNameValuePair("id",id));
nameValuePairs.add(new BasicNameValuePair("name",name));

    try
    {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://10.0.2.2/androidtest/insert.php");
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
        Log.e("pass 1", "connection success ");
}
    catch(Exception e)
{
        Log.e("Fail 1", e.toString());
        Toast.makeText(getApplicationContext(), "Invalid IP Address",
        Toast.LENGTH_LONG).show();
}

    try
    {
        BufferedReader reader = new BufferedReader
        (new InputStreamReader(is,"iso-8859-1"),8);
        StringBuilder sb = new StringBuilder();
        while ((line = reader.readLine()) != null)
    {
            sb.append(line + "\n");
        }
        is.close();
        result = sb.toString();
    Log.e("pass 2", "connection success ");
}
    catch(Exception e)
{
        Log.e("Fail 2", e.toString());
}

try
{
        JSONObject json_data = new JSONObject(result);
        code=(json_data.getInt("code"));

        if(code==1)
        {
    Toast.makeText(getBaseContext(), "Inserted Successfully",
        Toast.LENGTH_SHORT).show();
        }
        else
        {
     Toast.makeText(getBaseContext(), "Sorry, Try Again",
        Toast.LENGTH_LONG).show();
        }
}
catch(Exception e)
{
        Log.e("Fail 3", e.toString());
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

}
$host='localhost';
$uname='root';
$pwd='';
$db="test";

$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
mysql_select_db($db,$con) or die("db selection failed");

$id=$_REQUEST['id'];
$name=$_REQUEST['name'];

$flag['code']=0;

    $sql="INSERT INTO sample (id,name)VALUES('$id','$name')";

 if (!mysql_query($sql,$con))
{
    $flag['code']=1;
    echo"hi";
}
print(json_encode($flag));
mysql_close($con);

A: You have to change your ip in this line
 HttpPost httppost = new HttpPost("http://10.0.2.2/androidtest/insert.php");

Open cmd-type ipconfig -hit enter.
Get IPv4 address usually starts with 192.X

Change ip in your code. It should work

A: Your try statements are catching every exception. You should not do this and you certainly can't conclude 'Invalid IP address' in the first block.
It's much more likely that you are throwing a NetworkOnMainThreadException because you are trying to do networking on the UI thread. You shouldn't do that either. You should delegate the network code to a different thread or run it in an AsyncTask.


text:
Q: How to pass a unique uuid to each callback? I'm using multer-s3-transform, which allows me to manipulate the image coming in, before uploading it to my bucket. Here's what I have:
const singleImageUploadJpg = multer({
  storage: multerS3({
    s3: s3,
    bucket: "muh-bucket",
    acl: "public-read",
    key: function(req, file, cb) {
      const fileName = uuid.v4();
      cb(null, fileName);
    },
    shouldTransform: function(req, file, cb) {
      cb(null, true);
    },
    transforms: [
      {
        id: "original",
        key: function(req, file, cb) {
          cb(null, `${uuid.v4()}.jpg`);
        },
        transform: function(req, file, cb) {
          cb(
            null,
            sharp()
              .resize()
              .jpeg({ quality: 50 })
          );
        }
      },
      {
        id: "small",
        key: function(req, file, cb) {
          cb(null, `${uuid.v4()}_small.jpg`);
        },
        transform: function(req, file, cb) {
          cb(
            null,
            sharp()
              .resize()
              .jpeg({ quality: 50 })
          );
        }
      }
    ]
  }),
  limits: { fileSize: 50 * 1024 * 1024 }
}).single("image");

The problem is that the uuid will always be different for the small and the original versions. How can I make const fileName = uuid.v4() passed down to each callback, so that they'd have the same name, with _small being the only difference?

A: I assume that multer calls the functions provided repeatedly, which is why you don't do the obvious thing Jim Nilsson suggested. Also, sadly, you've said that the file you receive in the transform callback doesn't have the name you specify earlier.
Two possibilities, both assuming that either the file object or the req object you receive is the same in both callbacks:

*

*Your own expando property

*A WeakMap
Expando property
You could try to piggyback it on the file/req (I use file below), like so (see *** comments):
const singleImageUploadJpg = multer({
  storage: multerS3({
    s3: s3,
    bucket: "muh-bucket",
    acl: "public-read",
    key: function(req, file, cb) {
      file.__uuid__ = uuid.v4();                   // ***
      cb(null, file.__uuid__);
    },
    shouldTransform: function(req, file, cb) {
      cb(null, true);
    },
    transforms: [
      {
        id: "original",
        key: function(req, file, cb) {
          cb(null, `${uuid.v4()}.jpg`);
        },
        transform: function(req, file, cb) {
          cb(
            null,
            sharp()
              .resize()
              .jpeg({ quality: 50 })
          );
        }
      },
      {
        id: "small",
        key: function(req, file, cb) {
          cb(null, `${file.__uuid__}_small.jpg`);  // ***
        },
        transform: function(req, file, cb) {
          cb(
            null,
            sharp()
              .resize()
              .jpeg({ quality: 50 })
          );
        }
      }
    ]
  }),
  limits: { fileSize: 50 * 1024 * 1024 }
}).single("image");

That would probably be doing something undocumented, though, which means you need to be careful to test with every "dot release" of the library you upgrade to.
WeakMap:
Alternatively, you could use a WeakMap keyed by the file or req (I use file below):
const nameMap = new WeakMap();
const singleImageUploadJpg = multer({
  storage: multerS3({
    s3: s3,
    bucket: "muh-bucket",
    acl: "public-read",
    key: function(req, file, cb) {
      const fileName = uuid.v4();
      nameMap.set(file, fileName);                  // ***
      cb(null, fileName);
    },
    shouldTransform: function(req, file, cb) {
      cb(null, true);
    },
    transforms: [
      {
        id: "original",
        key: function(req, file, cb) {
          cb(null, `${uuid.v4()}.jpg`);
        },
        transform: function(req, file, cb) {
          cb(
            null,
            sharp()
              .resize()
              .jpeg({ quality: 50 })
          );
        }
      },
      {
        id: "small",
        key: function(req, file, cb) {
          const fileName = nameMap.get(file); // ***
          nameMap.delete(file);               // *** (optional, presumably `file` will be released at some point, which would remove it automatically)
          cb(null, `${fileName}_small.jpg`);  // ***
        },
        transform: function(req, file, cb) {
          cb(
            null,
            sharp()
              .resize()
              .jpeg({ quality: 50 })
          );
        }
      }
    ]
  }),
  limits: { fileSize: 50 * 1024 * 1024 }
}).single("image");

A: You could wrap it in a function and generate the uuid before calling multer:
const singleImageUploadJpg = (function()
{
    const uid = uuid.v4();
    return multer({
        storage: multerS3({
            s3: s3,
            bucket: "muh-bucket",
            acl: "public-read",
            key: function(req, file, cb) {
              const fileName = uid;
              cb(null, fileName);
            },
            shouldTransform: function(req, file, cb) {
              cb(null, true);
            },
            transforms: [
              {
                id: "original",
                key: function(req, file, cb) {
                  cb(null, `${uid}.jpg`);
                },
                transform: function(req, file, cb) {
                  cb(
                    null,
                    sharp()
                      .resize()
                      .jpeg({ quality: 50 })
                  );
                }
              },
              {
                id: "small",
                key: function(req, file, cb) {
                  cb(null, `${uid}_small.jpg`);
                },
                transform: function(req, file, cb) {
                  cb(
                    null,
                    sharp()
                      .resize()
                      .jpeg({ quality: 50 })
                  );
                }
              }
            ]
        }),
        limits: { fileSize: 50 * 1024 * 1024 }
    }).single("image");
})();

A: You're calling the uuid.v4 method in your handler, which returns something different each time you do so. What you need to do is to call it once and put it in a variable
const singleImageUploadJpg = ( function( my_uuid )
{
    // same as before

})(  uuid.v4() );

And then use that variable later on
cb(null, `${my_uuid}.jpg`);
// ...
cb(null, `${my_uuid}_small.jpg`);


text:
Q: How to convert date time to seconds I have a df given like this:
            A
0 03:32:57.565 2020-01-28
1 03:32:58.565 2020-01-28
2 03:32:59.566 2020-01-28
3 03:33:00.566 2020-01-28
4 03:33:01.569 2020-01-28
           ...
n 03:33:57.565 2020-01-28

I want to retrieve and store the accumulative of each row of each of these date times in seconds, excluding the date and the hours. Like this:
       A
0    7.565
1    8.565
2    9.566
3    10.566
4    11.569
     ...
n    67.565

A: Try
s.dt.second+s.dt.microsecond/10**6

For your example,
s = pd.to_datetime(pd.Series(["03:32:57.565 2020-01-28",
                   "03:32:58.565 2020-01-28",
                   "03:32:59.566 2020-01-28",
                   "03:33:00.566 2020-01-28",
                   "03:33:01.569 2020-01-28",
                   "03:33:57.565 2020-01-28"]))

this produces
0    57.565
1    58.565
2    59.566
3     0.566
4     1.569
5    57.565
dtype: float64

A: For those who are looking for the answer.
Here is how I solve it.
Maybe it is not the fastest of proper approach for pandas but it worked for what I need it.
elapsed = []
    tmp =[]

    for i in range (0, len(df)):
        tmp = datetime.strptime(df.Time[i], '%H:%M:%S.%f %Y-%m-%d')
        tmp_ms = tmp.microsecond
        tmp_s = tmp.second
        tmp_min  = tmp.minute
        tmp.append(tmp_min*60 + tmp_s + tmp_ms/1000000)

    for i in range (0, len(df)):
        elapsed.append(tmp[i]-tmp[0])


text:
Q: List implemented using an inorder binary tree For the new computer science assignment we are to implement a list/array using an inorder binary tree. I would just like a suggestion rather than a solution.
The idea is having a binary tree that has its nodes accessible via indexes, e.g.
t = ListTree()
t.insert(2,0) # 1st argument is the value, 2nd the index to insert at
t.get(0) # returns 2

The Node class that the values are stored in is not modifiable but has a property size which contains the total number of children below, along with left, right and value that point to children and store the value accordingly.
My chief problem at the moment keeping track of the index - as we're not allowed to store the index of the node in the node itself I must rely on traversing to track it. As I always start with the left node when traversing I haven't yet thought of a way to recursively figure out what index we are currently at.
Any suggestions would be welcome.
Thanks!

A: You really wouldn't want to store it on the node itself, because then the index would have to be updated on inserts for all nodes with index less than insert index.  I think the real question is how to do an in-order traversal.  Try having your recursive function return the number of nodes to its left.

A: I don't think you want to store the index, rather just the size of each subtree.  For insance, if you wanted to look up the 10th element in the list, and the left and right subrees had 7 elements each, you would know that the root is the eight element (since it's in-order binary), and the first element of the right subree is 9th.  armed with this knowledge, you would recurse into the right subree, looking for the 2nd element.
HTH

A: Well, a node in a binary tree cannot have a value and an index. They can have multiple pieces of data but the tree can only be keyed/built on one.
Maybe your assignment wants you to use the index value as the key to the tree and attach the value to the node for quick retrieval of the value given an index.

A: Does the tree have to be balanced? Does the algorithm need to be efficient?
If not, then the simplest thing to do is make a tree in which all the left children are null, i.e., a tree that devolves to a linked list.
To insert, recursively look go to the right child, and then update the size of the node on the way back out. Something like (pseudocode)
function insert(node, value, index, depth)
    if depth < index
        create the rightchild if necessary
        insert( rightchild, value, index, depth + 1)
    if depth == size
        node.value = value
    node.size = rightchild.size + 1

After you have this working, you can modify it to be more balanced. When increasing the length of the list, add nodes to the left or right child nodes depending on which currently has the least, and update the size on the way out of the recursion.
To generalize to be more efficient, you need to work on the index in terms of its binary representation.
For example, and empty list has one node, without children with value null and size 0.
Say you want to insert "hello" at index 1034. Then you want to end up with a tree whose root has two children, with sizes 1024 and 10. The left child has no actual children, but the right node has a right child of its own of size 2. (The left of size 8 is implied.) That node in turn, has one right child of size 0, with the value "hello". (This list has a 1-based index, but a 0-based index is similar.)
So you need to recursively break down the index into its binary parts, and add nodes as necessary. When searching the list, you need to take care when traversing a node with null children

A: A very easy solution is to do GetFirst() to get the first node of the tree (this is simply finding the leftmost node of the tree).  If your index N is 0, return the first node.  Otherwise, call GetNodeNext() N times to get the appropriate node.  This isn't super efficient though since accessing a node by index takes O(N Lg N) time.
Node *Tree::GetFirstNode()
{
    Node *pN,*child;
    pN=GetRootNode();
    while(NOTNIL(child=GetNodeLeft(pN)))
    {
        pN=child;
    }
    return(pN);
}

Node *Tree::GetNodeNext(Node *pNode)
{
    Node *temp;

    temp=GetNodeRight(pNode);
    if(NOTNIL(temp))
    {
        pNode=temp;
        temp=GetNodeLeft(pNode);
        while(NOTNIL(temp))
        {
            pNode=temp;
            temp=GetNodeLeft(pNode);
        }
        return(pNode);
    }
    else
    {
        temp=GetNodeParent(pNode);
        while( (NOTNIL(temp)) && (GetNodeRight(temp)==pNode) )
        {
            pNode=temp;
            temp=GetNodeParent(pNode);
        }
        return(temp);
    }
}


text:
Q: Apache NiFi stream into InfluxDB Within a cloud application I'm using NiFi (=> I'm a newbee) to work with data streams published by a mqtt broker. So far so good.
In the end I want to stream into an InfluxDB. That's the point I'm struggling with.
Does anybody have some experiences with a processor for such a setup? Is there a suitable processor for writing data into an InfluxDB?
Thanks a lot.
Kind regards,
T_F

A: There is a PutInfluxDB processor which accepts the incoming flowfile and writes the content as 'line content' in InfluxDB.


text:
Q: Why angular.json is removed from Angular 14? I have created a new angular project with the ng new command.
Angular CLI: 14.2.0
Node: 16.14.0
Package Manager: npm 8.3.1
OS: darwin arm64
Angular: 14.1.3
It has created a project which includes angular.json and the commands ng serve, and ng build were working. I just learned that angular.json is no longer used it was managed by angular CLI in the latest angular 14 versions. So, I tried to delete angular.json from my root project. But now the ng commands were not working.
The ng serve command gives the error: This command is unavailable when running the Angular CLI outside a workspace.
What does it mean? How can I fix this issue? Is it necessary to keep angular.json for workspace configuration? How can I serve my project without angular.json?


text:
Q: Вопрос по работе с API Есть такой API, где представлены персонажи "Звездных войн": https://swapi.dev/documentation#people
У меня задача, что, если искомый персонаж не найден, то выводить сообщение "Ничего не найдено". Как это сделать?

A:

async function findByName(name) {
    const params = new URLSearchParams({ search: name });
    const response = await fetch('https://swapi.dev/api/people/?' + params);
    const result = await response.json();
    return result.count >= 1 ? result.results : null;
}

(async () => {
    const peoples = await Promise.all([
        findByName('Luke'),
        findByName('r2'),
        findByName('123'),
    ]);

    for (const people of peoples)
        if (people)
            console.log(people[0].name);
        else
            console.log('People is not found');
})();

Итоговый вариант:

async function findByName(name) {
    const params = new URLSearchParams({ search: name });
    const response = await fetch('https://swapi.dev/api/people/?' + params);
    const result = await response.json();
    return result.count >= 1 ? result.results : null;
}

const input = document.querySelector('#input');
const datalist = document.querySelector('#datalist');

input.oninput = async (e) => {
    const { value } = e.target;
    const peoples = await findByName(value);
    if (!peoples) return;

    const options = peoples.map(
        ({ name }) => `<option value="${name}">`
    );

    datalist.innerHTML = options.join('');
}
<label>Enter people name:</label>
<input id="input" list="datalist" />

<datalist id="datalist"></datalist>

A: .catch(function() {
      alert("Ничего не найдено, попробуйте еще раз!");
});

Всё оказалось гораздо проще. Достаточно использовать перехват ошибок try...catch.


text:
Q: Unit test bypass for third party web service call I'm writing function unit tests for a REST API built with Symfony2. Part of the REST API checks HTTP basic authentication against a third party web service.
This presents a bit of a challenge when it comes to unit testing as I can't create a temporary user for the third party web service.
I could hard code credentials in, but I was thinking of an alternative approach. Would it be bad practice to hard code in some logic that shortcircuits the third party API call if the environment is test? Is there a better way to do something like this? I'm sure other applications face this problem.

A: The best practice is to :

*

*Isolate the authentication against the 3rd party WS in a new class

*Make a mock for that class for your tests

*Use dependency injection so that for your unit test, you can use your mock


text:
Q: Conflicting plugins I'm facing a problem which i'm not sure is one or not. The problem is that whenever I add any plugin related to jquery star rating my sidebar does not work. The jquery plugin im using is RATY. I've also tried using JRating,Bootstrap but the result remains the same.
This is the code for sidebar:
$("#content-1").mouseover(function(){
    $(this).css({'left':'120px'});
});
$("#content-1").mouseleave(function(){
    $(this).css({'left':"-10px"});
});

Please help. I have no idea why this is happening or rather this is the first time i'm seeing this. Thank You.


text:
Q: Adding plugin to sidebar file in WordPress So im in the middle of creating a site with WordPress but now Im stuck at the sidebars.
In sidebar.php-file I have added some text and CSS rules as a test and they are shown at the site as a sidebar. However, I want to show the forum's latest posts in this sidebar instead.
Im using a plugin called "tt post viewer". I tested it out on a page at the site and it shows me the latest post.
But im not sure what code I should add to the sidebar.php-file so that the plugin print the latest post at the sidebar.
And if it's possible?
https://wordpress.org/plugins/tt-post-viewer/
Would be grateful if anyone could help me out.
Thanks!
yours sincerely, Winterwind

A: You don't need to add code to the sidebar. Make sure your sidebar is wdiget-ready and just drag and drop the widget in the Wordpress Backend into your sidebar.


text:
Q: How to have a word floating to the left of a paragraph I am trying to achieve the same as what is shown in the figure below. Basically, I would like to have a word, or a couple of words, floating to the left of a paragraph where the term is first introduced.
This significantly improves readability and the identification of all the terms used in a background section, but I have no clue of how can I do this.
What LaTeX packages could I use to achieve this effect?

A: This is often referred to as a \marginpar.

\documentclass{article}

\usepackage{newpxtext}

\begin{document}

In most collections, the same concept may be referred to using different
words. This issue, known as \marginpar{\textsc{synonymy}}\emph{synonymy}, has an impact on the recall of most
information retrieval systems. For example, you would want a search for
\textsf{aircraft} to match \textsf{plane} (but only for references to an \emph{airplane}, not a woodworking
plane), and for a search on \textsf{thermodynamics} to match references to \textsf{heat} in
appropriate discussions.

\end{document}

Positioning on the left or right is possible via \marginpar[<left>]{<right>} when in twoside mode. You could also consider using the marginnote package, depending on the depth of usage.


text:
Q: Python with etc/Shadow so I'm writing this program that needs to check the password hash in etc/shadow and compare it to the password the user entered. I tried encrypting the password with hashlib.sha512, but the result was not the same. I think it's salted some how, but I don't know if it uses a universal salt or how I can get the salt each time.
tldr; I need a way for a user to enter a password, then have the program hash it and check it against the etc/shadow. Any ideas?

A: Try this https://pypi.python.org/pypi/pam . First link in google by python pam.
Look at distribution package manager for python-pam if exists. Else install with pip or easy_install.
Small example:
>>> import pam
>>> pam.authenticate('fred', 'fredspassword')
False

A: >>> import crypt
>>> line = 'bob:$1$qda8YAO9$rBiov9uVJlH1/97cbcyEt.:15965:0:99999:7:::'
>>> encript = line.split(':')[1]
>>> encript
--> '$1$qda8YAO9$rBiov9uVJlH1/97cbcyEt.'

>>> i = encript.rfind('$')
>>> salt = encript[:i]
>>> salt
--> '$1$qda8YAO9'

>>> crypt.crypt('bob_password',salt)
--> '$1$qda8YAO9$rBiov9uVJlH1/97cbcyEt.'
>>> encript
--> '$1$qda8YAO9$rBiov9uVJlH1/97cbcyEt.'

A: The passwd field is not just a SHA-512 hash of the password.*
This is explained in the crypt manpage. The format is $id$salt$hash, where id specifies the hash method (1 for MD5, 2a for Blowfish, 5 for SHA-256, 6 for SHA-512), salt specifies the salt to use with that algorithm, and hash specifies what the result should be.
As the manpage implies, you can actually pass the whole $id$salt$ to the crypt function in place of the salt, and it will automatically use the appropriate algorithm. This wouldn't be too hard to do via, say, ctypes.

At any rate, what you're doing is almost certainly a bad idea. You'll need to run as root in order to have access to /etc/shadow, and you'll need to simulate more than just password verification if you actually want to verify that the user can log in, and of course you'll need to handle secure input and make sure you don't end up saving the password in plaintext somewhere and so on. It's a lot simpler and safer to just let PAM do the work for you.

* I believe that in theory, it can be—if it doesn't start with a $ it's interpreted as some legacy format… presumably meaning it's interpreted as POSIX crypt using the DES algorithm.


text:
Q: max value of a tensor in graph mode tensorflow I have this tf code in graph mode (it has a training function wrapped by @tf.function) where I need to get the max value of a tensor x with type
<class 'tensorflow.python.framework.ops.Tensor'> Tensor("x_3:0", shape=(100,), dtype=int64).
Then I need to use the max value of x as one of the arguments in the shape argument of tf.reshape(). If I print the output of tf.reduce_max(x) I get Tensor("Max:0", shape=(), dtype=int64), which is an invalid argument for tf.reshape(). I have tried tf.reduce_max(x).numpy() and it throws the error message 'Tensor' object has no attribute 'numpy'
So how do I get the max value of a tensor in graph mode in tf 2.6.0?
UPDATE This is my code with the necessary details (I hope) to see what is going on:
MyModel.py
class MyModel(tf.keras.Model):
    def __init__(self, ...,hidden_size,name='model',**kwargs):
        super(MyModel, self).__init__(name=name, **kwargs)
        self.hidden_size = hidden_size

    def call(self, inputs, training=True):
        x1, input, target, length, y = inputs
        batch_size = input.shape[0]
        print('check point 2', length, tf.reduce_max(length))
        padded_outputs = tf.reshape(tf.boolean_mask(outputs_dec,mask), shape=(batch_size,tf.reduce_max(length),self.hidden_size))
        print('check point 3',padded_outputs.shape)

    @tf.function
    def train(self, inputs, optimizer):
        with tf.GradientTape() as tape:
            costs = self.call(inputs)
        gradients = tape.gradient(self.loss, self.params)
        optimizer.apply_gradients(zip(gradients, self.params))

train_mymodel.py
tr_data = tf.data.Dataset.from_tensor_slices((x1_tr,
                                              x2.input,
                                              x2.target,
                                              x2.length,
                                              y_tr))\
                                             .batch(args.batch_size)
while int(checkpoint.step) < args.epochs:
            for i, (x1_batch, input_batch, target_batch, length_batch, y_batch) in enumerate(tr_data):
                print('check point 1', length_batch)
                costs, obj_fn = mymodel.train((x1_batch, input_batch, target_batch, length_batch, y_batch),optimizer)

check point 1 tf.Tensor([300 300 ... 300 300], shape=(100,),type=int64)
check point 2 Tensor("x_3:0", shape=(100,), dtype=int64) Tensor("Max_1:0", shape=(), dtype=int64)
check point 3 (100, None, 500)

The shape of padded_outputs should be (100, 300, 500).
UPDATE2 The error happens when the graph is traced. If I hard code shape=(batch_size,300,self.hidden_size) and use tf.print(batch_size,tf.reduce_max(length),self.hidden_size) then the code runs without error messages and the output of tf.print() is (100,300,500). Is it any way to avoid such behavior?

A: It should work by simply passing the reduced tensor as an argument:
import tensorflow as tf
tf.random.set_seed(1)

@tf.function
def reshape_on_max_value():
  tensor1 = tf.random.uniform((5, 2), maxval=5, dtype=tf.int32)
  tensor2 = tf.random.uniform((4, 1), maxval=5, dtype=tf.int32)
  x = tf.reduce_max(tensor1)
  tf.print(type(tensor1), type(tensor2))
  tf.print(tf.reshape(tensor2, [x, 1, 1]).shape)

reshape_on_max_value()

<class 'tensorflow.python.framework.ops.Tensor'> <class 'tensorflow.python.framework.ops.Tensor'>
TensorShape([4, 1, 1])


text:
Q: Flask Form Post data to another html page I have a form that gets data and redirects to the bk.html page. I want to get the results from submitted form and have the page redirect with that info on it. I can dynamically put it on the same page but I don't know how to add it to a new page.
from flask import Flask, render_template, request, redirect
app = Flask(__name__)
# our index route will handle rendering our form
@app.route('/')
def index():
  return render_template("index.html")

@app.route('/users', methods=['POST'])
def create_user():
   print "Got Post Info"
   name = request.form['name']
   DojoLocation = request.form['location']
   FavoriteLanguage = request.form['Language']
   textarea = request.form['textarea']
   # redirects back to the '/' route
   return render_template('bk.html')

app.run(debug=True) # run our server

<!DOCTYPE html>
<html>
<head>
  <title>Dojo Survey Index</title>
  <meta charset="utf-8">
  <link rel='stylesheet' type='text/css' href="{{ url_for('static', filename='css/my_style_sheet.css')}}">
  <script type="text/javascript" src="{{ url_for('static', filename='js/my_script.js')}}"></script>
</head>
<body>
<div id = container 1 >
<form action='/users' method='post'>
Name: <input type='text' name='name'>
Dojo Location:  <select name="location">
<option value="Silicon Valley">Silicon Valley</option>
<option value="Seattle">Seattle</option>
<option value="Los Angeles">Los Angeles</option>
<option value="Dallas">Dallas</option>
<option value="Washington DC">Washington DC</option>
<option value="Dallas">Dallas</option>
<option value="Chicago">Chicago</option>
<option value="Berkely">Berkely</option>
<option value="Orange County">Orange County</option></select>
Favorite Language:  <select name="Language">
<option value="ios swift">ios swift</option>
<option value="Ruby on rails">ruby on rails</option>
<option value="Python">Python</option>
<option value="Mean">Mean</option>
<option value="C# ">C# DC</option>
</select>
<textarea name="textarea" value = "textbox" rows="4" cols="50" name="comment" ></textarea>

<input type='submit' value='submit'>
</form>
</div>
</body>
</html>

A: When you return the render_template() function, you can add the variables as:
var1 = 'this is a test string'
return render_template("bk.html", var1 = var1)

In your bk.html file, include the following to show the variable where you want it shown.
{{ var1 }}

You can read more on http://jinja.pocoo.org/


text:
Q: 117/5000 Uploaded file to public_html in cpanel I tried uploading the first laravel projet in cpanel, when uploading image files can't enter public_html as I marked red, and I have changed the index.php file as shown below.
cPanel public_html
index.php

A: You should use Composer (and git) to deploy your project. Here's a guide that works well for shared hosting: https://github.com/petehouston/laravel-deploy-on-shared-hosting


text:
Q: $ionicPopup.show buttons onTap function not getting coverage in Angular Jasmine Unit Test When I call the outOfMvp() function in my unit test spec file, everything inside the function is getting coverage except for the onTap function.
I was wondering how to get coverage in my unit test for the button's onTap function which is in a JSON object being passed in $ionicPopup.show() method?
Here is the function in the js file:
function outOfMvp(data) {
  environmentConfig.isScanDataReadValid = false;
  popup = $ionicPopup.show({
    title: kioskConstants.POPUP_WORDING.OUT_OF_MVP_RETURN.title,
    template: data.returnRejectReasons[0].description
    + '.

' + kioskConstants.POPUP_WORDING.OUT_OF_MVP_RETURN.template
    + ' ' + data.orderNo + '',
    cssClass: 'popup-container-small',
    buttons: [
      {
        text: "OK",
        type: "bottom-button green narrow",
        onTap: function () {
          if ($state.current.name != "order-history") {
            environmentConfig.isScanDataReadValid = true;
            $rootScope.$broadcast("CancelConnectQR", data.orderNo);
            OrderInfo.init();
            $state.go(kioskConstants.ROUTE_STATE_LANDING_PAGE);
          }
        }
      }
    ]
  });
}

unit test for outOfMvp function in spec file:
describe('If call customPopupWidget.outOfMvp(data) function',function () {

it('it should call $ionicPopup.show().', function () {
  customPopupWidget.outOfMvp(data);
  expect(ionicPopup.show).toHaveBeenCalled();
});

coverage html file for the outOfMvp function:

A: You need to modify your code a little bit to ensure whether code works or not with help of unit testing.
Try this:
function outOfMvp(data) {
  environmentConfig.isScanDataReadValid = false;
  popup = $ionicPopup.show({
    title: kioskConstants.POPUP_WORDING.OUT_OF_MVP_RETURN.title,
    template: data.returnRejectReasons[0].description
    + '.

' + kioskConstants.POPUP_WORDING.OUT_OF_MVP_RETURN.template
    + ' ' + data.orderNo + '',
    cssClass: 'popup-container-small',
    buttons: [
      {
        text: "OK",
        type: "bottom-button green narrow",
        onTap: function () {
          return true;
        }
      }
    ]
  });
  popup.then(function(response){
     if(response){ //when response is true
       if ($state.current.name != "order-history") {
         environmentConfig.isScanDataReadValid = true;
         $rootScope.$broadcast("CancelConnectQR", data.orderNo);
         OrderInfo.init();
         $state.go(kioskConstants.ROUTE_STATE_LANDING_PAGE);
       }
     }
  })
}

And you can test the above code as follows:
describe('If call customPopupWidget.outOfMvp(data) function',function () {

it('it should call $ionicPopup.show().', function () {
  spyOn($ionicPopup, 'show').and.callFake(function() {
     return $q.resolve(true);
  })
  customPopupWidget.outOfMvp(data);
  expect(ionicPopup.show).toHaveBeenCalled();
});

Don't forget to inject $ionicPopup, $q else you will get error. And one thing you need to remember is that you won't get coverage for this code:
onTap: function () {
   return true;
}

But your code will be tested with logically complete coverage as it will test what you want to do when "Ok" button is tapped.


text:
Q: Boost gzip how to output compressed string as text I'm using boost gzip example code here.
I am attempting to compress a simple string test and am expecting the compressed string H4sIAAAAAAAACitJLS4BAAx+f9gEAAAA as shown in this online compressor
static std::string compress(const std::string& data)
{
    namespace bio = boost::iostreams;
    std::stringstream compressed;
    std::stringstream origin(data);

    bio::filtering_streambuf<bio::input> out;
    out.push(bio::gzip_compressor(bio::gzip_params(bio::gzip::best_compression)));
    out.push(origin);

    bio::copy(out, compressed);
    return compressed.str();
}

int main(int argc, char* argv[]){
    std::cout << compress("text") << std::endl;
    // prints out garabage

    return 0;
}

However when I print out the result of the conversion I get garbage values like      +I-. ~
I know that it's a valid conversion because the decompression value returns the correct string. However I need the format of the string to be human readable i.e. H4sIAAAAAAAACitJLS4BAAx+f9gEAAAA.
How can I modify the code to output human readable text?
Thanks
Motivation
The garbage format is not compatible with my JSON library where I will send the compressed text through.

A: The example site completely fails to mention they also base64 encode the result:
base64 -d <<< 'H4sIAAAAAAAACitJLS4BAAx+f9gEAAAA' | gunzip -

Prints:
test

In short, you need to also do that:
Live On Coliru
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <iostream>
#include <sstream>

#include <boost/archive/iterators/binary_from_base64.hpp>
#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/transform_width.hpp>

std::string decode64(std::string const& val)
{
    using namespace boost::archive::iterators;
    return {
        transform_width<binary_from_base64<std::string::const_iterator>, 8, 6>{
            std::begin(val)},
        {std::end(val)},
    };
}

std::string encode64(std::string const& val)
{
    using namespace boost::archive::iterators;
    std::string r{
        base64_from_binary<transform_width<std::string::const_iterator, 6, 8>>{
            std::begin(val)},
        {std::end(val)},
    };
    return r.append((3 - val.size() % 3) % 3, '=');
}

static std::string compress(const std::string& data)
{
    namespace bio = boost::iostreams;
    std::istringstream origin(data);

    bio::filtering_istreambuf in;
    in.push(
        bio::gzip_compressor(bio::gzip_params(bio::gzip::best_compression)));
    in.push(origin);

    std::ostringstream compressed;
    bio::copy(in, compressed);
    return compressed.str();
}

static std::string decompress(const std::string& data)
{
    namespace bio = boost::iostreams;
    std::istringstream compressed(data);

    bio::filtering_istreambuf in;
    in.push(bio::gzip_decompressor());
    in.push(compressed);

    std::ostringstream origin;
    bio::copy(in, origin);
    return origin.str();
}

int main() {
    auto msg = encode64(compress("test"));
    std::cout << msg << std::endl;
    std::cout << decompress(decode64(msg)) << std::endl;
}

Prints
H4sIAAAAAAAC/ytJLS4BAAx+f9gEAAAA
test


text:
Q: Почему не сравнивается элемент массива с вводимыми данными из клавиатуры? BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Введите букву от A до Z: ");
        String accept =reader.readLine();

String[] mas = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o",
                "p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I",
                "J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};

        if(accept==mas[3]) {
            System.out.println("Mission compled");
        }
        else System.out.println("LOL");
        System.out.println(mas[0]);
        System.out.println(accept);

Здесь мы вводим букв d
и программа должна вывести System.out.println("Mission compled"), но выводится второе сообщение, что говорит об ошибки.
Можете объяснить, почему при равных значениях, программа  не работает

A: Сравнивать строки нужно методом equals(). С помощью оператора == вы сравниваете ссылки на объекты String. И хотя эти объекты могут содержать одинаковое значение "d", это разные объекты. Напишите:
if (accept.equals(mas[3])) {...}


text:
Q: Memory usage concern when using HTTPS for web services or web requests EDIT: After a long discussion in the comments, it seems that my original question didn't really capture what was going on.  Here's a summary of where I am now:

*

*When using HTTPS, there's what I would consider a dramatic jump in the virtual memory space of my application (typically from under 50mb to over 200mb) when the first HTTPS request (web service call, WebClient.DownloadFile(), etc.) is made

*At the same time, a CPU core also moves to nearly 100% usage.  This typically only lasts a few seconds, but I have seen it last longer

*It may very well be the case that this is just the cost of using HTTPS, but I was surprised by it since I had never noticed it before in other apps (and other developers on my team never noticed it in this app, which has been using HTTPS since long before I came on board).

*The kicker: this doesn't appear to happen on all machines, but does on most.  If it happened consistently on every machine, I'd be more willing to accept it as a "cost of doing business."  But since there does seem to be a difference between some machines running the same code and OS, I would like to understand why that is since it will either a) allow us to mitigate the behavior, or b) explain it in a way that satisfies non-technical higher-ups that it's not actually a "problem", as explaining that Windows Task Manager shows virtual memory and not necessarily actively-in-use physical memory hasn't been satisfactory so far :/

I've left the original post intact below in case anyone is interested, but it focuses more on web services, which aren't really at the root of the problem.
Thanks in advance for any further insight!

We're seeing memory usage increase dramatically whenever our application first makes a call to our web service using https.  The specifics vary by machine, but as an example we may see our application jump from ~50mb to over 250mb when the first web service call is made, and the usage never climbs back down.  Subsequent calls do not result in another such jump.  I can reproduce the behavior with the code below (not specific to our application) and a public web service that we do not own - so it seems to be independent of both our client- and server-side code.
Interestingly, in my test app I don't observe this jump on Windows XP (our application is currently deployed only on Windows 7).  We also don't see it on every dev/test machine in the office (but we do on most), and we don't currently have a way to retrieve this info from machines out in the "real world."
I haven't been able to pin down what's being allocated, but several profilers have made it clear that it resides in native (not managed) memory.  Analysis of some WinDbg dumps using DebugDiag leaves me to believe that there is a lot of memory getting allocated in crypt32.dll that isn't being released.  This makes sense to some extent (https implies certificates, security, etc., and it's likely that whatever is being loaded is getting cached, hence why subsequent calls don't result in additional jumps), but I have a hard time believing this is really just the cost of using https for a web service.
I know there will be some responses from the "if higher memory usage isn't causing problems, why worry?" camp.  In general I agree - the memory usage numbers in Task Manager often aren't indicative of whether the app is working as intended.  If the app was used strictly in-house, I could live with this as long as it wasn't a symptom of other problems.  But our app is deployed with consumer machines, so we have to worry about the perception of a problem just as much as the actual problem.  So if there's any way to fix this, I would greatly appreciate it!
Finally, the web service that I use in the test code below is available here: http://ws.cdyne.com/emailverify/Emailvernotestemail.asmx?wsdl.  The code for EmailVerNoTestEmail was generated using the wsdl.exe tool, with the slight modification of passing the URL as a parameter to the constructor rather than hard-coding it (so that http/https can be specified on the fly).
public static void Main(string[] args)
{
    const string urlSuffix = "://ws.cdyne.com/emailverify/Emailvernotestemail.asmx";
    string protocol = null;
    while(protocol == null)
    {
        Console.Write("Enter protocol (http, https): ");
        var line = Console.ReadLine();
        if (line != null) line = line.ToLower();
        if (line == "http" || line == "https")
            protocol = line.Trim();
    }
    var url = protocol + urlSuffix;
    Console.WriteLine("Using URL: " + url);
    Console.Out.Flush();

    var service = new EmailVerNoTestEmail(url);

    Console.WriteLine("Press any key to make the web service call...");
    Console.ReadKey(true);

    Console.WriteLine("Calling web service...");
    var resp = service.VerifyEmail("test@gmail.com", "test");
    Console.WriteLine("Response: " + resp);

    Console.WriteLine("Press any key to exit.");
    Console.ReadKey(true);
}

A: Unless a system is stressed, it is natural for it to remain at a certain memory level. The OS has heuristics which determine how much memory is needed and allocates to that high point greater than what is needed. Why? It is expensive for allocation and deallocation of memory and if a program can run in its own sandbox which was given, why decrease it if the system is not stressed.
As you mentioned it is not the amount of memory allocated which is a concern, but it is the leaking of memory. I suggest you run perfmon and monitor for leaks; read up on the things to look out for in this MSDN CLR article Investigating Memory Issues.
EDIT: (This is advice I have given before but may be relevant/ sorry for topic duplication)
To see the telltale sign of memory leaks one fires up perfmon and looks at Private Bytes in perfmon for that those signs.  See Identify And Prevent Memory Leaks In Managed Code to begin that process.
One other process to use is on the Processes tab of the Windows Task Manager. ( View + Select Columns,) check Handles, GDI Objects and USER Objects.  Observe these values for your program.  If there is t a handle leak, you'll see one of these steadily climbing if you do.  GDI in all likelihood under those scenarios.   In general when the OS runs an application it tries to determine how much memory is being used. It will allocate more memory for the application that what the application currently needs. The reason for that is, to allocate/deallocate memory is a cpu intensive operation. Why parallel what the app needs when it can reside in a pool  of memory which will allow it, the app, to expand and contract with no interference from the operating system. Saves on cycles.  What the developer sees is a high water mark for memory. If the system is not stressed, the system will not reclaim any memory and keep the high water mark. There are many posts in this forum where the users say, processing done, memory cleaned up but the OS still shows my app at memory point X, when it should be memory point M (lower). Winform users report the same but if one minimizes the app, suddenly the mem usage reported drops to that M level. That is done by design. Minimizing suggests that an app doesn't need the memory for it will not be interacting with the user and the OS will reclaim the point. If its not a winform and the OS is not stressed, the app stays at the high water mark of X.


text:
Q: Does this Question Have Enough Information to Answer? I need to determine the equation of the function in the graph below.
Attached is a graph with x-intercepts at (-4, 0) and (3,0) and another point given at (2,10). I know its not quadratic. Are complex zeros involved, and if so how do I find them?

A: Your function, presumably a polynomial, seems to have roots at $-4$ and $3$, thus is divisible by $(x+4)(x-3)=x^2+x-12$. Assuming that it's of the minimal degree to have that shape, namely degree four, you can write it as $(ax^2+bx+c)(x^2+x-12)=ax^4+(a+b)x^3+(-12a+b+c)x^2+(-12b+c)x-12c$. But it also passes through the point $(2,10)$, so you can get a relation among the undetermined coefficients $a$, $b$, and $c$, namely $-24a - 12b - 6c=10$.
More than that, it seems that your function has a local minimum at $x=0$ and a local maximum at $x=2$. So when you evaluate $f'$ at $0$ and at $2$, you'll get $0$, and these two facts give you two more linear relations among $a$, $b$, and $c$. With the three relations, you can solve for the unknowns. I'll leave that to you.


text:
Q: how to auto-focus and auto-capture picture(Driver's License) with camera in android programmatically?
(source: idownloadblog.com)
I am developing an android app in which when i open camera intent, i would want something like this screen-shot from the app Keyring. Instead of the Bar Code, I want to capture a Drivers License. A border for the user to focus the card in, Auto-focus the image and Auto-Capture. Please give me direction! Any help will be appreciated.
Instead of Drivers License, i mistakenly put Credit Card earlier, sorry for the confusion.
Also, Can this be done with Action_Image_Capture Intent or do i have to open Camera object and create a preview and all?

A: Use card.io. It's an open library that you can implement into yoour app which will accomplish exactly what you are trying to do.


text:
Q: Variable definition in 'sh -c' I tried to define a variable in a 'sh -c' command string:
sh -c "TMP=??; echo $TMP;"

Nothing was printed.
Why can't I define a variable in a 'sh -c' string?

A: sh -c 'TMP=??; echo "$TMP"'

With double quotes around the sh -c code, the $TMP is expanded by the interactive shell before the sh -c code executes.  With single quotes, $TMP will be expanded inside the sh shell. (I've also properly quoted the $TMP variable expansion for echo).
Single quotes protects a string from variable expansions.
If you do not intend the ?? to be treated as a filename globbing pattern inside the sh -c script, then use
sh -c 'TMP="??"; echo "$TMP"'

A: sh -c 'TMP=??; echo $TMP;'

When using double quotes the parameter expansion occurs when the command line is built i.e. the shell does not see
TMP=??; echo $TMP;

as its parameter but
TMP=??; echo ;

if $TMP is empty in the calling shell environment.


text:
Q: Create form for function Html This is my problem, hope get some support for this.
This is my function.
function show(n,q)
{
  for(j=1;j<=n;j++)
  {
    s=j.toString().length;
    t=0;
    for(i=s-1;i>=0;i--)
    {
      t+=Math.pow((Math.floor(j/Math.pow(10,i))%10),q);
    }
    if(t==j){document.write(t+ " ");}
    else{document.write("");}
  }
}
show(1000,3);

With two inputs: number n and the exponent q it will solve all the numbers smaller than n which the sum of all the q-exponented of its digits is equal to itself.
For example: q=3, n=200, we have the number 153 because: 1^3 + 5^3 + 3^3 = 153
This function is OK, but due to my bad javascript skill, I dont know how to create a form alowing to enter n and q into 2 boxes, then click button "Show" we have results in the third box.
I have tried this below code, but it does not work :(
<input id='number' type='text' />
<input id='exp' type='text' />
<button onclick='javascript:show()'>Show</button>

In additon, I want to do it myself, could you guys tell me where i can find guide for this problem.
Thanks.

A: Your code has some punctuation issues.
Try to replace:
    var n=document.getElementById('number').value,
    var q=document.getElementById('exp').value,
      out=document.getElementById('res'),
        out.innerHTML="";

by
    var n=document.getElementById('number').value,
        q=document.getElementById('exp').value,
        out=document.getElementById('res');
    out.innerHTML="";

A: The code looks fine and will do what you are trying to do. Just there are some , (Comma) instead of ; (Semi-colon) in your code. Change them and then try.
Check the solution here.
http://jsfiddle.net/JszG2/
var n=document.getElementById('number').value;
var q=document.getElementById('exp').value;
out=document.getElementById('res');

A: Below is solution using JQuery....


text:
Q: connecting PBI to impala I created a cloudera cluster (ENTERPRISE DATA HUB) on azure. I can use the DNSname:7180  to view and manage cluster. However, I am not successfull in connecting to the Impala from PowerBI Desktop. I tried both VM names with dn0 and mn0 extension ([myhostname]-dn0.eastus2.cloudapp.azure.com) and ports 71890, 21000, 21050, based on this and this
It always fail at the authentication level. I tried anonymous, windows and DB authentication, and they all failed with this error:
Details: "ODBC: ERROR [08S01] [Microsoft][ImpalaODBC] (100) Error from the Impala Thrift API: connect() failed: errno = 10060"

Any help or clue is appreciated.

A: The port is 21050. You have to open it on Azure VM since it is not open by default.


text:
Q: ruby popen3 -- how to repeatedly write to stdin & read stdout without re-opening process? I am using Open3's popen3 method to start a process that functions in a console-like / REPL fashion to repeatedly accept input and return output.
I am able to open the process, send input, and receive the output just fine, with code like this:
Open3.popen3("console_REPL_process") do |stdin, stdout, stderr, wait_thr|
    stdin.puts "a string of input"
    stdin.close_write
    stdout.each_line { |line| puts line } #successfully prints all the output
end

I want to do that many times in a row, without re-opening the process, as it takes a long time to start up.
I know I have to close stdin in order for stdout to return.. but what I don't know is, how do I 'reopen' stdin so I can write more input?
Ideally I want to do something like this:
Open3.popen3("console_REPL_process") do |stdin, stdout, stderr, wait_thr|
    stdin.puts "a string of input"
    stdin.close_write
    stdout.each_line { |line| puts line }

    stdin.reopen_somehow()

    stdin.puts "another string of input"
    stdin.close_write
    stdout.each_line { |line| puts line }
    # etc..
end

solution
Thanks to pmoo's answer, I was able to devise a solution using PTY and expect, expecting the prompt string that the process returns whenever it is ready for more input, like so:
PTY.spawn("console_REPL_process") do |output, input|
    output.expect("prompt >") do |result|
      input.puts "string of input"
    end
    output.expect("prompt >") do |result|
      puts result
      input.puts "another string of input"
    end
    output.expect("prompt >") do |result|
      puts result
      input.puts "a third string of input"
    end
    # and so forth
end

A: You can have some success using expect library, and have the child process to explicitly mark the end of each output, like:
require 'expect'
require 'open3'

Open3.popen3("/bin/bash") do
    | input, output, error, wait_thr |
    input.sync = true
    output.sync = true

    input.puts "ls /tmp"
    input.puts "echo '----'"
    puts output.expect("----", 5)

    input.puts "cal apr 2014"
    input.puts "echo '----'"
    puts output.expect("----", 5)
end

As a bonus, expect has a timeout option.


text:
Q: Fast string counting in dplyr I need to count instances of a pattern (fixed) within a string that's held in a column in a tibble. mutate(x = str_count(col, pattern)) does exactly what I want but it's not fast enough to process the volume of strings I have to evaluate.
Simplified tibble
test = tibble(
  id=c(1,2,3),
  seq=c("ATCG","ATTT","CGCG")
)

Works but is too slow in microbenchmark testing
test %>% mutate(CpG = str_count(seq, "CG"))

Theoretically faster on single sequences but not working on my tibble column
This just gives the single value of the first row's count
test %>% mutate(CpG = sum(gregexpr("CG", seq, fixed=TRUE)[[1]] > 0))

I tried to get purrr::map to work, but I'm failing at it...here are my attempts that won't run:
test %>% mutate(CpG = map(~sum(gregexpr("CG", seq, fixed=TRUE)[[1]] > 0)))
test %>% mutate(CpG = map(seq, ~sum(gregexpr("CG", .x, fixed=TRUE)[[1]] > 0)))

Edit: Time Benchmarks
Looks like stringi::stri_count_fixed is the optimal choice on the test set.
microbenchmark(
  mutate(test, CpG = stringr::str_count(seq, "CG")),
  mutate(test, CpG = purrr::map_int(seq, ~sum(gregexpr("CG", .x, fixed=TRUE)[[1]] > 0))),
  mutate(test, CpG = Biostrings::vcountPattern("CG", DNAStringSet(seq))),
  mutate(test, CpG = lengths(regmatches(seq, gregexpr("CG", seq)))),
  mutate(test, CpG = stringi::stri_count_fixed(seq,"CG"))
)
Unit: microseconds
                                                                                expr     min       lq     mean   median       uq      max neval
                                             mutate(test, CpG = stringr::str_count(seq, "CG")) 125.502 133.9995 159.0844 147.9045 164.2925  441.242   100
 mutate(test, CpG = purrr::map_int(seq, ~sum(gregexpr("CG", .x,      fixed = TRUE)[[1]] > 0))) 167.210 183.4695 215.7746 202.8890 230.5275  450.177   100
                        mutate(test, CpG = Biostrings::vcountPattern("CG", DNAStringSet(seq))) 789.889 827.3810 955.8919 887.3400 989.7415 1845.212   100
                             mutate(test, CpG = lengths(regmatches(seq, gregexpr("CG", seq)))) 150.315 159.4750 178.9039 169.1840 185.1345  316.479   100
                                      mutate(test, CpG = stringi::stri_count_fixed(seq, "CG")) 112.015 120.6615 131.4281 125.0470 135.4330  213.184   100

And, here are the results with one portion of my real data (~20,000 instances of 1500 nt sequences) run on a remote server with ~3X the available RAM and cores of my initial run. I continue to be impressed with stringi's implementation, which somehow read through everything in blazing 20-something milliseconds.
Unit: milliseconds
                                                                                expr        min         lq       mean     median        uq        max neval
                                             mutate(test, CpG = stringr::str_count(seq, "CG"))  402.55513  408.04101  419.82213  414.31085  425.4113  481.08128   100
 mutate(test, CpG = purrr::map_int(seq, ~sum(gregexpr("CG", .x,      fixed = TRUE)[[1]] > 0)))  429.84148  436.02402  474.08864  438.84198  447.3058 1054.48253   100
                        mutate(test, CpG = Biostrings::vcountPattern("CG", DNAStringSet(seq)))  301.26062  309.76674  310.97071  310.08229  310.8837  336.12834   100
                             mutate(test, CpG = lengths(regmatches(seq, gregexpr("CG", seq)))) 1981.78309 1990.84206 2050.41928 1999.07389 2020.3675 2980.62566   100
                                      mutate(test, CpG = stringi::stri_count_fixed(seq, "CG"))   23.33313   23.55215   23.90881   23.66268   23.8916   27.40499   100

Since I could run this on the native DNAStringSet since my data starts out as a GRanges object, I microbenchmarked the vector of sequences, too, and got ranges in the 240-250 ms ballpark.
I have another use-case coming up with 1,000-100,000 nt long sequences with longer search patterns and will plan to update with those results when I move back to that project.

A: You can use Biostrings::vcountPattern
library(Biostrings)
test %>% mutate(CpG = vcountPattern("CG", DNAStringSet(seq)))
#  # A tibble: 3 x 3
#     id seq     CpG
#  <dbl> <chr> <int>
#1     1 ATCG      1
#2     2 ATTT      0
#3     3 CGCG      2

Biostrings::vcountPattern is considerably faster than the str_count solution for a vector of longer (DNA) strings; here are some microbenchmark results
# Sample data
df <- tibble(
    id = 1:100,
    seq = replicate(
        100,
        paste0(sample(c("A", "C", "G", "T"), 100000, replace = T), collapse = "")))

library(microbenchmark)
res <- microbenchmark(
    str_count = df %>% mutate(CpG = str_count(seq, "CG")),
    vmatchPattern = df %>% mutate(CpG = vcountPattern("CG", DNAStringSet(seq))))
#Unit: milliseconds
#          expr       min       lq     mean   median       uq      max neval
#     str_count 156.37642 162.1629 167.2005 164.4958 169.2456 251.3426   100
# vmatchPattern  95.68998 102.4176 108.2428 105.2501 108.5511 322.3143   100

library(ggplot2)
autoplot(res)

A: Try using stri_count_fixed from stringi library which is known to be faster than it's stringr counterparts.
test %>% mutate(CpG = stringi::stri_count_fixed(seq, 'CG'))

#     id seq     CpG
#  <dbl> <chr> <int>
#1     1 ATCG      1
#2     2 ATTT      0
#3     3 CGCG      2

Apart from that you can use map_int which will return an integer vector as compared to map which returns a list to use it with gregexpr.
library(dplyr)

test %>%
  mutate(CpG = purrr::map_int(seq, ~sum(gregexpr("CG", .x, fixed=TRUE)[[1]] > 0)))

Or another option is regmatches with gregexpr.
test %>% mutate(CpG = lengths(regmatches(seq, gregexpr("CG", seq))))

A: Using @MauritsEvers test dataset df, you can use oligoNucleotideFrequency in Biostrings.
library(Biostrings)
head(oligonucleotideFrequency(DNAStringSet(df$seq),2))
       AA   AC   AG   AT   CA   CC   CG   CT   GA   GC   GG   GT   TA   TC   TG
[1,] 6402 6147 6351 6190 6129 6081 6180 6232 6311 6222 6323 6341 6249 6172 6342
[2,] 6305 6320 6295 6217 6379 6253 6139 6291 6227 6279 6239 6163 6225 6210 6235
[3,] 6284 6352 6305 6133 6211 6293 6356 6231 6374 6286 6280 6202 6205 6160 6201
[4,] 6217 6253 6265 6300 6189 6296 6302 6175 6379 6275 6207 6195 6251 6137 6282
[5,] 6346 6315 6217 6291 6289 6060 6254 6223 6269 6203 6313 6259 6264 6248 6260
[6,] 6066 6216 6282 6286 6376 6339 6223 6156 6216 6235 6360 6241 6193 6304 6186
       TT
[1,] 6327
[2,] 6222
[3,] 6126
[4,] 6276
[5,] 6188
[6,] 6320

We just get the "CG" column:
library(microbenchmark)
res <- microbenchmark(
    str_count = df %>% mutate(CpG = str_count(seq, "CG")),
    vmatchPattern = df %>% mutate(CpG = vcountPattern("CG", DNAStringSet(seq))),
    oligo=df %>% mutate(CpG = oligonucleotideFrequency(DNAStringSet(seq),2)[,"CG"])
)

> res
Unit: milliseconds
          expr       min        lq      mean    median        uq      max neval
     str_count 129.73744 135.05308 140.01877 139.11458 144.47085 158.9793   100
 vmatchPattern  82.30784  88.48554  92.13986  93.01389  95.53329 107.3482   100
         oligo  57.25595  62.11515  67.63134  64.50559  66.99784 349.3443   100
 cld
   c
  b
 a

You already know what bases or dinucleotide to expect, so it's a matter of counting rather than string matching, making this faster.


text:
Q: How to find the index of element (and a few other things) I was writing a code that would substitute some random 17 character strings into a single alphabet, and I can't find a way. Basically, what I'm trying to do is this:
char strings[] = {
    "L-nIbhm5<z:92~+,x",
    "9bC5f0q@qA(RKZ>|r",
    "9bC5f0q@qA(RKZ>|r",
    "k=5,ln(08IAl(gGAK",
    "|N,8]dGu)'^MaYpu[",
    "!&,Y*nz8C*,J}{+d]",
    "Us9%^%?n5!~e@@*+@",
    "zF8,1KV#¥]$k?|9R#",
    "0B4>=nioEjp>4rhgi",
}

char alphabet[]{
    "a","b","c","d","e","f","g","h","i",
}

replace(std::string str){
    /**get str and then see the index of the corresponding string in strings[], and replace the string with alphabet[index number], while deleting the original string part that was replaced**/

int main(){
    cin >> std::string replace;
    replace(replace);

example input: L-nIbhm5<z:92~+,x9bC5f0q@qA(RKZ>|r9bC5f0q@qA(RKZ>|r
expected output: abc
EDIT:
New Code
Changes from the original code
It also has a bigger array than the simplified version(previous code). It displays the structure of the full program.(where the strings are routed to and why)
Basically What it's doing
getting input from user, put it in the input variable, input goes through algorithm() function untouched, and then goes to the replace function and is replaced. It then the replaced string gets returned back through the original route to the main function, where it is displayed.
I've kept the arrays a string type because the const char* gave me a segmentation error.
std::string Subs[53]=
{
    "LQlMv]G5^^1kcm?fk",
    "7W^S;/vB(6%I|w[fl",
    "<w7>4f//Z55ZxK'z.",
    "_W5g(lu<pTu3^_A7n",
    "OfLm%8:EF}0V1?BSS",
    "|+E6t,AZ~XewXP17T",
    "L-nIbhm5<z:92~+,x",
    "L-nIbhm5<z:92~+,x",
    "9bC5f0q@qA(RKZ>|r",
    "9bC5f0q@qA(RKZ>|r",
    "k=5,ln(08IAl(gGAK",
    "|N,8]dGu)'^MaYpu[",
    "!&,Y*nz8C*,J}{+d]",
    "Us9%^%?n5!~e@@*+@",
    "zF8,1KV#¥]$k?|9R#",
    "0B4>=nioEjp>4rhgi",
    "EG@0[W9.N4i~E<f3x",
    "(0Pwkk&IPchJHs.7A",
    "7XgmQ6fW<|J+NY[m0",
    ".g4CwX/DU!!~!zbtZ",
    "+_U'qn_/9Fo|gT/!n",
    "=0s(mYh&F%y=MBS5(",
    "cg71(}bo+Q5P8F[T6",
    "lc|a\%5.9pOpooU+QR",
    "E_(3A:o+.]qL3MYA6",
    "H@O'X_RiVS@8l0bKD",
    "Y1gbGD`~8d>HSWN35",
    "LQlMv]G5^^1kcm?fk",
    "T4}gI;`BFVfhw=-sf",
    "6BHMA0IRix]/=(jht",
    "yS$=@Jdpp?P2k6SMQ",
    "t1~|kkh+>4d>}OQ`a",
    "2Y-\\CU\"944yBluWD5",
    "'M\\ZbIX5{`Xd;qi!o",
    "?N+RtVqj_r(C5@#0\"",
    "2;*Livh?V$X/8z@Md",
    ")IN|7FOs2l-mAM[d@",
    "(~f268J},xXrK'Rp'",
    "&r/qf9fFHnzV!RzH/",
    "}naDRH4p$NI2a).t,",
    "{8DM+7!.Mge|~fnO|",
    ")r[@nI0YDH>6cE38p",
    "(0Pwkk&IPchJHs.7A",
    ")r[@nI0YDH>6cE38p",
    "8M-=cQFQ,pPo7eu=p",
    "0PHw=/|(tZ1}FHm/'",
    "[su`'0Oybc.\"-/W5)",
    "1uHl[IC7Sr#NUJV;I",
    "8z8%,jK0CDOkJz8I?",
    "3Ao2yXDN%YzpE&Suy",
    "zNs`7E'e/$i8VqaUL",
    "bzHmA^K2>7`UZ?!AO",
};

std::string Alphabet[53] =
{
    " ","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","r","w","x","y","z",
    "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z",
};

std::string replace(std::string rep) {
    int len = sizeof(Subs)/sizeof(Subs[0]);
    std::stringstream ss1;
    for(int i = 0; i < len; i++) {
        if (rep.find(Subs[i]) != std::string::npos) {
            ss1 << Subs[i];
        }
    }
    std::string input = ss1.str();
    return input;
}

std::string algorithm(std::string input)
{
    //some other algorithms come here(not relative to this question)
    input = replace(input);
    return input;
}

int main(void){
    int ed;
    std::cin >> ed;

    if(ed == 1){
//different function(not relative to the question)
        }
    else if(ed == 0){
        std::string input;
        std::cin >> input;
        input = algorithm(input);
        std::cout << input << std::endl;
    }

    else{
        std::cout << "1 or 0" << std::endl;
        main();
    }

return 0;
}

example input: L-nIbhm5<z:92~+,x9bC5f0q@qA(RKZ>|r9bC5f0q@qA(RKZ>|r
expected output: abc
actual output: L-nIbhm5<z:92~+,xL-nIbhm5<z:92~+,x9bC5f0q@qA(RKZ>|r9bC5f0q@qA(RKZ>|r
Sorry it's become long.

A: There are few mistakes in above code :

*

*char array initialization is not correct.

*method body for main and replace method is not closed.

*Currently by default return type of replace method is int.

There is string#find method which can be helpful here.
I have tried to make those fixes and here is updated code in C++17 :
#include <iostream>
#include <sstream>
using namespace std;

const char *strings[9] = {
    "L-nIbhm5<z:92~+,x",
    "9bC5f0q@qA(RKZ>|r",
    "9bC5f0q@qA(RKZ>|r",
    "k=5,ln(08IAl(gGAK",
    "|N,8]dGu)'^MaYpu[",
    "!&,Y*nz8C*,J}{+d]",
    "Us9%^%?n5!~e@@*+@",
    "zF8,1KV#¥]$k?|9R#",
    "0B4>=nioEjp>4rhgi"
};

const char *alphabet[9] = {
    "a","b","c","d","e","f","g","h","i"
};

void replace(std::string rep) {
    int len = sizeof(strings)/sizeof(strings[0]);
    std::stringstream ss1;
    for(int i = 0; i < len; i++) {
        if (rep.find(strings[i]) != std::string::npos) {
            ss1 << alphabet[i];
        }
    }
    std::cout << ss1.str();
}

int main(){
    std::string rep;
    cin >> rep;
    replace(rep);
}

For reference : https://onlinegdb.com/Bd9DXSPAa
Note - Above code is just for reference, please make sure to add all test cases handling.

A: I made a c++17 version for your code.
Replacing 'c' style arrays and pointers with C++ style containers, iterators.
And using std::string::replace function. Use the standardlibrary if you can,
its tested and well documented.
#include <algorithm>
#include <iostream>
#include <regex>
#include <string>
#include <vector>

// std::vector/std::array instead of 'c' style arrays.
// allows us to us range based for loops later.
std::vector<std::string> strings =
{
        "L-nIbhm5<z:92~+,x",
        "9bC5f0q@qA(RKZ>|r",
        "k=5,ln(08IAl(gGAK",
        "|N,8]dGu)'^MaYpu[",
        "!&,Y*nz8C*,J}{+d]",
        "Us9%^%?n5!~e@@*+@",
        //"zF8,1KV#¥]$k?|9R#", // <<== I commented out this line, ¥ is not a valid charcter in my environment
        "0B4>=nioEjp>4rhgi"
};

// a string is already an array of characters.
std::string alphabet{ "abcdefghijkl" };

std::string replace_with_alphabet(const std::string& input)
{
    std::string retval{ input };
    std::size_t index{ 0 };

    // range based for, it will keep the order of the vector.
    for (const auto& str : strings)
    {
        // look if you can find any of the predefined strings
        // in the input strings.
        const size_t pos = retval.find(str, 0);

        // if found
        if (pos != std::string::npos)
        {
            // get the next character from the alphabet
            std::string replacement{ alphabet[index++] };

            // use std::string::replace for replacing the substring
            const size_t len = str.length();
            retval.replace(pos, len, replacement, 0);
        }
    }

    return retval;
};

/**get str and then see the index of the corresponding string in strings[], and replace the string with alphabet[index number], while deleting the original string part that was replaced**/
int main()
{
    auto output = replace_with_alphabet("L-nIbhm5<z:92~+,x9bC5f0q@qA(RKZ>|rk=5,ln(08IAl(gGAK");
    std::cout << output << std::endl;
}


text:
Q: Check if string contains the same pattern How can I check if a string has a specific pattern like this?

XXXX-XXXX-XXXX-XXXX

4 alphanumeric characters then a minus sign, 4 times like the structure above.
What I would like to do is that I would like to check if a string contains this structure including "-".

I'm lost, can anyone point me in the correct direction?
Example code:
$string = "5E34-4512-ABAX-1E3D";

if ($pattern contains this structure XXXX-XXXX-XXXX-XXXX) {
echo 'The pattern is correct.';
}

else {
echo 'The pattern is invalid.';
}

A: Use regular expressions
<?php
$subject = "XXXX-XXXX-XXXX-XXXX";
$pattern = '/^[a-zA-Z0-9]{4}\-[a-zA-Z0-9]{4}\-[a-zA-Z0-9]{4}\-[a-zA-Z0-9]{4}$/';
if(preg_match($pattern, $subject) == 1);
    echo 'The pattern is correct.';
} else {
    echo 'The pattern is invalid.';
}
?>

[a-zA-Z0-9] match a single character
{4} matches the character Exactly 4 times
\- matches a escaped hyphen

A: use preg_match :
$ok = preg_match('/^([0-9A-Z]{4}-){3}[0-9A-Z]{4}$/', $string)
And if you want to consider lowercase characters, use :
$ok = preg_match('/^([0-9A-Z]{4}-){3}[0-9A-Z]{4}$/i', $string)

A: With a perl regexp :
$string = "5E34-4512-ABAX-1E3D";

if (preg_match('/\w{4}-\w{4}-\w{4}-\w{4}/',$string)) {
    echo 'The pattern is correct.';
}


text:
Q: Passing cookies from Selenium to Python Requests I am making a Python 3-script with Selenium 4 and Gecko web driver.
I am using cookies = driver.get_cookies() to capture cookies after logging in to a site.
The question is how I can cookies from Selenium in a GET request using the Requests module.
In other words, how can we capture cookies with Selenium and use those cookies in Requests?
I tried the suggested answer in this question, but it is not correct and the question is over a year old without any other answers...

A: Try this way:
cookies = driver.get_cookies()
requests_cookies = {}
for c in cookies:
    requests_cookies[c['name']] = c['value']

response = requests.get('http://some-host...', cookies=requests_cookies)

Reference:
https://medium.com/geekculture/how-to-share-cookies-between-selenium-and-requests-in-python-d36c3c8768b


text:
Q: How to keep a video playing between beamer frames? I am currently creating a presentation where in a specific section I want to introduce a specific problem.
I do it by adding a video playing on the background and updating \minipage contents on the right side of the video.
I can include a video in my presentation without problems using \usepackage{multimedia} and the \movie command.
See the extracted part of my code below (hope it works I did not try it):
\documentclass{beamer}
\usepackage{graphics}
\usepackage{multimedia}

\begin{frame}{Pulling hose problem}
  \begin{minipage}{0.55\textwidth}
    \begin{center}
      \movie[autostart,loop,continue]{
        \includegraphics[width=\linewidth, keepaspectratio]{anImage.png}
      }{aMovie.mpg}

    \end{center}
  \end{minipage}  \hfill
%
\only<1>{
  \begin{minipage}{0.4\textwidth}
    \textbf{\color{txtcolor2} Setup :}
    \begin{itemize}
      \item HRP-2 humanoid robot
      \item rigid, \emph{empty} fire hoze
      \item motion capture system
    \end{itemize}
  \end{minipage}
}
%
\only<2>{
  \begin{minipage}{0.4\textwidth}
    \textbf{\color{txtcolor2} Major technical issues while}
    \begin{itemize}

    \item \textbf{\color{txtcolor2} pulling :}
    \begin{itemize}
      \item Important drift
      \item Robot less balanced
    \end{itemize}

    \item \textbf{\color{txtcolor2} picking :}
      \begin{itemize}
        \item Self-collision
        \item Joint limit
        \item Balance
      \end{itemize}

    \end{itemize}
  \end{minipage}
}
%
\only<3>{
  \begin{minipage}{0.39\textwidth}
    \textbf{\color{txtcolor2} Objectives :}
    \begin{itemize}
      \item Pick up a rigid fire hose
      \item Pull it toward a desired position
    \end{itemize}
    \vspace*{0.7cm}
  \end{minipage}
}
%
\end{frame}

\end{document}

The problem here is that Beamer will create several slides with the only<> instruction.
And the video will start again form time 0 each time I update the only<> part of the slide.
The question is :
Is there a way to keep the video playing while updating the slide?
I have been circling around with google I found only topics about embedded video in slide....
If someone knows if it is possible or not possible please tell me.

A: I think, keep the video playing will conceptional not be possible, as every overlay is an individual page in the pdf. However you could play a segment of the video in each overlay. So if for example the first frame should show the first minute and the second the second minute:

*

*the time range per overlay can be specified with start=0s,duration=60s

*to automatically switch slides \animate<1-2> \transduration<1-2>{60.0}
(Untested due to missing video file)
\documentclass{beamer}
\usepackage{multimedia}

\begin{document}

    \begin{frame}{Pulling hose problem}
        \animate<1-2>%
        \transduration<1-2>{60.0}%

        \begin{minipage}{0.55\textwidth}
            \centering
            \only<1>{
                \movie[autostart,loop,continue,start=0s,duration=60s ]{\includegraphics[width=\linewidth, keepaspectratio]{anImage.png}}{aMovie.mpg}
            }
            \only<2>{
                \movie[autostart,loop,continue,start=60s,duration=60s ]{\includegraphics[width=\linewidth, keepaspectratio]{anImage.png}}{aMovie.mpg}
            }
        \end{minipage}
        \hfill
        %
        \only<1>{
            \begin{minipage}{0.4\textwidth}
                1
            \end{minipage}
        }
        \only<2>{
            \begin{minipage}{0.4\textwidth}
                2
            \end{minipage}
        }

\end{frame}

\end{document}


text:
Q: Invalid Code Signing Entitlements on ITC after code signing with xctool and xcodebuild in build scripts I'm writing some build scripts for a continuous-integration situation where the code will be deployed on another machine, and needs to be able to build and correctly sign an Xcode Project, followed my a scripted upload to ITC.  So far I was able to work out the build and archive to .ipa, verify the code signing, but ITC is failing with the following error.  Why would this error be occurring and what can I add to fix this situation?
Error on ITC after upload of .ipa:
Invalid Code Signing Entitlements. The entitlements in your app bundle signature do not match the ones that are contained in the provisioning profile. According to the provisioning profile, the bundle contains a key value that is not allowed: '[ "AAAAAAAA.com.domain.Product" ]' for the key 'keychain-access-groups' in 'Payload/Product.app/Product'"
Note that on the target build machine I install the .mobileprovision file in "$HOME/Library/Provisioning Profiles", and create a custom keychain that has the relevant .cert and .p12 private key, such that the build can sign the file.  This took quite a bit of finagling until xctool finally recognized the key and profile.
I'm using the same Distribution App Store certificate and provisioning profile that I can use on Xcode on my machine, where this works fine.
Here is how I'm building the code and archiving the ipa.
xctool -project ./$PROJECT_NAME.xcodeproj
       -scheme $SCHEME
       -configuration Release
        CODE_SIGN_IDENTITY="${IDENTITY}"
        PROVISIONING_PROFILE="${PROVISIONING_PROFILE_UUID}"
        OTHER_CODE_SIGN_FLAGS="--keychain $HOME/Library/Keychains/$KEYCHAIN"
        clean archive
        -archivePath ./$PROJECT_NAME.xcarchive

xcodebuild -exportArchive -archivePath ./$PROJECT_NAME.xcarchive
           -exportPath $PROJECT_NAME
           -exportFormat ipa
           -exportProvisioningProfile "$PROVISIONING_PROFILE_NAME"

I'm also able to verify the unziped ipa app is signed, if that means anything.  It certainly fails if the signing doesn't occur as above.
$codesign --verify -vvvv Payload/Product.app
Payload/Product.app: valid on disk
Payload/Product.app: satisfies its Designated Requirement

EDIT:
I did a build/archive/export using XCode, which is accepted by ITC, and compared the result to the build generated by the scripts.
The scripted ipa is missing a file, archived-expanded-entitlements.xcent.  This seems to be the root of the problem.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>application-identifier</key>
    <string>AAAAAAA.com.domain.Product</string>
    <key>keychain-access-groups</key>
    <array>
            <string>AAAAAAA.com.domain.Product</string>
    </array>
</dict>
</plist>

A: Here is the fix I found that has worked.
Original .ipa creation line
xcodebuild -exportArchive -archivePath ./$PROJECT_NAME.xcarchive -exportPath $PROJECT_NAME -exportFormat ipa -exportProvisioningProfile "$PROVISIONING_PROFILE_NAME"

Replaced with this line:
xcrun -sdk iphoneos PackageApplication ./$PROJECT_NAME.xcarchive/Products/Applications/$PROJECT_NAME.app -o `pwd`/$PROJECT_NAME.ipa --sign "$IDENTITY" - -embed "$PROVISIONING_PROFILE_FILE"

This also required setting the "Code Signing Resource Rules Path" setting in Xcode to have a value of "$(SDKROOT)/ResourceRules.plist", since it throws an error about this otherwise.  Not happy with needing to do this for every project, but it's a one time thing and solved the problem.


text:
Q: Is this a bug in IE? I'm replicating a scenario from my application,
HTML:
<input type='text' disabled='true' />
<input type='text' disabled='true' />
<input type='text' disabled='true' />
<input type='text' disabled='true' />

    <input type='text' disabled='true' />

<input type='text' disabled='true' />

I want to enable these elements on a button click, the equivalent js,
var x = document.querySelectorAll('input[type="text"]');
var p = document.querySelector('#test');
[].slice.call(x);

for (var i = 0; i < x.length; i++) {
    p.innerHTML += x[i].getAttribute("disabled") + " ";

    x[i].removeAttribute("disabled");
}

Works fine in all browsers,
but, in IE, the input with it's parent disabled, appears disabled, but isn't.
Any explanation as to why this is happening?
I do realize that disabled is not a valid property for a div, but IE should ignore such a property?
JSFiddle

A: This doesn't conclude it is a bug but gives a little more insight into things.
http://www.techtamasha.com/the-disabled-attribute-in-internet-explorer/256
Directly from that article:

'disabled' attribute only works on BUTTON INPUT, OPTGROUP, OPTION,
  SELECT, and TEXTAREA tags and the general policy of browser is if you
  use any attribute which are not authorized to use in tag then browsers
  neglect them but they can be accessed using javascript. But IE isn't
  that kind in this case. If you apply 'disabled' on div tag, IE takes
  it seriously and makes div tag disabled. So what this means is that we
  not only have any control event on div but also according to "This
  attribute is inherited but local declarations override the inherited
  value." rule in W3C disable specification, IE applies disabled
  attribute on nested elements in div tag. So be careful.


text:
Q: ENOENT while creating a UNIX socket in Ruby I'm trying to create a socket in Ruby using
require "socket"
w = UNIXSocket.new("socket")

and I keep running into
No such file or directory - socket (Errno::ENOENT)

This looks completely backwards to me, because new() is supposed to create that missing file. What am I missing?

A: This is super old. Please don't try to use it verbatim anymore.
http://blog.antarestrader.com/posts/153
#!/ruby
file = 'path/to/my/socket'
File.unlink if File.exists(file) && File.socket?(file)
server = UNIXServer.new(file)
# return a UNIXSocket once a connection is made
socket = server.accept
# socket is now ready to communicate.

UnixServer makes the socket, UnixSocket only connects to an existing socket.


text:
Q: Loading shared model in ui-router states Is there any better way to load ashared model before the state change?
....
....
.state('state1',{
      ...
      resolve : {
           student : function($stateParams,StudentModel,StudentService){
                  return StudentService.getStudentById($stateParams.studentId).then(
                       function(response){
                            return StudentModel.loadStudent(response.data);
                       }
                  );
           }
      }
}).....
.....
...

In my current application, I use resolve attribute to load all my shared data models so that no controllers/directives will be executed before the  StudentModel is populated. But here, For the sake of loading StudentModel, I'm creating a resolved object (student in this case) in the state which I'm not going to use anywhere else.
Is there any better way to load my shared models before other controllers/directives are loaded for a particular state?
[Note : I am using angular 1.4.2 version ]
Update: Sorry that I missed return statement in the code above which has created some confusion. My question is not about to make the above code work.  Is there any alternative way for the same behaviour ? because in this design, I have to create a resolve object (student) which is not going to be used anywhere and StudentModel is the one which is used everywhere.

A: As such you haven't implemented promise function correctly. It should return promise to wait view to render.
Code
student: function($stateParams, StudentModel, StudentService) {
  return StudentService.getStudentById($stateParams.studentId).then(
    function(response) {
      return StudentModel.loadStudent(response.data);
    }
  );
}

Other than this, can you please elaborate on below line from question?

Is there any better way to load my shared models before other    controllers/directives are loaded for a particular state?

A: You need to return a $promise in the resolve so that the data can be loaded before the controller is created.
  resolve : {
       student : function($stateParams,StudentModel,StudentService){
              StudentService.getStudentById($stateParams.studentId).$promise;
       }
  }

Then in your controller you need to get the students from the parameter.
var StudentController = function(student, $scope) {
     ....
}
app.controller("StudentController", ["student", "$scope", StudentController]);


text:
Q: email validation function not working with element[x] in javascript form validation I added this validate email function here at the top, and i don't know how to make it ref. element[6] which is the email field in the form, and I'm not sure what the
return re.test(email);

statement is all about
here is the full script code:
<script type="text/javascript">

function validateEmail(email) {
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\
".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA
-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
}

function validation(form) {
  if(form.elements[3].value == '' ) {
      alert('Please enter your first name');
      form.first_name.focus();
      return false;
  }

  if(form.elements[4].value == '') {
      alert('Please enter your last name');
      form.last_name.focus();
      return false;
  }

  if(form.elements[6].value == '') {
      alert('Please enter your email address');
      form.email.focus();
      return false;

  if (validateEmail(email)) {
    $("#result").text(email + " is a valid email address :)");
    $("#result").css("color", "green");
  } else {
    $("#result").text(email + "is not a valid email address :(");
    $("#result").css("color", "red");
    return false;
  }

  if(form.elements[7].value == '') {
      alert('Please enter your telephone number');
      form.phone.focus();
      return false;
  }

  if(form.elements[17].value == '') {
      alert('Please let us know what you are most interested in');
      form.phone.focus();
      return false;
  }

  if(form.elements[18].value == '') {
      alert('Please enter the area you are most interested in');
      form.phone.focus();
      return false;
  }

  if(form.elements[20].value == '') {
      alert('Please enter the low end of your budget');
      form.phone.focus();
      return false;
  }

  if(form.elements[21].value == '') {
      alert('Please enter the high end of your budget');
      form.phone.focus();
      return false;
  }

  return true;
}
</script>

A: The function:
function validateEmail(email) {
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\
".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA
-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
}

has a regex object (re), the regex object uses the test function to test if the email passed into the function validates according to the regex. the test function returns true if it validates as an email and false if it doesnt.
you can use it like this:
if(!validateEmail(form.elements[6].value)) {
  alert('Please enter a valid email address');
  form.email.focus();
  return false;
}

The test function is native to regex objects, meaning your browser will know what to do with it (specs for the test function: developer.mozilla.org/en/JavaScript/Reference/Global_Objects/ )

A: Inside you validation() function variable email that is being passed to validateEmail is pretty much undefined.
You should either:
validateEmail(form.email.value);

OR
validateEmail($('#email').val()); // considering that `email` field has id="email"

Hope this helps...

A: form.elements was the way you selected DOM elements in 1996. You should be using document.getElementById instead:
var resultElement = $("#result");
var emailVal = document.getElementById('emailBoxId').value;
if (validateEmail(emailVal )) {
    resultElement
      .text(emailVal + " is a valid email address :)")
      .css("color", "green");
} else {
    resultElement
      .text(emailVal + "is not a valid email address :(")
      .css("color", "red");
    return false;
}

A: Create a variable email and set its value to form.elements[6].value
e.g.
function validation(form) {
  if(form.elements[3].value == '' ) {
    alert('Please enter your first name');
    form.first_name.focus();
    return false;
  }
  //...
  var email = form.elements[6].value
  if (validateEmail(email)) {
    $("#result").text(email + " is a valid email address :)");
    $("#result").css("color", "green");
  } else {
    $("#result").text(email + "is not a valid email address :(");
    $("#result").css("color", "red");
    return false;
  }
 //...
}