Q: Unable to resolve dependency tree after upgrading node, failing on node-sass After upgrading Node to the latest version, I start getting these error messages when I tried npm audit fix --force. It seems like I'm unable to fix my dependency tree issues. I've tried to search for solutions to this error extensively and tried many different solutions but none worked. Should the only solution be downgrading back to an older Node version?
npm ERR! path /Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-sass
npm ERR! command failed
npm ERR! command sh -c node scripts/build.js
npm ERR! Building: /usr/local/bin/node /Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-gyp/bin/node-gyp.js rebuild --verbose --libsass_ext= --libsass_cflags= --libsass_ldflags= --libsass_library=
npm ERR! gyp info it worked if it ends with ok
npm ERR! gyp verb cli [
npm ERR! gyp verb cli   '/usr/local/bin/node',
npm ERR! gyp verb cli   '/Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-gyp/bin/node-gyp.js',
npm ERR! gyp verb cli   'rebuild',
npm ERR! gyp verb cli   '--verbose',
npm ERR! gyp verb cli   '--libsass_ext=',
npm ERR! gyp verb cli   '--libsass_cflags=',
npm ERR! gyp verb cli   '--libsass_ldflags=',
npm ERR! gyp verb cli   '--libsass_library='
npm ERR! gyp verb cli ]
npm ERR! gyp info using node-gyp@3.7.0
npm ERR! gyp info using node@16.13.0 | darwin | x64
npm ERR! gyp verb command rebuild []
npm ERR! gyp verb command clean []
npm ERR! gyp verb clean removing "build" directory
npm ERR! gyp verb command configure []
npm ERR! gyp verb check python checking for Python executable "python2" in the PATH
npm ERR! gyp verb `which` succeeded python2 /usr/bin/python2
npm ERR! gyp verb check python version `/usr/bin/python2 -c "import platform; print(platform.python_version());"` returned: "2.7.16\n"
npm ERR! gyp verb get node dir no --target version specified, falling back to host node version: 16.13.0
npm ERR! gyp verb command install [ '16.13.0' ]
npm ERR! gyp verb install input version string "16.13.0"
npm ERR! gyp verb install installing version: 16.13.0
npm ERR! gyp verb install --ensure was passed, so won't reinstall if already installed
npm ERR! gyp verb install version is already installed, need to check "installVersion"
npm ERR! gyp verb got "installVersion" 9
npm ERR! gyp verb needs "installVersion" 9
npm ERR! gyp verb install version is good
npm ERR! gyp verb get node dir target node version installed: 16.13.0
npm ERR! gyp verb build dir attempting to create "build" dir: /Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-sass/build
npm ERR! gyp verb build dir "build" dir needed to be created? /Users/Mac/Desktop/Projects/folder/Website/filder/node_modules/node-sass/build
npm ERR! gyp verb build/config.gypi creating config file
npm ERR! gyp verb build/config.gypi writing out config file: /Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-sass/build/config.gypi
npm ERR! (node:19391) [DEP0150] DeprecationWarning: Setting process.config is deprecated. In the future the property will be read-only.
npm ERR! (Use `node --trace-deprecation ...` to show where the warning was created)
npm ERR! gyp verb config.gypi checking for gypi file: /Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-sass/config.gypi
npm ERR! gyp verb common.gypi checking for gypi file: /Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-sass/common.gypi
npm ERR! gyp verb gyp gyp format was not specified; forcing "make"
npm ERR! gyp info spawn /usr/bin/python2
npm ERR! gyp info spawn args [
npm ERR! gyp info spawn args   '/Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-gyp/gyp/gyp_main.py',
npm ERR! gyp info spawn args   'binding.gyp',
npm ERR! gyp info spawn args   '-f',
npm ERR! gyp info spawn args   'make',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   '/Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-sass/build/config.gypi',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   '/Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-gyp/addon.gypi',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   '/Users/Mac/.node-gyp/16.13.0/include/node/common.gypi',
npm ERR! gyp info spawn args   '-Dlibrary=shared_library',
npm ERR! gyp info spawn args   '-Dvisibility=default',
npm ERR! gyp info spawn args   '-Dnode_root_dir=/Users/Mac/.node-gyp/16.13.0',
npm ERR! gyp info spawn args   '-Dnode_gyp_dir=/Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-gyp',
npm ERR! gyp info spawn args   '-Dnode_lib_file=/Users/Mac/.node-gyp/16.13.0/<(target_arch)/node.lib',
npm ERR! gyp info spawn args   '-Dmodule_root_dir=/Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-sass',
npm ERR! gyp info spawn args   '-Dnode_engine=v8',
npm ERR! gyp info spawn args   '--depth=.',
npm ERR! gyp info spawn args   '--no-parallel',
npm ERR! gyp info spawn args   '--generator-output',
npm ERR! gyp info spawn args   'build',
npm ERR! gyp info spawn args   '-Goutput_dir=.'
npm ERR! gyp info spawn args ]
npm ERR! No receipt for 'com.apple.pkg.CLTools_Executables' found at '/'.
npm ERR!
npm ERR! No receipt for 'com.apple.pkg.DeveloperToolsCLILeo' found at '/'.
npm ERR!
npm ERR! No receipt for 'com.apple.pkg.DeveloperToolsCLI' found at '/'.
npm ERR!
npm ERR! gyp: No Xcode or CLT version detected!
npm ERR! gyp ERR! configure error
npm ERR! gyp ERR! stack Error: `gyp` failed with exit code: 1
npm ERR! gyp ERR! stack     at ChildProcess.onCpExit (/Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-gyp/lib/configure.js:345:16)
npm ERR! gyp ERR! stack     at ChildProcess.emit (node:events:390:28)
npm ERR! gyp ERR! stack     at Process.ChildProcess._handle.onexit (node:internal/child_process:290:12)
npm ERR! gyp ERR! System Darwin 19.6.0
npm ERR! gyp ERR! command "/usr/local/bin/node" "/Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-gyp/bin/node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="
npm ERR! gyp ERR! cwd /Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-sass
npm ERR! gyp ERR! node -v v16.13.0
npm ERR! gyp ERR! node-gyp -v v3.7.0
npm ERR! gyp ERR! not ok
npm ERR! Build failed with error code: 1

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/Mac/.npm/_logs/2021-11-24T18_21_54_491Z-debug.log

A: First solution
Make sure your nodejs version is not superior than the latest stable one. For that you can use n package from npm:
npm install -g n
n stable
# if one of the commands does not pass, you may need to use sudo
sudo npm install -g n
sudo n stable

Then you would wanna use sass package instead of node-sass, as it's deprecated. And for that run those commands:
npm uninstall node-sass --save
npm install sass --save

Second solution
If you need or want node-sass for some reasons, you should downgrade your nodejs version to like v14. For that you can use n package from npm:
npm install -g n
n 14
# if one of the commands does not pass, you may need to use sudo
sudo npm install -g n
sudo n 14

A: I got rid of everything and re-installed Xcode, Node and node-sass again, and the issue is resolved.


Q: Uninstall a Component in vue.js I installed this component in my application. I would like to uninstall it now. How can I do that ?


Q: Angular Material unit tests - Failed to find MatHarness element I am writing unit tests for my app which uses Angular Material.
I wanna make sure that there's a material card in the page. For this, I use the following code:
  let loader: HarnessLoader;
  let component: LoginComponent;
  let fixture: ComponentFixture<LoginComponent>;
  let authService: jasmine.SpyObj<AuthService>;

  beforeEach(async () => {
    authService = jasmine.createSpyObj<AuthService>(['authenticate', 'logout']);
    await TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [LoginComponent],
      providers: [{ provide: AuthService, useValue: authService }]
    })
      .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(LoginComponent);
    loader = TestbedHarnessEnvironment.loader(fixture);
    fixture.detectChanges();
  });

   it('should display a material card', async () => {
    const card = await loader.getHarness(MatCardHarness);
    expect(card).toBeTruthy();
  });

But, this returns the error:
Error: Failed to find element matching one of the following queries:
        (MatCardHarness with host element matching selector: ".mat-card")

Here's my HTML:
<mat-card class="custom-class">

Sign In

</mat-card>

I'll be able to solve this by adding mat-card class to the <mat-card> element. But isn't it supposed to work without manually adding the class? Is there anything wrong with the way I set up my tests?

A: Try importing MatCardModule into you TestBed configuration.
import { MatCardModule } from '@angular/material/card';

beforeEach(async () => {
  await TestBed.configureTestingModule({
    imports: [
      RouterTestingModule,
      MatCardModule,
    ],
    declarations: [LoginComponent],
    providers: [{ provide: AuthService, useValue: authService }]
  }).compileComponents();
});


Q: What is the technology most commonly used for iPhone - iPad communications? What is the most commonly used technology for communicating between an application running on an iPad and one on an iPhone?  For example, the famous Scrabble application uses device-to-device communication to host the game board on the iPad and the letters on the iPhone.

A: Bluetooth P2P connection.
Check that


Q: How to open/run YML compose file? How can I open/run a YML compose file on my computer? I've installed Docker for Windows and Docker tools but couldn't figure out how.

A: If you are asking how to open YAML files, then you can use some common editors like NotePad++ in windows or vim in linux.
If your question is about running the compose yaml file, then run this command from the directory where compose file is residing:
docker-compose -f {compose file name} up

You can avoid -f if your filename is docker-compose.yml

A: To manage .yml files you have to install and use Docker Compose.
Installation instructions can be found here: https://docs.docker.com/compose/install/
After the installation, go to your docker-compose.yml directory and then execute docker-compose up to create and start services in your docker-compose.yml file.
If you need more information, take a look to Docker Compose docs: https://docs.docker.com/compose


Q: How can my Spring integration tests create their own schema based on the model in a HSQL database? Writting some integration tests in Spring (Like in this question) I will like to avoid the work of a big script to create all tables in HSQL:

<jdbc:script location="classpath:createSchema.sql" />

As Spring is creating and updating my development tables from the model automagically. How could I tell Spring to do the same things for my integration tests?
My datasource file is
<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns=          "http://www.springframework.org/schema/beans"
    xmlns:xsi=      "http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context=  "http://www.springframework.org/schema/context"
    xmlns:jee=      "http://www.springframework.org/schema/jee"
    xmlns:p=        "http://www.springframework.org/schema/p"
    xmlns:jdbc=     "http://www.springframework.org/schema/jdbc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context               http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jee                   http://www.springframework.org/schema/jee/spring-jee.xsd
        http://www.springframework.org/schema/jdbc                  http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd">

    <!-- Usamos HSQLDB para hacer las pruebas con in-memory db -->
    <jdbc:embedded-database id="dataSource" type="HSQL">
        <jdbc:script location="classpath:create_schema.sql"/>
        <jdbc:script location="classpath:import.sql"/>
    </jdbc:embedded-database>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan" value="com.myProject.model" />
        <property name="hibernateProperties">
        <props>
            <prop key="hibernate.default_schema">TESTING</prop>
            <prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
            <prop key="hibernate.hbm2ddl.auto">create-drop</prop>
            <prop key="hibernate.show_sql">true</prop>
        </props>
        </property>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
