text:
Q: Removing a character from my stringbuilder I am having the following string builder as msrtResult, which is quite long:
mstrResult.Append(rtbResult.Text).Append("})})" + Environment.NewLine)

How can I remove the last "," from mstrResult Now? (it is in the middle of that mstrResult and it is not the last character of the whole string since I am appending strings to it)
I should do it before adding the newline.
Thanks

A: You can just decrease the length to shorten the string (C#):
mstrResult.Length -= 1;

EDIT:
After you updated you question, I think I know what you want :) How about this:
mstrResult.Append(rtbResult.Text).Append("})})" + Environment.NewLine);
var index = mstrResult.ToString().LastIndexOf(',');
if (index >= 0)
    mstrResult.Remove(index, 1);

A: You can use StringBuilder.Remove() if you know the position of the character(s) you want to remove.
I'd imagine that it would be easier not to add it in the first place.

Your updated question talks about removing the last comma character. I'm guessing you want to do this to avoid creating a message that looks like this:

My shopping list contained milk, eggs,
  butter, and fish.

You'd assemble this in a loop, iterating over an array.  Usually you can write the loop so that you simply choose (e.g. with an if statement) not to add the command when you are in the final iteration of the loop.

A: To just remove the last character you appended use below: (This is VB but C should work similarly)
Dim c As New StringBuilder
c.Remove(c.Length - 1, 1)

A: Add a StringBuilder extension.
public static StringBuilder RemoveLast(this StringBuilder sb, string value)
{
    if(sb.Length < 1) return sb;
    sb.Remove(sb.ToString().LastIndexOf(value), value.Length);
    return sb;
}

then invoke:
yourStringBuilder.RemoveLast(",");

A: Try
mstrResult.Remove( mstrResult.Length - 1 - Environment.NewLine.Length
                 , Environment.NewLine.Length);

A: Use:
stringbuilder blahh = new stringbuilder()
int searchKey = blahh.LastIndexOf(',');

then call
blahh.Remove( searchKey, 1).Insert(searchKey, " and"); or a blank.


text:
Q: OpenMP detects only a single core on multi-socket/multi-core system I program in C++ and uses OpenMP for parallelization. The machine has 2 CPU sockets and 8 cores per each socket.
Since I compile with intel compiler, I set the following environment variables
export KMP_AFFINITY=verbose,scatter

With verbose option, I can see the following messages when running the binary.
[0] OMP: Info #204: KMP_AFFINITY: decoding x2APIC ids.
[0] OMP: Info #202: KMP_AFFINITY: Affinity capable, using global cpuid leaf 11 info
[0] OMP: Info #154: KMP_AFFINITY: Initial OS proc set respected: {0}
[0] OMP: Info #156: KMP_AFFINITY: 1 available OS procs
[0] OMP: Info #157: KMP_AFFINITY: Uniform topology
[0] OMP: Info #159: KMP_AFFINITY: 1 packages x 1 cores/pkg x 1 threads/core (1 total cores)
[0] OMP: Info #206: KMP_AFFINITY: OS proc to physical thread map:
[0] OMP: Info #171: KMP_AFFINITY: OS proc 0 maps to package 0
[0] OMP: Info #242: KMP_AFFINITY: pid 12759 thread 0 bound to OS proc set {0}
[0] OMP: Info #242: KMP_AFFINITY: pid 12759 thread 14 bound to OS proc set {0}
[0] OMP: Info #242: KMP_AFFINITY: pid 12759 thread 15 bound to OS proc set {0}
[0] OMP: Info #242: KMP_AFFINITY: pid 12759 thread 11 bound to OS proc set {0}
[0] OMP: Info #242: KMP_AFFINITY: pid 12759 thread 6 bound to OS proc set {0}
[0] OMP: Info #242: KMP_AFFINITY: pid 12759 thread 7 bound to OS proc set {0}
[0] OMP: Info #242: KMP_AFFINITY: pid 12759 thread 8 bound to OS proc set {0}
[0] OMP: Info #242: KMP_AFFINITY: pid 12759 thread 9 bound to OS proc set {0}
[0] OMP: Info #242: KMP_AFFINITY: pid 12759 thread 10 bound to OS proc set {0}
[0] OMP: Info #242: KMP_AFFINITY: pid 12759 thread 13 bound to OS proc set {0}
[0] OMP: Info #242: KMP_AFFINITY: pid 12759 thread 12 bound to OS proc set {0}

As you can see, OMP cannot detect the correct number of packages (sockets) and cores per package. As a result, all the threads are pinned to a single core.
How can I resolve this issue? Where should I start?

A: I answer my question.
My program sets the CPU affinity of the main thread as follows:
...
CPU_ZERO(&cpuset);
CPU_SET(0, &cpuset);
pid_t tid = (pid_t) syscall(SYS_gettid);
sched_setaffinity(tid, sizeof(cpu_set_t), &cpuset);

unsigned long mask = -1;
int rc = sched_getaffinity(tid, sizeof(unsigned long), (cpu_set_t*) &mask);
if (rc != 0) {
  std::cout << "ERROR calling pthread_setaffinity_np; " << rc << std::endl;
  abort();
}

...
The OpenMP threads spawned after the setaffinitiy syscall are all bound to the same core that the main thread is bound.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ear deployed from IDE fails, but install from maven build works Red Hat JBoss Developer Studio
Version: 10.2.0.GA
Build id: GA-v20161125-1418-B55
Build date: 20161125-1418
I have an maven EAR project with separate projects for:
war
ejb-jar
ejb-client ( local interfaces)
If I run a mvn clean install  on the parent project from the command line, I can deploy the generated ear file to jboss eap7 with no problem.  However, if I perform a clean/build all from the IDE, then select run-as on server, I get the following error:
    Caused by: java.lang.IllegalStateException: WFLYEE0042: Failed to
construct component instance
        Caused by: java.lang.IllegalArgumentException: Can not set
com.hsntech.hif.eao.OperationsCache field
com.hsntech.hif.application.HIFManagement.opCache to
com.hsntech.hif.eao.OperationsCache$$$view8"}}

the ejb-client jar project contains the interface:
@Local
public interface OperationsCache  {

    Map<String, OperationMapping> getOperationsMaps() throws HIFEJBException;

    void resetCache();
}

