text:
Q: Spring Boot Custom HTTP EXCEPTION I have this method to handle all request header missing exceptions, but in one controller is expected to receive a json as body. If it is a invalid json or is null, it drops a exception with custom messages:
@ExceptionHandler(value = {ServletRequestBindingException.class, HttpMessageNotReadableException.class})
public final ResponseEntity<ErrorResponse> handleHeaderException(Exception ex) {
    List<String> details = new ArrayList<>();
    details.add(ex.getMessage());
    return new ResponseEntity<>(new ErrorResponse("Bad Request", details), HttpStatus.BAD_REQUEST);
}

{
      "message": "Bad Request",
      "details": [
          "Required request body is missing: public org.springframework.http.ResponseEntity
  packages.fazerLogin(packages.BodyLogin) throws java.io.IOException"
      ] }

{
      "message": "Bad Request",
      "details": [
          "JSON parse error: Unexpected character ('\"' (code 34)): was expecting comma to separate Object entries; nested exception is
  com.fasterxml.jackson.core.JsonParseException: Unexpected character
  ('\"' (code 34)): was expecting comma to separate Object entries\n at
  [Source: (PushbackInputStream); line: 3, column: 3]"
      ] }

But I don't want a long message such as above. Just "Required request body" or "JSON parse error" is just fine. I want to know what can I do.
My controller:
@PostMapping(value = "v1/token", consumes = "application/json;charset=UTF-8")
public ResponseEntity<TokenOutputDto> doLogin(@RequestBody @Valid BodyLogin body) throws IOException {
    return authenticationModel.auth(body.getEmail(), body.getPassword());
}

Also, should I create a @ExceptionHandler method to each one of the possibles exceptions (HttpClientErrorException, HttpServerErrorException etc)? It will be a bad pratice, because the code will repeat almost identically...

A: You can handle those exception handlers in your method by following way:
@ExceptionHandler(value = {ServletRequestBindingException.class, HttpMessageNotReadableException.class})
public final ResponseEntity<ErrorResponse> handleHeaderException(Exception ex) {
    List<String> details = new ArrayList<>();
    if (ex instanceof IOException ) {
        if (ex.getCause() instanceof JsonParseException) {
            details.add("JSON parse error");
        } else {
            details.add("Required request body");
        }
    } else {
        details.add(ex.getMessage());
    }
    return new ResponseEntity<>(new ErrorResponse("Bad Request", details), HttpStatus.BAD_REQUEST);
}