</beans>

Update: After NimChimpsky answer I had included the schema name in hibernate properties and created a script with just:
CREATE SCHEMA TESTING

After trying the first insert int the import.sql script I see:
org.hsqldb.hsqlexception user lacks privilege or object not found [MyTable]

A: You still need to create schema manually - but literally only the create schema my-schema-name statement, let hibernate create the tables
<jdbc:embedded-database id="dataSource" type="HSQL">
  <jdbc:script location="classpath:create_schema.sql"/>
</jdbc:embedded-database>

If populating the database with values is a problem, yeah it is. No shortcuts really.
And the import script will have to run after the tables are created, in a postconstruct method probably.

A: I solved the issue with the help of geoand comment. (Thanks, you should have posted it as an answer). But let me share more information to make future reader's life easier.
First. It seems that telling that you have an script to initializa database makes hibernate to avoid the creation proccess. I changed the code embedded elemento to:
<jdbc:embedded-database id="dataSource" type="HSQL"/>

Hibernate will automatically execute import.sql from the classpath (at least in Create or Create-Drop mode) so there was no need to indicate further scripts.  As Spring test framework does rollback the transaction you do no need to restore the database after each test.
Second, I had some problems with my context configuration that needed to be solved if I wanted Spring to create my schema. The best way to do it was to set the ignore failures attribute to "ALL" and look and the logs.
Third. Using HSQL for a few things MySQL for others has its own issues. Syntax is sometimes different and I had to fix my import.sql to become compatible with both databases.
Appart from that, it works:
@ContextConfiguration(locations={"file:src/test/resources/beans-datasource.xml",
                     "file:src/main/webapp/WEB-INF/applicationContext.xml",
                                 "file:src/main/webapp/WEB-INF/my-servlet.xml"})
        @Configuration
        @RunWith(SpringJUnit4ClassRunner.class)
        public static class fooTest{

            @Inject BeanInterface myBean;

            @Test
            @Transactional
            public void fooGetListTest(){

                assertTrue("Expected a non-empty list", myBean.getList().size() > 0 );
            }
        }
    }


Q: Ajax call include not works in Wordpress I have a PHP file that I call with Cron Job and I need it separately from the rest of code. So, I have a button that call AJAX request from my dashboard. The Ajax function in my Wordpress plugin includes the file (process.php), this in turn, includes another file (snippets.php).
If I call process.php directly, it works perfectly, but not from Ajax call.
Folder structure
plugin.php
plugin.js
snippets.php
processes/process.php

plugin.js
jQuery.ajax({
type: 'GET',
url: ajaxurl,
data : {
action : 'process',
}
})

plugin.php
function process(){
include_once( 'processes/process.php' );
}
add_action( 'wp_ajax_process', 'process' );

process.php
include_once('../snippets.php')
//here not includes 'snippets.php'

A: You should use relative includes from their own file, otherwise, it will run from the current path. To force this you can use __DIR__  and start with a slash
plugin.php
function process(){
include_once(__DIR__.'/processes/process.php' );
}
add_action('wp_ajax_process', 'process' );

process.php
include_once(__DIR__.'/../snippets.php');
//here not includes 'snippets.php'

Also, you forgot the semicolumn ; in process.php


Q: Unit tests for a custom Date Serializer I have recently started writing tests in Java and I am having some problem with the tests for the following class. How to write correctly tests for TestDateTimeSerializer class in such a form.
public class TestDateTimeSerializer extends JsonSerializer<LocalDateTime> {
    public static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

    @Override
    public void serialize(LocalDateTime dt, JsonGenerator gen, SerializerProvider serializerProvider) throws IOException {
        if (dt == null) {
            gen.writeNull();
        } else {
            gen.writeString(dt.format(FORMATTER));
        }
    }
}

this class is used here
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonFormat(with = JsonFormat.Feature.ACCEPT_CASE_INSENSITIVE_PROPERTIES)
public class TestRequest implements ITestResponse {
    @JsonProperty("TestID")
    private Long testID;
    @JsonSerialize(using = TestDateTimeSerializer.class)
    private LocalDateTime lastUpdateDate;
}

A: Make JsonGenerator as mock object, then verify its method call.
@ExtendWith(MockitoExtension.class)
class TestDateTimeSerializerTest {
    @Mock
    JsonGenerator generator;       // JsonGenerator is mock
    @Mock
    SerializerProvider provider;

    @Test
    void test() throws IOException {
        TestDateTimeSerializer serializer = new TestDateTimeSerializer();
        LocalDateTime now = LocalDateTime.now();

        // run your method
        serializer.serialize(now, generator, provider);

        // assert mocked generator's method call
        verify(generator).writeString(ArgumentMatchers.anyString());
    }
}

Mockito API doc : https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#1
you can find more example and usage.

A: Please try this:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.junit.Before;
import org.junit.Test;

import java.time.LocalDateTime;

import static java.time.format.DateTimeFormatter.ISO_LOCAL_DATE_TIME;
import static org.junit.Assert.*;

public class TestDateTimeSerializerSerializerTest {

        private ObjectMapper mapper;
        protected TestDateTimeSerializer serializer;

        @Before
        public void setup() {
            mapper = new ObjectMapper();
            serializer = new TestDateTimeSerializer();

            SimpleModule module = new SimpleModule();
            module.addSerializer(LocalDateTime.class, serializer);
            mapper.registerModule(module);
        }

        @Test
        public void testSerializeNonNull() throws JsonProcessingException {
            LocalDateTime ldt = LocalDateTime.parse("2016-10-06T10:40:21.124", ISO_LOCAL_DATE_TIME);

            String serialized = mapper.writeValueAsString(ldt);

            assertEquals("equal strings", "\"2016-10-06T10:40:21.124Z\"", serialized);
        }

        @Test
        public void testSerializeNull() throws JsonProcessingException {
            LocalDateTime ldt = null;

            String serialized = mapper.writeValueAsString(ldt);

            assertEquals("equal strings", "null", serialized);
        }

    }


Q: Access nested model attributes I have following setup:
class EmpsController < ApplicationController
  def new
    @emp = Emp.new
    @unit_options = Unit.all.collect{|unit| [unit.name, unit.id] }
  end

  def create
    @emp = Emp.new(emp_params)
    @emp.save!
    redirect_to :action => :list
  end

  def destroy
    @emp = Emp.find([:id])
    @emp.destroy
    redirect_to :action => :list
  end

  def list
    @emps = Emp.all
  end

  def emp_params
    params.require(:emp).permit(:name, :unit_id)
  end

 end

Model:
class Emp < ApplicationRecord
    has_one :units
    accepts_nested_attributes_for :units
end

Form:

 List of Employees:

<% @emps.each do |u| %>

<%= u.id %>	 <%= u.name %>	  <%= u.unit_id %>	   <%= link_to "Delete", u, :method => :delete %>

<% end %>

All I want to do is to print (in table above) unit attribute called :name related with Emp printed Emp object.
Found various related solution but they do not apply to my case.

A: First, don't use :units as the association name, it "has one unit" no "units", Rails convention over configuration expects the association to be singular.
Then you should be able to do some_emp.unit.name.
Or you can use method delegation:
class Emp < ApplicationRecord
  has_one :unit

  delegate :name, to: :unit
end

And now you can do some_emp.name.


Q: What is the Java equivalent of Objective-C's NSDictionary? What is the closest implementation of Objective-C's NSDictionary in Java?  To me, it looks like HashMap<String, Object>, but I'm very new to Objective-C.
Thanks

A: NSDictionary is a class cluster (see the "Class Cluster" section in The Cocoa Fundamentals Guide), meaning that the actual implementation is hidden from you, the API user. In fact, the Foundation framework will choose the appropriate implementation at run time based on amount of data etc. In addition, NSDictionary can take any id as a key, not just NSString (of course, the -hash of the key object must be constant).
Thus, closest analog is probably Map<Object,Object>.

A: For practical usage:
HashMap<String, Object> would be the way to go for a simple, non-parallel dictionary.
However, if you need something that is thread-safe (atomic), you'd have to use
HashTable<String, Object>
which is thread safe, but - notably - does not accept null as a valid value or key.

A: I'm admittedly an Android newbie, but to me ContentValues seems to be the closest thing to NSDictionary.


Q: Indexing lists of list/vectors Data
lst <- list(1, 1:3, 2:4)
ind <- c(1, 2, 2)

Problem
I can guarantee that length(ind) == length(lst) and now I want to get the 1st element of the the first element of lst, then the second element of the second element and finally the second element of the third element.
With a loop I could do something like
sapply(seq_along(ind), function(i) lst[[i]][[ind[i]]])

So my question is whether I need the loop or is there any smart indexing technique which I am not aware of? Background of the question is that I have the impression that I do not make best use of R's  capability to do incredible stuff with smart indexing (like indexing a matrix with another matrix).

A: We can use mapply to get the corresponding element of 'lst' based on the index in 'ind'.
mapply(`[`, lst, ind)
#[1] 1 2 3


Q: $elemMatch projection in node.js dbo.collection("users")
            .findOne({email: emailGiven, "friends.email": element.email},
                     { friends: { $elemMatch: { email: element.email } } },
                     function(errT, resultT) {})

I have the query above in node.js but for some reason the query's elemMatch part doesn't work on node.js but when I execute  the same query in mongo terminal it works, so I'm thinking maybe node.js doesn't support $elemMatch? If this is the case, could anyone tell me what would be the equivalent of this query in node.js?
Sample data from my DB:
/* 4 */
{
    "_id" : ObjectId("5ad20cef8248544860ce3dc1"),
    "username" : "test",
    "email": "",
    "fullName" : "",
    "friends" : [{email: "",
                 status :""}],
    "alarms": [ {"id":111,
        "title": "TITLE",
        "location": "",
        "startTime": "10-10-1996 10:18:00",
        "endTime": "10-10-1996 10:18:00" }, {},{}

    ],
     "pnumber" : ""
}

A: The node.js driver findOne has a different call signature than the findOne in the MongoDB shell. You pass the field selection object as the projection element of the options parameter:
dbo.collection("users")
    .findOne({"friends.email": email},
             {projection: { friends: { $elemMatch: { email: email } } } },
             function(errT, resultT) {...});

A: If you want to find for any values which is stored in some variable, you use regex for that. Your query should look like
dbo.collection("users").findOne({
    email: new RegExp(emailGiven, 'i'),
    "friends.email": new RegExp(element.email, 'i')
}, {
    friends: {
        $elemMatch: {
            email: new RegExp(element.email, 'i')
        }
    }
}, function(errT, resultT) {})

i is for case insensitive comparison here


