text:
Q: Why isn't the AVD launching my Android App? I'm only just learning Android development.  I created a new Android Application Project in Eclipse which created a basic hello world.  Eclipse launches the the AVD but does not launch the HelloWorld app.  It managed to launch the app once.  I will try to give as much information on my setup.  Any suggestions would be greatly appreciated.

*

*Windows 7 Home Premium 64-bit

*JDK 7u5 64-bit installed

*Eclipse IDE for Java Developers 64-bit

*Android ADT installed

*Android SDK installed

*

*Android 2.3.3 (API10)

When I created a new Android Application Project I chose Build SDK: Android 2.3.3 (API10) and for Minimum Required SDK: API10: Android 2.3.3 (Gingerbread).
MainActivity.java
package com.mytest.helloworld;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

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

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

AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mytest.helloworld"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

I have an AVD using the Android 2.3.3 - API Level 10 target with skin Default (WVGA800).  No custom properties.
I launch the MainActivity.java as a Android Application, the AVD launches but the HelloWorld app does not.  Here is the Eclipse Android console output:
[2012-07-22 02:11:22 - HelloWorld] ------------------------------
[2012-07-22 02:11:22 - HelloWorld] Android Launch!
[2012-07-22 02:11:22 - HelloWorld] adb is running normally.
[2012-07-22 02:11:22 - HelloWorld] Performing com.mytest.helloworld.MainActivity activity launch
[2012-07-22 02:11:22 - HelloWorld] Automatic Target Mode: launching new emulator with compatible AVD 'Android_2.3.3'
[2012-07-22 02:11:22 - HelloWorld] Launching a new emulator with Virtual Device 'Android_2.3.3'

Here's the console output when I somehow managed to get it to work:
[2012-07-21 15:51:57 - HelloWorld] ------------------------------
[2012-07-21 15:51:57 - HelloWorld] Android Launch!
[2012-07-21 15:51:57 - HelloWorld] adb is running normally.
[2012-07-21 15:51:57 - HelloWorld] Performing com.mytest.helloworld.MainActivity activity launch
[2012-07-21 15:51:57 - HelloWorld] Automatic Target Mode: launching new emulator with compatible AVD 'Android_2.3.3'
[2012-07-21 15:51:57 - HelloWorld] Launching a new emulator with Virtual Device 'Android_2.3.3'
[2012-07-21 15:51:58 - HelloWorld] New emulator found: emulator-5554
[2012-07-21 15:51:58 - HelloWorld] Waiting for HOME ('android.process.acore') to be launched...
[2012-07-21 15:52:06 - HelloWorld] HOME is up on device 'emulator-5554'
[2012-07-21 15:52:06 - HelloWorld] Uploading HelloWorld.apk onto device 'emulator-5554'
[2012-07-21 15:52:08 - HelloWorld] Installing HelloWorld.apk...
[2012-07-21 15:52:12 - HelloWorld] Success!
[2012-07-21 15:52:12 - HelloWorld] Starting activity com.mytest.helloworld.MainActivity on device emulator-5554
[2012-07-21 15:52:13 - HelloWorld] ActivityManager: Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.mytest.helloworld/.MainActivity }

Remember I didn't edit anything when I created this Hello World. The only thing I entered was the name of the project.

A: It takes time to boot up emulator.. then it will launch ur app.
Don't close emulator every time, start it once and run ur app by choosing this one only...

A: When I ran adb devices I did not see my AVD device listed.  It seems I need restart the adb server by running:
adb kill-server
adb start-server
I ran adb devices again and saw my AVD device listed.  My HelloWorld app finally ran.


text:
Q: OpenJPA distinct on In my DB schema I have conversations with several emails. I want to get the newest emails from a list of conversations. In PostgreSql the query:
select distinct on (conversation_id) *
from email
where conversation_id in (7085214, 7084964)
order by conversation_id, processing_date desc

OpenJPA:
(List<Email>) entityManager.createQuery("SELECT
   distinct(email.conversation.id), email FROM Email email WHERE
      email.conversation.id in :id ORDER BY email.conversation.id,
      email.processingDate DESC").setParameter("id", conversationIds);

It gives back a map of the conversation ids and the whole list of emails in the conversations.
How could I make it right?
Thanks

A: Use native SQL.
The only other way to do what you want is to develop a patch to OpenJPA that "teaches" it how to use the PostgreSQL extension DISTINCT ON in its JPQL parser and query generator. Most ORMs accept such extensions via dialect hooks. Don't expect this to be a simple task, though - unless you're writing a lot of these queries, native SQL is almost certain to be much easier.
You can't just use DISTINCT or DISTINCT ON like functions. They aren't; they're completely separate syntax. A JPQL engine would try to convert it into a true function call that'd fail at runtime - or in the case of distinct on, just fail to parse it in the first place.
BTW, DISTINCT ON is a bit like GROUP BY in some other vendor databases like MySQL, where you're allowed to specify columns in the SELECT that don't appear in the GROUP BY or an aggregate. So in MySQL people probably do this by just producing a technically invalid query that MySQL accepts anyway - it's quite likely that the OpenJPA JPQL handler won't notice the problem, so it'll pass it through fine. This trick won't work for DISTINCT ON and PostgreSQL is strictly standards compliant about GROUP BY, it won't let you produce a non-deterministic query with GROUP BY.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a misnegation in the following example? I have a question about an excerpt that I read online. Here it is:

Having reviewed the posts that you have identified, I conclude that you do not have any non-frivolous defamation against any of the posters.

My doubt is related to the second clause: "do not have any non-frivolous..." Is this a case of misnegation, in which the actual meaning of the phrase is "do not have any frivolous"?

A: No, definitely not. Lawyers do not like to say 'no possible case', since there is practically no limit to what an ingenious plaintiff can base a complaint on. You can, however, say that any such complaint would be adjudged frivolous.
If somebody says to you "Do not use unnecessary words", do you worry about whether the intended meaning was "do not use necessary words"?

A: My reading of the quoted language—

Having reviewed the posts that you have identified, I conclude that you do not have any non-frivolous defamation against any of the posters.

is that it is intended as a short form of this language:

Having reviewed the posts that you have identified, I conclude that you do not have legal grounds to pursue any non-frivolous action for defamation against any of the posters.

In other words, you can pursue an action for defamation in court, but any sensible judge will conclude that your action is frivolous—that is, according to definition 1b of frivolous in Merriam-Webster's Eleventh Collegiate Dictionary (2003), "having no sound basis (as in fact or law)."
So the lawyer (or pseudo-lawyer) is telling the client (or pseudo-client) that any proposed action for defamation based on the specified online posts is without merit and will fail in court.

A: In legal land, frivolous stuff is not valid. So non-frivolous stuff is valid.
So ... you do not have any non-frivolous ... means ... you do not have any valid ...
In context, ... you do not have any valid defamation [claims] against ...
In legal parlance, your screwed.


text:
Q: Как правильно тестировать запросы, требующие авторизацию, при использовании Cookie? В своем проекте использую Spring 2.2.4, как вы понимаете есть методы, требующие авторизацию - в которых я получаю текущего пользователя из сессии - как это все организовать в тестах, понимаю что как то надо замокать секьюрити, но опыта в данной теме вообще никакого. Вот это метод получения текущего юзера из сессии:
 public User getCurrentUser() throws Exception {
 Authentication auth =
 SecurityContextHolder.getContext().getAuthentication();

 if (null == auth) {
   throw new NotFoundException("");
 }

 Object obj = auth.getPrincipal();
 String username = "";

 if (obj instanceof UserDetails) {
  username = ((UserDetails) obj).getUsername();
 } else {
   username = obj.toString();
 }

 User user = userRepository.findByEmail(username).get();
 return user;

}
как мне все это лучше организовать?
хотелось бы сделать тесты подобного вида:
  @Test
void findPostById() {
 PostByIdApi postByIdApi = postService.findPostById(8);
 Assertions.assertEquals(8, postByIdApi.getId());
 Assertions.assertEquals("Rerum eos quam.", postByIdApi.getTitle());

}


text:
Q: What is the best/most solid way to translate SDL2 arrow/WASD keys to player movement? My question is what is the most solid way to implement directional input in SDL2.
The problem with my current code is that say you wanted to move the player to the left. Pressing a would decrease his x value and once you release the a key, it stops decreasing the x value. however, if you wanted to move to the left and then immediately move to the right, the player would just stop for a period of time and then continue moving right.
Any advice would be very helpful.
My keyboard function:
class KeyboardController : public Component {

public:
TransformComponent* transform;

void init() override {
    transform = &entity->getComponent<TransformComponent>();
}

void update() override {

    if (MainGame::evnt.type == SDL_KEYDOWN) {
        switch (MainGame::evnt.key.keysym.sym)
        {
        case SDLK_w:
            transform->velocity.y = -1;

            break;
        case SDLK_a:
            transform->velocity.x = -1;

            break;
        case SDLK_s:
            transform->velocity.y = 1;

            break;
        case SDLK_d:
            transform->velocity.x = 1;

            break;
        }
    }

    if (MainGame::evnt.type == SDL_KEYUP) {
        switch (MainGame::evnt.key.keysym.sym)
        {
        case SDLK_w:
            transform->velocity.y = 0;

            break;

        case SDLK_a:
            transform->velocity.x = 0;

            break;

        case SDLK_s:
            transform->velocity.y = 0;

            break;

        case SDLK_d:
            transform->velocity.x = 0;

            break;
        }
      }
   }
};

My velocity function:
/* class */

Vector2D position;
Vector2D velocity;

/* other code */

void update() override {
    position.x += velocity.x * speed; //speed = 3
    position.y += velocity.y * speed;
}

A: Instead of acting upon events to immediately change the velocity, consider adding additional state (an array) which remembers which keys are down at any given moment. Any time an input event is received, update the array and recalculate the velocity based on that.
For example, depending on what game you're making, you may want to make the player stop moving if both left and right are pressed at the same time. Alternatively, a keydown event for a direction key would make the player immediately start moving in that direction, but you'll still need to keep track of when no more buttons are held down to know when the player should stop moving.


text:
Q: react component re rendered multiple times when trying to invoke itself? code:
myMethod = () => {
 setTimeout(()=> {
 if(!this.state.otherFuncHasBeenCalled) {
    this.myMethod()
 }
},5000)
}

so the otherFuncHasBeenCalled state is set to true if my other function is called. but what I wanted to do here is when myMethod is invoked, after 5 seconds, if my other function is NOT called that sets otherFuncHasBeenCalled state to true, invoke myMethod again. But it re renders the component multiple times. Help?

A: How about something like this?
myMethod = () => {
  setTimeout(()=> {
   if(!this.state.otherFuncHasBeenCalled) { // wait 5 sec for check
    this.setState(
      {otherFuncHasBeenCalled: true}, // update state
      this.myMethod  // run again after state has been set
   }
  },5000)
}


text:
Q: How to plot ageing vector graph as the paper showed? I'm trying to plot a graph like this one from a paper The reference. This graph shows how global cognition (the dependent variable) of people with different baseline ages decline(direction and rate) over the 7 years of follow-up.
The dataset is a panel data. In this paper, it fitted the trajectory of global cognition first using Latent growth curve modelling.
However, I have no idea how to extract the information for the direction and rate. Can anyone provide some suggestion?
I search for tutorial with the key word "ageing vector graph". But I didn't get the results I needed.
I have fitted a mixed effect model with lmer() function. I guess its coefficients could provide information to plot each vector.


text:
Q: char[] array equivalent in c# i have a c++ struct which has char[20] like below, and it is packed.
#pragma pack(push, temp_aion_packed, 1)
struct temp
{
  char x[20];
  char y[20];
};
#pragma pack(pop, temp_aion_packed)

now how can i write this struct in c# so that both are same. i have written like this in c#
[DataContract]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1),Serializable]
public class temp
{
   [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)]
     public string x;
   [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)]
     public string y;
}