text:
Q: Как я могу переменную в java вернуть из одной функции и вставить её в другую? public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public static String executePost(String urlParameters) {
        HttpURLConnection connection = null;

        try {
            //Create connection
            URL url = new URL("https://api.privatbank.ua/p24api/pubinfo?json&exchange&coursid=5");
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");

            connection.setRequestProperty("Content-Length",
                    Integer.toString(urlParameters.getBytes().length));
            connection.setRequestProperty("Content-Language", "en-US");

            connection.setUseCaches(false);
            connection.setDoOutput(true);

            //Send request
            DataOutputStream wr = new DataOutputStream (
                    connection.getOutputStream());
            wr.writeBytes(urlParameters);
            wr.close();

            //Get Response
            InputStream is = connection.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            StringBuilder response = new StringBuilder(); // or StringBuffer if Java version 5+
            String line;
            while ((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\r');
            }
            rd.close();
            String resp = response.toString();
            return resp;
            //return response.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }

    }
    public void onButtonClick (View  v String resp) {
        TextView rateText = (TextView)findViewById(R.id.textView);
        rateText.setText(resp);
    }
}

Как мне переменную resp вставить в функцию onButtonClick()
потому-что данный код выдает ошибку . Я с java знаком 2 дня, перешел с Python. Если что-то делаю не так или нужен другой подход, то пожалуйста укажите как что делать.

A: Для начала нужно понять, что у вас статический метод. Такие методы не имеют доступа ко внутренним переменным класса.
Вам нужно создать переменную:
public class MainActivity extends AppCompatActivity {

private String response;

Затем, переменную нужно заполнить данными. Не забудьте! Работа с сетью в основном потоке (UI потоке) вызовет исключение! Для этого нужно вызвать метод:
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        AsyncTask.execute(() -> {
            String res = executePost(params);
            mButton.post(() -> {
                response = res;
            });
        });
    }

Теперь ваша переменная будет заполнена данными, но не сразу. Для того, чтобы узнать, когда она заполнится, лучше заблокировать кнопку в execute методе, а в post разблокировать.
Подробнее можете почитать тут или тут.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I prevent a browser page refresh in JavaScript? I would like to prevent an HTML page refresh (given a variable refreshMode != 1):
window.onbeforeunload = function(e) {
   if(refreshMode == 1){
     return;
   }else{
     // don't do it!
    e.preventDefault();
   }
};

I have tried e.preventDefault() and e.stopPropagation(), but neither appears to be preventing the refresh from submit the request.
Is it possible to do this?

A: Set a return value in additiont o preventing default. You cannot change the prompt text (that used to be possible), and you cannot prevent the prefresh if the user confirms on the prompt.
See https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event
window.addEventListener('beforeunload', (event) => {
  // Cancel the event as stated by the standard.
  event.preventDefault();
  // Chrome requires returnValue to be set.
  event.returnValue = '';
});


text:
Q: sending emails from gmail with c++ code I'm interested in sending emails with c++ code.
So far I've tried using the jwsmtp library at  jwsmtplib and I haven't had any real success.  Any suggestions?  Below is my code:
//code:
#include <iostream>
#include <jwsmtp/jwsmtp.h>

using std::cout;
using std::endl;

int main(  ) {

std::vector<char> vec;
std::string mess("Foo\nBar");
for(std::string::size_type i = 0; i < mess.length( ); ++i)
  vec.push_back(mess[i]);

jwsmtp::mailer mail("me@gmail.com",              // who the mail is too
                  "sme@gmail.com",              // who the mail is from
                  "There is always room for FooBar",  // subject for the email
                  vec,                                // content of the message
                  "smtp.gmail.com",             // the smtp server to mail to
          465,      //jwsmtp::mailer::SMTP_PORT, // default smtp port (25)
                  false);                             // do not query MX records

mail.username("me@gmail.com");
mail.password("mepassword");

//mail.authtype(jwsmtp::mailer::PLAIN);
mail.send();

return 0;
}

I'm definitely open to other libraries or classes, but I'm constraint with OS X.
I've also download the POCO library as I've seen it mentioned in other threads, but I would prefer to have a flatter learning curve.  If anyone has example code with POCO I would appreciate getting a look.
Thanks

A: Check out the VMime library!


text:
Q: How can i create a crontab executing a specific link with auth token on Wordpress on Linux instance? i'm working to add a scheduled cron to my Linux instance but i'm getting error 403www.mywebsite.com.
The link that i need to ad as cron have a syntax like this:
curl https://www.mysite.it/wp-content/plugins/sync/launch.php?launch=ok&token=056319e12d2ea964aae027de4d1c9bed

When i try to curl or wget, i'm getting on console:
[error 403www.mysite.it
 [1]+  Done              curl https://www.mysite.it/wp-content/plugins/sync/launch.php?launch=ok

It's like the part of the link after ok, that contain the token, disappear. Maybe Linux are unable to read the character &?
What i've tried:
curl https://www.mysite.it/wp-content/plugins/sync/launch.php?launch=ok&token=056319e12d2ea964aae027de4d1c9bed
wget https://www.mysite.it/wp-content/plugins/sync/launch.php?launch=ok&token=056319e12d2ea964aae027de4d1c9bed

Also the same two line of code adding >/dev/null 2>&1 at the end.

A: It should be in double quotation mark. The symptom can be seen when curl URL is cut at ampersand character.
$ curl "your-URL"
$ curl "https://www.mysite.it/wp-content/plugins/sync/launch.php?launch=ok&token=056319e12d2ea964aae027de4d1c9bed"


text:
Q: Upgrading to Jetpack Compose 1.0.0-alpha12 with Kotlin 1.4.30 error After upgrading to Jetpack Compose 1.0.0-alpha12 with Kotlin 1.4.30, also with Activity 1.3.0-alpha02 fix for setContent, but still got an error
Execution failed for task ':app:mergeDebugJavaResource'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.MergeJavaResWorkAction
   > 2 files found with path 'META-INF/AL2.0' from inputs:

Had to use the workaround to make it built
    packagingOptions {
        exclude 'META-INF/AL2.0'
        exclude 'META-INF/LGPL2.1'
    }

And also have the warning
Flag is not supported by this version of the compiler: -Xallow-jvm-ir-dependencies
No matter keeping freeCompilerArgs += ["-Xallow-jvm-ir-dependencies"] under kotlinOptions or not

A: The issue got fixed once upgrading to Compose 1.0.0-beta01. No workaround needed.

A: Once I upgraded to Compose 1.0.0-beta01, kotlin.collections such as arrayListOf, listOf, ... are not implicity imported anymore. Did it occur to you too ?

A: You must use compatible versions of compose and Kotlin. Compose beta08 and Kotlin 1.5.10 are compatible


text:
Q: VBA get connector 'from shape' and 'to shape' I have a flow design in Excel (using shapes, connectors, etc).
What I need is to have a matrix and for every shape to have all the predecessors and all the successors.
In VBA, to do that I'm trying to do something like:
- I'm listing all the connectors (Shapes.AutoShapeType = -2)
- for each one I want to have the name of the shape 'from' and the name of the shape 'to'.
I hope you get the idea.
I don't find the properties of the connector in order to retrieve this info.
This is what I have so far:
Sub getTransitions()
    ''the sheet with the design
    Set designSheet = Sheets("DesignSheet")
    Set tempSheet = Sheets("temp") 'Sheets.Add

    lLoop = 0

    'Loop through all shapes on active sheet
    For Each sShapes In designSheet.Shapes

        'Increment Variable lLoop for row numbers
        With sShapes

           ''connector shape type
           If ((sShapes.AutoShapeType) = -2) Then
                lLoop = lLoop + 1
                tempSheet.Cells(lLoop + 1, 1) = sShapes.Name
                tempSheet.Cells(lLoop + 1, 2) = sShapes.AutoShapeType

               ''here I want to have for the sShapes the from shape and the to shape

            End If

        End With

     Next sShapes
End Sub

Does anyone know the shape parameters for having this info ?

A: It seems that utilizing the ConnectorFormat object returned by the ConnectorFormat property and looking into the BeginConnectedShape and EndConnectedShape properties may be your best bet.

A: You can use something like that:
Set g = ActiveSheet
i = 1
For Each s In g.Shapes
    If ((s.AutoShapeType) <> -2) Then 'all shapes without connectors
        c = 0
        For Each s1 In g.Shapes
            If ((s1.AutoShapeType) = -2) Then 'only connectors
                With s1.ConnectorFormat
                   Set a = .BeginConnectedShape
                   Set b = .EndConnectedShape
                End With
                If a.Name = s.Name Or b.Name = s.Name Then
                    c = c + 1
                End If
            End If
        Next s1

        g.Cells(i, "A").Value = s.Name 'name of shape
        g.Cells(i, "B").Value = c 'count of connectors

    i = i + 1
    End If
Next s


text:
Q: How can I forward a GCP Pubsub subscription's messages to another topic? I would like to be able to forward a Google Cloud Platform (GCP) Pubsub subscription's messages to another GCP topic, which is possibly in another GCP Project.

*

*Is this possible via Push endpoint URL (What would the url of the destination topic be?)

*Some other easy configuration via API?

*(workaround) Alternatively, how would you provide this functionality?

A: There is a Dataflow template called Cloud_PubSub_to_Cloud_PubSub that read messages from a Pubsub subscription (inputSubscription) and publish the messages to a Pubsub topic (outputTopic).
Be sure that the service account used to launch the Dataflow job has the right permissions (roles/pubsub.subscriber in the project where inputSubscription is defined or directly on inputSubscription, and roles/pubsub.publisher in the project containing outputTopic or directly on outputTopic).
You can take a look at the code on GitHub if you are familiar with Java.

A: The only way to do this would be to publish the messages to the other topic in a subscriber you write when it receives the messages. There is no automated way to forward messages from one topic to another.


text:
Q: Which project type to select if I just want to use command line fro Xamarin Studio? I want to start learning C# and just want to use the command line, like the option offered by Xcode when you are choosing which project type. I do not want to make an app or anything of the sort, just want to use command line where I can print strings and read in inputs from the keyboard. Which project type do I select in order to do that?

A: Other / .Net / Console Project (& choose a language other than C# if needed)


text:
Q: Changes coming in Version 1.1 of the Twitter API in iPhone I am using twitter API version V1.0 for my new iphone application .I am successfully able to do this using twitters v1.0 of the API and all works perfectly. Simply making a request to http://api.twitter.com/1/statuses/user_timeline.json?screen_name=userid retrieves all the information that I require.
since v1.0 has been deprecated and V1.1 requires authentication for each request, I get a bad authorization error (HTTP response status: 400)using this API.
 What are the Changes i need to do in my appication .how to generate OAuth request headers,Do i need register my application ?How can i get authentication for new version?
I hope the above makes sense and any help would be appreciated.
Thanks in advance.

A: Visit https://dev.twitter.com/docs/ios/making-api-requests-slrequest
https://dev.twitter.com/docs/oauth/xauth
u can get the authentication using following method:
NSString *base64 = @"Basic NFRLWGlZY3l1aHJ4OVJaUWI5RW5BOmdVMXlvcVV6YzBNZUhUQmFXdVRZU2NtZHlIWDFOZXhwZmxqRE16bm01aw==";
    //oauth_consumer_secret,oauth_consumer_key
    NSURL *urlAPI = [NSURL URLWithString:[NSString stringWithFormat:@"https://api.twitter.com/oauth2/token"]];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:urlAPI];
[request setDelegate:self];
[request setRequestMethod:@"POST"];

[request addRequestHeader:@"Authorization" value:base64];

[request addRequestHeader:@"Content-Type" value:@"application/x-www-form-urlencoded;charset=UTF-8"];

[request setPostValue:@"client_credentials" forKey:@"grant_type"];

In response u will get the authtoken for your application like this
{"token_type":"bearer","access_token":"AAAAAAAAAAAAAAAAAAAAAMddRQAAAAAAXRP6Axur1RS%2Fv9YFtJ7TijyPAGo%3DpmNowwOGf3dZTHDiH2gnCcv7qNIyGZcyV2IW5YFTBs"}


text:
Q: Memory management for a programming puzzle in java I am trying to solve an interesting programming puzzle

There are several visitors to a movie rental store and want to rent movies. Each person can rent upto 2 movies. However the rental agency can only rent only 1 copy of each movie.To solve this, rental agency asks each person to give a wish list of movies they want to rent. Each person can provide upto 10 wishes.
  Depending on the wish list provided by people, rental agency wants to come up with a solution so that each person can be give a unique movie rental.
Input:
  A text file containingg of two columns
  column1 has perosn Id and column2 has the movie ID they wish to rent.
  There can be upto 10 entries for each person and file may not be sorted.
Solution

*

*Read the entire file line by line and create a map of person vs list of movies requested.

*Sort the entries in the map based on no of movies requested.

*Traverse the sorted list and then assign upto 2 movies to a person from the list if that particular movie is not assigned to anyone else (using a HashSet for this purpose).

This algorithm works for reasonable size of file. But if the input file is very large I get an out of memory error. To be specific, while trying to store the data in the map.
Is there any other approach that I can take? Probably do away with reading the entire file in memory.

A:
Probably do away with reading the entire file in memory.

Yeah, of course. Read it line by line.
BufferedReader br = new BufferedReader(new FileReader(file));
while(br.ready()) {
    String line = br.readline();
    // do something with line
}
br.close();

Now, if your map won't fit in memory, then you have a very different issue. But you didn't say that's the case, so I'll assume it's not.
Edit: If you can't store the entire map in memory, use a lightweight and local database like SQLite. That's what they're for.


text:
Q: Masking Email address along with domain using regex The requirement is as below:
Input: rajani@gmail.com
Output: r****i@*****.com

I tried below two regex's but I could not able to mask the gmail(domain name). Kindly help me on this.
String masked_email_Address2=email_Address.replaceAll("(?<=.{1}).(?=[^@]*?.@)", "*");

Output received as r****i@gmail.com
I searched in stack overflow on this, I got the below regex but it does not produce the correct result:
String masked_email_Address1=email_Address.replaceAll("\\b(\\w)[^@]+@\\S+(\\.[^\\s.]+)", "$1***@****$2");

Output received as: r***@****.com -- One star(*) is missed between R&@.

A: I started out trying to do this with a one-liner using String#replaceAll as you were doing, but then gave up, because variable length lookbehinds are not supported, and I could not come up with a pattern which did not use them.
Instead, try just using a format pattern matcher:
String email = "rajani@gmail.com";
String pattern = "([^@]+)@(.*)\\.(.*)";

Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(email);
if (m.find( )) {
    StringBuilder sb = new StringBuilder("");
    sb.append(m.group(1).charAt(0));
    sb.append(m.group(1).substring(1).replaceAll(".", "*"));
    sb.append("@");
    sb.append(m.group(2).replaceAll(".", "*"));
    sb.append(".").append(m.group(3));
    System.out.println(sb);
}

Demo
This may look like a lot of code to do a relatively small formatting job on an email address.  If you like, you may put this code into utility method, and then you can still get the masking effect with a single line of code, when you call the method.

A: How about:
String masked_email_Address2=email_Address.replaceAll("(.)?[^@]*([^@])@\\S+(\\.[^\\s.]+)?", "$1****$2@****$3");

This will work as long as your address is longer than 1 character long.

A: Try this:
int idx = email_Address.indexOf('@');
 String part1 = email_Address.substring(1, idx-1).replaceAll(".", "\\*");
 String part2 = email_Address.substring(idx + 1, email_Address.lastIndexOf('.')).replaceAll(".", "\\*");

 String masked_email_Address1=email_Address.replaceAll("^(\\S)[^@]+(\\S)@.*(\\..*)", "$1"+ part1 + "$2@" + part2 + "$3");


text:
Q: Fatal exception (Thread) I wanted to make some water ripples in my android application so I used this javascript code http://jsfiddle.net/esteewhy/5Ht3b/6/ converted into C code like it is shown here Live Wallpaper Water Ripple Effect (by esteewhy).
I have a main activity, which calls the water ripples activity after clicking a button. The water ripples are working great with my mutable bitmap, the problem is when I clicked the "back" button of the android device, the system crashes throwing this error:
FATAL EXCEPTION: Thread-2556
java.lang.NullPointerException
at com.wheelly.whater.WaterView.onDraw (line 149)
at com.wheelly.whater.WaterView$GameThread.run (line 255)

I guess there is some problem handling the Thread or the activities themselves.
Here is the code of the Water Ripples:
public class WaterView extends SurfaceView implements SurfaceHolder.Callback {
    GameThread thread;

    public static Bitmap icon;

    //Measure frames per second.
    long now;
    int framesCount=0;
    int framesCountAvg=0;
    long framesTimer=0;
    Paint fpsPaint=new Paint();

    //Frame speed
    long timeNow;
    long timePrev = 0;
    long timePrevFrame = 0;
    long timeDelta;

    private int width = 480;
    private int height = 800;

    private short riprad = 6;
    boolean flip;
    private short[] ripplemap, last_map;
    Bitmap ripple;

    private static final String TAG = null;

    private Rippler rippler;

    public WaterView(Context context) {
        super(context);
        initialize();
    }

    void initialize() {
        //CB
        icon = BitmapFactory.decodeResource(getResources(), R.drawable.sand100);
        icon = convertToMutable(icon);
        //--
        rippler = new NativeRippler();
        reinitgGlobals();
        fpsPaint.setTextSize(30);

        //Set thread
        getHolder().addCallback(this);

        setFocusable(true);
    }

    void reinitgGlobals() {
        int size = width * (height + 2) * 2;
        ripplemap = new short[size];
        last_map = new short[size];
        Bitmap texture = createBackground(width, height); // this creates a MUTABLE bitmap
        ripple = texture;
        _td = new int[width * height];
        texture.getPixels(_td, 0, width, 0, 0, width, height);
        _rd = new int[width * height];
    }

    void randomizer() {
        final Random rnd = new Random();
        final Handler disHAndler = new Handler();
        final Runnable disturbWater = new Runnable() {
            @Override
            public void run() {
                disturb(rnd.nextInt(width), rnd.nextInt(height));
                disHAndler.postDelayed(this, 7000);
            }
        };
        disHAndler.post(disturbWater);
    }

    private static Bitmap createBackground(int width, int height) {
        Canvas cb = new Canvas (icon);
        cb.save();
        cb.restore();
        return icon;
    }

    private Bitmap convertToMutable(Bitmap bitmap) {
        try {
            File file = new File("/mnt/sdcard/sample/temp.txt");
            file.getParentFile().mkdirs();
            RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");

            int width_mutable = bitmap.getWidth();
            int height_mutable = bitmap.getHeight();

            FileChannel channel = randomAccessFile.getChannel();
            MappedByteBuffer map = channel.map(MapMode.READ_WRITE, 0, width_mutable*height_mutable*4);
            bitmap.copyPixelsToBuffer(map);
            bitmap.recycle();

            bitmap = Bitmap.createBitmap(width_mutable, height_mutable, Config.ARGB_8888);
            map.position(0);
            bitmap.copyPixelsFromBuffer(map);

            channel.close();
            randomAccessFile.close();

        } catch (FileNotFoundException e) {
            Log.i(TAG, "::onActivityResult:" + ""+Log.getStackTraceString(e));
        } catch (IOException e) {
            Log.i(TAG, "::onActivityResult:" + ""+Log.getStackTraceString(e));
        }
        return bitmap;
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        width = w;
        height = h;
        reinitgGlobals();
    }

    @Override
    protected void onDraw(android.graphics.Canvas canvas) {
        super.onDraw(canvas);
        newframe();
        canvas.drawBitmap(ripple, 0, 0, null);

        //Measure frame rate (unit: frames per second).
        now=System.currentTimeMillis();
        canvas.drawText(framesCountAvg+" fps", 40, 70, fpsPaint);
        framesCount++;
        if(now-framesTimer>1000) {
                framesTimer=now;
                framesCountAvg=framesCount;
                framesCount=0;
        }
    }

    /**
     * Disturb water at specified point
     */
    private void disturb(int dx, int dy) {
        rippler.disturb(dx, dy, width, height, riprad, ripplemap, flip);
    }

    int[] _td;
    int[] _rd;

    /**
     * Generates new ripples
     */
    private void newframe() {
        System.arraycopy(_td, 0, _rd, 0, width * height);
        flip = !flip;
        rippler.transformRipples(height, width, ripplemap, last_map, _td, _rd, flip);
        ripple.setPixels(_rd, 0, width, 0, 0, width, height);
    }

    @Override
    public synchronized boolean onTouchEvent(MotionEvent event) {
            disturb((int)event.getX(), (int)event.getY());
            return true;

    }

    @Override
    public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
    }

    @Override
    public void surfaceCreated(SurfaceHolder arg0) {
        thread = new GameThread(getHolder(), this);
        thread.setRunning(true);
        thread.start();
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder arg0) {
        boolean retry = true;
        thread.setRunning(false);
        while (retry) {
            try {
                thread.join();
                retry = false;
            } catch (InterruptedException e) {

            }
        }
    }

    class GameThread extends Thread {
        private SurfaceHolder surfaceHolder;
        private WaterView gameView;
        private boolean run = false;

        public GameThread(SurfaceHolder surfaceHolder, WaterView gameView) {
            this.surfaceHolder = surfaceHolder;
            this.gameView = gameView;
        }

        public void setRunning(boolean run) {
            this.run = run;
        }

        public SurfaceHolder getSurfaceHolder() {
            return surfaceHolder;
        }

        @Override
        public void run() {
            Canvas c;
            while (run) {
                c = null;

                //limit frame rate to max 60fps
                timeNow = System.currentTimeMillis();
                timeDelta = timeNow - timePrevFrame;
                if ( timeDelta < 16) {
                    try {
                        Thread.sleep(16 - timeDelta);
                    }
                    catch(InterruptedException e) {
                    }
                }
                timePrevFrame = System.currentTimeMillis();

                try {
                    c = surfaceHolder.lockCanvas(null);
                    synchronized (surfaceHolder) {
                       //call methods to draw and process next fame
                        gameView.onDraw(c);
                    }
                } finally {
                    if (c != null) {
                        surfaceHolder.unlockCanvasAndPost(c);
                    }
                }
            }
        }
    }
}

A: I found the solution:
I had to interrupt the thread in the onPause method of the activity instead of doing it in the onStop method. Now it is just working fine.
Thanks a LOT to all of you for helping me with that problem.

A: you should shut down your working thread in the method Activity.onStop
    @Override
    protected void onStop() {
        thread.interrupt();
        super.onStop();
    }

in the run method of GameThread check if thread was interrupted right before you call gameView.onDraw(c); like this:
    if(isInterrupted()) {
        break;
    }
    gameView.onDraw(c);

BTW, probably it would be better if you replace gameView.onDraw(c) with gameView.invalidate();

A: Don't call onDraw directly on a view, but rather call gameView.invalidate()
synchronized (surfaceHolder) {
    //call methods to draw and process next fame
    gameView.invalidate();
}

If it doesn't work, try using debugger with a breakpoint to see which variable is null exactly


text:
Q: How to automatically run a "find and replace" after save? I have some regex here that transforms CSS hex to uppercase. This was originally from my previous question How to tranform css hex to uppercase in vscode?
find: #(?:[0-9a-fA-F]{3}){1,2}
replace all: \U$0

I want to ask how to auto-execute the above after saving a file. I finally came up to ask this since I just got tired of running these every time before I create a PR.

A: I think your find/replace needs to be in the form of a command so that it can be run on save.  You can make it into a command with this extension, Find and Transform, that I wrote.
With this in your settings.json:
  "findInCurrentFile": {
    "upcaseHexColors": {  // this will be the command name to use in the codeActions
      "title": "upcase Hex colors", // this is how it will look in the Command Palette
      "find": "#(?:[0-9A-FA-F]{3}){1,2}",
      "replace": "\\U$0",
      "isRegex": true
    },
  },

  "[css]": {                       // if you want to limit it to css files
    "editor.codeActionsOnSave": [
      "source.upcaseHexColors"
    ]
  },

Make sure you reload the vscode window: Developer: Reload Window after making these settings changes.


text:
Q: if exists, update else insert, with cursors in stored procedures only returns 1 row I have 2 tables api(columns - api , api_context, api_id -->primary key) and api_request_summary(columns - api_context). i need to insert the number of times the api_context relevant to a particular api_id is repeated in the table curhittest1. both tables have multiple rows so i have used cursors to loop through the tables. i can correctly insert the values to the table but i need to check wether that api_id already exists in the curhittest1 table and if yes update and if no insert.
DELIMITER //
CREATE PROCEDURE curhit12()

BEGIN

 DECLARE done INT DEFAULT FALSE;
 DECLARE apiId, noOfHits int(11);
 Declare apiContext varchar(255);

 DECLARE cur1 CURSOR FOR Select api_id from api;

 DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

  OPEN cur1;

read_loop: LOOP
    FETCH cur1 INTO apiId;

    IF done THEN
      LEAVE read_loop;
    END IF;

    select api_context into apiContext from api where api_id =apiId;

    SELECT COUNT(*) FROM api_request_summary WHERE api_context=apiContext into noOfHits;

 IF exists (SELECT * FROM curhittest1 WHERE apiid = apiId) THEN

   UPDATE curhittest1
                      SET noofhits=noOfHits
                      WHERE apiid = apiId;
 ELSE

  insert into curhittest1(apiid,noofhits) values (apiId,noOfHits);
 END IF;

  END LOOP;

  CLOSE cur1;

END//
DELIMITER

When i use the following code only 1 row is added to the curhittest1 table. When the exact same code is used in sql procedures without cursors it displays so i'm assuming i need to do something differently when using with cursors. How can i add all the values to the table accurately?

A: It worked after using INSERT ... ON DUPLICATE KEY UPDATE. Thank you @RickJames. For anyone interested here is the code
DELIMITER //
CREATE PROCEDURE curhit12()

BEGIN

 DECLARE done INT DEFAULT FALSE;
 DECLARE apiId, noOfHits int(11);
 Declare apiContext varchar(255);
 DECLARE cur1 CURSOR FOR Select api_id from api;
 DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

  OPEN cur1;

read_loop: LOOP
    FETCH cur1 INTO apiId;

    IF done THEN
      LEAVE read_loop;
    END IF;

    select api_context into apiContext from api where api_id =apiId;

SET noOfHits = (SELECT COUNT(*) FROM api_request_summary
                WHERE api_context=apiContext);

INSERT INTO api_hits (api_id,no_of_hits) VALUES (apiId,noOfHits)
   ON DUPLICATE KEY UPDATE no_of_hits=noOfHits;

  END LOOP;

CLOSE cur1;

END//
DELIMITER


text:
Q: Binding object from Inherit class to combobox c# Hello i have problems binding an inherit object of the type List, i can't figure out how to set the DisplayMember and ValueMember of the ComboBox
here is my class UserObject
using ComissionsTwo.Backend.Permissions;
using ComissionsTwo.Backend.SQL.User;
using System.Collections.Generic;
using System.Data;

namespace ComissionsTwo.Backend.User
{
    internal class UserObject
    {
        protected string userId;
        protected string userAlias;
        protected string userPassword;
        protected string userName;
        protected string userLastName;
        protected string userMail;
        protected string userIdRol;
        protected DataTable userData;
        protected DataTable userPermissions;
        protected SQLUser sqlUser = new SQLUser();
        protected RolesPermissionsOperations rolesPermissionsControl = new RolesPermissionsOperations();
        protected static List<UserObject> listOfUsers = new List<UserObject>();

        public UserObject(string userAlias, string userPassword)
        {
            this.userAlias = userAlias;
            this.userPassword = userPassword;
        }

        public UserObject(string userAlias)
        {
            this.userAlias = userAlias;
        }

        public UserObject()
        {

        }

    }

Here is my class from that i inherit my UserObject class, i call the method getListUsers() to get the list of users that will be binded to the combobox
using ComissionsTwo.Backend.Messages;
using System.Collections.Generic;
using System.Data;
using System.DirectoryServices;

namespace ComissionsTwo.Backend.User
{
    internal class UserOperations : UserObject
    {
        public UserOperations(string userAlias, string userPassword) : base(userAlias, userPassword)
        {

        }

        public UserOperations(string userAlias) : base(userAlias)
        {

        }

        public UserOperations() : base()
        {

        }

        internal bool getUsers()
        {
            listOfUsers.Clear();
            DataTable aliasUsers = sqlUser.getUsers();
            foreach (DataRow row in aliasUsers.Rows)
            {
                UserOperations user = new UserOperations(row[0].ToString());
                if (user.getInfo() == false)
                {
                    MessagesInfo.StatusMessage = "No se pudo obtener la información de los usuarios activos";
                    return false;
                }
                listOfUsers.Add(user);
            }
            return true;
        }

        internal List<UserObject> getListUsers()
        {
            return listOfUsers;
        }

        internal bool addUser(DataTable userData, string userActiveId)
        {
            return sqlUser.addUser(userData, userActiveId);
        }

        internal bool editUser(DataTable userData, string userActiveId)
        {
            return sqlUser.editUser(userData, userActiveId);
        }

        internal bool eraseUser(string userId, string userActiveId)
        {
            return sqlUser.eraseUser(userId, userActiveId);
        }

        internal bool getUserPermissions()
        {
            userPermissions = rolesPermissionsControl.getUserPermissions(userIdRol);
            if (userPermissions == null || userPermissions.Rows[0][0].ToString() == string.Empty)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        internal bool getInfo()
        {
            if (loginInDatabase() == false)
            {
                MessagesInfo.StatusMessage = "No se pudo obtener la información del usuario a editar";
                return false;
            }
            else if (getUserPermissions() == false)
            {
                MessagesInfo.StatusMessage = "No se pudo obtener los permisos de usuario.";
                return false;
            }
            else
            {
                return true;
            }
        }

        internal bool login()
        {
            if (loginInActiveDirectory() == false)
            {
                MessagesInfo.StatusMessage = "El usuario no pudo ser logeado en el directorio activo.";
                return false;
            }
            else if (loginInDatabase() == false)
            {
                MessagesInfo.StatusMessage = "El usuario no pudo ser logeado en la base de datos.";
                return false;
            }
            else if (getUserPermissions() == false)
            {
                MessagesInfo.StatusMessage = "No se pudo obtener los permisos de usuario.";
                return false;
            }
            else
            {
                return true;
            }
        }

        private bool loginInActiveDirectory()
        {

            string path = @"LDAP://192.168.0.15";       //CAMBIAR POR VUESTRO PATH (URL DEL SERVICIO DE DIRECTORIO LDAP)
                                                        //Por ejemplo: 'LDAP://ejemplo.lan.es'
            string domain = @"grupototal99.local";             //CAMBIAR POR VUESTRO DOMINIO
            string domainUser = domain + @"\" + userAlias;               //CADENA DE DOMINIO + USUARIO A COMPROBAR

            return autenticaUsuario(path, domainUser, userPassword);
        }

        private bool autenticaUsuario(string path, string user, string pass)
        {
            //Los datos que hemos pasado los 'convertimos' en una entrada de Active Directory para hacer la consulta
            DirectoryEntry directoryEntry = new DirectoryEntry(path, user, pass, AuthenticationTypes.Secure);
            try
            {
                //Inicia el chequeo con las credenciales que le hemos pasado
                //Si devuelve algo significa que ha autenticado las credenciales
                DirectorySearcher ds = new DirectorySearcher(directoryEntry);
                ds.FindOne();
                return true;
            }
            catch
            {
                //Si no devuelve nada es que no ha podido autenticar las credenciales
                //ya sea porque no existe el usuario o por que no son correctas
                return false;
            }
        }

        private bool loginInDatabase()
        {
            userData = sqlUser.getUser(userAlias);
            if (userData == null || userData.Rows[0][0].ToString() == string.Empty)
            {
                return false;
            }
            else
            {
                userId = userData.Rows[0][0].ToString();
                userName = userData.Rows[0][2].ToString();
                userLastName = userData.Rows[0][3].ToString();
                userMail = userData.Rows[0][4].ToString();
                userIdRol = userData.Rows[0][5].ToString();
                return true;
            }
        }

    }
}

Here is my method to bind the comboBox
private void userEditComboBoxBinding()
        {
            BindingSource usersEditComboBoxBindingSource = new BindingSource();
            usersEditComboBox.SelectedIndexChanged -= new System.EventHandler(this.usersEditComboBox_SelectedIndexChanged);
            usersEditComboBoxBindingSource.DataSource = user.getListUsers();
            usersEditComboBox.DataSource = usersEditComboBoxBindingSource.DataSource;
            usersEditComboBox.DisplayMember = "userAlias";
            usersEditComboBox.ValueMember = "userId";
            usersEditComboBox.SelectedIndex = -1;
            usersEditComboBox.SelectedIndexChanged += new System.EventHandler(this.usersEditComboBox_SelectedIndexChanged);
        }

I have tried
usersEditComboBox.DisplayMember = "userAlias";
usersEditComboBox.ValueMember = "userId";

And
usersEditComboBox.DisplayMember = "UserAlias";
usersEditComboBox.ValueMember = "UserId";

But i always get and error if i commented usersEditComboBox.ValueMember the comboBox display this
ComissionsTwo.Backend.User.UserOperations the name of my class


text:
Q: html5 canvas large image export I am looking to have a canvas export to 1500x1500 300dpi final product.
I am looking to drag and drop images only, no drawing into a canvas, to create something like a photobook/collage thing. So people will be dragging images from right panel into canvas, resize, rotate, etc.
It seems my best option is to render a 500x500 and track/record all image/object activity and then process/mimic the recorded actions to a larger file (1500x1500) in PHP, then save/export that file.
I dont think I want a browser to try to handle large canvas + high res images, and possible many images (15+) on the screen. (in local tests, it has crashed upon export a few times).
Basically using canvas as a preview mode (500x500), to create a photo collage, then PHP to export to large/hi res (1500x1500) - exactly to scale.
Looking primarily for documentation, direction or advice. Any things i need to look out for? possible issues? Advise is much appreciated.
Currently using FabricJS, but open to any solutions. Also any insight on achieving the 300dpi. Would consider hiring for this project, just looking to see best route to take, thanks.


text:
Q: Position spots on a 3D dice/die I'm trying to build a 3D die using CSS3. I've built my cube, am able to rotate it around its Y and X axis,  and am capable of adding the spots on both the front and back, but I am struggling to position the die's spots on the left, right, top, and bottom accurately. I am a little new using transform properties so I'm sure this isn't as difficult as I'm making it.
Here are my code snippets. I have commented out the spots contained on the top, left, and bottom as I am strictly working to get the right side spots in position at the moment. Thanks for your help!

$(document).ready(function(){
  $('body').on('click', '.roll', function(){
    console.log("should be flipping")
    $('#cube').toggleClass("rolling")
  })
})
.container{
  width: 200px;
  height: 200px;
  position: relative;
  perspective: 1000px;
  margin: 0 auto;

}
#cube{
  width: 100%;
  height: 100%;
  position: absolute;
  transform-style: preserve-3d;
  top: 30px;

}
#cube figure{
  margin: 0;
  width: 196px;
  height: 196px;
  display: block;
  position: absolute;
  border: 2px solid black;
  transform-style: preserve-3d;
}
figure{
  background-color: black;
  border-radius: 6px;
}
.spot{
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-color: white;
  position: absolute;

  transform-style: preserve-3d;
}
#front-1{
  transform: translateZ(100px);
  margin-left: 10px;
  margin-top: 10px;
}
#front-2{
  transform: translateZ(100px);
  margin-left: 10px;
  top: 50%;
  margin-top: -25px;
}
#front-3{
  transform: translateZ(100px);
  bottom: 0;
  margin-bottom: 10px;
  margin-left: 10px;
}
#front-4{
  transform: translateZ(100px);
  margin-left: 140px;
  margin-top: 10px;
}
#front-5{
  transform: translateZ(100px);
  margin-left: 140px;
  top: 50%;
  margin-top: -25px;
}
#front-6{
  transform: translateZ(100px);
  margin-left: 140px;
  bottom: 0;
  margin-bottom: 10px;
}
#back-1{
  transform: rotateX(180deg) translateZ(100px);
  top: 50%;
  margin-top: -25px;
  right: 50%;
  margin-right: -25px;
}
.roll{
  width: 100px;
  margin: 0 auto;
  margin-top: 250px;
  border: 2px solid black;
  background-color: #0000CD;
  color: white;
  border-radius: 4px;
  font-family: "Century Gothic", CenturyGothic, AppleGothic, sans-serif;
}
.roll p{
  padding: 0px 0px;
  text-align: center;
  line-height: 1em;
}
.front {
  transform: rotateY(  0deg) translateZ(100px)
}
#cube .back {
  transform: rotateX(180deg) translateZ(100px)
}
#cube .right{
  transform: rotateY( 90deg) translateZ(100px)
}
#cube .left  {
  transform: rotateY(-90deg) translateZ(100px)
}
#cube .top   {
  transform: rotateX( 90deg) translateZ(100px)
}
#cube .bottom{
  transform: rotateX(-90deg) translateZ(100px)
}
.rolling{
  transform:    rotateY( 90deg )
}
#cube {
  transition: transform 2s;
}

