dimanche 29 janvier 2017

Please Help! My scanner methods aren't working and the while-loop won't break

Sorry, I'm just a beginner and don't really know what is wrong with my program. I haven't got a clue what I am supposed to do.

What I would like the program to do is to allow the user to enter an Integer that is under MAX (1 000 000 000) but above 0. I also have put an exception block using the try and catch methods so that the user cannot enter a String.

The exception block works but it also prints the statements inside the if block --which I don't want.

This is what the console prints:

Number of marbles to divide: 
*three*
Please enter a number not a word
Try again: 
Please enter a number under 1 000 000 000 and above 0
Try again: 

I only want it to print... Please enter a number not a word Try again: after the user enters a String. What I mean is that I want the method's while-loop to break if the user has entered a string.

Another problem that I can't seem to solve is that if the user enters an Integer that's value is over MAX (1 000 000 000), the program continues. This is what the console prints...

Number of marbles to divide: 
1000000001
Number of people: 

As you can see the program continues even though the user has entered an Integer over MAX (1 000 000 000)

I do not know what to do, please help!

This is my code...

import java.util.*;

public class MarblesApp
{
    final static int MAX = 1000000000;
    static int  numberOfMarbles;
    static int numberOfPeople, marblesPerPerson, marblesLeftOver;
    static Scanner input = new Scanner(System.in);
    public static void main(String[] args) 
    {
        System.out.println("Welcome to the marble divvy-upper.");
        System.out.println("This program will tell you how many marbles to give to each person.\n"
    + "The maximum amount of marbles is 1 000 000 000. The maximum amount of people is the same.\n");

        System.out.println("Number of marbles to divide: ");
          numberOfMarbles = GetMarbles();

        System.out.println("Number of people: ");
          numberOfPeople = GetPeople();

        marblesPerPerson = (int)numberOfMarbles / numberOfPeople;
        marblesLeftOver = (int)numberOfMarbles % numberOfPeople;

        System.out.println("Give each child " + marblesPerPerson + " marbles."); 
        System.out.println("You will have " + marblesLeftOver + " marbles left over.");
    }
private static int GetPeople()
{
    while (true)
    {
        try
        {
            return input.nextInt();
        }
        catch(InputMismatchException f)
        {
            input.next();
            System.out.println("Please enter a number not a word\nTry again: ");
        }

        if(numberOfPeople > MAX || numberOfPeople == 0);
        {
            System.out.println("Please enter a number under 1 000 000 000 and above 0\nTry again: ");
        }
    }
}
public static int GetMarbles()
{
    while (true)
    {
        try 
        {
            return input.nextInt();
        }
        catch (InputMismatchException e)
        {
            input.next(); 
            System.out.println("Please enter a number not a word\nTry again: ");
        }

        if(numberOfMarbles > MAX || numberOfMarbles == 0);
        {
            System.out.println("Please enter a number under 1 000 000 000 and above 0\nTry again: ");
        }

        }
    } 
}

Is switch operator volatile?

In documentation it is said you could equally use if-else multiple times or switch-case:

int condition;

setCondition(int condition) {
    this.condition = condition;
}

Either switch-case