Q: Nested list with TAL I'm using Chameleon in the Pyramids Framework and want to repeat nested list while rendering the template.
My minimized HTML-Code is:
1. <ul>
2.  <li tal:repeat="item items">
3.      <input tal:attributes="id item.id; onclick item.url">
4.      <label tal:repeat="premise item.values" tal:attributes="for item.id; id premise.id">
5.          <label tal:replace="premise.title"/>
6.      </label>
7.      <label tal:attributes="for item.id" tal:content="item.title"/>
8.  </li>
9. </ul>

Whereby I got the following json-Data
[{
    'url': 'location.href="http://..."',
    'values':
    [{
        'id': '70',
        'title': 'some title 1'
    }],
    'attitude': 'justify',
    'id': '68',
    'title': 'some title 2'
}, {
    'url': 'null',
    'values':
    [{
        'id': '0',
        'title': 'some title 3!
    }],
    'attitude': 'justify',
    'id': '0',
    'title':
    'some title 4'
}]

If I kill HTML-lines 4.-6., everything is fine, otherwise Pyramid/Chameleon throws:
  File "/usr/local/lib/python3.4/dist-packages/chameleon/tal.py", line 471, in __call__
    iterable = list(iterable) if iterable is not None else ()
TypeError: 'builtin_function_or_method' object is not iterable

Anyone some idea?

A: Thanks to #pyramid in the IRC i got the first hint, which is mentioned in the comment. But..never ever name a key 'value' or 'values'!


Q: Angular JS - Date changes when submitting to $http - Timezone issue I am having a strange problem where a Date changes when it is passed to API through $http.put, I suspect a timezone issue:
Datepicker triggers ng-change event - console.log:
Tue Jun 10 2014 00:00:00 GMT+0100 (GMT Summer Time)
Passed to API using Angular $http.put...
When it hits Fiddler:
StartDate=2014-06-09T23:00:00.000Z
As you can see the date changes from 10th June to 9th June.
How can I stop this change of date? Is it the timezone causing the change? Both the API and client side are running on Localhost.
Further to this:
When the field is clicked a second time and the datepicker launched / date selected, this second time the problem does not appear:
Console.log:
Wed Aug 06 2014 22:00:00 GMT+0100 (GMT Summer Time)
Fiddler data received:
StartDate=2014-08-06T21:00:00.000Z

A: I think it is a TZ issue, b/c the difference between your GMT+0100 and your StartDate=2014-06-09T23:00:00.000Z is 5 hours.
.
The issue:
Your local time is currently BST (British Summer Time) equivalent to GMT +1
This is going to be the default time when you make your API call.
However, the API was written by Google in California, and they are rather egocentric.  Therefore, they're automatically converting the time since you're not providing any date formatting "instructions".
In other words, Chrome does the conversion for you nicely when you print to the console.log(), but when you make your $http.put, Angular, without explicit formatting for you, makes the call using it's default TZ (which is PST)
.
Resolution
You need to force the date formatting to your locale.

*

*Angular template
{{ date_expression | date : 'yyyy-MM-dd HH:mm:ss'}}

*In JavaScript
$filter('date')(date, 'yyyy-MM-dd HH:mm:ss')

*using localization
<html>
  <head>
    <title>My Angular page</title>
    <script src="angular-locale_en-uk.js"></script>
    ...
  </head>
  <body>
    ...
  </body>
</html>


Q: Lotus Notes - Column view as Totals: Total showing not 0.00 even if there aren't no docs saved I have a view which contains a column ( as Total ) . Even, there aren't any docs created, the column shows:
165.65 ( as total ) and not 0.00 ( as it should be )
Any suggestions?

A: Does the view show documents in a response hierarchy? Probably there is an "orphaned" response (Replication conflict or other reason) that is not shown in the view as the parent document is missing, but still is counted in the total- column. Try disable response- hierarchy in the View- Properties and check if there is such a document.
An additional reason for the total not being 0 could also be a document that is protected by a readers- field. Server will add this document to the totals (as View- Index is created by the server) whereas the Designer / User does not see the document.
If you know, what is in the Readers- Field (Role, GroupName, etc.) then make yourself member of that field (by assigning the Role to yourself or add yourself to the group).
If you don't know, what's in there (or something went wrong filling the readers field, e.g. forgot to tick the "multi value"- property), then you need somebody with "Full Access Administration"- right to the server. This Admin- function ovverrides all Reader- fields and makes the document visible to you.


Q: Adding another variable information or adding weight into stat_density_2d Below is a simple code to produce stat_density_2d plot of X~Y.
plot_data <-
  data.frame(X = c(rnorm(300, 3, 2.5), rnorm(150, 7, 2)),
             Y = c(rnorm(300, 6, 2.5), rnorm(150, 2, 2)),
             Z = c(rnorm(300, 60, 5), rnorm(150, 40, 5)),
             Label = c(rep('A', 300), rep('B', 150)))
ggplot(plot_data, aes(x=X, y=Y)) +
  stat_density_2d(geom = "polygon", aes(alpha = stat(level), fill = Label))

As I understand, the density is based on the count of X~Y. My question is can I use Z as the density? Or perhaps, add Z as weight to the density? I'm not sure I'm making sense here. As it is the density of X~Y is useful for me. But I'm just wondering if I can add the information in Z into the density of X~Y.
Perhaps you have alternative idea? Both the density of X~Y and Z are information that I want to convey. Currently I'm separating them into separate density X~Y, X~Z, Y~Z, and they're all useful to me (using my data of course).
Edit2, Manual Calculation Plan:
I'm still working on this as I go. This is a general idea of what I'm planning to do.

*

*Instead of using stat_density_2d, I plan to calculate the density itself using the method used in stat_density_2d, which is MASS::kde2d().

*I would then use interpolation such as akima::interp, to interpolate the Z into X~Y grid.

*I would then multiply Z unto the density of X~Y (from 1) as a form of weightage.

*Plot them again using ggplot.

Edit 3: Update with code of applying Z as weightage towards density of X~Y.
library(ggplot2)
library(data.table)
library(ggnewscale)
library(akima)
library(MASS)

plot_data <-
  data.frame(X = c(rnorm(300, 3, 2.5), rnorm(150, 7, 2)),
             Y = c(rnorm(300, 6, 2.5), rnorm(150, 2, 2)),
             Z = c(rnorm(300, 60, 5), rnorm(150, 60, 5)),
             Label = c(rep('A', 300), rep('B', 150)))
setDT(plot_data)

#Interpolation of Z into X~Y grid for Label A
int_plot_data_A=with(plot_data[Label=="A"],interp(x=X,y=Y,z=Z,nx=100,ny=100))
rownames(int_plot_data_A$z)=int_plot_data_A$x
colnames(int_plot_data_A$z)=int_plot_data_A$y
plot_data_Z_A <- melt(int_plot_data_A$z)
names(plot_data_Z_A) <- c("X", "Y", "Z")

#Calculation of kde2d for Label A
plot_data_A=plot_data[Label=="A"]
kde2d_A=kde2d(plot_data_A$X,plot_data_A$Y,n=100)
rownames(kde2d_A$z)=kde2d_A$x
colnames(kde2d_A$z)=kde2d_A$y
plot_kde_A <- melt(kde2d_A$z, na.rm = TRUE)
names(plot_kde_A) <- c("X", "Y", "Z")

#Interpolation of Z into X~Y grid for Label B
int_plot_data_B=with(plot_data[Label=="B"],interp(x=X,y=Y,z=Z,nx=100,ny=100))
rownames(int_plot_data_B$z)=int_plot_data_B$x
colnames(int_plot_data_B$z)=int_plot_data_B$y
plot_data_Z_B <- melt(int_plot_data_B$z)
names(plot_data_Z_B) <- c("X", "Y", "Z")

#Calculation of kde2d for Label B
plot_data_B=plot_data[Label=="B"]
kde2d_B=kde2d(plot_data_B$X,plot_data_B$Y,n=100)
rownames(kde2d_B$z)=kde2d_B$x
colnames(kde2d_B$z)=kde2d_B$y
plot_kde_B <- melt(kde2d_B$z, na.rm = TRUE)
names(plot_kde_B) <- c("X", "Y", "Z")

#Filtering out values under 0.01. It makes the plot better. This is subjective
setDT(plot_kde_A)
plot_kde_A[Z<0.01]=NA
setDT(plot_kde_B)
plot_kde_B[Z<0.01]=NA

#Calculate for A weighted with Z
plot_kde_A_Weight_Z=plot_kde_A
plot_kde_A_Weight_Z$Z=plot_kde_A_Weight_Z$Z*plot_data_Z_A$Z

#Calculate for B weighted with Z
plot_kde_B_Weight_Z=plot_kde_B
plot_kde_B_Weight_Z$Z=plot_kde_B_Weight_Z$Z*plot_data_Z_B$Z

ggplot() +
  geom_contour_fill(data=plot_kde_A,aes(x=X,y=Y,z=Z),alpha=0.8,bins=10) +
  scale_fill_continuous(low = "white", high = "blue") +
  geom_contour(data=plot_kde_A_Weight_Z,aes(x=X,y=Y,z=Z),bins=10) +
  new_scale_fill() +
  geom_contour_fill(data=plot_kde_B,aes(x=X,y=Y,z=Z),alpha=0.8,bins=10) +
  scale_fill_continuous(low = "white", high = "red") +
  geom_contour(data=plot_kde_B_Weight_Z,aes(x=X,y=Y,z=Z),color="red",bins=10)

Edit 1: After searching around while dropping keyword ggplot, I found something called kernel density estimation And this post, Plot contours of distribution on all three axes in 3D plot, feels like this is what I'm looking for to visualise my data. Unfortunately, I found out that ggplot does not have 3D functionality. There's a 4 years package called gg3D? plotly seems to be the best candidate for this? The final figure in the post looks like what I'm trying to achieve.


Q: How to target specific Cucumber runner classes or feature files within Jenkins? Is it possible to target specific runner classes or feature files within Jenkins?
Let's say for example I have the following files.
Runner classes:
RunnerClass1.java
RunnerClass1.java

Feature Files:
Login.feature
SignUp.feature

Is there a way to trigger specific runner classes or feature files within the Jenkins UI, I know you can use specific plugins such as: 'Parameterised / String Parameters', has anyone else found a solution to target specific tests from Jenkins?
thanks for your help

A: You can tag your test cases and maven will be able to run them by these tags.
For example, When I have Login cases with @Login tags and I want to run them with Maven, I am using the following terminal script :
mvn clean test -Dcucumber.options="--tags @Login"


Q: How to revoke Users Access On Schema in Azure SQL? I have a requirement where I need to revoke users access on a particular schema as we will be purging that schema and its table in future.
Currently, the process followed to create Schema and grant access is like below,

*

*Create Schema

*Create DB Role

*Create Azure AD Group on azure portal

*Create DB User with the same name as AD group

*Then, we run EXEC sp_addrolemember command to add DB user to DB role in database.

*Finally, we run the Grant command to give permission (Select, Insert etc) on Schema to DB Role.