Roll the Dice

A: Use only six div to create tha faces
Then use background-image to create the dots
See how to do it with the 3 face

div {
    width: 300px;
  height: 300px;
  background-color: black;
}

.three {
    background-image: radial-gradient(circle at 64px 64px, white 40px, transparent 40px),
      radial-gradient(circle at 150px 150px, white 40px, transparent 40px),
      radial-gradient(circle at 236px 236px, white 40px, transparent 40px);
}


text:
Q: what is the difference between the 2 cases; in java strings? why do these statements give different answers?
String s1="hello world";
String s2="hello world";
 System.out.println(s1.equals(s2));//true
    System.out.println(s1 == s2);//true

2nd case;
String s1=new String("hello world");
String s2=new String("hello world");
 System.out.println(s1.equals(s2));//true
    System.out.println(s1 == s2);//false

A: s1.equals(s2) compares the content of the two strings whereas s1 == s2 compares the objects' references.
Since both s1 and s2 are two different instances of the String class, their references are not equal. The == operator behaves this way for all Objects.

A: == just compares two references - i.e. it tests whether the two operands refer to the same object. s1 and s2 are two different objects so that's why the comparison is false.


text:
Q: How to force copy to output directory over eveything els? I have this code snippet in my .csproj file to force a specific version of System.Runtime.CompilerServices.Unsafe.dll to be copied into the output folder, after build:
  <Target Name="ForcingUnsafeSpecificVersion" AfterTargets="AfterBuild">
    <Copy SourceFiles="Path\System.Runtime.CompilerServices.Unsafe.dll" DestinationFolder="$(OutDir)" />
  </Target>