switch (condition) {
  case 1: print("one"); break;
  case 2: print("two"); break;

or

if (condition == 1) { print("one"); }
else if (condition == 2) { print("two"); }

Next, conditionis declared volatile and method setCondition() is called from multiple threads. If-else is not atomic and volatile variable write is a synchronizing action. So both "one" and "two" string could be printed in the last code.

It could be avoided if some method local variable with initial value was used:

int localCondition = condition;
if (local condition == ..) ..

Does switch-case operator hold some initial copy of variable? How are cross threads operations implemented with it?

Most efficient if statement?

I would like to write a function that takes integer numbers x, y, L and R as parameters and returns True if x**y lies in the interval (L, R] and False otherwise.

I am considering several ways to write a conditional statement inside this function:

  1. if L < x ** y <= R:
  2. if x ** y > L and x ** y <= R:
  3. if x ** y in range(L + 1, R + 1):

Why is option 1 the most efficient in terms of execution time ?

If statement string comparison in python

I want to start by saying that I'm a complete beginner in Python.

What I'm trying to do is read data from a relatively big CSV file (about 33k data points). The data consist of various readings each five minutes of 3 different stations from October until today. What I want to do is filter the data so I only get the results from 5 pm (17:00) to 7 pm (19:00) (of every day) and analyze only that set of data.

The code I have so far is this:

import csv

#Initialize list of different columns from my CSV file
date = []
time = []
Value1 = []
Value2 = []
Value3 = []

with open('MW_DATA_DIV.csv' , 'r') as csvfile:
    test = csv.reader(csvfile, delimiter= ',')
    for row in test:
        date.append(row[0])
        time.append(row[1])
        Value1.append((row[2]))
        Value2.append((row[3]))
        Value3.append((row[4]))


#print to see if all the data was acquired as desired
'''
print (len(time))
print (len(Value1))
print (len(Value2))
print (len(Value3))
print (len(date))
'''

#Sets a counter to run 1 by 1 thru the list "time"

for counter in time:
  hours = counter[0:2]   #Get first 2 digits (i.e. 17, which are the hours i want to take data from)
  #print (hours)
  #print (type(hours))

  if hours is "15" :
    print("[add code HERE]")
  elif hours is "16" :
    print("[also add code hereee]")
  elif hours is "17":
      print("Also Add code HERE")

The problem I'm having is that I'm not getting any message (add code here) So it's like its not executing the if statements. I have already checked and the data is a string. and whenever I print(hours) I get the readings of every hour (i.e: 0:05 , 0:10 , 0:15 , ... , 23:55 , ... , etc) just like I want...

I'm not sure what problem I have in my if statements that it's not executing them. Any help/advice/QUESTIONS are welcomed!!

Google Maps operation confusing me in Android

I have this seemingly simple class in my app. All it does it add a circle to the mapView at my Location with the circle color depending on the CDMA signal Strength at the location. Or that's what it's supposed to do. The app works fine if I only ask for one circle and the location with the cdma signal but it doesn't work in the if Statement format, even if there is only one else if present. My question is why and if It has anything to do with how many times maps can be called at once. And If anyone knows a workaround, it would help a lot.

private GoogleMap mMap;
    int cdmaSignal;
    double latitude;
    double longitude;

    BroadcastReceiver br;



    @Override
    protected void onResume() {
        super.onResume();
        if(br == null){
            br = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent z) {


                    shoveItThrough((int) z.getExtras().get("cell signal cdma"),
                            (double) z.getExtras().get("latitude"), (double) z.getExtras().get("longitude"));
                    CameraPosition cameraPosition = new CameraPosition.Builder()
                            .target(new LatLng(latitude, longitude))      // Sets the center of the map to location user
                            .zoom(17)                   // Sets the zoom
                            .bearing(0)                // Sets the orientation of the camera to east
                            .tilt(30)                   // Sets the tilt of the camera to 30 degrees
                            .build();
                    //
                    //mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));


                    /*mMap.addCircle(new CircleOptions()
                            .center(new LatLng(latitude,longitude)).radius(80).strokeColor(Color.rgb(255,0,0)).fillColor(Color.rgb((255,0,0)));*/
                    //LatLng home = new LatLng(latitude, longitude);




                    //mMap.addMarker(new MarkerOptions().position(home));
                    if(cdmaSignal<=-120 && cdmaSignal>-100){
                        mMap.addCircle(new CircleOptions()
                                .center(new LatLng(latitude,longitude)).radius(80).strokeColor(Color.rgb(255,0,0)).fillColor(Color.rgb(255,0,0)));
                        mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

                        /*LatLng home = new LatLng(latitude, longitude);

                        mMap.addMarker(new MarkerOptions().position(home));
                        mMap.moveCamera(CameraUpdateFactory.newLatLng(home));*/
                    } else if(cdmaSignal<=-100 && cdmaSignal>-80){
                        mMap.addCircle(new CircleOptions()
                                .center(new LatLng(latitude,longitude)).radius(80).strokeColor(Color.rgb(255,98,12)).fillColor(Color.rgb(255,98,12)));
                        mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

                        /*LatLng home = new LatLng(latitude, longitude);
                        mMap.addMarker(new MarkerOptions().position(home));
                        mMap.moveCamera(CameraUpdateFactory.newLatLng(home));*/
                    } else if(cdmaSignal<=-80 && cdmaSignal>-60){
                        mMap.addCircle(new CircleOptions()
                                .center(new LatLng(latitude,longitude)).radius(80).strokeColor(Color.rgb(255,181,12)).fillColor(Color.rgb(255,181,12)));

                        mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
                        /*LatLng home = new LatLng(latitude, longitude);
                        mMap.addMarker(new MarkerOptions().position(home));
                        mMap.moveCamera(CameraUpdateFactory.newLatLng(home));*/
                    } else if(cdmaSignal<=-60 && cdmaSignal>-40){
                        mMap.addCircle(new CircleOptions()
                                .center(new LatLng(latitude,longitude)).radius(80).strokeColor(Color.rgb(211,255,0)).fillColor(Color.rgb(211,255,0)));
                        mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
                        /*LatLng home = new LatLng(latitude, longitude);
                        mMap.addMarker(new MarkerOptions().position(home));
                        mMap.moveCamera(CameraUpdateFactory.newLatLng(home));*/
                    } else if(cdmaSignal<=-40 && cdmaSignal>-20){
                        mMap.addCircle(new CircleOptions()
                                .center(new LatLng(latitude,longitude)).radius(80).strokeColor(Color.rgb(164,255,0)).fillColor(Color.rgb(164,255,0)));
                        mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

                        /*LatLng home = new LatLng(latitude, longitude);

                        mMap.addMarker(new MarkerOptions().position(home));
                        mMap.moveCamera(CameraUpdateFactory.newLatLng(home));*/
                    } else if(cdmaSignal<=-20 && cdmaSignal>-0){

                        mMap.addCircle(new CircleOptions()
                                .center(new LatLng(latitude,longitude)).radius(80).strokeColor(Color.rgb(0,255,0)).fillColor(Color.rgb(0,255,0)));
                        mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
                        /*LatLng home = new LatLng(latitude, longitude);

                        mMap.addMarker(new MarkerOptions().position(home));
                        mMap.moveCamera(CameraUpdateFactory.newLatLng(home));*/
                    }


                }
            };
        }
        registerReceiver(br, new IntentFilter("location_update"));

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(br != null){
            unregisterReceiver(br);
        }
    }
    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
    }

    public void shoveItThrough(int c, double la, double lo){
        cdmaSignal = c;
        latitude = la;
        longitude = lo;


    }



}

