text:
Q: How to get the third wednesday of given year from edittext? I want to make a app where the user puts a number(year)in edittext and when you click the button the user gets in a textview the third wednesday of april from that year. For example they put 2020 and get as a result the date 15.04.2020. that was the third wednesday of april in 2020. I have an edittext, a button and a textview. Thank you for helping.
Problem solved thank you:

A: LocalDate with TemporalAdjuster
Use TemporalAdjuster implementation TemporalAdjusters.dayOfWeekInMonth.
Parse your textual input of year number to an int using Integer class.
Get the first day of your specified year as a LocalDate object.
Year y = Year.of( 2021 ) ;
LocalDate startOfYear = y.atDay( 1 ) ;  // First day of the year.

Move to April. Using immutable objects, so we get a new fresh object rather than alter ("mutate") the original.
LocalDate ld = startOfYear.with( Month.APRIL ) ;  // Move to the first of April, our desired month.

Get a temporal adjuster implementation for the 3rd Wednesday of the month.
int ordinal = 3 ;  // Third such day of the month.
DayOfWeek dow = DayOfWeek.WEDNESDAY ;
TemporalAdjuster ta = TemporalAdjusters.dayOfWeekInMonth( ordinal , dow ) ;

Apply the adjuster to get another LocalDate object, our desired result, the third Wednesday of that month.
LocalDate thirdWednesdayOfApril = ld.with( ta ) ;  // Move to the 3rd Wednesday of April of the specified year.

To generate text in a certain format for presentation to the user, use DateTimeFormatter.ofLocalizedDate. Search to learn more, as this has been addressed many times already on Stack Overflow.

About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?

*

*Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later  - Part of the standard Java API with a bundled implementation.

*

*Java 9 adds some minor features and fixes.

*Java SE 6 and Java SE 7

*

*Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

*Android

*

*Later versions of Android bundle implementations of the java.time classes.

*For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….


text:
Q: Binding UserControl properties within DataGridRow I need to bind UserControl properties within a DataGrid row. My XAML is as below.
I have DirectionArrow control which shows different angles in each row. How can I bind this to angle property DataGrid ItemsSource property?
<DataGrid x:Name="DtgProfiles" Grid.Row="0"  HorizontalScrollBarVisibility="Auto" SelectionMode="Extended" ItemsSource="{Binding Project.SelectedAxis.Profiles}" CanUserDeleteRows="False" CanUserAddRows="False" CanUserSortColumns="False" >
    <DataGrid.Columns>
        <DataGridTextColumn Header="No" Width="4*" Binding="{Binding Path=ProfileOrder,Mode=TwoWay}"  IsReadOnly="True" />
        <DataGridTemplateColumn Header="Direction" Width="8*" >
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <controls:DirectionArrow
                        HorizontalAlignment="Center" Height="13" Margin="0,0,0,0"
                        VerticalAlignment="Center" Width="13" BackgroundFill="LightBlue"
                        LineAngle="{Binding Direction}" LineLength="1"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

A: I  resolved this by adding the property directly to the class instead of vM

redpajama_set_name: RedPajamaStackExchange


text:
Q: User login and stay logged in with phonegap app? I'm building a mobile app for my website using Phonegap and I am using PHP Codeigniter framework to create my REST API. I need to allow users to log in to the app and retrieve information but I am little confused on the authentication part.
Right now this is what I have in mind:

*

*User logs in with username/password (they will be send to the server using HTTPS)

*My API will check the db to see if the user exists

*If the user exists generate a random string (token) and send it back to client

*On the client side (mobile app), store the token somewhere

*Every time user requests information from the server, send the token for validation

I decided to go with token method because I needed to allow users to stay logged in to the app once they login for the first time (I read that storing username/password on client side is bad).
So here are my questions,
Is my method valid/safe? If so how is token stored on phonegap? Will localStorage do the job?
Is there a better & simpler method?
Are there libraries that could help me do this easier/faster? especially with building REST API?
Lastly, I heard about OAuth2 but is this only for when you want to allow 3rd party logins (google, facebook etc)? I've looked into it and there seems to be an OAuth for PHP and OAuth for Phonegap. If I implement this, will I need to do it in my REST API AND phonegap side?
I'm fairly new to all this so any explanations with examples will be helpful.

A: I suggest to use your token method.Every time app launches check the localstorage for user token is set if not set up http request and store the token in localstorage.
Here is sample code
function validateUser(username,password){
  //get the user token from local storage
    if(window.localStorage.getItem('usertoken')==null){
           //set up the http request
            $.ajax({
              url:'www.example.com/login.php',
              method:post,
              data:{'username':username,'password':password}
              success:function(data){
                 //set the token in localstorage
                 window.localStorage.setItem('usertoken',data);

              }
           });
       }
      }
    }


text:
Q: Unable to read a continuous data stream from a node child process in Node.js First things first. The goal I want to achieve:
I have two processes:

*

*the first one is webpack that just watches for file changes and pushes the bundled files into the dist/ directory

*the second process (Shopify CLI) watches for any file changes in the dist/ directory and pushes them to a remote destination

My goal is to have only one command (like npm run start) which simultaneously runs both processes without printing anything to the terminal so I can print custom messages. And that's where the problem starts:
How can I continuously read child process terminal output?
Printing custom messages for webpack events at the right time is pretty easy, since webpack has a Node API for that. But the Shopify CLI only gives me the ability to capture their output and process it.
Normally, the Shopify CLI prints something like "Finished Upload" as soon as the changed file has been pushed. It works perfectly fine for the first time but after that, nothing is printed to the terminal anymore.
Here is a minimal representation of what my current setup looks like:
const spawn = require('spawn');

const childProcess = spawn('shopify', ['theme', 'serve'], {
  stdio: 'pipe',
});

childProcess.stdout.on('data', (data) => {
  console.log(data);
});

childProcess.stderr.on('data', (data) => {
  // Just to make sure there are no errors
  console.log(data);
});


text:
Q: How to implement customized authentication in Spring Boot Application I am building a web app with Spring Boot. Post requests can be made by a phone app to upload data in form of xml to the cloud. The phones that are allowed to push data are required to be registered company phones. The way to authenticate the APIs calls is to look up the android ID of the phone in a corporate database. It will accept the data only if the Android ID exists. The idea is to embed the android ID in the header of requests. Since it is not a typical way for authentication, how do I implement it with Spring Security? Or we don't even need Spring Security. Just extract the Android ID from the header and look it up in database. Reject the request if it is not a valid ID. Any advice would help.

A: Nothing prevents you from using Authorization header in a creative way, i.e., by embedding the Android ID into it. Then, in order to add authentication to your endpoints, you can use an AOP interceptor:
Protected operation marker interface:
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ProtectedOperation {
}

Interceptor:
@Aspect
@Component
public class SecurityAspect {
    private CorporateService corpService; // this is your custom service to check Android IDs
    @Autowired
    public SecurityAspect(CorporateService corpService) {
        this.corpService = corpService;
    }
    @Around("@annotation(operation)")
    public Object protectedOperationPermissionCheck(final ProceedingJoinPoint pjp, final ProtectedOperation operation) throws Throwable {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        String header = requestAttributes.getRequest().getHeader("Authorization");
        String androidId = // get the ID from header - try not to use existing authorization header formats like Bearer, Negotiate etc. to avoid collision with other authentication systems
        if (corpService.isAuthorized(androidId)) {
            return pjp.proceed();
        }
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.flushBuffer();
        return null;
    }
}

Make sure to add the spring-boot-starter-aop dependency to your pom.xml, for @Aspect support
EDIT: to protect an endpoint, annotate the endpoint method in your controller with @ProtectedOperation, and add @EnableAspectJAutoProxy to your Spring Boot application


text:
Q: How to get Key value pair from XML document Java I have an XML document from which I would like to retrieve the key and value from this XML document. However I am have trouble getting both, I realize I should use the data type of Map but I am unsure how to accomplish this.
Example:
I have the following XML file:
<?xml version="1.0"?>
    <config>
        <Request name="ValidateEmailRequest">
            <requestqueue>emailrequest</requestqueue>
            <responsequeue>emailresponse</responsequeue>
        </Request>
        <Request name="CleanEmail">
            <requestqueue>Cleanrequest</requestqueue>
            <responsequeue>Cleanresponse</responsequeue>
        </Request>
    </config>

I'd like to write a method which parses this file and returns me a key value pair of the node (key) and value (value) of the XML.
Such as [requestqueue,emailrequest] [responsequeue,emailresponse], etc...
What I currently have:
public Map<String, String> parseXML(File f) throws Exception {

    String xml = FileUtils.readFileToString(f);

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    Document document = builder.parse(new InputSource(new StringReader(xml)));
    Element rootElement = document.getDocumentElement();

    // I'm stuck...

    return null;
}

Any help or assistance would be much appreciated, thanks.
Edit:
I did some research and I found something that will print me the values but only 1 of the keys "Return"
@Test
public void testConverter() throws Exception {
    String xml = ("xmlDir/request.xml");
    Map<String,String> map = convertNodesFromXml(xml);

    for(Map.Entry<String, String> entry: map.entrySet()) {
        String key = entry.getKey();
        String value = entry.getValue();

        logger.debug("Key: "+key+" Value: "+value);
    }

}

public static Map<String, String> convertNodesFromXml(String xml) throws Exception {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document document = db.parse(xml);

    Element doc = document.getDocumentElement();
    logger.debug(doc.getFirstChild());

    return createMap(document.getDocumentElement());
}

public static Map<String, String> createMap(Node node) {
    Map<String, String> map = new HashMap<String, String>();
    NodeList nodeList = node.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node currentNode = nodeList.item(i);
        if (currentNode.hasAttributes()) {
            for (int j = 0; j < currentNode.getAttributes().getLength(); j++) {
                Node item = currentNode.getAttributes().item(i);
                map.put(item.getNodeName(), item.getTextContent());
            }
        }
        if (node.getFirstChild() != null && node.getFirstChild().getNodeType() == Node.ELEMENT_NODE) {
            map.putAll(createMap(currentNode));
        } else if (node.getFirstChild().getNodeType() == Node.TEXT_NODE) {
            map.put(node.getLocalName(), node.getTextContent());
        }
    }
    return map;
}

Output:
2015-08-18 15:01:31,651 : Key: Return Value:

    136
    125
    SEPTEMBER
    250

    OCTOBER
    250
    125
    136

    136
    125
    250
    APRIL

    136
    JUNE
    250
    125

    MAY
    136
    250
    125

    136
    250
    125
    JANUARY

    136
    125
    250
    MARCH

    250
    AUGUST
    136
    125

  3000

    136
    125
    250
    DECEMBER

    136
    JULY
    125
    250

    136
    125
    FEBRUARY
    250

  1500
  555-11-2222

    125
    136
    NOVEMBER
    250

  1632

  1
  22000
  1
  22000

  1970-01-01

  555-11-2222

      CA

A: The function getChildNodes() https://docs.oracle.com/javase/7/docs/api/org/w3c/dom/Node.html#getChildNodes() returns a nodelist which contains the children of this node. Maybe you make use of that function to walk through your nodetree.
Alternatively you can use a frameworks like Jaxb which maps your xml into Java Pojos. With that pojos you can build your map

A: Have you look at java documentation
First of all I will try with
NodeList nodeList = rootElement.getElementsByTagName("equestqueue");

And later I will iterate through this List (also look at the api) and find attributes, values etc...


