text:
Q: AppScript: Google Calendar Remove Events I have the following code that uploads my events from Google Sheet to Google Calendar. This code searches the rows that need to be synced to the calendar based on value in column E (status) x[4]. Events that are marked as Pending Schedule or Pending Removal will be synced to the calendar and then update the respective rows in the sheet with Scheduled or Removed.
This code runs just fine in terms of scheduling events. But when it comes to removing events it only works if the first row of the data is marked to be removed, but not on other rows. It gives me TypeError: Cannot read property 'deleteEvent' of undefined and when I investigated the deleteEvent object shows as CalendarEvent.
Seems like the way I have written the if() functions is somehow not appropriate and the else if() does not evaluate the whole data. I have tried replacing else if() with another if() but received the same error.

function calendarSync2() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var dataSheet = ss.getSheetByName('Test Sheet')
  var settingsSheet = ss.getSheetByName('Calendar Settings');
  var calendarId = settingsSheet.getRange('B2').getValues();
  var eventCal = CalendarApp.getCalendarById(calendarId);
  var eventArray = dataSheet.getRange('A2:I').getDisplayValues();

  for (x = 0; x < eventArray.length; x++) {

    var event = eventArray[x];
    var eventName = event[1];
    var eventDate = new Date(event[0]);
    var timeZone = event[5];
    var startTime = new Date(`${event[0]} ${event[2]} ${timeZone}`); ///Used Object literals of `` combined with ${}
    var endTime = new Date(`${event[0]} ${event[3]} ${timeZone}`);
    var status = event[4]; // Used in the following comparison expression instead of filter

    if (status === 'Pending Schedule') { /// === undertakes strict comparison
      var exisEvents = eventCal.getEvents(startTime, endTime, {search: eventName});  // prevents creation of duplicates
      if (exisEvents.length == 0) {
        Logger.log(`timed ${eventName} scheduled for: ${startTime} till ${endTime}`);
        eventCal.createEvent(eventName, startTime, endTime);
        eventArray[x][4] = "Scheduled"; // Updates the status
      }
    } else if (status === 'Pending Removal') {
      Logger.log(`${eventName} at ${eventDate} REMOVED`)
      var returnedEvent = eventCal.getEvents(startTime, endTime, {search: eventName});
      var toRemove = returnedEvent[x];
      Logger.log(`returnedEvent is: ${returnedEvent}`);
      toRemove.deleteEvent();
      eventArray[x][4] = "Removed";
    }
  }
  dataSheet.getRange('A2:I').setValues(eventArray); // Overwrite the source data with the modified array
}

A: So with a little bit of digging I figured I need to create another loop for removing events. so the following code:
else if (status === 'Pending Removal') {
      var returnedEvent = eventCal.getEvents(startTime, endTime, {search: eventName});
      var toRemove = returnedEvent[x];
      toRemove.deleteEvent();
      eventArray[x][4] = "Removed";
    }

Should be changed to:
else if (status === 'Pending Removal') {
      var returnedEvents = eventCal.getEventsForDay(eventDate,
{search: eventName});
      for (i = 0; i < returnedEvents.length; i++) {
        var toRemove = returnedEvents[i];
        toRemove.deleteEvent();
        eventArray[x][4] = 'Removed';
      }
    }