samedi 28 janvier 2017

Select2 multiple values and if/then

I am trying to have a div show if 2 options in a select2 box are chosen using jquery but am unsuccessful.

For example - my 2 choices are First and Second:

<select id="choose1" multiple="multiple">
<option value="first">First</option>
<option value="second">Second</option>
</select>

I have 2 divs that hidden:

<div id="first">
ABC
</div>
<div id="second">
XYZ
</div>

$('#first').hide();
$('#second').hide();

And now my jquery to show the divs:

$('#choose1').select2();

$('#choose1').change(function () {
    var val = $(this).val();
    var x = 'first';
    var y = 'second'
    var z = ['first','second'];

    if (val == x) {
        $('#first').show();
    }

  else if (val == y) {
    $('#second').show();
  }

  else if (val == z) {
  $('#first').show();
  $('#second').show();
  }

    });

Any ideas on how I can get this to work?

Thanks.

why select statement based on parameter( IF @SearchType= 0 SELECT...) returns only message "Command(s) completed successfully." and no result

I need to display certain number of column depending on what parameter end user is going to use. First I am declaring a table with SearchTypes based on Parameter then using that value to display necessary columns.
I am using statement

  ` IF @SearchType = 0 BEGIN 
    SELECT...
    FROM
    RETURN
    END 
IF @SearchType = 1 BEGIN 
    SELECT...
    FROM
    RETURN
    END 
` 

But for some reason when I execute the statement I only see

Command(s) completed successfully.

without any result.

Why cant I simply display select statement based on IF condition without inserting it into #TempTable?

DECLARE
       @UserGUID UNIQUEIDENTIFIER = '1E82F47B-4C8F-4185-82D2-ED2EB59796D6',
        @LineGUID UNIQUEIDENTIFIER = 'CF144437-F128-4B77-AC19-877247347D02'--'1CB72920-B3FC-4822-8030-37B50A2810EB'--, --WC

--------------------------------------------------------------------------------
--Populating @lineTable with GUIDs 
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

Declare @LineTable Table(GUID uniqueidentifier)
            IF @LineGuid IS NULL
            BEGIN
                  INSERT INTO @LineTable
                  SELECT LineGuid From lstLines
            END
            ELSE
            BEGIN
                  INSERT INTO @LineTable
                  SELECT * FROM dbo.StringOfGuidsToTable(@LineGuid,',')
            END
--------------------------------------------------------------------------------
--creating @SearchType based on param @LineGUID
--in this example @SearchType gives 0
declare @SearchType  int
set  @SearchType= (select   top 1   
                    CASE WHEN lstLines.LineGUID IN (  
                                                        'D657FDF6-19E1-425B-8598-295083424EFF', --eq access
                                                        'D4983D4A-1D12-461D-8837-6092DC74325B' --eq
                                                    ) then 1
                            WHEN lstLines.LineGUID IN ('F58F7128-18A6-4A3D-AE36-0F30236B4050',--flood
                                                        'E05E7F4A-07C4-4981-BD13-2461D4EE4BF3') then 2--terrorism
                            WHEN lstLines.LineGUID = 'CF144437-F128-4B77-AC19-877247347D02' then 3   --wind 
                            ELSE 0 end as SearchType

from                tblQuotes 
inner join lstLines ON tblQuotes.LineGUID = lstLines.LineGUID 
where lstLines.Inactive = 0
and  lstLines.LineGUID = @LineGUID)
--------------------------------------------------------------------------------
 IF @SearchType = 0
 BEGIN 
       SELECT DISTINCT 
            TOP 100 PERCENT 
                Column1,
                Column2,
                Column3
                --other columns
         FROM 
                  dbo.tblNoteEntities  (nolock) 
           --some other JOINs here 
         WHERE tq.LineGuid IN (SELECT * FROM @LineTable)
                AND               
                  (@UserGUID IS NULL OR tblNoteRecipients.UserGUID = @UserGUID) 
             ORDER BY  Column1
      RETURN
END
--------------------------------------------------------------------------------
if @SearchType = 1  --eq and eq access 
BEGIN 
SELECT DISTINCT 
            TOP 100 PERCENT 
                Column4,
                Column5,
                Column6
         FROM 
                  dbo.tblNoteEntities  (nolock) 
           --some other JOINs here 
         WHERE tq.LineGuid IN (SELECT * FROM @LineTable)
                AND               
                  (@UserGUID IS NULL OR tblNoteRecipients.UserGUID = @UserGUID) 
             ORDER BY  Column1
      RETURN
END
--------------------------------------------------------------------------------
if @SearchType = 3 --And so on