text:
Q: Binary Search Tree Data in Nodes always is zero I've been working on my Binary search tree for a while and the functions seem to work but I'm running into the same problem I had when I had a linked list program assignment. My nodes don't seem to want to store data. I can't figure out what the problem is. When I print it only prints zeros, the correct number of zeros, but still just zeros. Here's my code for my node. I should mention this is C++.
class Node{
    friend class BST;
    private:
    int data;
    Node *left;
    Node *right;
    public:
    Node(int data);
};

My add function is:
void BST::add(Node* node, int d) {
    if (root == NULL) {
        root = new Node(d);
    }
    else if (d <= node->data) {
        if (node->left == NULL) {
            node->left = new Node(d);
        }
        else {
            add(node->left, d);
        }
    }
    else if (d > node->data) {
        if (node->right == NULL) {
            node->right = new Node(d);
        }
        else {
            add(node->right, d);
        }
    }
}

Why won't it store data?

A: Please modify your Node::Node(int) into:
Node::Node(int data) {
    left = NULL;
    right = NULL;
    this->data = data;
}

Your Node::Node() described in your comment does not store the data at all; and your BST::add() relies on it to store values into Nodes.


text:
Q: Invalid argument --model_config_file_poll_wait_seconds I'm trying to start tensorflow-serving with the following two options like on the documentation
docker run -t --rm -p 8501:8501 \
    -v "$(pwd)/models/:/models/" tensorflow/serving \
    --model_config_file=/models/models.config \
    --model_config_file_poll_wait_seconds=60

The container does not start because it does not recognize the argument --model_config_file_poll_wait_seconds.
unknown argument: --model_config_file_poll_wait_seconds=60
usage: tensorflow_model_server

I'm on the latest docker image, 1.14.0 and the line is taken straight from the documentation
https://www.tensorflow.org/tfx/serving/serving_config
Does this argument even work?
Many thanks.

A: It seems https://www.tensorflow.org/tfx/serving/serving_config is talking about code that has not been released as a new version yet, which is odd. I will ask about that.
That package is generated from this source:
https://github.com/tensorflow/serving/blob/master/tensorflow_serving/g3doc/serving_config.md, it mentions the --model_config_file_poll_wait_seconds flag.
However, the same document for 1.14.0 has no mention of the flag:
https://github.com/tensorflow/serving/blob/1.14.0/tensorflow_serving/g3doc/serving_config.md
Try using the nightly tensorflow serving image and see if it works.
docker run -t --rm -p 8501:8501 \
    -v "$(pwd)/models/:/models/" tensorflow/serving:nightly \
    --model_config_file=/models/models.config \
    --model_config_file_poll_wait_seconds=60

A: Just tried. Tensorflow Serving 2.1.0 supports it while 1.14.0 doesn't.


text:
Q: Good way to chain filter functions in javascript I've got large json array of objects that I need to filter down based on multiple user select inputs. Currently I'm chaining filter functions together but I've got a feeling this is most likely not the most performant way to do this.
Currently I'm doing this:
var filtered = data.filter(function(data) {
    return Conditional1
  })
  .filter(function(data) {
    return Conditional2
  })
  .filter(function(data) {
    return Conditional3
  }) etc...;

Although (I think) with each iteration 'data' could be less, I'm wondering if a better practice would be to do something like this:
var condition1 = Conditional1
var condition2 = Conditional2
var condition3 = Conditional3
etc...

var filtered = data.filter(function(data) {
  return condition1 && condition2 && condition3 && etc...
});