text:
Q: Impala - CREATE TABLE after a WITH clause I have a query with several WITH clauses, then a CREATE TABLE :
    WITH TABLE_1 AS (
        SELECT * FROM SOMEWHERE_1
    ), TABLE_2 AS (
        SELECT * FROM SOMEWHERE_2

    (
        CREATE TABLE TABLE_3 AS
        (
            SELECT TABLE_1.*, TABLE_2.*
            FROM TABLE_1
            INNER JOIN TABLE_2 ON TABLE_2.key = TABLE_1.key
        )
    )

However I have the following error :

Encountered: CREATE Expected: SELECT, VALUES, WITH CAUSED BY: Exception: Syntax error

So I tried to put the CREATE statement first :
    CREATE TABLE_3 AS
    (
        WITH TABLE_1 AS (
            SELECT * FROM SOMEWHERE_1
        ), TABLE_2 AS (
            SELECT * FROM SOMEWHERE_2

        (
            SELECT TABLE_1.*, TABLE_2.*
            FROM TABLE_1
            INNER JOIN TABLE_2 ON TABLE_2.key = TABLE_1.key
        )
    )

But now I have the following error :

AnalysisException: Could not resolve table reference: 'TABLE_1'

Note that :

*

*The above query WORKS without the "CREATE" statement

*My present situation is more complex than this simpe example, and I would like to keep the WITH statements, for clarity.

A: Hmmm.  I think this will work:
CREATE TABLE TABLE_3 AS
    WITH TABLE_1 AS (
          SELECT * FROM SOMEWHERE_1
         ),
         TABLE_2 AS (
          SELECT * FROM SOMEWHERE_2
         )
    SELECT TABLE_1.*, TABLE_2.*
    FROM TABLE_1 INNER JOIN
         TABLE_2
         ON TABLE_2.key = TABLE_1.key;

Of course, you will have other problems, such as the key column being duplicated in the results -- and that should generate another error.  In practice, you should select exactly the columns that you want.

A: Alternatively, you can also do...
WITH TABLE_1 AS (
      SELECT * FROM SOMEWHERE_1
     ),
     TABLE_2 AS (
      SELECT * FROM SOMEWHERE_2
     )
SELECT TABLE_1.*, TABLE_2.* INTO TABLE_3
FROM TABLE_1 INNER JOIN
     TABLE_2
     ON TABLE_2.key = TABLE_1.key

It is much advised to always have a DDL handy and run INSERT INTO TABLE SELECT * FROM CTE

redpajama_set_name: RedPajamaStackExchange


text:
Q: MySQL query returns no result I have fields id and date defined as VARCHAR(16)
When I do this query:
SELECT *
FROM `members`
WHERE `id` = '4412040999876'
AND `date` = '201706054783'

I get no results.
When I do it like this:
SELECT *
FROM `members`
WHERE `id` = 4412040999876
AND `date` = 201706054783

Note - without the quotes - I get the result I am expecting.
EDIT: Here is the code used - I am not manually adding quotes. CI's DB class is adding them.
public function get_member_match($id, $mem, $field = 'name')
{
    $sql = "
        SELECT *
        FROM `members`
        WHERE `id` = ?
        AND `" . $field . "` = ?
    ";
    $sql_array = array($id, $mem);
    $q = $this->db->query($sql, $sql_array);
    return $q->result_array();
}

And I call this function as:
$this->members_model->get_member_match($id, $date, 'date');

I output the query, and the variables are matched correctly, no errors, only the quotes.
Any idea why? I never had this problem before. Working on CodeIgniter 3 using Query Builder.
EDIT2: Summary of findings so far:

*

*Localhost (MySQL 5.6.24) works, server (MySQL 5.5.55-0+deb7u1) doesn't.

*The problem occurs in my code and in PHPMyAdmin on the server but works locally, so I eliminate a code issue.

*The show variables like 'char%' query shows all character set settings identical on local and on the server.

*Database and fields have the same encoding on both server and local.

*Does not seem to be a casting issue as many of the comments suggest, as the problem is not present on localhost, only on the server, unless the server has config or other issues.

*...?

A: id might be defined as integer in your database. To match against integer fields you do not need to use quotes. Quotes are used when you match against string or text fields.

A: This should cast it back from the codeigniter's auto cast:
SELECT *
FROM `members`
WHERE `id` = '4412040999876'
AND `date` = '201706054783'

SELECT *
FROM `members`
WHERE CAST(`id` as INTEGER) = '4412040999876'
AND `date` = '201706054783'

A: Try to use this
$this->db->from('members');
$this->db->where('id',$id);
$this->db->where($field,$mem);
$q = $this->db->get();
return $q->result_array();

A: It's because the quotes imply that it is a string, whereas id field is an integer and must be written without quotes.
Same for date. Internally date is stored as an integer but is able to convert string into dates as long as they have an appropriate format


text:
Q: Python in AWS Lambda giving indent error on line that doesn't even exist I'm trying to setup a simple aws lambda function and no matter what python I put in the function it's returning an error on a line that's not even in the function.
What I started with:
def hello(event, context):
    print("hi i")
    return "hello-world"

What I"m at now:
def hello(event, context):
    pass

No matter what the body of the function is, when I test it I get this error:
Response:
{
  "errorMessage": "Syntax error in module 'handler'"
}

Request ID:
"6071965c-b7ad-4a9f-aa10-7a81980388f0"

Function logs:
START RequestId: 6071965c-b7ad-4a9f-aa10-7a81980388f0 Version: $LATEST
Syntax error in module 'handler': unindent does not match any outer indentation level (handler.py, line 4)

END RequestId: 6071965c-b7ad-4a9f-aa10-7a81980388f0
REPORT RequestId: 6071965c-b7ad-4a9f-aa10-7a81980388f0  Duration: 0.36 ms   Billed Duration: 1 ms   Memory Size: 1024 MB    Max Memory Used: 36 MB

The function I have now, just "pass" doesn't even have 4 lines, how could it be throwing this error? I'm using Python 2.7 Runtime.

Thank you!

A: Try changing
def hello(event, context):
to
def lambda_handler(event, context):
and rename your file from handler.py to lambda_function.py


text:
Q: Getting username of Parse user I have code that i am trying to get a username of a PFUser. I'm getting the user and able to print it out, but when I get to the line for the username, the code just stops. No crash nothing, just stops running?
Any ideas why it would do that?
    print(employeeObject)
    firstName.text = employeeObject.firstName
    lastName.text = employeeObject.lastName
    if employeeObject.roleType != nil {
        roleLabel.text = employeeObject.roleType?.roleName
    }
    if employeeObject.objectForKey("userPointer") != nil {
        employeeObject.userPoint = employeeObject.objectForKey("userPointer") as! PFUser
    }
    if employeeObject.userPoint != nil {
        let userID = employeeObject.userPoint!.objectId!
        let query = PFUser.query()
        query?.whereKey("objectId", equalTo: userID)
        query?.getFirstObjectInBackgroundWithBlock({ (userData : PFObject?, error : NSError?) in
            print(userData)
            self.userLoginSwitch.setOn(true, animated: false)
            self.userNameTextField.text = self.employeeObject.userPoint?.username!
            self.passwordTextField.text = ""
            self.emailAddressTextField.text = self.employeeObject.userPoint!.email
            if self.employeeObject.userPoint!.objectForKey("isAdmin") as! Bool {
                self.adminSwitch.setOn(true, animated: false)
            }
        })

    }
    if employeeObject.active {
        disableEnableEmployee.setTitle("Disable Employee", forState: .Normal)
    } else {
        disableEnableEmployee.setTitle("Enable Employee", forState: .Normal)
        disableEnableEmployee.setTitleColor(UIColor.blueColor(), forState: .Normal)
    }

I have userPoint casted as a PFUser, and then in Parse i have it pointed to the User table, and when i print. i can see all the information. It just stops working thought, with no error or explanation.
var userPoint : PFUser? {
    get {return objectForKey("userPointer") as? PFUser}
    set { setObject(newValue!, forKey: "userPointer") }
}

A: if you want to print the username from the query it has to be from the object that is returned, in your case userData and are you sure you dont have any break point in your code if it just stops?
self.userNameTextField.text = userData.username

A: When you fetching objects from Parse pointer objects are not included by default. There is only PFObject with objectId. If you want to include all of properties of pointer you need to use includeKey method with name of pointer. So if you get employeeObject from query (somewhere earlier) you should add line:
employeeQuery.includeKey("userPointer")

In this solution you wont need to get this user again because its the same object.
@Mazels answer is the second solution. You getting the same user by objectId so you can read data from usedData
self.userNameTextField.text = userData["username"]
self.emailAddressTextField.text = userData["email"]
if userData["isAdmin"] as! Bool { ...

Last thing:
if employeeObject.objectForKey("userPointer") != nil {
    employeeObject.userPoint = employeeObject.objectForKey("userPointer") as! PFUser
}

This is redundant. Look at your implementation of userPoint and this if statement. It really do nothing :)


text:
Q: Why is this simple program giving a segmentation fault? I have written a simple C++ program. The idea is, once it sees a non-alphabetic character, then till the time it see a new word (a blank) or the string ends, it keeps on incrementing the iterator.
This generates Segmentation fault, no idea why :(
Please help.
#include <iostream>
using namespace std;

int main()
{
 string str("Hello yuio");
 string::iterator it=str.begin();

 while(it!=str.end())
 {
  cout << *it << endl;

  if(isalpha(*it)==0){
   cout << *it << ":Is not an alphabet\n";

   while((*it!=' ')||(it!=str.end()))
   {
     cout << *it << endl;
     it++;
   }
  }

if(it!=str.end()){it++;}
  } // while loop ends
}  // End of main

A: while((*it!=' ')||(it!=str.end()))

The line above contains two errors.

*

*The condition says that the loop shall go on while the current character is not a space OR end of string is not reached yet. I.e., even when the end is reached but current char is not a space, the loop will proceed.

*Once you fixed this error (by replacing || with &&), you still try to dereference the end iterator (because the check for space comes before the check for end of string), which is not allowed. You have to switch the order of conditions:
while((it!=str.end()) && (*it!=' '))

A: The problem is here:
while((*it!=' ')||(it!=str.end()))

When you reach the end of the string, the first part of the condition is true and so you continue looping and incrementing the iterator.
You need to replace with &&:
while((*it!=' ')&&(it!=str.end()))

A: while((*it!=' ')||(it!=str.end()))

*it is evaluated before checking if it itself is ok to use. Change to:
while((it!=str.end())&&(*it!=' '))


text:
Q: Query for the same time period of every day in Prometheus I am trying to query for a metric on a specific hour of every day as a data table. I am new to Prometheus and not sure if it's even possible.
The end result I am looking for is something like this:
Average hourly latency for the month of April

Hour | Average Latency
---- | ---------------
12AM | 123.4
1AM  | 156.7
...

Is it possible and if so how to achieve that?


text:
Q: Spring boot enable/disable tomcat or kafka consumer based on the profile I'm writing a Spring Boot application with several @Configuration classes for rest APIs and for Kafka consumers/producers depending on which @Profile it chooses to initialize.
The first configuration class uses the REST interface, and I have these dependencies added.
This starts up an embedded Tomcat instance and runs fine.
Here the problem is the other profiles should not spin a tomcat server, it should act only as a Kafka consumer.
Is there any way to stop spinning the @SpringBootApplication from starting up Tomcat based on profiles?
I created 2 configuration classes, one for Kafka and one for rest endpoints, and added @Profile annotation for each config class. Can someone guide me on how to stop spin tomcat from my app?
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.0.RELEASE</version>
</parent>
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-batch</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.apache.tomcat</groupId>
                <artifactId>tomcat-jdbc</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>

Main application:
@SpringBootApplication
@Import(value = {RestScanConfiguration.class, KafkaScanConfiguration.class})
public class MainApp {

    public static void main(final String[] args) {
        SpringApplication.run(MainApp.class, args);
    }
}

RestScanConfiguration class:
@Configuration
@EnableAutoConfiguration
@ComponentScan(basePackages = "package.app.rest")
@Profile("!kafka")
public class RestScanConfiguration {
}

KafkaScanConfiguration class:
 @Configuration
@EnableAutoConfiguration(
        exclude = {
                DataSourceAutoConfiguration.class,
                HibernateJpaAutoConfiguration.class,
                ElasticsearchDataAutoConfiguration.class
        })
@ComponentScan(basePackages = {"package.app.kafka"})
@Profile("kafka")
public class KafkaScanConfiguration {
}

can someone guide me on this?
How to stop spinning the tomcat server in Kafka consumer/producer profile. Any help would be appreciated.

A: First you have to disbale the auto configuration for the embeded tomcat in the starter class to avoid deploying the tomcat:
@SpringBootApplication(exclude = {EmbeddedServletContainerAutoConfiguration.class,
                                  WebMvcAutoConfiguration.class})
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

and then add the following property to your kafka config (non-Rest profiles):
spring.main.web-environment=false

now you have disabled auto-deployment of the integrated tomcat in spring boot. Now add the following configuration to your Rest profile to enable tomcat (only for this profile):
@Profile({"REST"})
@Configuration
// importing EmbeddedServletContainerAutoConfiguration delays the autoconfiguration until the profile load into context
@Import(EmbeddedServletContainerAutoConfiguration.class)
public class HttpConfiguration {
    // ...
}

and afterwards you have configure your kafka dynamically. You can find a solution for that in Control enabling/disabling Kafka consumers in Spring Boot

A: Instead of configuring this in code I'd suggest you to create application-kafka.properties (or application-kafka.yml) and add the following line into it:
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration

This disables ServletWebServerFactoryAutoConfiguration which is a root configuration class for Web environment.
-kafka suffix in properties file name tells Spring to pick it up only when kafka profile is active.
Even better solution is to exclude
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>

from built jar. In other words you could have a pom.xml two profiles with only required dependencies (shared ones are located in main dependencies section). See https://stackoverflow.com/a/167284/12473843. Using this approach you don't even need specifying excluded autoconfigurations as without spring-boot-starter-web in the classpath corresponding started is never activated.


text:
Q: How to dismiss or unwind a view in Swift (Xcode 6)? I have been scouring the web for the best and most proper way to dismiss/unwind a view using Swift and cannot find a definitive answer. For ease of concept, I have two views and have linked one to the other with a button and a segue using "show." How do I return to the original view (no data needs to be passed)?

A: you can try adding a button action to your ViewController2 and add in the code below. Your ViewController2 will dismiss when the button is being pressed.
dismissViewControllerAnimated(true, completion: nil)


text:
Q: How to use for loop for login in karate framework Feature: Login
Background:
 * url ''

*

*def users = function(i){ return karate.call("classpath:v1/login.feature",
{ "username": 'shameem',
"password":  'shameen' ,
"ipAddress": "string",
"macAddress": "string",
"machineName": "string"})

*def usersResult = karate.repeat(2, users )

*match each usersResult[*].responseStatus == 200

Given url ''
And request users
When method post
Then status 200

*

*def Insert = response

*print Insert

*print 'created Insert is: ' + Insert.Message


text:
Q: HTML,javascript: on button click validation not working I am trying to validate(if they have value) my 1st two dropdowns of my html . On click of button getURL I am validating if there are any selected values in dropdowns and if YES I would like to proceed to function getURL.
But soon after validation , the control is not stopping if there are no values in 2nd dropbox. Its going ahead and displaying the URL.
I would like to display URL only if there are values in 1st two dropdowns. But now with my below code I am getting alert:url soon after alert:select product version
Javascript:
function validate() {
    var pname = document.getElementById("selProductName");
    if(pname.selectedIndex == 0) {
         alert('select product name');
    }

    var pversion = document.getElementById("selProductVersion");
    if(pversion.selectedIndex == 0) {
         alert('select product version');
         return false;
    }
  return true;
}

function getURL() {
    validate();
    // I have code here to create desired URL
    alert("url:" + url);
}

HTML:
Product Name:
<select id="selProductName" name="selProductName" onchange="changeProductName(this.value);">
<option>--Choose Product Name--</option>
</select>

Product Version:
<select id="selProductVersion" name="selProductVersion" onchange="changeProductVersion(this.value);">
</select>

File Name:
<select id="selFileName" name="selFileName"></select>

<button onclick="getURL()">Get URL</button>

A: validate() executes and returns false. Good. And then? Then the script goes on and alerts the url.
Currently :
function getURL() {
    validate(); // Returns true or return false, no consequence.
    alert("url:" + url); // Always happens.
}

You should use :
function getURL() {
    if(!validate()) return; // Blocks execution if validation fails.
    alert("url:" + url);
}

A: Your validate function is working exactly how it should. The problem is that you are never checking to make sure that validate didn't return false. Instead, you are just printing the url even if validate() does return false. Here is an edited version of the getURL() function that should work.
function getURL() {
    var isValid = validate();
    // Code to create URL

    // Only alert the formed URL if isValid doesn't equal false
    if(isValid != false) alert("url:" + url);
}


text:
Q: 1-cycle enable signal in a clocked process I am taking a vhdl online course.
One of the laboratory work is: "Based on frequency divider and 8-bit cyclic shift register implement a ring counter with a shift period of 1 s."
The task says that the most significant bit of the counter cannot be used as the clock signal of the shift register (i.e. in the if rising_edge (shifter (MSB)) construction.
It is necessary to form the enable signal as a strobe.
I did the job. The result is accepted.
I have a question related to shift register by enable.
    shift_reg_proc : process(clk)
    begin
        if (rising_edge(clk)) then
            if    (srst = '1') then
                shift_reg <= "10000000";
            elsif (en = '1') then
                shift_reg <= shift_reg(0) & shift_reg(7 downto 1);
            end if;
        end if;
    end process shift_reg_proc

If the duration of the enable signal is 1 period clk, then there is a probability that at the moment of rising_edge (clk) the en signal level will not have time to become = 1.
If this is the case, then it is not guaranteed that the register shift will occur in the next second.
Is there any "correct" way to do this task?
Is it so? Is my decision correct? Is the lab clue misleading?
I am attaching the implementation code, test bench and wave image.
ring_counter.vhd
--------------------------------------------------------------------------------
-- Based on frequency divider and 8-bit cyclic shift register implement a ring
-- counter with a shift period of 1 s.
--------------------------------------------------------------------------------

library ieee;
use ieee.std_logic_1164.all;
use ieee.std_logic_arith.all;

entity ring_counter is

    port(clk  : in  std_logic;
         srst : in  std_logic;
         dout : out std_logic_vector(7 downto 0);
         en_o : out std_logic
    );

end entity ring_counter;

architecture behave of ring_counter is

    signal   cntr             : std_logic_vector(26 downto 0) := (others => '0');
    signal   cntr_msb_delayed : std_logic;
    signal   shift_reg        : std_logic_vector(7 downto 0);
    signal   en               : std_logic;
    constant cntr_msb_num     : integer := 4; -- 26 for DE board, 4 for test bench

begin

    -- signal for test bench
    en_o <= en;

    --------------------------------------------------------------------------------
    -- Counter implementation
    --------------------------------------------------------------------------------

    cntr_proc : process(clk)
    begin
        if (rising_edge(clk)) then
            if (srst = '1') then
                cntr <= (others => '0');
            else
                cntr <= unsigned(cntr) + 1;
            end if;
        end if;
    end process cntr_proc;

    ----------------------------------------------------------------------------
    -- Shift register implementation
    ----------------------------------------------------------------------------

    shift_reg_proc : process(clk)
    begin
        if (rising_edge(clk)) then
            if    (srst = '1') then
                shift_reg <= "10000000";
            elsif (en = '1') then
                shift_reg <= shift_reg(0) & shift_reg(7 downto 1);
            end if;
        end if;
    end process shift_reg_proc;

    dout <= shift_reg;

    ----------------------------------------------------------------------------
    -- Enable signal generation
    ----------------------------------------------------------------------------

    -- Counter MSB delay for 1 period of clk
    delay_proc : process(clk)
    begin
        if (rising_edge(clk)) then
            cntr_msb_delayed <= cntr(cntr_msb_num);
        end if;
    end process delay_proc;

    en <= cntr(cntr_msb_num) and not cntr_msb_delayed;

end architecture behave;

ring_counter_tb.vhd
library ieee;
use ieee.std_logic_1164.all;

entity ring_counter_tb is

end entity ring_counter_tb;

architecture behave of ring_counter_tb is

    component ring_counter is
        port(clk  : in  std_logic;
             srst : in  std_logic;
             dout : out std_logic_vector(7 downto 0);
             en_o : out std_logic
        );
    end component ring_counter;

    signal clk  : std_logic;
    signal srst : std_logic;
    signal dout : std_logic_vector(7 downto 0);
    signal en_o : std_logic;

    constant clk_period : time := 4 ns;

begin

    dut : ring_counter
        port map (
            clk  => clk,
            srst => srst,
            dout => dout,
            en_o => en_o
        );

    clk_gen : process
    begin
        clk <= '0';
        wait for clk_period;
        loop
            clk <= '0';
            wait for clk_period/2;
            clk <= '1';
            wait for clk_period/2;
        end loop;
    end process clk_gen;

    srst <= '0',
            '1' after 100 ns,
            '0' after 150 ns;

end architecture behave;

wave for test bench

A: TL;DR
The rising edge of clk after which en is raised is not the same as the rising edge of clk at which your shift register shifts. en is asserted high after rising edge N and de-asserted after rising edge N+1. Your shift register is thus shifted at rising edge N+1.
So you have about one clock period delay between assertions of en and the register shifts. You don't care because your specification says that you want a shift period of 1 second. As long as en is periodic with a period of one second, even if there is a small constant delay between en and your shift register, you fulfill the specifications.
But what is of uttermost importance is that, as it is seen by your shift register, en is asserted high sufficiently after rising edge N to avoid a too early shift and de-asserted sufficiently after rising edge N+1 to allow a good nice shift. If you are interested in this too, please continue reading.
Detailed explanation
Your en signal is computed from the outputs of registers synchronized on the same clock clk as your shift register. You cannot have any hold time problem there: the propagation delay from the rising edge of the clock to the outputs of your cntr and cntr_msb_delayed registers guarantee that en will arrive at your shift register sufficiently after the rising edge of the clock that caused it (assuming you don't have large clock skews). It cannot arrive too early.
Can it arrive too late (setup time problem)? Yes, if your clock frequency is too high. The clock period would then be too short, en would not have enough time to be computed, stabilize and propagate to your shift register before the next rising edge of the clock and anything could happen (no shift at all, partial shift, metastabilities...)
This is a very common concern in digital design: you cannot operate at an arbitrarily high clock frequency. If you could you would clock your own computer at yotta-Hz or even more, instead of giga-Hz, and everything would become instantaneous. It would be nice but it is not how the real world works.
In a digital design you always have what is called a critical path. It is a particular chain of logic gates between a set of source registers and a destination register, along which the propagation delay of electrical signals is the largest of the whole design.
Which path it is among all possible and the total delay along this path depend on your design's complexity (e.g. the number of bits of your counter), your target hardware technology (e.g. the FPGA of your prototyping board) and the operating conditions (temperature, voltage of power supply, speed-grade of your FPGA).
(Yes, it depends also on the temperature, reason why hard-core gamers cool down their computers with high performance cooling systems. This avoids the destruction of the silicon and allows to operate the computer at a higher clock frequency with more frames per second and a better user experience.)
The largest time it takes for the signals to travel from the source clock-edge to the arrival at destination, augmented by a small security margin called the setup time of the destination register, is the smallest clock period (highest clock frequency) at which you can run your design. As long as you don't exceed this limit your system works as expected.
Hardware design tool chains usually comprise a Static Timing Analyzer (STA) that tells you what this maximum clock frequency is for your design, your target, and your operating conditions. If it tells you 500 MHz and you need only 350 MHz, everything is fine (you could however investigate and see if you could modify your design, save some hardware, and still run at 350 MHz).
But if you need 650 MHz it is time to roll up your sleeves, look at the critical path (the STA will also show the path), understand it and rework your design to speed it up (e.g. pipeline long computations, use carry look ahead adders instead of carry ripple...) Note that, usually, when you encounter timing closure problems you do not consider only one critical path but the set of all paths that exceed your time budget because you want to eliminate them all, not just the worst. This is why the STA gives you not only the worst critical path but a list of critical paths, in decreasing order of severity.


text:
Q: Moodle - Show image only in frontpage I am trying to display an image only on the front page of my Moodle.
Is there a way to detect where the user is, eg course page, profile page etc and use an if statment to display the picture only when the user is on the frontpage?
I am using a custom version of the Clean theme and I tried the code below.
When you are in a course it does not show the image, because the course with ID 1 is the frontpage, but it fails when you go to other pages, eg profile page.
<?php if ($PAGE->course->id == 1):?>
    <img src="<?php echo $OUTPUT->pix_url('header', 'theme'); ?>" class="img-responsive"/>

A: You can use the pagetype property in global $PAGE to check what page you are on
if (isset($PAGE) && (strpos($PAGE->pagetype, 'site-') === 0) {
    // I'm on the front page.
}

But you might be better off creating a front page layout. Edit theme/yourthemename/config.php and add (if its not there already)
$THEME->layouts =
....
array(
    // The site home page.
    'frontpage' => array(
        'file' => 'frontpage.php',
        'regions' => array('side-pre', 'side-post'),
        'defaultregion' => 'side-pre',
        'options' => array('nonavbar' => true),
    ),
);

Then edit frontpage.php - if there isn't one then copy columns3.php to frontpage.php
Then you can have a custom frontpage :)


text:
Q: Why is this sqlcmd batch file not outputting the file? I have a batch file with this code.
sqlcmd -S Database -E -Q "select * from People" -o "C:\test.csv" -h-1 -s"," -w 700

The batch file runs, and seems to pull the results of the query, but the output file never appears. Is there something wrong with the code, or is there a better way to output a sql query to a  .csv file?

A: Nick, I know this is old, but maybe could help newcomers as me. If you're working with a batch file, make sure you doesn't have a return char after the sql statement. Mine wasn't generating a file either, and then I found out that I pressed ENTER / RETURN after my statement.


text:
Q: merge 2 jsons by an element using javascript I have this json result:
[
  {
    "nom_playlist": "bbbb",
    "countMedias": 2
  },
  {
    "nom_playlist": "ccc",
    "countMedias": 1
  },
  {
    "nom_playlist": "aaaa",
    "countMedias": 3
  },
  {
    "nom_playlist": "xxxx",
    "countMedias": 1
  },
  {
    "nom_playlist": "resttttttttt",
    "countMedias": 2
  }
]

I have this other json :
[
  {
    idPlayListe: 25,
    idUtilisateur: 11968,
    idMedia: 79,
    etat: 1,
    nomPlaylist: 'bbbb'
  },
  {
    idPlayListe: 32,
    idUtilisateur: 11968,
    idMedia: 79,
    etat: 0,
    nomPlaylist: 'ccc'
   }
]

I want to add the etat of the second json to the first json and join it by nomPlaylist and if nomPlaylist doesn't exist I want set etat by default to 0.
This is an example of how I want the results to be :
[
  {
    nom_playlist: 'bbbb',
    etat: 1,
    countMedias: 2
  },
  {
    nom_playlist: 'ccc',
    etat: 0,
    countMedias: 1
  },
  {
    nom_playlist: 'aaaa',
    etat: 0,
    countMedias: 3
  },
  {
    nom_playlist: 'xxxx',
    etat: 0,
    countMedias: 1
  },
  {
    nom_playlist: 'resttttttttt',
    etat: 0,
    countMedias: 2
  }
]

Any help would be appreciated. Thank you

A: There are multiple ways to do it, you could loop over the first array and then loop over the second and reassign etat if nomPlaylist is the same (forgive the variable naming, I don't know what this data is supposed to represent):

const data = [
  { "nom_playlist": "bbbb", "countMedias": 2 },
  { "nom_playlist": "ccc", "countMedias": 1 },
  { "nom_playlist": "aaaa", "countMedias": 3 },
]
const otherData = [
  { etat: 1, nomPlaylist: 'bbbb' },
  { etat: 0, nomPlaylist: 'ccc' }
]

for ( const foo of data ) {
  let etat = 0;
  for ( const bar of otherData ) {
    if ( foo.nom_playlist === bar.nomPlaylist ) {
      etat = bar.etat;
      break;
    }
  }
  foo.etat = etat;
}
console.log( data );

A: You can try with map() and filter()

var arr1 = [{"nom_playlist": "bbbb","countMedias": 2},
            {"nom_playlist": "ccc","countMedias": 1},
            {"nom_playlist": "aaaa","countMedias": 3},
            {"nom_playlist": "xxxx","countMedias": 1},
            {"nom_playlist": "resttttttttt","countMedias": 2}];

var arr2 = [ {
    idPlayListe: 25,
    idUtilisateur: 11968,
    idMedia: 79,
    etat: 1,
    nomPlaylist: 'bbbb'
  },{
    idPlayListe: 32,
    idUtilisateur: 11968,
    idMedia: 79,
    etat: 0,
    nomPlaylist: 'ccc'
   }
];
var res = arr1.map(i => {
  var etat = arr2.filter(j => j.nomPlaylist == i.nom_playlist);
  i.etat = etat.length > 0 ?  etat[0].etat : 0;
  return i;
});

console.log(res);

A: *

*Create a map of first array of objects using .reduce().

*Use .map() to iterate over the first array and create a new object using Object.assign() using the map object (created above) to have the etat value from second array or defaults it to 0.

const data1 = [
  {"nom_playlist": "bbbb", "countMedias": 2},
  {"nom_playlist": "ccc", "countMedias": 1},
  {"nom_playlist": "aaaa", "countMedias": 3},
  {"nom_playlist": "xxxx", "countMedias": 1},
  {"nom_playlist": "resttttttttt", "countMedias": 2}
];

const data2 = [
  {idPlayListe: 25, idUtilisateur: 11968, idMedia: 79, etat: 1, nomPlaylist: 'bbbb'},
  {idPlayListe: 32, idUtilisateur: 11968, idMedia: 79, etat: 0, nomPlaylist: 'ccc'}
];

const map = data2.reduce((r, c) => (r[c.nomPlaylist] = c, r), {});

const result = data1.map(
  o => Object.assign(
    {}, o, {etat: o.nom_playlist in map ? map[o.nom_playlist].etat : 0}
  )
);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: Did you try such approach? Of course it needs some error checking and fallbacks.
const firstJson = ...;
const secondJson = ...;

const firstObject = JSON.parse(firstJson);
const secondObject = JSON.parse(secondJson);

const etatDict = secondObject.reduce((acc, cur) => acc[cur.nomPlaylist] = cur.etat, {});

for (const playlist of firstObject) {
    playlist.etat = etatDict[playlist.nom_playlist];
}

A: Using map and forEach loop

var a=[
  {
    "nom_playlist": "bbbb",
    "countMedias": 2
  },
  {
    "nom_playlist": "ccc",
    "countMedias": 1
  },
  {
    "nom_playlist": "aaaa",
    "countMedias": 3
  },
  {
    "nom_playlist": "xxxx",
    "countMedias": 1
  },
  {
    "nom_playlist": "resttttttttt",
    "countMedias": 2
  }
]

var b=[
  {
    idPlayListe: 25,
    idUtilisateur: 11968,
    idMedia: 79,
    etat: 1,
    nomPlaylist: 'bbbb'
  },
  {
    idPlayListe: 32,
    idUtilisateur: 11968,
    idMedia: 79,
    etat: 0,
    nomPlaylist: 'ccc'
   }
]
console.log(a.map(function(e){
b.forEach(function(k){
k.nomPlaylist==e.nom_playlist?e.etat=k.etat:false
})
if(!e.hasOwnProperty('etat'))
e.etat=0;
return e;
}))

A:

    // first array of objects
    var firstJson = [
            {
              "nom_playlist": "bbbb",
              "countMedias": 2
            },
            {
              "nom_playlist": "ccc",
              "countMedias": 1
            },
            {
              "nom_playlist": "aaaa",
              "countMedias": 3
            },
            {
              "nom_playlist": "xxxx",
              "countMedias": 1
            },
            {
              "nom_playlist": "resttttttttt",
              "countMedias": 2
            }
        ];

        // second array of objects
        var secondJson = [
            {
              nom_playlist: 'bbbb',
              etat: 1,
              countMedias: 2
            },
            {
              nom_playlist: 'ccc',
              etat: 0,
              countMedias: 1
            },
            {
              nom_playlist: 'aaaa',
              etat: 0,
              countMedias: 3
            },
            {
              nom_playlist: 'xxxx',
              etat: 0,
              countMedias: 1
            },
            {
              nom_playlist: 'resttttttttt',
              etat: 0,
              countMedias: 2
            }
        ];
       // Generating updated array using firstJson and secondJson arryas

        var mergedJson = firstJson.map(item => {
            secondJson.forEach(obj => {
                if (item.nom_playlist === obj.nomPlaylist) {
                    item["etat"] = obj.etat;
                }
            });
            if(!item["etat"]) {
                item["etat"] = 0;
            }
            return item;
        });
        console.log(mergedJson);


text:
Q: Difficulty listing data using a view model in ASP.NET MVC I am trying to pass data from a view model which derives from 2 models. The controller looks like this
public ActionResult SessionDetails()
{
    var Sessions = (from a in db.Appointments
                    join c in db.Clients
                    on a.clientid equals c.id into SessionList
                    from c in SessionList.DefaultIfEmpty()
                    select new SessionViewModel()
                    {

                        id = a.id,
                        sessionnotes = a.sessionnotes,
                        firstname = c.firstname,
                        date = a.date,

                    }).ToList()
             .Select(x => new SessionViewModel()
             {

                 id = a.id,
                 sessionnotes = a.sessionnotes,
                 firstname = c.firstname,
                 date = a.date,
             });

    return View(Sessions);
}

It is coming up with errors saying the name "a" does not exist in the current context? Any ideas as to what is going on?
I am really new to this, I followed these instructions using website http://techfunda.com/howto/262/list-data-using-viewmodel which does what I want SessionDetails to do.
I already have a view for this.
UPDATE
I have made following changes:
public ActionResult SessionDetails()
{
    var Sessions = (from a in db.Appointments
                    join c in db.Clients
                    on a.clientid equals c.id into SessionList
                    from c in SessionList.DefaultIfEmpty()
                    select new SessionViewModel()
                    {

                        id = a.id,
                        sessionnotes = a.sessionnotes,
                        firstname = c.firstname,
                        date = a.date,

                    }).ToList();

    return View(Sessions);
}

But when i run it, i get this: an exception of type System.NotSupportedException occurred in EntityFramework.SqlServer.dll but was not handled in user code.
Additional information: the entity or complex type fypag.Models.SessionViewModel cannot be constructed in a LINQ to Entities query.

A: I think your model should look like this.
   var Sessions = (from a in db.Appointments
                             join c in db.Clients
                             on a.clientid equals c.id into SessionList
                             from c in SessionList.DefaultIfEmpty()
                             select new SessionViewModel()
                             {

                                id = a.id,
                                 sessionnotes = a.sessionnotes,
                                 firstname = c.firstname,
                                 date = a.date,

                             }).ToList()
                   .Select(x => new SessionViewModel()
                    {
                         id = x.id,
                         sessionnotes = x.sessionnotes,
                         firstname = x.firstname,
                         date = x.date,
                    });

UPDATE:
var Sessions = (from a in db.Appointments
                join c in db.Clients
                on a.clientid equals c.id into SessionList
                from c in SessionList.DefaultIfEmpty()
                .Select(y => new SessionViewModel()
                {
                    id = y.id,
                    sessionnotes = y.sessionnotes,
                    firstname = y.firstname,
                    date = y.date,

                }).ToList();


text:
Q: Surround with {% trans "" %} tag What would be the simplest why to bind a pydev keyboard shortcut to a command which surrounds the selected text with a django trans template tag, modifying it to {% trans "text" %}?

A: Note: the answer below is if you're in the PyDev editor (.py files)... This support is not currently available for the Django Template editor (so, please let me know which editor you're actually using where you want that feature).
You currently can't set templates to a given keyboard shortcut.
Now, having said that, you can make it work by creating a custom scripting command.
It should be pretty straightforward, just follow the split lines (Ctrl+2, sl) as an example.
I.e.: in your PyDev install you should have a Python module at plugins/org.python.pydev.jython/jysrc/pyedit_create_lines_on_commas.py, create a copy of it -- but make sure it still starts with 'pyedit_', then change the function SplitTextInCommas to do what you want and change the ACTIVATION_STRING to something else -- i.e.: if you change it to x, you have to do Ctrl+2, x to activate it.
Also, you should probably also set the location of 'additional jython scripts' to a folder where you put that module (window > preferences > pydev > scripting pydev).
It may also be worth taking a look at: http://pydev.org/manual_articles_scripting.html for some more info on scripting PyDev.


text:
Q: Parameterized OPENJSON in SQL Server query using Entity Framework Core context.Set<BlogKeyValuePair>()
   .FromSql("SELECT [key], value FROM OPENJSON((SELECT JsonData FROM dbo.Blogs WHERE BlogId=1), '$.@path')",
        new SqlParameter("@path", "path.to.data"));

On first sighting this should work correctly and @path should be replace by path.to.data but it doesn't, an SqlException is thrown with the following error:

System.Data.SqlClient.SqlException: Incorrect syntax near '@path'.

Seems like SQL server does not replace the parameter because it is a parameter inside the OPENJSON function.
Looking for secure workarounds.

A: SQL does not recognize the variable because you put it inside a string:
-- Wrong:
OPENJSON((SELECT JsonData FROM dbo.Blogs WHERE BlogId = 1), '$.@path')

-- Correct:
OPENJSON((SELECT JsonData FROM dbo.Blogs WHERE BlogId = 1), '$.' + @path)

Code:
context
    .Set<BlogKeyValuePair>()
    .FromSql(@"
        SELECT [key], value
        FROM OPENJSON((SELECT JsonData FROM dbo.Blogs WHERE BlogId = 1), '$.' + @path)",
        new SqlParameter("@path", "path.to.data"));

A: This works for me in SSMS, so @marsze's answer should work.
declare @path nvarchar(2000) = 'ArrayValue';

DECLARE @json NVARCHAR(4000) = N'{
   "StringValue":"John",
   "IntValue":45,
   "TrueValue":true,
   "FalseValue":false,
   "NullValue":null,
   "ArrayValue":["a","r","r","a","y"],
   "ObjectValue":{"obj":"ect"}
}'

SELECT *
FROM OPENJSON(@json, '$.' + @path)


text:
Q: How to display correct value? discord.js I'm trying to make a currency system with mySQL. So, the problem I'm encountering is when a user types ?add (add currency )and then ?bal (to get user's balance) everything is fine, but if a user after them types ?bal, the bot will show the previous user's balance:
Expected output
User1: ?add

Bot: Now you have 10 money!

User1: ?bal

Bot: You have 10 money!

User2: ?bal

Bot: You have 20 money!

Actual output
User1: ?add

Bot: Now you have 10 money!

User1: ?bal

Bot: You have 10 money!

User2: ?bal

Bot: You have 10 money! //which is User1's bal

And the weird thing is that in the database the values are fine (example: User1 - 10; User2 - 20)
Below is the code
if(command == "add"){
      con.query(`SELECT * FROM money WHERE id = '${msg.author.id}'`, (err, rows) => {
        if (err) throw err;

        if(rows.length < 1){
       sql = `INSERT INTO money (id, money) VALUES ('${msg.author.id}', '${add}')`
        }else{

          let money = rows[0].money;
          sql = `UPDATE money SET money = ${money + add} WHERE id = '${msg.author.id}' `
          msg.channel.send(`Now you have ${money} money!`)

        }
        con.query(sql, console.log)

      })

    }
      if(command == "bal"){
        con.query(`SELECT * FROM money WHERE id = '${msg.author.id}'`, (err) => {
          if (err) throw err;

          msg.channel.send(`You have ${money} money!`)

      })
      }

A: You need to end the connection before you start another one, otherwise it just queries the same thing.
if(command == "add") {
  con.start() // I am not sure of the syntax for starting a connection, but this is an assumption
  con.query(`SELECT * FROM money WHERE id = '${msg.author.id}'`, (err, rows) => {
    if (err) throw err;

    if(rows.length < 1) {
   sql = `INSERT INTO money (id, money) VALUES ('${msg.author.id}', '${add}')`
    }else{

      let money = rows[0].money;
      sql = `UPDATE money SET money = ${money + add} WHERE id = '${msg.author.id}' `
      msg.channel.send(`Now you have ${money} money!`)

    }
    con.query(sql, console.log)
    con.end(); // these are important, because they close the connection
  })
}

if(command == "bal") {
    con.start()
    con.query(`SELECT * FROM money WHERE id = '${msg.author.id}'`, (err) => {
      if (err) throw err;

      msg.channel.send(`You have ${money} money!`)
    con.end();
  })
}

I am unsure of the nature of the syntax for starting a query, but I found online that <connection>.end() is used
I have never used MySQL and personally use better-sqlite3 since it is 40x faster, but this is what I think you are doing wrong.


text:
Q: ArcGIS: Extract portion of a geometric network that exists 30 mi downstream of intersection with another layer I have flow lines for streams. I've made them into a geometric network. The streams intersect with a rail network. I want to find all of the points of intersection and then get all of the flow lines 30 miles downstream of those points. The idea is to be able to mitigate any hazardous waste spill from the rail. We think 30 miles downstream is a good starting point for planning. How can I create a layer for all of these 30 mi downstream segments? I have included an example of what we're hoping the final product will look like. The rail is the black line and the streams are the blue lines.

A: You are wrong with your assumptions.
Picture below shows streams network, where some of the nodes (that I called Railway Intersections) are labelled by their flow distance to outlet. I created 4 "long rivers" starting at these nodes and ending at common outlet. I split four resulting rivers at the same distance of 3700 m from river start, and remove downstream bits. Ends of remaining same length "rivers" shown as red circles. I leave it to you to define pairs of  rail intersections/red circles.

So your question needs re-wording at least.
Also I used networkx python model to do the job. I don't think you can handle it using standard set of tools, perhaps invest in coding.


text:
Q: How can I improve this working sqldependency implementation? I'm a beginner with C# MVC (about 6 months of self-learning), currently working on my first project, and I recently came across the problem of an SQL dependency duplicating when the user refreshes a page.
Through looking at various posts and articles across sites, I have cobbled together a working implementation, but I'm still getting my head around some of the elements of it, especially the singleton design pattern and the various class and property modifiers.
I would like to know, are there any gaping holes in my code, or any other considerations I should be making as I plan to set up a few more dependencies?
To give a bit of background to the project scale, it will be used by up to 500 users at a time, and the data affecting the dependency will change up to around once a second during busy periods.
Many thanks in advance. :)
Here is my dependency class:
public sealed class UMCSingleton
{
    private static UMCSingleton instance;
    private static string connString = ConfigurationManager.ConnectionStrings["ServerConnection"].ConnectionString;
    private static SqlConnection conn = new SqlConnection(connString);
    private SqlDependency dependency;
    private static volatile object padlock = new object();

    private UMCSingleton() {}

    public static UMCSingleton Instance
    {
        get
        {
            if (instance == null)
            {
                lock (padlock)
                {
                    if (instance == null)
                    {
                        instance = new UMCSingleton();
                    }
                }
            }

            return instance;
        }

    }

    public static SqlConnection getUMCConnection()
    {
        try
        {
            if(conn == null)
            {
                conn = new SqlConnection(connString);
                conn.Open();
                return conn;
            }

            if(conn.State == ConnectionState.Closed)
            {
                conn.ConnectionString = connString;
                conn.Open();
            }
        }
        catch (SqlException e) {}
        finally {}
        return conn;
    }

    public void RegisterUnmanagdCallDependency()
    {
        using (getUMCConnection())
        {
            using (SqlCommand cmd = conn.CreateCommand())
            {
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "SELECT [CallRef], [CallLoggedByUserId] FROM [dbo].[UnplannedCustomers] Where [ServiceFlowId] = 1";

                cmd.Notification = null;
                if (dependency == null || dependency.HasChanges == true)
                {
                    dependency = new SqlDependency(cmd);
                    dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
                }

                using (SqlDataReader reader = cmd.ExecuteReader()) {}
            }
        }
    }

    void dependency_OnChange(object sender, SqlNotificationEventArgs e) //this will be called when any changes occur in db table.
    {
        if (e.Type == SqlNotificationType.Change)
        {
            SqlDependency dependency = (SqlDependency)sender;
            if (dependency.HasChanges == true)
            {
                dependency.OnChange -= dependency_OnChange;
            }
            UnmanagedCallHub.ShowCalls();

            RegisterUnmanagdCallDependency();
        }
    }
}

Here is my hub class:
    public class UnmanagedCallHubData
{
    public string CallRef { get; set; }
    public string RaisedBy { get; set; }
}

public class UnmanagedCallHub : Hub
{
    private ApplicationDbContext _context;
    public UnmanagedCallHub()
    {
        _context = new ApplicationDbContext();
    }

    public static void ShowCalls()
    {
        IHubContext context = GlobalHost.ConnectionManager.GetHubContext<UnmanagedCallHub>();
        context.Clients.All.UpdateCalls();

    }
}

And finally my api controller:
    public class UnmanagedCallController : ApiController
{
    private ApplicationDbContext _context;
    private UserProfile _uPro;

    //CONSTRUCTOR SETS DB CONTEXT
    public UnmanagedCallController()
    {
        _context = new ApplicationDbContext();
        ApplicationUser user = HttpContext.Current.GetOwinContext()
            .GetUserManager<ApplicationUserManager>().FindById(HttpContext.Current.User.Identity.GetUserId());
        _uPro = _context.UserProfiles.SingleOrDefault(x => x.UserId == user.Id);
    }

    [HttpGet]
    [Authorize]
    public List<UnmanagedCallHubData> GetUnmanagedCalls()
    {
        List<UnmanagedCallHubData> calls = _context.UnplannedCustomers
            .Where(x => x.ServiceFlowId == 1)
            .Where(x => x.CurrentManagerUserId == null)
            .Select(x => new UnmanagedCallHubData
            {
                CallRef = x.CallRef,
                RaisedBy = x.CallLoggedByUserId
            }).ToList();

        UMCSingleton.Instance.RegisterUnmanagdCallDependency();

        return calls;
    }
}


text:
Q: Unity Changing material color on multiple gameobjects I made a right click menu and i want to make objects change material color while i have my mouse on a button in that menu.
This is the code:
Color[] startCo;

public void OnPointerEnter(PointerEventData eventData)
{
    GameObject[] objects = GameObject.FindGameObjectsWithTag(myMenu.selected.title);

    for (int i = 0; i < startCo.Length; i++)
    {
        startCo[i] = objects[i].gameObject.GetComponent<MeshRenderer>().material.color;
    }

    foreach (GameObject obj in objects)
    {
        obj.gameObject.GetComponent<MeshRenderer>().material.color = Color.red;
    }
}

public void OnPointerExit(PointerEventData eventData)
{
    GameObject[] objects = GameObject.FindGameObjectsWithTag(myMenu.selected.title);

    for (int i = 0; i < objects.Length; i++)
    {
        objects[i].gameObject.GetComponent<MeshRenderer>().material.color = startCo[i];
    }
}

With first for loop it does not work at all, but without it, when I put my mouse on the button, it makes material colors red, but it won't change it back to orginal.
My question is, is there any better way to save original colors with using foreach?

A: Well my guess is you are finding objects every time these methods are called using GameObject.FindGameObjectsWithTag and i am pretty sure the order of these objects returned by FindGameObjectsWithTag is not specified so it can change ever time you call this method. This issue ends up giving you different original colors for different objects. My suggestion would be getting objectsin the Startonce and assigning colors to the array. Then use this array in OnPointerExitfunction.
Other than that your code and logic seems fine to me.

A: Try this version. It basically does exactly the same thing as your version, but makes sure to initialize the color array before using it (which was probably your main issue). It also keeps a copy of the list of objects whose colors were replaced, which is important in case new objects with a matching tag are created, or existing one's deleted. Finally, it adds a few safeguards to make it more robust in case you want to use ReplaceColors() and RestoreColors() in other places, too.
GameObject[] objectsWithReplacedColors;
Color[] originalColors;

public void OnPointerEnter(PointerEventData eventData)
{
    ReplaceColors(GameObject.FindGameObjectsWithTag(myMenu.selected.title), Color.red);
}

public void OnPointerExit(PointerEventData eventData)
{
    RestoreColors();
}

private void ReplaceColors(GameObject[] forObjects, Color withColor)
{
    if (objectsWithReplacedColors != null)    // if there are already objects with replaced colors, we have to restore those first, or their original color would be lost
        RestoreColors();

    objectsWithReplacedColors = forObjects;
    originalColors = new Color[objectsWithReplacedColors.Length];

    for (int i = 0; i < objectsWithReplacedColors.Length; i++)
    {
        originalColors[i] = objects[i].GetComponent<MeshRenderer>().material.color;
        objectsWithReplacedColors[i].GetComponent<MeshRenderer>().material.color = withColor;
    }
}

private void RestoreColors()
{
    if (objectsWithReplacedColors == null)
        return;

    for (int i = 0; i < objectsWithReplacedColors.Length; i++)
    {
        if (objectsWithReplacedColors[i])    // check if the objects still exists (it may have been deleted since its color was replaced)
            objectsWithReplacedColors[i].GetComponent<MeshRenderer>().material.color = originalColors[i];
    }

    objectsWithReplacedColors = null;
    originalColors = null;
}


text:
Q: Distributing Apps Outside the App Store I have a small app that I want to distribute to a small group of people and was following the Distributing Apps Outside the App Store instructions.  I have Archived the app with my developer ID and IOS Distribution Cert, created the Manifest.plist file. uploaded them to the website which is HTTPS with a root cert that is on the IOS9 trusted list and used the sample html link provided in the instructions.
clicking the link with Safari from an iPhone 9.2 I get an alert that say:
""Cannot install applications because the certificate for the "website" is not valid""
Any help on why this error(Alert) is happening and how to get the app to install would be appreciated.

A: Start here:
https://developer.apple.com/testflight/
TestFlight is by far the easiest option for something like this, but it does come with significant downsides. You need to push out a new version of your app every 60 days, because they expire automatically. Your app also has to pass a "Beta App Review", which it might not actually pass. I'd hope that the Beta App Review process is a bit faster/simpler than review for a generally-available app, but I don't have any experience there.
The other option is the Enterprise Developer program, but for that, you need to send Apple $300 a year, and you have to have a corporate legal entity to sign up.

A: thanks Mark
I will probably go with the Enterprise since I already have a corp D&B and that is what my current DeveloperId is under.  I will just let the 99.00 id expire and just use the Enterprise for what I need.  Either way the cost is a write-off.  Thanks for your replies...much appreciated.


text:
Q: Install CasperJS from git From the docs, the process is:
$ git clone git://github.com/n1k0/casperjs.git
$ cd casperjs
$ ln -sf `pwd`/bin/casperjs /usr/local/bin/casperjs

After doing this, my error is as follows.  What am I doing wrong?
$ casperjs --version
-bash: /usr/local/bin/casperjs: is a directory


text:
Q: STM32F4 How to stop triple interleaved mode? I am using triple interleaved mode with DMA in STM32F429 and have problem stopping it.
It should be stopped by HAL_ADCEx_MultiModeStop_DMA(&hadc1), but while debugging it gives HAL_DMA_ERROR_NO_XFER error during HAL_DMA_Abort function. I suspect it thinks DMA is busy, however I issue HAL_ADCEx_MultiModeStop_DMA(&hadc1) in HAL_ADC_ConvCpltCallback, which implies that conversion is completed (and I also use normal mode, not circular, so no transfers should occur).
I start the conversion by button press, the first conversion working, but because ADC is not stopped the second conversion (on second button press) never occurs. I checked the circular mode - it works fine, data is updated all the time.
I've found some mentions of this error on internet (like this and that, but not much help.
Here is my code, hope everything is clear. I omitted some unrelated stuff like RCC config, CubeMX boilerplate, etc.
I already tried turning off ADC2 and ADC3 before stopping ADC1 (although they seem to be stopped after ADC1, based on this example. Its for STM32F3 but I suppose it is similar in F4 too).
I tried using DMA access mode 2, however from datasheet I'm sure it needs to be access mode 3 because I use 8 bit resolution.
I also tried to change PeriphDataAlignment and MemDataAlignment between BYTE, HALFWORD and WORD, but no result too.
Also tried to put HAL_ADCEx_MultiModeStop_DMA(&hadc1) in main function after some delay (though maybe using it in callback is not good), but it doesn't change anything.
I have no idea what I am supposed to do, was changing code here and there for 5 hours with no result.
stm32f4xx_hal_msp.c
void HAL_ADC_MspInit(ADC_HandleTypeDef* hadc)
{

  GPIO_InitTypeDef GPIO_InitStruct;
  if(hadc->Instance==ADC1)
  {
  /* USER CODE BEGIN ADC1_MspInit 0 */

  /* USER CODE END ADC1_MspInit 0 */
    /* Peripheral clock enable */
    __HAL_RCC_ADC1_CLK_ENABLE();

    /**ADC1 GPIO Configuration
    PA3     ------> ADC1_IN3
    */
    GPIO_InitStruct.Pin = GPIO_PIN_3;
    GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

    /* Peripheral DMA init*/

    hdma_adc1.Instance = DMA2_Stream0;
    hdma_adc1.Init.Channel = DMA_CHANNEL_0;
    hdma_adc1.Init.Direction = DMA_PERIPH_TO_MEMORY;
    hdma_adc1.Init.PeriphInc = DMA_PINC_DISABLE;
    hdma_adc1.Init.MemInc = DMA_MINC_ENABLE;
    hdma_adc1.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
    hdma_adc1.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE;
    hdma_adc1.Init.Mode = DMA_NORMAL;
    hdma_adc1.Init.Priority = DMA_PRIORITY_HIGH;
    hdma_adc1.Init.FIFOMode = DMA_FIFOMODE_DISABLE;
    if (HAL_DMA_Init(&hdma_adc1) != HAL_OK)
    {
      Error_Handler();
    }

    __HAL_LINKDMA(hadc,DMA_Handle,hdma_adc1);

  /* USER CODE BEGIN ADC1_MspInit 1 */

  /* USER CODE END ADC1_MspInit 1 */
  }
  else if(hadc->Instance==ADC2)
  {
  /* USER CODE BEGIN ADC2_MspInit 0 */

  /* USER CODE END ADC2_MspInit 0 */
    /* Peripheral clock enable */
    __HAL_RCC_ADC2_CLK_ENABLE();

    /**ADC2 GPIO Configuration
    PA3     ------> ADC2_IN3
    */
    GPIO_InitStruct.Pin = GPIO_PIN_3;
    GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

  /* USER CODE BEGIN ADC2_MspInit 1 */

  /* USER CODE END ADC2_MspInit 1 */
  }
  else if(hadc->Instance==ADC3)
  {
  /* USER CODE BEGIN ADC3_MspInit 0 */

  /* USER CODE END ADC3_MspInit 0 */
    /* Peripheral clock enable */
    __HAL_RCC_ADC3_CLK_ENABLE();

    /**ADC3 GPIO Configuration
    PA3     ------> ADC3_IN3
    */
    GPIO_InitStruct.Pin = GPIO_PIN_3;
    GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

  /* USER CODE BEGIN ADC3_MspInit 1 */

  /* USER CODE END ADC3_MspInit 1 */
  }

}

main.c
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "stm32f4xx_hal.h"
#include "usb_device.h"

/* USER CODE BEGIN Includes */
#include "usbd_cdc_if.h"
#define ADC_BUFFER_LENGTH 14
/* USER CODE END Includes */

/* Private variables ---------------------------------------------------------*/
ADC_HandleTypeDef hadc1;
ADC_HandleTypeDef hadc2;
ADC_HandleTypeDef hadc3;
DMA_HandleTypeDef hdma_adc1;

/* USER CODE BEGIN PV */
/* Private variables ---------------------------------------------------------*/
uint8_t ADCBuffer[ADC_BUFFER_LENGTH];
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
void Error_Handler(void);
static void MX_GPIO_Init(void);
static void MX_DMA_Init(void);
static void MX_ADC1_Init(void);
static void MX_ADC2_Init(void);
static void MX_ADC3_Init(void);

/* USER CODE BEGIN PFP */
/* Private function prototypes -----------------------------------------------*/
void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* AdcHandle)
{
    HAL_ADCEx_MultiModeStop_DMA(&hadc1);
    HAL_ADC_Stop(&hadc3);   // Although it doesn't matter
    HAL_ADC_Stop(&hadc2);   // since prev function returns error
}
/* USER CODE END PFP */

/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

int main(void)
{

  /* USER CODE BEGIN 1 */
  /* USER CODE END 1 */

  /* MCU Configuration----------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* Configure the system clock */
  SystemClock_Config();

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_DMA_Init();
  MX_USB_DEVICE_Init();
    MX_ADC3_Init();
    MX_ADC2_Init();
  MX_ADC1_Init();

  /* USER CODE BEGIN 2 */
    HAL_Delay(1500);
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
  /* USER CODE END WHILE */

  /* USER CODE BEGIN 3 */
        if (HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_0) == 1)
        {
            HAL_ADC_Start(&hadc3);
            HAL_ADC_Start(&hadc2);
            HAL_ADCEx_MultiModeStart_DMA(&hadc1, (uint32_t*) &ADCBuffer, ADC_BUFFER_LENGTH);
            HAL_Delay(500);
        }
  }
  /* USER CODE END 3 */

}

/* ADC1 init function */
static void MX_ADC1_Init(void)
{

  ADC_MultiModeTypeDef multimode;
  ADC_ChannelConfTypeDef sConfig;

    /**Configure the global features of the ADC (Clock, Resolution, Data Alignment and number of conversion)
    */
  hadc1.Instance = ADC1;
  hadc1.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV2;
  hadc1.Init.Resolution = ADC_RESOLUTION_8B;
  hadc1.Init.ScanConvMode = DISABLE;
  hadc1.Init.ContinuousConvMode = ENABLE;
  hadc1.Init.DiscontinuousConvMode = DISABLE;
  hadc1.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
  hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT;
  hadc1.Init.NbrOfConversion = 1;
  hadc1.Init.DMAContinuousRequests = DISABLE;
  hadc1.Init.EOCSelection = ADC_EOC_SINGLE_CONV;
  if (HAL_ADC_Init(&hadc1) != HAL_OK)
  {
    Error_Handler();
  }

    /**Configure for the selected ADC regular channel its corresponding rank in the sequencer and its sample time.
    */
  sConfig.Channel = ADC_CHANNEL_3;
  sConfig.Rank = 1;
  sConfig.SamplingTime = ADC_SAMPLETIME_3CYCLES;
  if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }

        /**Configure the ADC multi-mode
    */
  multimode.Mode = ADC_TRIPLEMODE_INTERL;
  multimode.DMAAccessMode = ADC_DMAACCESSMODE_3;
  multimode.TwoSamplingDelay = ADC_TWOSAMPLINGDELAY_5CYCLES;
  if (HAL_ADCEx_MultiModeConfigChannel(&hadc1, &multimode) != HAL_OK)
  {
    Error_Handler();
  }

}

/* ADC2 init function */
static void MX_ADC2_Init(void)
{

  ADC_MultiModeTypeDef multimode;
  ADC_ChannelConfTypeDef sConfig;

    /**Configure the global features of the ADC (Clock, Resolution, Data Alignment and number of conversion)
    */
  hadc2.Instance = ADC2;
  hadc2.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV2;
  hadc2.Init.Resolution = ADC_RESOLUTION_8B;
  hadc2.Init.ScanConvMode = DISABLE;
  hadc2.Init.ContinuousConvMode = ENABLE;
  hadc2.Init.DiscontinuousConvMode = DISABLE;
  hadc2.Init.DataAlign = ADC_DATAALIGN_RIGHT;
  hadc2.Init.NbrOfConversion = 1;
  hadc2.Init.DMAContinuousRequests = DISABLE;
  hadc2.Init.EOCSelection = DISABLE;
  if (HAL_ADC_Init(&hadc2) != HAL_OK)
  {
    Error_Handler();
  }

    /**Configure for the selected ADC regular channel its corresponding rank in the sequencer and its sample time.
    */
  sConfig.Channel = ADC_CHANNEL_3;
  sConfig.Rank = 1;
  sConfig.SamplingTime = ADC_SAMPLETIME_3CYCLES;
  if (HAL_ADC_ConfigChannel(&hadc2, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }

}

/* ADC3 init function */
static void MX_ADC3_Init(void)
{

  ADC_MultiModeTypeDef multimode;
  ADC_ChannelConfTypeDef sConfig;

    /**Configure the global features of the ADC (Clock, Resolution, Data Alignment and number of conversion)
    */
  hadc3.Instance = ADC3;
  hadc3.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV2;
  hadc3.Init.Resolution = ADC_RESOLUTION_8B;
  hadc3.Init.ScanConvMode = DISABLE;
  hadc3.Init.ContinuousConvMode = ENABLE;
  hadc3.Init.DiscontinuousConvMode = DISABLE;
  hadc3.Init.DataAlign = ADC_DATAALIGN_RIGHT;
  hadc3.Init.NbrOfConversion = 1;
  hadc3.Init.DMAContinuousRequests = DISABLE;
  hadc3.Init.EOCSelection = DISABLE;
  if (HAL_ADC_Init(&hadc3) != HAL_OK)
  {
    Error_Handler();
  }

    /**Configure for the selected ADC regular channel its corresponding rank in the sequencer and its sample time.
    */
  sConfig.Channel = ADC_CHANNEL_3;
  sConfig.Rank = 1;
  sConfig.SamplingTime = ADC_SAMPLETIME_3CYCLES;
  if (HAL_ADC_ConfigChannel(&hadc3, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }

}

/**
  * Enable DMA controller clock
  */
static void MX_DMA_Init(void)
{
  /* DMA controller clock enable */
  __HAL_RCC_DMA2_CLK_ENABLE();

  /* DMA interrupt init */
  /* DMA2_Stream0_IRQn interrupt configuration */
  HAL_NVIC_SetPriority(DMA2_Stream0_IRQn, 0, 0);
  HAL_NVIC_EnableIRQ(DMA2_Stream0_IRQn);

}

static void MX_GPIO_Init(void)
{

  GPIO_InitTypeDef GPIO_InitStruct;

  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOH_CLK_ENABLE();
  __HAL_RCC_GPIOA_CLK_ENABLE();

  /*Configure GPIO pin : PA0 */
  GPIO_InitStruct.Pin = GPIO_PIN_0;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @param  None
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler */
  /* User can add his own implementation to report the HAL error return state */
  while(1)
  {
  }
  /* USER CODE END Error_Handler */
}

A: This is the problem with HAL. It is extremely difficult to make it working in any more complex configuration. Try the bare registers, and you will get the control back, without need of reading those ridiculous libraries – PeterJ_01 Sep 8 '17 at 23:37

A: HAL_ADCEx_MultiModeStop_DMA sets state to HAL_ADC_STATE_ERROR_DMA because HAL_DMA_Abort function returns HAL_DMA_ERROR_NO_XFER. One possible solution is to clear this bit by calling CLEAR_BIT:
HAL_ADCEx_MultiModeStop_DMA(&hadc1);
CLEAR_BIT(hadc1.State, HAL_ADC_STATE_ERROR_DMA);


text:
Q: Visual Studio 2010 workaround to target .NET 4.5 Is there some workaround to target .NET 4.5 from Visual Studio 2010?
I know there is no official support for this, but still, I'm hoping somebody discovered some clever way to get around this.
I know you can install 4.5 as an in-place replacement for 4.0 and your solutions will work, but I want to specifically target 4.5.

A: I've been looking around for this for a while too. It seems there is no plausible workaround except to upgrade to Visual Studio 2012. I've created a VM with the Visual Studio 2012 development environment and have been working on that and Visual Studio 2010 in another.


text:
Q: how do I make an input form clickable? I have been given a problem to solve an issue. The task is to make the input form clickable. but I can't figure out what's going on in the code. It's the first time I'm seeing such code. Can somebody help me?

  <form class="android-frontpage screen" onclick="window.open('javascript:SubmitForm(%27form2%27)', '_self');" name="form2" action="form2" method="post">

Join our community to get early access.

Enter your email address

Get Started

Courses

Blogs

Our Story

Contact Us

Building Education Of The Future!

  </form>

A: First of all, The input isn't clickable because it isn't even an input. It's just a blank piece of text. So you could replace the text with a input box. Here, I made one based on your code.
<input class="text-2" type="email" placeholder="Enter your email address here">
You can remove the class and add it to the div or remove the entire div tag and just leave the class there. What ever works best for you.
Hope this helps!


text:
Q: jQuery / Colorbox - create a separate link to open the colorbox? I'm trying to open a jQuery Colorbox from a link outside the rest of the colorbox images. So, all of the examples look like this:

OK, that's fine, but I also need to open that colorbox from a separate link:
 this link should also open the colorbox

What do I have to put where to do that? All of the colorbox examples just show what's in the first code block, and I'm no jQuery expert.

A: Ah, figured it out! This works:
Change the first link to:

Then, set up our extra link like this:
ID . '\', open:true});">click here

A: Here's a similar thing that worked for my project.
HTML
//I "display:none" the images gallery to hide them...

 Grouped Photo 1
 Grouped Photo 2
 Grouped Photo 3

//...then when I click on this JPG image the group of images (above) appear in a colorbox

Here's the JQUERY
$(document).ready(function(){

     //when i "click" on the image with a class of "circle1" it opens the "example1" group
     $('.circle1').click(function() {
        $("a[rel='example1']").colorbox({open:true});
     });

});

A: This example works, but without next and previous selections:
http://jsfiddle.net/pd6JN/8/

A: Try this:
$(".link-to-click").click(function() {
   $("a.colorbox-link").colorbox({open:true, rel:'colorbox-class-group'});
});


text:
Q: Verilog - what is the difference in use between vertical bar (|) and "or" When should I use "|" and when should I use "or"? I have noticed that the condition in always blocks uses "or" such as:
always @ (posedge clk or posedge reset)

while in if statements you use "|" such as:
if (condition1 | condition2)

Why must we use different operators? What other cases use "|" or "or"?

A: | is a bitwise 'or' operator.
or is used in the sensitivity list as an item separator (v95). , can be used instead of 'or' in v2k and system verilog.
or can also be a gate name in structural verilog.
|| is a logical 'or' operation

A: There needs to be a way to distinguish between logical or (||), bitwise or (|) and event or or. The difference is clearer when you have signals A and B
wire [1:0] A,B;
always @(A | B) ... // waits for a change in the bit-wise result of A | B
always @(A || B) ... // waits for a change in the logical result of A | B
always @(A or B) ... // waits for a change either A's value or B value


text:
Q: Getting from series solutions of Airy's equation to the Airy functions Ai(x) and Bi(x) If I solve the Airy differential equation ($ {y'' - xy = 0}$) using the power series method, I get the following solution:
$y(x) = a_0 \left(1 + \frac{x^3}{6} + \frac{x^6}{180} + \cdots \right) + a_1 \left(x + \frac{x^4}{12} + \frac{x^7}{504} + \cdots \right)$
However, everywhere I research the Airy differential equation, I see answers in terms of $Ai(x)$ and $Bi(x)$, which are expressed using gamma functions and fractional powers of 3.
My question is how do we get from the series solution (where I am at) to $Ai(x)$ and $Bi(x)$?


text:
Q: Get Discord user ID from username If I have a user's Discord name and discriminator as a string (e.g ExampleUser#1234) how can I get their user ID from it? I've found get_user(id), but that returns a user object from an ID. I'm using Python and Discord.py.

A: As stated in this excellent answer by Sam Rockett (Finding a User ID by Discord Discrim via Python (1st ans) you can try this:
p = client.get_all_members()
found_members = filter(lambda m: m.discriminator==your_discrim, p)
member = discord.utils.get(found_members, name=your_username)
id = member.id

P.S. This snippet only works for finding members who share a server with the bot. To find users who do not share a server with the bot, you must have already an ID.

A: In one line just do
discord.utils.get(client.get_all_members(), name="ExampleUser", discriminator="1234").id

notice the .id at the end, that gives you the ID of that person.
Also for the discriminator part don't include the hash(#)

A: Discord Bots Hub
Hello Discord User
I will tell you the best way to do this. You have to search the member user and matching username with member user.
message.guild.members.find(m => m.user.username === 'USERNAME').user.id
https://thediscordbots.blogspot.com/2019/10/what-are-discord-bots-really-and-which.html


text:
Q: How to protect files with .htaccess and a login page? I'm hosting on my servers few files (like photos, music etc) that I don't want to be public. So I build a PHP form that asks for OTP, and if the code is correct, it shows "OK". It's not hard to prohibit the access to a PHP file, but how can I do it to any other file type?
For example, I want that when user enters to:
www.example.net/private.png

The .htaccess will go to:
www.example.net/access.php

Without the user knowing it, like AJAX.
If the file returns true, it shows the user the content in the www.example.net/private.png. if it returns him false, it'll show him the form in this URL:
www.example.net/login.php?url=private.png

After successful login, the PHP will redirect him to:
www.example.net/private.png

Again. Than all the process again, but now, because he is already logged in, www.example.net/access.php will return him true.
What should be written in the .htaccess file to do it?

A: To guard file access using PHP, put the files in a private directory not directly accessible to the web.
Create a PHP script to allow user login
login.php
<?PHP
session_start();

// { Write your own code to authenticate the user }

echo "
Logged in
";

// set this after user logs in successfully
$_SESSION['access_allowed'] = true;

?>

Create another PHP script to check if the user is logged in. If the user is logged in, read the requested file from your private directory and push it to the browser.
guard.php
<?PHP
session_start();

if(!isset($_SESSION['access_allowed'])){
    header("HTTP/1.0 401 Unauthorized"); // or redirect to the login page
    exit;
}

$private_dir = "/home/tester/guarded";
$filename = $private_dir.$_SERVER['PATH_INFO'];

if(!file_exists($filename)) {
    header("HTTP/1.0 404 Not Found");
    exit;
}

// $mime_type = "application/octet-stream";

// Finding MIME type using Fileinfo extension
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime_type = finfo_file($finfo, $filename);
finfo_close($finfo);

header('Content-Type: '.$mime_type);
header('Content-Disposition: inline; filename='.basename($filename));
header('Content-Length: ' . filesize($filename));
readfile($filename);
exit;
?>

When a logged user requests www.youserver.com/guard.php/image/secret.jpg he/she will be sent the image file: /home/tester/guarded/image/secret.jpg
Further Changes
Add this to your .htaccess file (make sure you have mod_rewrite enabled in your Apache web server)
.htaccess
RewriteEngine on
RewriteRule ^(video|music|image)/(.*)$ guard.php/$1/$2

If your music files are located in the music directory inside your private directory, only logged-in users can access song.mp3 at http://www.yourserver.com/music/song.mp3
Videos and images can be accessed similarly.


text:
Q: Positioning buttons under slideshow in CSS I am trying to re-position some navigation tools in CSS but anything I try doesn't work. Is there a way I could group it together and move it as a div?
I've tried adjusting the background properties and also playing with padding and margins of the individual tags. I'm not sure how else it can be done?
This is the code i'm working with:
#slides .slidesjs-navigation {
      margin-top:5px;
    }

    a.slidesjs-next,
    a.slidesjs-previous,
    a.slidesjs-play,
    a.slidesjs-stop {
      background-image: url(images/btns-next-prev.png);
      background-repeat: no-repeat;
      display:block;
      width:12px;
      height:18px;
      overflow: hidden;
      text-indent: -9999px;
      float: left;
      margin-right:5px;

    }

    a.slidesjs-next {
      margin-right:10px;
      background-position: -12px 0;

    }

    a:hover.slidesjs-next {
      background-position: -12px -18px;
    }

    a.slidesjs-previous {
      background-position: 0 0;
    }

    a:hover.slidesjs-previous {
      background-position: 0 -18px;
    }

    a.slidesjs-play {
      width:15px;
      background-position: -25px 0;
    }

    a:hover.slidesjs-play {
      background-position: -25px -18px;
    }

    a.slidesjs-stop {
      width:18px;
      background-position: -41px 0;
    }

    a:hover.slidesjs-stop {
      background-position: -41px -18px;
    }

It's sitting in the bottom of the page! I would like it to sit just beneath the slideshow of images! Any help would be great!


text:
Q: Pandas loc with prefix I have two data frames and I want for each line in one data frame to locate the matching line in the other data frame by a certain column (containing some id). I thought to go over the lines in the df1 and use the loc function to find the matching line in df2.
The problem is that some of the id's in df2 has some extra information except the id itself.
For example:
df1 has the id: 1234,
df2 has the id: 1234-KF
How can I locate this id for example with loc? Can loc somehow match only by prefixes?

A: Extra information can be removed using e.g. regular expression (or substring):
import pandas as pd
import re

df1 = pd.DataFrame({
    'id': ['123', '124', '125'],
    'data': ['A', 'B', 'C']
})

df2 = pd.DataFrame({
    'id': ['123-AA', '124-AA', '125-AA'],
    'data': ['1', '2', '3']
})

df2.loc[df2.id.apply(lambda s : re.sub("[^0-9]", "", s)) == df1.id]


text:
Q: How to invoke "done()" function in transformFile() after calling resizeImage()? I have a problem with DropzoneJS. It's about the method transformFile. I use this method to calculate MD5 and to generate a presigned upload URL to S3.
It works great when I don't have to resize the image, but when I have to do it, then Dropzone doesn't proceed with upload - it only generates MD5 and presigned URL. I know I should invoke done() function but I'm not sure how to do this in my case.
Here is my implementation:
transformFile: async function transformFile(file, done) {
    if ((this.options.resizeWidth || this.options.resizeHeight) && file.type.match(/image.*/)) {
      //return this.resizeImage(file, this.options.resizeWidth, this.options.resizeHeight, this.options.resizeMethod, done);
      return this.resizeImage(file, this.options.resizeWidth, this.options.resizeHeight, this.options.resizeMethod, async function (result) {
         file.md5 = await calculateMD5(result);
         file.presign = await initUpload(file.name, file.type, file.md5);
         return result;
       });
    } else {
      file.md5 = await calculateMD5(file);
      file.presign = await initUpload(file.name, file.type, file.md5);
      return done(file);
    }
  },

and here the original one from Dropzone:
transformFile: function transformFile(file, done) {
    if ((this.options.resizeWidth || this.options.resizeHeight) && file.type.match(/image.*/)) {
      return this.resizeImage(file, this.options.resizeWidth, this.options.resizeHeight, this.options.resizeMethod, done);
    } else {
      return done(file);
    }
  },

I specifically have to do it in this method or later, but I'm pretty sure this is the last possible moment for me to generate MD5 and presigned URL. Any help will be appreciated.

A:  transformFile: async function transformFile(file, done) {
    if ((this.options.resizeWidth || this.options.resizeHeight) && file.type.match(/image.*/)) {
      return this.resizeImage(file, this.options.resizeWidth, this.options.resizeHeight, this.options.resizeMethod, async function (result) {
         file.md5 = await calculateMD5(result);
         file.presign = await initUpload(file.name, file.type, file.md5);
         done(result);
       });
    } else {
      file.md5 = await calculateMD5(file);
      file.presign = await initUpload(file.name, file.type, file.md5);
      return done(file);
    }
  },


text:
Q: Force element to scroll when it is slightly off screen I need an element to scroll into the screen when it is partially out of it. I already have a function that is detecting whether or not it is within the viewport, but I would like to bring the element completely into the viewport using its size. Think of it as a square element which is half way in the viewport, I would like to scroll in a way that will bring that element completely in.
This may be off to the side or above or beneath the current viewport. How do I scroll the element into the viewport when it is detected to be out?
Here is the current code:
const $target = $(evt.target) // this is the current target which will be tested whether or not is outside of the viewport
if (isOutsideOfViewport($target)) {
      $target.scrollToBringTargetCompletelyToViewport() // how to make something like this work?
    }

Edit: to show in more details what I am trying to do, I have drawn the following diagram.
As you can see, the target is slightly outside of the viewport. The objective is to bring the target completely in the viewport.
Before:

After:

This would happen no matter where the target is on the screen, I just want to scroll just enough for it to be completely within the viewport.


text:
Q: Connect points with color from a scalar (Paraview)? I think my question is quite simple for Programmable filter users with Paraview, but I really have no idea how to do that.
I am trying to visualize the path of one particle with a line colored by a scalar.
(For example, I want to visualize the evolution of the temperature along the path of my particle.)
I have a data file with point coordinates (each line represents its evolution in time) and some scalars (like temperature, diameter) as input.
"x", "y", "z", "scalar1", "scalar2"
0, 0, 0, 300, 12.5
0, 12, 7, 302, 35.4

After converted that into Table Of Points, I used a Programmable Filter to connect the points (thanks to this subject : How to connect points in paraview?) :
pdi = self.GetPolyDataInput()
pdo =  self.GetPolyDataOutput()
numPoints = pdi.GetNumberOfPoints()
pdo.Allocate()
for i in range(0, numPoints-1):
   points = [i, i+1]
   # VTK_LINE is 3
   pdo.InsertNextCell(3, 2, points)

Now, I think I just have to add a command line to specify a color thanks to the scalar associated, but I don't know how to do that. Do you have any idea?
Thanks a lot.

A: In the Programmable Filter properties panel, turn on the checkbox for "Copy Arrays". That will pass the point data (i.e. the "scalar1" and "scalar2" fields) to the line output. You can then color the lines by these fields as you would any other field.


text:
Q: Sorted eigenvalues and eigenvectors on a grid I have a matrix at each point on a 3d grid. I need to calculated the eigen values and eigen vectors at each point and the sort them in ascending order of eigen value. I wrote the following test case below using python, I am able to sort the eigen value but the associated eigen vector is of larger dimension.
import numpy as np
from numpy import linalg as LA
n = 2
a = np.zeros((3,3,n,n,n))
a[:,:,0,0,0] = [[5,0,0],[0,1,0],[0,0,3]]
a[:,:,1,1,1] = [[2,0,0],[0,3,0],[0,0,1]]
eigvals,eigvecs = LA.eig(a.swapaxes(0, -1).swapaxes(1,-2))
ev = eigvals.swapaxes(0,-1)
evecs = eigvecs.swapaxes(0,-1).swapaxes(1,-2)
evo = np.sort(ev,axis=0)
print evo[:,0,0,0],evo[:,1,1,1]
print evecs[:,:,0,0,0]
print evecs[:,:,1,1,1]
eveco = evecs[np.argsort(ev,axis=0)]
print np.shape(eveco)
print eveco[:,0,0,0,:,0,0,0] # decided after knowing the shape
print eveco[:,1,1,1,:,0,0,0] # decided after knowing the shape

It gives right answers, but not right shape, shape of eveco should be (3,3,2,2,2):
[ 1.  3.  5.] [ 1.  2.  3.]
[[ 1.  0.  0.]
 [ 0.  1.  0.]
 [ 0.  0.  1.]]
[[ 1.  0.  0.]
 [ 0.  1.  0.]
 [ 0.  0.  1.]]
(3, 2, 2, 2, 3, 2, 2, 2)
[[ 0.  1.  0.]
 [ 0.  0.  1.]
 [ 1.  0.  0.]]
[[ 0.  0.  1.]
 [ 1.  0.  0.]
 [ 0.  1.  0.]]

A: How about this, it places an open grid on the non sorted dimensions preventing them from being duplicated (replace the last four lines of your code with the following).
eveco = evecs[(np.argsort(ev,axis=0)[:, None, ...],) + tuple(np.ogrid[:3,:n,:n,:n])]
print np.shape(eveco)
print eveco[:,:,0,0,0]
print eveco[:,:,1,1,1]

Output (of the new code only):
(3, 3, 2, 2, 2)
[[ 0.  1.  0.]
 [ 0.  0.  1.]
 [ 1.  0.  0.]]
[[ 0.  0.  1.]
 [ 1.  0.  0.]
 [ 0.  1.  0.]]


text:
Q: Cant figure out this error -> IndexError: list index out of range So i have been working on this code for a while and i cant fin a solution to this problem and i was wondering if anyone in here could help me solve this? The problem is supposed to be in the method "hent_celle" where it takes in a coordinate from a grid and returns the object that is in that position.
The error is:
Traceback (most recent call last):
File "/Users/cc/Documents/Python/Oblig8/rutenettto.py", line 105, in <module>
    print(testobjekt._sett_naboer(2,1))
File "/Users/cc/Documents/Python/Oblig8/rutenettto.py", line 64, in
    _sett_naboer nabo_u_kol = self.hent_celle(rad+1,kol)
File "/Users/cc/Documents/Python/Oblig8/rutenettto.py", line 43, in hent_celle
    return self._rutenett[rad][kol] IndexError: list index out of range

And the code is:
from random import randint
from celle import Celle

class Rutenett:
def init(self,rader,kolonner):
    self._ant_rader = int(rader)
    self._ant_kolonner = int(kolonner) self._rutenett = []

def _lag_tom_rad(self):
    liste = []
    for x in range(self._ant_kolonner):
        liste.append(None)
    return liste

def _lag_tomt_rutenett(self):
    liste2 = []
    for x in range(self._ant_rader):
        liste_ = self._lag_tom_rad()
        liste2.append(liste_)
    self._rutenett = liste2

def lag_celle(self,rad,kol):
    celle = Celle()
    tilfeldig_tall = randint(0,100)
    if tilfeldig_tall <= 33:
        celle.sett_levende()
        return celle
    else:
        return celle

def fyll_med_tilfeldige_celler(self):
    for x in self._rutenett:
        for y in x:
            rad = int(self._rutenett.index(x))
            kol = int(x.index(y))
            self._rutenett[rad][kol] = self.lag_celle(rad,kol)

def hent_celle(self,rad,kol):
    if rad > self._ant_rader or kol > self._ant_kolonner or rad < 0 or kol < 0:
        return None
    else:
        return self._rutenett[rad][kol]

def tegn_rutenett(self):
    for x in self._rutenett:
        for y in x:
            print(y.hent_status_tegn(), end="")

def hent_alle_celler(self):
    liste = []
    for x in self._rutenett:
        for y in x:
            liste.append(y)
    return liste

def _sett_naboer(self,rad,kol):
    cellen = self.hent_celle(rad,kol)
    # lik linje
    nabo_v_rad = self.hent_celle(rad,kol-1)
    nabo_h_rad = self.hent_celle(rad,kol+1)
    # under
    nabo_u_kol = self.hent_celle(rad+1,kol)
    nabo_u_kol_h = self.hent_celle(rad+1,kol+1)
    nabo_u_kol_v = self.hent_celle(rad+1,kol-1)
    # over
    nabo_o_kol = self.hent_celle(rad-1,kol)
    nabo_o_kol_h = self.hent_celle(rad-1,kol+1)
    nabo_o_kol_v = self.hent_celle(rad-1,kol-1)

    liste = [nabo_v_rad,nabo_h_rad,nabo_u_kol_h,nabo_u_kol_v,nabo_o_kol,nabo_o_kol_h,nabo_o_kol_v]
    #print(liste)
    #print(nabo_o_kol_h)

    for x in liste:
        if x == None:
            pass
        else:
            cellen._naboer.append(x)
    return cellen._naboer

def antall_levende(self):
    teller = 0
    for x in self._rutenett:
        for y in x:
            if y._status == "doed":
                pass
            else:
                teller +=1
    return teller

testobjekt = Rutenett(3,3)
testobjekt._lag_tomt_rutenett()
testobjekt.fyll_med_tilfeldige_celler()
print(testobjekt._sett_naboer(2,1))

I just cant figure out why the list index is out of range

A: Pyhton list indexes start at 0, which means a list with 10 elements will use indices 0-9. Assuming self._ant_rader and self._ant_kolonner are the number of rows and columns, then rad and kol would need to be less than those values and cannot be the same value, or you get an index out of bounds error.
Fixed version of the method:
def hent_celle(self,rad,kol):
    if rad >= self._ant_rader or kol >= self._ant_kolonner or rad < 0 or kol < 0:
        return None
    else:
        return self._rutenett[rad][kol]

As you can see, the > has been replaced with >= instead. This means indices which are out of bounds will return None.


text:
Q: A Comma Here Or Not?
That's what this struggle, this isolation, this retreat is all about.

Should there be a comma after this retreat?
In the state above, it looks to me as if this struggle and this isolation are modifying this retreat, which isn't the sense of the sentence.
I was thinking that putting a comma after this retreat would make everything that follows this struggle to become enclosed in bracketing commas instead.
Is that the effect of adding the comma? And how are the commas currently functioning? They don't appear to be bracketing commas to me.

A:

*

*1.) That's what this struggle, this isolation, this retreat is all about.

ON FIRST BLUSH: Yes, it does seem that a comma is missing in that example; and that your analysis looks solid to me.
The commas in the example seem to be bracketing commas, where they are bracketing supplements which have the appearance of having the form of an appositional construction. That is: there are two expressions -- "this isolation" and "this retreat" -- that are supposed to be supplements (whose ultimate anchor is the expression "this struggle"), but the last expression is missing its ending bracketing comma.
It seems that your example sentence ought to be punctuated as you suggested, for the reasons that you suggested. That is,

*

*2.) That's what this struggle, this isolation, this retreat, is all about.

BUT . . . see below
EDITED-TO-ADD:
On second thought, there is another possibility. Having read the comments to the OP's main post, it now dawns on me that the three expressions could be in the form of an asyndetic "AND" coordination. That is, the original sentence has the meaning of:

*

*3.) That's what this struggle and this isolation and this retreat is all about.

And if that was what the author wanted as their interpretation, than the original punctuation of version #1 is, er, appropriate. But as this thread has demonstrated, the author's choice of punctuating this sentence seems to perhaps not been the best choice after all.
At the moment, I'm thinking that the author probably did mean to have the interpretation of version #3, for when I was analyzing version #2 earlier, its reading didn't quite seem right to me -- it seemed a bit weak -- and I thought the author would've tweaked it to make it stronger.
So, my current answer is that the original punctuation of version #1 is what was intended by the author -- the commas as used are for asyndetic "AND" coordination (and are not used for bracketing supplements).


text:
Q: Symfony 4: how to add users to database by admin user? I start using Symfony 4 framework. It will be a system where users should be added inside application by admin user (so without registration).
Could you suggest me how to do it, which bundle, class or which approach to use?
Also I do not want to build separate admin panel app. There will be one intranet system, where user with admin role should be able to add other users.

A: Symfony is a framework that can be used to build your admin on your own or you can use the SonataAdmin Bundle which is very often used to build Admin-Panels from existing Entities.

A: You can generate the login functionality using the amazing Symfony MakerBundle, as documented here.
As Stony provided, there is the SonataAdminBundle which you can use. You can also check into EasyAdminBundle, which also generates admin tables based on your entities. EasyAdmin is somewhat a simplistic version of SonataAdmin and the configuration is quite easy to use.

A: You can review your task as a simple persist of some entity (User entity) into the database. First of all you need to design your authorization\authentication strategy. I strongly recommend you to read this security documentation
After you create your User entity you can implement your own CRUD system or use admin bundles like EasyAdminBundle or SonataAdminBundle. If you want to create some api application, you can also review Api Platform