But it doesn't work. It doesn't override the version of the output directory, or probably something else is overriding it.
I also tried:
  <ItemGroup>
    <PackageReference Include="System.Runtime.CompilerServices.Unsafe" Version="4.6.0-preview.18571.3">
      <NoWarn>NU1605</NoWarn>
    </PackageReference>
  </ItemGroup>

Still no success. I also tried:
  <ItemGroup>
    <None Include="Path\System.Runtime.CompilerServices.Unsafe.dll">
      <Link>System.Runtime.CompilerServices.Unsafe.dll</Link>
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
  </ItemGroup>

Didn't work. Please note that this line works
  <ItemGroup>
    <None Include="Path\System.Runtime.CompilerServices.Unsafe.dll">
      <Link>System.Runtime.CompilerServices.Unsafe2.dll</Link>
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
  </ItemGroup>

If I add number 2 at the end of the name of the output file, then it works. But it seems that all of these build configurations fail and get overridden by something else.
How do I force this file to be copied into the output directory?

A: 1.It seems you're simply trying to copy something to OutDir after build.
  <Target Name="ForcingUnsafeSpecificVersion" AfterTargets="AfterBuild">
    <Copy SourceFiles="Path\System.Runtime.CompilerServices.Unsafe.dll" DestinationFolder="$(OutDir)" />
  </Target>