below is the pinvoke declaration in c#
[DllImport("rmsCAPI.dll", CallingConvention = CallingConvention.StdCall, ExactSpelling = true, EntryPoint = "OrderRequirement")]
    public static extern int OrderRequirement(ref temp tmp);

c++ function that calls this struct as parameter
long __stdcall OrderRequirement(struct temp *tmp)
{
  string p="";
  string q="";
  p=temp->x;
  q=temp->y;
  char buff[2048];
  sprintf(buff,"p: %s\n q: %s\n x: %s\n y: %s\n",p,q,temp->x,temp->y);
 }

but when i do like this in c# it is giving me the junk data in c++, when i assign values for them in c#. Can any one please assist.
Thank you all for help on the above one, but now i got a new problem which is an extension of this, i am providing everything in detail below.
My structures in c++
#pragma pack(push, temp_aion_packed, 1)
struct temp
{
  long req;
  struct type m_type;
  short id;
  char x[20];
  char y[20];
};
#pragma pack(pop, temp_aion_packed)

#pragma pack(push, type_aion_packed, 1)
struct type
{
  short i;
};
#pragma pack(pop, type_aion_packed)

i have written equivalent c# structs like this
[DataContract]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1),Serializable]
public struct temp
{
   [DataMember]
    public long req;
   [DataMember]
    [MarshalAs(UnmanagedType.Struct)]
     public type m_type;
   [DataMember]
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)]
     public string x;
   [DataMember]
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)]
     public string y;
}

[DataContract]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1),Serializable]
public struct type
{
  [DataMember]
    public short i;
}

below is my c# pinvoke
[DllImport("rmsCAPI.dll", CallingConvention = CallingConvention.StdCall, ExactSpelling = true, EntryPoint = "OrderRequirement")]
    public static extern int OrderRequirement(ref temp tmp);

below is my c++ method that calls struct as parameter
long __stdcall OrderRequirement(struct temp *tmp)
{
  char buff[2048];
  sprintf(buff,"req: %ld \n id: %d \n x: %s\n",tmp->req,tmp->id,tmp->x);
}

now the problem i am getting is as i have structure variable m_type(of struct "type") declared in struct temp, the variables declared before (long req)that are printing fine in my c++ program but the variable declared after that are not giving me any output. So i think the declaration of structures in c# is messing up and i am unable to figure it out so can any one please help.

A: You declared the struct as a class in C#. That's fine, but it means that any variable of that type is already a reference. So you don't need to pass by ref. When you pass a class by ref you end up passing a pointer to a pointer to the object. That's one level of indirection too many.
The P/invoke in the C# code should therefore be like this:
public static extern int OrderRequirement(temp tmp);

The other way to fix it is to leave the ref in the function declaration, but to declare the temp type as a struct rather than a class. That's because a struct is a value type. A variable whose type is a struct is a value rather than a reference.
Both solutions work, it's up to you which you choose.

There is another problem in your C++ code.
sprintf(buff,"p: %s\n q: %s\n x: %s\n y: %s\n",p,q,temp->x,temp->y);

You are passing p and q, which are of type std::string to printf and expecting the %s format string to print them. That's an error. You need to call c_str() on the strings. Like this:
sprintf(
  buff,
  "p: %s\n q: %s\n x: %s\n y: %s\n",
  p.c_str(),q.c_str(),temp->x,temp->y
);

The problem with your update is that long is 32 bits in Windows C++ and 64 bits in C#. You need to declare it as int in C#. And you missed the id field altogether.
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1),Serializable]
public struct temp
{
    [DataMember]
    public int req;

    [DataMember]
    public type m_type;

    [DataMember]
    public short id;

    [DataMember]
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)]
    public string x;

    [DataMember]
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)]
    public string y;
}


text:
Q: rxjava - cache from observerables using concat not working Following this tutorial
I tought i'd create a fake memory,disk, network objects to see there order if one fails.  My goal was to see if one failed it concat move to the next one as per the articles comment:

The key to this pattern is that concat() only subscribes to each child Observable when it needs to. There's no unnecessary querying of slower sources if data is cached, since first() will stop the sequence early. In other words, if memory returns a result, then we won't bother going to disk or network. Conversely, if neither memory nor disk have data, it'll make a new network request.

i then created the following test:
 Data disk=new Data();
    disk.setAddress("38 Oriole");
    disk.setPostalCode("mc72l9");
    disk.setDate("feb 12");

Data network=new Data();
network.setAddress("39 skyway");
network.setPostalCode("mt82l9");
network.setDate("feb 13");

Observable observerMemory = Observable.create(new Observable.OnSubscribe<String>() {

            @Override
            public void call(final Subscriber subscriber) {
                subscriber.onNext(null);
            }}
);

Observable<Data> observerDisk = Observable.from(disk);
Observable<Data> observerNetwork = Observable.from(network);

Observable.concat(observerMemory, observerDisk, observerNetwork).first().subscribe(new Subscriber<Data>() {
    @Override
    public void onCompleted() {

    }

    @Override
    public void onError(Throwable e) {
        System.out.println("****" + e);
    }

    @Override
    public void onNext(Data data) {
        System.out.println(data.toString());
    }
});

However, when running this test i was expecting it to print the disk observable (stream) . so the output should have been 38 Oriole etc since the very first observable was returning null and concat should get the next stream if one fails i thought.  I mean as per the article if one stream failed such as the memory stream then concat should go to the next stream which is disk.  But for me it did no such thing. The emission stopped at the first error of null.  What am i doing wrong. I am doing this fake test to ensure this way works before i continue to make a real cache system using reactive programming.
by the way here is the rxjava dependency im using:
compile 'com.netflix.rxjava:rxjava-android:0.20.7'

A: The problem is that observerMemory is calling onNext(null) when subscribed to. To get concat to move on to the next Observable, observerMemory needs to complete. If you replace subscriber.onNext(null) with subscriber.onComplete() the first emitted item will then be from disk.


text:
Q: Automatically clicking 500+ links on a website I've requested my data from a popular social media app. There are photos they have saved and have provided download links to. I don't want to click each one individually.
What's the best option of automatically going down the entire page and "click" each download link? Python? JS?
Thanks.

A: Selenium or Puppeteer.
https://developers.google.com/web/tools/puppeteer
https://www.selenium.dev/
Both tools are great to automate task like this.
You may also want to read this book on automating with python:
https://automatetheboringstuff.com/


text:
Q: How to prevent event for primeng dropdown? I would like to know how can i prevent the event for the primeng dropdown.
Kindly note: I do not want to disable the options.

A: You should take a look to the documentation
On your template
<p-dropdown [options]="yourDropdownOptions" [(ngModel)]="dropdownSelectedValue" (onChange)="onChange($event)"></p-dropdown>

On the .ts you can compare the selected value with whatever logic you want
onChange(event) {
    console.log(event.value);
}


text:
Q: ClassNotFoundException when including a library jar In my android project I added a library jar into the libs folder.
This jar contains three different packages:

*

*google GSON (com.google.gson)

*jboss netty (org.jboss.netty)

*A client application I developed myself which uses these two other libs. (com.example.core)

The jar is compiled/archived using ant.
There are no errors in eclipse, but when I try to run my android app on a device I get this:
E/AndroidRuntime(23807): FATAL EXCEPTION: main
E/AndroidRuntime(23807): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.project/com.example.project.MainActivity}: java.lang.ClassNotFoundException: Didn't find class "com.example.project.MainActivity" on path: /data/app/com.example.project-1.apk
E/AndroidRuntime(23807):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)
E/AndroidRuntime(23807):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
E/AndroidRuntime(23807):    at android.app.ActivityThread.access$600(ActivityThread.java:141)
E/AndroidRuntime(23807):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
E/AndroidRuntime(23807):    at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(23807):    at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(23807):    at android.app.ActivityThread.main(ActivityThread.java:5039)
E/AndroidRuntime(23807):    at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(23807):    at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(23807):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
E/AndroidRuntime(23807):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
E/AndroidRuntime(23807):    at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(23807): Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.project.MainActivity" on path: /data/app/com.example.project-1.apk
E/AndroidRuntime(23807):    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:65)
E/AndroidRuntime(23807):    at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
E/AndroidRuntime(23807):    at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
E/AndroidRuntime(23807):    at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
E/AndroidRuntime(23807):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
E/AndroidRuntime(23807):    ... 11 more

And it's definitely my jar that is causing this, since if I remove references to it's classes from within the MainActivity then the problem is solved and the app runs on the device.
Using apktool I checked to see what goes into the apk, and I found that everything is being added to the smali directory, that is everything except for my package (com.example.core).
So all of the android app classes (com.example.project), the gson (com.google.gson) and netty (org.jboss.netty) from my jar are there but not com.example.core.
My environment:
Eclipse 4.2.1
ADT 21.0.1
Java 7 (oracle)
Devices I tested on:
Samsung galaxy S2
LG nexus 4
Any ideas?
Thanks.

A: Ok, I finally managed to find the problem, it took me a while.
I am using java 7 on my machine and the ant builder uses this default version as well, unfortunately though, android does not like java 7, and so this fixed the problem for me:
<javac srcdir="." destdir="bin/classes" source="1.6" target="1.6">
    ...
</java>

Or you can use these steps in Eclipse:
Eclipse menu: Window/Preferences/Java/Compiler
Compiler Compliance level: 1.6
tick "use default"

Hope that this will save some time for others who are facing this problem.

A: (java build path / order and export) move your lib on top and check in

A: You're getting a NoClassDefFoundError because your jar file is not available at runtime.
In order for it to be available at runtime you'll have to check the checkboxes on your jar file in your java build path like this:

A: For IntelliJ this setup finally made the error go away for me:


text:
Q: Advice on how to structure this data? I receive this data, it's over the network so need to cache it locally.
The data is in format:
Action (String)
    Direction (String)
        Frame (int)
            X,Y (Point or int,int)

The usage is basically:
Point myPoint = data.get(action).get(direction).get(frame);
myPoint.x; // do something with x and y

I tried a this huge hashmap type of structure:
HashMaP<String, HashMap<String, HashMap<int, Point>>>

it works, but ugly and prone to errors.
I also tried splitting it into Classes, which works; but needs a lot of housekeeping code.
Anyone know what this data structure called, maybe I can google it.
Any suggestions?