Now, whenever any new user need access to that schema we simply add him in the Azure AD group and he is able to see and access that schema.
However, when I Revoke the access of user by removing him from Azure AD group he is still able to see that Schema.
As I am not an expert in SQL so I am not sure what am I missing in order to revoke his access.
I also tried Revoke command like below but still the user is able to see the schema.
REVOKE SELECT ON SCHEMA :: Schema_Name TO [DB Role]
Am I missing anything, can anyone please let me know the right steps to revoke user access so that they should not be able to see that schema anymore or should not be able to run any command on that schema not even select command?

A: Then, in addition to remove it from the AD group, try to deny permissions on the schema:
DENY SELECT,VIEW DEFINITION On SCHEMA::Schema_Name To [user_name]


Q: PopBackStack previous last fragment and check which fragment it is I got a few fragments in MainActivity which can be selected from Navigation Drawer. Now, whenever users press a profile button, it will jumps to UserProfile Fragment. If home button is pressed, it will pop back the last fragment. Since I've assigned each of the fragments a specific backstack name i.e .addToBackStack("abc"), how can I check what is the last fragment by using popBackStack() method ?

A: To get the last fragment:
FragmentManager fm = getSupportFragmentManager();
int lastFragEntry = fm.getBackStackEntryCount()-1;
String lastFragTag = fm.getBackStackEntryAt(lastFragEntry).getName();

Log.i("Last Fragment Tag->", lastFragTag);

NB: If you want to get the name/tag of last fragment, you also have to use the same Tag during fragment transaction:
ft.replace(android.R.id.container, fragment, "abc");
ft.addToBackStack("abc");

Hope this helps.


Q: How to convert mathematical expressions into C statement? How to convert each of the following mathematical expressions to its equivalent statement in C?

*

*1 / (x^2 + y^2)

*square root of (b^2 - 4ac)

A: *

*1.0 / (pow(x,2) + pow(y,2))

*sqrt(pow(b,2) - 4*a*c)
See pow() and sqrt() functions manual.
You can also write x*x instead of pow(x, 2). Both will have the exact same result and performance (the compiler knows what the pow function does and how to optimize it).

(For commenters)
GCC outputs the exact same assembler code for both of these functions:
double pow2_a(double x) {
    return pow(x, 2);
}

double pow2_b(double x) {
    return x * X;
}

Assembler:
    fldl    4(%esp)
    fmul    %st(0), %st
    ret


Q: Best way to join 3 lists and count how many times an ID is in the list using linq Looking for some help with this problem i'm trying to work through to learn how linq works.
My thinking was to join the person and customer list on personID to get the name for the customers and then join the customer and sale lists on customerID and then count the customerID in sale to get the amount of sales by the customer that were from the online store.
Task: Determine which people have placed the most orders from our online store
public class Person
{
    public int PersonID { get; set; }
    public string PersonType { get; set; }
    public bool NameStyle { get; set; }
    public string Title { get; set; }
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string LastName { get; set; }
    public string Suffix { get; set; }
}

public class Sale
{
    public int SalesOrderId { get; set; }
    public int RevisionNumber { get; set; }
    public DateTime OrderDate { get; set; }
    public DateTime DueDate { get; set; }
    public DateTime? ShipDate { get; set; }
    public bool IsOnlineOrder { get; set; }
    public int CustomerId { get; set; }
    public int? SalesPersonId { get; set; }
    public int? TerritoryID { get; set; }
    public decimal SubTotal { get; set; }
    public decimal TaxAmt { get; set; }
    public decimal Freight { get; set; }
    public decimal TotalDue { get; set; }
}

public class Customer
{
    //CustomerID can belong to a store or a person
    public int CustomerID { get; set; }
    public int? StoreID { get; set; }
    public int? PersonID { get; set; }
    public int? TerritoryID { get; set; }
    public string AccountNumber { get; set; }
}

    public void MostOrders()
    {
        List<Person> per = Data.GetAllPersons();
        List<Sale> sale = Data.GetAllSales();
        List<Customer> cus = Data.GetAllCustomers();

        var join = (from x in per
                    join y in cus
                    on x.PersonID equals y.PersonID
                    join t in sale
                    on y.CustomerID equals t.CustomerId
                    select new
                    {
                        ......
                    });
    }

A: I would create a class that will hold gather all "store entities" and their sales, i think that using a collection of this class (StoreEntity in my example) it will be much easier to perform a variety of data manipulation (for this task and in future tasks).
here is my suggestion:
public class StoreEntity
{
    Person PersonEntity { get; set; }
    Customer CustomerEntity { get; set; }
    List<Sale> SalesList { get; set; }

    public StoreEntity(Person p, Customer c,List<Sale> sales)
    {
        this.PersonEntity = p;
        this.CustomerEntity = c;
        this.SalesList = sales;
    }

    public int SalesCount
    {
        get
        {
            if (SalesList == null)
            {
                return 0;
            }
            else
            {
                return SalesList.Count;
            }
        }
    }
}

public List<StoreEntity> Entities { get; set; }
public void MostOrders()
{
    List<Person> per = Data.GetAllPersons();
    List<Sale> sale = Data.GetAllSales();
    List<Customer> cus = Data.GetAllCustomers();

    Entities = new List<StoreEntity>();
    foreach (Person p in per)
    {
        var cust = cus.Where(x => x.PersonID == p.PersonID).Select(x => x).SingleOrDefault();
        if (cust != null)
        {
            var sales = sale.Where(x => x.CustomerId == cust.CustomerID).ToList();
            StoreEntity entity = new StoreEntity(p, cust, sales);
            Entities.Add(entity);
        }
    }

    // now you have list of all entities with their sales
    // it will be musch easy to manipulate with linq
    // you can do this:
    Entities = Entities.OrderBy(x => x.SalesCount).ToList();
    // or this...
    var bestEntity = Entities.Max(x => x.SalesCount);
}


Q: Status of RFD groups and $C^*$-algebras Motivated by this question and its great answers, I become very curious to know what do we know about RFD (residually finite dimensional) groups and $C^*$-algebras, e.g. do we know how these properties behave under various constructions (amalgamated product etc.). Are there some survey articles on these topics?


Q: SQL SELECT 3 consecutive records with the same value I want to select 3 consecutive (by year) records with same value from 'participation' table (name, year) :
Name    Year
-------------
Carol   1999
Carol   2000
Carol   2001
Carol   2002
Faith   1996
John    2001
John    2002
John    2003
John    2009
Lyla    1994
Lyla    1996
Lyla    1997

Here is my initial code :
SELECT DISTINCT p1.name, p1.year
FROM participatition p1,
     participatition p2
WHERE (p1.year = p2.year + 1 OR p1.year = p2.year - 1) AND p1.name = p2.name
ORDER BY p1.name, p1.year

which returns ALL consecutive records but I only want records which meet 3 consecutive criteria, ie not Lyla:
Name    Year
-------------
Carol   1999
Carol   2000
Carol   2001
Carol   2002
John    2001
John    2002
John    2003
Lyla    1996
Lyla    1997

Is it possible to build on my code, eg add an extra criterion, to refine the selection without implementing the row_number() method?
I would like the following output:
Name
Carol
John
ie all records if there are at least 3 consecutive

A: Consider it as a gaps-and-islands problem and use the following trick to group consecutive rows together:
WITH cte1 AS (
    SELECT *, Year - ROW_NUMBER() OVER (PARTITION BY Name ORDER BY Year) AS grp
    FROM t
), cte2 AS (
    SELECT *, COUNT(*) OVER (PARTITION BY Name, grp) AS grp_count
    FROM cte1
)
SELECT *
FROM cte2
WHERE grp_count >= 3
ORDER BY Name, Year

If you look at the values in grp column you will find the pattern.
db<>fiddle

A: If there are no duplicate years for each Name, you need LEAD() window function to check for the 2nd next row.
If the year in that row is equal to the current year + 2 then this means that for this Name there are 3 consecutive years:
WITH cte AS (
  SELECT *, LEAD(Year, 2) OVER (PARTITION BY Name ORDER BY Year) next_next
  FROM participatition
)
SELECT DISTINCT p.*
FROM participatition p INNER JOIN cte c
ON p.Name = c.Name AND p.Year BETWEEN c.Year AND c.next_next
WHERE c.next_next = c.Year + 2;

See the demo.

A: I would simply use lead():
select distinct name
from (select p.*,
             lead(year, 2) over (partition by name order by year) as year_2
      from participation p
     ) p
where year_2 = year + 2;

For each row, this looks at the row two ahead for the same name ordered by year.  If that row is the current year plus 2, then you have three years in a row.

A: There may be a more elegant way. But, well, this is what I've come up with:
select name, year
from
(
  select
    name, year,
    case when lag(year, 2) over (partition by name order by year) = year - 2 then 1 else 0 end +
    case when lag(year, 1) over (partition by name order by year) = year - 1 then 1 else 0 end +
    case when lead(year, 1) over (partition by name order by year) = year + 1 then 1 else 0 end +
    case when lead(year, 2) over (partition by name order by year) = year + 2 then 1 else 0 end +
    1 as consecutive_rows
  from participatition
) analyzed
where consecutive_rows >= 3
order by name, year;

If the table participatition can contain multiple rows for one name and year, add DISTINCT to the subquery (aka derived table).

A: WITH CTE AS (
    SELECT name
         , year-lag(year,2) OVER(PARTITION BY name ORDER BY year ASC) as two_years_ago
    FROM t
)
SELECT name, two_years_ago
FROM cte
WHERE two_years_ago=2

A: You can solve this using row pattern matching if you're using Oracle Database:
with rws as (
  select 'Carol' nm, 1999 yr from dual union all
  select 'Carol' nm, 2000 yr from dual union all
  select 'Carol' nm, 2001 yr from dual union all
  select 'Carol' nm, 2002 yr from dual union all
  select 'Faith' nm, 1996 yr from dual union all
  select 'John' nm, 2001 yr from dual union all
  select 'John' nm, 2002 yr from dual union all
  select 'John' nm, 2003 yr from dual union all
  select 'John' nm, 2009 yr from dual union all
  select 'Lyla' nm, 1994 yr from dual union all
  select 'Lyla' nm, 1996 yr from dual union all
  select 'Lyla' nm, 1997 yr from dual
)
  select * from rws match_recognize (
    partition by nm
    order by yr
    all rows per match
    pattern ( init cons{2} )
    define
      cons as yr = prev ( yr ) + 1
  );

NM            YR
Carol       1999
Carol       2000
Carol       2001
John        2001
John        2002
John        2003

A: Adding to my initial code Group By and Having clause as below builds on the existing code (which filtered all consecutive name, year) :
SELECT DISTINCT p1.name
  FROM participatition p1, participatition p2
  WHERE (p1.year = p2.year+1 OR p1.year = p2.year-1) AND p1.name = p2.name
  GROUP BY p1.name
  HAVING COUNT(p1.name) > 2
  ORDER BY p1.name, p1.year

Thanks for all the answers - I never realised there was so many alternative solutions which has opened my eyes.