This task should always work if you just need to copy one file,if not, maybe it could be something about access. You can add a OverwriteReadOnlyFiles options to the command to check if it helps:
  <Target Name="ForcingUnsafeSpecificVersion" AfterTargets="AfterBuild">
    <Copy SourceFiles="Path\System.Runtime.CompilerServices.Unsafe.dll" DestinationFolder="$(OutDir)" OverwriteReadOnlyFiles="true"/>
  </Target>

2.If it still fails, change the msbuild verbosity to Detailed and check the detailed log in Output window:

You can figure out what happened in that process according to that log.
3.Also, you can try if you can copy one assembly to target path by copy or xcopy command in cmd.exe, if it works, then you can also consider using a Exec Task to do what you want.
4.If all above not helps, please share more details of your project type and the details about the content of the rpoject(nuget packages...). I guess if there's any misunderstanding about the $(OutDir), maybe actually you're trying to copy that to publish/deploy folder instead of normal output folder(bin\Debug\netcoreappx.x...).


text:
Q: Redirect http symlink to https Imagine I got "www.example.com". Files in /var/www. I have a symlink, mail -> /usr/share/squirrelmail.
Now I would like to redirect www.example.com/mail to https://www.example.com/mail using htaccess. I have tried so many things. Everytime I get internal server error. Please help me. Thank You in advance.

A: You can do it this way
RewriteEngine on

RewriteCond %{HTTPS} !on
RewriteCond %{REQUEST_URI} ^/mail$
RewriteRule ^.*$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]


text:
Q: How to get jobtracker details in hadoop1.2 cluster using hadoop api in java client. Issue: I am getting some cluster Details using hadoop api of namenode and datanode. Now i want to get IPAdd and port no. of jobtacker. But its not working using jobclient or jobtacker class.
Flow is like this:
1) user will enter namenode hostname and port
2) using hadoop api i am getting info about datanode and few other info of namenode.

Now how i can get information of jobtracker as it can be on namenode or it can be on some other machine with out giving any inputs from myside.
Pls refer link to get how i am getting cluster details using hadoop api  How to get the HDFS server metadata information in a java client?


text:
Q: force function to use value of variable HELP on javascript
force function to use the value of variable and not the variable name
var a = 12;
var b = 13;

element.setAttribute("onChange","calculate('a','b')");

calculate(x,y){

z = x + y;
alert(z)

}

how to pass value of variable to be use in function?

A: HTML:
<input type="checkbox" name="cb" id="cb">

JavaScript:
function calculate(x, y) {
    var z = x + y;
    alert(z);
}

var a = 12,
    b = 13,
    element = document.getElementById('cb');

element.onchange = function(e) {
    calculate(a, b);
};

DEMO
Also consider the usage of element.addEventListener

A: 'a' is not the variable a.  It's the string 'a'.  if you want the variable, take the quotes off.

A: .setAttribute("onChange","calculate(" + a + "," + b +")");


text:
Q: Using and displaying data using shiny I have a .mat file that contains certain data. How would I insert that data and be able to display it using Shiny?

A: Use the R.matlab package and the readMat() function to get the file into R, after that, you can build a shiny app from scratch the way you normally would.


text:
Q: Android: How to display an image file (building's floor map) and update the file? I have read ImageView. I want to use it to display the image file. Also, I have plan to provide functionality to update the file.
Would you teach me on how to display the image file. Then add group of radio buttons on the top to represent the floors. When I click 1st Floor, the imageview source change to image1.png, then click 2nd floor radio button, change to image2.png and so on..
I am using Android Platform 2.1-update1 and eclipse ADT for this thesis.
Here's my current code: (although there is some undesirable appearance of the radio buttons)
public class DisplayImageMapActivity extends Activity {
    ImageView iv;
    private final String FLOOR = "F";
    private final String storagePath = Environment.getExternalStorageDirectory() + "/keitaiAppH23";
    private final String localMapsPath = storagePath + "/localMaps";

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

        iv=(ImageView)findViewById(R.id.storageimage);

        RadioGroup levelRGroup = (RadioGroup) findViewById(R.id.level_rgroup);

        int levelSize = 8;
        for (int i = 0; i < levelSize; i++) {
            RadioButton levelRButton = new RadioButton(this);
            if(i==0) {
                levelRButton.setText(new StringBuffer(i+1).append(FLOOR).append("(start)"));
            } else if (i==7) {
                levelRButton.setText(new StringBuffer(i+1).append(FLOOR).append("(end)"));
            }
            levelRButton.setTag((i+1) + FLOOR);
            levelRButton.setLayoutParams(
                    new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1));

            levelRGroup.addView(levelRButton);
        }

        levelRGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            public void onCheckedChanged(RadioGroup group, final int checkedId) {
                iv.setImageURI(Uri.parse(new StringBuffer(localMapsPath)
                .append("/").append(group.findViewById(checkedId).getTag()).append(".gif").toString()));
                iv.invalidate();
            }
        });

        levelRGroup.getChildAt(0).performClick();

    }
}

main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/main_layout"
    >
    <RadioGroup android:id="@+id/level_rgroup"
        android:layout_width="wrap_content" android:orientation="horizontal"
        android:layout_height="wrap_content">
    </RadioGroup>
    <ImageView android:id="@+id/storageimage" android:src="@drawable/icon"
        android:layout_width="fill_parent" android:layout_height="wrap_content" />
</LinearLayout>

UPDATE:
Requirements:

*

*image file are set dynamically which obtain from external source
(e.g. DB,url). - Resolved

*radiobuttons are need to be dynamically created because it is not fix by 8F. It should be the number of target floors (e.g. start is 5F, end is 7F, so it should be 3 radiobuttons only 5F,6F,7F). - Resolved
Problems Encountered:

*

*Image cannot be updated. - Resolved

*All radiobuttons are not displayed as expected (Maybe due to wrong layout). - Not Yet Resolved

*When I click the radiobuttons to toggle the selection, it doesn't change on the 1F radiobutton. Note: It is OK for 2F to 8F. It switches the selection as expected. - Resolved
Screen shot:

A: These modifications should do it (there may be some typos):
Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/main_layout"
    >
    <ImageView android:layout_height="wrap_content" android:layout_width="fill_parent"
                android:id="@+id/iView" android:src="@drawable/icon"></ImageView>

    <RadioGroup android:id="@+id/level_rgroup"
        android:layout_width="fill_parent" android:orientation="horizontal"
        android:layout_height="wrap_content">
        <RadioButton android:id="@+id/rb1"
            android:width="106dip" android:height="80dip" android:text="Floor 1"/>
        <RadioButton android:id="@+id/rb2"
            android:width="106dip" android:height="80dip" android:text="Floor 2"/>
        <RadioButton android:id="@+id/rb3"
            android:width="106dip" android:height="80dip" android:text="Floor 3"/>
    </RadioGroup>
</LinearLayout>

Code:
public class DisplayImageMapActivity extends Activity {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            RadioGroup levelRGroup = (RadioGroup) mainLayout.findViewById(R.id.level_rgroup);
            final ImageView iView = (ImageView) findViewById(R.id.iView);

            levelRGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                public void onCheckedChanged(RadioGroup group, final int checkedId) {
                    switch (checkedId) {
                    case R.id.rb1:
                        iView.setImageResource(R.drawable.floor_1);
                        iView.invalidate();
                        break;
                    case R.id.rbM2:
                        iView.setImageResource(R.drawable.floor_2);
                        iView.invalidate();
                        break;
                    case R.id.rb3:
                        iView.setImageResource(R.drawable.floor_3);
                        iView.invalidate();
                        break;
                    }
                }
            });
        }
    }