I've looked into multiple chains of higher order functions, specifically the filter function - but I haven't seen anything on best practice (or bad practice, nor have I timed and compared the two I've suggested).
In a use case with a large data set and many conditionals which would be preferred (I reckon they are both fairly easily readable)?
Or maybe there is a more performant way that I'm missing (but still using higher-order functions).

A: Store your filter functions in an array and have array.reduce() run through each filter, applying it to the data. This comes at the cost of running through all of them even when there's no more data to filter.
const data = [...]
const filters = [f1, f2, f3, ...]
const filteredData = filters.reduce((d, f) => d.filter(f) , data)

Another way to do it is to use array.every(). This takes the inverse approach, running through the data, and checking if all filters apply. array.every() returns false as soon as one item returns false.
const data = [...]
const filters = [f1, f2, f3, ...]
const filteredData = data.filter(v => filters.every(f => f(v)))

Both are similar to your first and second samples, respectively. The only difference is it doesn't hardcode the filters or conditions.

A: interesting question

data = new Array(111111).fill().map((a,n) => n);

const f1 = (a) => a % 2;
const f2 = (a) => a % 5;
const f3 = (a) => a > 347;
const filters = [f1, f2, f3];

// 1
t1 = performance.now();
res = data.filter(a=>a%2).filter(a=>a%5).filter(a=>a>347);
t2 = performance.now();
console.log("1) took " + (t2-t1) + " milliseconds.");
// 2
t1 = performance.now();
res = data.filter(a=>a%2 && a%5 && a>347);
t2 = performance.now();
console.log("2) took " + (t2-t1) + " milliseconds.");
// 3
t1 = performance.now();
res = filters.reduce((d, f) => d.filter(f) , data)
t2 = performance.now();
console.log("3) took " + (t2-t1) + " milliseconds.");
// 4
t1 = performance.now();
res = data.filter(v => filters.every(f => f(v)))
t2 = performance.now();
console.log("4) took " + (t2-t1) + " milliseconds.");

also remember in for-loop and for example with case of two loops one 3000 and one 7 then : 3000x7 > 7x3000 in time measuring .

A: The two options are not exactly the same, although they could produce the same result
var filtered = data.filter(function(data) {
    return Conditional1
  })
  .filter(function(data) {
    return Conditional2
  })
  .filter(function(data) {
    return Conditional3
  }) etc...;

That option is better if you want to check the conditions independently of one another. You should use that if you need the data filtered by condition1 before filtering by condition2. If what you want is to filter items that match the 3 conditions or a combination of them, use the second one:
var condition1 = Conditional1
var condition2 = Conditional2
var condition3 = Conditional3
etc...

var filtered = data.filter(function(data) {
  return condition1 && condition2 && condition3 && etc...
});

A: If you think of this as a "for-loop" optimization problem, you can see that the original approach results in iterating the list multiple times.
Your second approach will reduce the iterations to one pass.
After that, you're just looking at the best way to quickly decide whether an item passes muster or not.

A: not sure about performance but I am in love with reduce method in javascript these days. Something like:
arr.reduce((itemMap, item) => {
    if (item.something !== somethingElse) return itemMap;
    return itemMap.push(item);
}, [])

this works essentially like .filter but you can do much more with it. Like if you want to even map some values, you could do so by updating the item object and returning that item if it matches all the conditionals.
Although, not sure how performant this is..

A: type PredicateFn = (input: any) => boolean

const isBig: PredicateFn = (n: number): boolean => {
  return n > 100
}
const isEven: PredicateFn = (n: number): boolean => {
  return n % 2 === 0
}

const isInt: PredicateFn = (n: number): boolean => {
  return !n.toString().includes('.')
}

function composeFilters<T>(array: T[], predicates: PredicateFn[]): T[] {
  function filter(input: T) {
    return predicates.every(predicate => predicate(input))
  }
  return array.filter(filter)
}

const input = [1, 2.5, 101, 100.5, 110, 220.24, 333, 400, 500, 223, 111]

const result = composeFilters(input, [isBig, isInt, isEven])

console.log(result)


text:
Q: Object required error, copy paste loop I am trying to copy a range from one sheet to the other but can not get the code to run with out an error(object-required). Can someone please correct where I am going wrong.
In addition I need this code to repeat this process 20 times; I want this list to have 20 duplicates of each value. should I just make a loop and run this code 20 times? Or is there a faster way to do this?
Thank you.
Sub Update_FSKU()

'Range of list in Final Good Tab
Dim TrowFG As Integer
Dim BrowFG As Integer

'Range of Existing List in Final Tab
Dim TrowF As Integer
Dim BrowF As Integer

'Application.ScreenUpdating = False
BrowF = (ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row) + 1
Worksheets("Finished Good").Activate
TrowFG = 2
BrowFG = (ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row) + 1

Range("A2:" & "B" & BrowFG).Copy

Sheets("Final").Activate.Range("A" & BrowF).PasteSpecial

End Sub

A: Activate doesn't return a value, so you can't chain .Range() onto it.
Try:
Sheets("Final").Range("A" & BrowF).PasteSpecial


text:
Q: SQL sysdate / Trunc functions in Oracle Ok so i'm trying to return all information in a a month that preceeds the current month. I'm struggling slightly with the format and code. Here is my attempt.
I can provide table structure if needed
SELECT hd.Holiday_desc,
soh.Site_Name,
FROM   holiday_details hd
WHERE TRUNC(LAST_DAY(SYSDATE), 'MM' - 1) = TRUNC(hdep.Holiday_Departure, 'MM')
       INNER JOIN holiday_departure hdep
               ON hd.holiday_code = hdep.holiday_code
Inner join site_visited sv on hd.Holiday_Code = sv.Holiday_code
inner join site_of_holiday soh on sv.Site_code = soh.Site_code

A: I would use the ADD_MONTHS() function and the BETWEEN operator to accomplish this:
SELECT hd.Holiday_desc,
soh.Site_Name,
FROM   holiday_details hd
WHERE hdep.Holiday_Departure BETWEEN trunc(add_months(sysdate,-1),'MM')
                                 AND last_day(add_months(sysdate,-1)) + .99999
       INNER JOIN holiday_departure hdep
               ON hd.holiday_code = hdep.holiday_code
Inner join site_visited sv on hd.Holiday_Code = sv.Holiday_code
inner join site_of_holiday soh on sv.Site_code = soh.Site_code;

Also, if your column hdep.Holiday_Departure is indexed you would want to avoid using the TRUNC function so you do not invalidate any indexes on this column.

A: I think you want
SELECT
  hd.Holiday_desc,
  soh.Site_Name
FROM   holiday_details hd
       INNER JOIN holiday_departure hdep
               ON hd.holiday_code = hdep.holiday_code
       INNER JOIN site_visited sv
               ON hd.Holiday_Code = sv.Holiday_code
       INNER JOIN site_of_holiday soh
               ON sv.Site_code = soh.Site_code
WHERE
  TRUNC(hdep.Holiday_Departure, 'MM') = ADD_MONTHS(TRUNC(SYSDATE, 'MM'), -1)

You'll need to learn a bit about the syntax. 'MM' - 1 is not going to work, just as having a WHERE clause in the middle of your query. :) Also, there was a comma to many just before FROM.


text:
Q: Most memory efficient data structure to store 2D array values (Java) So I am trying to make the most memory efficient algorithm for the following problem: We have an infinite basement.
Now we start with no coins on the grid, so the outcome is always predictable. I used a 2D array for this. I was wondering if there was another way. I was thinking about Hashmaps or Hashsets but i don't know how that would work

A: Track only the locations visited that have coins.
A HashSet where each entry is an x,y pair will do; initially it is empty.
If x,y is not in the map, it has no coin - add an entry.
If x,y is in the map, it has a coin - remove the entry.
This should have better memory utilization than an array that covers everywhere you 'might' visit, and you don't have to guess at how large an array is large enough.

A: If you want to introduce a Map in your project, that's doable.
As a key you can generate a String combined from x and y coordinates, and Boolean will be a convenient option as a value, if you don't need to represent other cases apart from coin is present or not.
The HashMap can entirely substitute the basement array in your code. In addition to a map you need to introduce two int fields that will represent the size in x and y directions.
You can prepopulate the map in the same way you've done it with the array. And instead of initializing all coordinates with the same default value, you can generate random starting values.
In the game-loop you can toggle the value mapped to a particular tile like that:
map.put(key, !map.get(key));

or this way by using Java 8 method compute():
hasCoinByTileKey.compute(key, (k, v) -> !v);

And to find out whether the tile contains the coin, use get():
if (map.get(key)) {
    // do something
}

In regard to performance, it'll perform reasonably well, but slightly slower than an array-based solution. Because under the hood, HashMap is backed by the array. In short, each array element constitutes a bucket, which correspond to a particular range of hash-values. Map-entries will form a linked list, if several keys are mapped to the same bucket (after a certain threshold, the list will get transformed into a tree). The same will holds true for a HashSet, because the HashSet class is build on top of the HashMap.
If you replace an array with the HashMap your Basement class might look like that:
public class Basement {
    public static void main(String[] args) {
        new Basement(20, 20).update();
    }

    private static final int STEPS = 20;
    private Map<String, Boolean> hasCoinByTileKey = new HashMap<>();
    private List<Tile> path = new ArrayList<>();
    private int rows;
    private int cols;

    private record Tile(int x, int y) {}

    public Basement(int rows, int cols) {
        this.rows = rows;
        this.cols = cols;

        Random random = new Random();
        for (int row = 0; row < cols; row++) {
            for (int col = 0; col < cols; col++) {
                hasCoinByTileKey.put(getKey(row, col), random.nextBoolean());
            }
        }
    }

    public static String getKey(int row, int col) {
        return row + "," + col;
    }

    public void update() {
        path.clear(); // cleaning the previous keys
        int x = rows / 2;
        int y = cols / 2;
        int orientation = 0;
        /*
        0 - up
        1 - right
        2 - left
        3 - down
        */
        for (int steps = 0; steps < STEPS; steps++) {
            path.add(new Tile(x, y)); // updating the path will current coordinates
            String key = getKey(x, y);
            if (!hasCoinByTileKey.get(key)) {
                hasCoinByTileKey.compute(key, (k, v) -> !v); // toggling the boolean value of the tile
                if (orientation == 0) {
                    y += 1;
                    orientation = 1;
                } else if (orientation == 1) {
                    x += 1;
                    orientation = 3;
                } else if (orientation == 2) {
                    x -= 1;
                    orientation = 0;
                } else {
                    y -= 1;
                    orientation = 2;
                }
            } else {
                hasCoinByTileKey.compute(key, (k, v) -> !v); // toggling the boolean value of the tile
                if (orientation == 0) {
                    y -= 1;
                    orientation = 2;
                } else if (orientation == 1) {
                    x -= 1;
                    orientation = 0;
                } else if (orientation == 2) {
                    x += 1;
                    orientation = 3;
                } else {
                    y += 1;
                    orientation = 1;
                }
            }
        }
        System.out.println(path.size());
        System.out.println(path);
        this.print();
    }

    public void print() {
        boolean[][] grid = new boolean[rows][cols];
        for (Tile tile: path) {
            grid[tile.x][tile.y] = true;
        }
        for (int row = 0; row < rows; row++) {
            for (int col = 0; col < cols; col++) {
                System.out.print(grid[row][col] ? 'a' : ' ');
            }
            System.out.println();
        }
    }
}

In order to print the path, a separate list is used to track the path durin the execution of update method. Object that hold coordinates is a record.
main() - demo
public static void main(String[] args) {
    new Basement(20, 20).update();
}

Output - 20 steps (the pattern differs from your example because roughly a half of the tiles will be prepopulated with coins)

        aaaa
        aaaa
        aaa
        aaaaa
         aaaa
          aa

A: public final class Basement {

    private final Map<Integer, Set<Integer>> board = new HashMap<>();
    private final Tile curTile = new Tile();
    private final Axis row = new Axis();
    private final Axis col = new Axis();

    public void nextStep() {
        if (hasCoin())
            pickUpCoinAndRotate();
        else
            placeCoinAndRotate();

        col.update(curTile.col);
        row.update(curTile.row);
    }

    private boolean hasCoin() {
        return hasCoin(curTile.col, curTile.row);
    }

    private boolean hasCoin(int col, int row) {
        return board.getOrDefault(row, Set.of()).contains(col);
    }

    private void placeCoinAndRotate() {
        board.computeIfAbsent(curTile.row, val -> new HashSet<>()).add(curTile.col);
        curTile.rotateClockwise();
    }

    private void pickUpCoinAndRotate() {
        board.computeIfAbsent(curTile.row, val -> new HashSet<>()).remove(curTile.col);
        curTile.rotateCounterclockwise();
    }

    private void print() {
        for (int row = this.row.min; row <= this.row.max; row++) {
            for (int col = this.col.min; col <= this.col.max; col++)
                System.out.print(hasCoin(col, row) ? 'a' : '.');

            System.out.println();
        }
    }

    private enum Orientation {
        UP {
            @Override
            public Orientation rotateClockwise(Tile curTile) {
                curTile.col++;
                return RIGHT;
            }

            @Override
            public Orientation rotateCounterclockwise(Tile curTile) {
                curTile.col--;
                return LEFT;
            }
        },
        RIGHT {
            @Override
            public Orientation rotateClockwise(Tile curTile) {
                curTile.row++;
                return DOWN;
            }

            @Override
            public Orientation rotateCounterclockwise(Tile curTile) {
                curTile.row--;
                return UP;
            }
        },
        DOWN {
            @Override
            public Orientation rotateClockwise(Tile curTile) {
                curTile.col--;
                return LEFT;
            }

            @Override
            public Orientation rotateCounterclockwise(Tile curTile) {
                curTile.col++;
                return RIGHT;
            }
        },
        LEFT {
            @Override
            public Orientation rotateClockwise(Tile curTile) {
                curTile.row--;
                return UP;
            }

            @Override
            public Orientation rotateCounterclockwise(Tile curTile) {
                curTile.row++;
                return DOWN;
            }
        };

        public abstract Orientation rotateClockwise(Tile curTile);

        public abstract Orientation rotateCounterclockwise(Tile curTile);
    }

    private static final class Tile {

        private int row;
        private int col;
        private Orientation orientation = Orientation.UP;

        public void rotateClockwise() {
            orientation = orientation.rotateClockwise(this);
        }

        public void rotateCounterclockwise() {
            orientation = orientation.rotateCounterclockwise(this);
        }

    }

    private static final class Axis {

        private int min;
        private int max;

        public void update(int cur) {
            min = Math.min(min, cur);
            max = Math.max(max, cur);
        }

    }

    public static void main(String... args) {
        Basement basement = new Basement();

        for (int steps = 0; steps < 200; steps++) {
            basement.nextStep();
            basement.print();
            System.out.println();
        }
    }

}

Demo:
..aaaa...
.a....a..
aaa....a.
aaaaaaaa.
.aa.a..a.
.a...a.aa
..aaa.aaa
aaa....a.
...aaaa..

A: use sparse matrix
    class Node {
int row;
int col;
int value;
Node next;
Node(int r, int c, int val)
{ row = r; col = c; this.value = val; }
}
public class Sparse{
public static void main(String[] args)
{
/*Assume a 4x4 sparse matrix */
int sparseMatrix[][] = {
{0, 0, 1, 2},
{3, 0, 0, 0},
{0, 4, 5, 0},
{0, 6, 0, 0}
};
Node start = null; /*Start with the empty list*/
Node tail = null;
int k = 0;
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
{
if (sparseMatrix[i][j] != 0) /*Pass only non-zero values*/
{
Node temp = new Node(i, j, sparseMatrix[i][j]);
temp.next = null;
if(start == null){
start = temp;
tail=temp;
}
else{
tail.next = temp;
tail = tail.next;
}
}
}
Node itr = start;
while(start != null){
System.out.println(start.row  + " " + start.col + " " + start.value);
start = start.next;
}
}
}


text:
Q: How to create a VM from a shared image gallery in a different azure customer account I have setup a Shared Image Gallery and added a VM image to it.  I can provision a new VM in my subscription from it.  A friend wants to use that same image to provision the same VM in his subscription, a totally different Azure account.  He has added me temporarily as an owner to his subscription and I can change directory from my azure portal to access and work with it no problem.
When I try to create a VM, I can't find the gallery in my subscription/account from his subscription (a totally different Azure account).
I have tried making an application registration and even added permissions for the application in his subscription too (contributor).  Still can't see it.
Is this possible at all or am I doing something wrong?
thank you much

A: At the moment, we have no way to use the portal to deploy a VM from an image in another azure tenant. To create a VM from an image shared between tenants, you must use the Azure CLI or Powershell. For more details, please refer to here
For example

*

*create a service principal in the tenant 1

*Give Tenant 2 access
a. Register the sp into tenant 2
we can implement it by requesting a sign-in using a browser
https://login.microsoftonline.com/<Tenant 2 ID>/oauth2/authorize?client_id=<Application (client) ID>&response_type=code&redirect_uri=https%3A%2F%2Fwww.microsoft.com%2F

b. Assign Azure RABC role Contributor to the sp

*Create VM

a. Log into both tenants using the application ID, secret and tenant ID.
$applicationId = '<App ID>'
$secret = <Secret> | ConvertTo-SecureString -AsPlainText -Force
$tenant1 = "<Tenant 1 ID>"
$tenant2 = "<Tenant 2 ID>"
$cred = New-Object -TypeName PSCredential -ArgumentList $applicationId, $secret
Clear-AzContext
Connect-AzAccount -ServicePrincipal -Credential $cred  -Tenant $tenant1
Connect-AzAccount -ServicePrincipal -Credential $cred -Tenant $tenant2

b. Create VM
$resourceGroup = ""
$location = ""
$vmName = ""

# Set a variable for the image version in Tenant 1 using the full image ID of the shared image version
$image = "/subscriptions/<Tenant 1 subscription>/resourceGroups/<Resource group>/providers/Microsoft.Compute/galleries/<Gallery>/images/<Image definition>/versions/<version>"

# Create user object
$cred = Get-Credential -Message "Enter a username and password for the virtual machine."

# Create a resource group
New-AzResourceGroup -Name $resourceGroup -Location $location

# Networking pieces
$subnetConfig = New-AzVirtualNetworkSubnetConfig -Name mySubnet -AddressPrefix 192.168.1.0/24
$vnet = New-AzVirtualNetwork -ResourceGroupName $resourceGroup -Location $location `
  -Name MYvNET -AddressPrefix 192.168.0.0/16 -Subnet $subnetConfig
$pip = New-AzPublicIpAddress -ResourceGroupName $resourceGroup -Location $location `
  -Name "mypublicdns$(Get-Random)" -AllocationMethod Static -IdleTimeoutInMinutes 4
$nsgRuleRDP = New-AzNetworkSecurityRuleConfig -Name myNetworkSecurityGroupRuleRDP  -Protocol Tcp `
  -Direction Inbound -Priority 1000 -SourceAddressPrefix * -SourcePortRange * -DestinationAddressPrefix * `
  -DestinationPortRange 3389 -Access Allow
$nsg = New-AzNetworkSecurityGroup -ResourceGroupName $resourceGroup -Location $location `
  -Name myNetworkSecurityGroup -SecurityRules $nsgRuleRDP
$nic = New-AzNetworkInterface -Name myNic -ResourceGroupName $resourceGroup -Location $location `
  -SubnetId $vnet.Subnets[0].Id -PublicIpAddressId $pip.Id -NetworkSecurityGroupId $nsg.Id

# Create a virtual machine configuration using the $image variable to specify the shared image
$vmConfig = New-AzVMConfig -VMName $vmName -VMSize Standard_D1_v2 | `
Set-AzVMOperatingSystem -Windows -ComputerName $vmName -Credential $cred | `
Set-AzVMSourceImage -Id $image | `
Add-AzVMNetworkInterface -Id $nic.Id

# Create a virtual machine
New-AzVM -ResourceGroupName $resourceGroup -Location $location -VM $vmConfig


text:
Q: Photo capture with Windows Phone 8.1 and JavaScript I am trying to capture a Picture within a Windows Phone 8.1 app and I saw a very promising answer here at stockoverflow: Photo capture on Windows Store App for Windows Phone
But I am developing with JavaScript and HTML. Unfortunately I can not find a solution within this environment. In the stackoverflow answer CaptureElement is mentioned but on the official site from Microsoft about the CaptureElement class one can read for javascript:

No code example is currently available or this language may not be supported.

How is it possible to take a picture with JavaScript?
Thanks a lot for any ideas!
Cheers,
Tim.

A: I finally know what the difference is. One link helped me a lot: MediaCapture.StartPreviewAsync is not available in javascript? There is a link mentioned pointing to a sample source code: Media capture using capture device sample. The most important part:
mediaCapture = new Windows.Media.Capture.MediaCapture();
mediaCapture.initializeAsync().done(function(result){
    var video = this.document.getElementById("PhotoPreview");
    video.src = URL.createObjectURL(mediaCapture, { oneTimeOnly: true });
    video.play();
})

Thanks to everyone reading my question.


text:
Q: Indy 10 email attachment appears in body I've upgraded an existing email sending program from Indy 9 to Indy 10.  This works fine in our test environment but on a clients site the attachments are appearing in the body of the email. Their SMTP server is adding a footer to the email and adding <html> ... </html> tags around the whole thing, which is causing this issue. The previous version on Indy 9 worked fine for this client.
Here is an example of the email we are sending:
Content-Type: multipart/mixed; boundary="gcJJK3Qk5C6XIV9FEwfRcK=_EH4Oq32hqE"
MIME-Version: 1.0
Date: Thu, 1 Oct 2020 00:02:29 +0100
Message-Id: <20201001000278.SM78660@B-P-S0308-APP1>

This is a multi-part message in MIME format

--gcJJK3Qk5C6XIV9FEwfRcK=_EH4Oq32hqE
Content-Type: text/plain
Content-Transfer-Encoding: quoted-printable
Content-Disposition: inline

Body text appears here.

--gcJJK3Qk5C6XIV9FEwfRcK=_EH4Oq32hqE
Content-Type: application/octet-stream;
    name="PDA Audit.pdf"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
    filename="PDA Audit.pdf"

JVBERi0xLjINCjEgMCBvYmoNCjw8IC9UeXBlIC9DYXRhbG9nIA0KL1BhZ2VzIDMgMCBSIA0KL1Zp
ZXdlclByZWZlcmVuY2VzIDw8IA0KPj4NCj4+IA0KZW5kb2JqDQo1IDAgb2JqDQo8PCAvVHlwZSAv
<more lines here>

--gcJJK3Qk5C6XIV9FEwfRcK=_EH4Oq32hqE--

Is there anything wrong with this?
I note that the boundary no longer contains the =_NextPart, so I'm wondering if the code on the server has been badly written and is expecting to find this. Has anyone else had a similar issue?

A: Issue solved.  We were allowing Indy to decide on the Content-Type which worked if we only sent an email with an attachment.  If a previous email was just text the Content-Type was set to text/plain.  When the email with the attachment was then sent Indy thought the Content-Type was already set so did not change it.  Setting the Content-Type correctly solved the problem.


text:
Q: Database access in asp.net I am not very much familiar with razor view engine. I tried this code.
@for(var item in ViewBag.list)
{
    @foreach (var itemvote in ViewBag.listVote)
    {
        <h1>@Html.ActionLink(@item.Title, "Details", "Report", new { id = item.Id},null)</h1>
    }
}

And it shows the following error:

Compiler Error Message: CS1973: 'System.Web.Mvc.HtmlHelper' has no applicable        method named 'ActionLink' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.
my controller class is ReportController and method is Details to which it will be submitted.
public ActionResult Details(int id = 0)
        {
            Report report = Context.Reports.Find(id);
            if (report == null)
            {
                return HttpNotFound();
            }
            ViewBag.report = report;

            return View();
        }

I googled and found some link like HTML.ActionLink method
but i am still unable to correct it.

A: There are at least 2 problems with your call to actionlink.
First, the first parameter does not require a '@' because you're already using one at the start of the line with @Html.ActionLink.
Secondly, the first parameter should be itemvote.Title not item.Title, as you don't have a variable called item.
That could be part of your problem, because the compiler might not realize that @item.Title is supposed to be a string, and there is a valid signature of ActionLink(string, string, string, Object, Object)


text:
Q: "Jagged" rectangle text in emacs Suppose I have something like
this
is
text

I want to change it to be
"this"
"is"
"text"

The first quote I can insert simply by making a rectangle and doing C-x r t, but the trailing quote I can't add because they aren't all at the same alignment. Is there any way to add something to the end of all selected lines?

A: I usually use replace-regexp for this -- replace $ (end of line) with whatever you want.  You could do it all in one shot by replacing ^.*$ with "\&".


text:
Q: PHP - show user id in url I wanna be able to show userid in url, like this: profile.php?user=1, 2 etc.
I've been searching everywhere, but I can't get it to work.
profile.php code:
<?php
ob_start();
session_start();
require_once 'dbconnect.php';

 // if session is not set this will redirect to login page
 if( !isset($_SESSION['user']) ) {
 header("Location: index.php");
 exit;
 }
 // select loggedin users detail
 $res=mysql_query("SELECT * FROM users WHERE userId=".$_SESSION['user']);
 $userRow=mysql_fetch_array($res);
 $id = $_GET['userId'];

?>

PHP code:
<?php
ob_start();
session_start();
 require_once 'dbconnect.php';

 $id = (isset($_GET['id'])) ? $_GET['id'] : $_SESSION['id'];
 $query = "SELECT * FROM users WHERE userId = $id";
 // if session is not set this will redirect to login page
 if( !isset($_SESSION['user']) ) {
 header("Location:profile.php?id=" . $_SESSION['user']);
 exit;
 }
// select loggedin users detail
 $res=mysql_query("SELECT * FROM users WHERE userId=".$_SESSION['user']);
 $userRow=mysql_fetch_array($res);
 $id = $_GET['userId'];
?>

<?php echo $userRow['userId'];?>

I use that last command there to link to my own profile, but I wanna know how to view other users profiles.

A: So basically you want to show id in url or want to pass id from url
if you want to pass id using url than :
use
<a href="profile.php?user=<?php echo $id; ?>">

And you cant get that data using $_GET[user];
SO please clarify that what you want.?

A: i would do like this:
 if( !isset($_SESSION['user']) ) {
   header("Location: index.php");
   exit;
 }
 elseif ( isset($_SESSION['user'] && !$_GET['user']){
   header("Location: profile.php?user=" . $_SESSION['user']);
 }
 else{
   // select loggedin users detail
   $res=mysql_query("SELECT * FROM users WHERE userId=".$_SESSION['user']);
   $userRow=mysql_fetch_array($res);
   $id = $_GET['userId'];
 }

A: I believe you are setting the $_SESSION['user'] on successfully login, then you direct the user to the profile.php page using the header, what you need to do now u need to change your header to look like:
<?php

header("Location:profile.php?id=" . $_SESSION['user']);

?>

That will direct the user to profile.php?use=1 if id is one then when ever you are linking back to profile.php from your dashboard using the anchor it must look like:
<a href="profile.php?id=<?php echo $_SESSION['user'];?>">profile

NB: For your own benefit don't use mysql_ the function is depreciated
  and removed from php 7. use mysqli instead,
Then for your own data security use prepared statements, with mysqli
  or pdo

A: This code will show the userid to the url if your using form:
<form="profile.php?=user<?php echo $id; ?>">

And just in case you want to pass it on other page so you can use it there here's the code:
if (isset($_POST['nameofsubmitbutton']))
{

$Sample = $_POST['nameoffield'];
header("Location: nextpage.php?id=$Sample");
}


text:
Q: Identical electrons after measurement Let's take a system made of two electrons. Since they are identical, the spin state must be either symmetric or antisymmetric under exchange.
Let's suppose we previously have the following spin part :
$\begin{align}
|\chi\rangle = \frac{1}{\sqrt{2}} \cdot (|\uparrow \downarrow\rangle + |\downarrow \uparrow\rangle)
\end{align}$
And we measure the spin of both electrons. If we measure $|\uparrow \downarrow\rangle$ the wave function collapses in this state. My problem is that this state is neither symmetric nor antisymmetric under exchange... isn't this problematic ? The spin part must always be symmetric or antisymmetric for identical particles, or it would be possible to distinguish them, right ? So what happens in this case ?

A: It is not the case that the spin part of the state must be symmetric or antisymmetric. Instead, it is only required that the overall state is (in the case of electrons) antisymmetric. If the state is separable into spin and spatial parts (i.e. it can be expressed as $\lvert\chi\rangle\lvert\psi\rangle$, where $\lvert\chi\rangle$ is the spin part and $\lvert\psi\rangle$ is the spatial part), then it must be the case that of those two parts, one is symmetric, and the other is antisymmetric. However, it is also possible for the spin and spatial parts to be entangled, in which case the individual spin and spatial states do not need to be (anti)symmetric, as long as the corresponding state with the particles swapped also appears in the superposition, with the appropriate sign. For example, the state $\lvert\chi_1\rangle\lvert\psi_1\rangle-\lvert\chi_2\rangle\lvert\psi_2\rangle$, where $\lvert\chi_1\rangle+\lvert\chi_2\rangle$ and $\lvert\psi_1\rangle+\lvert\psi_2\rangle$ are both symmetric, is antisymmetric under exchange, even if none of $\lvert\chi_{1,2}\rangle$ or $\lvert\psi_{1,2}\rangle$ are.
Going back to your example, in saying that the state is $\lvert\uparrow\downarrow\rangle$, you are assuming some way of labelling the electrons. Since these particles are indistinguishable, we cannot say whether we measured the "first" or "second" electron; however we can meaningfully label them by their spatial states. For instance, if we say that the "first" electron is in the spatial state $\lvert\alpha\rangle$ and the "second" electron is in the spatial state $\lvert\beta\rangle$, then after measuring the spins, we would say that the state is $\lvert\uparrow\downarrow\rangle\lvert\alpha\beta\rangle-\lvert\downarrow\uparrow\rangle\lvert\beta\alpha\rangle$.


text:
Q: What font does my system uses? I'm running Ubuntu 18.10 with dwm. I have removed almost all GUI programs provided by the default desktop environment Gnome. Now, my system uses a font that I want to use in my terminal, but for that I need to know the name of the font. How do I know what font it is?
Here is a demo of the font used by chromium, same as my system.

A: The font used by applications is often selected not directly by name, but because it's first in the list for the sans-serif generic alias in your system (according to FontConfig files in /etc/fonts).
$ fc-match sans-serif

$ fc-match -s sans-serif | head

Assuming you're referring to Chromium's chrome and not the document, in most Linux distributions that's most likely "DejaVu Sans" (or something closely related, e.g. "Bitstream Vera Sans").
$ pango-view --font="DejaVu Sans 10" --text="What font does my system..."


text:
Q: Dynamically accessing properties in TypeScript I'm new to TypeScript and am trying to access the property of an object by a string. Here is a sandbox showing my problem: https://codesandbox.io/s/optimistic-mendel-f1zdg?file=/src/App.tsx
Code snippet (App.tsx: 17): newFlags[event.target.name] = event.target.value;
Error: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ hidden: string; completed: string; }'.
I can make the error go away by adding an if statement like if(event.target.name === hidden || event.target.name === "completed") but that solution seems really hard to scale. It seems great if I could use the <Flag> type as a variable, but that seems to make TypeScript mad.
Is there a DRY solution to fixing this error?

A: This error makes sense since TS is a compiler, it can't know the exact runtime type of target.name, if you are sure it's one of the Flag keys, you should specify it:
// const flag = event.target.name as 'hidden' | 'completed';
const flag = event.target.name as keyof Flag
return { ...prevFlags, [flag]: event.target.value };

A: One approach is to declare the handler inline, and take the key from the outer scope instead of from the event target:
  for (const [key, value] of Object.entries(flags)) {
    flagSelectors.push(
      <FlagFiltering
        key={key}
        name={key}
        value={value}
        handleChange={(e) => setFlags({
          ...flags,
          [key]: e.target.value
        })}
      />
    );
  }

I'd also recommend avoiding the mutator method .push if something more appropriate exists, like .map:
  return (
    <div className="App">{
      Object.entries(flags).map(([key, value]) => (
          <FlagFiltering


text:
Q: Lock Entire Row Based On Date I have Cell A1 with Month mentioned. I am trying to compare date in A2:last cell and wherever date > A1, I want the row to be unlocked, otherwise locked. The below code doesn't work"
Sub Lockrow()
Dim DestSh As Worksheet
Dim lastrow As Long
Dim i As Integer

Set DestSh = Sheets("Consultant & Volunteer")

With DestSh
    'finds the last row with data on A column
    lastrow = .Range("A" & .Rows.Count).End(xlUp).Row

  'parse all rows
    For i = 6 To lastrow
       'if your conditions are met
       If Month(.Cells(i, 26)) > Month(.Cells(1, 1)) Then
          .Range("A" & i).EntireRow.Cells.Locked = True 'lock the row
       End If
    Next i
End With

End Sub

A: This can be done simply with below, but you have to be careful that Year doesn't change... Also the lastrow should be on Column Z.
Also, if the worksheet isn't Protected, there is no effect.
Option Explicit

Sub Lockrow()
    Dim DestSh As Worksheet
    Dim lastrow As Long
    Dim i As Long ' Integer

    Set DestSh = Sheets("Consultant & Volunteer")

    With DestSh
        'finds the last row with data on A column
        lastrow = .Range("Z" & .Rows.Count).End(xlUp).Row ' <-- EDIT
        'parse all rows
        For i = 6 To lastrow
           'if your conditions are met
           .Rows(i).Locked = Not (Month(.Cells(i, "Z")) > Month(.Range("A1")))
'           If Month(.Cells(i, 26)) > Month(.Cells(1, 1)) Then
'              .Range("A" & i).EntireRow.Cells.Locked = True 'lock the row
'           End If
        Next i
        .Protect UserInterfaceOnly:=True
    End With
    Set DestSh = Nothing
End Sub

A: Alternative to loop.
Dim r As Range, DestSh As Worksheet, lastrow As Long
Set DestSh = Sheets("Consultant & Volunteer")
With DestSh
    lastrow = .Range("A" & .Rows.Count).End(xlUp).Row
    Set r = .Range("A1:A" & lastrow)
    r.EntireRow.Locked = False
    r.AutoFilter 1, ">" & .Range("A1").Value2
    r.SpecialCells(xlCellTypeVisible).EntireRow.Locked = True
    .AutoFilterMode = False
    .Protect UserInterfaceOnly:=True
End With


text:
Q: Application Architecture Feedback I was looking for some feedback on the current design.
Here is how it currently looks

*

*Web App (UI) References BLL Layer and BusinessEntities Layer

*BusinessEntites Layer - Contains Interfaces and Classes (with internal validations on the properties)

*BLL (references the BusinessEntities and DAL Layer) - Has mostly Managers for each of the Business Objects with methods like Create() Save() Delete().

*DAL (references BusinessEntities Layers) - Has DB commands that create/add/update Business Entities Objects.

I'm not quite sure about the naming conventions i used for the layers so if anyone has any better suggestions than i'll gladly adopt them.
Also i don't like the idea of the DAL referencing the BusinessEntities Layer, but how else am i going to return objects instead of Datasets/DataTables?
Thanks for any feedback.

A: With respect to your needing to reference the business layer from the DAL, I would agree that this is probably not optimal -- lower tiers should not know about the ones above them, it reduces reusability and adds extra/potentially circular dependencies.
Have you considered having your business entities "fill themselves up" and do their own persistence operations using the DAL classes, rather than the DAL acting like a factory for them (as in your current design)?  That way, your DAL would be a more direct representation of the database, and the business entities would contain the (business) logic needed to fill and persist themselves appropriately.
Also, the "BLL" layer you spec out doesn't really appear to me to contain business logic;  it looks to me to be more of a persistence services layer for the entities.
So a variation of what you propose could be:

*

*Web/UI, referencing Business Entities

*BusinessEntities, contains interfaces and classes with business logic.  References DataServices layer

*DataServices, contains classes that load, find and persist data.  Can serve up "generic" structures containing the data (Data Transfer Objects) that can be produced, consumed and processed by Business Entities.  References DAL.

*DAL, which simply provides classes that map to tables.

Depending on your requirements, I would consider merging your BusinessEntities and DataServices (BLL in your original design) into a single tier; the only reason I can think of to split them apart is if you are doing something like Silverlight where you need asynchronous data operations on client-side business entities.
Of course all of this is with an incomplete knowledge of your specific system requirements -- you will need to design what is best for your specific application.  Good luck!


text:
Q: Estimation of recurrent sequence Suppose we have $z_{n+1}=\frac{z_{n}^2}{1+cz_{n}}$ where $c>1$ and $z_{1}>0$. What can we say about $z_{n}$? Can we find an explicit formula? Can we at least get an approximation of the form $c_{1}a_{1}(n)+c_{2}a_{2}(n)+\mathcal O(a_{3}(n))$ for some constants $c_i$ and some sequences $a_{i}$ with decreasing order of magnitude?
Edited: the index of the sequence in $\mathcal O$.

A: Introduce $\gamma=\gamma(c,z_1)$ with $0\lt\gamma\lt1$, as
$$
\gamma=z_1^{1/2}\cdot\prod_{n\geqslant1}(1+cz_n)^{-1/2^n}.
$$
Then $z_n^{1/2^n}\to\gamma$ decreasingly, and, considering $\delta\lt\gamma$ defined by $\delta=\gamma^3/4$,
$$
z_n=\gamma^{2^n}+c\cdot\delta^{2^n}+o(\delta^{2^n}).
$$
To prove this, one can start from the formula
$$
z_n^{1/2^n}=\gamma\cdot\prod_{k\geqslant n+1}(1+cz_k)^{1/2^k}.
$$


text:
Q: How do I create a Live Stream M3U8 from Already Hosted MP4 Videos? I'd much appreciate if anyone could help me create
Here is an example of how I create my m3u8 files
#EXTM3U
#EXTINF:-1,Home Video 1
http://linktomymp4homevideogoeshere.com
#EXTINF:-1,Home Video 2
http://linktomymp4homevideogoeshere.com

So How can I make this M3U8 Playlist a Live Stream for a program like VLC Player?
Basically How can I make a live stream of a m3u8 playlist file which has already hosted mp4 videos, and it loops to go to the first video after it's finished cycling through the last video on the list?

A: First of all HLS does not support MP4, it only supports MPEG-2 Transport Streams. They have recently added support for fragmented MP4. You can use ffmpeg to convert mp4 files to mpegts by simple command
ffmpeg -i input.mp4 -c copy -bsf h264_mp4toannexb output.ts

You can statically create a simple playlist like
#EXTM3U
#EXT-X-TARGETDURATION:13
#EXTINF:13.0,
1.ts
#EXTINF:13.0,
2.ts
#EXT-X-ENDLIST

Loop is a player property, there is no HLS tag defined in HLS draft https://datatracker.ietf.org/doc/html/draft-pantos-http-live-streaming-20#section-4.3.4.2 to start playing again from beginning.


text:
Q: Find the area of a parallelogram with the following. We are given the vectors AB=m+2n, AD=m-3n.
Where |m|=2, |n|=3 and $\angle(m,n)=\dfrac{\pi}{6}$. Find the area of the Parallelogram.

A: I Hope I got the translation right but it is question 4
enter image description here

A: Hints:

*

*The area of Parallelogram is the cross-product of their vectors. Thus, $AB\times AD$

*Distributive over the addition: $A\times (B+C)=(A\times B)+(A\times C)$

*Cross products of a vector with itself is $0$. Therefore, $m\times m$ and $n\times n$ is equal to $0$

*And the last one $A\times B=|A||B|sin\theta$  (where $\theta$ is the angle between  $A$ and $B$)

These hints are enough to solve this problem.


text:
Q: Javascript clipboard.readText() not working in IOS Safari? I have lines:
$(document).ready(function(){
        $(window).on('focus', function () {
            navigator.clipboard.readText().then(q => {
                alert(q);
            }).catch(err => {
                console.error('Failed to read clipboard contents: ', err);
            });

         });
    });

Run well on Android's browser. But in IOS Safari, nothing happens.
Please help !

A: Some changes has been done on webkit: https://webkit.org/blog/10247/new-webkit-features-in-safari-13-1/
Answer has been done here:
Javascript / Clipboard API / Safari iOS / NotAllowedError Message


text:
Q: ID al registrar usuario en SQLite Tengo un problema a la hora de registrar el id de un nuevo usuario en SQlite.
En la ventana de registro solo requiere un usuario y contraseña del mismo, pero a la hora de introducir quiero que el id sea superior al anterior en 1.
private static final AtomicInteger count = new AtomicInteger(0);
private boolean isFilled;

public User(int idUser, String username, String password, boolean isAdmin) {

        isFilled = false;
        this.idUser = count.incrementAndGet();
        this.username = username;
        this.password = password;
        this.isAdmin = isAdmin;
    }

Para ello, he utilizado AtomicInteger, pero no consigo que funcione correctamente.

 public void actionPerformed(ActionEvent e) {

                String idUserx = txtidUser.getText();
                int idUser = Integer.parseInt(idUserx);
                String name = txtName.getText();
                String Password = txtPass1.getText();
                String Admin1 = txtAdmin.getText();
                int  Admin = Integer.parseInt(Admin1);

                db.DBConnector.insertUser(idUser, name, Password, Admin);

                MainWindow w = new MainWindow(null);
                w.setVisible(true);

            }

Toda sugerencia es bienvenida.
Muchisimas gracias!


text:
Q: Issue Routing along IPSEC VPN I am struggling to get two different subnets routing along a IPSec tunnel.
The tunnel is between a Vyatta (6.5) and a Juniper firewall.
The tunnel was initially created to route between a subnet in our office behind the Vyatta (10.150.0.0/24) to a subnet in our offsite DR (10.250.0.0/24). However, I now also want to route another subnet in our office to the offsite DR (192.168.47.0/24).
I have added another tunnel on the Vyatta to allow this:
 tunnel 1 {
 allow-nat-networks disable
 allow-public-networks disable
 esp-group ***
 local {
     prefix 10.150.0.0/24
 }
 remote {
     prefix 10.250.0.0/24
 }
 }
 tunnel 2 {
 allow-nat-networks disable
 allow-public-networks disable
 esp-group ***
 local {
     prefix 192.168.47.0/24
 }
 remote {
     prefix 10.250.0.0/24
 }
 }

Also I have modified the security and routing on the Juniper to allow this traffic.
The strange thing is, this seems to work but for only one tunnel at a time. Both tunnels show as up and connected however I can only ever receive responses from the 10.250.0.0 subnet from either the 10.150.0.0 or the 192.168.47.0, not both at the same time.
Not quite sure where I am going wrong here!


text:
Q: java.endorsed.dirs="" is no longer supported. IntelliJ 2019.3 I am getting

JVMJ9VM148E java.endorsed.dirs="" is no longer supported. The endorsed-standards override mechanism is only supported via upgradable modules.
  Error: Could not create the Java Virtual Machine.
  Error: A fatal exception has occurred. Program will exit.

When trying to run a Java 11 program in IntelliJ 2019.3
This started happening after I updated my IntelliJ.
I have found this question on StackOverflow,: How do you replace endorsed directory in Java 9?
And also this: form IntelliJ, https://intellij-support.jetbrains.com/hc/en-us/community/posts/360000615010-IntelliJ-is-adding-a-no-longer-supported-Djava-endorsed-dirs-JDK-9-parameter-on-Gradle-runs-which-results-in-failure
but none apply to my situation.
Does anyone know ho I can solve this? Thanks in advance.


text:
Q: Accessing register depending their address Does anyone know the Verilog code to select single register from the register list depending on the address of the register?
For Example
+------+--------------+---------+
| Name | Offset_value | Address |
+------+--------------+---------+
| Reg1 |           01 | 0x00    |
| Reg2 |           00 | 0x04    |
| Reg3 |           00 | 0x08    |
| Reg4 |           00 | 0x0C    |
+------+--------------+---------+

If I give address as 0x08, then I can read/write from Reg3 and so on.
Each register is 32 bits.

A: From your description you have multiple flip-flops or registers that you want to update based on a write address.
always @(posedge clk) begin
  case ( address )
    8'h00 : Reg1 <= data;
    8'h04 : Reg2 <= data;
  endcase
end

If however you wanted to uses memory structure instead of REG1/2/3
reg [7:0] Reg_dat [0:254]; //255 8bit locations
always @(posedge clk) begin
  Reg_dat[address] <= data;
end

A: As @Morgan suggested, you can use flop based memory to make reg bank,
reg [7:0] Reg_dat [0:254]; //255 8bit locations
always @(posedge clk) begin
  Reg_dat[write_reg_address] <= wr_reg;
end

For writing particular reg, you have to provide write_reg_address and value which you want to be write in register.
For reading of specific register value, you have to provide only read_reg_address and it gives value of that particular reg.
assign read_reg = Reg_dat[read_reg_address];


text:
Q: Integrating Bing Maps tiles into Google Maps API I currently managed to integrate OpenStreetMap into Google Maps API as it is described in this example. I wonder if I can also integrate Bing Maps tiles into Google Maps API. Is it possible? I could not find anything about that.
Note: I do know about mapstraction but for now, I would like to stick to Google Maps API.
Thanks in advance.

A: Based on the OpenStreetMap example that you cited, I would say that it's possible but it could be quite a challenge.  I would strongly advise against it since the OSM example uses version 2 of the Google API and it now officially deprecated.
But if you want to give it a try I would adapt the OSM example to point to the Bing tiles and make sure that the tileUrlTemplate property matches Bing's format for storing tiles.  Unfortunately, Bing uses a quad tree format  while Google uses a coordinate based format for storing tiles and accessing them via a URL.  It will be important to understand the differences if you're going to make the example work so be sure to dig into the documentation links above.  Also, MapTiler has a fantastic visualization of the different tile formats out there.  I've found this invaluable.
Personally, I would use OpenLayers.  Since Bing and Google both use spherical mercator, adding multiple tile sources to a single map is a trivial exercise.  Here is an example.

A: function TileToQuadKey ( x, y, zoom){
  var quad = "";
  for (var i = zoom; i > 0; i--) {
    var mask = 1 << (i - 1);
    var cell = 0;
    if ((x & mask) != 0) cell++;
    if ((y & mask) != 0) cell += 2;
    quad += cell;
  }
  return quad;
}

var bingMapType = new google.maps.ImageMapType({
  name: "Bing",
  getTileUrl: function(coord, zoom) {
    // this returns aerial photography
    return "http://ecn.t1.tiles.virtualearth.net/tiles/a" +
      TileToQuadKey(coord.x, coord.y,  zoom) + ".jpeg?g=1173&n=z";
      // i dont know what g=1173 means
  },
  tileSize: new google.maps.Size(256, 256),
  maxZoom: 21
});


text:
Q: Unable to send files between computers using Python socket programming I wrote a socket programming code in Python. It is supposed to be able to send files between different computers. I tested my code on the same computer (ie. by sending files from 2 different folders) and it works. However, when I try to test the code by sending the files from my computer to my friend's computer, I keep getting this error:
 WindowsError: [Error 3] The system cannot find the path specified: 'C://Users//Admin//Desktop//SharedFiles/*.*'

The error occurs when my Python program tried to access the client_side_folder variable as shown below:
client_side_folder = "C://Users//Admin//Desktop//SharedFiles"

I have also tried replacing the client_side_folder as "C:/Users/Admin/Desktop/SharedFiles" and "C:\Users\Admin\Desktop\SharedFiles". But both still have the same error.
Does this error got to do with how Python deal with Windows address? If so, how come it works when I tried to send files from 1 folder to another folder in the same computer? Any ideas how I can solve this problem?
EDIT:
The code crashes where it hit the following code:
        def listOfFiles(directory):
                list_dir = os.listdir(directory)
                return list_dir

A: You might find it easier to handle paths in python, through the os.path module. For instance, if you want to access a file in the home directory of a user:

from os.path import expanduser, join

userhome = expanduser( '~' )
desktop = join( userhome, 'Desktop' )
shared_dir = join( desktop, 'SharedFiles' )
file_list = os.listdir( shared_dir )

This also implies that the user executing the script has access privileges to whatever path you're trying to access.
addendum 1:
Assuming you're using tcp sockets this a sample code for client and server:
server running on your friend's host:
import socket
serversocket = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
serversocket.bind( ( 'localhost', 13000 ) )
serversocket.listen(5) # 5 is the number of client connections that can be queued
while 1:
    #accept connections from outside
    (clientsocket, address) = serversocket.accept()
    # processing of the incoming connection
    ....

client running on your host:
import socket
s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
s.connect( ( 'friendshost', 13000 ) )
s.send( .... )

A: The Problem
The code that is breaking is:
list_dir = os.listdir(directory)

This means the directory pointed to by directory does not exist in your local machine.
In your code, you have
client_files = listOfFiles(client_side)
server_files = listOfFiles(server_side)

which won't work.
You cannot use os.listdir to get the listing of a folder on a remote machine (friend's machine) without using something like \\hostname\\path.
When you are running the server and client on same machine, it works as both points to the local machine.
Solution
Method 1: Stop trying to get the listings of the remote machine and let the code running on that machine do it for you.
Method 2: Use remote access URL (shared folder or something) to access the details of the remote machine.


text:
Q: pipes and foreach loops Recently, I've been playing with PowerShell, and I've noticed some weird behavior when using pipes and foreach loops that I couldn't understand.
This simple code works:
$x = foreach ($i in gci){$i.length}
$x | measure -max

Makes sense.
But this code won't:
foreach ($i in gci){$i.length} | measure -max

And I'm getting the following error:
An empty pipe element is not allowed.
At line:1 char:33
+ foreach ($i in gci){$i.length} | <<<<  measure -max
+ CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : EmptyPipeElement

What is the difference between those two methods, and why does the second one fails?

A: The foreach statement doesn't use the pipeline architecture, so its output cannot be passed to a pipeline directly (i.e. item by item). To be able to pass output from a foreach loop to a pipeline you must run the loop in a subexpression:
$(foreach ($item in Get-ChildItem) { $item.Length }) | ...

or collect it in a variable first:
$len = foreach ($item in Get-ChildItem) { ... }
$len | ...

If you want to process data in a pipeline use the ForEach-Object cmdlet instead:
Get-ChildItem | ForEach-Object { $_.Length } | ...

For further explanation of the differences between foreach statement and ForEach-Object cmdlet see the Scripting Guy blog and the chapter on loops from Master-PowerShell.

A: You need to evaluate the foreach before piping the resulting Object like you did in the first test:
$(foreach ($i in gci){$i.length}) | measure -max

Alternatively, use the % shorthand to which will evaluate it before piping it as well:
gci | % { $_.Length } | measure -max


text:
Q: Order relation between cohomological dimensions of open orientable manifolds Let $M$ be an open orientable connected manifold and let $\operatorname{Cohdim}_{\mathbb{Z}_{2}}(M)$ and $\operatorname{Cohdim}_{\mathbb{Z}}(M)$ be the cohomological dimensions of $M$ over $\mathbb{Z}_{2}$ and $\mathbb{Z}$ respectively, where cohomological dimension is defined to be the largest degree of a non-trivial cohomology group with given coefficient ring.

Is there an order relation between $\operatorname{Cohdim}_{\mathbb{Z}_2}(M)$ and $\operatorname{Cohdim}_{\mathbb{Z}}(M)$? Is it true that $\operatorname{Cohdim}_{\mathbb{Z}_{2}}(M)\leq \operatorname{Cohdim}_{\mathbb{Z}}(M)$?

I know that this is true for closed orientable manifolds. Also, for closed non-orientable manifolds this is not true.

A: It seems that your definition of cohomological dimension is not the standard definition, see here for example. The answer below is regarding cohomological dimension according to your definition.
First, you claimed that $\operatorname{Cohdim}_{\mathbb{Z}_2}(M) \leq \operatorname{Cohdim}_{\mathbb{Z}}(M)$ is not true for closed non-orientable manifolds $M$. That is incorrect. For such connected manifolds we have $H^{\dim M}(M; \mathbb{Z}_2) \cong \mathbb{Z}_2$ and $H^{\dim M}(M; \mathbb{Z}_2) \cong \mathbb{Z}_2$, so $\operatorname{Cohdim}_{\mathbb{Z}_2}(M) = \operatorname{Cohdim}_{\mathbb{Z}}(M) = \dim M$.
Moving on to the case of open manifolds, let $X$ be a topological space. From the short exact sequence of groups $0 \to \mathbb{Z} \xrightarrow{\times 2} \mathbb{Z} \to \mathbb{Z}_2 \to 0$, we obtain a long exact sequence in cohomology
$$\dots \to H^{k-1}(X; \mathbb{Z}_2) \to H^k(X; \mathbb{Z}_2) \xrightarrow{\times 2} H^k(X; \mathbb{Z}) \to H^k(X; \mathbb{Z}_2) \to H^{k+1}(X; \mathbb{Z}) \to \dots$$
Suppose that $\operatorname{Cohdim}_{\mathbb{Z}_2}(X) = k$. As $H^k(X; \mathbb{Z}_2) \neq 0$, it follows from the exactness of the above sequence that at least one of $H^k(X;\mathbb{Z})$ and $H^{k+1}(X; \mathbb{Z})$ is non-zero, so $\operatorname{Cohdim}_{\mathbb{Z}}(X) \geq k$ and hence
$$\operatorname{Cohdim}_{\mathbb{Z}_2}(X) \leq \operatorname{Cohdim}_{\mathbb{Z}}(X).$$
In general, the two are not equal, even for manifolds. In fact, the difference between the two can be arbitrarily large.
Example: Consider a $(2n+1)$-dimensional Lens space $L(p; q_1, \dots, q_{n+1})$ with $p > 1$ odd. Fix $x \in L(p; q_1, \dots, q_{n+1})$ and set $M = L(p; q_1, \dots, q_{n+1})\setminus\{x\}$. It follows from Mayer-Vietoris that
$$H^k(M; \mathbb{Z}) \cong \begin{cases}
\mathbb{Z} & k = 0\\
\mathbb{Z}_p & k \in \{2, 4, \dots, 2n\}\\
0 & \text{otherwise}.
\end{cases}$$
Note that for $k > 0$, the map $H^k(M; \mathbb{Z}) \xrightarrow{\times 2} H^k(M; \mathbb{Z})$ is an isomorphism because either $H^k(M; \mathbb{Z}) = 0$ or $H^k(M; \mathbb{Z}) \cong \mathbb{Z}_p$ and $\mathbb{Z}_p \xrightarrow{\times 2} \mathbb{Z}_p$ is an isomorphism since $(2, p) = 1$. It then follows from the long exact sequence above that
$$H^k(M; \mathbb{Z}_2) = \begin{cases}
\mathbb{Z}_2 & k = 0\\
0 & k > 0.
\end{cases}$$
So we have $\operatorname{Cohdim}_{\mathbb{Z}_2}(M) = 0$ and $\operatorname{Cohdim}_{\mathbb{Z}}(M) = 2n$.


text:
Q: Subtracting from an Array, coding challenge I am trying to solve this coding challenge and want to know why my code isn't working. Please let me know what the problem is and suggest an alternative solution.
Here is the question:
Create a function called 'reversedLooper' that when passed an array will loop through it backwards and subtract 2 from the last element, 1 from the second to last, 0 from to the third to last, add one to the fourth to last, add 2 to the fifth to last, etc. until it reaches the front of the array.  Return the list when you are done
Here is my solution
var arr = [2, 3, 3, 5, 7, 19];
var difference = [];
var arr3 = [];

//the function below is working correctly in the way I intend...

function arrayCreator (arr3) {
    var i;
    for(i = arr.length - 3; i >= -2; i--) {
        arr3.push(i);
    }
    return arr3;
}

function reversedLooper (arr) {
    var i;
    for(i=0; i< arr.length; i++) {
        var pusher = arr[i] - arr3[i];
        difference.push(pusher);
    }

    return difference;
}

console.log(reversedLooper(arr));

// answer should be [5, 5, 4, 5, 6, 17] in this case

A: You can use the map() function and reverse() functions:
count = -3;
finalArray = [2, 3, 3, 5, 7, 19]
                .reverse()
                .map(function (obj) {
                   count++;
                   return obj + count;
                 })
                 .reverse();

Executing on console gives this:
» count = -3; [2, 3, 3, 5, 7, 19].reverse().map(function (obj) { count++; return obj + count; }).reverse()
« [5, 5, 4, 5, 6, 17]

Snippet

count = -3;
final = [2, 3, 3, 5, 7, 19].reverse().map(function(obj) {
  count++;
  return obj + count;
}).reverse();
alert(final.join());

A: You can create an auxiliar variable starting at 2 and decrementing it each iteration, take a look:

function reversedLooper(arr) {
  for (var i = arr.length - 1, numToSum = 2; i >= 0; i--, numToSum--) {
    arr[i] = arr[i] - numToSum;
  }
}

var arr = [2, 3, 3, 5, 7, 19];
reversedLooper(arr);
document.write(arr);

A: Your code just declare the arrayCreator function without invocation.
And also var pusher = arr[i] + arr3[i];  Edited these two things and your code will work.

A: change the function reversedLooper to:
function reversedLooper(arr){
  var x=-2;
  for(var i=arr.length-1;i>=0;i--)
  {
    arr[i]+=x;
    x++;
  }
  return arr;
}


text:
Q: Best way to mask a single bit in AVX2? For example, with an input ymm vector x and bit index i I want an output vector with only the ith bit kept and everything else zeroed.
With AVX512 k registers, I could write the following, but AVX2 and below doesn't have k registers, so what do you think is the best way to do it?
__m512i m512i_maskBit(__m512i x, unsigned i) {
    __mmask8 m = _cvtu32_mask8(1u << i / 64);
    __m512i vm = _mm512_maskz_set1_epi64(m, 1ull << i % 64);
    return _mm512_and_si512(x, vm);
}

A: Here is an approach using variable shifts (just creating the mask):
__m256i create_mask(unsigned i) {
    __m256i ii = _mm256_set1_epi32(i);
    ii = _mm256_sub_epi32(ii,_mm256_setr_epi32(0,32,64,96,128,160,192,224));
    __m256i mask = _mm256_sllv_epi32(_mm256_set1_epi32(1), ii);
    return mask;
}

_mm256_sllv_epi32 (vpsllvd) was introduced by AVX2 and it shifts each 32 bit element by a variable amount of bits. If the (unsigned) shift-amount is bigger than 31 (i.e., also for signed negative numbers), the corresponding result is 0.
Godbolt link with small test code: https://godbolt.org/z/a5xfqTcGs

A: How about the simplest approach:
__m256i m256i_create_mask(unsigned i) {
    // Get the required bit in every byte of the vector
    __m256i vm = _mm256_broadcastb_epi8(_mm_cvtsi32_si128(1u << (i & 7u)));
    // Mask off the bytes that are outside the index
    __m256i vi = _mm256_broadcastb_epi8(_mm_cvtsi32_si128(i >> 3u));
    __m256i vm1 = _mm256_cmpeq_epi8(vi,
        _mm256_setr_epi8(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
            16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31));
    return _mm256_and_si256(vm, vm1);
}

A: Here's another approach. Not sure it's necessarily better, it depends on CPU model and surrounding code, but it might be.
// A buffer to load vectors with a single bit set in one lane
alignas( 64 ) static const std::array<int, 16> s_oneBuffer =
{
    0, 0, 0, 0, 0, 0, 0, 0,
    1, 0, 0, 0, 0, 0, 0, 0
};

__m256i maskSingleBit( __m256i x, uint32_t bitIndex )
{
    // Load `1` into a single 32-bit lane of the vector
    // The buffer aligned by 64 bytes, contained in a single cache line, no unaligned load penalty.
    __m256i one = _mm256_loadu_si256( ( const __m256i* )( ( s_oneBuffer.data() + 8 ) - ( bitIndex / 32 ) ) );

    // Left shift to move the `1` into the correct location
    __m128i shift = _mm_cvtsi32_si128( bitIndex % 32 );
    __m256i bit = _mm256_sll_epi32( one, shift );

    // Bitwise AND with the value
    return _mm256_and_si256( x, bit );
}


text:
Q: In DS9 episode 5.15 (By Inferno's Light) is one of the prisoners wearing Leia's Boushh helmet from Return of the Jedi? In Return of the Jedi we see Leia wearing a Boushh helmet.

In Deep Space Nine episode 5.15 (By Inferno's Light) we see a prisoner wearing what appears to be the same helmet.
My question is: In DS9 episode 5.15 (By Inferno's Light) is one of the prisoners wearing Leia's Boushh helmet from Return of the Jedi?

A: No, it's not the same prop, nor is it a replication of it.  While the Breen (the episode you're asking about is the first appearance) wear suits that look a great deal like the Boushh costume, that's as far as the connection goes.
Here you can see many details differ between Boushh and Breen:

The top of the Breen helmet is taller than Boushh, there's one 'eye' slit in the Breen helmet vs. 2 in the Boushh helmet.  And the Breen helmet lacks Boushh's distinctive snout design.

A: Besides @Keen's answer, see @Praxis's answer here which I have included below, which talks about the origin of the Breen design.

The Breen vs. the Ubese bounty hunters

This is probably the best and most definitive example of a character's appearance being copied between the two works.  Many Internet forums report the existence of an interview in which Deep Space Nine costume designer Robert Blackman addressed the Breen issue explicitly, indicating that the Breen helmet was based directly on the Ubese helmet (specifically, Leia's in Return of the Jedi), and that this was intended as an homage.
If I can locate a transcript or video of the interview, I will add it here.


text:
Q: kettle mongo _id I'm trying to upsert by using the _id field in Mongo.
I've tried to recover first the _id by using a Json Input step, no luck with $._id or $._id.$oid
Anyone knows how to upsert by _id?

A: Once you have the _id, transform it into the extended JSON notation indicated by Stennie with a Modified Javascript Value script like:
var _id = '{ "$oid": "' + _id + '" }';

In your MongoDB Output step, set the JSON column to Yfor the _id row. I'm not sure when this JSON option was introduced but found it in the latest CI build of Kettle today.


text:
Q: How to reply properly with Tweepy? I am developing a bot for learning purposes, that replies a meme answer to everyone who types 'good morning' in Portuguese.
However, I cannot seem to reply in the OPs Tweet, only in my feed, using the @ of the OP, which is not as intended. Here's the code:
    import tweepy
    import time
    auth = tweepy.OAuthHandler('xxxx', 'xxxxx')
    auth.set_access_token('xxxxxx', 'xxxxxx')

    api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)
    user = api.me()
    search = 'bom dia'
    numerotweets = 50
    for tweet in tweepy.Cursor(api.search, search).items(numerotweets):
    try:
            bomdia =  "example, " "@" + tweet.user.screen_name + " example"
            status = api.get_status(tweet)
            api.update_status(status = bomdia, in_reply_status_id = status.id, auto_populate_reply_metadata=True)
    print('bom dia com sucesso')
            tweet.favorite()
            time.sleep(120)
    except tweepy.TweepError as e:
    print(e.reason)
            time.sleep(5)
    break
    except StopIteration:
    break

I´ve tried with in_reply_status_id = tweet.id, but it also did not work. Sometimes I get error 431; sometimes it doesn't find any Tweet.

A: The parameter for API.update_status and the POST statuses/update endpoint it uses is in_reply_to_status_id, not in_reply_status_id.


text:
Q: How to Hide/ByPass Authoriaztion Pop Up while accessing Google Drive API I am using Google Drive API's using JAVA for getting drive files, i want to create a background job which will fetch the google drive files
without any user interaction (eg asking for user to explicity Authorize).
In the example given below by google, after running this java program we need to explicitly hit URL in browser & click on Authorize
for full execution of the program.
https://developers.google.com/drive/v3/web/quickstart/java
Using the Service Account I am able to fetch the google drive contents without any kind of user action (eg click on allow to authorize).
I want to acheive the same flow for individual user accounts, I have the list of emailid and passowords for google accounts.
Other than service accounts, is there any method so that i connect to the authorization url in background using HTTPPost request and
fetch the file list.

A: I don't think there's another way of doing this aside from Service Accounts which you are currently using. You can try to use the Google Playground but this is for testing purposes only and not for production.


text:
Q: I want to resolved a generic type E to a variable I have to add this statement  public void removeRange (int fromIndex, int toIndex)  to my ListType class.
This method should remove all the elements with indexes in the range of fromIndex (inclusive) and toIndex (exclusive). All of the succeedng elements in the list should be shifted toward the front of the list to occupy the gap left by the removed elements. This method should trown an IndexOfBoundException if either of the specified indexes is invalid.
When I try to use a Generic type E to resolved a variable in this method, I get a error.
Error Message "E cannot be resolved to a variable"
My code

public void removeRange(int fromIndex, int toIndex)
   {
      if (fromIndex >= elements || fromIndex < 0 || toIndex >=elements || toIndex<0 ||   toIndex<=fromIndex)
      throw new IndexOutOfBoundsException();
      for( int i = fromIndex; i <toIndex; ++i)
      E temp = remove(i);
   // Return the element that was removed.
      return;
   }

I know I can't declare a generic type E object, but I don't how to get around this?

A: Try
public E removeRange<E>(int fromIndex, int toIndex)
   {
      if (fromIndex >= elements || fromIndex < 0 || toIndex >=elements || toIndex<0 ||   toIndex<=fromIndex)
      throw new IndexOutOfBoundsException();
      for( int i = fromIndex; i <toIndex; ++i)
      E temp = remove(i);
   // Return the element that was removed.
      return temp;
   }

A: Your ListType class should declare that it takes generic type E. So you want something like:
public class ListType<E> extends ArrayList<E> {
    public void removeRange(int fromIndex, int toIndex) {
        // your remove logic here
        ...

        // now you can use E here
        E temp = remove(i);
        return;
    }
}

I'm guessing that you're extending ArrayList here. Either way it's the same concept.


text:
Q: How does application layer unit tests look like in DDD? In my job we are writing web services, which are called by an app. We are working in agile mind set using domain driven design. As in DDD we have domain and application layer. However, we encountered problem in writing unit tests for those layers, because it seems that we are testing domain logic twice: in domain unit tests and again in application unit tests:
Application unit test
    [TestMethod]
    public void UserApplicationService_SignOut_ForExistingUserWithBalance_ShouldClearBalanceAndSignOut()
    {
        //Arrange
        long merchantId = 1;
        long userId = 1;

        var transactionId = "001";
        var id = "122";
        var user = Help.SetId<User>(User.Register(id, new DateTime(2015, 01, 01, 00, 00, 01)), userId);

        _usersDb.Add(user);
        var userBonusBalanceRepository = _testContext.MoqUnitOfWork.MockUnitOfWork.Object.GetUserBonusAccountRepository();

        UserBonusAccount uba = userBonusBalanceRepository.GetForUser(user);
        uba.PayTo(
            new Domain.Core.Money { TotalAmount = 10, BonusAmount = 0 },
            new Domain.Core.Outlet
            {
                BonusPercentage = 50,
                IsLoyalty = true,
                Id = id,
                OutletId = "111"
            },
            transactionId,
            DateTime.Now);
        userBonusBalanceRepository.Update(uba);

        //Act
        _testContext.UserApplicationService.SignOut(id);

        //Assert
        var firstOrDefault = this._balances.FirstOrDefault(x => x.UserId == user.Id && x.MerchantId == merchantId);
        Assert.IsTrue(firstOrDefault != null && firstOrDefault.Balance == 0);
        Assert.IsNotNull(this._transactions.Where(x => x.Id == transactionId && x.Type == BonusTransactionType.EraseFunds));
    }

Domain unit test
    [TestMethod]
    public void UserBonusAccount_ClearBalances_shouldClearBalancesForAllMerchants()
    {
        long userId = 1;
        long firstMerchantId = 1;
        long secondMerchantId = 2;
        User user = User.Register("111", new DateTime(2015, 01, 01, 00, 00, 01));
        Shared.Help.SetId(user, userId);
        List<BonusTransaction> transactions = new List<BonusTransaction>();
        List<BonusBalance> balances = new List<BonusBalance>();

        var userBonusAccount = UserBonusAccount.Load(transactions.AsQueryable(), balances.AsQueryable(), user);

        userBonusAccount.PayTo(new Money {TotalAmount = 100, BonusAmount = 0},
            new Outlet
            {
                BonusPercentage = 10,
                IsLoyalty = true,
                MerchantId = firstMerchantId,
                OutletId = "4512345678"
            }, "001", DateTime.Now);

        userBonusAccount.PayTo(new Money {TotalAmount = 200, BonusAmount = 0},
            new Outlet
            {
                BonusPercentage = 10,
                IsLoyalty = true,
                MerchantId = secondMerchantId,
                OutletId = "4512345679"
            }, "002", DateTime.Now);

        userBonusAccount.ClearBalances();

        Assert.IsTrue(userBonusAccount.GetBalanceAt(firstMerchantId) == 0);
        Assert.IsTrue(userBonusAccount.GetBalanceAt(secondMerchantId) == 0);
    }

As you can see these both tests checks whether user balance is 0, which is domain responsibility. Thus the question is: how application layer unit tests should look like and what it should test? Somewhere I read that unit tests should test in "application services for flow control and domain models for business rules". Could someone elaborate more and give some examples what application layer unit tests should test and look like?

A: App Service Unit Tests
The responsibilities of app services include input validation, security and transaction control. So this is what you should test!
Here are some example questions that app service unit tests should provide and answer for:
Does my app service...

*

*behave correctly (e.g. return the expected error) when I pass in garbage?

*allow only admins to access it?

*correctly commit the transaction in the success case?

Depending on how exactly you implement these aspects it may or may not make sense to test them. Security, for example, is often implemented in a declarative style (e.g. with C# attributes). In that case you may find a code review approach more appropriate than checking the security attributes of each and every app service with a unit test. But YMMV.
Also, make sure your unit tests are actual unit tests, i.e. stub or mock everything (especially domain objects). It's not clear in your test that this is the case (see side note below).
Testing Strategies for App Services in General
Having unit tests for app services is a good thing. However, on the app service level, I find integration tests to be more valuable in the long run. So I typically suggest the following combined strategy for testing app services:

*

*Create unit tests for the good and bad cases (TDD style if you want to). Input validation is important, so don't skip the bad cases.

*Create an integration test for the good case.

*Create additional integration tests if required.

Side Note
Your unit tests contain a few code smells.
For example, I always instantiate the SUT (system under test) directly in unit tests. Like that, you exactly know what dependencies it has, and which of them are stubbed, mocked, or the real one is used. In your tests, this is not at all clear.
Also, you seem to depend on fields for collecting the test output (this._balances for example). While this is usually not a problem if the test class contains only a single test, it can be problematic otherwise. By depending on fields, you depend on state that is "external" to the test method. This can make the test method difficult to understand, because you can't just read through the test method, you need to consider the whole class. This is the same problem that occurs when over-using setup and tear-down methods.


text:
Q: Plone 4.0.4 and collective.contentrules.mailtogroup - no group search result I would be very happy to have "mailtogroup" installed - really - so if someone could tell me how to exactly configure "mailtogroup" in order to sent group email. The problem is that no group names pop up, when I do the search. I was able to setup the single user email facility.

A: The first thing I'd check if you have the right version of UberSelectionWidget installed. From the documentation for mailtogroup:

This content rule uses the UberMultiSelectionWidget from plone.app.form. This widget is
  broken in version 1.1.7 of plone.app.form. Plone 3.3.4 has this version.
As of version 1.1.8 the widget is working again. To use the correct version pin down
  plone.app.form:
[versions] ... plone.app.form = 1.1.8

A: Do you see any errors in the Plone log? You need to be precise when searching for users/groups. Can you try to search for the default 'administrators' group? Are you using the latest version (1.2) of mailtogroup?


text:
Q: Is this a partially ordered set? I was wondering if partially ordered sets could have loops in their diagrams. For example isn't the $S=\{1,2,3\}$ and relation $R=\{(1,1),(2,2),(3,3),(1,2),(2,3),(3,1)\}$ a partially ordered set that has a cycle? $R$ is reflexive, antisymmetric and transitive.

A: Transitivy fails for your relation $R$.
As for loops on the diagram, that is not possible due to transitivy, that should become apparent from the algorithm to draw diagrams I describe in this answer.


text:
Q: Select only 5 child-values from the same column, multiple parent-values in MySQL Can I get some help with this?
Database: CompanyXYZ
Table: mkt_product
Category ID is the parent value and Product ID is the child value
I have those columns, in the same table:

Product ID
Category ID
Product

001
cat1
Washing machine

002
cat1
Refrigerator

003
cat1
Oven

004
cat1
Built in Oven

005
cat1
Microwave

006
cat1
Vacuum cleaner

007
cat1
Hob

008
cat2
Potato

009
cat2
Carrot

010
cat2
Onion

011
cat2
Garlic

012
cat2
Tomato

013
cat2
Cucumber

014
cat2
Lettuce

The result I want:

Product ID
Category ID
Product

001
cat1
Washing machine

002
cat1
Refrigerator

003
cat1
Oven

004
cat1
Built in Oven

005
cat1
Microwave

008
cat2
Potato

009
cat2
Carrot

010
cat2
Onion

011
cat2
Garlic

012
cat2
Tomato

In the end, it doesn't matter if I get the top 5 results from each category, but I want only 5 results from each category. It's like a 'limit 5' for each category but in the same output, only one query.
I tried with 'limit' and 'having count' but I don't get what i want.
Thank you!

A: As I said in the comment,you can using window-functions-usage to do it
Schema code:
create table mkt_product(
  product_id varchar(100),
 category_id varchar(100),
 product varchar(100)
);

insert into mkt_product(product_id,category_id,product)
values
('001','cat1','Washing machine'),
('002','cat1','Refrigerator'),
('003','cat1','Oven'),
('004','cat1','Built in Oven'),
('005','cat1','Microwave'),
('006','cat1','Vacuum cleaner'),
('007','cat1','Hob'),
('008','cat2','Potato'),
('009','cat2','Carrot'),
('010','cat2','Onion'),
('011','cat2','Garlic'),
('012','cat2','Tomato'),
('013','cat2','Cucumber'),
('014','cat2','Lettuce');

Query sql:
  SELECT t1.*
  FROM mkt_product t1
  JOIN
  (
     SELECT product_id,category_id,product,
     ROW_NUMBER() OVER(PARTITION BY category_id ORDER BY product_id) as rn
     FROM mkt_product
   ) t2 ON t1.product_id = t2.product_id
     AND t1.category_id=t2.category_id AND t1.product=t2.product
  WHERE rn<=5

Note: t1.product_id = t2.product_id AND t1.category_id=t2.category_id AND t1.product=t2.product is very ugly,if your table have primary key such as id,it would be more simple
DB Fiddle Demo


text:
Q: How to use specific element of one to many relationship in whereHas (Laravel) I want to get data list , which has many relational rows in another table.
I need to check specific row of relational rows for getting data list from first, for example with it can be the first one and second ... (some conditions), but in whereHas you know that we are checking all elements.
$shipments->whereHas('shipment_stops', function ($q) use ($startDate) {
               $q->where('departure_date', '>=', $startDate) ;
            });

This will check all shipment_stops, but I want to check only the last stop with the specific type (for example).
I know that maybe I can create better structure in DB, but anyway, I have this structure.
Thanks

A: Use Has One Of Many
public function latestShipmentStop()
{
    return $this->hasOne(ShipmentStop::class)->latestOfMany();
}

..
$shipments->whereHas('latestShipmentStop', function ($q) use ($startDate) {
    $q->where('departure_date', '>=', $startDate) ;
});


text:
Q: Is there a way to know the type of the dataextension programatically I could not find a field to determine the type of DataExtension (Standard, Filtered, Synchronized) using ssjs, AMPScript, REST or SOAP Api.
Has anynone faced this problem?

A: The DataExtensionTemplate property may be able to provide you that information.

Indicates template used to create a data extension.

You can perform a retrieve on the DataExtension object.