A: I have updated my code based on feedback (distinct, inner join, etc) from @ThorstenKettner using PSQL this time
SELECT p1.name
  FROM participation p1
  JOIN participation p2 ON p1.name = p2.name
  WHERE (p1.year = p2.year+1 OR p1.year = p2.year-1)
  GROUP BY p1.name
  HAVING COUNT(p1.name) > 2
  ORDER BY p1.name

This seems to work fine, is easy to understand and less complex. However I would like to test all solutions so I may apply such instead to suit new requirements. So thank you all for your generous help. Esp. Danke TK!


Q: Cython: Compiling and Cannot Find Library Mac OSX 10.12 I am just getting started with Cython and am trying to compile a "Hello World" script. I am trying to use gcc -Os /User/Documents/Python/Test\ Python/helloCopy.c -I/Library/Frameworks/Python.framework/Versions/3.5/include/python3.5m -l, but I don't know what to add after the -l. Other forum pages say to "include -lpython2.7 (or whatever version of Python you're using) on the linker command-line" but that produces ld: library not found for -lpython3.5
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Should I be directing the -l to a particular folder?

A: I do not know what resource you're using, but this does not say anything about a -l flag. It suggests

cython -a helloCopy.pyx

This creates a yourmod.c file, and the -a switch produces an annotated html file of the source code. Pass the -h flag for a complete list of supported flags.
gcc -shared -pthread -fPIC -fwrapv -O2 -Wall -fno-strict-aliasing -I/usr/include/python2.7 -o helloCopy.so helloCopy.c

(Linux)
On macOS I would try to compile with
gcc -I/usr/bin/python -o helloCopy.so helloCopy.c

to use the standard version of Python.


Q: plotly layout - Y Axis range not working i am trying to create a graph that will show a Scatter of the times i opened my computer. - i am using plotly offline.
Y  = time,
X  = date.
this works fine, but i can't make the Y axis to show all the hours of the day, but only the range of times that was in the data.
(for example, if i opened my computer only between 13:00-15:00 every day, the range of the Y axis will be from 13:00 to 15:00 only)
i am trying to show all the hours of the day on the Y axis by using the 'range' attribute in the layout, but it still doesn't work for me.
an example of my code:
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
from plotly.graph_objs import *
from datetime import datetime, time

init_notebook_mode(connected=True)

# in the example i am using fabricated data. declaring the data:
time_data = [datetime(2017, 07, 28, 21, 37, 19), datetime(2017, 07, 29, 17, 11, 56), datetime(2017, 08, 01, 11, 15, 45), datetime(2017, 08, 02, 13, 54, 03)]
x_data = []
y_data = []

# creating the x-row data with dates only, and the y-row data with the time only
for row in time_data:
    x_data.append(row.date())
    y_data.append(datetime.combine(datetime(2017, 1, 1).date(), row.time))

#declaring the data for the graph
data = [Scatter(x=x_data, y=y_data, name='Times On', mode='markers')]

# creating the hour range
hours = []
for i in range (0, 24):
    hours.append(datetime(2017, 1, 1, i, 0, 0))

# declaring the Layout with the 'range' attribute, and Figure
layout = dict(title='Times On', xaxis=dict(type='date'), yaxis={'type': 'date', 'tickformat': '%H:%M', 'range': hours})
fig = Figure(data=data, layout=layout)

# plotting
plot(figure_or_data=fig, filename='C:\Users\tototo\Desktop\Time-On')

does someone know what's the problem? any help would be blessed!
Thanks!

A: plotly seems to limit the axis based on the max and min values present in the corresponding axis. I tried each of the properties and came up with a solution.
Approach: The first one is generating what you need, but cant seem to get it to start at 12 in the midnight and end at 12 the next day.
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
from plotly.graph_objs import *
from datetime import datetime, time

init_notebook_mode(connected=True)

# in the example i am using fabricated data. declaring the data:
time_data = [datetime(2017, 7, 28, 21, 37, 19), datetime(2017, 7, 29, 17, 11, 56), datetime(2017,8, 1, 11, 15, 45), datetime(2017, 8, 2, 13, 54, 3)]
x_data = []
y_data = []

# creating the x-row data with dates only, and the y-row data with the time only
for row in time_data:
    x_data.append(row.date())
    y_data.append(str(datetime.combine(datetime(2017, 1, 1).date(), row.time())))

#declaring the data for the graph
data = [Scatter(x=x_data, y=y_data, name='Times On', mode='markers')]

# creating the hour range
hours = []
for i in range (0, 24):
    hours.append(datetime(2017, 1, 1, i, 0, 0))

# declaring the Layout with the 'range' attribute, and Figure
layout = dict(title='Times On', xaxis=dict(type='date'), yaxis={'type': 'date', 'tickformat': '%H:%M',
                                                                'nticks': 30, 'tick0': hours[0],
                                                                'range': [hours[0], hours[len(hours)-1]],
                                                                'autorange': False})
fig = Figure(data=data, layout=layout)

# plotting
iplot(figure_or_data=fig)

The above code is giving me the output:


Q: how to replace the first column of a tab delimited file 690070  690070  A
690451  690451  B
690571  690571  C
690578  690578  D
690637  690637  F

How can I replace the first column values with a sequential number, starting from 1...n. So it becomes:
1  690070  A
2  690451  B
3  690571  C
4  690578  D
5  690637  F

Can this be done in Vim or some linux command?

A: You can use awk or vim macro.
awk is really great for such text manipulation
awk '{count++; print count " " $2 " "$3;}'  data.stat > /tmp/data.stat && mv /tmp/data.stat data.stat

A: in Vim:
:let i=1 | g/^[^/\t]*\t/s//\= i. "\t"/ | let i=i+1

Reference
Update
For splitting the first two columns and saving into another file,
I recommend using awk as in Tomáš Šíma's answer, specifically:
awk '{print $1 "\t" $2;}'  data.stat > newfilename.txt
If you want to to do everything in Vim:

*

*Copy the current file to a new one

:w newfilename.txt

*

*Open the newly copied file:

:o newfilename.txt

*

*Split the first two columns of the rest of the line:

:%s/^\([^\t]*\)\t\([^\t]*\).*$/\1\t\2/g

*

*Save your edits of course

:w newfilename.txt


Q: HTTP 302 "Moved Temporarily" Error While we are getting latest project from TFS2013, we are facing below error.

PS: We are using proxy in our network.
Thank you in advance

A: I faced with the same problem before and when I add my ip adress to proxy then try again to do Get latest in TFS. Its worked!!!. Have a nice coding :)


Q: Account and Physical Thermostat I signed up for a developer account using the same account that I have my home thermostat on. I'm getting an error in the Home Simulator saying that a mix of physical and virtual devices is dangerous.
Do I have to create a separate account to be my developer account or can I just remove my physical thermostat from the Home Simulator? I don't want to remove my thermostat from my account though since I use that to manage my thermostat.

A: Yes, it is a good idea to create a separate account.
Quote from https://developer.nest.com/documentation/cloud/home-simulator
"This Home Simulator is intended to be used with virtual devices for testing purposes. We strongly suggest that you create a separate account for testing and add virtual devices to it via the Home Simulator."


Q: Is it possible to use the letter keys to access programs on Windows 8.1 Metro, like in XP? For those who remember (or still use) Windows XP, you might remember that you could launch the start bar with your Windows key on your keyboard and then hit the letter of the program/folder/file you wanted and as long as there wasn't another program/folder/file on the start bar starting with the same letter, it'd launch right away.
e.g. If you wanted to open excel, you'd hit the windows key and press the letter "e" and excel would launch.
So, for those who do remember that feature, I'm wondering, is there any way to get that functionality back in Windows 8.1? Right now, what happens is that when you hit the windows key, Metro pops up (which is fine) but if you type "e", for example, windows will automatically start searching instead of just launching Excel (or whatever letter you've typed).
I'd rather keep the interface as it is and, if possible, prefer not to install any 3rd party software (unless there's no other go). My preference is to be able to utilize the OS to get that option (if available), even if that includes going through regedit.
Just a note, I am already aware that 8.1 and XP are completely different architectures and I also realize that automatic searching does have its benefits but I prefer that specific XP functionality so it'd be great if I could get it back in 8.1.
Thanks in advance for your help.

A: This isn't the exact thing that I'm looking for but I've found somewhat of a workaround. You can create global keyboard shortcuts and thereby circumvent the metro/start screen altogether.
To do so, create a shortcut of the program/folder/file you want to easily access (the shortcut can be placed anywhere). Then, go to the properties of the shortcut and go to the shortcut tab where you can enter a global shortcut key (about half way down the box).
Of course, there are limitations to this because there are only a few keys (key combinations) free that you can use globally whereas with the XP method I was looking for, you could essentially have up to 36 different items you can access with just two keystrokes (26 letters, 10 numbers - not sure if other characters worked).
If anyone has figured out the XP method, though, that would be great.


Q: Get all records that do not have an empty field Posts have many Comments. Each Comment optionally belongs to a User.
How can I get all comments for Post 1 that HAVE a user?
Comments

content                           post_id    user_id
-------                           -------    -------
There is no user for this post.   1
This is an example with a user.   1          123
Another example with a user.      1          8321

Things I've tried:
This returns no records
@comments = Post.find(1).comments.where(:user_id != nil)
These return every record:
@comments = Post.find(1).comments.where("user_id IS NOT NULL")

@comments = Post.find(1).comments.where("user_id <> 0")

When I print out the user_ids on the page, it looks like the nil ones are being read as "0", but are still null in the db.

A: It looks you have blank user_id column when comments doesn't have user. So the correct query should be
@post = Post.find(1)
@comments = @post.comments.where("user_id != ''")

A: I'd do this:
#app/models/post.rb
class Post < ActiveRecord::Base
   has_many :comments do
      def no_user
         where.not(user_id: "") #-> http://robots.thoughtbot.com/activerecords-wherenot
      end
   end
end

#app/models/comment.rb
class Comment < ActiveRecord::Base
   belongs_to :post
end

This will allow me to call:
#app/controllers/comments_controller.rb
class CommentsController < ApplicationController
  def show
     @post = Post.find params[:post_id]
     @comments = @post.comments.no_user
  end
end

--
Notes on Null
Having null is a specific data-type in your database
We use it when wanting to "default" populate a table's columns - allowing you to submit no data, having the database be as efficient as possible in providing the right allocations of data.
I would certainly look up about the NULL data type with the likes of MYSQL & PGSQL. This will give you the ability to define any unpopulated data columns as NULL - allowing you to call the NOT NULL command.
Currently, your "non defined" data is just blank - not null

A: My code might not represent a standard way but it would work in both cases(Null and blank).
@post = Post.find(1)
@comments = @post.comments.where("user_id > 0")


Q: Is there a way to use a PCF spring cloud config server from a client outside the PCF? We have a few spring-boot micro-services  running on PCF for which we have the PCF cloud config server for serving the configurations for various profile/environments. These micro-services are bound to the config server and all are managed by the PCF infrastructure. We have a few services running on Virtual Machines which are not managed by PCF. Is it possible to serve the resources from the same PCF config server to the services running on the VM which is not managed by PCF?

