text:
Q: Is this polymorphic behaviour okay? I have a super class with one common method for its subclasses and this method will internally a call an abstract method. Code is working fine, but help me decide whether this design is ok.
All the subclasses are doing the same operation but they are servicing different clients. So I cannot put all other methods as common in the super class. Is this polymorphic approach is allowable?
code below:
class A{
public void insertEmployee(Employee emp){
}
public void updateEmployee(Employee emp){
}
public void deleteEmployee(Employee emp){
}

public collection getAll(){
    getAllHelper();
    return collection;
}

public collection  getAllHelper(){
    return collection;
}

}

class B{

public void insertEmployee(Department emp){
}

public void updateEmployee(Department emp){
}

public void deleteEmployee(Department emp){
}
public collection getAll(){
    getAllHelper();
    return collection;
}
public collection  getAllHelper(){
    return collection;
}
}

Then i introduced a new class
abstract class c{
public collection getAll(){
  return collection;
}
public abstarct collection getAllHelper();
}

so A and B extends C , is this ok ?
thank you all

A: It is not clear what you mean by "All subclasses are doing the same operation"
if all your subclasses are performing the same function (executing identical code) there is no polymorphism.
Polymorphism comes into play if you have subclasses that are different from each other in behavior , yet still use the same method signature to override a base class behavior.
eg:
Class Base { abstract void doWork() },
Class A extends Base
{
 void doWork() { Read from file and process }
}

Class B extends Base
{
 void doWork { Read from Network and process }
}

There is a code fragment which take a collection of Base objects
and executes them one by one without knowing the exact subtype.
Class Processor{
 void process ( List<Base> baseList)
 {
   for ( Base b: baseList){
    b.doWork();
    // Note: This is where polymorphism comes into action
    // At run-time A or B instances will be executed with appropriate doWork methods
   }
 }
}

In this case, polymorphic behavior of the method doWork comes into play.
http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming

A: its not that clear from your question (maybe some code would help :)), but yes this seems like  an acceptable approach, in that the consumer does not care which subclass is used, as they all inherit from the same abstract base class.
You might also consider making the base class implement an interface, so you are decoupled from the implementation even more, and only need to satisfy the contact of the interface.
This might help if you find you need another implementation which (for some reason) cannot be satisfactorily implemented just by overriding the abstract method .  If you are only reliant on the interface then you can provide another implementation which does not derive from the super class, but still implements the interface and everything will still be ok.


text:
Q: Is there a way to override a dunder method of a class so that the objects can be written in an Excel sheet with xlwings in Python? I have created a very simple class representing a period with a start date, an end date and a corresponding name.
I have a dataframe that has as columns instances of this class and I want to print this dataframe in Excel. I want the name of the period to be written, however the following error occurs:
TypeError: Objects of type 'Period' can not be converted to a COM VARIANT (but obtaining the buffer() of this object could)
Is there any other way to do this than renaming the columns by replacing the instances with their names?
Below is my Period class and the code that raises the error.
class Period:
    def __init__(self, start_date, end_date, period_name):
        self.start_date = start_date
        self.end_date = end_date
        self.period_name = period_name

    def __str__(self):
        return str(self.period_name)

    def __repr__(self):
        return f'Period(start_date={self.start_date},end_date={self.end_date},period_name={self.period_name})'

    def __lt__(self, other):
        return self.start_date < other.start_date

    def __gt__(self, other):
        return self.start_date > other.start_date

    def __eq__(self, other):
        return self.start_date == other.start_date

    def __hash__(self):
        return hash(self.period_name)

The code I would perform :
import datetime as dt

import pandas as pd
import xlwings as xw

period_info = [{'start_date':dt.datetime(2021,1,1),'end_date':dt.datetime(2022,1,1),'period_name':'1Y'},
               {'start_date':dt.datetime(2019,1,1),'end_date':dt.datetime(2022,1,1),'period_name':'3Y'}]

list_of_period = [Period(**period_param) for period_param in period_info]

df = pd.DataFrame(data=[[1,2],[3,4]],columns=list_of_period)

wb = xw.Book()
wb.sheets[0].range('A1').value = df

Thanks.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Variable is already defined with local variables? How? This is my code for checking a register page. It says that variables i and j are already defined, although it's local variables and not global. What could I do in this situation? How can I make the vars locally and not globally? Help is really appreciated, I am a new student in Computer Science.
function checkName() { // בודק על
    var n = document.getElementById("FullName").value;
    var len = n.length;
    var no = "!@#$%^&*()-_+=\'|][}{><./,;:?,";
    var num = "0123456789";
    if (n == "") {
        document.getElementById("errName").innerHTML = "רשום את השם בבקשה";
        return false;
    }
    for (var i = 0; i < n.length; i++) {
        if (n.charAt(i) == " ") {
            len--;
        }
    }
    if (len < 2) {
        document.getElementById("errName").innerHTML = "לא הגיוני שם עם אות אחת";
        return false;
    }
    for (var i = 0; i < n.length; i++) {
        if (n.charAt(i) >= "a" && n.charAt(i) <= "z") {
            document.getElementById("errName").innerHTML = "לא הגיוני שם עם אותיות באנגלית";
            return false;
        }
    }
    for (var i = 0; i < no.length; i++) {
        for (var j = 0; j < n.length; j++) {
            if (no.charAt(i) == n.charAt(j)) {
                document.getElementById("errName").innerHTML = "אסור תווים מיוחדים";
                return false;
            }
        }
    }
    for (var i = 0; i < num.length; i++) {
        for (var j = 0; j < n.length; j++) {
            if (num.charAt(i) == n.charAt(j)) {
                document.getElementById("errName").innerHTML = "אסור מספרים";
                return false;
            }
        }
    }
    for (var i = 0; i < 3; i++) {
        if (n[i] == ' ') {
            document.getElementById("errName").innerHTML = "אסור רווחים בהתחלה";
            return false;
            if (n[i + 1] == ' ') {
                document.getElementById("errName").innerHTML = "אסור רווחים בהתחלה";
                return false;
            }
        }
    }
    document.getElementById("errName").innerHTML = "";
    return true;
}

A: Javascript has function scope, so defining any variable in a function with var will make it exist throughout the function.
In each for loop, you redefine i with var i = 0. For example:
for (var i = 0; i < n.length; i++) {
    if (n.charAt(i) == " ") {
        len--;
    }
}
...

for (var i = 0; i < num.length; i++) {
    for (var j = 0; j < n.length; j++) {
        if (num.charAt(i) == n.charAt(j)) {
            document.getElementById("errName").innerHTML = "אסור מספרים";
            return false;
        }
    }
}

You can add a var i; at the top of the function instead, and simply say i=0 in your loops, so you don't define it multiple times.
Consider looking into using let in newer JS versions.

A: Try to use new ES6 let instead of var to declare a variables in your functions/project.
This will solve your issue with global name scope.
You can read more here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

A: You need to look into function scoping. As var has scope of function in which it is defined.
So in your case variable i has access inside checkName function. Using let will help you out in above scenario.


text:
Q: How to access value from Datepicker to change button title according to date picker value? I am working on project in which I have to set button title by According to datepicker value.
My design is like below

Now my code is like below
This is button which I set into tableviewCell
  let btn_start_time = cell.viewWithTag(2) as! UIButton
  btn_start_time.addTarget(self, action: #selector(btnStartTimePressed), forControlEvents: .TouchUpInside)

This is my button action method when I clicked
func btnStartTimePressed(sender: UIButton!)  {
        let buttonPosition = sender.convertPoint(CGPointZero, toView: self.tbl_availability)
        let indexPath = self.tbl_availability.indexPathForRowAtPoint(buttonPosition)
        UtilityHandler.addpopupZoomAnimationTopickerView(view_time_picker, view: self.view)
        time_picker.addTarget(self, action: Selector(datepickeractionmethod(time_picker)), forControlEvents: .ValueChanged)
        sender.setTitleColor(BUTTON_BLACK_COLOR_222222, forState: .Normal)
        sender.setTitle(strDate as String, forState: .Normal)
}

This is my datepicker Action method
 func datepickeractionmethod(sender : UIDatePicker) {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "hh:mm a"
        strDate = dateFormatter.stringFromDate(self.time_picker.date)
 }

I want to change button title when datepicker value is changed.
I tried
1) I take extra parameter as button into datepicker action method and set title there but it also changed when I clicked on button , NOT WHEN MY DATEPICKER VALUES CHANGE
2) I try to set into button action method but it worked when I clicked on button.
Please help me with it.

A: Make one enum and make its instance to check which picker is currently shown is it startTime or endTime, also create two String instance for holding the values from picker.
enum TimeType {
    case StartTime
    case EndTime
}

var timeType: TimeType?
var startTime = "Start Time"
var endTime = "End Time"