and the ejb.jar impelemtation contains:
@Singleton
@ConcurrencyManagement(ConcurrencyManagementType.CONTAINER)
public class OperationsCacheImpl implements OperationsCache, Observer {

The EJB is being created in the war project in this class:
@Singleton
@Startup
public class HIFManagement implements HIFManagementMBean {

@EJB
private OperationsCache opCache;

A: My money goes to class loading issue. Having Eclipse build and package your app is not exactly immune to errors. IDE will keep its own build instructions, how to assemble your app into a deployable .ear artifact. You can fiddle with the settings in project settings/web assembly. I guess that if you compare the Eclipse built ear with maven built one, there will be differences in the classes contained within modules or libs.
If you are using maven ejb plugin, to filter out implementation classes from the ejb-client module, then I do not think there is a way how to get the same thing working in Eclipse. That being said, I do not think that you actually need a separate module for ejb-client. War module within ear will have access to all classes contained in jar supermodules of the parent ear module.  So just add you ejb-jar as dependency to your war module with scope provided.

A: I will going to give you a cure for all possible problems:
 1. Arrange order of modules at parent pom:
<modules>
    <module>core-module</module>
    <module>depends-on-core</module>
    <module>depends-on-core2</module>
    <module>depends-on-depends-on-core</module>
</modules>

*mvn eclipse:clean don't worry Developer Studio is based on eclipse so it will be no problem.

*mvn eclipse:eclipse

*Run on server

A: General advice: Don't do it from Eclipse anyway, it's prone to random errors due to classloading,  etc...
But here are some possible hints:

*

*check if you're using the same Maven runtime from console and Eclipse. Some Eclipse distros ship with a weird build-in version

*check if Eclipse is set to ignore some Maven plugins

*check if the JBoss-Deployment works via console. There is a plugin. If you can get to work, you could use that from Eclipse, instead of the build-in feature.


text:
Q: Debug steps for celery chord not running in Django with RabbitMQ broker and DB backend? I am struggling to debug an issue I have all of a sudden been hitting and would value some advice.
I am using celery 3.1.18 with Django, with RabbitMQ as the broker and an Oracle database as the backend, ie.:
CELERY_RESULT_BACKEND='djcelery.backends.database.DatabaseBackend'
My code makes use of chords and has been working successfully for a year or so now.
All of a sudden chords are not firing the callback across both my Dev and Prod envs and I am at a loss as to how to debug further. The code has not changed and last night, without changing the code *something I did made chords come back to life temporarily only to stop working again this morning .. suggesting this is some sort of resource issue rather than a code problem.
So far, I have:

*

*restarted the host that rabbitmq-server and celery are running on.

*purged all queues and repeated step 1.

*Disabled the backend (commented it out from settings.py, got the error about disabled backend, then enabled the backend once again.

*Tried to run the basic commands that show chords working in the docs. The example hangs on the shell and when you CTRL-C out you get:
from celery import chord
from tasks import add, sum
callback = tsum.s()
header = [add.s(i, i) for i in range(100)] result = chord(header)(callback)
result.get()
^CTraceback (most recent call last): File "", line 1, in  File "/opt/exaboard/eXaboard/lib/python2.7/site-packages/celery/result.py", line 169, in get no_ack=no_ack, File "/opt/exaboard/eXaboard/lib/python2.7/site-packages/celery/backends/base.py", line 220, in wait_for on_interval() File "/opt/exaboard/eXaboard/lib/python2.7/site-packages/celery/result.py", line 181, in maybe_reraise_parent_error node.maybe_reraise() File "/opt/exaboard/eXaboard/lib/python2.7/site-packages/celery/result.py", line 485, in maybe_reraise result.maybe_reraise() File "/opt/exaboard/eXaboard/lib/python2.7/site-packages/celery/result.py", line 270, in maybe_reraise if self.state in states.PROPAGATE_STATES: File "/opt/exaboard/eXaboard/lib/python2.7/site-packages/celery/result.py", line 394, in state return self.get_task_meta()['status'] File "/opt/exaboard/eXaboard/lib/python2.7/site-packages/celery/result.py", line 339, in _get_task_meta return self._maybe_set_cache(self.backend.get_task_meta(self.id)) File "/opt/exaboard/eXaboard/lib/python2.7/site-packages/celery/backends/base.py", line 292, in get_task_meta meta = self._get_task_meta_for(task_id) File "/opt/exaboard/eXaboard/lib/python2.7/site-packages/djcelery/backends/database.py", line 40, in _get_task_meta_for return self.TaskModel._default_manager.get_task(task_id).to_dict() File "/opt/exaboard/eXaboard/lib/python2.7/site-packages/djcelery/managers.py", line 144, in get_task return self.get(task_id=task_id) File "/opt/exaboard/eXaboard/lib/python2.7/site-packages/django/db/models/manager.py", line 92, in manager_method return getattr(self.get_queryset(), name)(args, *kwargs) File "/opt/exaboard/eXaboard/lib/python2.7/site-packages/django/db/models/query.py", line 351, in get num = len(clone) File "/opt/exaboard/eXaboard/lib/python2.7/site-packages/django/db/models/query.py", line 122, in __len self._fetch_all() File "/opt/exaboard/eXaboard/lib/python2.7/site-packages/django/db/models/query.py", line 966, in _fetch_all self._result_cache = list(self.iterator()) File "/opt/exaboard/eXaboard/lib/python2.7/site-packages/django/db/models/query.py", line 211, in iterator if connections[self.db].features.supports_select_related: File "/opt/exaboard/eXaboard/lib/python2.7/site-packages/django/db/models/query.py", line 900, in db @property KeyboardInterrupt
Any advice on how to DEBUG further would be much appreciated!


text:
Q: About socket programming and REST design We need to design a server that will serve a webpage to several clients but also query a remote database for these clients. One of the requirement for this project is that the whole system must be compliant with the REST architecture style. We need use Java as programming language but many questions arised while we were designing it.
We want to have a main thread that will get connections, as shown in this example:
// System.out.println("Starting a new web server using port " + port)

    try {
        ServerSocket reciever = new ServerSocket(port);
        while (true) {
            try {
                Socket s = reciever.accept();
                Client c = new Client(s);
            } catch (IOException e) {
                System.err.println("New item creation failed.");
                IOUtil.close(reciever);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    } catch (IOException e) {
        System.err.println("ServerSocket problem.");
    }

Then each connection will be created as a new thread (the Client object in the code) that will take care of reading ONE request. If the request is a GET, then the thread will serve the resource to the client. If it is a POST, then it will add the request to a buffer and let another thread handle the query to the database and also the answer back to the client. After handling this only request, the thread closes the socket and terminates.
Is the use of sockets violating the REST principle? In order to respect the REST architecture, do we need to destroy every Client object (thread & socket) after each HTTP message? Is there another way of client-server communication that does not use sockets?

A: Ok, I think you are confusing a whole bag of junk together.
Firstly, different between low level IP sockets that allow data to go from A to B and 'websockets' that use HTTP to bootstrap a connection from a client to a server that can be kept open for TWO WAY communication.
Based on your requirements, you just want a 'standard' JEE container. Using something like JAX-RS you can apply some basic annotations to functions such as @PATH('/MyResource/Cars/') and have that function be called for that path.
Using a container will free you from all that boring boilerplate rubbish. No need to manual setup threads to listen, and spawn other threads to handle requests.
Using IP sockets is (indirectly) a mandate of REST; REST has to (according to Fielding, but strictly speaking it is protocol agnostic) be over HTTP, thus over TCP/IP sockets (though obviously you could do HTTP over any other transport protocol). Websockets however are using HTTP to form a persistent stateful connection between client and server, which is fundamentally opposed to REST. Basic HTTP would (and you would do this via the container doing it for you) fully open and close the connection for each isolated request, in practice however HTTP (and thus REST) will allow for the low level connection (the TCP connection that is slow to start) to be maintained for a series of request. This functionality is intended for the scope of loading a HTML page, and all resources in one TCP connection, but over many HTTP requests.

A: Sockets move bytes over TCP/IP. That's a lower level protocol, you don't want to worry about that. You care about the higher up protocol (which in this case is HTTP).
Sockets are closed in HTTP after every request, so what you're thinking sounds reasonable. Although I'm not sure why you would create a separate thread for a POST request. I'm assuming that your Client implementation already runs in its own thread (if it doesn't, then your server isn't very efficient).


text:
Q: Project won't build unless reference lowercase I have a C# web application that's a mishmash of C# and VB.NET. I'm adding some features to it. I took it out of the mothballs, dusted it off and tried compiling it in VS2015. It gave me some reference errors. I fixed them by removing the assembly references and then just adding them back in. That worked; weird.
Looking at the project file differences, however, all I see are some GUIDs that have different cases. For example, this:
<ProjectReference Include="..\SomeControllers\SomeControllers.csproj">
  <Project>{D7423D79-0A59-4F9E-A142-863785821DF0}</Project>
  <Name>SomeControllers</Name>
</ProjectReference>

was changed to this:
<ProjectReference Include="..\SomeControllers\SomeControllers.csproj">
  <Project>{d7423d79-0a59-4f9e-a142-863785821df0}</Project>
  <Name>SomeControllers</Name>
</ProjectReference>

The only difference that I can see is that one is lowercase, the other is uppercase. The other difference is that the project compiles with the second GUID, not the first one.
One other mystery is that there are still plenty of GUIDs in the project files that are all uppercase, and they still compile. Can anyone explain this strange behavior?


text:
Q: Loading of OSGi bundle dynamically from a file system I have a modular application which uses OSGi framework. Here I'm using org.eclipse.equinox.common_3.4.0 OSGi container. So now the application is already running with all the osgi bundles installed and active and I am displaying all the active OSGi bundles on the UI, by looping though a hash map, based on some action.
Now the requirement is, while the application is already running, I want to instal a new OSGi bundle, from a file system, by giving this new bundle to the application's OSGi container so that it will start this bundle.
How do I achieve this ?
I have tried reading the OSGi bundle as a JarInputstream and read the bundle activator fully qualified class path and tried to instantiate this using Class.forName("") and type casted to BundleActivator interface.  But while starting it, it is taking bundle context as a argument to start method.
Is there way where I can just give the OSGi bundle to the container pragmatically so that it will take care of installing and starting the bundle and then my UI will automatically picks up this new bundle name in the display.

A: Assuming you have the file to load, you can install the bundle like:
void install( BundleContext context, File file) throws Exception {
    Bundle b = context.installBundle( file.toURI().toString() );
    b.start();
}

And you can uninstall it (if the file is gone):
void uninstall( BundleContext context, File file) throws Exception {
    Bundle b = context.getBundle( file.toURI().toString() );
    b.uninstall();
}

You get the BundleContext from your activate or Declarative services component's activate method. These are the recommended methods but in dire cases you can also use:
BundleContext context = FrameworkUtil.getBundle( this.getClass() ).getBundleContext();

Though handy it bypasses some mechanism that you might want to use in the future so getting the context in the recommended way is much better


text:
Q: Is the word 'appreciate' too formal? I tend to use appreciate in my letter endings. Such as: "I appreciate your help".
I wonder if it is too much formality?

A: If it is to someone you don't know personally, it is not too formal. For a friend, usually a thanks will do.

A: It's not more formal at all.  It does read like a deeper level of thanks than a simple "thank you" or "thanks" but I doubt anyone will think anything of it.

A: How formal the word is depends mostly on the context you use it in. I will sometimes casually say, "appreciated" to my friends if they do something for me, and that's very informal. Letters are usually slightly (but only slightly) more formal than direct speech though, even between friends. "I appreciate your help" would not be out of place in such a letter, though I would word it with a slightly less-formal, "I appreciate the help." "Thanks for helping me out with that" would also be a good option.


text:
Q: bot framework nlp with dispatch I followed this example on GitHub and was successfully able to test it using the emulator.
However, I would like to understand:

*

*What is the dispatch tool doing exactly? I can see a new Luis app in my Luis.ai account when I executed the command "dispatch create -b nlp-with-dispatch.bot | msbot connect dispatch --stdin," but I need to understand what the dispatch tool does behind the scenes.
I can see that the dispatch LUIS App contains utterance like:
"turn dimmer off" which in Home Automation was like "turn device operation."
I also need to understand why it is being done this way. What if we don't have the requirement of multiple LUIS models how utterances are resolved with entities.

*Whatever is done using CLI tools like creating/importing the LUIS services and intents can also be done using luis.ai and azure portal, but is the only way to configure the Dispatch application with the CLI  or can we create it directly on luis.ai without using any command?

A: 1) If you imagine the NLP of your bot as a series of sieves or sifters, it's easier to understand dispatch. Dispatch is the first level of sifting. It can be trained to evaluate whether a particular utterance goes to a certain LUIS intent or to a connected QnAMaker Service. The tutorial here gives a better, more formal description.
2)Dispatch has to be created using the CLI.


text:
Q: NSTextAttachment cover the text when use textkit I want to insert image in UITextView, so I use textkit and NSTextAttachment. But when I insert image, the image display above the content in UITextView, the effect like below:

and the code is like this:
//
//  TextKitView.m
//  TextKit
//
//  Copyright (c) 2015 icell.com. All rights reserved.
//

#import "SNArticleView.h"

@interface SNArticleImageAttachment : NSTextAttachment

@end

@implementation SNArticleImageAttachment

- (CGRect)attachmentBoundsForTextContainer:(NSTextContainer *)textContainer proposedLineFragment:(CGRect)lineFrag glyphPosition:(CGPoint)position characterIndex:(NSUInteger)charIndex {

    CGFloat attachmentWidth = CGRectGetWidth(lineFrag) - textContainer.lineFragmentPadding * 2;
    return CGRectMake(0, 0, attachmentWidth, attachmentWidth / self.image.size.width * self.image.size.height);
}

@end

@interface SNArticleView ()

@property (strong, nonatomic) NSTextStorage *textStorage;
@property (strong, nonatomic) UITextView *textView;

@end

@implementation SNArticleView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (void)commonInit {
    _textStorage = [[NSTextStorage alloc] init];

    NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
    [_textStorage addLayoutManager:layoutManager];

    NSTextContainer *textContainer = [[NSTextContainer alloc] init];
    [layoutManager addTextContainer:textContainer];

    _textView = [[UITextView alloc] initWithFrame:self.bounds textContainer:textContainer];
    [_textView setAutoresizingMask:UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth];
    [_textView.textContainer setLineFragmentPadding:20];
    [self addSubview:_textView];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    [self.textView setFrame:self.bounds];
}

- (void)setAttributedText:(NSAttributedString *)attributedText {
    _attributedText = [attributedText copy];
    [_textStorage insertAttributedString:_attributedText atIndex:0];
}

- (void)insertImage:(UIImage *)image atLocation:(NSUInteger)index; {
    NSMutableAttributedString *attributedTemp = [self.attributedText mutableCopy];

    SNArticleImageAttachment *attachment = [[SNArticleImageAttachment alloc] init];
    [attachment setImage:image];
    NSAttributedString *imageAttrStr = [NSAttributedString attributedStringWithAttachment:attachment];
    [attributedTemp insertAttributedString:imageAttrStr atIndex:_attributedText.length];

    [_textStorage replaceCharactersInRange:NSMakeRange(0, _attributedText.length) withAttributedString:attributedTemp];

}

@end

A: Finally, I find the solution by myself. Because the NSAttributedString I used had a attribute of paragraph style, and I set the MaximumLineHeight before, so it effected the NSTextAttachment.


text:
Q: Parsing HTML form to JSON I'm struggling to summarise an HTML form to JSON. I don't want the values that are disabled, since I am only interested in times that are available.

console.log($(".venue input:enabled"))

// Ideally it could be in a JSON object like:
// { 2: [ "07:00AM", "01:00PM", "02:00PM"], ... }

Court 2

            <input type="checkbox" name="timeslots[]" id="534584">
            07:00 AM

            <input type="checkbox" disabled="">
            08:00 AM

            <input type="checkbox" disabled="">
            09:00 AM

            <input type="checkbox" disabled="">
            10:00 AM

            <input type="checkbox" disabled="">
            11:00 AM

            <input type="checkbox" disabled="">
            12:00 PM

            <input type="checkbox" name="timeslots[]" id="534590">
            01:00 PM

            <input type="checkbox" name="timeslots[]" id="534591">
            02:00 PM

            <input type="checkbox" disabled="">
            03:00 PM

            <input type="checkbox" disabled="">
            04:00 PM

            <input type="checkbox" disabled="">
            05:00 PM

            <input type="checkbox" disabled="">
            06:00 PM

            <input type="checkbox" disabled="">
            07:00 PM

            <input type="checkbox" disabled="">
            08:00 PM

            <input type="checkbox" disabled="">
            09:00 PM

Court 3

            <input type="checkbox" name="timeslots[]" id="534584" disabled>
            07:00 AM

            <input type="checkbox" disabled="">
            08:00 AM

            <input type="checkbox" disabled="">
            09:00 AM

            <input type="checkbox" disabled="">
            10:00 AM

            <input type="checkbox" disabled="">
            11:00 AM

            <input type="checkbox" disabled="">
            12:00 PM

            <input type="checkbox" name="timeslots[]" id="534590">
            01:00 PM

            <input type="checkbox" name="timeslots[]" id="534591">
            02:00 PM

            <input type="checkbox" disabled="">
            03:00 PM

            <input type="checkbox" disabled="">
            04:00 PM

            <input type="checkbox" disabled="">
            05:00 PM

            <input type="checkbox" disabled="">
            06:00 PM

            <input type="checkbox" disabled="">
            07:00 PM

            <input type="checkbox" disabled="">
            08:00 PM

            <input type="checkbox" disabled="">
            09:00 PM

A: You could use Stringify:
JSON.stringify([1, 'false', false]); // '[1,"false",false]'

Not sure if that's what you want to do.
more info about stringify Here

A: Not 100% sure but are you looking for this.

var times = {};
$('.venue').each(function(e) {
  var $this = $(this);
  var timeLabel = $this.find('input:enabled').next();
  var timeArray = [];
  timeLabel.each(function() {
    timeArray.push($(this).text());
  })
  times[e + 1] = timeArray;
})
times = JSON.stringify(times);
console.log(times);

Court 2

            <input type="checkbox" name="timeslots[]" id="534584">
            07:00 AM

            <input type="checkbox" disabled="">
            08:00 AM

            <input type="checkbox" disabled="">
            09:00 AM

            <input type="checkbox" disabled="">
            10:00 AM

            <input type="checkbox" disabled="">
            11:00 AM

            <input type="checkbox" disabled="">
            12:00 PM

            <input type="checkbox" name="timeslots[]" id="534590">
            01:00 PM

            <input type="checkbox" name="timeslots[]" id="534591">
            02:00 PM

            <input type="checkbox" disabled="">
            03:00 PM

            <input type="checkbox" disabled="">
            04:00 PM

            <input type="checkbox" disabled="">
            05:00 PM

            <input type="checkbox" disabled="">
            06:00 PM

            <input type="checkbox" disabled="">
            07:00 PM

            <input type="checkbox" disabled="">
            08:00 PM

            <input type="checkbox" disabled="">
            09:00 PM

Court 3

            <input type="checkbox" name="timeslots[]" id="534584" disabled>
            07:00 AM

            <input type="checkbox" disabled="">
            08:00 AM

            <input type="checkbox" disabled="">
            09:00 AM

            <input type="checkbox" disabled="">
            10:00 AM

            <input type="checkbox" disabled="">
            11:00 AM

            <input type="checkbox" disabled="">
            12:00 PM

            <input type="checkbox" name="timeslots[]" id="534590">
            01:00 PM

            <input type="checkbox" name="timeslots[]" id="534591">
            02:00 PM

            <input type="checkbox" disabled="">
            03:00 PM

            <input type="checkbox" disabled="">
            04:00 PM

            <input type="checkbox" disabled="">
            05:00 PM

            <input type="checkbox" disabled="">
            06:00 PM

            <input type="checkbox" disabled="">
            07:00 PM

            <input type="checkbox" disabled="">
            08:00 PM

            <input type="checkbox" disabled="">
            09:00 PM

A: If you can't change the HTML, here you have an option...
var myJson = {};

$('div.venue').each(function() {
    var hours = [];
    var courtno = $(this).find('h4').text().split(' ')[1];

    $(this).find('input:enabled').each(function() {
        hours.push($(this).next('label').text());
    });

    myJson[courtno] = hours;
});

... but if you can, I would add a data-courtno to the venue div to indicate the parameter independently of the text you want to use in the h4. So, first adding...

Court 2

...

Court 3

...

... and the jquery would be...
var myJson = {};

$('div.venue').each(function() {
    var hours = [];

    $(this).find('input:enabled').each(function() {
        hours.push($(this).next('label').text());
    });

    myJson[$(this).data('court')] = hours;
});


text:
Q: Relative/dynamic cumulative measure in MDX to work with Power BI I am setting up a multidimensional cube in SSAS which will be queried in PowerBI and Excel.
I need a calculated measure (MDX) similar to YTD/MTD/QTD for Sales but the cumulative function needs to be dependent on the date filter (period level, eg. 202111) used in the reporting tool.
For example, if periods 202102, 202103 and 202104 are chosen, the measure need to aggregate the numbers for each month starting from 0.
Feb Sales: 100, measure shows 100.
March Sales: 200, meaure shows 300.
April Sales: 100, measure shows 400.
The following DAX measure does the trick. I need the equivalent in MDX
Cumulative sales =
    IFERROR(
        CALCULATE(
            [Sales],
            FILTER(
                ALLSELECTED(Date[Period]),
                Date[Period] <= MAX(Date[Period])
            )
        ),
        BLANK()
    )


text:
Q: Checking Internet Connection without URL test connection using java How can I check whether my computer is connected to the Internet. I don't want to use URL check method. Is it possible to call an operating system's function using java? For example, in JNA library, is there any function to perform this ?

A: You can use ping command like this:
class PingHost
{
        public static void main(String[] args)
        {
            String ip = "www.google.com";
            String pingResult = "";

            String pingCmd = "ping " + ip;
            try
            {
                Runtime r = Runtime.getRuntime();
                Process p = r.exec(pingCmd);

                BufferedReader in = new BufferedReader(new
                InputStreamReader(p.getInputStream()));
                String inputLine;
                while ((inputLine = in.readLine()) != null)
                {
                    System.out.println(inputLine);
                    pingResult += inputLine;
                }
                in.close();

            } catch (IOException e) {
                System.out.println(e);
            }

        }
    }

You should receive a response like:
64 bytes from 173.194.37.147: icmp_seq=0 ttl=52 time=299.032 ms
64 bytes from 173.194.37.147: icmp_seq=1 ttl=52 time=508.100 ms

A: You could check to see if a common hostname (such as google) is resolvable through dns to an ip address.
Once that address has been resolved, you can check to see if it is reachable.


text:
Q: using Google GmailAPI send mail not working I need help. Program WebApplication Code C# Asp.Net
First ,I've implemented a way to put a URI in Google OAuth 2 authorization.
Download the Json file for the program to read the file and generate the token.

Error

Failed to launch browser with "https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&response_type=code&client_id=879100301665-3hpkd1h812d5eejji8o4mku3c2ci3rcs.apps.googleusercontent.com&redirect_uri=http%3A%2F%2F127.0.0.1%3A63526%2Fauthorize%2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fgmail.send" for authorization. See inner exception for details.

Second , I used to put values in Programs by assigning Client ID and Client secret in Google OAuth 2 authorization.

Error
Access to the path 'C:\Windows\system32\config\systemprofile' is denied

A: There are a number of issues with what you are doing.
First being that you have created what appears to be a web application credentials on Google cloud console.  However the code you are using GoogleWebAuthorizationBroker.AuthorizeAsync is intended for use with installed applications only.    This is why you are getting the error you are getting.
The code for creating an asp .net core web app is as follows
public void ConfigureServices(IServiceCollection services)
{
    ...

    // This configures Google.Apis.Auth.AspNetCore3 for use in this app.
    services
        .AddAuthentication(o =>
        {
            // This forces challenge results to be handled by Google OpenID Handler, so there's no
            // need to add an AccountController that emits challenges for Login.
            o.DefaultChallengeScheme = GoogleOpenIdConnectDefaults.AuthenticationScheme;
            // This forces forbid results to be handled by Google OpenID Handler, which checks if
            // extra scopes are required and does automatic incremental auth.
            o.DefaultForbidScheme = GoogleOpenIdConnectDefaults.AuthenticationScheme;
            // Default scheme that will handle everything else.
            // Once a user is authenticated, the OAuth2 token info is stored in cookies.
            o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        })
        .AddCookie()
        .AddGoogleOpenIdConnect(options =>
        {
            options.ClientId = {YOUR_CLIENT_ID};
            options.ClientSecret = {YOUR_CLIENT_SECRET};
        });
}

The second issue you are having is that the redirect uri you are adding is not a valid URL it needs to be https:// at the very least you are missing the //.  As well as the fact that the client library will be sending the request using /signin-google
So a proper redirect uri should be more like this.
https://localhost:5001/signin-google

I have a YouTube video which shows How to get a Google users profile information, with C#.  with a companion blog post Asp .net core 3 and Google login  both should work fine with .net 5 as well.


text:
Q: Remove middle initial only if there is one [![Image 1][1]][1]
Image 2
I have 1000 rows of data, some have a middle initial... some don't. I need to remove the middle initial so I am left with just first name. When I apply this.... =LEFT(B8,FIND(" ",B8,1)-1) I get an error for those cells that do not have a middle initial or name.

A: With data in column A, in another cell enter:
=LEFT(A1,FIND(" ",A1)) & TRIM(RIGHT(SUBSTITUTE(A1," ",REPT(" ",LEN(A1))),LEN(A1)))

The names are a set of words separated by a space.  The formula gets the first word and the last word.


text:
Q: How to run sql script in java Hi what is the best way to run an sql script in Java? I have my connection to the db and picked up some code that I think may work to run the script getting a few errors currently.
public class DatabaseConnection {

private String userName = "";
private String password = "";
private String serverName = "";
private String portNumber = "";

public Connection getConnection() throws SQLException {

    Connection conn = null;

    Properties connectionProps = new Properties();
    connectionProps.put("user", this.userName);
    connectionProps.put("password", this.password);
    String connectionString = "jdbc:mysql://" +
            this.serverName +
            ":" + this.portNumber;

    System.out.println("Connection String: " + connectionString);

    conn = DriverManager.getConnection(connectionString, connectionProps);

    System.out.println("Connected to database");
    return conn;

    **ScriptRunner runner = new ScriptRunner(conn, connectionString, connectionProps)
    String file = "resources/cleanDatabaseScript.sql";
    System.out.println("retreived script");
    runner.runScript(new BufferedReader(new FileReader(file)));**

}

The ScriptRunner section is the area im struggling with currently.

A: Here's a basic class to connect to a mySql:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class DbConnection {

    private static Connection singleConnection ;
    private static Statement  singleStatement;

    public static synchronized Statement getStatement() throws SQLException{

        if (singleConnection == null){
            singleConnection = DriverManager.getConnection("jdbc:mysql://HereTheHost:HereThePortNumber/HereTheDataBaseName","HereTheUserName","HereThePassWord");
            if (singleStatement == null){
                singleStatement = singleConnection.createStatement();
                System.out.println("Connection Success !");
            }
        }
        return singleStatement;
    }

}

This example makes sure that you will have only one instance of the database connection, if you don't understand this just ignore it.


text:
Q: Which is the best way to filter data in two columns in a dataframe I have a dataframe like the one below, just as an example of my dataframe (the list of tickers I have is very long). I would like to get a new dataframe where all the tickers which are accomplishing the 3 SOS signals 'Absorption Vol', 'Stopping Vol', 'Test in Rising' appear as a result.
data = {
    'Ticker': ['SEDG', 'SEDG', 'SEDG', 'PEP', 'PEP', 'PEP', 'CTLT'],
    'SOS': ['Absorption Vol', 'Stopping Vol', 'Test in Rising', 'Test in Rising', 'Absorption Vol', 'Shakeout', 'Test'],
    'Date': ['2021-12-14', '2021-12-16', '2021-12-18', '2021-12-14', '2021-12-16', '2021-12-18', '2021-12-20']
}
df = pd.DataFrame(data)
print(df)

Output:
  Ticker             SOS        Date
0   SEDG  Absorption Vol  2021-12-14
1   SEDG    Stopping Vol  2021-12-16
2   SEDG  Test in Rising  2021-12-18
3    PEP  Test in Rising  2021-12-14
4    PEP  Absorption Vol  2021-12-16
5    PEP        Shakeout  2021-12-18
6   CTLT            Test  2021-12-20

The problem I have now is that I would like to filter the dataframe showing only the tickers with match in SOS column for 'Absorption Vol', 'Stopping Vol', 'Test in Rising'. I need the condition that these 3 SOS signals need to be present for each ticker in order to be shown as a result. If only one of the SOS signals is matched and not the rest, the ticker should not appear.
The result I want is something like this, but extended for the huge amount of tickers.
  Ticker             SOS        Date
0   SEDG  Absorption Vol  2021-12-14
1   SEDG    Stopping Vol  2021-12-16
2   SEDG  Test in Rising  2021-12-18

I am trying this code, but it's not showing the ticker when all these 3 SOS signals appear, but when one does:
SOS_values_filter = ['Test in Rising', 'Absorption Vol', 'Stopping Vol']
rslt = final_df_sos[final_df_sos['SOS'].isin(SOS_values_filter)].groupby('Ticker').filter(lambda x: len(x) >= 3)
print(rslt)

A: .groupby('Ticker') first, then you can check if each group's SOS column contains the necessary values.
s = {'Test in Rising', 'Absorption Vol', 'Stopping Vol'}
df.groupby('Ticker').filter(lambda sf: s.issubset(sf['SOS']))

Output:
  Ticker             SOS        Date
0   SEDG  Absorption Vol  2021-12-14
1   SEDG    Stopping Vol  2021-12-16
2   SEDG  Test in Rising  2021-12-18

Here I'm using a set because the order of the input doesn't seem to matter. And I'm using .issubset() because I assume it doesn't matter if other SOS values are present as long as the necessary three are. You can customize this to your needs.


text:
Q: How secure is Google Images I am developing a chrome plugin that heavily uses Google Images with users for medical images. It's an image classification system, so I need some human results, and I've resorted to use a plugin with some external users.
What it does is tracking user interaction with specific results, in other words, they are presented some results from the search, and then:

*

*users will select results from the list as in the first picture

*users will select from similar images as in the second picture
They also have the option from the third image to select to see other similar images with "View more".
How secure are all these communications? Since I am dealing with health issues, the protocol I need to follow is strict: every communication must be encrypted.
Are all data completely secure, or some steps, as selecting a particular result (pic 1), or choosing similar images within a result (pic 2), are insecure?
This will have a great impact on the plugin development, as I keep track of what every user will do.
Thanks!

A: very secure, don't worry. but remember that google uses everything for their benefit and may use them later on


text:
Q: mod_rewrite for flat links behaves like it's in the subdirectory I'm trying to create a mod_rewrite ruleset in .htaccess so that I can create some flat links to functionality in a page.
When the user enters: http://example.com/where/location
I want to redirect to : http://example.com/index.php?where=location
I'm currently using:
RewriteEngine on
RewriteRule ^where/([^/.]+)/?$ /index.php?where=$1

which kind of works, except that css, JS and image links in index.php are no longer found - it's as though the server is serving index.php up from the non-existant /where/location sub-directory.
Is this what's happening and is there a way to case the server to serve index.php with relative links from its actual location in the root directory normally?

A: The server side is irrelevant here. You are in fact serving the site from /where/location; it's irrelevant that this URL is getting rewritten internally. If you're using relative paths to CSS files, the browser is resolving those against the current URL that it is on. The best strategy is typically to use absolute paths for included files, e.g.:
/css/style.css

instead of
css/style.css


text:
Q: Find All Radio Buttons in ASP Table I have an ASP table which contains a large number of radio buttons.  I want to loop through them all quickly and set the checked property to false:
   <asp:Table runat=Server ID=tblSchedule>
            <asp:TableRow>
                <asp:TableCell>
    <asp:RadioButton runat=Server ID=rdb1/>
</asp:TableCell>
</asp:TableRow>
</asp:table>

The following code never returns any results though.
foreach (RadioButton rdb in tblSchedule.Controls.OfType<RadioButton>())
{
    rdb.Checked = false;
}

A: You need to loop through the layers of the table control, like this:
foreach (var tr in tblSchedule.Controls.OfType<TableRow>())
{
    foreach (var td in tr.Controls.OfType<TableCell>())
    {
        foreach (var rdb in td.Controls.OfType<RadioButton>())
        {
            rdb.Checked = false;
        }
    }
}

Or alternatively you can use LINQ, like this:
foreach (var rdb in tblSchedule.Controls.OfType<TableRow>()
    .SelectMany(tr => tr.Controls.OfType<TableCell>()
    .SelectMany(td => td.Controls.OfType<RadioButton>())))
{
    rdb.Checked = false;
}

A: As far as i remember the table's control cllection does not contain all controls in all rows' cells. Controls.OfType does not search recursively in child controls. So you either have to use a recursive method or just use the Rows property and this linq query:
IEnumerale<RadioButton> allRadios = this.tblSchedule.Rows.Cast<TableRow>()
     .SelectMany(r => r.Cells.Cast<TableCell>()
                       .SelectMany(c => c.Controls.OfType<RadioButton>()));

foreach(RadioButton rBtn in allRadios)
    rBtn.Checked = false;


text:
Q: how to use DownloadManager columns i'm wondering how to use DownloadManager columns like COLUMN_ID because it gives me the constant value when i use it directly
I'm new to android programming (c# background) so i need a little help with some basics in android, i've read android developers guide but it lacks examples so it's worthless
i miss c# guide ;(
this is my code :
fun download(url: String, name: String) {
    //start download request
    var request = DownloadManager.Request(Uri.parse(url))
    request.setVisibleInDownloadsUi(true)
    request.allowScanningByMediaScanner()
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
    request.setDestinationInExternalPublicDir("a destination", "$name.pdf")
    // get download service and enqueue file
    val manager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
    manager.enqueue(request)
    var x = (DownloadManager.COLUMN_ID)
    Toast.makeText(applicationContext,x ,Toast.LENGTH_SHORT).show()
    //or
    //var x = (DownloadManager.COLUMN_TOTAL_SIZE_BYTES)
    //Toast.makeText(applicationContext,x ,Toast.LENGTH_SHORT).show()
}

the Toast text was:
_id (for COLUMN_ID)
total_size(for COLUMN_TOTAL_SIZE_BYTES)

A: Once you receive a broadcast with the download id , you can use the id to fetche details related to the download. In your broadcast receiver you get the download id like this intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID. You take this id , and query the download manger.
    DownloadManager.Query query = new DownloadManager.Query();
    query.setFilterById(downloadId);
    Cursor cursor = downloadManager.query(query);

Once you get the cursor , you can run a loop like this .
     if (cursor.moveToFirst()) {
        if (cursor.getCount() > 0) {

            int statusOfTheDownload = cursor.
        getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
            String fileUri = cursor.
        getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));

        }
    }

A:
This answer is in Java, you need to  modify it.
Query the download manager about downloads that have been requested.

Cursor cursor = downloadManager.query(ImageDownloadQuery);
if (cursor.moveToFirst()) {
    Download(cursor, Image_DownloadId);
}

private void Download(Cursor cursor, long DownloadId) {

        //column for download  columnId
        int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_ID);
        int columnId = cursor.getInt(columnIndex);
        Log.d("Tag", "columnId " +columnId);
}