A: Atlast, this is what I had to do to connect an external service from VM to connect to the PCF managed Config Server.

When the profile property was not set to 'dev' in the bootstrap.yml, the profile was set to 'default' which triggered a login prompt even though I had a relaxed security config in place. I still don't know if this is a best practice. But, once I set the profile property as 'dev', I was able to consume the resouces seamlessly.


Q: Finding general solution of first order Given $\frac{\mathrm{d}y}{\mathrm{d}x}=xe^{-2y}$, find a general solution that satisfies $y(0)=2$. My steps are:
$$
\int\frac{\mathrm{d}y}{e^{-2y}}=\int x \mathrm{d}x \implies \ln e^{2y}=x^2 + C \implies y= \frac{\ln(x^2 + C)}{2}.
$$
Then $y(0)=2$ gives
$$
4 = \ln(0 + C) \implies e^4 = C,
$$
so that
$$
y=\frac{\ln{(x^2+e^4)}}{2}.
$$
Is this right?

A: $\int \frac{1}{e^{-2y}} dy =\int x dx$
$\int e^{2y} dy=\int x dx$
$\frac{1}{2} e^{2y}=\frac{x^2}{2}+C$

A: Yes that's correct
$$\int\frac{dy}{e^{-2y}}=\int x dx \implies \int{e^{2y}}dy=\int x dx$$
$$\frac {e^{2y}}2=\frac {x^2}2+K \implies e^{2y}=x^2+C$$
$$ y(0)=2 \implies C=e^4$$
$$y(x)=\frac {\ln |x^2+e^4|}2$$


Q: Android's InputMethodService keyEventCode won't work I'm trying to create my keyboard, and now am at the place when the pressed button should send the letter to the application.
In the examples I found
InputMethodService.sendDownUpKeyEvents(keyEventCode);