A: implicit in "huge hashmap type of structure" is the relationship between entities:

*

*action is a String which indexes 'many' direction

*direction is a String which indexes 'many' frame

*frame is a number which indexes 'many' points

*Point is a structure

One simple approach might be to define a 'key' object containing 'action' 'direction' and 'frame' and use this in a Map structure e.g.
class PointKey {
    String action, direction;
    int frame;
    PointKey(String action, String direction, int frame { .. init etc etc }

...

depending on usage characteristics you will want either to override hashCode to provide some "reasonably" unique value based of the three-part key or else implement Comparable if you're expecting there to be a large amount of these values and you expect to be reading them more than writing them.
Then you define your Map thus:
Map<PointKey,Point> data = new HashMap<PointKey,Point>();

or
Map<PointKey,Point> data = new TreeMap<PointKey,Point>();

depending on which approach you have selected.
Another concern, if you are creating a large amount of these keys is the overhead of creating new keys to randomly access them, and in such a case you may like to use a flyweight e.g.
...
// PointKey instance that is retained and used again and again, purely for 'access' purposes
dataKey.setIdentifiers(myAction, myDirection, myFrame);
Point myPoint = data.get(dataKey)


text:
Q: You cannot add or remove an unsaved Parse Object from a relation I'm trying to add relation between my Place & User classes. But getting "You cannot add or remove an unsaved Parse Object from a relation" error. My code is like below.
var user = req.session.user;
var placeId = req.body.placeId;

var placeQuery = new Parse.Query('Place');
placeQuery.equalTo('objectId', placeId);
placeQuery.first()
.then(function (place) {
  place.increment('likeCount');
  var relation = place.relation('likes');
  relation.add(user);
  return place.save(null, {useMasterKey : true})
})
.then(function () {
  return next();
})
.then(function (error) {
  return res.status(500).send(error);
})


text:
Q: What is the maximum and minimum value that will validate for a HTML5 input type=number using android webkit? What is the maximum and minimum value that will validate for a HTML5 input type=number using android webkit ?
<input id="number" name="number" type="number" value="3.4028e+38" />

//does not validate
document.getElementById("number").value = Number.MAX_VALUE ;

A: Maximum Value that will validate is
var max = 3.40282346638528878701170117011496e+28;

Minimum Value that will validate is
var min = -3.40282346638528878701170117011496e+28;

Even if your input attribute max is set to 1.79e+308 it will only be able to validate up to this max number. Anyone know why that is ?


text:
Q: Unable to write over selected text on a input I'm unable to write over selected text on a input at Android 2.2.1.
The following example selects the input text but the maxlength property prevents from writing the new value.
If I remove the maxlength the new value is concatenated after the previous value.
Edit: If I use the click event instead of keyup the example works fine.

A: Try this
$( '#current1' ).keyup( function(e) {
    $( '#current2' ).focus();
    $( '#current2' ).selectRange( 0, 1 );
});

$.fn.selectRange = function(start, end) {
    var e = document.getElementById($(this).attr('id')); // I don't know why... but $(this) don't want to work today :-/
    if (!e) return;
    else if (e.setSelectionRange) { e.focus(); e.setSelectionRange(start, end); } /* WebKit */
    else if (e.createTextRange) { var range = e.createTextRange(); range.collapse(true); range.moveEnd('character', end); range.moveStart('character', start); range.select(); } /* IE */
    else if (e.selectionStart) { e.selectionStart = start; e.selectionEnd = end; }
};


text:
Q: pandas get the average and mode group by specified columns      rev_id  worker_id  toxicity  toxicity_score
0    2232.0        723         0             0.0
1    2232.0       4000         0             0.0
2    2232.0       3989         0             1.0
3    2232.0       3341         0             0.0
4    2232.0       1574         0             1.0
5    2232.0       1508         0             1.0
6    2232.0        772         0             1.0
7    2232.0        680         0             0.0
8    2232.0        405         0             1.0
9    2232.0       4020         1            -1.0
10   4216.0        500         0             0.0
11   4216.0        599         0             0.0
12   4216.0        339         0             2.0
13   4216.0        257         0             0.0
14   4216.0        303         0             1.0
15   4216.0        188         0             0.0
16   4216.0       1549         0             1.0
17   4216.0         64         0             1.0
18   4216.0       1527         0             0.0
19   4216.0       1502         0             0.0
20   8953.0       2596         0             1.0
21   8953.0       2403         0             0.0
22   8953.0       2539         0             0.0
23   8953.0       2542         0             0.0
24   8953.0       2544         0             0.0
25   8953.0       1016         0             0.0
26   8953.0       2550         0             0.0
27   8953.0       2578         0             0.0
28   8953.0       2494         0             0.0
29   8953.0        971         0             0.0

I want to get the mode number (either 1 or 0) from toxicity  and the mean from toxicity_score group by rev_id via pandas. How can I do this ?
Thanks.

A: It seems you need groupby with aggregate by agg mean and mode:
df = (df.groupby('rev_id', as_index=False)
        .agg({'toxicity_score':'mean', 'toxicity': lambda x: x.mode()}))

Alternative is value_counts with select first value of index:
df = (df.groupby('rev_id', as_index=False)
        .agg({'toxicity_score':'mean', 'toxicity': lambda x: x.value_counts().index[0]}))

print (df)
   rev_id  toxicity_score  toxicity
0  2232.0             0.4         0
1  4216.0             0.5         0
2  8953.0             0.1         0


text:
Q: Syntax error in my If Else statement in my VBA access code I have been working on this problem for a while and I'm close to the answer thanks to the help of stack overflow and google. Let me give you some insight. I have a table and 2 forms and a Key named CalibrationKey that auto increments as a Autonumber to keep track of the record and how many and what not. On 1 form are all my table fields. On my 2nd form is the Subfields to the first form that feed into the table. First form is Calibration and 2nd form is Calibration Detail. In my first form, I have it so you can edit OR add a new record(where my problem started). My 2nd form I have it so you can only add a new record and have the Data Entry on Property Sheet to YES as I only want you to be able to add a new record from that form.  So I made a If Else statement as a click event in my First Form that if my Text box is Empty, then you add a new record. If it is NOT empty, then you edit the form. But, I get a Syntax error every time I try and do this. I'm not sure what the problem is.
Private Sub Make_Click()
If Not IsNull(Make.Value) Then
DoCmd.OpenForm "Calibration Detail", , , "[CalibrationKey]= " & Me.[CalibrationKey], acFormAdd, acDialog
Else: DoCmd.OpenForm "Calibration Detail", , , "[CalibrationKey]= " & Me.[CalibrationKey], acFormEdit, acDialog
End If
End Sub

Then I found that a IsEmpty might be easier, but it gives the same Syntax error in the ELSE line of code as the Not IsNull line did.

Private Sub Make_Click()
If IsEmpty(Make.Value) Then
DoCmd.OpenForm "Calibration Detail", , , "[CalibrationKey]= " & Me.[CalibrationKey], acFormAdd, acDialog
Else: DoCmd.OpenForm "Calibration Detail", , , "[CalibrationKey]= " & Me.[CalibrationKey], acFormEdit, acDialog
End If
End Sub

Trying to diagnose the problem of the incorrect Syntax as Either IsEmpty or Not IsNull seems to give the same syntax error on the same line. Looking to correct the syntax error and which is function is better to use, rather it be IsEmpty, or Not IsNull

A: Try using the normal If-Then-Else syntax:
Private Sub Make_Click()

    Dim DataMode As acFormOpenDataMode

    If Me.Dirty = True Then
        'Save record.
        Me.Dirty = False
    End If

    If Not IsNull(Make.Value) Then
        DataMode = acFormOpenDataMode.acFormAdd
    Else
        DataMode = acFormOpenDataMode.acFormEdit
    End If
    DoCmd.OpenForm "Calibration Detail", , , "[CalibrationKey]= " & Me.[CalibrationKey], DataMode, acDialog

End Sub


text:
Q: OpenCV build support for Windows 8 ARM Has anyone succeeded in building OpenCV for ARM on Windows 8?
I am specifically interested in using OpenCV in Windows 8 apps for tablets.
This guy shows some face detection using OpenCV for Windows 8.  But I think it's on x86:
http://channel9.msdn.com/Events/TechEd/NorthAmerica/2012/DEV322


text:
Q: Update Tkinter from within an Exscript function I am writing a Python script that uses Exscript to log into network switches to gather information. I'm using Tkinter to present a graphical interface.
I'm trying to create a canvas window with status so that when the "go" button is clicked, the status windows is made visible and as the script logs into devices a label on the status window is updated (logging into device x of y).
I found the .update() and .update_idletasks(), which works when I enter the initial function (clicking the go button), but updating the label happens 2 functions deep in the Exscript start() function. In there anything I do to my canvas causes the script to hang and I have to force close it.
onhost = 0
hostcount = 0
def go_main():
 canvas.itemconfig(statuswindow, state='normal')
 canvas.itemconfig(statuslabel_window, state='normal')
 canvas.update()
 filename = InvEntry.get()
 accounts = [Account(unameEntry.get(), pwordEntry.get())]
 workbook = xlrd.open_workbook(filename)
 sheet = workbook.sheet_by_name("Infrastructure")
 global hostcount
 hostcount = sheet.nrows
 hosts = []
 for x in range (1, hostcount):
  hosts.append(conproto.get() + "://" + sheet.cell_value(x, 0))
 start(accounts, hosts, login_func)

def login_func(job, host, conn):
 global onhost
 global hostcount
 onhost = onhost + 1
 newstat = "Gathering MACs on switch %s of %s..." % (onhost, hostcount)
 stat.set(newstat)
 #canvas.update()
 conn.execute('term len 0') #We don't want a pause in the output
 conn.execute('sh ver') #Make sure we're a Nexus or Catalyst switch before continuing
 r = conn.response
 if r != '' and ('nx-os' or 'catalyst') in r.lower():
  #Grab the device's hostname:

As soon as it hits the "stat.set(newstat)" line it hangs. What am I doing wrong? Sorry if I slaughtered all the programmer lingo, I'm a network engineer pretending to be a programmer. Thanks!


text:
Q: javascript google maps api combined with angular 2 google maps api Specifically is it at all possible to use both javascript(developers.google.com documentation)
and angular 2 google map (SebastianM : angular2-google-maps) in tandem.
Reason being angular 2 google maps at a very early stage and events are not totally there e.g.map marker right click.
Would also like to know if this affect other possible fields that draw from my angular 2 marker array, will i still be to do data binding.


text:
Q: calling subset of an array to calculate autocorrelations in excel vba I would like to calculate an array's auto-correlation so need to access two subsets of the array (one with a lag) . Here's my code:
Option Base 1
Sub test()

Dim intPerNum As Integer
intPerNum = 10
Dim dblMRet() As Double
ReDim dblMRet(intPerNum)
Dim intPerCntr As Integer

Rnd (-2)
For intPerCntr = 1 To intPerNum
    dblMRet(intPerCntr) = WorksheetFunction.NormSInv(Rnd(1))
    Range("TesterTest").Offset(0, intPerCntr) = dblMRet(intPerCntr) 'for debugging
Next intPerCntr

With WorksheetFunction
  Range("Output") = .Covar(.Index(dblMRet,0,1):.Index(dblMRet,0,intPerNum-1),.Index(dblMRet,0,2):.Index(dblMRet,0,intPerNum)) / .Var(dblMRet)
End With

End Sub

I can't use ":" to access a subset of the dblMRet array in VBA so that line does not work. What's a good way of doing this instead?  I do not want to make this calculation on an Excel worksheet since I do not want to output the array's actual values. Thanks.

A: Got the answer here: http://answers.microsoft.com/en-us/office/forum/office_2010-excel/how-to-access-subset-of-an-array-in-excel-vba/c74765e5-b57e-423f-b9d4-0935ef9674e3?tm=1379435289782
Instead of using ":" in VBA, you can accomplish the same thing by using Evaluate inside the Index function. Works beautifully.
If you need to use variables inside Evaluate, you can just concatenate strings by using &.
For example, instead of using:
Range("Output") = WorksheetFunction.Average(WorksheetFunction.Index(MyArray, 1, Evaluate("ROW(1:3)")))
I can use:
Range("Output") = WorksheetFunction.Average(WorksheetFunction.Index(MyArray, 1, Evaluate("ROW(1:" &(intPerNum-1) &")")))


text:
Q: Voice to text - Alexa Voice Service I'm trying to make an android app which uses Alexa voice service to translate voice to text.A simple mic and text box app.
I'm new to android and need deep instructions to understand.

A: You cannot get the voice to text conversion from Alexa ..However you can try the below library and understand the Alexa features.
https://github.com/willblaschko/AlexaAndroid
You can try the below sample for voice to text using android framework component and you dont need internet for it to work in the application its an offline recognition engine.
http://www.androidhive.info/2014/07/android-speech-to-text-tutorial/


text:
Q: Can't remove LVM thinpool - unable to deactivate tdata, tmeta I somehow messed up some thinly provisioned lvm volumes on ubuntu 14.04 and now I want to start fresh by deleting the thinpool with all its volumes and data inside. Unfortunatelly this failes and I can't find a solution.
The logical volumes look like this:
user@server1:~$ sudo lvs
  dm_report_object: report function failed for field data_percent
  LV             VG   Attr      LSize   Pool       Origin Data%  Move Log Copy%  Convert
  project2       vg0  Vwi-i-tz-  22.00g mythinpool
  project1       vg0  Vwi---tz-  20.00g mythinpool
  project3       vg0  Vwi---tz-  21.00g mythinpool
  home           vg0  -wi-ao--- 140.00g
  mythinpool     vg0  twi-i-tz-  78.82g                    52.15
  root           vg0  -wi-ao---  10.00g
  swap           vg0  -wi-ao---   4.00g
  tmp            vg0  -wi-ao---   5.00g

Now I want to remove the thinpool with the three lvms inside:
sudo lvremove /dev/vg0/mythinpool

Removing pool mythinpool will also remove 3 thin volume(s). OK? [y/n]: y
Do you really want to remove and DISCARD logical volume project1? [y/n]: y
  device-mapper: message ioctl on  failed: Invalid argument
  Unable to deactivate open vg0-mythinpool_tdata (252:5)
  Unable to deactivate open vg0-mythinpool_tmeta (252:4)
  Failed to deactivate vg0-mythinpool-tpool
  Failed to resume mythinpool.
  Failed to update thin pool mythinpool.

I don't care about the data inside mythinpool, but the rest of the volume group vg0 MUST stay intact. How could I solve this problem? Thank you for any help on this.
EDIT 1:
After following the answer from shodanshok I was able to remove one LVM-Image by booting into CentOS7, but unfortunatelly the other two volumes including thin pool return another error message - transaction_id mismatch:

There is also no space available for lvconvert --repair

A: I finaly solved it very with some simple steps as described here: remove corrupt LVM thin pool
vgcfgbackup -f  vg.bak   vgname

//edit vg.bak and remove all thinp related volumes

vgcfgrestore -f vg.bak  vgname

After following the advice from @shodanshok to boot into Live CentOS7 sticked to the server on an USB stick, I was able to issue the described commands and to eventually get rid of the corrupt thin pool without damaging the root file system that resides inside the same volume group.
Thank you everybody for your helpful advice that led eventually to the solution.

A: Something is keeping your thin volumes opened. Please do the following:

*

*check if the volumes are mounted. If so, unmount them

*if you can not unmount them, maybe some files are still opened by a running process. You can use lsof | grep mountpoint to find the offending processes. Kill them and try to unmount the filesystems

*if this fails, reboot the machine and try to unmount the filesystems related to the thin volumes

*if you still can't unmount the volumes, try to reboot into single user mode, unmount them and delete the volumes

*if all else fails, use a live CD/USB image to boot your PC and remove the offending volumes.

EDIT:
As you can't use a live image and your rescue system has no thin-volume support, we can try an alternate route. Basically, we will set the "skip activation flag" on your thin volumes/pool and reboot the machine. Follow these steps:

*

*set activation skip: lvchange -ky vg0/project1 ; lvchange -ky vg0/project2 ; lvchange -ky vg0/project3 ; lvchange -ky vg0/mythinpool

*reboot the machine and the volumes should be inactive

*you can now remove them with lvremove
However, if any of these volumes are needed for machine boot you will end with an unbootable machine. Be sure to have a "plan B" to restore the machine via a recovery console or such.
EDIT 2
If your system does not support the -k flag, you can try using lvchange -aay volumename and reboot. This will set the volume for autoactivation, which only works for volumes specified on /etc/lvm.conf


text:
Q: how to make compound index for multiple column range queries I want to make a range query on multiple columns. for example:
db.dmnscore.find({price:{$lte:10}, "updated" : {"$gte" : new
Date(1304874799000)} ,"score" : {"$gte" : 0,"$lte" :
1000}).sort({score:-1})
Is it possible to make a proper compound index for this query?
Thanks

A: The easiest thing is to test it yourself. Create an index on the properties, then run this query:
db.dmnscore.find({price:{$lte:10}, "updated" : {"$gte" : new Date(1304874799000)} ,"score" : {"$gte" : 0,"$lte" : 1000}).sort({score:-1}).explain()

notice the explain() on the end. If the result contains Btree you're good, if the result contains BasicCursor it hasn't used the index.


text:
Q: Read a file from JQuery inside AngularJS Hi I'm a beginner at programming. I'm trying to put data from a json file into a variable
I want to have AngularJS put text into a html document like this
{{ data.text }}

And the text is based off of a json file I have in the app.js, so I set data using JQuery:
myApp.controller('Ctrl', function ($scope, $http) {
 $.getJSON("../static/file.json", function(data) {
   $scope.data = data;
 });

But nothing shows up initially. When I log $scope.data, it turns out to be undefined. But I know that my json file is correct because if I put all this code in some method that is called like
$scope.foo = function(){$.getJSON("../static/file.json", function(data) {
       $scope.data = data;
     });}

and have some button activate this, it'll work fine. But I want this to be there initially.

A: try
$.getJSON("/static/file.json", function(data) {
   $scope.data = data;
});

then it load file from web http://xxx/static/file.json, not file system.


text:
Q: Is this the fastest way to do Multi processing in Python I am using this
def processImage(i):
      # Load image
      # Predict on the image using Machine learning model that uses GPU
      # Print the result

p=mp.Pool(3) #Define Number of Process to Use
p.map(processImage,range(len(filesToProcess))) # Call the Download Image funciton
p.close() #Close the multi threads
p.join()

I wonder, how can I speed this up? This multi process code is not 3x faster than one process code. I know there will be some overhead, but how can  I reduce those?


text:
Q: Detectar TR clicada passar por função REACT Como detectar a TH que eu cliquei e passar por parametro no React?
Queria fazer uma ordenação, mas estou com dificuldades de passar por parametro em uma função a TH que eu cliquei, alguém pode me ajudar com isso?
ordertableBy = async(ev) => {
    console.log(ev.target.value);
    alert('orderby' + ev.target.value);
}

     this.ordertableBy(ev)}>Nome
     this.ordertableBy(ev)}>Email
     this.ordertableBy(ev)}>Telefone

Tá retornando orderby undefined

A: De forma muito simples pode fazer assim
 this.ordertableBy("headerNome")}>Nome
 this.ordertableBy("headerEmail")}>Email
 this.ordertableBy("headerTelefone")}>Telefone