Now use this two strings object in cellForRowAt indexPath.
let btn_start_time = cell.viewWithTag(2) as! UIButton
btn_start_time.addTarget(self, action: #selector(btnStartTimePressed), forControlEvents: .TouchUpInside)
btn_start_time.setTitle(startTime, for: .normal)

let btn_start_time = cell.viewWithTag(3) as! UIButton
btn_start_time.addTarget(self, action: #selector(btnEndTimePressed), forControlEvents: .TouchUpInside)
btn_start_time.setTitle(endTime, for: .normal)

Now set the enum instance in the button action.
func btnStartTimePressed(sender: UIButton!)  {
   UtilityHandler.addpopupZoomAnimationTopickerView(view_time_picker, view: self.view)
    time_picker.addTarget(self, action:#selector(datepickeractionmethod(_:)), forControlEvents: .ValueChanged)

    //Set which picker is Shown
    timeType = .StartTime
}

func btnEndTimePressed(sender: UIButton!)  {
    let buttonPosition = sender.convertPoint(CGPointZero, toView: self.tbl_availability)
    let indexPath = self.tbl_availability.indexPathForRowAtPoint(buttonPosition)
    UtilityHandler.addpopupZoomAnimationTopickerView(view_time_picker, view: self.view)
    time_picker.addTarget(self, action: #selector(datepickeractionmethod(_:)), forControlEvents: .ValueChanged)

    //Set which picker is Shown
    timeType = .EndTime
}

Now use this enum in datePicker action
func datepickeractionmethod(sender : UIDatePicker) {
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "hh:mm a"
    let time = dateFormatter.stringFromDate(self.time_picker.date)
    if self.timeType = .StartTime {
        self.startTime = time
    }
    else {
        self. endTime = time
    }

    //Now simply reload tableView or you can even reload single row that contains these two buttons.
    self.tableView.reloadData()
}

A: you need declare global button instance for track click button .
class ViewController: UIViewController{
    var clickedButton : UIButton

func btnStartTimePressed(sender: UIButton!)  {
        let buttonPosition = sender.convertPoint(CGPointZero, toView: self.tbl_availability)
        let indexPath = self.tbl_availability.indexPathForRowAtPoint(buttonPosition)
        UtilityHandler.addpopupZoomAnimationTopickerView(view_time_picker, view: self.view)
        time_picker.addTarget(self, action: Selector(datepickeractionmethod(time_picker)), forControlEvents: .ValueChanged)
        sender.setTitleColor(BUTTON_BLACK_COLOR_222222, forState: .Normal)
        clickedButton = sender
}

 func datepickeractionmethod(sender : UIDatePicker) {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "hh:mm a"
        strDate = dateFormatter.stringFromDate(self.time_picker.date)
        clickedButton.setTitle(strDate as String, forState: .Normal)
 }


text:
Q: How to override shipping-address/form.html with my theme I am trying to override the file vendor/magento/module-checkout/view/frontend/web/template/shipping-address/form.html using my theme, but I can't find which path is correct. Can someone point me in the right direction?

A: Please place the file form.html inside your theme like this in path -
"app/design/frontend/Ced/ced_2k18/Magento_Checkout/web/template/shipping-address/form.html"
Please do let know if it helps or not.
Please refer the below image for clear image structure in phpstorm


text:
Q: php - how to sort array by keys I have itinerary/tour page that contain number of sections: header. description, body, guide_details, footer
I would like to let my client to set the order - which section will appear first, second, third...
So I have array from DB that contain the number of each section. The number id the section position
Table itin_oreder:
clientID     header    description  body  guide_details footer
   6           1            3        2          4          5

$query = "SELECT * FROM itin_oreder WHERE client= 6 ";
$res = mysql_query($query);

I also have array that contain the content of each section:
itinContent = array ("header" => $header, "description" => $description....)

How do I print the array itinContent in the order that the client set?

A: What you are looking for call "uksort" (uksort  in PHP-MANUAL)
Let say you have itin_oreder array with the order to the scheme. you can build comparison  function by that global array.
This is sample code:
<?php

$init_order= array("clientID"=>6, "header"=>3, ...);
$initContent = array ("header" => $header, "description" => $description....)

function sortByInitOrder($a,$b)
{
        global $init_order;
        return ($init_order[$a] > $init_order[$b]);
}

uksort($initContent, 'sortByInitOrder');
echo print_r($initContent, true);

If you want to print only the array values:
foreach($initContent as $key => $value)
{
  echo "$value \n";
}


text:
Q: Copy files without changing owner How to copy all files from /var/www onto a flash disk without changing owners of folders in the /var/www folder? (Or how to insert the whole /var/www folder into an archive and put it onto  a flash disk)
My system:
Debian 6 (Linux PSB1 2.6.32-5-686 #1 SMP Mon Sep 23 23:00:18 UTC 2013 i686)

A: cp -rp /var/www/ /path/to/flash/disk/

From cp manpage:
-p     same as --preserve=mode,ownership,timestamps

--preserve[=ATTR_LIST]
      preserve the specified attributes (default: mode,ownership,timestamps),
      if possible additional attributes: context, links, xattr, all

A: First mount your usb.
 $ mkdir -p /mnt/myusb
 $ mount -t vfat -o rw,users /dev/sda1 /mnt/myusb
 $ mount

After that you can use rsync command to do this wirh -avz arguments
rsync -avz /var/www /mnt/myusb

This will keep permissions, owner and links of /var/www .

A: You must be root (or have CAP_CHOWN and CAP_FOWNER and probably also CAP_DAC_OVERRIDE, and CAP_DAC_READ_SEARCH) in order to do that. Then it is simple: cp -a

A: If your filesystem is capable of preserving the ownership information, then cp -a (archive) preserves all parameters (permission, ownership, links, extended attributes).


text:
Q: How do I make Google Spreadsheet automatically divide a column into another column? I'm making a spreadsheet that includes a long list of values, with a column that contains a total of values, and after that an average of the values in the row. I need the averaged column to always be 1/6 of the value in the summed column, but I can't figure out a way to make it automatically calculate it for me for each new row.
So far, I have been doing it all manually (type out all the values, manually add them together for the total, then divide by 6 myself for the average) but I'd really like to automate the math parts. I have not found a single way to properly do this - using "=DIVIDE(K2,6)" as a modified version of a suggestion on this other question (modified to use the column I'm actually putting the numbers in) does literally nothing, and I'd have to manually change and paste it into each row, which is actually harder and more tedious than continuing to do the math myself.
Here's an example image of what my columns look like. All the math is correct so far, I just want to automate it so I can type fewer numbers:

EDIT: Combined answers from Scott and Player0 is what worked! thanks for being patient with me! I was able to also use that to make the Sum column function automatically as well, so both columns are fully automated now! :D

A: use on row 2:
=INDEX(IFERROR(K2:K/6; 0)

also see: ArrayFormula of Average on Infinite Truly Dynamic Range in Google Sheets

A: You don't have to enter the formula manually on every line.
Enter =K2/6 in cell L2; then select cell L2
and drag/fill it down to L12.
(That means click on the dot in the lower right corner of the cell
and drag it down.)
Or however far your sheet actually goes.
That will automatically fill in L3 with =K3/6,
L4 with =K4/6, and so on.


text:
Q: C# console app with MS Access OdbcConnection only completes in debug mode I've got a console app, and I've put the following code in the main method. All its doing is opening a connection to an MS Access database.
public static int Main(string[] args)
{
    var connectionString = "Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=MyDatabase;Uid=Admin;Pwd=;";
    using var connection = new OdbcConnection(connectionString);
    connection.Open();
    return 1;
}

This all works fine in debug, but when its ran without a debugger attached, the command window hangs around indefinitely and the process never completes.


text:
Q: Is it possible to create a standalone file to import a python library created with pybind? I hope I'm clear in my question, if not please tell me.
I am using OpenImageIO's python bindings (pybind11) for some scripts that will run on hundreds of computers. Unfortunately it took me a lot of time to install OpenImageIO and make it work with my Python2 installation. I'd like to know if there's a way to create a file/folder that I could send to other computers so they can install the Python module simply with "pip install file/folder".
Thanks ofr your help

A: Are you running the scripts on a compute cluster with a shared filesystem?  If so, then there's no need to create separate installations of python for each machine.  The simplest solution is to create ONE python environment in a location that is accessible by all of your machines.  An easy way to create a Python environment in a non-system location is to use Miniconda.  Install it to a shared (network) location, and create an environment for all of your machines to use.
If your machines do NOT have a shared file system, then you'll need to somehow reproduce the environment on all of them independently.  In this case, there's no simple way to do that with pip.**
But if you can use conda instead, then there's a very straightforward solution.  First, install everything you need into a single conda environment.  Then you have a choice: You can export the list of conda packages, or simply copy the entire conda environment directory to the other machines.
OpenImageIO is available from the conda-forge channel, a community-developed repository of conda packages.  The name of the package is py-openimageio.  They have stopped updating the python-2.7 version, but the old versions are still available.
Here's how to do it.

*

*Install Miniconda-2.7

*Create a new environment with python 2.7, OpenImageIO, and any other packages you need:

conda create -n jao-stuff -c conda-forge py-openimageio python=2.7
conda activate jao-stuff
python -c "import OpenImageIO; print('It works!')"

*Do ONE of the following:
a. Export the list of packages in your environment:
conda env export -n jao-stuff -f jao-stuff-packages.yaml

Then, on the other machines, install Miniconda, then create the environments using the package list from the previous step:
conda create -n jao-stuff --file jao-stuff-packages.yaml

OR
b. Just copy all of the files in the environment to the other machines, and run them directly. Conda environments are self-contained (except for a few low-level system libraries), so you can usually just copy the whole thing to another machine and run it without any further install step.
tar czf jao-stuff.tar.gz $(conda info --prefix)/envs/jao-stuff

On the other machine, unpack the tarball anywhere and just run the python executable it contains:
tar xzf jao-stuff.tar.gz
jao-stuff/bin/python -c "import OpenImageIO; print('It works!')"

**That's because OpenImageIO is a C++ project, with several C++ dependencies, and they don't provide binaries in the wheel format.  I don't blame them -- pip is not well suited to this use-case, even with wheels.  Conda, on the other hand, was designed for exactly this use-case, and works perfectly for it.


text:
Q: d3.js iterate order changes As project to get to know d3.js, I'm displaying tweets on a map in real-time. Everything has worked this far, and I'm very, very pleased with the library.
On the page, I'm trying to list all languages. On hover, I want all tweets of that language to pop up. All of this is done, except some items in the list pops up the tweets of another language. A wrong one, I might add.
This is how I project the dots on the map:
points.selectAll('circle')
    .data(tweets)

    .enter()
    .append('circle')

    // Attach node to tweet, so I can use refer to the nodes later
    .each(function(d) {
        d.node = this;
    })

    .attr('r', 1);

This is how I create the list:
var data = d3.nest()

    // Group by language code
    .key(function(d) { return d.lang.code; })
    .entries(tweets)

    // Sort list by amount of tweets in that language
    .sort(function(a, b) {
        return b.values.length - a.values.length;
    });

var items = languages_dom

    // Add items
    .selectAll('li')
    .data(data)
    .enter()
    .append('li');

    // Used for debugging
    .attr('data-lang', function(d) {
        return d.key; // Group key = language code
    })

    // Set text
    .text(function(d) {
        var dt = d.values[0];
        return dt.lang.name;
    })

    // Mouseover handler
    .on('mouseover', function(d) {

        // Compare attribute with
        // These values are actually different
        var attr = d3.select(this).attr('data-lang');
        console.log(attr, d.key);

        // Pop up each node
        d.values.forEach(function(d) {
            d = d3.select(d.node);

            d.transition()
                .duration(200)
                .attr('opacity', 0.5)
                .attr('r', 8);
        });
    });

Note that the script above is run several times. d.key refers to another value later in the chain, while I'm not modifying data in that chain.

Edit 22:08
Things seems to work fine when I'm not sorting the data. At least it's a lead.

A: As noted in the comments, you're overwriting d in your forEach function. Instead, you should try something like
    d.values.forEach(function(p) {
        d3.select(p.node)
            .transition()
            .duration(200)
            .attr('opacity', 0.5)
            .attr('r', 8);
    });

Notice the forEach variable is named p instead of d.

A: As the data changed, the old data seems to be kept somehow.
Either way, I simply deleted the list before applying the new data:
languages_dom
    .selectAll('li')
    .remove();

Can't say this is graceful, nor performant, but it gets the job done :)


text:
Q: Problem Install R on OS 10.14 Using Mathematica 12.1.0.0 on Mac OS 10.14
Attemping to use my version of R
Tried using:
Needs["RLink`"]
JLink`UninstallJava[]
InstallR["RVersion" -> "3.61",
 "RHomeLocation" ->
  "/Users/james2/opt/anaconda3/envs/Rtest/lib/R/library",
 "NativeLibLocation" ->
  "/Users/james2/opt/anaconda3/envs/Rtest/lib/R/library/rJava/jri"]

Received error message:
Failed to install R.  The following error was encountered:crash in low-lever RLink component or in R runtime


text:
Q: Product ID tracking in a sorter machine (PLC programming) I'm writing a PLC program (Q Series Mitsubishi PLC, GXWORKS 2 Software) for a package sorting machine. The logic of the machine is the following:
1.Packages are induced in the conveyor. A barcode reader scanner gets the package barcode.
2.Barcode is send to our SMS (sorting management system), it calcules the exit and send it back to the PLC.
3.Package travels to the calculed exit, then is derived into the chute.
The tracking of the products is done by an encoder and a shift register. This means that every memory address represents a physical position in the conveyor. Then, the shift register move the bits representing the packages along the memory buffer, till the bit arrives to an address that represents an exit, so the package can be derived.
My problem is not the tracking of the product, but the product ID tracking:
When a package enters in the conveyor, an ID is set for that product (1,2,...,n). The idea is that this ID is used to track the state of that package, for example if the package was derived in the correct exit, if it has a damaged barcode, etc.
My question is, how can I track this ID along in an efficient way. I was thinking in use the same shift register not moving a sole bit, but moving a larger number for example |1|0000011|, where the first bit acts like a flag that represents the existence of a product and the rest of the numbers is the product ID. When the flag gets to the exit address I can substract 10000011 - 10000000 = 00000011, to get the product ID.
Is any more efficient way to do this ?

A: The part with the encoder is not clear to me, so I replace it with a nr x of sensors.
Maybe you can explain it better, then I will update the answer.
Now, let's imagine a simple model of the conveyor:
        S           S               S
        |           |               |EXIT
---------------------------------------------------
    x           x   x           x
---------------------------------------------------

*

*x are the packages on the conveyor

*s are the sensors along the conveyor

*EXIT is where the package exits

You can create a Function Block that represents a Package: FB_Package
FB_Package has following data structure :
TYPE ST_Package :
STRUCT
    sBarcode : STRING;
    eLocation : E_ConveyorLocation;
    eState : E_PackageState;
    uiPackageID: UINT;
END_STRUCT
END_TYPE

Then you can create an FB_Conveyor that has/or manages an array of FB_Packages
FB_Package has a step chain which checks the current location on the conveyor.
Every time it receives a new location from the conveyor it checks in its step chain if that location is plausible considering the current location (time frame to get to the next location and if the received location is after the current location for example).
If the check is successful the package updates it's location and when the last location is reached the fbPackage instance changes it's state to ePackageExited for example.
The fbConveyor instance recognizes that the package has exited the conveyor and resets its instance in the array.
As you can see, I used ENUMS for the package location and the state because they are human readable and make your code easier to understand than shifting around with bits in bytes.


text:
Q: Reading one file and writing to a new file leaves new file empty I am trying to read from a file that contains a character "|" that I need removed when copying the data to a new file. For example my data looks something like, where the content of one line transfers to another:
| bob |  Timestamp: 1493651705861 |  sally |

I would like the "|" removed and after each time in appears the next set of text would move to the next line, so afterwards it would appear like the following:
bob
Timestamp: 1493651705861
sally

I constructed the following code to read the old file line by line and then character by character and then checked if the character was a "|" and if it was to not write it. However, when I do so, my print statements do not print anything and the new file is empty. Here is the code I am working with:
with open('example-file','r') as f, open('example-file-New','w') as fnew:
    line = f.readline()
    for line in f:
        for ch in line:
            print("character is: ")
            print(ch)
            if ch =="|":
                 print("Not printing character")
                 fnew.write('\n')
            else:
                fnew.write(ch)
    print('end of program')
    fnew.close()

Any help would be greatly appreciated as I am still trying to get used to Python.

A: Your code works for me, but when I run it on your example input, I don't get your exact example output. Based on the output, I assume you also want to remove whitespace padding the text. There are a several ways of achieving this, but I like using the substitute sub method in the regular expression re library.
import re
with open('example-file','r') as f, open('example-file-New','w') as fnew:
    for line in f:
        line = re.sub("^\|\s+", "", line)
        line = re.sub("\s+\|$", "", line)
        line = re.sub("\s+\|\s+", "\n", line)
        fnew.write(line)

"^\|\s+" - match the first bar with adjacent whitespace
"\s+\|$" - match the final bar with adjacent whitespace
"\s+\|\s+" - match the other bars with adjacent whitespace
You can achieve this with fewer expressions, but I broke them up for clarity. I recommend investing a couple hours into familiarizing yourself with regex (regular expressions), as it will make your text-manipulation tasks much easier.


text:
Q: save the state of my togglebutton after return in the same activity or restart application everybody! I try to save the state of my ToggleButton. In fact, i would like to have the same state after user restart his application or return in this activity.
But for example when i return in my previous activity and then when i re-return in my activity where is my ToggleButton, i see that the ToggleButton status is not registered. If anyone can help me?
Like you can see, i use setDefaults to save the state of my ToggleButton and getDefaults to recover it.
public class OnOff extends Activity {

    ToggleButton toggle1;
    ToggleButton toggle2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.on_off);
        // Show the Up button in the action bar.
        setupActionBar();

        toggle1 = (ToggleButton) findViewById(R.id.ontoggle1);
        toggle1.setChecked(getDefaults("etatToggle",this));
        setDefaults("etatToggle", toggle1.isChecked(), this);
    }

    //Fonction appelée pour enregistrer en mémoire, ici en l'occurence l'état du ToggleButton: true ou false
    public static void setDefaults(String key, Boolean value, Context context)
    {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putBoolean(key, value);
        editor.commit();
    }

    //Fonction appelée pour récupérer ce qui a été saisi en mémoire
    public static Boolean getDefaults(String key, Context context)
    {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        return preferences.getBoolean(key, true);
    }
}

A: @Override
public void onStart(){
    super.onStart();

    toggle1.setChecked(getDefaults("etatToggle",this));
}

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

    setDefaults("etatToggle", toggle1.isChecked(), this);
}

A: Since you are calling the following
    setDefaults("etatToggle", toggle1.isChecked(), this);

in onCreate(), everytime you start your application the ToggleButton is checked irrespective of the previous state of the ToggleButton when the application was closed. So this line of code should be placed as follows-
    toggle1.setOnClickListener(new View.OnClickListener() {

    public void onClick(View v) {

           setDefaults("etatToggle", toggle1.isChecked(), OnOff.this);
    }
});

so that the state of the ToggleButton is saved when you click it and thereby the ToggleButton will retain its previous state when the application is started again.


text:
Q: Can Espresso work without launching activity with intent? I want to write an Espresso test that will use currently launched activity on my tablet's screen. So I'll manually navigate to this activity with appropriate content prior launching the test,  cause it's difficult and reluctant to write additional code to launch this activity with the same global "state" in app and pass all needed params in the launching intent and so one.
Is it possible and how to do this with Espresso,
or I have to use UI Automator then?

A: If you absolutely do not want to set up the intent to launch the activity you want to test then you can just use a breakpoint in your test. This will allow you to manually navigate to the activity before your Espresso tests start executing.
I would say, however, that at the very least you should use Espresso to automate those manual steps.
@Test
fun testActivityIsDisplayed() {
    openTestActivity() //automate with espresso or put breakpoint to do manually
    onView(withId(R.id.testActivity)).check(matches(isDisplayed()))
}

private fun openTestActivity() {
    ...
}


text:
Q: Writing SSPBUF from variable in I2C slave protocol in PIC18 I am migrating this question from StackOverflow to this forum because I believe it is more adequate.
I am writing an I2C slave routine for PIC18F25K80 and I am stuck on a weird problem.
This is my routine: (EDITED WITH THE LATEST VERSION BASED ON THE COMMENTS - STILL SAME PROBLEM)
void interrupt interruption_handler() {
INTCON1bits.GIE = 0; // Disable Master Synchronous Serial Port Interrupt

if (PIR1bits.ADIF == 1) {
    //This is a A/D interruption
    PIR1bits.ADIF = 0;
    INTCON1bits.GIE = 1; // Enable Master Synchronous Serial Port Interrupt
    return;
} else
if (PIR1bits.SSPIF == 1) {
    //This is a I2C interruption
    PIR1bits.SSPIF = 0;
    //Treat overflow
    if ((SSPCON1bits.SSPOV) || (SSPCON1bits.WCOL)) {
        dummy = SSPBUF; // Read the previous value to clear the buffer
        SSPCON1bits.SSPOV = 0; // Clear the overflow flag
        SSPCON1bits.WCOL = 0; // Clear the collision bit
        SSPCON1bits.CKP = 1;
        board_state = BOARD_STATE_ERROR;
    } else {
        if (!SSPSTATbits.D_NOT_A) {
            //Slave address
            debug(0, ON);
            //Read address (A/D number)
            address = SSPBUF; //Clear BF
            while (BF); //Wait until completion
            if (SSPSTATbits.R_NOT_W) {
                SSPCON1bits.WCOL = 0;
                unsigned char a = 0x01;
                SSPBUF =  a; //0x01; //a+1; //Deliver first byte
            }
        } else {
            if (SSPSTATbits.BF) {
                dummy = SSPBUF; // Clear BF (just in case)
                while (BF);
            }
            if (SSPSTATbits.R_NOT_W) {
                //Multi-byte read
                debug(1, ON);
                SSPCON1bits.WCOL = 0;
                SSPBUF = 0x02; //Deliver second byte
            } else {
                //WRITE
                debug(2, ON);
            }
        }
        transmitted = TRUE;
        SSPCON1bits.CKP = 1;
        PIR1bits.SSPIF = 0; //Clear again just in case

        INTCON1bits.GIE = 1; // Enable Master Synchronous Serial Port Interrupt
    }
} else
    PIR1 = 0x00; //Just in case
}

It works like a charm if I set constant values on SSPBUF. For example, if you do:
SSPBUF = 0x01;
(...)
SSPBUF = 0x02;

I get the two bytes on the master. I can even see the wave forms of the bytes being transmitted on the oscilloscope. Quite fun!
But when I try to set SSPBUF using a variable like:
unsigned char a = 0x01;
SSPBUF = a;

I get zero on the master.
It is driving me crazy.
Some hypothesis I've discarded:

*

*Watchdog timer is messing up interrupting in the middle of the protocol: It is not. It is disabled and the problem happens in both SSPBUF assignments

*I need to wait until BF goes low to continue: I don't. AFAIK, you setup the SSPBUF, clear SSPIF, set CKP and return from interruption to take care of life in 4Mhz while the hardware send data in few Khz. It will interrupt you again when it finishes.

It makes no sense to me. How good it is if you cannot define an arbitrary value using a variable?
Please gurus out there, enlighten this poor programmer.
Thanks in advance.

A: I found a workaround. It is absolutely mind blowing. If I change:
SSPBUF = a;

to
SSPBUF = a+1;

it works. The data+1 goes to the I2C server. I guess it has something to do with the generated assembler code.
Let's analyze the options:
Option 1 - assigning a constant (it works)
The code
SSPBUF = 0x23;

results in:
1548                           ;naplaca.c: 320: SSPBUF = 0x2;
1549  00008A  0E02                  movlw   2
1550  00008C  D00F                  goto    L3
(...)
1661  0000BA                     L3:
1662  0000BA  6EC9                  movwf   4041,c  ;volatile

Option 2 - assigning a variable (does not work)
The code:
unsigned char a = 0x2;
SSPBUF = a;//0x01; //Deliver first byte

results in:
1544                           ;naplaca.c: 318: unsigned char a = 0x2;
1545  000086  0E02                  movlw   2
1546  000088  6E11                  movwf   interruption_handler@a,c
1547
1548                           ;naplaca.c: 319: SSPBUF = a;
1549  00008A  C011  FFC9            movff   interruption_handler@a,4041 ;volatile

Option 3 - assigning the result of an expression (works but send data +1)
The code:
unsigned char a = 0x2;
SSPBUF = a+1;//0x01; //Deliver first byte

results in:
1544                           ;naplaca.c: 318: unsigned char a = 0x2;
1545  000086  0E02                  movlw   2
1546  000088  6E11                  movwf   interruption_handler@a,c
1547
1548                           ;naplaca.c: 319: SSPBUF = a+1;
1549  00008A  2811                  incf    interruption_handler@a,w,c
1550  00008C  D00F                  goto    L3
1551  00
(...)
1661  0000BA                     L3:
1662  0000BA  6EC9                  movwf   4041,c  ;volatile

I tried to sum 0, but the compiler optimizes it and make it equals to option 2.
The same happens for a+1-1 and a+2-1-1.
Thus the workaround so far is to send data+1.
Option 4 (volatile variable - does not work) -- edit
The code:
volatile unsigned char a = 0x09;
SSPBUF =  a;// byte1_0 + 1; //0x01; //Deliver first byte

results in:
1634                           ;naplaca.c: 350: volatile unsigned char a = 0x09;
1635  000098  0E09                  movlw   9
1636  00009A  6E11                  movwf   interruption_handler@a,c    ;volatile
1637
1638                           ;naplaca.c: 351: SSPBUF = a;
1639  00009C  C011  FFC9            movff   interruption_handler@a,4041 ;volatile
1640

Conclusion
It seems to work when the compiler assign value to SSPBUF with movwf. When it uses move, it does not work.
I am posting this as an answer but I will not mark it as the right answer. I hope someone bring some light to this problem.

A: Turn the extended instruction set off in your codes config bit settings ie:
#pragma config XINST = OFF   // Extended Instruction Set (Disabled)

It makes all sorts of weird problems, just remember to turn it off from the start.
I2C stuff also gets itself in a tizzy sometimes if you don't leave a small delay between initializing I2C, calling functions etc.


text:
Q: ImageJ: Wrong transferrence of Coordinates from picture to picture for my Thesis I must count cells on pictures stained with Immunofluorescence and I am writing a macro in ImageJ to do it for me.
For this I coloursplit the picture, analyse particles in the red channel (my Antibody´s colour) and then I want to take the coordinates of analysed particles and only count them if at the same coordinates in the blue channel there is also a staining (DAPI - just a general cell staining).
This way I assure that there is as little dirt counted as possible.
The problem is that when I get the coordinates from the results table and use them to makePoint(x,y) the coordinates are "distorted" - usually the correct coordinates but plus 4ish, though never in exactly the same, which is why i can´t simply distract a number from the coordinates
Below I first write down the critical lines of code, then the whole code.
Thank you very much in advance
run("Analyze Particles...", "  circularity=r1-r2 display clear in_situ");
                roiManager("deselect");
                z=nResults;

                for (j=0; j<z; j++) {   //loops through the Results table and adds to "counter" if a match is found
                    selectImage(channelsplit[2]);   //selects blue window
                    setThreshold(d,l);
                    run("Threshold...");
                    setOption("BlackBackground", true);
                    run("Convert to Mask", "method=Default background=Default black");
                    run("Coordinates...", "left=0 right=19373 top=0 bottom=13600"); //I tried to set the boundaries of the pictures equally, but it didnt work
                    makePoint(getResult("X", j)), (getResult("Y", j));
                    print ("X" + j + ": " + getResult("X",j));  //this and the following line are not to be in the program, once it works
                    print ("Y" + j + ": " + getResult("Y",j));
                    run ("Measure");
                    if (getResult("Mean", nResults-1)>100) {
                        counter++;
                    }
                } //for j
                print (i + ": " + counter);

setBatchMode(true);
if (isOpen("ROI Manager")) {
    r=roiManager("count");
} else {
    setBatchMode(false);
    exit("You need a ROI Manager open with the ROIs of all the pictures to be measured");
}

Dialog.create ("Variables")

Dialog.addCheckbox ("red", true);
Dialog.addCheckbox ("green", false);
Dialog.addCheckbox ("blue", false);
Dialog.addCheckbox ("watershed", true);

Dialog.addNumber ("Thresholddark:", 110);
Dialog.addNumber ("Thresholdlight:", 255);
Dialog.addNumber ("greenThresholddark:", 110);
Dialog.addNumber ("greenThresholdlight:", 253);
Dialog.addNumber ("pmin:", 15);
Dialog.addNumber ("pmax:", 100);
Dialog.addNumber ("roundness1:", 0.5);
Dialog.addNumber ("roundness2:", 1.0);

Dialog.addMessage("batch - select 'true' for your macro to run faster, but you will not see what it does until finished\nstack - selecht this box if you use unstacked pictures and want them stacked, deselect if you use a readied stack or a single picture\nred - select this box if you want to count red coloured cells \ngreen - select this box if you want to count green coloured cells \nblue - select this box if you want to count blue coloured cells\nall variables are the same for the colours you count. It may be better to adjust variables for each colour and count seperately\nwatershed - select this box only if you have overlapping cells in your image\nThresholdlight - particles lighter than this won't be measured/counted \nThresholddark - particles darker than this won't be measured/counted \nThresholdlight and Thresholddark can be between 0 and 255 \ntry thresholding manually at least once manually to get best results \npmin -  particles with a size smaller than this won't be counted \npmax - particles with a size greater than this won't be counted")
Dialog.show ();

cr=Dialog.getCheckbox();
cg=Dialog.getCheckbox();
cb=Dialog.getCheckbox();
w=Dialog.getCheckbox();

d=Dialog.getNumber();
l=Dialog.getNumber();
dg=Dialog.getNumber();
lg=Dialog.getNumber();
pmin=Dialog.getNumber();
pmax=Dialog.getNumber();
r1=Dialog.getNumber();
r2=Dialog.getNumber();

dir = getDirectory("Choose a Directory ");  //choose the folder with all the pictures to be measured
listFiles(dir);                 //I found this in a listFiles recursively Demo and changed it to open my pictures

function listFiles(dir) {
    list = getFileList(dir);
    for (o=0; o<list.length; o++) {     //loops through the file list, opening then analysing then closing one after another
        if (endsWith(list[o], "/")) {
            listFiles(""+dir+list[i]);
        } else {
            open(dir + list[o]);
//the previous opens all pictures in a given folder in a way i do not understand
//I only use this function because I could not use the variable list.length outside of it for unknown reasons
//following is my cellcount program to be executed for each picture
//then the picture will be closed before the new one is opened
            run("Split Channels");
            channelsplit = getList("image.titles");
            if (cr==1) {
            a=0;
            }
            if (cg==1) {
            a=1;
            }

            selectImage(channelsplit[a]);   //selects red or green window, depending on input in the Dialog
            setThreshold(d,l);
            run("Threshold...");
            setOption("BlackBackground", true);
            run("Convert to Mask", "method=Default background=Default black");
            run("Coordinates...", "left=0 right=19373 top=0 bottom=13600");

            for (i=2*o; i<=((2*o)+1); i++) {    //loops through two ROIs of the ROIManager
                counter=0;
                selectImage(channelsplit[a]);
                roiManager("deselect");
                roiManager("select", i);
                if (w==1) {
                    run("Watershed", "slice");
                }
                run("Analyze Particles...", "  circularity=r1-r2 display clear in_situ");
                roiManager("deselect");
                z=nResults;

                for (j=0; j<z; j++) {   //loops through the Results table and adds to "counter" if a match is found
                    selectImage(channelsplit[2]);   //selects blue window
                    setThreshold(d,l);
                    run("Threshold...");
                    setOption("BlackBackground", true);
                    run("Convert to Mask", "method=Default background=Default black");
                    run("Coordinates...", "left=0 right=19373 top=0 bottom=13600"); //I tried to set the boundaries of the pictures equally, but it didnt work
                    makePoint(getResult("X", j)), (getResult("Y", j));
                    print ("X" + j + ": " + getResult("X",j));  //this and the following line are not to be in the program, once it works
                    print ("Y" + j + ": " + getResult("Y",j));
                    run ("Measure");
                    if (getResult("Mean", nResults-1)>100) {
                        counter++;
                    }
                } //for j
                print (i + ": " + counter);
                close("Results");   //closes Results to get the variables in order for the next window
//              IJ.renameResults("res" + i);
            } //for i
            close("*");     //closes all image windows to save RAM
        } //else
    } //for o
} //function
setBatchMode(false);


text:
Q: DynamoDB access pattern change I am using DynamoDB as the database of choice in a very large and complex system.
This was done around 2017/18 and the application has been working and evolving ever since. The decision of using DynamoDB was based on the access patterns and scalability properties.
Recently we are doing a face-lift of our UI and it drastically changes some of the access patterns we designed our database and model for.
We don't want to migrate out of DynamoDB so I am thinking of creating an auxiliary store in (SQL or similar) that replicates our DynamoDB table but let's us do all the needed queries of the data.

*

*What would you do in this case?

*Is it recommended to duplicate the data (subset of attributes) in order to satisfy our UI requirements?

*How other people have solved this?
More details
The table that is changing holds many entities. The change is for one of this entities. It used to get accessed sorting by timestamp, and paging was done using pointers (infinite scroll in the UI).
The new design is great. Gives the user more power to massage the data, but changes drastically the access patterns we designed the model and table for.

*

*they can sort by many attributes

*they can filter by many attributes simultaneously

*they can free text search by multiple attributes at the same time

*paging by set pages with dynamic pages size (user driven)

We are not looking to change our database. This entity has 10+ attributes but one of them is a tree like structure, and JSON is perfect and DynamoDB as well. We also use heavily Streams and TTL for post processing and other stuff. Our whole application relies on this DynamoDB table to be the source of truth for this entity.
Some possible solutions, that I can think of, but I am not convinced.

*

*Create an Aurora Serverless Postgress DB that holds a view of our entity. It acts as a replica of our entity in DynamoDB. We can achieve this in application code by writing in DynamoDB and then in this SQL store. This will let us do all the queries with SQL (offset, limit, order by, etc). Like a durable cache.

*OpenSearch. Use an index in open search. Very similar approach to the previous one, except instead of having a SQL counter part we have an (Elastic Search) Open Search index that holds a subset of this entity to do all the operations.

*Add a bunch of indexes and do parallel querying in DynamoDB. Basically code all the possible sort, filter and paging logic in our application code.

A: A fourth option is Rockset. It can scan what's in DynanoDB and stay up to date with Streams, then provides a variety of ad hoc query capabilities against the data including text search features and analytics.
It's serverless and does all the sync work for you, two big benefits. I'd try that first.


text:
Q: How can I tell if a group is linear? The basic question is in the title, but I am interested in both necessary and sufficient conditions.
I know the Tits' alternative and Malcev's result that finitely generated linear groups are residually finite, but I don't know any purely group-theoretical sufficient conditions.
Though it's not purely group-theoretical, what if the group acts simplicially on a (finite) simplicial complex? Does this imply linearity? Does it imply linearity over $\mathbb{C}$?

A: Since this is not purely group theoretical and not a complete answer, this maybe should be more of a comment, but since you mentioned simplicial complexes perhaps you should check out the following paper to get you started:
Haglund, Frédéric, and Daniel T. Wise. "Special cube complexes." Geometric and Functional Analysis 17.5 (2008): 1551-1620.
Which is concerned with the fundamental groups of certain square complexes (VH complexes whose 1-cells are divided into two classes, "horizontal" and "vertical", and the attaching maps of squares alternate v-h-v-h). For instance, they prove that any fundamental group of a compact virtually clean (clean means attaching maps are embeddings, and this implies that the group splits as a clean graph of groups, as studied in [1]) VH-complex is linear.
Although this isn't purely group theoretic, it is at least mostly presentation theoretic, and the result itself isn't too hard to apply if you have for instance a finitely presented group. In this case, there is often an easy algorithm to check whether such a group has a VH-subdivision. (For instance, there is an example of such a procedure outlined in my paper with Wise [2]). After you still have to check the virtually clean condition, which may or may not be so easy depending on what you are doing.
[1] Wise, Daniel T. "The residual finiteness of negatively curved polygons of finite groups." Inventiones mathematicae 149.3 (2002): 579-617.
[2] Polák and Wise, "A Note on VH Subdivisions", To appear.

A: Here are some more purely group theoretical conditions. This is also not a complete answer, since it gives just some necessary conditions for certain groups to be linear.

*

*Schur: Suppose that $G$ is a finitely generated linear group, such that all elements have finite order. Then $G$ is finite.

*Jordan: Suppose that $G$ is a finite linear group of degree $n$ over a field of characteristic zero. Then there exists an integer-valued function $\beta(n)$ such that G contains an abelian normal subgroup of finite index at most $\beta(n)$.

*Malcev: Suppose that $G$ is a finitely-generated linear group. Then $G$ is residually finite. If $G$ is simple, then $G$ is finite.

*Platonov: Suppose that $G$ is a linear group of degree $n$ of finite Pruefer rang $r$ over a field of characteristic  $p > 0$. Then $G$ contains an abelian normal subgroup of finite index bounded in terms of $r, n$, and $p$.

*Malcev: Suppose that $G$ is a solvable linear group of degree $n$ over an algebraically closed field. Then $G$ contains a triangularizable normal subgroup of finite index bounded by a function of $n$.

A: One more necessary condition. Let $T$ be a matrix from $SL_n(\mathbb{C})$. Then the set of all matrices $B$ such that $\lim_{n\to \infty} T^{n} BT^{-n} = 1$ is a nilpotent subgroup (an exercise, first noticed by Margulis, I think, a proof can be found here.). This implies, for example,  that the group $\langle a,b,t \mid tat^{-1}=a^2, tbt^{-1}=b^2\rangle$ is not linear (this group is residually finite).


text:
Q: Any advice on troubleshooting instability in Mountain Lion OS X 10.8.4? In all cases of crashes, I can SSH to the machine, but I can't figure out anything useful to remedy the situation.
This freeze happened when sizing the crop in Aperture. Machine had been running for probably 3 days.
Apple support wants to me uninstall every system extension, etc. to troubleshoot. They can't seem to find anything in the logs. I find that hard to believe that this issue cannot be troubleshooted via ssh or the logs.
Needless to say, freezing every 3 days is awful. My guess is that the issue is related to updates related to Aperture or Chrome. I'm pretty sure I've been running Chrome every time the machine has crashed. I'm also sure the machine has sometimes crashed without Aperture running.
Any advice on how to troubleshoot?
In installed Tempurature Monitor download. Any advice on alert settings?
I'm going to try SMC Fan Control set to "Higher RPM".
Is there any way to have the dual video card only use the NVidia card rather than the Intel one (when using A/C)? Could that be relevant?
Possibly Related
Apple discussion on same topic
> Jun 10 12:56:48 JustinMbp.local Aperture[37669]: [<__NSDictionaryM
> 0x7fa727424490> valueForUndefinedKey:]: this class is not key value
> coding-compliant for the key Projects. Jun 10 12:56:48 JustinMbp.local
> Aperture[37669]: (        0   CoreFoundation
> 0x00007fff8ce05b06 __exceptionPreprocess + 198        1   libobjc.A.dylib
> 0x00007fff8e3eb3f0 objc_exception_throw + 43      2   CoreFoundation
> 0x00007fff8ce99f49 -[NSException raise] + 9       3   Foundation
> 0x00007fff9131f15c -[NSObject(NSKeyValueCoding) valueForUndefinedKey:]
> + 238         4   Foundation                          0x00007fff91266ea9 -[NSObject(NSKeyValueCoding) valueForKey:] + 400         5   Foundation                          0x00007fff912841bd -[NSDictionary(NSKeyValueCoding) valueForKey:] +
> 139       6   Aperture                            0x000000010a64b3fa
> Aperture + 1963002        7   Aperture
> 0x000000010a64d1ab Aperture + 1970603         8   Foundation
> 0x00007fff91271463 __NSFireTimer + 96         9   CoreFoundation
> 0x00007fff8cdc2804
> __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 20        10  CoreFoundation                      0x00007fff8cdc231d
> __CFRunLoopDoTimer + 557      11  CoreFoundation                      0x00007fff8cda7ad9 __CFRunLoopRun + 1529        12  CoreFoundation
> 0x00007fff8cda70e2 CFRunLoopRunSpecific + 290         13  HIToolbox
> 0x00007fff8e5f5eb4 RunCurrentEventLoopInMode + 209        14  HIToolbox
> 0x00007fff8e5f5b94 ReceiveNextEventCommon + 166       15  HIToolbox
> 0x00007fff8e5f5ae3 BlockUntilNextEventMatchingListInMode + 62         16
> AppKit                              0x00007fff88d1d533 _DPSNextEvent +
> 685       17  AppKit                              0x00007fff88d1cdf2
> -[NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:] + 128        18  Aperture                            0x000000010a8e42b9 Aperture
> + 4686521         19  AppKit                              0x00007fff88d141a3 -[NSApplication run] + 517       20  ProKit                              0x000000010ba036c5 NSProApplicationMain + 378       21  Aperture
> 0x000000010a47c4ee Aperture + 66798       22  Aperture
> 0x000000010a47be14 Aperture + 65044   )

More
> Jun 10 13:05:33 JustinMbp kernel[0]: (default pager): [KERNEL]: default_pager_backing_store_monitor - send LO_WAT_ALERT

More -- this is the most consistent issue I see

6/10/13 1:17:08.000 PM kernel[0]: NVDA(OpenGL): Channel timeout!

I believe the machine locked up at about 13:00.
> Jun 10 13:01:06 JustinMbp com.apple.launchd[1]
> (com.apple.cfprefsd.xpc.daemon[39103]): Exited: Killed: 9 Jun 10
> 13:01:06 JustinMbp kernel[0]: memorystatus_thread: idle exiting pid
> 39103 [cfprefsd] Jun 10 13:01:26 JustinMbp
> com.apple.launchd.peruser.501[228]
> (com.apple.cfprefsd.xpc.agent[39102]): Exited: Killed: 9 Jun 10
> 13:01:26 JustinMbp kernel[0]: memorystatus_thread: idle exiting pid
> 39102 [cfprefsd] Jun 10 13:01:26 JustinMbp com.apple.launchd[1]
> (com.apple.hiservices-xpcservice[39082]): Exited: Killed: 9 Jun 10
> 13:01:26 JustinMbp kernel[0]: memorystatus_thread: idle exiting pid
> 39082 [com.apple.hiserv] Jun 10 13:01:36 JustinMbp.local
> WindowServer[128]: CGXDisableUpdate: UI updates were forcibly disabled
> by application "Aperture" for over 1.00 seconds. Server has re-enabled
> them. Jun 10 13:01:36 JustinMbp com.apple.launchd[1]
> (com.apple.iCloudHelper[39101]): Exited: Killed: 9 Jun 10 13:01:37
> JustinMbp kernel[0]: memorystatus_thread: idle exiting pid 39101
> [com.apple.iCloud] Jun 10 13:01:42 JustinMbp.local WindowServer[128]:
> reenable_update_for_connection: UI updates were finally reenabled by
> application "Aperture" after 7.27 seconds (server forcibly re-enabled
> them after 1.00 seconds) Jun 10 13:01:58 JustinMbp
> com.apple.launchd.peruser.501[228]
> (com.apple.cfprefsd.xpc.agent[39127]): Exited: Killed: 9 Jun 10
> 13:01:58 JustinMbp kernel[0]: memorystatus_thread: idle exiting pid
> 39127 [cfprefsd] Jun 10 13:02:38 JustinMbp.local
> com.apple.usbmuxd[84]: _SendAttachNotification (thread
> 0x7fff75fa5180): Device
> d8:d1:cb:88:7e:5b@fe80::dad1:cbff:fe88:7e5b._apple-mobdev._tcp.local.
> has already appeared on interface 4. Suppressing duplicate attach
> notification. Jun 10 13:02:41 JustinMbp com.apple.launchd[1]
> (com.apple.xpcd.F5010000-0000-0000-0000-000000000000[38883]): Exited:
> Killed: 9 Jun 10 13:02:41 JustinMbp kernel[0]: memorystatus_thread:
> idle exiting pid 38883 [xpcd] Jun 10 13:02:51 JustinMbp kernel[0]:
> (default pager): [KERNEL]: default_pager_backing_store_monitor - send
> LO_WAT_ALERT Jun 10 13:02:56 JustinMbp.local iTunes[13067]:
> _NotificationSocketReadCallbackGCD (thread 0x7fff75fa5180): Unexpected connection closure... Jun 10 13:02:56 JustinMbp.local ath[13082]:
> _NotificationSocketReadCallbackGCD (thread 0x7fff75fa5180): Unexpected connection closure... Jun 10 13:04:53 JustinMbp com.apple.launchd[1]
> (com.apple.cfprefsd.xpc.daemon[39172]): Exited: Killed: 9 Jun 10
> 13:04:53 JustinMbp kernel[0]: memorystatus_thread: idle exiting pid
> 39172 [cfprefsd] Jun 10 13:05:30 JustinMbp kernel[0]: macx_swapoff
> SUCCESS Jun 10 13:05:33 JustinMbp kernel[0]: (default pager):
> [KERNEL]: default_pager_backing_store_monitor - send LO_WAT_ALERT Jun
> 10 13:06:11 JustinMbp.local com.apple.usbmuxd[84]:
> _SendAttachNotification (thread 0x7fff75fa5180): Device d8:d1:cb:88:7e:5b@fe80::dad1:cbff:fe88:7e5b._apple-mobdev._tcp.local.
> has already appeared on interface 4. Suppressing duplicate attach
> notification. Jun 10 13:06:21 JustinMbp.local com.apple.usbmuxd[84]:
> _SendAttachNotification (thread 0x7fff75fa5180): Device 7c:c3:a1:83:92:17@fe80::7ec3:a1ff:fe83:9217._apple-mobdev._tcp.local.
> has already appeared on interface 4. Suppressing duplicate attach
> notification. Jun 10 13:06:33 JustinMbp.local iTunes[13067]:
> _NotificationSocketReadCallbackGCD (thread 0x7fff75fa5180): Unexpected connection closure... Jun 10 13:06:33 JustinMbp.local ath[13082]:
> _NotificationSocketReadCallbackGCD (thread 0x7fff75fa5180): Unexpected connection closure... Jun 10 13:09:18 JustinMbp kernel[0]:
> macx_swapoff SUCCESS Jun 10 13:11:36 JustinMbp.local CrashPlan menu
> bar[514]: CPMessageHandler Asked to change 'isConnected' status for
> GUID 550808839686455618, but I couldn't find any computer with that
> GUID. Jun 10 13:11:46 JustinMbp.local com.apple.usbmuxd[84]:
> _SendAttachNotification (thread 0x7fff75fa5180): Device d8:d1:cb:88:7e:5b@fe80::dad1:cbff:fe88:7e5b._apple-mobdev._tcp.local.
> has already appeared on interface 4. Suppressing duplicate attach
> notification. Jun 10 13:11:47 JustinMbp com.apple.launchd[1]
> (com.apple.cfprefsd.xpc.daemon[39225]): Exited: Killed: 9 Jun 10
> 13:11:47 JustinMbp kernel[0]: memorystatus_thread: idle exiting pid
> 39225 [cfprefsd] Jun 10 13:11:52 JustinMbp.local iTunes[13067]:
> _NotificationSocketReadCallbackGCD (thread 0x7fff75fa5180): Unexpected connection closure... Jun 10 13:11:52 JustinMbp.local ath[13082]:
> _NotificationSocketReadCallbackGCD (thread 0x7fff75fa5180): Unexpected connection closure... Jun 10 13:13:46 JustinMbp.local
> com.apple.usbmuxd[84]: _SendAttachNotification (thread
> 0x7fff75fa5180): Device
> d8:d1:cb:88:7e:5b@fe80::dad1:cbff:fe88:7e5b._apple-mobdev._tcp.local.
> has already appeared on interface 4. Suppressing duplicate attach
> notification. Jun 10 13:14:12 JustinMbp com.apple.launchd[1]
> (com.apple.cfprefsd.xpc.daemon[39395]): Exited: Killed: 9 Jun 10
> 13:14:12 JustinMbp kernel[0]: memorystatus_thread: idle exiting pid
> 39395 [cfprefsd] Jun 10 13:14:14 JustinMbp.local iTunes[13067]:
> _NotificationSocketReadCallbackGCD (thread 0x7fff75fa5180): Unexpected connection closure... Jun 10 13:14:14 JustinMbp.local ath[13082]:
> _NotificationSocketReadCallbackGCD (thread 0x7fff75fa5180): Unexpected connection closure... Jun 10 13:14:14 JustinMbp
> com.apple.launchd.peruser.89[250]
> (com.apple.cfprefsd.xpc.agent[39171]): Exited: Killed: 9 Jun 10
> 13:14:14 JustinMbp kernel[0]: memorystatus_thread: idle exiting pid
> 39171 [cfprefsd] Jun 10 13:14:19 JustinMbp.local Aperture[37669]:
> Could not connect the action infoClicked: to target of class
> RKCropToolController Jun 10 13:14:24 JustinMbp kernel[0]:
> NVDA(OpenGL): Channel exception! exception type = 0x1f = Fifo: MMU
> Error Jun 10 13:14:44 JustinMbp kernel[0]: NVDA(OpenGL): Channel
> timeout!

A: You could try using this menu bar app http://gfx.io to force integrated only mode (provided you don't used an external display) and see if stability improves.
Sounds like you are using an iMac (or MacBook Pro)? I had a similar issue with graphics-instability in my 2009 Mac Pro. After I replaced the graphics card I realized the original one was chock-full of dust blocking basically all airflow to the GPU fan. I disassembled it and cleaned it out and it is now running fine (albeit with smcFanControl ramped up a bit, because it seems my chipset also runs hot or has a bad sensor).
What I'm trying to say here is: try to make sure you have good air-flow in addition to ramping up the fan speeds. Easiest is just to feel if there is flow, but if there is not, some disassembly may be required. The stability of my machine was improved drastically by those two measures, though.

This thread speculated (similar due to the LO_WAT_ALERT error) about ram usage and free swap space, but ultimately solved it with a mobo replacement.

A: if you can ssh into the machine, I would have a detailed read of the syslog output.  You could also post it here but there is going to be a lot to go through.
Probably best to ssh into the box just after the display crashes and run it then piping the output as such:
syslog | tail -n 100 |open -ef


text:
Q: Determine whether a date falls on weekend in Angular/Javascript Given a date in yyyy-mm-dd format, how can I determine whether a date falls in the weekend in Angular/Javascript?
$scope.isWeekend= function(){
  $scope.date = '2018-05-13';
  /* if (day(date)=='saturday' || day(date)=='sunday') { */
  alert("");
  /* } */
}

A: Use Date#getDay() to get day of week and check if it is 6 (Saturday) or 0 (Sunday):

function isWeekend(string) {
  var date = new Date(string);
  return date.getDay() === 6 || date.getDay() === 0;
}

console.log(isWeekend('2018-05-13'));
console.log(isWeekend('2018-05-12'));
console.log(isWeekend('2018-03-13'));

A: Using momentjs just for determining whether a date falls on a weekend is a bit overkill.
You can do it reliably in vanilla JavaScript in just four easy steps :

*

*Split your yyyy-mm-dd into a [yyyy, mm, dd] array.

*Use new Date(year, month, day) to create a Date object, using the values in your array.Note that for month a value between 0 and 11 rather than between 1 and 12 is expected.

*Use date.getDay() to get a numeric representation of the day of the week, where 0 is Sunday, 1 is Monday, 2 is Tuesday, etc.

*Check whether the the day of the week is 0 or 6.

Demo

function isWeekend(dateString) {
  /* Step 1 */ var dateArray = dateString.split("-");
  /* Step 2 */ var date = new Date(dateArray[0], dateArray[1] - 1, dateArray[2]);
  /* Step 3 */ var day = date.getDay();
  /* Step 4 */ return day === 0 || day === 6;
}

console.log(isWeekend("2018-05-03")) // false
console.log(isWeekend("2018-05-04")) // false
console.log(isWeekend("2018-05-05")) // true
console.log(isWeekend("2018-05-06")) // true
console.log(isWeekend("2018-05-07")) // false
console.log(isWeekend("2018-05-08")) // false

A: In momentjs, use  moment('YYYY-MM-DD').day() to get the number of the day and then check if it equals 6 or 0(Saturday or Sunday).

function isWeekend(date) {
  var date = moment(date),day = date.day();
  return (day === 6) || (day === 0)
}

console.log(isWeekend("2018-05-06")) // true
console.log(isWeekend("2018-05-08")) // false
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>


text:
Q: Is it safe using `$` as an identifier in C/C++? Is it safe to use $ character as part of identifier in C/C++?
Like this,
int $a = 10;
struct $b;
class $c;

void $d();

A: No; it is a non-standard extension in some compilers.

A: No. The C standard only guarantees the use of uppercase and lowercase English letters, digits, _, and Unicode codepoints specified using \u (hex-quad) or \U (hex-quad) (hex-quad) (with a few exceptions). Specific compilers may allow other characters as an extension; however this is highly nonportable. (ISO/IEC 9899:1999 (E) 6.4.2.1, 6.4.3) Further note that the Unicode codepoint method is basically useless in identifiers, even though it is, strictly speaking, permitted (in C99), as it still shows up as a literal \uXXXX in your editor.

A: This is not standard and only Microsoft Visual Studio (that I know of) even allows the '$' character in identifiers.
So if you ever want your code to be portable (or readable to others), I'd say no.


text:
Q: make individual items in listbox selectable I have a listbox where some items should be selectable and others shouldn't be selectable.
The listbox uses a datatemplate and has animations that are initiated with triggers. I can set an attached property on listboxItem to do this but I'm at a loss as how to do this in a datatemplate

A: Use the ItemContainerStyle to bind IsEnabled for example.


text:
Q: How to Call A ASPNET web Service from javascript? How to Call A ASPNET web Service from javascript?

A: Hai vaishu,
Have a look at these
How do I call a web service from javascript
How can I call web service methods from javascript?
http://www.asp.net/AJAX/Documentation/Live/Tutorials/ConsumingWebServicesWithAJAXTutorial.aspx
http://www.dotnetspider.com/resources/1081-Calling-WebServices-using-Javascript-ADVANCED.aspx


text:
Q: Different order for getsockopt SO_PEERCRED in Linux and OpenBSD I'm trying to get the Unix socket peer credentials in python.
I am using this piece of code for that:
peercred = conn.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, struct.calcsize("3i"))
pid, uid, gid = struct.unpack("3i", peercred)

This works correctly in Linux, but in OpenBSD the order is different.
In OpenBsd the order is [uid, gid, pid] instead.
What is causing this difference? How do I know when to use which order?
The linux systems I tried were running on a x86_64 architecture and the openbsd system was on a amd64 architecture.

A: I'm no python programmer, but I guess you should special case your code based on sys.platform.
SO_PEERCRED is not a standardized interface, and the actual structure / binary interface is different between the systems.
On Linux, as defined in /usr/include/bits/socket.h:
struct ucred {
        __u32   pid;
        __u32   uid;
        __u32   gid;
};

On OpenBSD, as defined in /usr/include/sys/socket.h:
struct sockpeercred {
        uid_t           uid;            /* effective user id */
        gid_t           gid;            /* effective group id */
        pid_t           pid;
};

(uid_t, gid_t and pid_t are also 32bit on OpenBSD)
Other systems (eg. solaris, FreeBSD) have a completely different interface -- for some code that gets the peer credentials in a "system-independent" manner you could look at the update_client_creds() function from the heimdal source code (which is using the getpeereid(3) library function on OpenBSD and FreeBSD instead of directly SO_PEERCRED or LOCAL_PEERCRED).
In any case, the credentials got this way will be those of the process that called connect(2) or listen(2) on the socket (a process that may no longer exist), not necessarily those of the process actually using the socket by writing to or reading from it.

A: You could use cffi and the "API level" approach.  This requires a C compiler, although it is possible to do the compiling on a compatible system and then re-use the result.
https://cffi.readthedocs.io/en/latest/overview.html#api-mode-calling-the-c-standard-library

Note that this works independently of the exact C layout of struct passwd (it is "API level", as opposed to "ABI level").


text:
Q: how to get a screenshot for failure tests with method name of failure test With the listeners how can we solve it.Give me a better solution.I tried using with Listners but it is not giving the method name of failure test, it giving the screenshot name with current method name.for example if a  test is failed in one class i want that class method name only.but it is giving execution method as screen shot name
public class Invoke {
    public static WebDriver driver;

    public static void invoking() throws Exception {
        System.setProperty("webdriver.chrome.driver",
            "E:\\AK\\Selenium files\\chromedriver_win32 (1)\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.get("facebook.com/");
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        driver.findElement(By.xpath("akdhd")).click();
    }
}

public class Excecution {
    @Test public static void m() throws Exception {
        Invoke.invoking();
        String val=ExcelDynamic.r("C:\\Users\\PC\\Desktop\\facebook.xlsx", "Sheet1", 1, 1);
        System.out.println(val);
    }

This code is in another class
    public static void screen(String Filepath) throws Exception {
        TakesScreenshot ts = ((TakesScreenshot) driver);
        File fi = ts.getScreenshotAs(OutputType.FILE);
        String img = Thread.currentThread().getStackTrace()[2].getMethodName() + ".jpg";
        FileUtils.copyFile(fi, new File(Filepath + img));
    }
}

i'm calling this method in execution class so it is printing screenshot name m. But i want output name as invoking for screen shot

A: Below is a utility method that returns the calling method name.
public static String get_calling_method_name() {
    return Thread.currentThread().getStackTrace()[2].getMethodName();
}

Hope this solves the issue.

A: You may try By this,
To change with first index,
String img = Thread.currentThread().getStackTrace()[1].getMethodName() + ".jpg";

Hope it will work.


text:
Q: Why i cant use '<' operation on my Search View I want to create my filter to sort about 'Start Date' and 'End Date'
For example
i want to see the day that employee leave in 2013

*

*so i put

<filter string="Year 2013" icon="terp-year" name="year 2013" domain="[('date_from','>','2013-01-01 00:00:00')]/>
It's Work !

*

*But when i put

<filter string="Year 2013" icon="terp-year" name="year 2013" domain="[('date_from','>','2013-01-01 00:00:00'), ('date_to','<','2014-01-01 00:00:00')]/> It's doesn't Work!
i try many operation '>', '>=', '=', '!=' it's work too but when i use '<' it's doesn't
Some one plz help me and thank you for you time to rend my word (sorry about my language :'|)

A: @iSS.f use < instead of < because the HTML parser thinks it as the start of another HTML element. From there it starts rendering of new control so the error will occur.


text:
Q: Linphone Android Import and Build I am working on Linphone Library and using GITHUB repo and downloaded the zip file with Download Zip button.

Now when i go through the README file i saw that i need to run ./prepare_sources.sh script then i ran it on terminal but it asks for file to patch as
Now when i opened the folder inside submodules/externals/ffmpeg -- It's completely empty
and other folders are also empty.
But on GitHub also i saw it with some kind of black folder which i can't select.
I am stuck here ? should i do how can i get all these files into my directory so that i can make the build.
One more thing Should i import this downloaded Zip into my eclipse it shows me these projects which one should i import (Should i import it after i download the Zip from Github or should i import it after running all the scripts to make the build on terminal and then import it in eclipse)?
Need Help .

A: because all this are submodules so you have to download it thru terminal
Enter Following Command then you get everything with subfolders.
git clone git://git.linphone.org/linphone-android.git --recursive
--recursive will fetch submodules also.
i hope it helps you.


text:
Q: Script to open multiple Chrome tabs each for a Google search from a list of keywords present in an Excel sheet I have a list of keywords stored in a column in an Excel sheet. I want to do a Google search for each keyword in separate chrome tabs.
Can anyone please help me with Python code to automate it?

A: Rahil, say your keywords are in the "A" column of rahils_keywords.xlsx file, in the worksheet called keywords. At the shell, install this dependency:
> pip install openpyxl

Then in your text editor or Python REPL:
import webbrowser

from openpyxl import load_workbook

def google_search_keywords_from_spreadsheet(path: str, sheet: str, column: str):
    wb = load_workbook(filename=path)
    worksheet = wb[sheet]
    num_rows = worksheet.max_row

    for row_num in range(num_rows):
        cell = f"{column}{row_num + 1}"
        keyword = worksheet[cell].value
        if keyword: # skip blank cells
            url = f"https://google.com/search?q={keyword}"
            print(f'searching for keyword "{keyword}"...')
            webbrowser.open(url)

google_search_keywords_from_spreadsheet(
    path="rahils_keywords.xlsx",
    sheet="keywords",
    column="A",
)


text:
Q: Easier / more idiomatic way to do a "zip with conditional" in RXJS? I'm trying to zip two Observables in RXJS, taking values from each in pairs when a certain condition is met. I found a way to accomplish this without using zip, but I was wondering if anybody knew of a more idiomatic way to do it.
const { zip, merge, Subject } = require("rxjs");
const rxop = require("rxjs/operators");

const a$ = new Subject();
const b$ = new Subject();

// Zipping a$ and b$ on conditional a.n === b.n
const zippedWithCondition$ = merge(
  a$.pipe(
    rxop.mergeMap(aMsg => b$.pipe(
      rxop.find(bMsg => aMsg.n === bMsg.n),
      rxop.map(bMsg => [aMsg, bMsg])
    ))
  ),
  b$.pipe(
    rxop.mergeMap(bMsg => a$.pipe(
      rxop.find(aMsg => aMsg.n === bMsg.n),
      rxop.map(aMsg => [aMsg, bMsg])
    ))
  )
);
const withConditionSub = zippedWithCondition$.subscribe(msg => {
  console.log("[ZIPPED WITH CONDITION]", msg);
});
a$.next({n: 0, type: "a"});
b$.next({n: 1, type: "b"});
a$.next({n: 1, type: "a"});
a$.next({n: 2, type: "a"});
b$.next({n: 2, type: "b"});
b$.next({n: 0, type: "b"});
a$.next({n: 3, type: "a"});
b$.next({n: 3, type: "b"});
withConditionSub.unsubscribe();

// Zipping a$ and b$ without a conditional
const normalZipped$ = zip(a$, b$);
const normalZippedSub = normalZipped$.subscribe(msg => {
  console.log("[NORMAL ZIP]", msg);
});
a$.next({n: 0, type: "a"}); // same order as above
b$.next({n: 1, type: "b"});
a$.next({n: 1, type: "a"});
a$.next({n: 2, type: "a"});
b$.next({n: 2, type: "b"});
b$.next({n: 0, type: "b"});
a$.next({n: 3, type: "a"});
b$.next({n: 3, type: "b"});
normalZippedSub.unsubscribe();

Output:
[ZIPPED WITH CONDITION] [ { n: 1, type: 'a' }, { n: 1, type: 'b' } ]
[ZIPPED WITH CONDITION] [ { n: 2, type: 'a' }, { n: 2, type: 'b' } ]
[ZIPPED WITH CONDITION] [ { n: 0, type: 'a' }, { n: 0, type: 'b' } ]
[ZIPPED WITH CONDITION] [ { n: 3, type: 'a' }, { n: 3, type: 'b' } ]

[NORMAL ZIP] [ { n: 0, type: 'a' }, { n: 1, type: 'b' } ]
[NORMAL ZIP] [ { n: 1, type: 'a' }, { n: 2, type: 'b' } ]
[NORMAL ZIP] [ { n: 2, type: 'a' }, { n: 0, type: 'b' } ]
[NORMAL ZIP] [ { n: 3, type: 'a' }, { n: 3, type: 'b' } ]

See how for my [ZIPPED WITH CONDITION] the n's match for each pair. For normal zip, that doesn't occur, because messages came in out-of-order.
So is there a better way to do this? Maybe in a way that is extensible to zipping any number of observables on a condition?

A: In your solution you are building 2n + 2m observables. In other words, if a$ emits m values and b$ emits n values, you are creating 2n + 2m observables.
To see this, you just need to add complete methods to a$ and b$ to your test data sequence, like in the following example
a$.next({n: 0, type: "a"});
b$.next({n: 1, type: "b"});
a$.next({n: 1, type: "a"});
a$.next({n: 2, type: "a"});
b$.next({n: 2, type: "b"});
b$.next({n: 0, type: "b"});
a$.next({n: 3, type: "a"});
b$.next({n: 3, type: "b"});
a$.complete();
b$.complete();
withConditionSub.unsubscribe();

I think that, in order to find a good solution, you should complete you requirements considering also the time variable. For instance: "a$ and b$ emit always objects with n property increased by 1 sequentially - no holes in the sequential sequence are foreseen - and so on and so for.
If time related requirements can not be specified, it is difficult to imagine an RxJS solution


text:
Q: conn_7 Error control message: ClientId[6528662]:ErrorId[8]: Error on incoming message I am currently creating a firebase realtime database transaction in unity c# and keep getting this error:
[Error log]
[conn_7] Error control message: ClientId[6528662]:ErrorId[8]: Error on incoming message
UnityEngine.Debug:LogError (object)
Firebase.Platform.FirebaseLogger:LogMessage (Firebase.Platform.PlatformLogLevel,string) (at /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/app/platform/Unity/FirebaseLogger.cs:95)
Firebase.LogUtil:LogMessage (Firebase.LogLevel,string) (at /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/app/src/LogUtil.cs:69)
Firebase.LogUtil:LogMessageFromCallback (Firebase.LogLevel,string) (at /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/app/src/LogUtil.cs:77)
Firebase.AppUtil:PollCallbacks () (at /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/android_unity/armeabi-v7a/app/swig/Firebase.App_fixed.cs:4604)
Firebase.Platform.FirebaseAppUtils:PollCallbacks () (at /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/app/platform/FirebaseAppUtils.cs:33)
Firebase.Platform.FirebaseHandler:Update () (at /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/app/platform/Unity/FirebaseHandler.cs:208)
Firebase.Platform.FirebaseMonoBehaviour:Update () (at /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/app/platform/Unity/FirebaseMonoBehaviour.cs:45)

Source Code:
public void SendjointPoints()
{
    if (!TransactionComplete)
    {
        Debug.Log("not finished Transaction.  skip a frame.");
        return;
    }

    TransactionComplete = false;
    DatabaseReference reference = FirebaseDatabase.DefaultInstance.GetReference("jointPoints");
    Debug.Log("Running Transaction...");
    reference.RunTransaction(SendTransaction)
      .ContinueWithOnMainThread(task => {
          if (task.Exception != null)
          {
              TransactionComplete = true;
              Debug.Log(task.Exception.ToString());
          }
          else if (task.IsCompleted)
          {
              TransactionComplete = true;
              Debug.Log("Transaction complete.");
          }
      });
}

This error freezes Unity. any more transaction is not working until Unity Stop.
My code wants 1~2 transaction per a second.
Any idea why this is happening?
My code is trying to navigate through the various levels of mutabledata I got from my database reference.

*

*Unity version 2021.3.5f1

*Building for Android and Window

*IDE: Microsoft Visual Studio

*firebase_unity_sdk_9.4.0 (dotnet4 : FirebaseDatabase.unitypackage)


text:
Q: Multiple resizing in CodeIgniter I need to make two images of a single loaded picture. This images must have fixed width, - 180 and 300 pixels.
At the bottom of my current results. This function can resize and create just one of two images. Everybody failed on second image, I trying whole day, but I'm can't find reason. Need help.
$this->_resize($data['upload_data']['file_name'], 300);
$this->_resize($data['upload_data']['file_name'], 180);
private function _resize($file_name, $size) {
            $config['image_library'] = 'gd2';
            $config['source_image'] = 'img/upload/' . $file_name;
            $config['dest_image'] = base_url() . 'img/';
            $config['create_thumb'] = TRUE;
            $config['thumb_marker'] = '_' . $size;
            $config['maintain_ratio'] = FALSE;
            $config['width'] = $size;
            $config['height'] = $size;
            $this->load->library('image_lib', $config);
            $result = $this->image_lib->resize();

            $this->image_lib->clear();
            return;
        }

I'm use CodeIgniter 2.02

A: This could help you, from user guide

A good practice is use the processing
  function conditionally, showing an
  error upon failure, like this:
if ( ! $this->image_lib->resize())
{
    echo $this->image_lib->display_errors();
}

A: Dont load image_lib multiple times. Add image_lib in autoload libs and change
$this->load->library('image_lib', $config);

to
$this->image_lib->initialize($config);

A: Nill
Think that problem takes place because on the first run your script moves initial file to another folder. Try to use:
$config['new_image'] = base_url() . 'img/';

instead of
$config['dest_image'] = base_url() . 'img/';

A: I found myself this problem. In my case, I put the image source and new_image without base_url or REAL_PATH:
public function create_thumbnail($file_name='2012_02_23_15_06_00_1.jpg'){
    $this->layout = false;
    $image_url = PATH_TO_IMAGE_ARTICLE.DIRECTORY_SEPARATOR;
    $config['image_library'] = 'gd2';
    $config['source_image'] = 'assets/img/content/article/'.$file_name;
    $config['create_thumb'] = FALSE;
    $config['maintain_ratio'] = TRUE;
    $config['width'] = 210;
    $config['height'] = 160;
    $config['new_image'] = 'assets/img/content/article/thumb/thumb_' .  $file_name;

    $this->load->library('image_lib', $config);
    if(!$this->image_lib->resize())
    {
        echo $this->image_lib->display_errors();exit;
    }
    return TRUE;
}

See?
you don't put
$config['new_image'] = base_url().'assets/img/content/article/thumb/thumb_' .  $file_name;

but
$config['new_image'] = 'assets/img/content/article/thumb/thumb_' .  $file_name;


text:
Q: ¿Como convertir Filas en Columnas SQL Server? tengo la siguiente tabla en SQL Server:

Necesito que los CODIGO_USUARIO se muestren como columnas y los Items (Abanico Mesa, Abanico Techo, etc) se muestren como filas.


text:
Q: run two different after_create statements for different events i have two different after_create callbacks. I only want one to run when a field is present in the created record
i have an idea of how to do it but i can't quite get the syntax
#rental.rb
after_create :delete_booking , :if => ":booking_no = 'NOT NULL'"
after_create :set_requires_allocation

 def delete_booking
  @booking = Booking.where(:booking_no => self.booking_no).first
 @booking.destroy
end

def set_requires_allocation
self.user.requires_allocation = 'false'
end

also will set_requires_allocation actually acheive what i think it will by changing 'true' to 'false' in the users table?
thanks

A:
after_create :delete_booking, :if => Proc.new { |rental|
  rental.booking_no.present? }

A: Since you have two after_create callbacks you can combine them into one line:
after_create :delete_booking, :set_requires_allocation, :if => Proc.new {|r| r.booking_no.present?}

If you want the associated user to be updated as well in the set_requires_allocation callback, then you might want to do something like this:
def set_requires_allocation
   user.update_column(:requires_allocation, false)
end

Just setting the attribute to false, will not actually save the user record. I chose update_column, since that will prevent any callbacks or validations on the User model to be triggered. If you do want to trigger callbacks on User, then use update_attribute (triggers callbacks, does not trigger validation checks) or update_attributes, which will save the user with validation checks and callbacks.


text:
Q: How do I set my local git identity? This is my first setup of a repo on GitHub. I am running Linux, and my GitHub account has ssh-keys setup for my computer.
When I try to run git commit, I get this error.
git commit -m "examples"
*** Please tell me who you are.

Run

  git config --global user.email "you@example.com"
  git config --global user.name "Your Name"

to set your account's default identity.
Omit --global to set the identity only in this repository.

fatal: unable to auto-detect email address (got 'j0h@sx.(none)')
j0h@sx:~/Learning-OpenCV-3_examples$   git config --global user.email "you@example.com"

What I do not understand is which name(s) and identity this is asking for when it says git config --global user.name "Your Name" does that mean the name on my PC? Or my GitHub username? Or my email username? Or something else?
I have tried a variety of combinations, but I still cannot commit via the command line.

A: Two issues here:
Setting Your Git Identity
First, your identity should be simply your full name and email address which could be your GitHub username and email combo. But this is not a verification stage as much as a "tag" to identify you; this has nothing to do directly with your GitHub username unless they are indeed one and the same.
So perhaps your version of those commands would be:
git config --global user.email "j0h@example.com"
git config --global user.name "jOh"

And then check those values like this:
git config -l

Output should be something like this; modified version of my own output for that command so the credential.helper and core.editor settings might be different for you:
credential.helper=osxkeychain
user.name=jOh
user.email=j0h@example.com
core.editor=nano

Adding Files and Making a Commit
But then you say this:

When I try to run git commit, I get this error.
git commit -m "examples"

Well, that command is missing the -a which is an alias for --all which means the following according to the man page for git-commit:

Tell the command to automatically stage files that have been modified and deleted, but new files you have not told Git about are not affected.

So the command would be:
git commit -a -m "examples"

And if you have not already added files to the repository, you would run git add for the specific file:
git add [filename]

Or maybe just use a wildcard to get all files set:
git add *

And then run the git commit command like this:
git commit -a -m "examples"


text: Q: git pull gets Permission denied (publickey) in Intellij but works in terminal I created keys with ssh-keygen and added it to ssh-agent. Things works fine in terminal, but Intellij seems to run git pull without using keys in ssh-agent. Is there a way to tell intellij to check the keys in ssh-agent


text:
Q: Why is setting textContent triggering reflow? I have a simple countUp/Down utility, which utilizes requestAnimationFrame to set the textContent of a specific DOM. Surprisingly every time I make the content update, the browser triggers a reflow. Is there any way to avoid this?
There is a simple demo on requestAnimationFrame found in CodePen, using the performance tool of Chrome dev tool, you can see each callback call is followed by reflow (Layout)
To my knowledge, setting textContent shouldn't cause style recalculation. I have also tried giving the element fixed dimension, but that did not help.

A: Unlike some methods, it doesn't trigger a reflow synchronously, but when the next painting will occur, the browser will still have to recalculate the layout since the textContent change could have changed the page's layout.
The only way to avoid a reflow at all I can think of, would be to render this text in a <canvas>.


text:
Q: How to keep the last row of a matching string in excel I want to remove all the rows except the last one for a matching userId "james.oconnor", i have a huge excel file and there are multiple rows of same "userId" with different "account" name. i want to keep only the last row having all the "account" name for a given userId - how can i do that?
How can i turn my Excel file from  to

Many Thanks, Deepak

A: I would add a helper column that counts the number of accounts you have in that line, e.g. =COUNTA(F2:AA:2) in cell E2 then sort the sheet by this new column in descending order (highest numbers on the top).
After that you can either go through Remove Duplicates (only filtering by the userId column) or a VLOOKUP to only keep the top ones.
Does that work for you?

A: You could try:
Option Explicit

Sub test()

    Dim Counter  As Long, i As Long, LastRow As Long
    Dim LookUpValue As String

    LookUpValue = "james.oconnor"

    With ThisWorkbook.Worksheets("Sheet1")

        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
        Counter = 0

        For i = LastRow To 2 Step -1

            If .Range("A" & i).Value = LookUpValue Then

                Counter = Counter + 1

                If Counter > 1 Then
                    .Rows(i).EntireRow.Delete
                End If

            End If

        Next i

    End With

End Sub


text:
Q: android :How to show following pattern on empty list view? I have seen in facebook and flipkart that if list is empty they show a image or whatever which clearly indicates that something is loading
how to achieve this.Image is not static it look like wave.

A: You can use FiftyShadesOf library to archive that effect


text:
Q: MVC4 EF5 Changes not saved to DB My code looks like this: (where "user" is the UserProfile instance passed back from the view after being edited)
UserProfile original = DBContext.UserProfiles.Where(x => x.UserId == user.UserId).FirstOrDefault();
if (original != null)
{
   original = user;
   DAL.DAL.Instance.TGIMobiledb.SaveChanges();
}

This code fires without error, but does not update the DB. After some research it seems I have to add the following line before calling SaveChanges()
DBContext.Entry(original).State = EntityState.Modified;

But that line of code causes this error:
"An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key."
The changes saves to the db fine if I assign every field manually like this:
original.UserId = user.UserId;
original.FirstName = user.FirstName;
original.Surname = user.Surname;
original.UserName = user.UserName;

Obviously this is less than optimal, especially with the larger entities.

A: Try:
DBContext.Entry(original).CurrentValues.SetValues(user);

A: I'm guessing you retrieve the user and check for null to see if you need to create or update it.
Instead, you can check the UserId field.
if (user.UserId == 0)
{
    DBContext.UserProfiles.Add(user);
}
else
{
    DBContext.UserProfiles.Attach(user);
    DBContext.Entry(user).State = EntityState.Modified;
}


text:
Q: Silent printing via Chrome for Android I have an application that should print receipts. Now it works as a website but also it can work as PWA. For silent printing in Linux or Windows I just call Chrome with argument --kiosk-printing and it work perfectly. The app prints receipts without a confirmation dialog.
But how I can make it for Android device?
I tried various utils to turn the Android device into a kiosk, but this is overkill, those utils are paid, etc. All I need is silent printing.


text: Q: Automate Deployment from windows server to Linux/Raspbian How can I automate the build and deployment process from Windows server as a controlling machine to multiple Linux (Raspbian OS) as node machine. Is there any tool which takes care of cross platform deployment, if yes then suggest ?


text:
Q: Entity Framework LINQ Get all items part of another collection Get all the NWatchRelation records from the DBContext that overlap those in the relationsCollection.
The same Id, RelatedNodeId, and RelationType (enum: int) should be what's considered a match.
public class NWatchRelation : INWatchRelation
{
    public int Id { get; set; }
    public int NodeId { get; set; }
    public NWatchNode Node { get; set; }
    public int RelatedNodeId { get; set; }

    public NWatchNode RelatedNode { get; set; }
    public NWatch.NWatchRelationType RelationType { get; set; }
}

INWatchRelation[] relationsCollection = GetRelations();

A: You can do a LINQ join between these 2 collections.
var result = from a in db.NWatchRelations.AsEnumerable()
             join b in relationsCollection on a.RelatedNodeId equals b.RelatedNodeId
                                           && a.Id equals b.Id
                                           && a.RelationType equals b.RelationType
             select a;

A: The only way you can do that fully in LINQ to Entities is to manually compose UNION ALL query by using Queryable.Concat like this:
IQueryable<NWatchRelation> query = null;
foreach (var relation in relationsCollection)
{
    var m = relation;
    var subQuery = db.NWatchRelations
        .Where(r => r.Id == m.Id
            && r.RelatedNodeId == m.RelatedNodeId
            && r.RelationType == m.RelationType);
    query = query == null ? subQuery : query.Concat(subQuery);
}

But please note that it's a limited approach and will not work if the relationsCollection is big.

A: You could create a kind of unique key using the three values:
//To create a unique key (an string, which is a primitive type) combining the three values
var keys=relationsCollection.Select(e=>e.Id+"-"+e.RelatedNodeId+"-"+ ((int)e.RelationType)).Distinct();

var query=db.NWatchRelations.Where(r=>keys.Any(k=>k == (SqlFunctions.StringConvert((double)r.Id)+"-"+
                                                        SqlFunctions.StringConvert((double)r.RelatedNodeId )+"-"+
                                                        SqlFunctions.StringConvert((double)((int)r.RelationType)) ));

If your NWatchRelations table doesn't have many rows or relationsCollection is a small collection, please,  use one of the alternatives that were proposed earlier at your convinience.

A: Also you can have the directly linked like this
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public NWatchRelation()
    {
        this.INWatchRelation = new HashSet<INWatchRelation>();
    }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<INWatchRelation> INWatchRelation { get; set; }

But the entiry relation must be liked like this in order to work properly
Then you could select/list it like this
db.NWatchRelation.INWatchRelation.ToList();


text:
Q: MongoDB shell getCollectionNames not working properly When in mongo shell 3.x I found this strange behaviour:

*

*Typing db.getCollectionNames() i get [] but I know that there are collections

*Typing db.myColl.findOne() in fact it returns  a document as I expect

Does anyone know why?
Thanks

A: You're already on 3.x. so this shouldn't have any impact i take ?
docs.mongodb.com/manual/reference/method/db.getCollectionNames
as the link says it returns empty array for shell lower than 3.X

A:
For MongoDB 3.0 deployments using the WiredTiger storage engine, if
  you run db.getCollectionNames() from a version of the mongo shell
  before 3.0 or a version of the driver prior to 3.0 compatible version,
  db.getCollectionNames() will return no data, even if there are
  existing collections.

FOr more details, refer here