But couldn't really figure out, what should go into keyEventCode?
For example, how do I send a letter "A" ?
edit: Just one more thing, here ( http://developer.android.com/reference/android/view/KeyEvent.html ) I can find only codes for english character. How do I get other unicode characters?
Thanks!

A: That function takes the constants from the KeyEvent class.
To send a, use
sendDownUpKeyEvents(KeyEvent.KEYCODE_A);


Q: The instance member "..."' can't be accessed in an initializer I am trying to create a simple flutter project for learning. I need to delete the selected student  -Photo- but at the beginning I assigned the StudentList private so setState() function is not working when I try to delete. How can I assign StudentList as global.
This is the code I wrote at the beginning:
class _MyAppState extends State<MyApp> {

  StudentManager ChoosedStudent = new StudentManager.WithId(0, "", "", 0, "");
  StudentManager student1 = new StudentManager.WithId(1, "Name1", "LastName1",
      22, "https://uifaces.co/our-content/donated/hvaUVob5.jpg");
  StudentManager student2 = new StudentManager.WithId(2, "Name2", "LastName2",
      70, "https://uifaces.co/our-content/donated/eqUZLcBO.jpg");
  StudentManager student3 = new StudentManager.WithId(3, "Name3", "LastName3",
      55, "https://uifaces.co/our-content/donated/-oe25tWA.png");
  StudentManager student4 = new StudentManager.WithId(
      4,
      "Name4",
      "LastName4",
      99,
      "https://images.generated.photos/ukvWCGJJF8xoZ_rvVSFDLnQ-WDkGw2WsZ53uPPm63M8/rs:fit:512:512/Z3M6Ly9nZW5lcmF0/ZWQtcGhvdG9zLzA3/OTI0MTAuanBn.jpg");
  StudentManager student5 = new StudentManager.WithId(
      5, "Name5", "LastName5", 45, "https://thispersondoesnotexist.com/image");

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text("Student Exam Result System"),
      ),
      body: bodyBuilder(context),

    );

  }

  bodyBuilder(BuildContext context) {
    List<StudentManager> StudentList = [
      student1,
      student2,
      student3,
      student4,
      student5
    ];
    return Column(
      children: [
        Expanded(
            child: ListView.builder(
                itemCount: StudentList.length,
                itemBuilder: (BuildContext context, int index) {
                  if (StudentList[index].Grade >= 50) {
                    StudentList[index].IsPassed = true;
                  } else if (StudentList[index].Grade < 50) {
                    StudentList[index].IsPassed = false;
                  }
                  return ListTile(
                    leading: CircleAvatar(
                      backgroundImage:
                          NetworkImage(StudentList[index].PhotoURL),
                    ),
                    title: Text(StudentList[index].Name +
                        " " +
                        StudentList[index].Surname),
                    subtitle: Text(
                        "${StudentList[index].Name} named students grade is "
                        "${StudentList[index].Grade}, ${StudentList[index].AlphebaticalGrade}"),
                    isThreeLine: true,
                    trailing: buildStatusIcon(StudentList[index].IsPassed),
                    onTap: () {
                      setState(() {
                        ChoosedStudent = StudentList[index];
                      });
                    },
                  );
                })),

I want to assign StudentList like this:
    class _MyAppState extends State<MyApp> {

      StudentManager ChoosedStudent = new StudentManager.WithId(0, "", "", 0, "");
      StudentManager student1 = new StudentManager.WithId(1, "Name1", "LastName1",
          22, "https://uifaces.co/our-content/donated/hvaUVob5.jpg");
      StudentManager student2 = new StudentManager.WithId(2, "Name2", "LastName2",
          70, "https://uifaces.co/our-content/donated/eqUZLcBO.jpg");
      StudentManager student3 = new StudentManager.WithId(3, "Name3", "LastName3",
          55, "https://uifaces.co/our-content/donated/-oe25tWA.png");
      StudentManager student4 = new StudentManager.WithId(
          4,
          "Name4",
          "LastName4",
          99,
          "https://images.generated.photos/ukvWCGJJF8xoZ_rvVSFDLnQ-WDkGw2WsZ53uPPm63M8/rs:fit:512:512/Z3M6Ly9nZW5lcmF0/ZWQtcGhvdG9zLzA3/OTI0MTAuanBn.jpg");
      StudentManager student5 = new StudentManager.WithId(
          5, "Name5", "LastName5", 45, "https://thispersondoesnotexist.com/image");
      List<StudentManager> StudentList = [
        student1,
        student2,
        student3,
        student4,
        student5
    ];

but this is throwing "The instance member "..."' can't be accessed in an initializer." Error. is there any other way to assign StudentList globally and what is the reason of the error?
Full version of the code if it's neccesary:
import 'dart:ffi';

import 'package:by_myself/models/students.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(home: MyApp()));
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  StudentManager ChoosedStudent = new StudentManager.WithId(0, "", "", 0, "");
  StudentManager student1 = new StudentManager.WithId(1, "Name1", "LastName1",
      22, "https://uifaces.co/our-content/donated/hvaUVob5.jpg");
  StudentManager student2 = new StudentManager.WithId(2, "Name2", "LastName2",
      70, "https://uifaces.co/our-content/donated/eqUZLcBO.jpg");
  StudentManager student3 = new StudentManager.WithId(3, "Name3", "LastName3",
      55, "https://uifaces.co/our-content/donated/-oe25tWA.png");
  StudentManager student4 = new StudentManager.WithId(
      4,
      "Name4",
      "LastName4",
      99,
      "https://images.generated.photos/ukvWCGJJF8xoZ_rvVSFDLnQ-WDkGw2WsZ53uPPm63M8/rs:fit:512:512/Z3M6Ly9nZW5lcmF0/ZWQtcGhvdG9zLzA3/OTI0MTAuanBn.jpg");
  StudentManager student5 = new StudentManager.WithId(
      5, "Name5", "LastName5", 45, "https://thispersondoesnotexist.com/image");

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text("Student Exam Result System"),
      ),
      body: bodyBuilder(context),

    );

  }

  bodyBuilder(BuildContext context) {
    List<StudentManager> StudentList = [
      student1,
      student2,
      student3,
      student4,
      student5
    ];
    return Column(
      children: [
        Expanded(
            child: ListView.builder(
                itemCount: StudentList.length,
                itemBuilder: (BuildContext context, int index) {
                  if (StudentList[index].Grade >= 50) {
                    StudentList[index].IsPassed = true;
                  } else if (StudentList[index].Grade < 50) {
                    StudentList[index].IsPassed = false;
                  }
                  return ListTile(
                    leading: CircleAvatar(
                      backgroundImage:
                          NetworkImage(StudentList[index].PhotoURL),
                    ),
                    title: Text(StudentList[index].Name +
                        " " +
                        StudentList[index].Surname),
                    subtitle: Text(
                        "${StudentList[index].Name} named students grade is "
                        "${StudentList[index].Grade}, ${StudentList[index].AlphebaticalGrade}"),
                    isThreeLine: true,
                    trailing: buildStatusIcon(StudentList[index].IsPassed),
                    onTap: () {
                      setState(() {
                        ChoosedStudent = StudentList[index];
                      });
                    },
                  );
                })),
        Text("Student: " + ChoosedStudent.Name),
        Center(
          child: Row(
            children: [
              Flexible(
                fit: FlexFit.tight,
                flex: 1,
                child: RaisedButton(
                  onPressed: () {},
                  color: Colors.blueAccent,
                  textColor: Colors.white,
                  child: Row(
                    children: [
                      SizedBox(
                        width: 16.0,
                      ),
                      Icon(Icons.add),
                      Text("Add"),
                    ],
                  ),
                ),
              ),
              Flexible(
                fit: FlexFit.tight,
                flex: 1,
                child: RaisedButton(
                  onPressed: () {},
                  color: Colors.blueAccent,
                  textColor: Colors.white,
                  child: Row(
                    children: [
                      SizedBox(
                        width: 16.0,
                      ),
                      Icon(Icons.update),
                      Text("Update"),
                    ],
                  ),
                ),
              ), //KAY
              Flexible(
                fit: FlexFit.tight,
                flex: 1,
                child: RaisedButton(
                  onPressed: () {
                    setState(() {
                      StudentList.remove(ChoosedStudent);
                      print(StudentList);
                    });
                  },
                  color: Colors.blueAccent,
                  textColor: Colors.white,
                  child: Row(
                    children: [
                      SizedBox(
                        width: 16.0,
                      ),
                      Icon(Icons.delete),
                      Text("Delete"),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }
}

Widget buildStatusIcon(bool IsPassed) {
  if (IsPassed == true) {
    return Icon(Icons.done);
  } else if (IsPassed == false) {
    return Icon(Icons.warning);
  } else {
    return Icon(Icons.error);
  }
}


Q: android activity without graphic From the BroadcastReceiver I want to call a activity without graphic. Without graphic because it will speak some words.
Intent iSpeechIntent = new Intent(context, TTS.class);
iSpeechIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(iSpeechIntent);

but activity cycle is not finished correctly. onDestroy() method is never executed. Why?
@Override
    public void onDestroy() {
        // Don't forget to shutdown!
        if (tts != null) {
            tts.stop();
            tts.shutdown();
        }
        super.onDestroy();
    }

And is OK if i am using activity without graphic XML just for speak some text with TTSEngine?

A: You misunderstood Activity lifecycle. onDestroy() is NOT called when your activity is dismissed. And dismissing it (i.e. by starting another activity) does NOT equal destroying activity (however you may enforce destroy of activity, by calling finish() - and then your onDestroy() method will be invoked). You may want to move your code to onPause() and onResume() respectively or maybe you shall use IntentService instead, if you dot require any UI for the task.

A: I propose to use Android Service for such kind of tasks http://developer.android.com/reference/android/app/Service.html .


Q: Screen going behind bottom material tab bar Hi am working on screens which involves bottom tab bar. For that I have implemented material bottom tab bar from react-navigation-material-bottom-tabs. Problem is my screen is going behind the bottom tab like below
The yellow border was given to see how UI would look like. The bottomline of screen is expected to be just above the bottom bar not behind it.

<SafeAreaView style={{backgroundColor: '#f3f3f5'}}>
    <View
      style={{
        borderWidth: 3,
        borderColor: 'yellow',
        width: width,
        height: height,
        flexDirection: 'column-reverse',
      }}>
      <Header data={headerData} />
      <LabelledView
        rectanglebarfunc={() => this.rectanglebarfunc()}
        height={height * 0.07}
        rectanglebarbuttontext={'List Item 01'}
        width={width}
        color="white"
        icolor="#ff007C"
        textColr="#120F3F"
        fontSize={16}
        rectanglebarfunc={() => {}}
      />
      <View
        style={{
          width: '100%',
          height: 0.5,
          backgroundColor: 'transparent',
        }}
      />
      <LabelledView
        rectanglebarfunc={() => this.rectanglebarfunc()}
        height={height * 0.07}
        rectanglebarbuttontext={'List Item 00'}
        width={width}
        color="white"
        icolor="#ff007C"
        textColr="#120F3F"
        fontSize={16}
        rectanglebarfunc={() => {}}
      />

      {/* <View
        style={{
          width: '90%',
          height: '70%',
          backgroundColor: 'red',
          alignSelf: 'center',
          marginVertical: 5,
        }}></View> */}
    </View>
  </SafeAreaView>

A: Try adding marginBottom to safeAreaView and View :
<SafeAreaView style={{backgroundColor: '#f3f3f5' ,marginBottom:100}}>
    <View
      style={{
        borderWidth: 3,
        borderColor: 'yellow',
        width: width,
        height: height,
        flexDirection: 'column-reverse',
      marginBottom:100
      }}>

try adjusting your marginBottom to check
Hope it helps. feel free for doubts


Q: Magento 2 : How to create shipment label programmatically I am currently building a functionality to create order,invoice and shipment via script.
I can create shipment with tracking ID programmatically but could not create shipment label via script.
I am using FedEx shipping method. please help how to create shipment label for FedEx programmatically.


Q: Using IntentFilter I am trying to use IntentFilter with Brodcastreciver, but text not updates.
I want to update text every time when time changes. Better if when day changes, but I dont know how to do this.
Can you help me please to do it right?
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FadingActionBarHelper helper = new FadingActionBarHelper()
            .actionBarBackground(R.drawable.ab_background)
            .headerLayout(R.layout.header)
            .contentLayout(R.layout.activity_main);
    setContentView(helper.createView(this));
    initCard();

    initHeader();
    helper.initActionBar(this);

    IntentFilter s_intentFilter = new IntentFilter();
    s_intentFilter.addAction(Intent.ACTION_TIME_TICK);
    s_intentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
    s_intentFilter.addAction(Intent.ACTION_TIME_CHANGED);
    registerReceiver(m_timeChangedReceiver, s_intentFilter);
    initHeader();
}

private void initHeader() {
    TextView title = (TextView)(findViewById(R.id.title));
    final TextView subtitle = (TextView)(findViewById(R.id.subtitle));
    SimpleDateFormat sdf = new SimpleDateFormat("dd.mm.yyyy.HHmmss");
    final String currentDateandTime = sdf.format(new Date());
    subtitle.setText(currentDateandTime);

}
private final BroadcastReceiver m_timeChangedReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();
        if (action.equals(Intent.ACTION_TIME_CHANGED) ||
                action.equals(Intent.ACTION_TIMEZONE_CHANGED)||
                action.equals(Intent.ACTION_TIME_TICK))
        {
            initHeader();
        }
    }
};

Update: Time changes. Sorry)
Actually it is chnges every minute


Q: How to fix 'Unexpected identifier' in JavaScript I am writing code for a calculator and I got an error 'Unexpected Identifier' and I don't know what's wrong. The line of code is
alert("Welcome to the multiplication website!").
I have no idea what's wrong.
<head>
  <title>Multiplication Table</title>
  <script type="text/javascript">
    alert("Welcome to the multiplication website!")
    var rows = prompt("What is your first number?")
    var cols = prompt("What is your second number?")
        output = rows * cols
        if rows isNaN()
        then output = Error: Not a Number
    document.write(output);
  </script>
</head>
<body>
</body>
</html>

I expected it to not have errors, then there were errors.

A: You have a little code that looks like pseudoxode - try this:
if (isNaN(rows)) alert("Error: Not a Number");


Q: Ionic native using ionic/angular 1 I'm currently working on a project in ionic/angular 1. I'm using ionic native to wrap the cordova plugins.
I installed ionic native with bower, and added dependency to 'ionic.native' in my app's angular module. Now I can inject stuff like $cordovaFile into my controllers and use them. This works great.
My problem is using the MediaPlugin. I inject $cordovaMediaPlugin in my controller. Now the documentation ( https://ionicframework.com/docs/v2/native/mediaplugin/ ) says do this:
new MediaPlugin('path/to/file.mp3', onStatusUpdate);
Obviously i cant do this in angular1.
I tried stuff like this:
var media = this.$cordovaMediaPlugin('PATH');
var media = new this.$cordovaMediaPlugin('patch');
nothing seems to work, getting undefined all the time.
How would I make this calls in angular/ionic 1? I really think the 'new' keyword is the issue here...

A: Try to install ngCordova Media plugin.
Install ngCordova, and inject in your app module 'ngCordova'.

*

*See de following steps

*Install plugin

*If you want create a service to provide a media resources see (Not required)


Q: Solve the matrices equation AX=B (tridiagonal matrices) Solve this equation AX=B
\begin{align}
    \begin{bmatrix}
    1 & 1 & 1 & \cdots & 1 \\
    0 & 1 & 1 & \ddots & 1 \\
    \vdots & \ddots & \ddots & \ddots & \vdots \\
    \vdots & \ddots & \ddots & 1 & 1 \\
    0 & \cdots & \cdots & 0 & 1
    \end{bmatrix}
\cdot X =
    \begin{bmatrix}
    2 & 1 & 0 & \cdots & 0 \\
    1 & 2 & 1 & \ddots & \vdots \\
    0 & 1 & 2 & \ddots & 0 \\
    \vdots & \ddots & \ddots & 2 & 1 \\
    0 & \cdots & 0 & 1 & 2
    \end{bmatrix}
\end{align}
I have never found inverse of a nxn tridiagonal matrix and multiplied them before ($X = A^{-1}\cdot B$)
Thanks for your help

A: By Gauss-Jordan method we can easy see that
$$ \begin{bmatrix}
    1 & 1 & 1 & \cdots & 1 \\
    0 & 1 & 1 & \ddots & 1 \\
    \vdots & \ddots & \ddots & \ddots & \vdots \\
    \vdots & \ddots & \ddots & 1 & 1 \\
    0 & \cdots & \cdots & 0 & 1
    \end{bmatrix}^{-1}=\begin{bmatrix}
    1 & -1 & 0 & \cdots & 0 \\
    0 & 1 & -1 & \ddots & 0 \\
    \vdots & \ddots & \ddots & \ddots & \vdots \\
    \vdots & \ddots & \ddots & 1 & -1 \\
    0 & \cdots & \cdots & 0 & 1
    \end{bmatrix}$$


Q: Pattern matching from mochiweb xpath I am trying to pattern match these values which are returned by running mochixpath.  The pattern is clearly [elemName, htmlAttrs, children], but what I really need from the following values is UserNameA and "This is a message"
[{"tr", [{"bgcolor", "White"}],
  [{"td", [{"class", "Topic"}],
   [{"div", [],
    [{"a", [{"class", "lnkUserName"}, {"href", "/users/prof.aspx?u=27149"}],
      ["UserNameA"]
    }]
 }]},
 {"img", [{"alt", ""}, {"src", "/Images/Icons/userIcon.gif"}], []},
 {"td", [{"class", "bHeader"}],
    [{"div", [{"style", "float:left;width:77%;"}],[
        {"a", [{"class", "PostDisplay"}],
          ["This is a message"]}]
    }]
 }]

Essentially I'm using the parsed xml from the output of the xpath to get the username and the message they sent.  I am very new to elixir and the concept of pattern matching so any help is greatly appreciated.

A: Something is wrong with the output, because it spits syntax error, when I copy it to console, so I'll assume that you have tr, with td, img and other td inside.
Pattern matching can be used for unwrapping this way. Lets say, you have your whole data in variable Data, you can extract the contents with:
[TR] = Data,
{_Name, _Attrs, Contents} = TR.

Now Contents is again a list of nodes: [Td1, Img, Td2], so you can do:
[Td1, Img, Td2] = Contents.

And so on, until you actually reach your contents. But writing that is pretty tedious and you can use recursion instead. Lets define contents function, that recursively scans the elements.
contents({_Name, _Attrs, Contents}) ->
    case Contents of
        [] -> []; % no contents like in img tag
        [H | T] ->
            case is_tuple(H) of
                % tupe means list of children
                true -> lists:map(fun contents/1, [H | T]);
                % otherwise this must be a string
                _ -> [H | T]
            end
    end.

This will return nested list, but you can at the end run lists:flatten like this:
Values = lists:flatten(contents(Data)).

A: The curly and square brackets are not balanced in your example. I guess it is missing a }] at the end.
It seems that the deepness of the expression may vary, so you have to explore it recursively. The code belows does it, assuming that you will find the information in type "a" elements:
-module (ext).
-compile([export_all]).

extL(L) -> extL(L,[]).

extL([],R) -> R;
extL([H|Q],R) -> extL(Q, extT(H) ++ R).

extT({"a",PropL,L}) ->
    case proplists:get_value("class",PropL) of
        "lnkUserName" -> [{user_name, hd(L)}];
        "PostDisplay" -> [{post_display,hd(L)}];
        _ -> extL(L,[])
    end;
extT({_,_,L}) -> extL(L,[]).

with your example it returns the proplist [{post_display,"This is a message"},{user_name,"UserNameA"}]


Q: Vue.js routes does not work using router-link i make a project using vue js. in the nav bar i put menu home and about which is will go direct to each page when it's clicked. there is no error when i run the project but the router doesn't work when i clicked the menu.
main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './routes'

import './assets/main.css'

createApp(App).use(router).mount('#app')

routes.js
import { createWebHistory, createRouter } from "vue-router";
import Home from '@/components/Home.vue';
import AboutMe from '@/components/AboutMe.vue';

const routes = [
    {
        name: 'Home',
        path: '/',
        component: Home
    },
    {
        name: 'AboutMe',
        path: '/aboutme',
        component: AboutMe
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes
})

export default router;

app.vue

        <router-link to="/" class="nav-item">HOME</router-link>
        <router-link to="/aboutme" class="nav-item">ABOUT ME</router-link>

A: You missed to add <router-view/>
add it on your app.vue file after the nav section.
Example:

        <router-link to="/" class="nav-item">HOME</router-link>
        <router-link to="/aboutme" class="nav-item">ABOUT ME</router-link>

      <router-view/>


Q: How to return range or location of cursor in TinyMCE when clicked or cursor location changed? how can I get the location of the cursor when the TinyMCE editor is focused on or when cursor location changes?
Thanks.

A: Use the tinymce onActivate event in case of focus.
A cursor location change is possible, but it is expensive to detect, because you will have to check on each key-action if the cursor is still on the previous spot or not.


Q: Replacing "foreach" with "for" in PHP I need to replace my "foreach" with "for", but actually I don't know how.
Here is the part of my php code:
$r = "";
$j = 0;
foreach ($orgs as $k => $v) {
    echo "\n\r" . $v->id . "\n\r";
    if (1) {
        $a_view_modl = ArticleView :: model($v->id, $v->id);
        $connection = $a_view_modl->getDbConnection();

Thanks!

A: $r = "";
$j = 0;
foreach ($orgs as $k => $v) {
    echo "\n\r" . $v->id . "\n\r";
    if (1) {  //you don't really need this, because it's allways true
        $a_view_modl = ArticleView :: model($v->id, $v->id);
        $connection = $a_view_modl->getDbConnection();

if $orgs is an associative array, it becomes:
$r = "";
$j = 0;
for($i = 0; $i < count($orgs); $i++)
{
    echo "\n\r" . $orgs[$i]->id . "\n\r";
    $a_view_modl = ArticleView :: model($orgs[$i]->id, $orgs[$i]->id);
    $connection = $a_view_modl->getDbConnection();
}

better you do some checks first if you go for this solution.
if you implement your solution with foreach which is in this case more readable, you can increment or decrement a given variable, like normal:
$i++; //if you want the increment afterwards
++$i; //if you want the increment before you read your variable

the same for decrements:
$i--; //decrement after reading the variable
--$i; //decrement before you read the variable

A: A foreach loop is just a better readable for loop. It accepts an array and stores the current key (which is in this case an index) into $k and the value into $v.
Then $v has the value you are using in the snippet of code.
A for loop does only accept indexed arrays, and no associative arrays.
We can rewrite the code by replacing $v with $orgs[ index ], where index starts from 0.
$r = "";
$j = 0;

for ($i = 0; $i < count($orgs); $i++) {
    echo "\n\r" . $orgs[$i]->id . "\n\r";
    if (1) {
        $a_view_modl = ArticleView::model($orgs[$i]->id, $orgs[$i]->id);
        $connection = $a_view_modl->getDbConnection();

A: $r = "";
$j = 0;
for($i = 0 ; $i < count($orgs); $i++)
{
    $v = $orgs[$i];
    echo "\n\r" . $v->id . "\n\r";
    if (1) {
        $a_view_modl = ArticleView :: model($v->id, $v->id);
        $connection = $a_view_modl->getDbConnection();
}

A: foreach ($orgs as $k => $v) {
    // Your stuff
}

for loop
for ($i = 0; $i < count($orgs); $i++) {
    // Your stuff ... use $orgs[$i];
}


Q: Decrease top menu so it does not stick out on carousel I have made this website here: http://dijon-egg.com/Possum/
If you click on green big dot button, it takes you to page2.  My problem is I can't figure and fix the menu being too big on page 2 or change view of carousel on page 2 so full carousel can show to us.

A: As I looked at your source code, I guess you should somehow add the .cbp-af-header-shrink class back to the header, when you click the green button.


Q: How to create a template dashbord in tableu? I have a Dashboard in tableau that I want to replicate it with another database that has the same columns/pills!
is it possible to do that?

A: The best way would be to open the "template dashboard", add the new data source, then go to menu DATA => Replace data source and change the old data source to the new data source.
At this point close the old data source.
The fastest way, but this might not work, is to open the .twb file of the dashboard with Notepad and replace the old database name with the new one...of course something could be broke.
If you have a .twbx file you can open it with WinZip, WinRar, ... and find the .twb file inside.

A: Possibly you could try 2 Options:

*

*Take a copy of your template. In the Data Source tab, go to Connections -> Edit Connection to point it to the new data source.

*In the template, create a new data source. Replace the Old data source with the new one by Data -> Replace Data Source.

For the formulas and filters to reflect on the new data source, make sure the field names and data types are the same as the old data source.
Kindly note: Editing the XML is unsupported by Tableau! Create a copy of your original workbook before attempting any XML editing, as this could potentially corrupt your workbook.


Q: Cannot Remove Secondary Dynamic IP I'm running Ubuntu Server 20.04. The system was setup initially with DHCP. I went into /etc/netplan and changed the file to use a static IP, as shown below.
network:
  ethernets:
    enp0s4:
      addresses: [10.0.1.9/24]
      dhcp4: false
      gateway4: 10.0.1.1
      nameservers:
        addresses: [8.8.8.8, 4.2.2.2]

  version: 2

1
The plan has been applied and rebooted multiple times. The new IP works and is valid, but the old DHCP address is still present. I disabled DHCPCD with no luck. When I enter ip a it shows both the static and dynamic IP. I'm trying to get rid of the secondary dynamic address, but everthing I've tried doesn't seem to work.
2: enp0s4: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:a0:98:12:22:95 brd ff:ff:ff:ff:ff:ff
    inet 10.0.1.9/24 brd 10.0.1.255 scope global enp0s4
       valid_lft forever preferred_lft forever
    inet 10.0.1.242/24 brd 10.0.1.255 scope global secondary dynamic enp0s4
       valid_lft 81243sec preferred_lft 81243sec

2

A: I had the same problem and running the following help me determine my problem:
netplan --debug generate

I'd backed up my 50-cloud-init.yaml to _50-cloud-init.yaml which was still be read as a valid yaml file; doh! Renamed it to 50-cloud-init.yaml.bak, rebooted; problem solved.


Q: translationY doesn't change bounds I'm trying to create a flexible toolbar using the ObservableScroll library
 following the code that he wrote, only that I want to use a RecyclerView instead of a ScrollView.
here's the layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:elevation="4dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?attr/colorPrimary"
            android:minHeight="?attr/actionBarSize"/>

        <View
            android:id="@+id/vFlexible"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:background="?attr/colorPrimary" />
        </LinearLayout>

    <TextView
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="16dp"
        android:paddingLeft="72dp"
        android:ellipsize="end"
        android:maxLines="1"
        android:layout_gravity="start"
        android:minHeight="?attr/actionBarSize"
        android:textColor="@android:color/white"
        android:textSize="20sp"
        android:text="test"/>
</FrameLayout>

<com.github.ksoichiro.android.observablescrollview.ObservableRecyclerView
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:id="@+id/rv" />

and here's the code:
package test.itayrabin.toolbartest;

import android.content.res.TypedArray;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.github.ksoichiro.android.observablescrollview.ObservableRecyclerView;
import com.github.ksoichiro.android.observablescrollview.ObservableScrollViewCallbacks;
import com.github.ksoichiro.android.observablescrollview.ScrollState;

 public class MainActivity extends ActionBarActivity implements ObservableScrollViewCallbacks {

private View vFlexibleSize;
private Toolbar mToolbar;
private TextView tvTitle;
private int flexibleSize;
public static final String TAG = "FlexibleTest";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mToolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(mToolbar);

    tvTitle = (TextView) findViewById(R.id.title);
    tvTitle.setText(getTitle());
    setTitle(null);

    final ObservableRecyclerView recyclerView = (ObservableRecyclerView) findViewById(R.id.rv);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));

    recyclerView.setAdapter(new Adapter(this));
    recyclerView.setScrollViewCallbacks(this);

    flexibleSize = getResources().getDimensionPixelSize(R.dimen.flexible_space_height);
    int flexibleAndToolbar = flexibleSize + getActionBarSize();

    vFlexibleSize = findViewById(R.id.vFlexible);
    vFlexibleSize.getLayoutParams().height = flexibleAndToolbar;

    //recyclerView.setPadding(0,flexibleAndToolbar,0,0);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
public void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging) {
    update(scrollY);
}

@Override
public void onDownMotionEvent() {}

@Override
public void onUpOrCancelMotionEvent(ScrollState scrollState) {}

protected int getActionBarSize() {
    TypedValue typedValue = new TypedValue();
    int[] textSizeAttr = new int[]{R.attr.actionBarSize};
    int indexOfAttrTextSize = 0;
    TypedArray a = obtainStyledAttributes(typedValue.data, textSizeAttr);
    int actionBarSize = a.getDimensionPixelSize(indexOfAttrTextSize, -1);
    a.recycle();
    return actionBarSize;
}

private void update(final int scrollY){
    vFlexibleSize.setTranslationY(-scrollY);

    int adjustedY = scrollY;
    if (scrollY<0){
        adjustedY = 0;
        Log.i(TAG,"Scroll Y <0 - " + scrollY);
    } else if (flexibleSize < scrollY){
        adjustedY = flexibleSize;
        Log.i(TAG,"scrollY is bigger than flexibleSize - " +scrollY);
    }

    float maxScale = (float) (flexibleSize - mToolbar.getHeight()) / mToolbar.getHeight();
    Log.i(TAG,"maxScale is " + maxScale);

    float scale = maxScale * ((float) flexibleSize - adjustedY) / flexibleSize;
    Log.i(TAG,"scale is " + scale);

    tvTitle.setPivotX(0);
    tvTitle.setPivotY(0);
    tvTitle.setScaleX(scale + 1);
    tvTitle.setScaleY(scale + 1);

}

What's basically happening here is there is a Frame layout at the top of the screen, consisting of a LinearLayout that has the Toolbar on top and a view underneath it that expands and collapses when we scroll. below that I have the recyclerView.
I collapse the flexibleView when there is a scroll in the update method by setting it's TranslationY.
The problem is that when I scroll and the FlexibleView collapses the recyclervies's padding stays, or the LinearLayout doesn't change it's bounds, or something is making the recylcerview stay in it's location and not go up sticking to the edge of the toolbar FrameLayout.
Does anyone have any ideas how do I fix this?