pelo que o seu ordertableby ficaria simplesmente
ordertableBy = async(value) => {
    console.log(value);
    alert('orderby' + value);
}

Caso queira utilizar o evento, seria algo do genero
 this.ordertableBy(ev)}>Nome
 this.ordertableBy(ev)}>Email
 this.ordertableBy(ev)}>Telefone

ordertableBy = async(ev) => {
    console.log(ev.target.value);
    alert('orderby' + ev.target.value);
}

PS: Normalmente usa-se  e não  quando se trata do cabeçalho da tabela


text:
Q: Firebug doesn't show JSON tab in console I am debugging my javascript code (below).
The webgrid is populated after a user has clicked the search button. I have added a button to the webgrid which opens a dialog that has to be populated with values from a JSON object.
This is where the problem is - when I debug using firebug the JSON tab in the console is not shown.
Below is the part of my code:
 $('.edit-recipients').live('click', function ()
           {
               $.getJSON('/Methods/GetRecipients/' + $(this).attr('id'), function (data)
               {
                   var recipient = data;
                   console.log(recipient);
               $('#edit-opno').val(recipient.OpNo);

Console.log(recipient) shows the values from my GetRecipients method.
This code  $('#edit-opno').val(recipient.OpNo); is meant to show the value in my input text where I have this code below.
<input type="text" name="opno" id="edit-opno" size="15" />

However at first I thought the GetRecipients was not executed but from firebug realized it is executed with console.log(recipients) showing the values but no JSON tab, hence failing to populate my dialog input box.
Below is my server side code:
@{
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    if(UrlData[0].IsInt()){
        var db = Database.Open("sb_cpd");
        var sql = "SELECT * FROM cpd_recipients WHERE ID = @0";
        var recipients = db.QuerySingle(sql,UrlData[0]);
        Json.Write(recipients, Response.Output);
    }
}

I have inserted an image of whats happening. Notice my dialog is not populated with values from GetRecipients method.

A: You should set the header content-type to application/json. Firebug will then recognize the response as JSON:
@{
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    if(UrlData[0].IsInt()){
        var db = Database.Open("sb_cpd");
        var sql = "SELECT * FROM cpd_recipients WHERE ID = @0";
        var recipients = db.QuerySingle(sql,UrlData[0]);
        Response.Headers.Add("Content-type", "application/json");
        Json.Write(recipients, Response.Output);
    }
}


text:
Q: Multiple floating IPs I am configuring Squid with High Availability. I want the setup with below conditions

*

*Two squid proxy servers (siblings) with one IP address each

*Both the servers in active passive HA cluster with floating IP

*More than one floating IP assigned to cluster and used in round robin fashion as per requests coming in from clients

*Squid proxy forwarding requests to "Force Point" proxy server(master/parent proxy server).

I am able to achieve point numbers 1, 2 and 4 with Squid, corosync and pacemaker.
However, I am not able achieve point number 3, on how to add additional floating IP for the cluster. Any leads to achieve this?

A: You can perform it only if your cluster is on same VLAN. If it is you can do following steps to achieve point 3:

*

*Set up a DHCP server. There are many packages for that and configure it in a random behavior of giving IP in Round Robin Fashion. You can use DNSMASQ.

*Put all the cluster IPs on interface of each server.

*Add the iptables rule to route the traffic from the specifec ip received from DHCP and delete the old one.
Sample rule for iptables:
iptables -t nat -A POSTROUTING -m statistic -j SNAT --to-source DHCPIP

IP_received_from_DHCP # For ADDING


text:
Q: Using exports module in node I am creating a small project in node, i have routes of two tables, drums and pianos in same file named routes.js in two different function called drums() for drums and pianos() for pianos. i have exported both functions and both of them return router. Router is return value of express.Route() class.
I have used these two functions in index.js file by importing, i am accessing route by following code
app.use('/pianos', routes.pianos());
app.use('/drums', routes.drums());

But i am getting response from only one function, if i keep
app.use('/pianos', routes.pianos());

at first then i get list of pianos with url localhost/pianos and localhost/drums as well and if i keep
app.use('/drums', routes.drums());

at first then i get list of drums with url localhost/drums and localhost/pianos as well. What is mistake here?
const express = require('express');
const router = express.Router();
const joi = require('joi');

function drums(){
    drums = [
        {id:1, name:'Bongo drum'},
        {id:2, name:'Bass drum'},
        {id:3, name:'Ashiko'},
        {id:4, name:'Basler drum'},
        {id:5, name:'Cajón'}
    ];

    router.get('/', (req, res)=>{
        res.send(drums);
    });
    router.get('/:id', (req, res) =>{
        const drum = drums.find( c=> c.id === parseInt(req.params.id));

        if(!drum){
            return res.status(404).send("Error: Drum is not available");
        }
        res.send(drum.name);
    });
    router.post('/', (req, res)=>{
        const {error} = validator(req.body);
        if(error) return res.status(400).send('Eror 400: Bad request', error.details[0].message);

        const drum = {id:drums.length+1, name:req.body.name};

        drums.push(drum);
        res.send(drum);
        }
    );
    router.put('/:id', (req, res)=>{
        const drum = drums.find(c=> c.id === parseInt(req.params.id));
        if(!drum) return res.status(404).send('Error: Drum is not available');

        const {error} = validator(req.body);
        if(error) return res.status(400).send('Error 400: Bad request', error.details[0].message);

        drum.name = req.body.name;
        res.send(drum);
    });
    return router;
}

function pianos(){
    const pianos = [
        {id:1, name:'Yamaha U1'},
        {id:2, name:'Roland RD-2000'},
        {id:3, name:'Nord Piano 4'},
        {id:4, name:'Yamaha NU1X'},
        {id:5, name:' Dexibell Vivo S7'}
    ];

    router.get('/', (req, res)=>{
        res.send(pianos);
    });

    router.get('/:id', (req, res)=>{
        const piano = pioanos.find(c=> c.id === parseInt(req.params.id));
        if(!piano) return res.status(404).send('Error:The piano is not available');

        res.send(piano);
    });

    router.post('/', (req, res)=>{
        const {error} = validator(req.body);
        if(error) return res.status(400).send('Error-Bad request', error.details[0].message);

        const piano = {id:pianos.length+1, name:req.body.name};

        pianos.push(piano);
        res.send(piano);
    });

    router.put('/:id', (res, req)=>{
        const piano = pioanos.find(c=> c.id === parseInt(req.params.id));
        if(!piano) return res.status(404).send('Error: Piano is the available');

        const {error} = validator(req.body);
        if(error) return res.status(400).send('Error:Bad request', error.details[0].message);

        piano.name = req.body.name;
        res.send(piano);
    });
    return router;
}

function validator(instrument){
    const schema={
        name:joi.string().min(5).required()
    };
    return joi.validate(instrument, schema);

}

module.exports.drums = drums;
module.exports.pianos = pianos;

MY index.js file is like this:
    const mongoose = require('mongoose');
    const express = require('express');
    const app = express();
    const debug = require('debug')('pm:index');
    const routes = require('./routes/routes');

    mongoose.connect('mongodb:localhost/planetmusic')
        .then(()=> debug('Connected to database'))
        .catch(err => debug('Error!!Could not connect to database', err.message));

    app.use(express.json());
    app.use(express.urlencoded({extended: true}));
    app.use(express.static('public'));

    app.use('/drums', routes.drums());
    app.use('/pianos', routes.pianos());

    const port = process.env.port || 5000;
    app.listen(port, ()=> console.log(`listening at port: ${port}`));

If there are other better solution to manage my all routes then please help me.

A: taken that we should separate concerns, I would recommend split everything into files, it is easier to maintain and to add features in the future as everything is in it's own place...
in a NodeJs project, it is normal to encounter, in examples, some folder rearrangement, and I would suggest this:
.
├── package.json
└── server/
    ├── server.js
    └── routes/
        ├── drums.js
        ├── index.js
        └── piano.js

here is a very simple example, so you can understand how ExpressJs routes work when spread out upon multiple files:
server.js content
const express = require('express');

const routes = require('./routes');
const app = express();

const PORT = 5001;

app.use('/drums', routes.drums);
app.use('/pianos', routes.pianos);
app.use('/', (req, res) => { res.send({ action: 'default get' }); });

app.listen(PORT, () => {
    require('./utilities/api-table')(app._router.stack);
    console.log(`ready on http://localhost:${PORT}`);
});

server/routes/index.js content
const fs = require("fs");
const path = require("path");

const routing = {};

fs.readdirSync(__dirname) // read all files in this directory
  .filter(
    file =>
      // only read .js files, but not the index.js (this file)
      file.indexOf(".") !== 0 && file !== "index.js" && file.slice(-3) === ".js"
  )
  .forEach(file => {
    const filename = file.replace(".js", "");
    // attach the routes in it's own filename
    routing[filename] = require(path.join(__dirname, file));
  });

module.exports = routing;

drums.js and pianos.js content are exactly the same, just the "drums" and "pianos" change so we know we are reading from the correct file...
const express = require('express');

const router = express.Router();

const getAll = (req, res) => {
    res.send({ action: 'GET all drums' })
};
const create = (req, res) => {
    res.send({ action: 'POST drums', data: res.body })
};
const getById = (req, res) => {
    res.send({ action: 'GET drums by id', id: req.params.id })
};
const editById = (req, res) => {
    res.send({ action: 'PUT drums by id', id: req.params.id })
};
const deleteById = (req, res) => {
    res.send({ action: 'DEL drums by id', id: req.params.id })
};

router.get('/', getAll);
router.post('/', create);
router.get('/:id', getById);
router.put('/:id', editById);
router.delete('/:id', deleteById);

module.exports = router;

when you fire up the server up, you will get all this routes:

and output as

full project (though it's very simple) can be found on GitHub


text:
Q: Implementing Redux-Saga with configureStore My first time attempting to implement redux-saga with configureStore. The following is my store:
//LOCAL
import { rootSaga } from "./saga"
import { reducer } from "./reducers"
//GLOBAL
import {configureStore} from "@reduxjs/toolkit"
import createSagaMiddleware from "redux-saga"
import logger from "redux-logger"

//create Middleware
const sagaMiddleware = createSagaMiddleware()
sagaMiddleware.run(rootSaga)

const store = configureStore(
    {
        reducer: reducer,
        middleware: [sagaMiddleware, logger]
    }

)

export default store

I'm getting the following error:
Before running a Saga, you must mount the Saga middleware on the Store using applyMiddleware
at Function.sagaMiddleware.run

Which makes sense since I've run the middleware before applying it to the store. However, when I place it after the configureStore call, I get:
Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app

I've gotten this error before, and I don't believe it, since it just seems to crop up for various different issues. So what exactly am I doing wrong here?
Any help is appreciated, thanks!

A: I found the answer here: https://stackoverflow.com/a/69242812
I had a similar issue; I fixed this by running npm install react-redux redux . Try it.

It apparently had nothing to do with my code but rather I didn't have the proper packages installed. Hope this can help someone else one day!


text:
Q: Fail to submit spark job I am trying to run the Spark-solr Twitter example with spark-solr-3.4.4-shaded.jar,
bin/spark-submit --master local[2]  \  --conf "spark.driver.extraJavaOptions=-Dtwitter4j.oauth.consumerKey=?
-Dtwitter4j.oauth.consumerSecret=? -Dtwitter4j.oauth.accessToken=? -Dtwitter4j.oauth.accessTokenSecret=?" \  --class com.lucidworks.spark.SparkApp \  ./target/spark-solr-3.1.1-shaded.jar \  twitter-to-solr -zkHost localhost:9983 -collection socialdata

but it is failed and the following message is shown
INFO ContextHandler: Started o.e.j.s.ServletContextHandler@29182679{/metrics/json,null,AVAILABLE,@Spark}
Exception in thread "main" java.lang.NoSuchMethodError: org.apache.spark.SparkContext.jobProgressListener()Lorg/apache/spark/ui/jobs/JobProgressListener;

I can confirm the path for ./target/spark-solr-3.1.1-shaded.jar is correct.
I suspect there is something wrong in --class com.lucidworks.spark.SparkApp  (ClassPath), but I am not sure.
I am running on local mode and I change the parameters as instructed in the example.
Version:

*

*Spark 2.1.1

*Spark-solr 3.1.1

*Solr 6.6.0


text:
Q: How to use a custom comments template My wordpress makes use of custom post templates. I'm now trying to create a custom comments template as well.
I noticed that the comments template is called via this function
<?php comments_template( '', true ); ?>
I checked in my functions.php and comments.php but don't see the function being declared anywhere. Can someone please advise on how to go about introducing a custom comments template?

A: The comments_template() template tag sets up the commenting variables and functions, and includes the comments.php template-part file. So, to create a custom comments template, use comments.php.
From there, you will need to get comfortable with the arguments, filters, and callbacks for wp_list_comments(), which is used to output the comment list, and comment_form(), which is used to output the comment-reply form.

A: You can use the callback function on wp_list_comments() function.
wp_list_comments();

Usually, you will find this line in comments.php file of your wordpress theme. And the output from this command is a pretty straightforward HTML structure.
Wordpress have a option of passing the callback function as an argument to wp_list_comments function.
This callback function should return the modified HTML structure of comments section, which we are looking to implement.
<ul class="comment-list comments">
    <?php
    wp_list_comments( array(
        'style'      => 'ul',
        'short_ping' => true,
            'callback' => 'better_comments'
    ) );
     ?>
</ul><!-- .comment-list -->

You can check detailed tutorial here
https://www.5balloons.info/custom-html-for-comments-section-in-wordpress-theme/


text:
Q: Unordered and repeating indexes in pandas dataframe x test X train y train We are currently doing a project on indoor positioning system. We are currently using KNN for predicting the positions.
The code written is as follows
# Function to return the list of distances of the test records from train records
def distNeighbours(X_train,Y_train,X_test,K):
    distance=[]
    for i in range(len(X_train)):
        eDistance=0
        for j in range(len(X_train.columns)):
                eDistance+=round(np.sqrt(pow((X_train.iloc[i,j]-X_test[j]),2)),2)
        distance.append((eDistance,i,Y_train.iloc[i]))
        distance=sorted(distance, key=lambda x: x[0])[0:K]
    return distance
def predictOutputNumeric(X_train,Y_train,X_test,K):
    neighbours=[]
    responses=[]
    for i in range(len(X_test)):
        neighbours.append(distNeighbours(X_train,Y_train,X_test.iloc[i,:],K))
    for i in neighbours:
        mean=0
        for j in i:
            mean+=j[-1]
        mean=mean/K
        responses.append(mean)
    return responses

When the Test data is double labeled, we get a output as a list of pandas series which when converted to dataframe we got index values which are unordered and some are repeating. We are still not aware which part of the code has mistake as the index is confusing.
Output which we are getting
Sample data which we are using


text:
Q: Read from stdin or file in single stagment in ruby I have this code
if filename
  begin
    if filename == '-'
      ARGF.each{|url|
        begin
          check(url)
        rescue Timeout::Error, Errno::ETIMEDOUT
          puts "Timeout Error, try again"
          redo
        end
      }
    else
      File.open(filename) {|file|
        file.each{|url|
          begin
            check(url)
          rescue Timeout::Error, Errno::ETIMEDOUT
            puts "Timeout Error, try again"
            redo
          end
        }
      }
    end
  rescue Interrupt, Errno::EINTR
    exit(1)
  end
end

But I don't want repeated code for stdin and file, how can I rewrite it?

A: You can pull out your repeated code into a method and call that on ARGF or file as they respond to the same methods.
def do_check(to_check)
  to_check.each do |url|
    begin
      check(url)
    rescue Timeout::Error, Errno::ETIMEDOUT
      puts "Timeout Error, try again"
      redo
    end
  end
end

Then your example becomes:
if filename
  begin
    if filename == '-'
      do_check(ARGF)
    else
      File.open(filename) do |file|
        do_check(file)
      end
    end
  rescue Interrupt, Errno::EINTR
    exit(1)
  end
end

I've used do ... end rather than {} simply because I find it easier to read.

A: Try using $< special variable: http://ruby.wikia.com/wiki/Special_variable


text:
Q: Customising hg log output (Mercurial newbie)
I'm trying to get hg log to give me the full changeset description, but without the file listing given by the -v option. Basically, I want the default output but with the full description rather than just the first line.
I've played about with templates, but can't see a way to do what seems like it should be a very simple change. Am I missing a built-in solution?

A: hg log --template ... or ... --style ...
with hand-made template or style.
Just write it
PS: Hint - use {desc} keyword

A: I don't think what you want is built in, but the log is formatted so:
Powershell:
hg log -v | where {$_ -notmatch "files:"}

*Nix:
hg log -v | grep -v "files:"

achieves what you want I think.


text:
Q: Laravel: Contract file is not instantiable while building Controller I am trying to add a shopping cart function to my Laravel application. I installed darryldecode/laravelshoppingcart package from GitHub and have been following instructions in these two websites.
TECHPOOL-Create a Shopping Cart with Laravel 6
LARASHOUT-Laravel E-Commerce Application Development – Checkout
I was able to create most of the shopping cart function with the first website but it didn't cover checkouts and placing orders so I found the second website.
The problem is that the contract file is not working. Here is the error I got.

Illuminate\Contracts\Container\BindingResolutionException
Target [App\Contracts\OrderContract] is not instantiable while building [App\Http\Controllers\CheckoutController].
http://localhost:8000/checkout

Where I use the contract file is in the checkout process witch is explained in the second website. I made few changes in the codes so that it will be consistent with the first website but mostly I followed what the website says.
Here are the codes that are mentioned in the error.
OrderContract.php
<?php

namespace App\Contracts;

interface OrderContract
{
    public function storeOrderDetails($params);
}

CheckoutController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Contracts\OrderContract;
use App\Http\Controllers\Controller;

class CheckoutController extends Controller
{
    protected $orderRepository;

    public function __construct(OrderContract $orderRepository)
    {
        $this->orderRepository = $orderRepository;
    }

    public function getCheckout()
    {
        return view('checkout');
    }

    public function placeOrder(Request $request)
    {
        // Before storing the order we should implement the
        // request validation which I leave it to you
        $order = $this->orderRepository->storeOrderDetails($request->all());

        dd($order);
    }
}

OrderRepository.php
<?php

namespace App\Repositories;

use Cart;
use App\Models\Order;
use App\Product;
use App\Models\OrderItem;
use App\Contracts\OrderContract;

class OrderRepository extends BaseRepository implements OrderContract
{
    public function __construct(Order $model)
    {
        parent::__construct($model);
        $this->model = $model;
    }

    public function storeOrderDetails($params)
    {
        $order = Order::create([
            'order_number'      =>  'ORD-' . strtoupper(uniqid()),
            'status'            =>  'pending',
            'grand_total'       =>  Cart::getSubTotal(),
            'item_count'        =>  Cart::getTotalQuantity(),
            'table_number'      =>  $params['table_number'],
            'name'              =>  $params['name'],
            'notes'             =>  $params['notes']
        ]);

        if ($order) {

            $items = Cart::getContent();

            foreach ($items as $item) {
                // A better way will be to bring the product id with the cart items
                // you can explore the package documentation to send product id with the cart
                $product = Product::where('name', $item->name)->first();

                $orderItem = new OrderItem([
                    'product_id'    =>  $product->id,
                    'quantity'      =>  $item->quantity,
                    'price'         =>  $item->getPriceSum()
                ]);

                $order->items()->save($orderItem);
            }
        }

        return $order;
    }
}

RepositoryServiceProvider.php
<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Contracts\OrderContract;
use App\Repositories\OrderRepository;

class RepositoryServiceProvider extends ServiceProvider
{
    protected $repositories = [
        OrderContract::class            =>          OrderRepository::class,
    ];

    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        foreach ($this->repositories as $interface => $implementation) {
            $this->app->bind($interface, $implementation);
        }
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
}

I'm not really familiar with the contract concept since I only started learning Laravel recently and I'm completely lost here. Maybe the problem is that I haven't created another file that is necessary or maybe something else.
Any help would be appreciated as I have tried multiple methods with no success.
Thank you in advance.

A: Yes, this is expected...your contract should point to a Solid class else it's going to fail while trying to resolve it out of the container. So this is what you should do:

*

*Create a class that implements that trait.

*Go to your AppServiceProvider and bind it to that contract like this:
class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
        $this->app->bind(\App\Contracts\OrderContract::class, App\Repositories\ClassImplementingOrderContract::class);
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
}

this should fix your problem.

A: This error could caused even if you have forget to add "RepositoryServiceProvider" into "config/app.php" 's serviceProviders array.


text:
Q: Jquery click is not working on dynamically added table tr via PHP I am getting data from my database and displaying it on my HTML via php echo. Now I need to put a click function on specific tr with id breakrow, but this click function is not working. I am using .on function as suggested in documentation for dynamically added content. Also I dont see any error in console also.
Here is the sample code. (When I add same code directly into html page, its working as expected)
PHP Part:
echo '

                  customer
                  product
                  thedate
                  value

customer 01

customer 01	product 01	30 10 2017	974.57

customer 01	product 02	04 12 2017	634.50

customer 01	product 03	30 10 2017	974.57

customer 01	product 04	04 12 2017	634.50

customer 02

customer 02	product 01	04 12 2017	634.50

customer 02	product 02	30 10 2017	974.57

customer 03

customer 03	product 01	30 10 2017	974.57

customer 03	product 02	04 12 2017	634.50

customer 03	product 03	30 10 2017	974.57

';

Jquery:
$( document ).ready(function() {

    $('#tableMain').on('click', 'tr.breakrow',function(){
        $(this).nextUntil('tr.breakrow').slideToggle(200);
    });
});

can someone guide me how to resolve this ?

A: When loading content using ajax the script needs to bind the dynamically added content so you can use below script which can take effect on dynamically loaded data.
$(document).on('click', 'tr.breakrow', function(){
    $(this).nextUntil('tr.breakrow').slideToggle(200);
});

A: your click function is not working because jQuery is running on client side and php is running on server side so when the script executed it will not find the particular ID because the table is rendering via php.
This is done by event delegation. Event will bind on wrapper-class element but will be delegated to selector-class element. This is how it works.
$('.wrapper-class').on("click", '.selector-class', function() {
    // Your code here
});

Note:
wrapper-class element can be anything ex. document, body or your wrapper. Wrapper should already exist.

A: When adding the dynamic content or add other elements after the window loaded or any ajax data, In this condition static click $(element).click(function(){}) is't work, You must bind the target element with document, Here the example:
$(document).on('click', 'your target element', function(){
    //your code here......
});

_ - - - - - - _
Thank you
_ - - - - - - _

A: You do not need to pass second argument on click event.working code is as per below.Here i just alert on click,you have to put your custom code in place of alert.
$( document ).ready(function() {
    $('#tableMain tr.breakrow').on('click',function(){
       alert('toggle');
     });
});

Click Here for working example in jsfiddle.


text:
Q: Android IAP acknowledgedState =1 after subscription expire
*

*I have been testing subscriptions with android IAP.

*When i let a subscription run it's course (six 5-minute intervals) the subscription expires as expected

*When i repurchase the subscription, the acknowledgedState = 1 during verification before acknowledging the subscription.

*although this new sub purchase's acknowledgeState = 1, the subscription is not recognized as such on my device and the subscription inevitably reverts.

*When i cancel the subscription, then wait a while (30-60 minutes at least), the acknowledgeState = 0 and i am able to then acknowledge the purchase and finish the transaction successfully.


text:
Q: How do I determine the likelihood of a single measurement coming from a known distribution? I have a set of 2000 numbers that form an approximately normal distribution, with a mean of about 0.24, and an SD of 0.06.  These form an estimate of the population.  I now have a single sample measurement of 0.38 and would like to determine the chance (p value) that this single sample measurement comes from the same population distribution.  (Unfortunately, in my work the nature of the "test" means that it is unfortunately theoretically impossible to obtain another measurement).
It must be true that the further that the single sample is from the mean of the population, the more unlikely that single event is.  Furthermore, of course one needs to take into account the distribution of the population - had the SD of the population been 6 rather than 0.6 the chance of obtaining the single measurement at 0.38 would be much higher, and hence the p value lower.  I am happy to assume for my purposes that the distribution from which the sample has been obtained would have the same SD as the population.
The question is how I calculate the likelihood (p-value) that the observed single sample comes from a distribution with the same mean as the population?
I have thought about carrying out a one sample t-test, testing whether the observed population is different from the single sample value, but that doesn't seem right to me as that test assumes that the single sample value is the mean of the distribution being tested against, rather than a single sample.
What is the best approach to this analysis?
Thanks in advance for any advice and help.

A: The question for a p-Value of one measurment is an interesting topic. However, you flips the meaning of the p-Value. You are asking for a p-Value that the sample measurement is drawn from the previously measured distribution. But you can only ask for a p-Value that you can reject your starting hypothesis.
For calculating the p-value commonly you are looking for the frequency that experiments result in a result more extreme (or more of the expected) than your actual result, when you repeat the experiment a lot,
Comparing one measurement to the distribution, which is a gaussian means in this sense, you have to get the area of the probability density function below 0.10 and above 0.34. Why I am looking for both sides is as when thinking in extremes lower and higher values are equal extreme.
Finally this gives a p-Value


text:
Q: Verilog: "Unspecified I/O standard" and "Poor placement for routing between an IO pin and BUFG" Errors I am fairly new to Verilog and FPGA development. I am currently working on a project to control two motors using a Basys 3 board and an H bridge.
The module is currently built to use PWM to control the motor speed, sending the output to the ena and enb pins on the H-Bridge. The H inputs are currently constant for the sake of testing the PWM control.
Well long story short I have run into a variety of I/O errors that I just haven't been able to fully wrap my head around.
Here is my primary module:
module RDrive(
    input clock,
    input BUTTON,
    input H1, H2, H3, H4,
    output ena, enb
    );

    wire clock, BUTTON, H1, H2, H3, H4;

    reg[1:0] speed;
    reg[3:0] counter, width;
    reg PWMtemp;

    wire ena, enb;

    // initial values
    initial begin
        counter <= 4'b0000;
        speed = 0;
        PWMtemp <= 0;
        width <= 0;
    end

    // Every button press increments speed value
    always @ (posedge BUTTON)
    begin
        speed <= speed + 1;
        // width adjusted for PWM module
        case (speed)
            2'b00 : width <= 4'b0000;
            2'b01 : width <= 4'b0101;
            2'b10 : width <= 4'b1010;
            2'b11 : width <= 4'b1111;
            default : width <= 4'b0000;
        endcase
    end

    // PWM
    always @ (posedge clock)
    begin
        if (counter < width) PWMtemp <= 1;
        else PWMtemp <= 0;
        counter <= counter + 1;
    end

    assign ena = PWMtemp;
    assign enb = PWMtemp;

endmodule

Here is my test bench:
module RDrive_TB(

    );
    reg clock;
    wire ena = 0;
    wire enb = 0;
    reg BUTTON, H1, H2, H3, H4;

    initial begin
        BUTTON = 0;
        clock = 0;
        // H values for testing PWM speed control
        H1 = 1;
        H2 = 0;
        H3 = 1;
        H4 = 0;

        // Simulating button presses
        #1000;
        BUTTON = 1;
        #10;
        BUTTON = 0;

        #1000;
        BUTTON = 1;
        #10;
        BUTTON = 0;

        #1000;
        BUTTON = 1;
        #10;
        BUTTON = 0;

        #1000;
        BUTTON = 1;
        #10;
        BUTTON = 0;

    end

    // clock generator
    always begin
        #1 clock = ~clock;
    end

    RDrive RDriveTest(clock, BUTTON, H1, H2, H3, H4, ena, enb);

endmodule

and here are my constraints:
set_property PACKAGE_PIN W5 [get_ports CLK100MH]
set_property IOSTANDARD LVCMOS33 [get_ports CLK100MH]
create_clock -add -name sys_clk_pin -period 10.00 -waveform {0 5} [get_ports
CLK100MH]

set_property PACKAGE_PIN U18 [get_ports BUTTON]
set_property IOSTANDARD LVCMOS33 [get_ports BUTTON]

##Sch name = JA8
set_property PACKAGE_PIN K2 [get_ports {enb}]
set_property IOSTANDARD LVCMOS33 [get_ports {enb}]

The first error (occurred during implementation) that I got was this:
ERROR: [Place 30-574] Poor placement for routing between an IO pin and BUFG.
I did some research, and I think the problem was a result of
    always @ (posedge BUTTON)
not being exactly in time with the clock.
So I added this line to the constraints to ignore the error:
set_property CLOCK_DEDICATED_ROUTE FALSE [get_nets BUTTON_IBUF]

This allowed me to run the implementation successfully. However, I encountered the following error when attempting to generate the bitstream:
ERROR: [DRC NSTD-1] Unspecified I/O Standard: 1 out of 4 logical ports use I/O standard (IOSTANDARD) value 'DEFAULT', instead of a user assigned specific value.
From what I understand, this error occurs when inputs/outputs are not assigned an initial value, so they assume whatever the 'DEFAULT' value is. I fiddled around with the initial values and value types of each of the "problem pins" that were listed. I was able to fix most of them, but currently 'clock' is the only remaining problem pin. I've been trying to fix clock for a while now with no luck.
Some help would be greatly appreciated, thanks!

A: 1/ You should not use @ (posedge BUTTON) for two reasons:

*

*You have not de-bounced the button so a single push can trigger multiple speed increments.

*In simple design like that everything should run of a single clock.
You should synchronize your button input to the clock and then add a counter + logic to check if the signal is stable (bouncing has stopped).
2/ The error message is very clear and specific:

Unspecified I/O Standard: 1 out of 4 logical ports....

All I did was check all your I/O ports and check your pin constraints. I see no constraint for the ena signal.


text:
Q: Count all  on html page I want to get all the <a> tags from an Html page with this JavaScript method:
function() {
    var links = document.getElementsByTagName('a');
    var i=0;
    for (var link in links){i++;}
    return i;
}

And i noticed it's won't return the correct number of a tags.
Any idea what can by the problem?
Any idea if there is any other way to get all the href in an Html ?
Edit
I tried this method on this html : http://mp3skull.com/mp3/nirvana.html .
And i get this result:"1". but there are more results in the page.

A: You don't have to loop over all of them just to count them. HTMLCollections (the type of Object that is returned by getElementsByTagName has a .length property:
$countAnchors = function () {
    return document.getElementsByTagName('a').length;
}

A: Using getElementsByTagName("a") will return all anchor tags, not only the anchor tags that are links. An anchor tags needs a value for the href property to be a link.
You might be better off with the links property, that returns the links in the page:
var linkCount = document.links.length;

Note that this also includes area tags that has a href attribute, but I assume that you don't have any of those.

A: UPDATE Also gets href
You could do this
var linkCount = document.body.querySelectorAll('a').length,
    hrefs= document.body.querySelectorAll('a[href]');

EDIT See the comment below, thanks to ttepasse

A: You don't need a loop here. You can read length property.
function getACount() {
    return document.getElementsByTagName('a').length;
}

A: I would cast them to an array which you then slice up, etc.
var array = [];
var links = document.getElementsByTagName("a");
for(var i=0; i<links.length; i++) {
    array.push(links[i].href);
}
var hrefs = array.length;

A: The JavaScript code in the question works as such or, rather, could be used to create a working solution (it's now just an anonymous function declaration). It could be replaced by simpler code that just uses document.getElementsByTagName('a').length as others have remarked.
The problem however is how you use it: where it is placed, and when it is executed. If you run the code at a point where only one a element has been parsed, the result is 1. It needs to be executed when all a elements have been parsed. A simple way to ensure this is to put the code at the end of the document body. I tested by taking a local copy of the page mentioned and added the following right before the other script elements at the end of document body:
<script>
var f = function() {
    var links = document.getElementsByTagName('a');
    var i=0;
    for (var link in links){i++;}
    return i;
};
alert('a elements: ' + f());
</script>

The results are not consistent, even on repeated load of the page on the same browser, but this is probably caused by some dynamics on the page, making the number of a elements actually vary.

A: What you forget here was the length property. I think that code would be:
var count = 0;
for (var i = 0; i < links.length; i++) {
  count++;
}
return count;

Or it would be:
for each (var link in links) {
  i++;
}

length is used to determine or count the total number of the element which are the result.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for (For Loop)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for_each...in (Foreach Loop)


text:
Q: Alter session slows down the query through Hibernate I'm using Oracle 11gR2 and Hibernate 4.2.1.
My application is a searching application.
Only has SELECT operations and all of them are native queries.
Oracle uses case-sensitive sort by default.
I want to override it to case-insensitive.
I saw couple of option here http://docs.oracle.com/cd/A81042_01/DOC/server.816/a76966/ch2.htm#91066
Now I'm using this query before any search executes.
ALTER SESSION SET NLS_SORT='BINARY_CI'

If I execute above sql before execute the search query, hibernate takes about 15 minutes to return from search query.
If I do this in Sql Developer, It returns within couple of seconds.
Why this kind of two different behaviors,
What can I do to get rid of this slowness?
Note: I always open a new Hibernate session for each search.
Here is my sql:
SELECT *
FROM (SELECT
        row_.*,
        rownum rownum_
      FROM (SELECT
               a, b, c, d, e,
               RTRIM(XMLAGG(XMLELEMENT("x", f || ', ') ORDER BY f ASC)
                     .extract('//text()').getClobVal(), ', ') AS f,
               RTRIM(
                  XMLAGG(XMLELEMENT("x", g || ', ') ORDER BY g ASC)
                  .extract('//text()').getClobVal(), ', ')    AS g
             FROM ( SELECT src.a, src.b, src.c, src.d, src.e, src.f, src.g
                      FROM src src
                     WHERE upper(pp) = 'PP'
                       AND upper(qq) = 'QQ'
                       AND upper(rr) = 'RR'
                       AND upper(ss) = 'SS'
                       AND upper(tt) = 'TT')
             GROUP BY a, b, c, d, e
             ORDER BY b ASC) row_
      WHERE rownum <= 400
) WHERE rownum_ > 0;

There are so may fields comes with LIKE operation, and it is a dynamic sql query. If I use order by upper(B) asc Sql Developer also takes same time.
But order by upper results are same as NLS_SORT=BINARY_CI. I have used UPPER('B') indexes, but nothings gonna work for me.

A's length = 10-15 characters
B's length = 34-50  characters
C's length = 5-10 characters

A, B and C are sort-able fields via app.
This SRC table has 3 million+ records.
We finally ended up with a SRC table which is a materialized view.
Business logic of the SQL is completely fine.
All of the sor-table fields and others are UPPER indexed.

A: UPPER() and BINARY_CI may produce the same results but Oracle cannot use them interchangeably.  To use an index and BINARY_CI you must create an index like this:
create index src_nlssort_index on src(nlssort(b, 'nls_sort=''BINARY_CI'''));

Sample table and mixed case data
create table src(b varchar2(100) not null);
insert into src select 'MiXeD CAse '||level from dual connect by level <= 100000;

By default the upper() predicate can perform a range scan on the the upper() index
create index src_upper_index on src(upper(b));

explain plan for
select * from src where upper(b) = 'MIXED CASE 1';

select * from table(dbms_xplan.display(format => '-rows -bytes -cost -predicate
    -note'));

Plan hash value: 1533361696

------------------------------------------------------------------
| Id  | Operation                   | Name            | Time     |
------------------------------------------------------------------
|   0 | SELECT STATEMENT            |                 | 00:00:01 |
|   1 |  TABLE ACCESS BY INDEX ROWID| SRC             | 00:00:01 |
|   2 |   INDEX RANGE SCAN          | SRC_UPPER_INDEX | 00:00:01 |
------------------------------------------------------------------

BINARY_CI and LINGUISTIC will not use the index
alter session set nls_sort='binary_ci';
alter session set nls_comp='linguistic';

explain plan for
select * from src where b = 'MIXED CASE 1';

select * from table(dbms_xplan.display(format => '-rows -bytes -cost -note'));

Plan hash value: 3368256651

---------------------------------------------
| Id  | Operation         | Name | Time     |
---------------------------------------------
|   0 | SELECT STATEMENT  |      | 00:00:02 |
|*  1 |  TABLE ACCESS FULL| SRC  | 00:00:02 |
---------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   1 - filter(NLSSORT("B",'nls_sort=''BINARY_CI''')=HEXTORAW('6D69786564
              2063617365203100') )

Function based index on NLSSORT() enables index range scans
create index src_nlssort_index on src(nlssort(b, 'nls_sort=''BINARY_CI'''));

explain plan for
select * from src where b = 'MIXED CASE 1';

select * from table(dbms_xplan.display(format => '-rows -bytes -cost -note'));

Plan hash value: 478278159

--------------------------------------------------------------------
| Id  | Operation                   | Name              | Time     |
--------------------------------------------------------------------
|   0 | SELECT STATEMENT            |                   | 00:00:01 |
|   1 |  TABLE ACCESS BY INDEX ROWID| SRC               | 00:00:01 |
|*  2 |   INDEX RANGE SCAN          | SRC_NLSSORT_INDEX | 00:00:01 |
--------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   2 - access(NLSSORT("B",'nls_sort=''BINARY_CI''')=HEXTORAW('6D69786564
              2063617365203100') )

A: I investigated and found that The parameters NLS_COMP y NLS_SORT may affect how oracle make uses of execute plan for string ( when it is comparing or ordering).
Is not necesary to change NLS session. adding
ORDER BY NLSSORT(column , 'NLS_SORT=BINARY_CI')

and adding a index for NLS is enough
create index column_index_binary as NLSSORT(column , 'NLS_SORT=BINARY_CI')

I found a clue to a problem in this issue so i'm paying back.
Why oracle stored procedure execution time is greatly increased depending on how it is executed?


text:
Q: How to get Iterable phones values in Flutter using the package contacts_services? I can't print or access the phone numbers in the contacts since it's Iterable. Instead of the phone number, it's showing Instance of 'Item' and couldn't find any solutions too. Any help is appreciated.

A: As the error message says, contact.phones returns a List<Item>.
Item is a class from the package defined as follows:
class Item {
  Item({this.label, this.value});
}

Therefore, if you'd like to print out the values, you could use a source like the following:
contact.phones.forEach((phone) => print("${phone.label}: ${phone.value}"));

A: The phones member of the Contact class is a list, not a single item. You will need to iterate it with a loop.
Make sure you can find such things out yourself. Your IDE has a feature called "Show definition" or some similar translation. By default it's CTRL + b, but your keyboard layout may vary. It will jump to the source where this type or member is defined and you can look for yourself what it is and how you want to use it.


text:
Q: A possible closed form? Does it have a closed form?
$$\int _{0}^{\infty }\!{\frac {x\cos \left( x \right) -\sin \left( x
 \right) }{{x} \left( {{\rm e}^{x}}-1 \right) }}{dx}$$
EDIT: no need for answer, I just found the closed form. Thanks!

A: Is this what you have found?
$$\int _{0}^{\infty }\!{\frac {x\cos \left( x \right) -\sin \left( x
 \right) }{{x} \left( {{\rm e}^{x}}-1 \right) }}{dx} = \frac{\pi}{2}+\arg\left(\Gamma\left(i\right)\right)-\Re\left(\psi_0\left(i\right)\right).$$
Here $\arg$ is the complex argument, $\Re$ is the real part of a complex number, $\Gamma$ is the gamma function, $\psi_0$ is the digamma function, $i$ is the imaginary unit and $\pi$ is also a famous constant.

A: $\newcommand{\+}{^{\dagger}}%
 \newcommand{\angles}[1]{\left\langle #1 \right\rangle}%
 \newcommand{\braces}[1]{\left\lbrace #1 \right\rbrace}%
 \newcommand{\bracks}[1]{\left\lbrack #1 \right\rbrack}%
 \newcommand{\ceil}[1]{\,\left\lceil #1 \right\rceil\,}%
 \newcommand{\dd}{{\rm d}}%
 \newcommand{\down}{\downarrow}%
 \newcommand{\ds}[1]{\displaystyle{#1}}%
 \newcommand{\equalby}[1]{{#1 \atop {= \atop \vphantom{\huge A}}}}%
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}%
 \newcommand{\fermi}{\,{\rm f}}%
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}%
 \newcommand{\half}{{1 \over 2}}%
 \newcommand{\ic}{{\rm i}}%
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}%
 \newcommand{\isdiv}{\,\left.\right\vert\,}%
 \newcommand{\ket}[1]{\left\vert #1\right\rangle}%
 \newcommand{\ol}[1]{\overline{#1}}%
 \newcommand{\pars}[1]{\left( #1 \right)}%
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}%
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,#2\,}\,}%
 \newcommand{\sech}{\,{\rm sech}}%
 \newcommand{\sgn}{\,{\rm sgn}}%
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}%
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$
\begin{align}
&\int _{0}^{\infty}{x\cos\pars{x} - \sin\pars{x} \over x\pars{\expo{x} - 1}}\,\dd x
=
\Re\int _{0}^{\infty}
\bracks{\expo{\ic x} - {\sin\pars{x} \over x}}\,{1 \over \expo{x} - 1}\,\dd x
\\[3mm]&=
\Re\int _{0}^{\infty}
\bracks{\expo{\pars{\ic - 1}x} - {\sin\pars{x}\expo{-x} \over x}}\,
{\dd x \over 1 - \expo{x}}
=
\Re\int _{0}^{\infty}
\bracks{\expo{-\pars{1 - \ic}x} - {\sin\pars{x}\expo{-x} \over x}}\,
\sum_{\ell = 0}^{\infty}\expo{-x}\,\dd x
\\[3mm]&=
\Re\sum_{\ell = 0}^{\infty}\int _{0}^{\infty}
\bracks{\expo{-\pars{\ell + 1 - \ic}x} - {\sin\pars{x}\expo{-\pars{\ell + 1}x}
        \over x}}\,\dd x
\end{align}

Also
  $$
\totald{}{\mu}\int_{0}^{\infty}{\sin\pars{x}\expo{-\mu x} \over x}\,\dd x
=
-\Im\int_{0}^{\infty}\expo{\pars{\ic - \mu}x}\,\dd x
=-\Im\pars{1 \over \mu - \ic} = -\,{1 \over \mu^{2} + 1}
$$
  $$
\int_{0}^{\infty}{\sin\pars{x}\expo{-\pars{\ell + 1}x} \over x}\,\dd x
=
{\pi \over 2} - \int_{0}^{\ell + 1}{\dd\mu \over \mu^{2} + 1}
={\pi \over 2} - \arctan\pars{\ell + 1} = \arctan\pars{1 \over \ell + 1}
$$

\begin{align}
&\color{#00f}{\large\int _{0}^{\infty}{x\cos\pars{x} - \sin\pars{x} \over x\pars{\expo{x} - 1}}\,\dd x
=
\Re\sum_{\ell = 0}^{\infty}
\bracks{{1 \over \ell + 1 - \ic} - \arctan\pars{1 \over \ell + 1}}}
\end{align}


text:
Q: Relating limits of a mapping and limits of nets Let $X$ be a topological space and $(x_d)_{d \in D}$ a net in $X$. Then $x_d$ converges to $x \in X$ if for every neighborhood $U$ of $x$ there exists $d_0 \in D$ such that for all $d \geq d_0$ we have $x_d \in U$.
Denote the set of limits of $x_d$ by $\lim_{d \in D} x_d$ which can be empty, have one point or several different points. If $X$ is Hausdorff then $\lim_{d \in D} x_d$ has at most one point.
Let $\Omega \subseteq X$ be an arbitrary subset, $a \in X$ an accumulation point of $\Omega$ in $X$, $Y$ a further topological space and $f : \Omega \to Y$ an arbitrary map.
A point $y \in Y$ is called a limit of $f$ at $a$ if for every neighborhood $V$ of $y$ there exists a neighborhood $U$ of $a$ such that $f(\Omega \cap U \setminus \{ a \}) \subseteq V$.
Let $\lim_{x \to a} f(x) \subseteq Y$ denote the set of all limit points of $f$ at $a$ which can be empty, consisting of one point or of several points.
I was asking myself whether we can relate these two kinds of convergence. Consider the directed set $D := \{ \Omega \cap U \setminus \{ a \} \mid U \text{ nbhd. of } a \}$ with $d_1 \leq d_2 :\Leftrightarrow d_2 \supseteq d_1$ for $d_1, d_2 \in D$. Is it true that
$$\lim_{x \to a} f(x) = \bigcap \lim_{d \in D} f(x_d)$$
where the intersection goes over all nets $(x_d)_{d \in D}$ in $X \setminus \{ a \}$ with $a \in \lim_{d \in D} x_d$?
One inclusion can be easily established:
Let $y \in \lim_{x \to a} f(x)$ and fix a net $(x_d)_{d \in D}$ in $\Omega \setminus \{ a \}$ such that $a \in \lim_{d \in D} x_d$. In order to show that $y \in \lim_{d \in D} f(x_d)$ let $V$ be a neighborhood of $y$. For this $V$ there exists a neighborhood $U$ of $a$ such that $f(\Omega \cap U \setminus \{ a \}) \subseteq V$ since $y \in \lim_{x \to a} f(x)$. For this $U$ there exists $d_0$ such that for all $d \geq d_0$ we have $x_d \in U$ since $x_d \to a$. Since $x_d \in \Omega \setminus \{ a \}$ it follows that $f(x_d) \in f(U \cap \Omega \setminus \{ a \}) \subseteq V$ and thus $y \in \lim_{d \in D} f(x_d)$.

A: To prove the other inclusion, suppose $y \not\in \lim_{x\to a} f(x)$. Then there is a neighbourhood  $V \ni y$ such that for all neighbourhoods $U \ni a$, we have $f[\Omega \cap U-\{a\}] \not\subseteq V$. Now let $d \in D$, by the above we have $f[d] \not\subseteq V$, choose $x_d \in d$ with $f(x_d) \not\in V$. Then, by construction $a \in \lim_{d\in D} x_d$ as $x_d \in d$, but $y\not\in \lim_{d \in D} f(x_d)$, as $V \ni y$ does not contain any $f(x_d)$.
So $\bigcap \lim f(x_d) \subseteq \lim f(x)$