You can add those buttons programatically if you want to, remember to set layout_width and other attributes for them if you want them to be seen (I put them in the XML since I had that code laying around).
Comment if you have any questions.


text:
Q: Tomcat Application Manager won't authenticate I'm running a local Tomcat 6.0 server. I can get to the main admin page from a browser. I've created a user for the Tomcat Application Manager by configuring tomcat-users.xml like so:
<tomcat-users>
      <role rolename="manager-gui" />
      <user username="myUsername" password="myPswd" roles="manager-gui" />
</tomcat-users>

When I type a cmd for TAM e.g. http://localhost:8080/manager/list, it prompts for credentials w/ the Authentication Required dialog. I enter myUsername/myPswd, and the dialog just re-prompts for credentials again.
What am I missing here?

A: The roles required to use the Manager application in Tomcat 7 were changed from the single manager role in Tomcat 6 to the following four roles:

*

*manager-gui - allows access to the HTML GUI and the status pages

*manager-script - allows access to the text interface and the status

*pages manager-jmx - allows access to the JMX proxy and the status

*pages manager-status - allows access to the status pages only

If you are using Tomcat 6 you need to change the role to "manager".

A: I had a problem like this too, I don't know if its a problem with my version of the manager/tomcat or if I have a newer tomcat then manager version but I've found that I have to use the legacy role 'manager' despite being on 6.0.x.
  <role rolename="manager" />
  <user username="myUsername" password="myPswd" roles="manager" />


text:
Q: Calculate age from "Date" HTML element I have an HTML form with "Date" element and a submit button. There are 2 functions. One is for calculating age from given birth date in the "date" HTML element. The other function is for comparing the age with minimal allowed age. I need help to complete it. See my questions in remarks in code. Yes, I have seen other similar questions. I would like to learn and not just copy/paste. If I understand what is wrong with my code / syntax, then I will learn better. Thanks in advance.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0  Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

   <title></title>

     <form>
      Date Of Birth: <input type="date" name="date of birth" id="date" />
      <input type="submit" name="submit" id="submit" onClick="_setAge();" />

     </form>