text:
Q: Not able to change property of dynamically added element I am working on the following demo. Why am I not able to change the css rule of hidden element #prev in popover here?

$("[data-toggle=popover]").each(function(i, obj) {

$(this).popover({
  html: true,
  content: function() {
    var id = $(this).attr('id')
    return $('#popover-content-' + id).html();
  }
});

});

$(document).on("click","#next", function(){
    console.log('Click on Next is working but the #prev is not displaying!');
   $("#prev").css('display','block');
});
#prev{
   display:none;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

    Display

        <button id="next"> Next</button>
        <button id="prev"> Prev</button>

A: The problem is because, due to the way the popover() library works by cloning HTML, you're duplicating the same id within the page. When selecting by that id it then only reads the first one found, which is not the visible one. To fix the issue, use DOM traversal to find the .prev relative to the clicked .next, and change the id attributes to class. Try this:

$("[data-toggle=popover]").each(function(i, obj) {
  $(this).popover({
    html: true,
    content: function() {
      var id = $(this).attr('id')
      return $('#popover-content-' + id).html();
    }
  });
});

$(document).on("click", ".next", function() {
  $(this).next(".prev").show();
});
.prev {
  display: none;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

  Display

    <button class="next"> Next</button>
    <button class="prev"> Prev</button>


text:
Q: React Material UI condition statement within style property of button I need to have a condition within style property of the button.
Here is how my code look like at this moment.
  <Button variant="outlined" component="span" className={classes.button}>
    Choose file
  </Button>

I need to have condition something like this.
      <Button variant="outlined" component="span" className={classes.button}
style={{display: ((this.props.filename === true)? 'none' : 'block') }}
>
        Choose file
      </Button>

Any idea how can I make this work?
Ref: https://material-ui.com/api/button/

A: You were very close. The only trick here is that by specifying === true in your condition will omit the type coercion on your variable, which is actually needed in this case as we want to check if the string is empty.
One fix for this would be to just remove it, and let JavaScript perform the type coercion, which checks if the string is empty or null:
<Button variant="outlined" component="span" className={classes.button}
  style={{display: ((this.props.filename) ? 'none' : 'block') }}>
   Choose file
</Button>

This post explains well how the conversion is done. More ways of checking for empty string in JavaScript, with coercion or not, can be found in this SO post.

A: I think the problem here is the same as described here:
Can withStyles pass props to styles object?

A: Another approach is to create a separate classes: displayNone- when condition is met, and displayBlock-when not. Then use the clsx library to combine the two classes, like so:
      import clsx from "clsx"
        <Button variant="outlined" component="span"
    className={clsx(classes.button,this.props.filename? classes.displayNone:classes.displayBlock)}>
Choose file</Button>


text:
Q: Remove root element from a heap tree How do I remove the smallest element of an heap tree?
This element is at the root of the tree. If I remove that, I'm left with two independent subtrees.
data Heap a = Empty
            | Node a (Heap a) (Heap a)

The type of the function is:
removeMin :: Heap a -> (a, Heap a)

It should return the tree and the minimum removed.
Should I make an auxiliary function to build a new tree, or is there a faster way to do this?

A: Your type, as written, raises some questions:

*

*Q: What's the output from removeMin Empty?
A: You can't produce an a from nothing, so the result should be wrapped in Maybe.

*Q: If I've put (+), (-) and (*) in a Heap (Int -> Int -> Int), which one should be returned by removeMin?
A: Not all data types have an ordering (notably, functions lack one), so it makes sense to require that the data type have an Ord instance.
So the updated type becomes:
removeMin :: Ord a => Heap a -> Maybe (a, Heap a)

Now consider it case by case:

*

*Empty has no min element:
removeMin Empty = Nothing

*If one branch is empty, the remaining heap is the other branch
removeMin (Node a Empty r) = Just (a, r)
removeMin (Node a l Empty) = Just (a, l)

Convince yourself that this works for Node a Empty Empty.

*If neither branch is empty, then the new smallest min element must be the root of one of the branches.
The branches in the resulting Heap are just the branch of the larger element, and the branch of the smaller element, with its minimum removed.
Fortunately, we already have a helper to remove the minimum from a Heap!
removeMin (Node a l@(Node la _ _) r@(Node ra _ _)) = Just (a, Node mina maxN minN')
  where (minN, maxN) = if la <= ra then (l,r) else (r,l)
        Just (mina, minN') = removeMin minN

Now, while this produces a valid heap, it's not necessarily the best algorithm because it's not guaranteed to produce a balanced heap.  A poorly balanced heap is no better than a linked list, giving you O(n) insertion and deletion times where a balanced heap can give you O(log n).

A: You should build an appropriate function to build new tree, but don't worry- it will not perform poorly. GHC can optimize such use cases and this operation could be just as fast as you want (including large, even infinite (recursive) data structures).
I understand you are able to create such auxiliary function by yourself? It is straightforward - anyway, in case of troubles I can write it later.

A: Think of it this way: After removing the top node, you're left with two heaps. So you need to implement (recursive) merging of two heaps, something like
merge :: (Ord a) => Heap a -> Heap a -> Heap a

You could also implement a monoid instance for Heap
instance (Ord a) => Monoid (Heap a) where
    mempty = Empty
    mappend = -- the merging function


text:
Q: Pointer to 2D Array I'm given the following snippet of code:
int group1[3][3] = {3,4,5,1,9,8};
int group2[3][3] = {{1},{2,3},{4,5}};
int *gPtr1 = group1;
int *gPtr2 = group2;

The question asks me for the value of: (I'm supposed to answer this on paper, of course, no computer)
*(gPtr1 + 3)
*(gPtr2 + 3)

Normally, I know for 1-dimensional array it adds an "address" instead of value. So for example:
int  balance[10]={1,2,6,4};
int *p=balance;  //p points to balance [0]

p+=3;           //points to balance [3]

However, I cant seem to make a pointer to a 2D array to test this out as in the question, I always get an "Initialization from incompatible pointer type" error.

A: The correct records will look like
int ( *gPtr1 )[3] = group1;
int ( *gPtr2 )[3] = group2;

And these expressions
*(gPtr1 + 3)
*(gPtr2 + 3)

are trying to access the memory after the last elements of the arrays because the arrays have only three rows. That is the type of expression *(gPtr1 + 3) is int[3] and there are only three such elements in the oridinal arrays.
or you could write
int *gPtr1 = ( int * )group1;
int *gPtr2 = ( int * )group2;

In this case using the pointers the arrays are interpretated as one-dimensional arrays with 9 elements and expressions
*(gPtr1 + 3)
*(gPtr2 + 3)

will return correspondingly
1
2

A: To access the address of group1 pass it to the pointer in this way:
int *gPtr1 = &group1[0][0];

Using that it's easy to find the soultions: 1 and 2.

A: Maybe this will help you get started:
#include <stdio.h>

int group1[3][3] = {3,4,5,1,9,8};
int group2[3][3] = {{1},{2,3},{4,5}};

int main( void )
{
    int *p;
    int i;
    for (p = group1[0], i = 0; i < 9; ++i, ++p )
        printf( "%d - ", *p);
    printf( "\n" );
    for (p = group2[0], i = 0; i < 9; ++i, ++p )
        printf( "%d - ", *p);
    printf( "\n" );
    return 0;
}

If you understand how memory in that 2D array is stored, it should be clear why this will work. Since I assume that understanding is what you're looking for, I'll leave you to figure that part out on your own. :-)

A: Two-dimensional matrices are represented in row-major order in memory. This is because memory is one-dimensional, and so it stores two-dimensional arrays as a concatenated list of rows.
When you create group1, you get an array of integers that is 9 long, and it looks like:
3 4 5 1 9 8 _ _ _

So, when you do *(gPtr1 + 3), it adds 3 to the original location of gPtr1, which is the address of 3. Adding 3 gets you to the location of 1, which you dereference.
So, when you create group2, you get an array of integers that is 9 long, and it looks like:
1 _ _ 2 3 _ 4 5 _

So, when you do *(gPtr2 + 3), it adds 3 to the original location of gPtr2, which is the address of 1. Adding 3 gets you to the location of 2, which you dereference.


text:
Q: use Gmail API to send email from own account, with out asking user for consent I have a spring web application, and I want to be able to send email from my application. I had a working solution with javax.mail
However, due to the security changes by google, I have to either use OAuth2 or allow less secure apps to use the email account that I am using to send emails.
I tried going with the first option and I have it working, but I am asked for consent the first time that email is sent.
I am not sure if a user might be asked to give consent any time in the future. Is there a way around this, or do I have to completely use a different approach?
public void sendEmail(CustomerMessage customerMessage)
        throws MessagingException, IOException, GeneralSecurityException {
    String to = "myemail@xxx.com";
    String from = "myemail@xxx.com";
    MimeMessage mimeMessage = createEmail(to, from, customerMessage.getName(), customerMessage.toFormatedString());
    Message message = createMessageWithEmail(mimeMessage);
    sendMessage(getGmailService(), from, message);
}

private Gmail getGmailService() throws GeneralSecurityException, IOException {

    final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
    Gmail service = new Gmail.Builder(HTTP_TRANSPORT, JacksonFactory.getDefaultInstance(),
            getCredentials(HTTP_TRANSPORT)).setApplicationName(APPLICATION_NAME).build();
    return service;
}

/**
 * Creates an authorized Credential object.
 *
 * @param HTTP_TRANSPORT
 *            The network HTTP Transport.
 * @return An authorized Credential object.
 * @throws IOException
 *             If the credentials.json file cannot be found.
 */
private Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {

    // Load client secrets.
    InputStream in = GmailService.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY,
            clientSecrets, SCOPES)
                    .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
                    .setAccessType("offline").build();
    LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
    return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");

}


text:
Q: Identifier not declared in generic map, vhdl Following a previous suggestion in this post i tried to write by my self an example, but it doesn't work.
Top entity
library ieee;
use ieee.std_logic_1164.all;
use ieee.std_logic_misc.all;
use ieee.numeric_std.all;

entity topEntity is
    generic(m : natural);
    port(x : in std_logic_vector(m - 1 downto 0));
end topEntity;

architecture rtl of topEntity is
    component componentEntity is
        generic(n : natural);
        port(x : in std_logic_vector(n - 1 downto 0));
    end component;
begin
    INSTANCE : componentEntity
        generic map(n => m)
        port map(x(n - 1) => '0', x(n - 2 downto 0) => x(m - 2 downto 0));
end architecture rtl;

Component entity
library ieee;
use ieee.std_logic_1164.all;
use ieee.std_logic_misc.all;
use ieee.numeric_std.all;

entity componentEntity is
    generic(n : natural);
    port(x : in std_logic_vector(n - 1 downto 0));
end entity;

architecture foo of componentEntity is
begin
end architecture foo;

when i run ncvhdl -v93 it says:
ncvhdl: 15.10-s008: (c) Copyright 1995-2015 Cadence Design Systems, Inc.
                port map(x(n - 1) => '0', x(n - 2 downto 0) => x(m - 2 downto 0));
                           |
ncvhdl_p: *E,IDENTU (topEntity.vhd,19|13): identifier (N) is not declared [10.3].

why it's not declared? it's a generic parameter properly initialized.
Update:
I putted:
port map(x(m - 1) => '0', x(m - 2 downto 0) => x(m - 2 downto 0));
The result is
ncvhdl: 15.10-s008: (c) Copyright 1995-2015 Cadence Design Systems, Inc.
                port map(x(m - 1) => '0', x(m - 2 downto 0) => x(m - 2 downto 0));
                          |
ncvhdl_p: *E,FMLNLS (topEntity.vhd,19|12): formal must be identified a locally static name 87[4.3.3.2] 93[4.3.2.2].
                port map(x(m - 1) => '0', x(m - 2 downto 0) => x(m - 2 downto 0));
                                           |
ncvhdl_p: *E,FMLNLS (topEntity.vhd,19|29): formal must be identified a locally static name 87[4.3.3.2] 93[4.3.2.2].
                port map(x(m - 1) => '0', x(m - 2 downto 0) => x(m - 2 downto 0));
                                           |
ncvhdl_p: *E,UFPTID (topEntity.vhd,19|29): port (X) must be associated [1.1.1.2].

Updated 2...
Still trying to figure out what it is the problem with all these kind of declaration/mapping in vhdl... my new attempt is:
The error report that formal must be identified a locally static name
I found a glossary where each term of interest for this error is explained it also refers to the language standard:
 locally static name: A name in which every expression is locally static (if every discrete range that appears as part of the name denotes a locally static range or subtype and if no prefix within the name is either an object or value of an access type or a function call). (§6.1)

locally static expression: An expression that can be evaluated during the analysis of the design unit in which it appears. (§7.4, §7.4.1)

analysis: The syntactic and semantic analysis of source code in a VHDL design file and the insertion of intermediate form representations of design units into a design library. (§1 1.1, §11.2, §11.4)

There's also the error with the
    port (X) must be associated
So i guess the problem could be that the name of the top entity input is x which is the same name as the component input. However i'm not sure about this because in general with port mapping like x => x don't cause any trouble to me...
Looking at the standard as static name it spits out that:
A name is said to be a static name if and only if one of the following conditions holds:
    — The name is a simple name or selected name (including those that are expanded names) that does not
    denote a function call, an object or value of an access type, or an object of a protected type and (in
    the case of a selected name) whose prefix is a static name.
    — The name is an indexed name whose prefix is a static name, and every expression that appears as part
    of the name is a static expression.
    — The name is a slice name whose prefix is a static name and whose discrete range is a static discrete
    range.
Futhermore a specification is given for locally static name, which should help me to figure out the problem with the name:
a name is said to be a locally static name if and only if one of the following conditions hold:
    — The name is a simple name or selected name (including those that are expanded names) that is not an
    alias and that does not denote a function call, an object or value of an access type, or an object of a
    protected type and (in the case of a selected name) whose prefix is a locally static name.
    — The name is a simple name or selected name (including those that are expanded names) that is an
    alias, and that the aliased name given in the corresponding alias declaration (see 4.3.3) is a locally
    static name, and (in the case of a selected name) whose prefix is a locally static name.
    — The name is an indexed name whose prefix is a locally static name, and every expression that appears
    as part of the name is a locally static expression.
    — The name is a slice name whose prefix is a locally static name and whose discrete range is a locally
    static discrete range
So the issue should be that the name x doesn't fall in any of the categories listed, but why?

A: Try to replace your component instantiation with this:
INSTANCE : componentEntity
        generic map(n => m)
        port map(x(m - 1) => '0', x(m - 2 downto 0) => x(m - 2 downto 0));

Since n is not declared inside topEntity you can't use it. Your misconception is that the named generic n of componentEntity should be directly visible inside the port assignments region (that is port map (...)). This is not the case.
Since m and n are going to hold the same value (due to n => m) you can just use m when doing port assignments.

A: First off the basis for the errors:
IEEE Std 1076-1993,4.3.2.2 Association lists, para 14:

A formal may be either an explicitly declared interface object or member (see Section 3) of such an interface object. In the former case,such a formal is said to be associated in whole. In the latter cases,named association must be used to associate the formal and actual; the subelements of such a formal are said to be associated individually. Furthermore, every scalar subelement of the explicitly declared interface object must be associated exactly once with an actual (or subelement thereof)in the same association list, and all such associations must appear in a contiguous sequence within that association list. Each association element that associates a slice or subelement (or slice thereof) of an interface object must identify the formal with a locally static name.

You'll find as damage says that n is not defined (and you'd expect a separate error message). You also don't define m, both of which need to have values declared for elaboration.
Neither generic is locally static:
7.4 Static expressions:

Certain expressions are said to be static. Similarly, certain discrete ranges are said to be static, and the type marks of certain subtypes are said to denote static subtypes.
There are two categories of static expression. Certain forms of expression can be evaluated during the analysis of the design unit in which they appear; such an expression is said to be locally static. Certain forms of expression can be evaluated as soon as the design hierarchy in which they appear is elaborated; such an expression is said to be globally static.

7.4.1 Locally static primaries:

An expression is said to be locally static if and only if every operator in the expression denotes an implicitly defined operator whose operands and result are scalar and if every primary in the expression is a locally static primary, where a locally static primary is defined to be one of the following:

a. A literal of any type other than type TIME
    b. A constant (other than a deferred constant) explicitly declared by a constant declaration and initialized with a locally static expression
    ...

Generics are globally static:
7.4.2 Globally static primaries:

An expression is said to be globally static if and only if every operator in the expression denotes a pure function and every primary in the expression is a globally static primary, where a globally static primary is a primary that, if it denotes an object or a function, does not denote a dynamically elaborated named entity (see 12.5 ) and is one of the following:

a. A literal of type TIME
    b. A locally static primary
    c. A generic constant

An expression can be both globally static and locally static, a generic isn't one of those, it's value is fixed at elaboration time (even with a default value):
12.2.1 The generic clause:

Elaboration of a generic clause consists of the elaboration of each of the equivalent single generic declarations contained in the clause, in the order given. The elaboration of a generic declaration consists of elaborating the subtype indication and then creating a generic constant of that subtype.
The value of a generic constant is not defined until a subsequent generic map aspect is evaluated or, in the absence of a generic map aspect, until the default expression associated with the generic constant is evaluated to determine the value of the constant.

4.3.2.1 Interface lists, para 3:

A generic interface list consists entirely of interface constant declarations....

So a a generic is a constant. It's not a deferred constant in the meaning given in 4.3.1.1 Constant declarations, para 4:

If the assignment symbol ":=" followed by an expression is not present in a constant declaration, then the declaration declares a deferred constant. Such a constant declaration may only appear in a package declaration. The corresponding full constant declaration, which defines the value of the constant, must appear in the body of the package (see 2.6 ).

The lack of a defined value will cause an elaboration error:
1.1.1.1 Generics, para 3:

The value of a generic constant may be specified by the corresponding actual in a generic association list. If no such actual is specified for a given formal generic (either because the formal generic is unassociated or because the actual is open), and if a default expression is specified for that generic, the value of this expression is the value of the generic. It is an error if no actual is specified for a given formal generic and no default expression is present in the corresponding interface element. ...

And also tells us we can supply the value in an association list (which your code example doesn't do).
And about now you can get the idea that VHDL is pretty complex. Mastery follows a journeyman system, albeit with the road to mastery taking longer than 3 years and there's no investiture by your fellows at the end and the board of masters are those producing VHDL tools (and they agree on what is the standard).
I liken it to someone studying religious texts. Almost all your answers can be found in the LRM (The first sentence of the introduction to the standard "The VHSIC Hardware Description Language (VHDL) is a formal notation intended for use in all phases of the creation of electronic systems. ", a formal notation has to be formally defined). It's a matter of how well you know the standard, how inculcated you can be with the terminology or how well you can search the standard. And the latter two aren't emphasized in educational institutes 'teaching' VHDL. You actually teach yourself.
On the other hand tool vendors could do a lot better at providing information on errors, potentially avoiding the need for mastery to make sense of an issue.
And the good news is that while analyzing your last two questions I've found and submitted two bugs found in my favorite VHDL tool. (In case you're wondering what would possess someone to analyze questions in depth).


text:
Q: Android TextView shadow doesn't work when Radius set to 0 I need to draw a shadow on a title, without any blur, like in this image:
text with shadow, shadowRadius = 0
My problem is that as soon as I set the shadowRadius to 0, the shadow doesn't appear anymore.
Here's the code I'm using, in my style.xml
<style name="navigationTitleWithShadow">
    <item name="android:textAllCaps">true</item>
    <item name="android:textColor">@color/navigationTitleForegroundColor</item>
    <item name="android:shadowColor">@color/navigationTitleShadowColor</item>
    <item name="android:shadowDx">1</item>
    <item name="android:shadowDy">1</item>
    <item name="android:shadowRadius">0</item>
</style>

And in the layout :
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/nav_header_vertical_spacing"

    android:text="@string/menuTableViewController_navigationTitle"
    android:textAppearance="@style/navigationTitleWithShadow" />

Any idea how to have this 0 shadowRadius ?

A: I found a solution, subclassing TextView, overriding method onDraw(). Here's my code:
@Override
protected void onDraw(Canvas canvas) {
    //super.onDraw(canvas);

    if ( getShadowColor() != 0 && getShadowRadius() == 0 ) {

        Paint paint = this.getPaint();
        paint.setColor(getShadowColor());

        paint.setTextAlign(Paint.Align.CENTER);

        int xPos = (canvas.getWidth() / 2);
        int yPos = (int) ((canvas.getHeight() / 2) - ((paint.descent() +
                paint.ascent()) / 2));

        // Draw the shadow text first, so it appears below
        canvas.drawText(getText().toString().toUpperCase(), xPos + getShadowDx(), yPos + getShadowDy(), paint);

        paint.setColor(getCurrentTextColor());

        // Draw the main text on top of it
        canvas.drawText(getText().toString().toUpperCase(), xPos, yPos, paint);

    } else {
        super.onDraw(canvas);
    }

}

It works well, although I'm not sure why I need the setTextAlign, but without it my text is misplaced, on the right.

A: While not stated in TextView.shadowRadius, the Paint.setShadowLayer description states that

If radius is 0, then the shadow layer is removed.

What seems to be a good idea when having the shadow completely hidden behind the text, but as shadow can be offset and the text can be semi transparent it can hide wanted shadows.
Using a min blur of 0.1f is not the same but works out in my case.
paint.setShadowLayer(
    max(blur, 0.1f),
    dx,
    dy,
    color
)


text:
Q: Find the limit of $\frac{1}{x} \cdot \int_{0}^{x}(1+\sin(t))^\frac{1}{t}dt$ Like I said I need to find the limit
$\lim_{x\to 0} \frac{1}{x} \cdot \int_{0}^{x}(1+\sin(t))^\frac{1}{t}dt$
I think I have to use L'Hospital here since the test will be about it but I can't understand how to solve this exercise at all.

A: $$\lim_{x\rightarrow\infty}\frac{\int_{0}^{x}(1+\sin{t})^{1/t}dt}{x}=\lim_{x\rightarrow\infty}\frac{d}{dx}\int_{0}^{x}(1+\sin{t})^{1/t}dt=$$
$$=\lim_{x\rightarrow\infty}(1+\sin{x})^{1/x}=1$$

A: You do indeed have a quotient, so L'Hôpital does apply. Specifically, the limit is $\lim_{x \to \infty} \frac{\int_{0}^{x}(1+sin(t))^\frac{1}{t}}{x}$.
To actually invoke L'hopital, check that your form is indeed indeterminate (i.e. 0/0, $\infty/\infty$, etc). The bottom is obviously infinity. The top is a little less obvious. Does this definite integral expression keep growing as x keeps growing?
The answer is yes. The integrand is always positive after a while, so you won't have cancellation issues. Additionally, because raising something to $\frac{1}{t}$ for large t is essentially just taking a giant nth root (what happens when you take giant nth roots of numbers greater than 1? Positive numbers less than 1?), the integrand hovers around f(x)=1 for large x. That means your integral (area-finding) expression is going to go off to infinity (the infinite integral of a roughly constant function diverges).
Great, so we have $\infty/\infty$. This is an indeterminate form, and L'hopital's rule applies. Now differentiate the top and bottom.
Differentiating the bottom is easy (it's just $1$). Differentiating the top is also easy (remember fundamental theorem of calculus?)—it's just the integrand since we're going from 0 to x.
Your limit expression is now just
$\lim_{x \to \infty} \frac{(1+sin(t))^\frac{1}{t}}{1}$.
EDIT: IGNORE EVERYTHING BENEATH THIS LINE. Apparently the limit was approaching 0, not $\infty$, so we actually avoid the weird properties I discuss below.
Common sense should tell you the limit is 1, because no matter what we're taking the "giant nth root" of a positive number, and that always goes to 1. We should prove it rigorously though. (If we prove this rigorously, then we also prove that the integral of the expression diverges as x goes to infinity. Can you reason out why? Think in terms of epsilons and deltas, or perhaps greatest upper bounds.)
Break this down case-by-case. Since the thing inside the parentheses oscillates between 0 and 2, and each of those values in between gets raised to an extremely small power, consider the limits of all non-zero quantities as $\frac{1}{t}$ goes to zero. Because you know something about "giant nth roots", you should be able to reason that these limits are all 1.
What about the weird case when the thing in parentheses is zero? We have to prove that as we approach zero, maintaining a high power, those things stay near 1. (We're really proving that the points where the function dips $\epsilon$-away from 1 form a set of arbitrarily small measure after some x > N, which is the best we're gonna get, since 0 to any finite power vanishes).
We can simply argue this by saying "let the parenthetical term be any $\epsilon > 0$. Then for all $\epsilon > 0$, there's a small enough $1/t$ such that we get really close to 1."
This problem is a bit weird because of the property that the function dips to exactly zero once every $2\pi$ units, but the above argumentation (for the purposes of your class I'm not sure how necessary or lacking it is) should be enough to prove that the desired limit is 1.

A: If it is indeed the limit when $x\to 0$, the limit of this quotient is but the definition of the derivative at $0$ of the function
$$\begin{cases}f(x)=\displaystyle\int_0^x(1+\sin t)^{\tfrac1t}\mathop{}\!\mathrm d t &\text{if } x\ne 0\\[1ex]f(0)=0\end{cases}$$
By the First fundamental theorem of integral calculus,
$$f'(x)=(1+\sin x)^{\tfrac1x} \quad (x\ne 0).$$
and $\;f'(0)=\lim_{x\to 0}f'(x)$ if this limit exists.
So all we have to do is finding this limit. We'll find first the limit of its logarithm:
$$\ln f'(x)=\frac1x\ln(1+\sin x)\sim_0\frac{\sin x}x\to 1, $$
whence
$$\lim_{x\to 0} f'(x)=\mathrm e =f'(0). $$


text:
Q: Is there any way to find the shortest distance from a point to a line? I´m working with QGIS 1.8.0. I have a map divided into many features (thousands of small rectangles) and I have a point at the center of each of those features. I also have a map of the transmission lines of the country. Is there any method to measure (not one by one) the shortest distance from the points to the transmission lines? Does the maps have to be projected into any specific CRS?
Regards

A: Continuing with simplexio's suggestion, if you don't have a PostGIS server at hand, you can do the job quickly and simply with SpatiaLite:
Import both the transmission_lines layer and the center_points layer in a new spatialite DB. Then two SQL commands will give you the shortest distance from each point to the transmission line:
First add a column to the centerpoints for the distance value:
ALTER TABLE center_lines ADD COLUMN dist real;

Now calculate the distance:
UPDATE center_points SET dist=(
SELECT MIN( ST_Distance(cp.geometry, tl.geometry) )
FROM center_points AS cp, transmission_lines AS tl
WHERE cp.pk_uid = center_points.pk_uid);

Regarding projection: the ST_Distance function returns values in the units of the projection, so if you want meters, then you must have both layers in a meters based CRS. If your layers are in geographic (Long/Lat) coordinates, you will get the distance in degrees (not very usefull...), so reproject into an appropriate CRS first.


text:
Q: How do I test for null in NSDictionary from SBJSON? I've got an API returning a JSON encoded string of data that returns a real number or "null" as a value. As long as the JSON contains a numeric or string value, everything works as expected. If the key:value pair value is null, the code below crashes.
How do I properly test NSDictionary objectForKey when it's getting a NULL from SBJSON?
When the API returns a null for filetype, the code below crashes at the if() line.
My Objective-C code attempts to test for expected values:
if (1 == [[task valueForKey:@"filetype"] integerValue]) {
    // do something
} else {
    // do something else
}

The API JSON output:
{"tclid":"3","filename":null,"filetype":null}

The NSLog() output of the NSDictionary is:
task {
    filename = "<null>";
    filetype = "<null>";
    tclid = 3;
}

A: When transferring data from JSON to a Cocoa collection, the NSNull class is used to represent "no value", since Cocoa collections can't have empty slots. <null> is how NSNull prints itself.
To test for this, you can use someObject == [NSNull null]. It's a singleton -- there's only one instance of NSNull per process -- so pointer comparison works, although you may prefer to follow the usual Cocoa comparison convention and use [someObject isKindOfClass:[NSNull class]].
You're getting the crash because you're sending integerValue to that NSNull object. NSNull doesn't respond to integerValue and raises an exception.

A: You should first test if there is a value is null, if it is null performing the intValue method may crash your application.
Doing this should do.
if ([[task valueForKey:@"filetype"] isKindOfClass:[NSNumber Class]] && 1 == [[task valueForKey:@"filetype"] integerValue]) {
    // do something
} else {
     // do something else
}

I hope it helps.


text:
Q: BigDecimal round to 0 or 5 I'm tinkering with BigDecimal and currency formatting in Android, and was wondering if it was possible to do the following using BigDecimal:
What I desire:
  64.99 --> 65.00 (Rounded Up)
  64.99 --> 60.00 (Rounded Down)
  65.01 --> 70.00 (Rounded Up)
  65.01 --> 65.00 (Rounded Down)

At present, with my code below, I'm only able to round to zeros. For example:
What I get:
  64.99 --> 70.00 (Rounded Up)
  64.99 --> 60.00 (Rounded Down)
  65.01 --> 70.00 (Rounded Up)
  65.01 --> 60.00 (Rounded Down)

Is there a way using BigDecimal to achieve what I desire?
My code:
private static void printRoundedValues() {
    NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
    BigDecimal valueUp = new BigDecimal(64.50, new MathContext(1,RoundingMode.UP));
    BigDecimal valueDown = new BigDecimal(64.50, new MathContext(1,RoundingMode.DOWN));

    System.out.println("Value Up: " +  currencyFormat.format(valueUp));
    System.out.println("Value Down: " +  currencyFormat.format(valueDown));
}

A: You can multiply by 2, then round to the nearest 10, then divide by 2.  The precision is 2 for these BigDecimals; it may need to be different for BigDecimals of different scale.
BigDecimal[] bds = {new BigDecimal("64.99"), new BigDecimal("65.01")};
BigDecimal two = new BigDecimal("2");
MathContext mcUp = new MathContext(2, RoundingMode.UP);
MathContext mcDown = new MathContext(2, RoundingMode.DOWN);
NumberFormat currency = NumberFormat.getCurrencyInstance();
for (BigDecimal bd : bds)
{
    System.out.println("Test: " + bd);
    BigDecimal roundUp5 = bd.multiply(two).round(mcUp).divide(two);
    System.out.println("Round up: " + currency.format(roundUp5));
    BigDecimal roundDown5 = bd.multiply(two).round(mcDown).divide(two);
    System.out.println("Round down: " + currency.format(roundDown5));
}

Output:
Test: 64.99
Round up: $65.00
Round down: $60.00
Test: 65.01
Round up: $70.00
Round down: $65.00

A:     NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
    BigDecimal valueUp = new BigDecimal(64.50, new MathContext(2, RoundingMode.UP));
    BigDecimal valueDown = new BigDecimal(64.50, new MathContext(2, RoundingMode.DOWN));

    System.out.println("Value Up: " +  currencyFormat.format(valueUp));
    System.out.println("Value Down: " +  currencyFormat.format(valueDown));

Here is how MathContext precision works:

*

*creates a value (64.5)

*set the precision to given value (2) which results in 64.5

*round this value using given RoundingMode (UP), which gives you the value of 65

You probably need to set scale rather than precision:

    BigDecimal valueUp = new BigDecimal(64.50).setScale(0, RoundingMode.UP);
    BigDecimal valueDown = new BigDecimal(64.50).setScale(0, RoundingMode.DOWN);

A: The function you are looking for is setScale and is part of BigDecimal.
Here is a good answer to the same question:
Java BigDecimal: Round to the nearest whole value


text:
Q: Path of moon orbiting the Earth I'm trying to make an animation showing the path of the moon orbiting around the earth, but I'm having some trouble plotting it. For some reason, Mathematica doesn't give me any error messages but after running the animation it doesn't show anything.
I'm trying to get a similar animation to this:

Here is what I got so far:
m1 = 100/q;
m2 = 1/q;
eqn = {x2''[t] ==
   q*m2*(x1[t] - x2[t])/((x2[t] - x1[t])^2 + (y2[t] - y1[t])^2)^(3/2),
   y2''[t] ==
   q*m2*(y1[t] - y2[t])/((x2[t] - x1[t])^2 + (y2[t] - y1[t])^2)^(3/2),
   x1''[t] ==
   q*m2*(x2[t] - x1[t])/((x2[t] - x1[t])^2 + (y2[t] - y1[t])^2)^(3/2),
   y1''[t] ==
   q*m2*(y2[t] - y1[t])/((x2[t] - x1[t])^2 + (y2[t] - y1[t])^2)^(3/2)}

Testek = NDSolve[{eqn, x1'[0] == 0, x1[0] == 0, y1'[0] == 0,
   y1[0] == 0, x2'[0] == 0, x2[0] == 100, y2'[0] == 1,
   y2[0] == 0}, {x1, y1, x2, y2}, {t, 0, 200}]

Animate[ParametricPlot[
   Evaluate[{x1[t], y1[t], x2[t], y2[t]} /. Testek], {t, 0, 200},
   PlotRange -> All], {t, 0, 200}];


text:
Q: Bluetooth Complexity I want, users of my Domain can not pass or transfer any file via Bluetooth due to Data Leakage issue in my office. But They can able to use Bluetooth TWS / Bluetooth sound systems. How can i do this?
Maximum tutorial I found is about direct block bluetooth. Here my case is different and something complex. If I block fsquirt.exe then whole bluetooth system will be shutdown.
Operating System: Windows 10

A: Disabling fsquirt.exe should not shut down everything.  It is responsible for file transfer only.
The bluetooth profile you want to disable is called OBEX and there is indeed a way to disable specific profiles in Windows.. unfortunately.. the REAL way to do it seems to be mostly undocumented.
 This link points to data that shows that the mechanism exists and uses CSPs (configuration service providers) through windows client management.  I know NOTHING about CSPs.. I am not an admin.  If you DO, I would use the section in the middle of the link above to enable only the BT profiles that you want.  Search that page for OBEX and you will find your stuff!
I did quite a bit of research on this (just now) and it also looks like the implementation is still a moving target.
I DID find your fsquirt.exe solution that should have worked for you.
How do I unhook Fsquirt.exe?
Software developers that desire to replace the in-box Bluetooth File Transfer Wizard with a proprietary application can unhook Fsquirt.exe from the underlying transfer wizard mechanism by performing the following steps:

* Create a DWORD value that is named DisableFsquirt under the HKLM\System\CurrentControlSet\Services\Bthport\Parameters key in the registry.
* Set the value of DisableFsquirt to 0x1
* Either reboot or run the following command in a command prompt window: fsquirt.exe -UnRegister

This information  came from MS here .
It should work.
In the future, we will probably (hopefully) have a less stupid solution.
Good luck!
Please let me know if it worked. :)


text:
Q: Hotspot is not working correctly
I have issues in using a hotspot from a laptop using the command prompt. Can anybody help me through this?

A: Try running
    netsh wlan show drivers
and see if hostednetwork supported is set to yes.
If it isn't, try updating your wireless card drivers


text:
Q: TDD dummy repository storage What is best practice to storage dummy data wich will be pased to unit of work class ? I was thinking i can store this data to dictionary but i have quite large amount of linq queries, so it is ok to storage this data to some kind of lightweight sql database? I am new in TDD and maybe missing something important

A: If you are using Entity Framework, you could consider using something like Effort.
One thing to consider is that if you do use a dictionary of list in your test repository, there are cases where using linq against an in-memory structure returns different results to when querying a database.


text:
Q: Integration MVC application with WordPress using Single Sign On I am trying to integrate WordPress blog with the MVC application so that the users logged into the MVC application can access the WordPress blog (like SSO).(i.e) the users should able to access WordPress blog with the credentials used for the MVC application.
Previously I have tried with OAuth2 and DotnetOpenAuth plug-ins, but I could not make it single sign on. Is there any other way to make SSO with WordPress from MVC.


text:
Q: Orbits of arithmetic subgroups intersection a compact set Let us suppose we have $G$ a connected reductive group over a number field $F$. Consider $G(\mathbb{A})$ the group over the adeles and $G(\mathbb{Q})$ embedded discretely. For $\gamma \in G(\mathbb{Q})$ we denote by $\mathcal{O}(\gamma)$ the orbit $\gamma$ under conjugation by elements of $G(\mathbb{A})$. My question is the following. If $M$ is a compact subset of $G(\mathbb{A})$, is it true that only finitely many $\mathcal{O}(\gamma)$ have the property that intersection with $M$ is nonempty?
Note: I am interested in the finiteness of the number of orbits with such property, not the $\gamma$'s.


text:
Q: Row won't move to the next line I am working on my personal website and i'm trying to make a new row with Bootstrap 4. The row has an H1 above it. Whatever I'm trying, the row won't move to the next line. I tried different solutions, inline, br, different rows, nothing works. Can somebody help me out?
This is my current HTML code:

Projecten

col

col

col

I didn't change anything on the CSS code, just the default bootstrap code.
Click here for a screenshot

A: With bootstrap is

Text

col

col

col


text:
Q: Parameterization of Equation with Gaussian Integer I'd like to ask how to get the parameterization to this equation: $3z_1^2+z_2^2=156$, where $z_1$ and $z_2$ are both Gaussian integers.
More generally, is there any parameterization to the general equation $az_1^2+bz_2^2=c$?

A: Here is a discussion around solving $$3x^2+y^2=156\ ,\qquad x,y\in\Bbb Z[i]\ ,$$ based on the factorization of $156$ in the ring $R$ of integers of the number field $$K=\Bbb Q(\sqrt{-1},\sqrt{-3})=\Bbb Q(i,\sqrt 3)\ .$$
I am using $x,y$ instead of the indexed $z$-variables, since it is comfortable to use further the implicit notations $x=x_1+ix_2$, $y=y_1+iy_2$, and avoiding too much indices makes typing simpler.
Note that any solution of the given equation can be rewritten
$$
(y+x\sqrt{-3})
(y-x\sqrt{-3})
=156\ .$$
So we have to find among all factors of $156\in R=\mathcal O_K$ the suitable ones (that have coefficients in $\Bbb Z$ w.r.t. the basis $\{1,i,\sqrt 3,i\sqrt{3}\}$). Note that $R=\mathcal O_K$ is a unique factorization domain. This, and some further steps can be get using sage, the sage code is generally object oriented, structural, and easily readable for mathematicians, i hope its application here by my typing hand does not suggest the contrary, the fields $Q=\Bbb Q(i)$, $L=Q(\sqrt{-3})$, and $K=\Bbb Q(i+\sqrt3)\cong L$ will be introduced, and some properties of them are questioned...
sage: R.<x> = PolynomialRing(QQ)
sage: Q.<j> = QuadraticField(-1)
sage: L.<s> = Q.extension( x^2+3 )
sage: Q
Number Field in j with defining polynomial x^2 + 1
sage: L
Number Field in s with defining polynomial x^2 + 3 over its base field
sage: j^2, s^2
(-1, -3)
sage: L.is_unique_factorization_domain()
True
sage: S.<X> = PolynomialRing(L)
sage: (X-j-j*s)*(X-j+j*s)*(X+j-j*s)*(X+j+j*s)
X^4 - 4*X^2 + 16
sage: K.<a> = NumberField( x^4 - 4*x^2 + 16 )
sage: a.complex_embedding()
-1.73205080756888 - 1.00000000000000*I
sage: K.is_unique_factorization_domain()
True
sage: K.class_number()
1
sage: K.unit_group()
Unit group with structure C12 x Z of Number Field in a
with defining polynomial x^4 - 4*x^2 + 16
sage: L.unit_group()
Unit group with structure C12 x Z of Number Field in s
with defining polynomial x^2 + 3 over its base field
sage: K.units()
(1/8*a^3 - 1/2*a + 1,)
sage: (1/8*a^3 - 1/2*a + 1).norm()
1
sage: L.units()
(-1/2*j*s + 1/2*j + 1,)
sage: (-1/2*j*s + 1/2*j + 1).norm()
1

Let us also ask for the factors of $156\in \mathcal O_L$, and their multiplicities...
sage: print "%4s %-30s %4s %s" % ( 'Mul', 'Factor', 'Norm', 'Norm/Q' )
sage: for fact, mul in L(156).factor():
....:     print ( "%4s %-30s %4s %s"
....:             % (mul, fact, fact.norm(), fact.relative_norm()) )
....:

 Mul Factor                         Norm Norm/Q

   4 (-1/2*j - 1/2)*s - 1/2*j - 1/2    4 2*j
   2 1/2*s + 3/2                       9 3
   1 -1/2*s - j + 3/2                 13 -3*j + 2
   1 1/2*j*s - 3/2*j + 1              13 -3*j - 2
   1 (-1/2*j + 1/2)*s + 1/2*j - 3/2   13 -3*j + 2
   1 (1/2*j + 1/2)*s - 1/2*j - 3/2    13 3*j + 2

Some results were manually rearranged to fit in the shown width.
Humanly, this means we have the following factors that appear in the decomposition of $156$:
$$
\begin{aligned}
f_1 &=\frac 12(1+i+\sqrt{-3}+i\sqrt{-3}) &&\sim \bar f_1\ , &&\text{ order }4\ ,\\
f_2 &=\sqrt{-3}&&\sim \bar f_2\ , &&\text{ order }2\ ,\\[2mm]
f_3 &=\frac 12(3-\sqrt{-3})-i &&\sim \bar f_5\ , &&\text{ order }1\ ,\\
f_4 &=\frac 12(3-\sqrt{-3})+i&&\sim \bar f_6\ , &&\text{ order }1\ ,\\[2mm]
f_5 &=\frac 12(-3+\sqrt{-3}(1-i)+i)&&\sim \bar f_3\ , &&\text{ order }1\ ,\\
f_6 &=\frac 12(-3+\sqrt{-3}(1+i)-i)&&\sim \bar f_4\ , &&\text{ order }1\ ,
\end{aligned}
$$
and now we have to group them w.r.t. the Galois conjugation which maps $i\to i$, $\sqrt{-3}\to-\sqrt{-3}$. A solution of $y^2+3x^2=156$ in integers corresponds to a solution for the relative norm problem
$$
N_{L:\Bbb Q(i)}(y+x\sqrt{-3})=(y+x\sqrt{-3})(y-x\sqrt{-3})=156\ ,
$$
and the two factors contain $(L:\Bbb Q(i))$-conjugated prime factors. These factors are those from above, there may also appear a unit, and we have a classification for the unit group of the field. It has a $12$--torsion part generated by the fourth roots of the unit $1,i,-1,-i$, and the sixth roots of the unit, $1,u,u^2,u^3=-1, -u,-u^2$, where $u=\frac 12(1+\sqrt{-3})$, and the two groups of order $4$, resp. $6$ have the obvious subgroup of order two, $\pm 1$ in common. It also has a free part, in the code we have the generating unit
$$
W = 1+\frac i2(1-\sqrt{-3})\ ,
$$
and its first few powers are:
sage: for k in range(19):
....:     print "W^%2s = %s" % ( k, W^k )
....:
W^ 0 = 1
W^ 1 = -1/2*j*s + 1/2*j + 1
W^ 2 = (-j + 1/2)*s + j + 3/2
W^ 3 = (-3/2*j + 3/2)*s + 5/2*j + 5/2
W^ 4 = (-2*j + 7/2)*s + 6*j + 7/2
W^ 5 = (-2*j + 15/2)*s + 13*j + 7/2
W^ 6 = 15*s + 26*j
W^ 7 = (15/2*j + 28)*s + 97/2*j - 13
W^ 8 = (28*j + 97/2)*s + 84*j - 97/2
W^ 9 = (153/2*j + 153/2)*s + 265/2*j - 265/2
W^10 = (181*j + 209/2)*s + 181*j - 627/2
W^11 = (390*j + 209/2)*s + 181*j - 1351/2
W^12 = 780*j*s - 1351
W^13 = (2911/2*j - 390)*s - 1351/2*j - 2521
W^14 = (2521*j - 2911/2)*s - 2521*j - 8733/2
W^15 = (7953/2*j - 7953/2)*s - 13775/2*j - 13775/2
W^16 = (5432*j - 18817/2)*s - 16296*j - 18817/2
W^17 = (5432*j - 40545/2)*s - 35113*j - 18817/2
W^18 = -40545*s - 70226*j

Not all of them have coefficients in $\Bbb Z[i]$, but $W^{6k}\in\Bbb Z[i]$ is a fact.
Now we can proceed as follows. We find all the solutions using a unit and some (suitably chosen) factors among $f_1,\dots, f_6$. These provide a finite set of solutions. We multiply them with powers of $W$ and get algebraic integers $y+x\sqrt{-3}$ of norm $156$.
So the general solution is of the form:
$$
y + x\sqrt{-3}
=
u\cdot f_1^2\, f_2\, f_{3\text{ or }5}\, f_{4\text{ or }6}\cdot W^k\ ,
$$
where $u$ is a unit (among $12$) and $k\in \Bbb Z$.
We can pass from $(x,y)$ to a solution with real part of $x,y$ both $>0$ (by using powers of $i$).
Here are some values for $x,y\in\Bbb Z[i]$, computed via sage:
Q.<j> = QuadraticField(-1)
R.<X> = Q[]
L.<s> = Q.extension(X^2+3)
f1, f2, f3, f4, f5, f6 = [ f for f, mul in L(156).factor() ]
u = (1+s)/2
units = list(set([ v1*v2 for v1 in [1,j,-1,-j] for v2 in [1,u,u^2,-1,-u,-u^2] ]))
W = L.units()[0]

for k in [0..12]:
    for v in units:
        for f35 in [f3, f5]:
            for f46 in [f4, f6]:
                xi = v * f1^2 * f2 * f35 * f46 * W^k
                xibar = 2*xi.lift().coefficients()[0] - xi
                y, x  = (xi+xibar)/2, (xi-xibar)/2/s
                if (y^2 + 3*x^2 == 156) and QQ(y + y.conjugate()) > 0 and QQ(x + x.conjugate()) > 0:
                    print "y = %-15s | x = %-15s | y^2 + 3x^2 = %3s" % (y, x, y^2 + 3*x^2)

Results:
y = 12              | x = 2               | y^2 + 3x^2 = 156
y = 3*j + 12        | x = -3*j + 4        | y^2 + 3x^2 = 156
y = -3*j + 12       | x = 3*j + 4         | y^2 + 3x^2 = 156
y = 3               | x = 7               | y^2 + 3x^2 = 156
y = 9               | x = 5               | y^2 + 3x^2 = 156
y = 21*j + 6        | x = -3*j + 14       | y^2 + 3x^2 = 156
y = 18*j + 33       | x = -18*j + 11      | y^2 + 3x^2 = 156
y = 6*j + 15        | x = -6*j + 5        | y^2 + 3x^2 = 156
y = 6*j + 24        | x = -12*j + 4       | y^2 + 3x^2 = 156
y = 15*j + 18       | x = -9*j + 10       | y^2 + 3x^2 = 156
y = 60*j + 63       | x = -36*j + 35      | y^2 + 3x^2 = 156
y = 84*j + 21       | x = -12*j + 49      | y^2 + 3x^2 = 156
y = 27*j + 48       | x = -27*j + 16      | y^2 + 3x^2 = 156
y = 24*j + 84       | x = -48*j + 14      | y^2 + 3x^2 = 156
y = 69*j + 120      | x = -69*j + 40      | y^2 + 3x^2 = 156
y = 225*j + 234     | x = -135*j + 130    | y^2 + 3x^2 = 156
y = 102*j + 177     | x = -102*j + 59     | y^2 + 3x^2 = 156
y = 90*j + 312      | x = -180*j + 52     | y^2 + 3x^2 = 156
y = 315*j + 78      | x = -45*j + 182     | y^2 + 3x^2 = 156
y = 258*j + 447     | x = -258*j + 149    | y^2 + 3x^2 = 156
y = 381*j + 660     | x = -381*j + 220    | y^2 + 3x^2 = 156
y = 336*j + 1164    | x = -672*j + 194    | y^2 + 3x^2 = 156
y = 1176*j + 291    | x = -168*j + 679    | y^2 + 3x^2 = 156
y = 840*j + 873     | x = -504*j + 485    | y^2 + 3x^2 = 156
y = 963*j + 1668    | x = -963*j + 556    | y^2 + 3x^2 = 156
y = 3594*j + 6225   | x = -3594*j + 2075  | y^2 + 3x^2 = 156
y = 1254*j + 4344   | x = -2508*j + 724   | y^2 + 3x^2 = 156
y = 3135*j + 3258   | x = -1881*j + 1810  | y^2 + 3x^2 = 156
y = 4389*j + 1086   | x = -627*j + 2534   | y^2 + 3x^2 = 156
y = 1422*j + 2463   | x = -1422*j + 821   | y^2 + 3x^2 = 156
y = 13413*j + 23232 | x = -13413*j + 7744 | y^2 + 3x^2 = 156
y = 4680*j + 16212  | x = -9360*j + 2702  | y^2 + 3x^2 = 156
y = 16380*j + 4053  | x = -2340*j + 9457  | y^2 + 3x^2 = 156
y = 11700*j + 12159 | x = -7020*j + 6755  | y^2 + 3x^2 = 156
y = 5307*j + 9192   | x = -5307*j + 3064  | y^2 + 3x^2 = 156

The general case depends on the way to capture a bigger class number, the computation of units is relatively simpler to get calculated. But note that the units can accidentally a "very big height" and hard to compute in special cases.