A: You can add or subtract javascript dates by basic mathematical functions.
Just make a new Date for today var Today = new Date() and then substract the date from the form. You get the difference in milliseconds.
Now you just need to convert them to years/months by dividing them by (1000*60*60*24*365)
So just do:
var difference = (curDate - birth_date)/((1000*60*60*24*365);
var differenceString = "The difference is: " + difference.toFixed(1) + " years.";

The toFixed(1); returns your number with 1 decimal point.
And always remember JavaScripts Dates Months are zero-based.
Your second function should work then too.
Here is a working fiddle

A: This will work you can simply replace code with this
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0  Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title></title>

    <form>
    Date Of Birth:
    <input type="date" name="date of birth" id="date" />
    <input type="submit" name="submit" id="submit" onclick="_setAge();" />
    </form>

A: I've managed to get it to work. Credit also goes to https://stackoverflow.com/users/444991/matt for the part I borrowed from him here:
https://stackoverflow.com/a/4076440/3189118
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

     <title></title>

<form>
    Date Of Birth: <input type="date" name="date of birth" id="date" />
    <input type="submit" name="submit" id="submit" onClick="_setAge();" />

</form>

A:
Try This..

<!DOCTYPE html>

    <title>Person Details</title>

    <form>
        Birthday: <input type="date" name="bday" id="birth_date">

    </form>

    <button onclick="myFunction()">view</button>

    `


text:
Q: True for all values but 1, cannot figure out why (VBA) My loop goes over a range of cells and compares the values:
For k = 7 To wsPlany.UsedRange.Rows.Count
    If wsPlany.Cells(k, 1) = datu Then
        'code here
    End If
Next k

Basically the cells are cells with numbers, 1, 2, 3 ... and the datuis a number too. It all works but for the value 1 and I cannot figure out why.
Even debug.printing something like: wsPlany.Cells(k, 1), datu and comparing them into next line confirms that if value is 2 or higher, it will return true for that line, if it is 1 exactly, it returns false as if it were comparing with other number (but I see they are the same as they are side by side in debug.print).

A: A simple addition of 1 line where I turn the values to Integers no matter what data type they were before solved the problem.
For k = 7 To wsPlany.UsedRange.Rows.Count
    'turns the values to integers first
    wsPlany.Cells(k, 1).Value = CInt(wsPlany.Cells(k,1))

    If wsPlany.Cells(k, 1) = datu Then
        'code here
    End If
Next k


text:
Q: Ember: Model's property changes not detected in computed property I have 2 models.
models/calendar.js
export default Model.extend({
  holidays: hasMany('holiday'),
  date: attr(),
  occasion: attr()
})

models/holiday.js
export default Model.extend({
  calendar: belongsTo('calendar')
})

And a component.
holidays/component.js
export default Component.extend({
  init() {
    this._super(...arguments);
    this.store.find('calendar', this.get('calendarId'))
      .then(calendar => this.set('calendar', calendar));
  },

  calendarIsDirty: computed('calendar.holidays.@each.{date,occasion}', function () {
    // This is not executed
  })
})

holidays/template.hbs
{{each calendar.holidays as |holiday|}}
  {{input value=holiday.date}}
  {{input value=holiday.occasion}}
{{/each}}

{{#if calendarIsDirty}}
  <button>Save</button>
{{/if}}

I'm displaying the holidays in the UI and when the user edits the date or occasion of the holiday, I want to do something. But the computed property that listens to these changes is not executed at all. Kindly help me with this.
I have an 'Add Holiday' button that adds an empty holiday that the user can edit. When I add a holiday, that computed property is executed. Only when I make changes to an existing holiday, the computed property is not executed.

A: your problem is simple that you assume that this.store.findAll('calendar') returns a single calendar, but it returns a list of calendars.
So with this: this.set('calendar', calendar) you set calendar to an array of calendars.
Next your dependency key calendar.holidays.@each is wrong because calendar is an array and so has no property holidays.
If you want a single calendar you should do a findId or queryRecord. If you want an array of calendars you should change your code accordingly. However you need to know that foo.@each.bar.@each is not a valid dependency key - this is a limitation of ember. you would need to work around this.


text:
Q: How to give permission to a pipeline to access a resource in Azure DevOps using CLI commands? I have created an end-to-end CI/CD pipeline in Azure DevOps. I am trying to clone the original repository and create new pipelines using the Azure CLI(v1), using the below command:
az pipelines create --name {PIPELINE_NAME} --description {PIPELINE_DESCRIPTION} --repository {REPOSITORY_NAME} --branch {BRANCH_NAME} --repository-type {tfsgit} --project {PROJECT_NAME} --organization {ORGANIZATION_NAME} --yml-path {YAML_PATH} --service-connection {SERVICE_CONNECTION_NAME} --subscription {SUBCRIPTION_ID} --skip-first-run {true}
I am trying to execute the newly created pipeline using the below command:
az pipelines build queue --branch {BRANCH_NAME} --org {ORGANIZATION_NAME} --project {PROJECT_NAME} --definition-id {PIPELINE_ID} --subscription {SUBCRIPTION_ID}
The problem is, after executing the above commands, I always need to go to the Azure DevOps portal and manually authorize the pipeline to use the Service Connection. It shows a message like this in the portal This pipeline needs permission to access a resource before this run can continue.
I am using this command to log in to the portal echo {PAT} | az devops login --organization {ORGANIZATION_NAME}.
How can I avoid this problem of not going to the portal every time to authorize the pipeline to use the service connection? Is there a way I can do this using the CLI?
PS: All the above commands are executed using Python SubProcess.

A: According to the description, you could check the following steps:

*

*Please check the security of the service connection: Project Settings>Pipelines>Service connections name (the service connection you use in the YAML pipeline)>…(In the upper right corner of the service connection page)>Security, then you can check whether there is a YAML pipeline you authorized under Pipeline permissions. You could also try to grant access permission to all pipelines.

*Check the pipeline permissions. Project Collection Administrators, Project Administrators, and Build Administrators are given all of the above permissions by default.


text:
Q: Template code to split a post and print a custom field? So I want a blog post but in the center of every blog post I want to split the content and print a custom field attached to the blog post type.
Ie you field called "Blog Quote" and the user will enter "Some sample text here." Then put the body of the post in the standard body text area.
Then in the template I want to have:

So the final result on page would look like:
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Incidunt debitis accusantium cupiditate possimus laboriosam corporis officia quas, eaque facere, porro odio sit! Quia consequuntur nemo repellendus, et consectetur, voluptatem voluptates adipisci beatae quidem a cum labore dignissimos tempore officia harum. Doloremque quis cupiditate recusandae hic ad error accusamus voluptate nemo harum fugiat, minima, repellendus non?
Some sample text here.
Autem similique porro quae quis sapiente voluptatibus nam distinctio sit necessitatibus, perferendis esse accusamus dignissimos hic obcaecati laudantium libero enim molestiae eaque perspiciatis quia ipsa soluta voluptates aperiam voluptatem! Ratione aspernatur labore repellat facere officiis consequuntur pariatur sed? Explicabo excepturi neque eligendi provident, molestias distinctio quae maxime ut aperiam numquam reprehenderit qui ea molestiae libero exercitationem doloribus itaque corrupti.
EDIT: I haven't tried anything because I don't know where to begin but I'm thinking maybe I add some php to strip the 1st X amount of characters on the render content and then do the opposite for the second break. That should handle the content, maybe? As far as the custom field, I'm hoping there's a hook that can pull the currently viewed custom field or something? If this is the right direction, any documentation you can point me too would be great.

A: I'd suggest doing it this way to avoid running into problems where you split within a sentence/paragraph.
Try splitting on
 - then put the first element (first paragraph) into
 and the rest (if any) into
 in your template.
It should be something like this (assuming $content has the html for the post)
$paragraphs = preg_split('/<p/i', $content);
array_shift($paragraphs); // ( remove first empty element
$first_half = '<p' . array_shift($paragraphs);
$second_half = '<p' . implode('<p', $paragraphs);

I chose <p to split on since presumably the content will be formatted into paragraphis with
 tags - but could have inline styles/classes attached, so you can't split on a
.
As far as getting the post's custom field, this should be a good start.


text:
Q: How to keep GoogleAPIClient always connected I am using GoogleAPIClient to read location information. I want this to be always connected. How to ensure that it is always connected. One way is to reconnect it whenever connection failure callbacks are invoked.
What are the use-case at which below callbacks are triggered?
1.OnConnectionFailedListener -> onConnectionFailed
2. ConnectionCallbacks -> onConnectionSuspended
I tried force stopping google play services but did not get callback [onConnectionSuspended]
Will there be any issue (battery, performance) if GoogleAPIClient is always connected?

A: From the official documentation you can find the following:
// Create an instance of GoogleAPIClient.
if (mGoogleApiClient == null) {
     mGoogleApiClient = new GoogleApiClient.Builder(this)
         .addConnectionCallbacks(mConnectionCallbacks)
         .addOnConnectionFailedListener(mConnectionFailedCallbacks)
         .addApi(LocationServices.API)
         .build();
}
//you will need to specify the callbacks.

//Of course, you will need to connected:
protected void onStart() {
     mGoogleApiClient.connect();
     super.onStart();
}

//Disconnect
protected void onStop() {
     mGoogleApiClient.disconnect();
     super.onStop();
}

//get last location
public Location getLastLocation(){
//you need to be connected. Therefore this must be in the onConnected
//method of the mConnectionCallbacks.
     mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
            mGoogleApiClient);
}

Link: Getting the Last Known Location
EDIT:
The only use case for having it connected (or the only I know) is for when you want to have a service that tracks your location even when the app is in the background.

Read here some interesting tutorials about this:
http://www.101apps.co.za/articles/services-tutorials-part-2-a-foreground-service.html

http://www.edureka.co/blog/android-tutorials-beginners-service-component/
Edit 2

Links for details about failed connection:
1. onConnectionFailed
2. Accessing the Google Api


text:
Q: Get Audio Video Images From SdCard Android Requires Minimum sdk 19 I Am Working In A Project Where I Have To get audio, video , images from SdCard and upload to server
I get The Images Quite Easily but Issue Is With The Audio And Video . Where Cursor Return Null
I Have Android lollipop .
This Is Code :-
Cursor cursor = getActivity().managedQuery(selectedImageUri, projection, null,null, null);
    int data_column_index = cursor.getColumnIndexOrThrow("_data");
   int size_column_index = cursor.getColumnIndexOrThrow("_size");
   int name_column_index = cursor.getColumnIndexOrThrow("_display_name");

It Returns null
Now I am using This :-
https://limbaniandroid.blogspot.in/2014/03/how-to-get-absolute-path-when-select.html
But issue is, it requires minimum SDK 19, Warning/error in android studio .But it is compiling and running fine . I have Android lollipop
so its good to kept moving with this . Or I have to do my projects minimum SDK 19
Will it produce any error while uploading assigned .apk .
Because I have to upload it within 2, 3 days
Or I have to write separate code for lower version
Any help please.

A: Please try the following code:
Add the below file as DocumentPathUtil.java
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

public class DocumentPathUtil {

    /**
     * Get a file path from a Uri. This will get the the path for Storage Access
     * Framework Documents, as well as the _data field for the MediaStore and
     * other file-based ContentProviders.
     *
     * @param context The context.
     * @param uri     The Uri to query.
     * @author paulburke
     */
    @TargetApi(Build.VERSION_CODES.KITKAT)
    public static String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }

                // TODO handle non-primary volumes
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{
                        split[1]
                };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context       The context.
     * @param uri           The Uri to query.
     * @param selection     (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    public static String getFileName(String path) {
        String fileNameSegments[] = path.split("/");
        return fileNameSegments[fileNameSegments.length - 1];
    }
}

And in onActivityResult use:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {
        case RESULT_LOAD_DOC:
            if (resultCode == Activity.RESULT_OK && data != null) {
                String selectedImagePath = ImagePathUtil.getPath(this, data.getData());
            }
            break;
    }
}

where selectedImagePath will give you the path to use.
RESULT_LOAD_DOC is the identifier used to check which data is being fetched.


text:
Q: Toad For MySql Give error on new connection Recently i installed Toad For MySQL latest version but when ever i create new connection i got this error.

A: Please check following condition

*

*root user has privilege to connect to localhost

*you have given right password for the user root


text:
Q: Blink led infinitely while the rest of the code is running in Matlab-Arduino I am new to arduino and working on a college project about tic tac toe game. In there, main code must script on matlab using arduino. There are two players who can input and light up relevant leds.What I want is to blink the leds of player 2 until the game is finished. I cannot use while statement as it has to be run infinitely and hence the rest of the code unable to run. So what I can do to this problem? Is there any solutions available?
Thank you.

A: You can use a timer interrupt to blink the LED without changing anything in your main loop.
Each time the timer 'fires' your interrupt handler is called, and in that handler you can turn the LED on and off.
This looks like a good tutorial on the subject.


text:
Q: Триггер, выдающий сообщение... Помогите, пожалуйста. Не получается создать триггер такой, чтоб выдавал сообщение, допустим, Таблица1 и Таблица2. Сообщение при вводе в Таблицу2, когда значение Поля1 Таблицы1 допустим, < 5. Сообщение, что значение меньше 5, должно выходить в Таблице2. Здесь триггер на какую таблицу на 1 или на 2 надо создавать?! помогите пожалуйста... SQL Server.
A: Не совсем понятно, что нужно :(. Пример триггера с выводом сообщения и откатом действия DML инструкции вызвавшего триггер:
CREATE TABLE testT(Val int NULL,RowidV nvarchar(10))
CREATE TABLE testT2(Val int NULL,RowidV nvarchar(10))

create TRIGGER CheckVal_I ON testT
INSTEAD OF INSERT AS
BEGIN
   SET NOCOUNT ON

   IF EXISTS(SELECT 1 FROM inserted WHERE Val < 5)
    BEGIN
      RAISERROR(59998, 16, 1, N'Val less 5')
      RETURN
    END
   insert into testT2(Val,RowidV) select Val,Rowid0 from inserted
   insert into testT(Val,RowidV)  select Val,Rowid0 from inserted
END


text:
Q: wanted: simple HTML file that does disclosure triangle  hide/reveal I have a program that produces a text report. I want it to make an HTML report with multiple disclosure triangles, so that when you click a triangle more of the report shows or hides. I am okay with embedding JavaScript inside the file, but I really want it all in a single file, with no additional files.  Is there an easy way to do this with modern browsers?

A: If you don't care about compatibility with Internet Explorer, you could use the  html tag: http://www.w3schools.com/tags/tag_details.asp
Its a very quick way to prototype disclosure triangles.
For example:

  The contents of the summary tag is always visible

Everything else inside the details tag will be hidden in a disclosure triangle

A: The simplest way is something like this:

Example header 1

bodytext 1

Example header 2

bodytext 2

Example header 3

bodytext 3

I have made a simple working example here: http://jsfiddle.net/NXuQt/1/
It isn't pretty but should give you the simple template you need.
Note that in this solution, the entire header is click-able... I figure adding an image and changing it as part of the click event is something you can take care of yoruself, otherwise let me know :)
Note: The javascript is based on the inclusion of the jQuery library.
EDIT: I updated the answer to copy/paste ready working code, the reason you couldn't make it work as it was, was because i had only taken the essentials from the fiddle example. The fiddle automatically ran the click handler initialization at DOMready, which the updated example now has built in :)

A: With straight HTML, no. That's not what it's for. You will need to use a scripting language, either JavaScript or VBScript, most likely.
This is a script I've used in the past (not mine, but I don't have the URI of the original):
var timerlen = 5;
var slideAniLen = 250;

var timerID = new Array();
var startTime = new Array();
var obj = new Array();
var endHeight = new Array();
var moving = new Array();
var dir = new Array();

function slidedown(objname)
{
    if(moving[objname])
        return;

    if(document.getElementById(objname).style.display != "none")
        return; // cannot slide down something that is already visible

    moving[objname] = true;
    dir[objname] = "down";
    startslide(objname);
}

function slideup(objname)
{
    if(moving[objname])
        return;

    if(document.getElementById(objname).style.display == "none")
        return; // cannot slide up something that is already hidden

    moving[objname] = true;
    dir[objname] = "up";
    startslide(objname);
}

function startslide(objname)
{
    obj[objname] = document.getElementById(objname);

    endHeight[objname] = parseInt(obj[objname].style.height);
    startTime[objname] = (new Date()).getTime();

    if(dir[objname] == "down")
    {
        obj[objname].style.height = "1px";
    }

    obj[objname].style.display = "block";

    timerID[objname] = setInterval('slidetick(\'' + objname + '\');',timerlen);
}

function slidetick(objname)
{
    var elapsed = (new Date()).getTime() - startTime[objname];

    if (elapsed > slideAniLen)
    {
        endSlide(objname)
    }
    else
    {
        var d =Math.round(elapsed / slideAniLen * endHeight[objname]);
        if(dir[objname] == "up")
            d = endHeight[objname] - d;

        obj[objname].style.height = d + "px";
    }

    return;
}

function endSlide(objname)
{
    clearInterval(timerID[objname]);

    if(dir[objname] == "up")
        obj[objname].style.display = "none";

    obj[objname].style.height = endHeight[objname] + "px";

    delete(moving[objname]);
    delete(timerID[objname]);
    delete(startTime[objname]);
    delete(endHeight[objname]);
    delete(obj[objname]);
    delete(dir[objname]);

    return;
}

function toggleSlide(objname)
{
    if(document.getElementById(objname).style.display == "none")
    {
        // div is hidden, so let's slide down
        slidedown(objname);
    }
    else
    {
        // div is not hidden, so slide up
        slideup(objname);
    }
}

You would assign a call to toggleSlide() to the onclick() event of the element you want to toggle.

A: CSS:
.hidden {
    display: none;
}

Javascript:
function createSection(section, hidden) {
    var triangle = section.children[0]; // assumes the triangle image is the first child of a section (see HTML)
    var contents = section.children[1];
    triangle.onclick = function() {
        if (contents.className.indexOf("hidden") != -1) { // the section is hidden
            contents.className = contents.className.replace("hidden", "");
        } else { // the section wasn't hidden
            contents.className += " hidden";
        }
    }
    if (hidden) {
        contents.className += " hidden";
    }
}

    // Create the sections when window loads
window.onload = function() {
    createSection(document.getElementById("section1"));
    createSection(document.getElementById("section2"), true);
}

HTML:

This is the section content

this section is hidden by default

Obviously you would have to change some things to your own html file

A: Well, after some fiddling around, I was able to make a file that does what I want using the switchcontent.js and switchicon.js javascript files I found at http://www.dynamicdrive.com/dynamicindex17/switchcontent2.htm
Here's my code, based on editing down theirs:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Dynamic Drive DHTML scripts- Switch Content Script II (icon based)</title>

How hot is our Sun?

The surface of the Sun is around 5800 Kelvin, while the core reaches over 15 million Kelvin.

How big is our Sun in terms of mass?

The contains more than 99.8% of the total mass of our Solar System.

It looks like this when closed:
▶ How hot is our Sun?
▶ How big is our Sun in terms of mass?

And this when opened:
▼ How hot is our Sun?
The surface of the Sun is around 5800 Kelvin, while the core reaches over 15 million Kelvin.
▼ How big is our Sun in terms of mass?
The contains more than 99.8% of the total mass of our Solar System.


text:
Q: Runtime error embedding Javascript call in ASPX page I am trying to get a basic webpage up and running that displays the video for my tests I create using SauceLabs. To do this, they provide a service to embed the video in Javascript.
I am creating the web page in ASP in Visual Studio 2010. However, I'm getting an error when I navigate to my page.
My ASP page looks as follows and simply takes in a jobID (jID) and an access code (code) which are fed into the JavaScript call.
   <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Show Video.aspx.cs" Inherits="ResultsDisplay.Show_Video" %>

   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

       <title>Test Video</title>

       <form id="form1" runat="server">

       </form>

However, when I access the page, Visual Studio throws an error (in a dynamic script block) as follows:

Microsoft JScript runtime error: 'flowplayer' is undefined

Although I can ignore the error, nothing appears on my webpage.
Any ideas?
Thanks,
Gordon

A: There is some JavaScript code trying to use a variable named flowplayer somewhere and the variable has not been defined. Can you paste the rendered source from the script tag in your browser's address bar and get the code back? Have you tried reloading the page with Ctrl-F5? Does the script assume that there is a variable named flowplayer already defined when the page loads? These are a few debugging questions you might want to look into.


text:
Q: Target an opener after the popup has been refreshed I have a function that opens a popup
windowName = window.open("scriptName.php?&value="+value, "windowName");
windowName.focus();

That popup submits to itself using function that reloads the page with new variables passed in
Is there any way I can target the original opener after the script has refreshed?
window.opener.functionName() doesn't seem to work in this case


text:
Q: Why my RoR destroy links don't work? there is a problem puzzling me for quite a time now related to Ruby on Rails applications. I tested the very same workflow in 3 different environments and in none of them I am able to get the "destroy" links to work!
Using this setup:

*

*RVM 1.17.4

*Ruby 1.9.3p327

*Rails 3.2.9

Then, executed, literally, these commands:
$ rails new foo
$ cd foo/
$ rails g scaffold bar title:string
$ rake db:migrate

It generated this controller:
  # DELETE /bars/1
  # DELETE /bars/1.json
  def destroy
    @bar = Bar.find(params[:id])
    @bar.destroy

    respond_to do |format|
      format.html { redirect_to bars_url }
      format.json { head :no_content }
    end
  end

This is the destroy line in the view:
<%= link_to 'Destroy', bar, method: :delete, data: { confirm: 'Are you sure?' } %>

This is the code in the final page:
Destroy

In the layout I have these:
  <%= stylesheet_link_tag    "application", :media => "all" %>
  <%= javascript_include_tag "application" %>
  <%= csrf_meta_tags %>

And in the application.js I have these:
//= require jquery
//= require jquery_ujs
//= require_tree .

These are the lines in the html output:

These are the routes:
    bars GET    /bars(.:format)          bars#index
         POST   /bars(.:format)          bars#create
 new_bar GET    /bars/new(.:format)      bars#new
edit_bar GET    /bars/:id/edit(.:format) bars#edit
     bar GET    /bars/:id(.:format)      bars#show
         PUT    /bars/:id(.:format)      bars#update
         DELETE /bars/:id(.:format)      bars#destroy

Anyone came to the same results? Why doesn't it work?
The workarounds I found in the Internet are suggesting the javascript is not properly loaded and sometimes it is suggested to change the action from DELETE to GET. Some suggest changing the link for a button. Anyway, the confirmation never shows up and it is really annoying to rewrite all the destroy actions in all views.

A: Given the html, there should be no problem. Therefore this is likely a client-side problem, not a server-side problem.
As you said...

The workarounds I found in the Internet are suggesting the javascript is not properly loaded...

*

*You probably have a browser without javascript support, or else you have disabled javascript.
Which browsers have you tested this in? Try Firefox, and in the Options window, ensure the Content tab has Enable javascript checked.

*Alternatively, go to /assets/jquery.js?body=1 and /assets/jquery_ujs.js?body=1 in your browser to ensure that the javascript framework files are there. If not, you need to add these to your assets directory, and may need to run rake assets:precompile if you are running in a production environment.

A: If JavaScript is enabled and you sure that destroy action must work, but link doesn't send the right HTTP_METHOD = DELETE, and routes setting are right, then try to change DOCTYPE:
<!DOCTYPE html>


text:
Q: Noetherian local domain of dimension one While revising for my exam in Commutative algebra, I came across the following statement that:

Let $A$ be a Noetherian local domain of dimension one. Let $x,y \in A$ with $x \neq 0$ and $y \in \mathfrak{m}$. Then $ax = y^n$ for some $a \in A$ and $n \geq 1$.

But I don't really understand why? Does this have anything to do with that in a Noetherian local domain every non-zero ideal can be written as a power of the maximal ideal? If yes, why do we even need an $a \in A$?
Thanks in advance!

A: If $A$ is a DVR, then every nonzero ideal in a DVR is a power of the maximal ideal $\mathfrak{m}$, and we have $x=ut^n$ for $t\in \mathfrak{m}$ being a uniformizer. However, if $A$ is not a DVR, then this is not true in general. Then
$\mathfrak{m}$ is not principal.


text: Q: Определить часовой пояс стандартной библиотекой time.h возникла необходимость определения и вывода часового пояса, поискал в интернете и не нашел как сделать это стандартными методами не используя консоль, так вообще можно сделать? Или обязательно нужно обращаться в консоль?


text:
Q: WPF Combobox - PreSelect An Item I want to pre-select a combobox, (select an existing item) from the itemssource. Here is my class model and xaml syntax.
Class ViewModelSample
{
 Public List<Animal> Animals;
 Public LivingBeing  LivingBeingInst {get; set;}
}

Class LivingBeing
{
  Public Animal AnimalInst {get; set;}
}

--------------------------------------------------------------------
<Combobox ItemsSource={Binding Animals} SelectedItem={Binding LivingBeingInst.AnimalInst}
 DisplayMemeber = SomePropertyInAnimal>
--------------------------------------------------------------------------

But this doesnt work. All I want is, when the xaml shows up, I need the combobox to be pre-selected with the item given in SelectedItem.
Any help is much appreciated. Thanks, Mani

A: Thanks for the input and I have resolved this. I had implemented INotifyPropertyChanged but that wasnt the issue.
The combobox's SelectedItem should be one of the values from the Collection that is given in ItemsSource. Though, AnimalInst is of type Animal, it is not one of the objects in te ItemsSource. So what I did is, declared a SelectedAnimal property, binded that to SelectedItem. 'SelectedAnimal' will return the same instance from 'Animals' collection comparing AnimalInst.Name. An example as in below. (Schedules is the collection).
 private ISchedule _selectedSchedule;
       public ISchedule SelectedSchedule
        {
            get
            {
                if(_selectedSchedule != null)
                {
                    var schedule = this.Schedules.Where(item => item.GlobalCodesId == _selectedSchedule.GlobalCodesId).FirstOrDefault();
                    return schedule;
                }
                return _selectedSchedule;
            }
           set
           {
               _selectedSchedule = value;
               base.NotifyPropertyChanged("SelectedSchedule");
           }
        }

A: Normally you'd have a List (in your case Animals) off of your ViewModel and a SelectedAnimal property, in your case, it appears that the LivingBeingInst property is supposed to be the selected animal from the list.
To get something like that to work, you'll probably have to write some code to convert a LivingBeing into an animal and back via ValueConverter.
However, I believe your best bet would be to create a SelectedAnimal property to store the selected Animal.
In your constructor, or wherever you initially populate the list of Animals, you can set the SelectedAnimal to the first element in the list.

A: The initial value of the SelectedItem needs to be an instance of an object that is a member of the ComboBox's ItemsSource. In this example, LivingBeingInst.AnimalInst would need to be in the Animals collection.
You could also have a property that finds the corresponding item to LivingBeingInst.AnimalInst in the Animals collection, like how the Everything Matters 's answer does.

A: You don't have change notification implemented in these classes.  So unless you've populated all of these properties in the respective classes' constructors, there's no way for the bindings to know that you've done so.
At least, that's my guess from the non-working, non-compilable, not-really-code that you've posted.  Generally speaking, you'll get more useful answers if you post real code, especially if you take the time to implement the smallest minimal subset of your existing code that still exhibits the problem you're trying to solve.  (Among other things, you might find the answer yourself when you do that.)


text:
Q: two commands be implemented same time for each item of list I have a list of links and I am trying to execute two commands for each item of the list before executing those commands for next item of the list.
This is what I have so far:
 set max-links sort-on [(- label)] link-set [max-one-of my-in-links [label]] of turtles
     foreach max-links
      [
        the-links -> ask the-links [show end1]
      ask the links [ask end1 [ask my-out-links with [not member? self max-links] [die]]]
      ask the links  [ask end2 [ask my-in-links with [not member? self max-links] [die]]]
    ]

the problem right now is that the commands first begin to execute for all end1 in the entire list then for end2, whereas I want both commands execute for each item before moving on to the next item of list