text:
Q: JBoss and Resteasy: ClassNotFoundException while deserializing java-serialized object Context: we are using Activiti as a process engine and Activiti-Rest as its interface towards our application. As the question is related to REST services returning objects serialized by Java, I did not add this to the title.
Scenario: we have a JBoss Wildfly instance which contains an EAR with a module (lets call it X for reference) that contains a class "ProcessContext". Activiti is running inside this EAR and the ServiceTasks (Java-snippets getting called from the processes to do some work) depend on that class. They use this class to instantiate a process variable and add some data to it.
We have a second deployment (a WAR, currently on the same Wildfly instance but later on a remote server), which accesses Activiti by its REST api and now we need to access the "ProcessContext" data. This WAR also has a dependency on X and its classloader can resolve "ProcessContext" without problems.
Ok, fine. Doing so seemed simple. Call:
GET history/historic-process-instances/{processInstanceId}/variables/{variableName}/data

This returns a response with MediaType "application/x-java-serialized-object" and inspecting it with the debugger seemed fine. But when I tried to deserialize the object I got this error:
Caused by: java.lang.ClassNotFoundException: xxx.commons.metadata.ProcessMetadata from [Module "org.jboss.resteasy.resteasy-jaxrs:main" from local module loader @103f852 (finder: local module finder @587c290d (roots: /opt/wildfly/modules,/opt/wildfly/modules/system/layers/base))]
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:213) [jboss-modules.jar:1.3.3.Final]
at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:459) [jboss-modules.jar:1.3.3.Final]
at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:408) [jboss-modules.jar:1.3.3.Final]
at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:389) [jboss-modules.jar:1.3.3.Final]
at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:134) [jboss-modules.jar:1.3.3.Final]
at java.lang.Class.forName0(Native Method) [rt.jar:1.8.0_20]
at java.lang.Class.forName(Class.java:340) [rt.jar:1.8.0_20]
at java.io.ObjectInputStream.resolveClass(ObjectInputStream.java:626) [rt.jar:1.8.0_20]
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1613) [rt.jar:1.8.0_20]
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1518) [rt.jar:1.8.0_20]
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1774) [rt.jar:1.8.0_20]
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1351) [rt.jar:1.8.0_20]
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:371) [rt.jar:1.8.0_20]
at org.jboss.resteasy.plugins.providers.SerializableProvider.readFrom(SerializableProvider.java:76) [resteasy-jaxrs-3.0.10.Final.jar:]
... 131 more

Wondering about it I found that the Classloader that is used to deserialize the object if the Module-Classloader of the Resteasy module instead my local (module) classloader.
One solution would probably be to write a module that contains "ProcessContext" and make it globally known in JBoss but that is some infrastructure-decission that was denied by the project lead.
Shouldn't Resteasy rather use the classloader of the caller instead its module classloader? The caller knows its required classes and if I could get hands on the responses internal input stream I could deserialize it myself without any problems. I realy wonder if this a bug or a feature.
Any ideas how to solve this problem?

A: Okay, finally I found a solution by writing an own provider and registering it with the Resteasy client programmatically. I also tried doing this by web.xml but that did not work as I will explain.
For others who have a similr problem here my solution. The message body provider:
@Provider
@Consumes("application/x-java-serialized-object")
public class ActivitiObjectMessageBodyReader implements MessageBodyReader<ProcessMetadata> {

@Override
public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
    return (type == ProcessMetadata.class && "application/x-java-serialized-object".equals(mediaType.toString()));
}

@Override
public ProcessMetadata readFrom(Class<ProcessMetadata> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {

    BufferedInputStream bis = new BufferedInputStream(entityStream);
    ObjectInputStream ois = new ObjectInputStream(bis);
    try {
        return ProcessMetadata.class.cast(ois.readObject());
    } catch (ClassNotFoundException e) {
        throw new WebApplicationException(e);
    }
}

}
I know, I probably do not need the whole expression in the isReadable due to the annotation but well...
The programmatical registration looks like this:
ResteasyProviderFactory factory = new ResteasyProviderFactory();
factory.register(new ActivitiObjectMessageBodyReader());
Configuration configuration = new ClientConfiguration(factory);

Now I can use the configuration like this:
Client client = ClientBuilder.newClient(configuration);

And wow, the Java object variable is retrieved over REST.
----- You can stop reading here unless you want to know about what I think are the reasons of the problem -----
The problem is related to the loading of provider factories inside resteasy. I debugged into it and saw it swapping the providers against the configured providers like this:
Providers current = ResteasyProviderFactory.getContextData(Providers.class);
ResteasyProviderFactory.pushContext(Providers.class, configuration);

When using web.xml or RegisterBuiltin.register(factory) to register my provider globally, the provider can be found in current after the above calls but current is not used for deserialization. Instead the configuration is used and this has a chain of parent factories that result in the factory initialized within the Resteasy module, which does not contain my provider and cannot find my class, due to its own classloader.
And yes, I have e.g. resteasy.scan enabled in web.xml but it does not help.
When providing the factory to the client, it injects it into the response constructor and now the provider is available at serialization time, using the classloader of my own module (as it is registered as a bean), which results in the desired deserialized object.

A: Copy and paste original Jboss SerializableProvider into your application and declare it in web.xml
https://github.com/resteasy/Resteasy/blob/master/jaxrs/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/SerializableProvider.java
<context-param>
        <param-name>resteasy.scan.providers</param-name>
        <param-value>true</param-value>
</context-param>


text:
Q: Perl mail format with new line Hi am writing a perl script were am doing push(@var1,$var2) in @var the values will be get stored and am passing that array value in mail like system("echo @var1| mail -s \"perlmailformat\"  xyz.perlmonks\@example.com");.Hence am success in getting mail but values are clubbed each other with out any new lines .Please let me know how to make a mail format in script or sysntax

A: You are interpolating the @var1 into a shell command which is an extremely unsafe thing to do. It also prints all items in the array on the same line, because interpolating an array into a string joins all items with a single space (and the echo command simply prints all it's arguments onto a single line, with spaces in between and a single newline at the end).
You want to open a pipe to the mail command:
my $subject = "perlmailformat";
my $address = "xyz@example.com";

# open a pipe to "mail"
open my $mail, "|-", "mail", "-s" => $subject, $address
  or die "Can't open mail command: $!";

# print each line:
print { $mail } "$_\n" for @var1;

# close the pipe
close $mail or die "Couldn't send mail: $!";

This completely circumvents the shell, and is thus much safer.

A: Push a newline into the array before passing the same to the mail command.
push @var,"\n";
system("echo \"@var\" | mail -s \"perlmailformat\" xyz.perlmonks\@example.com");

redpajama_set_name: RedPajamaStackExchange


text:
Q: wordpress: not able to pass form data from one page to other I have two different forms on two pages. These two pages are using different page templates. I need to pass the form data from page1 to page2. I use below jQuery function.
if(form_validated) {
url = templateDir + "?page_id=1508"; //permalink of the submit page

        var form = '<form action="' + url + '" method="post">' +
            '<input type="hidden" name="pt-username" value="' + name + '"></input>' +
            '<input type="hidden" name="pt-zipcode" value="' + zipcode + '"></input>' +
            '<input type="hidden" name="pt-email" value="' + email + '"></input>' + '</form>';

        $('body').append(form);
        $(form).submit();
}

But on my page2 POST variables are blank. I am not able to get the form data on the page2.
Can anyone help me with this?


text:
Q: word problem about right-angle triangle An observer who is standing $47$ m from a building, measures the angle of elevation of the top of the building as $17°.$ If the observers eye is $167$ cm from the ground, what is the height of the building?

A:
Here height of building is $AC$
In right angle triangle $\Delta ABC$
$$\dfrac {h}{47}=\tan 17^\circ\implies h=47\tan17^\circ$$
so total height of building is $(1.67+47\tan17^\circ)$ m $\approx16$m

A: Let denote by $x$ the distance (elevation) from the obsever's eye to the top of building so
$$x=47\tan(17^°)\approx 14.36 m$$
so the height of the building is $h=x+1.67\approx 16 m$


text:
Q: document is undefined in document.getElementById, while writing unit test cases in Jest I have written a code to disable a button using :
document.getElementBydId('btn').disabled = true;
This call is written inside componentWillUnmount life cycle event of react. Using this way because the button is coming from a common repo, which can't be accessed directly inside my component.
Now all the unit test cases for this component are failing and getting an error that 'document' is null. We are using jest for writing unit test cases.
Can anyone please help on this.

A: This is one of reasons why using DOM in React directly is discouraged.
document.getElementById('btn').disabled should be provided and mocked, wither with JSDOM or by stubbing variables explicitly.
JSDOM can be applied to global scope directly or with Jest configuration (it defaults to stubbing DOM with JSDOM).
It can also be stubbed with:
beforeEach(() => {
  global.document = {
    getElementById: jest.fn()
  }
});

afterEach(() => {
  delete global.document;
});

it('...', () => {
  document.getElementById.mockReturnValue({ disabled: true });
  ...
  expect(document.getElementById).toHaveBeenCalledWith('btn');
});

A: You need to mock getElementById in for your test case.
Then you can test if getElementById is called with correct params and disabled is being set to true (assuming it to be false before).
expect(document.getElementById).toHaveBeenCalled();
expect(document.getElementById.mock.calls[0][0]).toBe("btn");
expect(btnParams.disabled).toBeTruthy();

I have created a working test case for the same which can be found at https://codesandbox.io/s/jznv48w32v
Please note that we are using beforeEach and afterAll in our test case.
beforeEach resets our mocked function after every test case.
afterAll is used to restore the value of the mocked function to original value.


text:
Q: UIScrollView displaying Camera I have created a camera view to be displayed on the screen by creating a AVCaptureVideoPreviewLayer and now I would like it to be able to be displayed inside of my scroll view.  Currently my scroll view is set up to handle UIImageViews but not the camera layer.  Here is how it all works together:
//Set Up the Camera View
    [self setCaptureManager:[[CaptureManager alloc] init]];
[[self captureManager] addVideoInput];

[[self captureManager] addVideoPreviewLayer];
CGRect layerRect = [[[self view] layer] bounds];
[[[self captureManager] previewLayer] setBounds:layerRect];
[[[self captureManager] previewLayer] setPosition:CGPointMake(CGRectGetMidX(layerRect),
                                                              CGRectGetMidY(layerRect))];
[[[self view] layer] addSublayer:[[self captureManager] previewLayer]];

[[captureManager captureSession] startRunning];

int PageCount = 2;
NSMutableArray *arrImageName =[[NSMutableArray alloc]initWithObjects:settingsView,captureManager,nil];
UIScrollView *scroller = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
scroller.scrollEnabled=YES;
scroller.backgroundColor = [UIColor clearColor];
[scroller setShowsHorizontalScrollIndicator:NO];
scroller.pagingEnabled = YES;
scroller.bounces = NO;
scroller.delegate = self;
[self.view addSubview:scroller];
int width=scroller.frame.size.width;
int xPos=0;
for (int i=0; i<PageCount; i++)
{
    UIView *view1 = [[UIView alloc]initWithFrame:CGRectMake(xPos, 0, scroller.frame.size.width, scroller.frame.size.height)];
    UIView *view2 = [arrImageName objectAtIndex:i];
    [view1 addSubview:view2];
    [scroller addSubview:view1];
    scroller.contentSize = CGSizeMake(width, 0);
    width +=scroller.frame.size.width;
    xPos  +=scroller.frame.size.width;
}

The capture manager handles the AVCaptureVideoPreviewLayer and this all works fine and displays by itself.  I am trying to get it to show up inside my scrollView so I have commented out the CGRect layerRect and instead am trying to get it displayed in my array on the scrollView.  At the bottom of the scrollView, I have a UIImageView that is taking the array and displaying it, however this wont obviously work as the camera is not an Image.  What can I change or look into at the bottom to make this work?  Change it to a UIView?  Thank you.

A: After your loop, just create and add UIView at the bottom of the your UIScrollView (with proper position and rect). Then, add video preview layer as a sublayer to the view added to the scrollView. Good Luck!
EDIT
ok, try this:
[[self captureManager] addVideoInput];

[[self captureManager] addVideoPreviewLayer];
CGRect layerRect = [[[self view] layer] bounds];
[[[self captureManager] previewLayer] setBounds:layerRect];
[[[self captureManager] previewLayer] setPosition:CGPointMake(CGRectGetMidX(layerRect),
                                                              CGRectGetMidY(layerRect))];
UIView *captureView = [[UIView alloc] initWithFrame:self.view.bounds];
[[captureView layer] addSublayer:[[self captureManager] previewLayer]];

[[captureManager captureSession] startRunning];

int PageCount = 2;
NSMutableArray *arrImageName =[[NSMutableArray alloc]initWithObjects:settingsView,captureView,nil];
UIScrollView *scroller = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
scroller.scrollEnabled=YES;
scroller.backgroundColor = [UIColor clearColor];
[scroller setShowsHorizontalScrollIndicator:NO];
scroller.pagingEnabled = YES;
scroller.bounces = NO;
scroller.delegate = self;
[self.view addSubview:scroller];
int width=scroller.frame.size.width;
int xPos=0;
for (int i=0; i<PageCount; i++)
{
    UIView *view1 = [[UIView alloc]initWithFrame:CGRectMake(xPos, 0, scroller.frame.size.width, scroller.frame.size.height)];
    UIView *view2 = [arrImageName objectAtIndex:i];
    [view1 addSubview:view2];
    [scroller addSubview:view1];
    scroller.contentSize = CGSizeMake(width, 0);
    width +=scroller.frame.size.width;
    xPos  +=scroller.frame.size.width;
}


text:
Q: Scanner method and string pool The script below will compare two string to see if they are equal. In this case one string is declared and the other string is input from the scanner. I understand  why these two string are not equal when compared (say aName = test and anotherName= test) because they will contain different references addresses.
This next paragraph will lead into my question. The nextLine() method returns a string. I know normally if two strings contain the same text they would have the same address in the string pool. So my question is, why isn't the string returned from the nextLine() method to the anotherName variable assigned to the string pool and given the same address as aName, since they have the same text? *
import java.util.Scanner;
public class TryToCompareString
{
public static void main(String[] args)
{
String aName = "test";
String anotherName;
Scanner input = new Scanner(System.in);
System.out.println("Enter your name");
anotherName = input.nextLine();

if (aName == anotherName)
{
System.out.println(aName + " equals " + anotherName);
}
else
{
System.out.println(aName + " does not equal " + anotherName);
}
}
}


text:
Q: Call mySQL rows to a Flask function and run model on them, outputting the results to a HTML table? I want to call the rows of a column from a mySQL database table to my Flask application, so I can run my LDA topic model over them. I then want to print the LDA topics identified into a HTML table for the user to see. (I also want to visualise this data in the table, but that's another challenge). For now I just want to print the topics in a basic way.
When I run the code below and load my application, I get the following error:
TypeError: 'int' object is not iterable

Full traceback:
    Traceback (most recent call last):
  File "C:\Users\jeram\anaconda3\envs\my_env\lib\site-packages\flask\app.py", line 2091, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:\Users\jeram\anaconda3\envs\my_env\lib\site-packages\flask\app.py", line 2076, in wsgi_app
    response = self.handle_exception(e)
  File "C:\Users\jeram\anaconda3\envs\my_env\lib\site-packages\flask\app.py", line 2073, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\jeram\anaconda3\envs\my_env\lib\site-packages\flask\app.py", line 1518, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Users\jeram\anaconda3\envs\my_env\lib\site-packages\flask\app.py", line 1516, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Users\jeram\anaconda3\envs\my_env\lib\site-packages\flask\app.py", line 1502, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
  File "c:\Users\jeram\Documents\NCI\Semester 3\TriagatronX50\app.py", line 65, in insight
    new_corpus = [common_dictionary.doc2bow(text) for text in resultValue]
TypeError: 'int' object is not iterable

This is my Python function:
    @app.route('/insight', methods=['GET', 'POST'])
def insight():

    if request.method == 'GET':
        # if request.form['submit_button'] == 'Main Themes':
            cur = mysql.connection.cursor()
            resultValue = cur.execute("SELECT journal_entry FROM journals")
            common_dictionary = Dictionary(common_texts)
            new_corpus = [common_dictionary.doc2bow(text) for text in resultValue]
            lda = gensim.models.LdaModel(new_corpus, num_topics=5, alpha='auto', eval_every=5)
            main_themes = pprint(lda.print_topics())
        # return render_template('insight.html', value=main_themes)
    return render_template('insight.html', value=main_themes)

My HTML code:

                    <form method=" ">
                        Topics Identified

                             {{ value }}

                    </form>

                <input type="submit" name="submit_button" value="Main Themes" class='btn'>

Ideally I would also like to get my button working so that the function only acts when it is called, but firstly I just want to get it working at a basic level.
Any help would be greatly appreciated!


text:
Q: Updating Subscriber(Contact) key in Marketing Cloud Currently, we use Subscriber key= Email Address = Contact Key;
We are planning to use Salesforce Contact ID as Subscriber key/ContactKey. Is there a way to mass update Subscriber key value for all our current Subscribers (we have around 250k subscribers)? Also, will we lose all the tracking data about our subscribers? We are mostly concerned about Einstein Optimization data, but we are not sure if Einstein tracks and stores the data based on the Subscriber Key or email address?

A: What you are looking into is a so-called Subscriber Key migration. A task which can't be done within the UI, and requires a paid services engagement by Salesforce. It will basically update the database, replacing the old Subscriber Keys with new ones, based on a SubscriberKey Data Extension containing the following fields:

*

*OldSubKey - Text Field

*NewSubKey - Text Field

*MigrationDate - Date Field

The data MUST be validated

*

*No duplicate keys can exist in the OldSubKey column

*No duplicate keys can exist in the NewSubKey column

*OldSubKey and NewSubkey values cannot be the same for a subscriber across the entire data set.

So you will want to have your email addresses in the OldSubKey column and your Salesforce IDs in NewSubKey column.
All OldSubkey values should exist in the Subscriber table. If any OldSubkey is not in the Subscriber table, then those OldSubkey values will not be included in the migration.
If a subscriber is NOT included in the mapping DE, there will be no update applied to the subscriber. The process will migrate only what exists in the mapping DE.
This is relatively easy. What makes the task more complex is the fact that you CANNOT send during the migration process. Sending includes both Batch Sends and Triggered Sends. You must ensure your API calls are halted and that the Triggered Send queue is cleared and then paused on the Marketing Cloud side.
Once all of the above has been completed SFMC Services in the US will need to be engaged to carry out and oversee the actual migration.
To avoid having legacy Subscriber Keys appear in Marketing Cloud, it is essential to ensure the Sales Cloud becomes single source of consumer identity and other systems should no longer provide data which in any way reference the legacy Subscriber Key, being the email address.
Subscriber Key migration will indeed carry engagement over from the old Sub Key to the new ones, which applies to both clicks/opens, and Einstein engagement. Most of the clients I work with accept the fact of the engagement data being lost, as the impact of the Subscriber Key migration on their business continuity is seen as too significant - as downtime of approx 24 hours should be expected. They just create new subscribers with new Subscriber Key value, and perform contact deletion on the old records.
You can read more about Subscriber Key migration in my blog.


text:
Q: PHP Pagination show first two pages and last two pages I'm currently using the php pagination script below. The pagination displays six results per page with previous/next links. I was wondering if anyone might know what I could add so that the pagination also displays links to the first two pages and the last two pages? Like the pagination in this example page: http://www.winelog.net/wines/Oregon
$data=file("data.txt");
$pages=0;
foreach($data as $temp){
    $x=explode("|",$temp);
    if($x[0] > 0){
        $pages=$pages+1;
    }
}

if($_GET['p']){
    $page=$_GET['p'];
}

if($_GET['i']){
    $index=$_GET['i'];
}

if($index == "p"){
    $page=$page-1;
}
if($index == "n"){
    $page=$page+1;
}
if($page < 1){
    $page=1;
}
if($page  >  $pages){
    $page=$pages;
}
$line=$data[$page-1];
$fields=explode("|",$line);

The displayed navigation:
$show=6;
echo "
« PREV
";

if($page-($show/2)  >  1){
    $temp=$page-$show;
    echo "
...
";
}

if($page-($show/2) >= 1 && $page+($show/2) <= $pages){
    $start=$page-($show/2);
    $stop=$page+($show/2);
}

if($page-($show/2) < 1){
    $start=1;
    $stop=$show;
}

if($page+($show/2) > $pages){
    $start=$pages-$show;
    $stop=$pages;
}

for($i=$start; $i<=$stop; $i++){
    if($page==$i){
        echo "
$i
";
    }
    else{
        echo "
$i
";
    }
}

if($page+($show/2) < $pages){
    $temp=$page+$show;
    echo "
...
";
}
echo "
NEXT »
";

A: Here's what you need to do.
First get a count of the number of 'pages' that there are.
If there are less than, say, 10 pages - output all the pages.
Otherwise:
Output from current page - 5 to current page + 5.
Before the output, put a 'First' button - page = 1
After the output, put a 'Last' button - page = total number of pages.
If you want a second-to-last button, just go page = total number of pages - 1, etc.
You might want to look into Zend_Paginator - You don't need to use the whole Zend Framework to use individual parts of it, it's designed so it can be pulled apart.

A: The full code of their pagination script is available for free @Stranger Studios There is a php and a Perl script available for download.
Code PHP version:
<?php
//function to return the pagination string
function getPaginationString($page = 1, $totalitems, $limit = 15, $adjacents = 1, $targetpage = "/", $pagestring = "?page=")
{
    //defaults
    if(!$adjacents) $adjacents = 1;
    if(!$limit) $limit = 15;
    if(!$page) $page = 1;
    if(!$targetpage) $targetpage = "/";

    //other vars
    $prev = $page - 1;                                  //previous page is page - 1
    $next = $page + 1;                                  //next page is page + 1
    $lastpage = ceil($totalitems / $limit);             //lastpage is = total items / items per page, rounded up.
    $lpm1 = $lastpage - 1;                              //last page minus 1

    /*
        Now we apply our rules and draw the pagination object.
        We're actually saving the code to a variable in case we want to draw it more than once.
    */
    $pagination = "";
    if($lastpage > 1)
    {
        $pagination .= "
";

        //previous button
        if ($page > 1)
            $pagination .= "� prev";
        else
            $pagination .= "� prev";

        //pages
        if ($lastpage < 7 + ($adjacents * 2))   //not enough pages to bother breaking it up
        {
            for ($counter = 1; $counter <= $lastpage; $counter++)
            {
                if ($counter == $page)
                    $pagination .= "$counter";
                else
                    $pagination .= "$counter";
            }
        }
        elseif($lastpage >= 7 + ($adjacents * 2))   //enough pages to hide some
        {
            //close to beginning; only hide later pages
            if($page < 1 + ($adjacents * 3))
            {
                for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
                {
                    if ($counter == $page)
                        $pagination .= "$counter";
                    else
                        $pagination .= "$counter";
                }
                $pagination .= "...";
                $pagination .= "$lpm1";
                $pagination .= "$lastpage";
            }
            //in middle; hide some front and some back
            elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))
            {
                $pagination .= "1";
                $pagination .= "2";
                $pagination .= "...";
                for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
                {
                    if ($counter == $page)
                        $pagination .= "$counter";
                    else
                        $pagination .= "$counter";
                }
                $pagination .= "...";
                $pagination .= "$lpm1";
                $pagination .= "$lastpage";
            }
            //close to end; only hide early pages
            else
            {
                $pagination .= "1";
                $pagination .= "2";
                $pagination .= "...";
                for ($counter = $lastpage - (1 + ($adjacents * 3)); $counter <= $lastpage; $counter++)
                {
                    if ($counter == $page)
                        $pagination .= "$counter";
                    else
                        $pagination .= "$counter";
                }
            }
        }

        //next button
        if ($page < $counter - 1)
            $pagination .= "next �";
        else
            $pagination .= "next �";
        $pagination .= "
\n";
    }

    return $pagination;

}
?>

Change the code to fit your needs and add some CSS.
There are a lot of questions about pagination, I hope this is helpful to users who in need of a pagination script..

A: The link to the winelog site is broken. Hence, I couldn't see the sample you are interested in.
I have written a pagination script in PHP which shows two adjacent pages to the active page, i.e.
< 1  2  3 4  5 >  // 3 being the active page

< 1  2  3  4 >  // 2 being the active page

Here is the code:
/* set total records */
$total_records = 26;  // this is the total count of values in an array or query results from the database

/* set records per page */
$records_per_page = 5;

/* calculate total pages */
$total_pages = ceil($total_records / $records_per_page);

/* get and set value for current page */
if (isset($_GET['page'])) {
    $current_page = $_GET['page'];
} else {
    $current_page = 1;
}

/* calculate and set previous and next page values */
$previous = $current_page - 1;
$next = $current_page + 1;

/* set start page value */
$start_page = 1;

/* set number of pages to display to the left */
/* maximum value should be 4 */
$pages_to_left = 2;

/* set number of pages to display to the right */
/* maximum value should be 4 */
$pages_to_right = 2;

/* show previous pages to the left */
if ($current_page <= $total_pages && $current_page > $start_page + $pages_to_left) {
    $start_page = $current_page - $pages_to_left;
}

/* show next pages to the right */
if ($current_page <= $total_pages && $current_page > $start_page - $pages_to_right) {
    $end_page = $current_page + $pages_to_right;
    if ($current_page == $total_pages || $current_page + 1 == $total_pages || $current_page + 2 == $total_pages || $current_page + 3 == $total_pages) {
        $end_page = $total_pages;
    }
} else {
    $end_page = $total_pages;
}

/* show previous button */
if ($current_page > 1) {
    echo '«';
    echo "  ";
}

/* display pages */
for ($page = $start_page; $page <= $end_page; $page++) {
    echo ''.$page.'';
    echo "  ";
}

/* show last page button */
if ($end_page + $pages_to_right <= $total_pages || $end_page != $total_pages) {
    echo '…' . $total_pages . '';
}

/* show next button */
if ($current_page < $total_pages) {
    echo "  ";
    echo '»';
}

Here is a pastebin link to the script: https://pastebin.com/espTvimy
Kindly check it out and let me know if it works for you.


text:
Q: How to make a loop on the results of loop I have a function which returns array of objects.
const matches = checkMatching(param1, param2, param3);
Function checkMatching returns array and I want on that array call another function checkMatching. And then if checkMatchingfunction still returns array I want to recall checkMatching on that array. Summarizing I want to create infinite loop until chechMatching won't  returns array;
Basically I'm trying to create array
let allMatchingWords = []
Which collects all results from loops.
Currently I have something like this

const checkMatching = (board, r, c) => {
  const top = board[r - 1] !== undefined && { row: r - 1, column: c };
  const bottom = board[r + 1] !== undefined && { row: r + 1, column: c };
  const left = board[r][c - 1] !== undefined && { row: r, column: c - 1 };
  const right = board[r][c + 1] !== undefined && { row: r, column: c + 1 };

    const directionsWithMatches = [top, bottom, left, right]
    .filter(dir => dir instanceof Object)
    .filter(({ row, column }) => board[row][column].word === board[r][c].word);

  return directionsWithMatches;

};
const matches = checkMatching(param1, param2, param3);

let allMatchingWords = [];

 matches.map(({ row, column }) => {
    allMatchingWords = [
      ...matches,
      ...allMatchingWords,
      ...checkMatching(param1, param2, param3),
    ];
});
/// removing duplicates
 allMatchingWords = allMatchingWords.filter(
    (v, i, a) => a.findIndex(t => t.key1 === v.key1 && t.key2 === v.key2) === i,
  );

But for now there is a shortcut to loop twice.
I tried to create while loop but I'm not sure that it's possible that way.


text:
Q: Highcharts - How to start x axis from an arbitrary value I am using [highcharts][1] to plot a graph between a range of values from data base. I want by X Axis values to start from the user input.
For example, if the user wants the values between range 50 and 100, I want my x axis to start from 50.
The range would be of variable size. The size of the data is large so I can't do something like getting all and using min and max for display.
Thanks in advance.
This is my chart object. I have two input fields for user that I use to query the database and return rows in between.
I use multiple type of graphs. The problem is that I have no idea on how to define the start of X axis as 50 if I am getting data from database between 50 and 100. It shows 50 values but start them from 0 upto 50.
I tried min 10 and so. That do start from that value but skips the first 10 or so values.
The input field has id 'lower' and 'upper'.

var options = {
      chart: {
        renderTo: ctn.attr('id'),
        type: $('#graph_type option:selected').val(),
        zoomType: 'x'
      },
      title: {
        text: $('#graph_title').val()
      },
      subtitle: {
          text: "Graph - " + (graph_no + 1)
      },
      xAxis: {

        title: {
           text: $('#x_label').val()
        }
      },
      yAxis: {
        title: {
          text: $('#y_label').val()
        }
      },

      credits: {
        enabled: false
      },
      series: []
    };

A: I think setting min and max for xAxis will work.
Refer this link
and you can say
startOnTick: false,
endOnTick:false
For example refer  : example
I have values set min of y to 20 and max to 217,
yAxis: {
        min: 20,
        max:217,
        startOnTick: false,
        endOnTick:false
    },

See how ther chart is displayed.
I hope this helps.

A: Thanks everyone for the response. I found the solution. Min max was not actually doing as I wanted it to.
I found the solution.
To start the x axis value from desired value use
plotOptions:
     <your_graph_type>:{
             pointStart: <your_value>
}


text:
Q: Angular HttpInterceptor, получить статус от запроса несмотря на ошибку или 201    addToken(req: HttpRequest<any>, token: string|null): HttpRequest<any> {
        return req.clone({ setHeaders: { Accept: 'application/json', Authorization: 'Bearer ' + token }})
      }

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

return next.handle(this.addToken(req, this.Token.accessToken())).pipe(
      catchError(error => {
        if (error instanceof HttpErrorResponse) {
          switch ((<HttpErrorResponse>error).status) {
            case 400:
              return this.handle400Error(error);
            case 401:
              return this.handle401Error(req, next);
            default:
              return observableThrowError(error);
          }
        } else {
          return observableThrowError(error);
        }
      }));
}

catchError выдает ошибку типов, другой способ кроме catchError есть, чтобы поймать 401 статус и message от backend?


text:
Q: Real-time data acquisition and data plot problem in Matlab I' ve been having problems to acquire data and plot it in real time. I' ve been able to plot a graph that has a moving x-axis with the help of function drawnow nd by translating the x-axis with the help of function xlim. Now I' ve been wondering if there is a way to read acquisited data one by one (bite per bite), and to plot it in real - time using the same method. Also I' m wondering if the same method could be aplied to generate a signal and send it to an analog output(example winsound), but to make it go outside bit by bite. The folowing is Matlab code used for gui.
function pushbutton3_Callback(hObject, eventdata, handles)
handles.StopGenSignal = 0;
guidata(hObject,handles);
amp=str2double(get(handles.edit7,'String'));
frek=str2double(get(handles.edit6,'String'));
% ao=analogoutput('winsound');
% addchannel(ao,1);
% set(ao,'StandardSampleRates',8000);
% set(ao,'TriggerType','Immediate');
% set(ao,'SampleRate',2*8000);
h=animatedline;
xlabel('Vrijeme [sec]');
ylabel('Amplituda [V]');
title('Generisani signal');
axis([0 3 -amp-1 amp+1]);
grid on;
t=0;
while handles.StopGenSignal==0
    y=amp*sin(2*pi*frek*t);
%putdata(ao,y);

if(t>3)
  axis([t-2.9 t+0.1 -amp-1 amp+1]);
end
addpoints(h,t,y);
drawnow
pause(0.01);
t=t+0.01;
handles = guidata(hObject);
end
function pushbutton5_Callback(hObject, eventdata, handles)
handles.StopGenSignal = 1;
guidata(hObject,handles);

The given code represents the generated signal, my question is whether there is a way to make an analogoutput object (or analog input) and to send data (or recieve) data bite per bite (with a refresh period) so that I can use the same metod as in the shown while loop to plot date in real time, and to send it to winsound (or mcc). Thanks in advance.


text:
Q: Boosting AND Bagging Trees (XGBoost, LightGBM) There are many blog posts, YouTube videos, etc. about the ideas of bagging or boosting trees. My general understanding is that the pseudo code for each is:
Bagging:

*

*Take N random samples of x% of the samples and y% of the features

*Fit your model (e.g., decision tree) on each of N

*Predict with each N

*Average the predictions to get the final prediction

Boosting:

*

*Fit your model (e.g., decision tree) to your data

*Get the residuals

*Fit your model to the residuals

*Go to 2 for N boosting rounds

*The final prediction is a weighted sum of the sequential predictors.

I'll take any clarifications to my understanding above, but my intended question is as follows:
Both XGBoost and LightGBM have params that allow for bagging. The application is not Bagging OR Boosting (which is what every blog post talks about), but Bagging AND Boosting. What is the pseudo code for where and when the combined bagging and boosting takes place?
I expected it to be "Bagged Boosted Trees", but it seems it is "Boosted Bagged Trees". The difference seems substantial.
Bagged Boosted Trees:

*

*Take N random samples of x% of the samples and y% of the features

*Fit Boosted trees on each of the N samples

*Predict with each N

*Average the predictions to get the final prediction

This seems like the best way to do it. After all, the risk in boosting is overfitting and the primary benefit of bagging is to reduce overfitting; bagging a bunch of boosted models seems like a great idea.
However, from looking through, for example the scikit-learn gradient_boosting.py (which does sample bagging, but not random feature selection), and cobbling together some small nuggets across posts about LightGBM and XGBoost, it looks like XGBoost and LightGBM work as follows:
Boosted Bagged Trees:

*

*Fit a decision tree to your data

*For i in N boosting rounds:

*

*Get the residuals

*if i mod bag_frequency == 0 (i.e., bag every 5 rounds):

*

*Take a single random sample of x% of the samples and y% of the features; use this random sample going forward

*fit tree to the residuals

*The final prediction is a weighted sum of the sequential predictors.

Please correct my understanding here and fill in the details. Boosted Bagged Tree (with just 1 random tree per bag_frequency) doesn't seem as powerful as Bagged Boosted Tree.

A:
Bagging:
  Take N random samples of x% of the samples and y% of the Features

Instances are repeatedly sub-sampled in Bagging, but not Features. (RandomForests, XGBoost and CatBoost do both):
Given dataset D of size N.
For m in n_models:
    Create new dataset D_i of size N by sampling with replacement from D.
    Train model on D_i (and then predict)
Combine predictions with equal weight

Include an initialization step in your Boosting pseudo code to get rid of redundancy:
Init data with equal weights (1/N).
For m in n_model:
    Train model on weighted data (and then predict)
    Update weights according to misclassification rate.
    Renormalize weights
Combine confidence weighted predictions

Bagged Boosted Trees (as you call it) is certainly a reasonable Approach, but different from XGBoost or CatBoost:
Given dataset D of size N.
For m in n_models:
    Create new dataset D_i of size N by sampling with replacement from D.
    (Insert Boosting pseudo code here (on D_i))
Combine predictions with equal weight

XGBoost and CatBoost are both based on Boosting and use the entire training data. They also implement bagging by subsampling once in every boosting Iteration:
Init data with equal weights (1/N).
For m in n_model:
    Train model on weighted bootstrap sample (and then predict)
    Update weights according to misclassification rate.
    Renormalize weights
Combine confidence weighted predictions

If you want to stick to "fit model to residuals", then this would be equivalent to "fit model to residuals of data in bootstrap sample".

Further Remarks:
There is no "best way to do it" as you suggest (no free lunch theorem). "Bagged Boosted Trees" might outperform XGBoost on certain data sets.

Take a single random sample of x% of the samples

This line is confusing. Where did you get this from?

if i mod bag_frequency == 0 (i.e., bag every 5 rounds):

This should not be mentioned in your pseudo code. Especially when there are other more important parameters left out (like learning rate in boosting).


text:
Q: Application of conformal normal coordinates for higher order elliptic operator Let $n>2$ be even. Consider a compact Riemannian manifold $(M^n,g)$ and denote with $P_g$ the critical GJMS operator.
Recall that $P_g$ is conformally invariant, i.e.
$$P_{\tilde g}=e^{-nu}P_g$$ if $\tilde g=e^{2u}g$ for some $u$.
Let $H$ be given by the following expression $$H(x,y)=c_n \log(\frac{1}{r})f(r)$$ where $r=d_g(x,y)$ is the geodesic distance from $x$ to $y$ and $f(r)$ is a positive decreasing function, $f(r)=1$ in a neighborhood of $r=0$ and $f(r)=0$ for $r\geq r_{inj}$ the injectivity radius.
From Lee-Parker "The Yamabe problem" (Theorem $5.1$) there exists a metric $\tilde g$ conformal to $g$ such that $$ |\tilde g(x,y)|=1+O(r^m)$$ for some $m$ big enough. In coordinates we have the following expression for the Laplace-Beltrami operator $$\Delta_{\tilde g, y}v=\frac{1}{\sqrt{|\tilde g|}}\partial_i(\tilde g^{ij}\sqrt{|\tilde g|}\partial_j v).$$
In normal conformal coordinates one has $$\tilde g^{ij}=\delta_{ij}+O(r^2)$$ $$\partial_i \tilde g^{ij}=O(r).$$
Question: prove that working in this coordinate system one has $$|P_{\tilde g} H(x,y)|\leq C r^{2-n}$$ for $r\leq Cr_{inj}$.
This is a step of the proof of Lemma 2.1 in Ndiaye "Constant Q-curvature metrics in arbitrary dimension". It is not clear to me how to do the computation to prove the estimate and why one needs conformal normal coordinates instead of geodesic coordinates.
A proof for $n=4$ is well appreciated too. In this case $$P_g v=(-\Delta_g)^2 v+\textrm{div}_g(\frac{2}{3} R_g g-2Ric_g)dv$$ where $R_g$ denotes the scalar curvature and $Ric_g$ the Ricci curvature. For $n>4$ one has $$P_g v=(-\Delta_g)^{n/2} v+l.o.t.$$


text:
Q: How to draw bitmap from external file on the form? I am using QT Creator 3.5.0 on Ubuntu 15.10. I have one form (mainwindow.ui) and I draw one GraphicView object (QGraphicsView) and one button (QPushButton). Signal on_pushButton_clicked() is created.
How to draw image from external file (BMP/ JPG/ PNG) on GraphicView object (that already exists) on the specific coordinates inside GraphicView object (x, y) when I click on the QPushButton?


text:
Q: Ruby on Rails renamed foreign key I'm trying to create a model for a comic book which has 1 writer and 1 artist. These are both instances of a Person. However how do I show this in my migration?
class CreateComics < ActiveRecord::Migration
   def self.up
     create_table :comics do |t|
       t.column :name, :string
       t.column :writer_id, :integer, :null => false
       t.column :artist_id, :integer, :null => false
     end
   end
...

How do I say :writer_id should map to :person_id or is this kind of renaming frowned upon?

A: You create the mapping in your model class using the class_name and foreign_key option.
belongs_to :writer, :class_name => "Person", :foreign_key => "writer_id"
belongs_to :artist, :class_name => "Person", :foreign_key => "artist_id"

A: The migration has no knowledge of how you intend to use the tables defined within it. All that information goes in the models.
In short your migration is fine for what you've described will be done. But you need to flesh out the models to define the associations you're thinking of.
class Comic < ActiveRecord::Base
  belongs_to :writer, :class_name => "Person"
  belongs_to :artist, :class_name => "Person"
end

This allows you to reference the Writer and Artist from a Comic. However, you will probably want to reciprocate the association so that you can easily fetch a comic from a person based on their role in it's production.
class Person < ActiveRecord::Base
  has_many :comics_as_writer, :class_name => "Comic", :foreign_key => :writer_id
  has_many :comics_as_artist, :class_name => "Comic", :foreign_key => :artist_id

  # some times you don't care what a person did for a comic,
  # you just want to know what they worked on.
  has_many :comics, :finder_sql => "SELECT comics.* FROM comics, people WHERE " +
     "`comics`.`writer_id` = `people`.`id` OR " +
     " `comics`.`artist_id` = `people`.`id`"
end

With these relationships defined the following is possible:
@comic.artist # => Person with id matching comics.artist_id
@comic.writer # => Person with id matching comics.writer_id

@person.comics_as_writer # => Array of comics where @person.id matches comics.writer_id
@person.comics_as_artist # => Array of comics where @person.id matches comics.artist_id

@person.comics # => Array of comics where @person.id matches comics.writer_id or comics.artist_id


text:
Q: delete, insert, and get() data from a Text widget in a class I am trying to run a script to have a button delete, insert, and potentially get() whatever data I need from a Text widget. Standard procedure tells me to just use the naming convention chosen for the widget
text = Text(tk),
text.delete('1.0', END)

but I'm using a class to embed text within a frame and then placing that frame on a notebook "tab". Using the class and staying with the format i've chosen, I'm having hard time getting python to register any naming convention for the widget to call/edit from a different class where I'm having the button execute the script.
import Tkinter as tk
from Tkinter import *
import ttk

class Text1(Frame):
    def __init__(self, master, width=0, height=0, **kwargs):
        self.width = width
        self.height = height

        Frame.__init__(self, master, width=self.width, height=self.height)
        self.text_widget = Text(self, **kwargs)
        self.text_widget.pack(expand=YES, fill=BOTH)

    def pack(self, *args, **kwargs):
        Frame.pack(self, *args, **kwargs)
        self.pack_propagate(False)
        self.grid(row=1, column=0)

    def grid(self, *args, **kwargs):
        Frame.grid(self, *args, **kwargs)
        self.grid_propagate(False)

rows = 0
while rows < 50:
    root.rowconfigure(rows, weight=1)
    root.columnconfigure(rows, weight=1)

rows +=1

nb = ttk.Notebook(root)
nb.grid(row=1, column=0, columnspan=50, rowspan=49, sticky='NESW')
style = ttk.Style()
current_theme =style.theme_use()
style.theme_settings(current_theme, {"TNotebook.Tab": {"configure": {"padding": [20, 5]}}})

page1 = ttk.Frame(nb)
nb.add(page1, text='SS')

Text1(page1, width=470,height=400).pack()


text:
Q: How to set event time slot in custom calendar day view? I am developing an app with custom calendar.It includes day view with list of events of that day.I am getting the array of events with overlapped time slots.
Now how can I display the events with proper block adjustment?
I can find the overlapped events group,But not able to set the block adjustment.
Ex:- I have below events
1)From 8:00 To 12:00 event A
2)From 8:00 To 9:00 event B
3)From 9:00 To 10:00 event C
4)From 10:00 To 11:00 event D
5)From 11:00 To 12:00 event E
should be display like below picture.
This is only one type of case,I have many other type of combination.
To draw the Rect I used below method.
*- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
CGContextRef context = UIGraphicsGetCurrentContext();

CGContextSetRGBFillColor(context, 244.0/255.0, 244.0/255.0, 244.0/255.0, 1.0);

for (int i=0; i<arrayRects.count; i++)
{
    if ([[arrayRects objectAtIndex:i] isKindOfClass:[NSMutableArray class]])
    {
        NSMutableArray *confictArray =(NSMutableArray*)[arrayRects objectAtIndex:i];

        for (int j=0; j<confictArray.count; j++)
        {
            NSString *strRect = [confictArray objectAtIndex:j];
            CGRect newRect = CGRectFromString(strRect);
            newRect.size.height -=1.5;
            CGContextFillRect(context, newRect);

            //Draw Line on Left
            {
                if(i==0) {
                    CGContextSetRGBStrokeColor(context, 0.0, 1.0, 0.0, 1.0); // green line
                } else if(i==1) {
                    CGContextSetRGBStrokeColor(context, 1.0, 0.0, 0.0, 1.0); // red line
                } else {
                    CGContextSetRGBStrokeColor(context, 0.0, 0.0, 1.0, 1.0); // blue line
                }

                CGContextBeginPath(context);

                CGContextMoveToPoint(context, newRect.origin.x , newRect.origin.y + 0.5); //start point
                CGContextAddLineToPoint(context, newRect.origin.x ,newRect.origin.y + newRect.size.height - 0.5); // end path

                CGContextClosePath(context); // close path

                CGContextSetLineWidth(context, 5.0); // this is set from now on until you explicitly change it
                CGContextStrokePath(context); //
            }
        }
    }
    else {

        NSString *strRect = [arrayRects objectAtIndex:i];
        CGRect newRect = CGRectFromString(strRect);
        newRect.size.height -=1.5;
        CGContextFillRect(context, newRect);

        //Draw Line on Left
        {
            if(i==0) {
                CGContextSetRGBStrokeColor(context, 0.0, 1.0, 0.0, 1.0); // green line
            } else if(i==1) {
                CGContextSetRGBStrokeColor(context, 1.0, 0.0, 0.0, 1.0); // red line
            } else {
                CGContextSetRGBStrokeColor(context, 0.0, 0.0, 1.0, 1.0); // blue line
            }

            CGContextBeginPath(context);

            CGContextMoveToPoint(context, newRect.origin.x , newRect.origin.y + 0.5); //start point
            CGContextAddLineToPoint(context, newRect.origin.x ,newRect.origin.y + newRect.size.height - 0.5); // end path

            CGContextClosePath(context); // close path

            CGContextSetLineWidth(context, 5.0); // this is set from now on until you explicitly change it
            CGContextStrokePath(context); //
        }
    }
}*


text:
Q: Oracle DBMS_LOB.WRITEAPPEND to Postgres Conversion Can someone please let me know how to convert the below Oracle Code to Postgresql
IF prodNum = 1 THEN
          DBMS_LOB.WRITEAPPEND(pkgFilterNode, LENGTH(pkgFilter_tab || '<PackageFilters isNewFormat="Y" > '||l_crlf), pkgFilter_tab || '<PackageFilters isNewFormat="Y" > '||l_crlf);
END IF;

Appreciate your time!

A: It depends on a size of your large object. When your large objects are less about 500MB, then you don't need to use LOBs (PostgreSQL uses term LO), and you can use a text or varchar type - the work is similar like with varchar. After this size you should to use LO API.
CREATE OR REPLACE FUNCTION writeappend(oid, text)
RETURNS void AS $$
DECLARE
  content bytea;
  fd int;
BEGIN
  content := convert_to($2, getdatabaseencoding());
  fd := lo_open($1, 131072);
  PERFORM lo_lseek(fd, 0, 2);
  IF length(content) <> lowrite(fd, content) THEN
    RAISE EXCEPTION 'not all content was written';
  END IF;
  PERFORM lo_close(fd);
END;
$$ LANGUAGE plpgsql;

postgres=> select lo_creat(-1);
┌──────────┐
│ lo_creat │
╞══════════╡
│    20653 │
└──────────┘
(1 row)

postgres=> select writeappend(20653, e'Hello\r\n');
┌─────────────┐
│ writeappend │
╞═════════════╡
│             │
└─────────────┘
(1 row)

postgres=> select writeappend(20653, e'Hello\r\n');
...

postgres=> select convert_from(lo_get(20653),getdatabaseencoding());
┌──────────────┐
│ convert_from │
╞══════════════╡
│ Hello\r     ↵│
│ Hello\r     ↵│
│              │
└──────────────┘
(1 row)

So you can use LO API, but basic types should be preferred. The limits for these types is usually good enough - and work with basic types are much more comfortable - with some possibilities like fulltext.


text:
Q: Roboguice: using manual injections causes ConfigurationException (no implementation was bound) I've found an issue with Roboguice when using manual instance resolution. It works once I turn off the Annotation Database. Otherwise I get the exception:
No implementation for com.kmsoftware.roboguicetest.SomeInterface was bound.

Am I doing something wrong or is it just a Robolectric/Roboblender bug?
The code looks like this:
MainActivity.java
public class MainActivity extends RoboActionBarActivity {

//    static {
//        RoboGuice.setUseAnnotationDatabases(false);
//    }

    @Inject
    FragmentManager fragmentManager;

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

        TextView tv = (TextView) findViewById(R.id.activityMainLabel);

        SomeInterface instance = RoboGuice.getInjector(this).getInstance(SomeInterface.class);

        tv.setText(String.valueOf(instance.getValue()));
    }

    ...
}

RoboModule.java
public class RoboModule extends AbstractModule {
    @Override
    protected void configure() {

        bind(SomeInterface.class).to(ConcreteClass.class);
    }
}

SomeInterface.java
public interface SomeInterface {
    int getValue();
}

ConcreteClass.java
public class ConcreteClass implements SomeInterface {
    @Override
    public int getValue() {
        return 7;
    }
}


text:
Q: Reading a continous hex file in verilog I have a continuous hex file such as 0000 ffff 0000 ffff acac 0000 ffff 000
and I need to assign the value read to tb_b = data[15:8]
tb_a = data[7:0]
Code:
initial
  begin
    while(cond) begin
      $readmemh("test.txt",f_data,0, 2**32);
      tb_b = data[15:8];
      tb_a = data[7:0];
...
end

Can someone please let me know how I can accomplish this.
Many thanks

A: Use $fscanf instead.
int file, status;

initial
  begin
    file = $fopen("test.txt","r");
    if (file == 0) $error("text.txt not opened");
    while(cond) begin
      status = $fscanf(file,"%h",data);
      tb_b = data[15:8];
      tb_a = data[7:0];
...
end


text:
Q: Book from circa 1983 about a man who can teleport into different copy bodies of himself The story centers around a man who can teleport into different copy bodies of himself. I believe much of the book takes place on Mars but they also visit Mercury and I believe the moon. One of the things that stood out was instead of using spacesuits they took pills called goofballs that supplied them with air.

A:
The Sirens of Titan, a novel by Kurt Vonnegut, Jr.; first published in 1959, reprinted in many editions.
From the Wikipedia summary:

Malachi Constant is the richest man in a future America. He possesses extraordinary luck that he attributes to divine favor which he has used to build upon his father's fortune. He becomes the centerpoint of a journey that takes him from Earth to Mars in preparation for an interplanetary war, to Mercury with another Martian survivor of that war, back to Earth to be pilloried as a sign of Man's displeasure with his arrogance, and finally to Titan where he again meets the man ostensibly responsible for the turn of events that have befallen him, Winston Niles Rumfoord.
Rumfoord comes from a wealthy New England background. His private fortune was large enough to fund the construction of a personal spacecraft, and he became a space explorer. Traveling between Earth and Mars, his ship—carrying Rumfoord and his dog, Kazak—entered a phenomenon known as a chrono-synclastic infundibulum, which is defined in the novel as "those places ... where all the different kinds of truths fit together." When they enter the infundibulum, Rumfoord and Kazak become "wave phenomena", somewhat akin to the probability waves encountered in quantum mechanics. They exist along a spiral stretching from the Sun to the star Betelgeuse. When a planet, such as the Earth, intersects their spiral, Rumfoord and Kazak materialize, temporarily, on that planet.

The story centers around a man who can teleport into different copy bodies of himself.
Winston Niles Rumfoord is not the central character but the next most important character in the book; he does not exactly teleport but he's in a weird condition which causes him to materialize in different places.
I believe much of the book takes place on Mars but they also visit Mercury and I believe the moon.
Parts of the book are set on Earth, on Mars, on Mercury, and on Saturn's moon Titan.
One of the things that stood out was instead of using spacesuits they took pills called goofballs that supplied them with air.
That's what clinched the identification. Excerpt, with emphasis added:

Unk's mate, the mother of young Chrono, `was in instructress in the Schliemann Breathing School for Recruits. Schliemann breathing, of course, is a technique that enables human beings to survive in a vacuum or in an inhospitable atmosphere without the use of helmets or other respiratory gear.
It consists, essentially, of taking a pill rich in oxygen. The bloodstream takes on this oxygen through the wall of the small intestine rather than through the lungs. On Mars, the pills were known officially as Combat Respiratory Rations, in popular parlance as goofballs.
Schliemann Breathing is at its simplest in a benign but useless atmosphere like that of Mars. The breather goes on breathing and talking in a normal manner, though there is no oxygen for his lungs to take in from the atmosphere. All he has to remember is to take his goofballs regularly.
The school in which Unk's mate was an instructor taught recruits the more difficult techniques necessary in a vacuum or in a harmful atmosphere. This involves not only pill-taking, but plugging one's ears and nostrils, and keeping one's mouth shut as well. Any effort to speak or to breathe would result in hemorrhages and probably death.


text:
Q: Заменить в файле все первые буквы в словах на заглавные буквы //---------------------------------------------------------------------------

#pragma hdrstop

//---------------------------------------------------------------------------
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<iostream>
#include <locale>
#include<cctype>
#include<cstring>
#include<string>
#include<vcl.h>
#pragma argsused
int main(int argc, char* argv[])
{
char help[100];
int n;
setlocale(LC_ALL, "russian_russian");
FILE *f1, *f2;
printf("Input file name\n");
gets(help);
f1 = fopen(help, "rt");
if ((!f1)) {
printf("File not found!");
}
else
{
    f2 = fopen("File2.txt", "wt");
{
    while (fgets(help,99,f1))
{
    help[n] = toupper(help[n]);
    fprintf(f2, "%s", help);
}
}
getch();
return 0;
}
}
//---------------------------------------------------------------------------

В первом файле у меня, допустим, есть строка "иван иванов", нужно, чтобы эта строка записалась во второй файл и при этом выглядела бы так: "Иван Иванов". Но проблема в том, что строка записывается во второй файл без изменений, то есть как было "иван иванов", так и осталось.
То есть нужно, чтобы заменились в файле все первые буквы в словах на заглавные буквы. Как это реализовать?
A: Надо:

*

*
Пройти по всем символам строки от начала до конца.

*
Определить, является ли текущий символ первым в слове - он либо первый в строке, либо стоит после пробела, перевода строки и т.п.).

*
Если да, то перевести в верхний регистр (как в той строчке).
Поэтому нам нужен каждый i-й символ, который удовлетворяет условию п.2, его мы попробуем перевести в верхний регистр. Для упрощения предположим, что слова в строке разделяются только пробелами, знаков препинания и др. символов, кроме букв, нет. Тогда это условие может иметь вид:
if (i == 0 || help[i-1] == ' ')
    help[i] = toupper(help[i]);

т.е. если i=0, то help[i] первый символ строки, если help[i-1] == ' ', то текущему символу help[i] предшествует пробел. Только в этих случаях мы пытаемся его преобразовать.
Остается немного подпилить: поместить этот фрагмент в цикл со счетчиком i, чтобы пройти по всем символам от первого (i=0) до конца строки.
A: for(int n = 0; n<strlen(help); n++)
{
if((help[n-1]==' ') || (( n==0 ))
help[n] = toupper(help[n]);
}

Всё исправно работает!Если в первый файл ввести строку "иван иванов",то во втором файле выведется "Иван Иванов".


text:
Q: Can not get cookies in ReactJS with ViteJs I have a get request to Nest JS backend. Making the request using CRA then the cookies are set in my browser, but trying to make the request using React Js that was generated using ViteJs, then i don't get any cookies in my browser.  Question: Why i can not get cookies using Vite and React but with CRA works? Do the cookies work only with localhost as CRA works, because VITE url is something like http://127.0.0.1:5173/ but not localhost as in CRA?

A: Setting the DNS default result order to verbatim will replace the ip address with localhost which should allow your cookies to be set.
When setting cookies the url you are sending the request from and the cross-origin url need to be the same. This happens with vite due to it having a different start address, but does not happen with CRA.
This is my code for my vite config file:
    import { defineConfig} from "vite";
    import react from "@vitejs/plugin-react";
    import dns from 'dns'

    dns.setDefaultResultOrder('verbatim')

    // https://vitejs.dev/config/
    export default defineConfig({
        plugins: [react()],
        server: {
            host: "localhost",
            port: "3002",
        },
    });


text:
Q: How to solder a stranded wire to a THT hole of a PCB as shock-resistant as possible I'd like to solder several stranded wires of a cable (maximum 18 VDC) to a PCB. I've got corresponding THT holes (⌀ 0.8 mm; it's the eight holes underneath the yellow wire,) but the wire is thicker (⌀ 1.1 mm.) What makes my issue more complicated is that the board is to be part of an automotive electronics solution which must withstand slight shocks. See the picture below:

What is a good method to solder these wires durably to the PCB?
UPDATE: Here is a close-up of the eight soldering holes (J9) in question. The PCB is very cramped as J9 is situated between the amplifier in front and the resistors and caps behind it:

A: Mount an appropriate connector block to the same substrate the PCB is mounted to. Use this to transition from the oversized wires to smaller wires suitable for connection to the PCB and to provide strain relief.

A: Soldering a stranded wire makes the soldered part much less flexible and so bending tends to concentrate on the part of the wire immediately at the end of the solder, causing fatigue and failure.  For this reason, crimp or screw terminals are preferred where vibration is likely to be a problem.  If you have to solder the wires then it would be wise to immobilise them a short distance from the end, perhaps with a cable tie or clamp.  If you're going to use an adhesive or potting compound then it needs to be stiffer than the wire in order to be effective, so epoxy is better than silicone.

A: You can leverage unused through holes for lacing wire/string.  You can lace wire through the holes and pull the cables down against the board for strain relief.  Then the cable/lacing combo should be potted against the PCB with epoxy.  I have personally used this method in applications tested to 26G.
If you cannot use epoxy, you can try just the lacing itself.
These are all sub-optimal solutions, but if you're in a pinch they are viable temporary workarounds.

A: If the pcb is an automotive electronics solution, it should not only withstand slight shocks, it should also withstand vibrations and some harder shocks.
So you should use only those connectors designed for such cables and don't solder the cable at all. There are additional strain-relief parts for those connectors and cables.

A: A good way (but a bit late now...) is to have two holes for each wire, perhaps a half-inch apart - one large enough to pass the insulated wire, and the second of suitable size to pass the actual conductor and provide the electrical connection.
The larger hole for the insulated wire provides a strain relief and prevents or reduces movement of the actual wire connection.

A: Wire to board solder connections are not ideal for a high vibration environment. Even with good strain relief the solder joint may eventually fail due to cyclical stress. As others have said it would be best to add a connector or terminals of some kind.
However, soldering the wire might work ok ..but make sure they have excellent strain relief. The solder joint needs to be put under as little stress as possible. Be especially careful about repetitive stress, as even a small amount will cause a failure after some time.
If there's too much slack in the wires between the strain relief and the solder connections, the vibration of the wires will cause stress. If there's too little slack the assembly process or flexture of the enclosure and mounting points may tug on the wires, which would also be very bad. You can see how this arrangement is touchy.

A: If the wires are stranded, you can strip and remove some of the strands to make it fit within the PTH. If it is solid core wire or you dont want to reduce the capacity, find a pin that fits in the PTH (plated through hole) then wrap and solder your wire onto it. To make it shock resistant the wires need to be staked (glued down to the board for strain relief) that way there is no stress on your solder joint.


text:
Q: How to remove duplicate record from results doing left join in sql I have three tables User, Enquiry and Activity. When I do an INNER and LEFT JOIN, I am getting duplicate records because of NULL values.
User:
User_id | user_firstName | user_lastName
--------+----------------+--------------
1       | Joe            | Smith
2       | John           | Doe
3       | Robert         | Smith

Enquiry:
EnquiryID  | CreatedBy|
-----------+------------
1          |     1
2          |     1

Activity:
ActivityID | CreatedBy| AssignedBy| AssignedTO
-----------+----------+-----------+-----------
1          |     1    |    null   |  null
2          |     1    |      2    |   3

Expected output of all three combining result is
Enquiry ID |  CreatedBy | AssignedBy | AssignedTO
-----------+------------+------------+------------
1          |     Joe    |    null    |  null
2          |     Joe    |      John  |   Rober

SQL statement:
SELECT DISTINCT
    E.EnquirdID AS Enquiry,
    U.FirstName AS CreatedBy,
    U1.FirstName AS AssignedBy,
    U2.FirstName AS AssignedTo
FROM
    Enquiry E
INNER JOIN
    User U ON E.UserID = U.UserID
INNER JOIN
    Activity A ON E.Enquiry = A.EnquiryID
LEFT JOIN
    User U1 ON A.AssignedBy = U1.UserID
LEFT JOIN
    User U2 ON A.AssignedTo = U2.UserID

I am getting duplicate Enquiry records from this query, even though I'm using DISTINCT for EnquiryID
END RESULT: my plan is to use the SQL to select the data and display it in PHP on a website. It's an enquiry management website. I want to be able to have PHP pull the variables from SQL so I can use them however I feel fit.

A: The query seems to work as expected. I just fixed some syntax and column names:
SELECT DISTINCT E.EnquiryID as Enquiry, U.user_FirstName as CreatedBY ,U1.user_FirstName as AssignedBY  , U2.user_FirstName as AssignedTO
FROM Enquiry E inner join [User] U on E.createdby = U.User_ID
               inner join Activity A on E.EnquiryID = A.createdby
               Left Join [User] U1  on A.AssignedBY = U1.User_ID
               Left Join [User] U2 on  A.AssignedTO = U2.User_ID


text:
Q: Chat application where the client side is the listener rather than the webserver I am trying to make a simple chat web application. The simple way is to make the webapp (flash/ajax) query the server every x seconds to find new messages.
Is there a way to make the web-app the listener so that the server will contact it whenever there are new messages to show on the client side? I've heard opinions that it is possible using flash.
Thanks

A: There are many different ways to achieve server initiated communication. Here you can read a good overview

A: Flash Sockets can be used to do what you describe:
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/Socket.html
This works as follows:
Flash opens a socket connection to the server. If the server has something to update it uses the connection to send data.Flash recives the data and fires an event (socketData) to tell your application that new data is available
If you use sockets it's Flash starting the connection, not the server, for that reason NAT is not an issue, but firewalls blocking those connections can be.


text:
Q: Opening UIView programmatically iOS I want to open a window every time a if state is correct.
The thing is that the code works if i use it on a button but not on load. The error
code says that the view is not int the window hierarchy.
    info *vs = [self.storyboard instantiateViewControllerWithIdentifier:@"run"];
   [self presentViewController:vs animated:YES completion:nil];

A: I made a non repeatable timer to load a function that opens the other view. Its a bit strange but it gets the job done.


text:
Q: I'm new at C++ and I'm doing a shell, I did an echo command but the text get cut if it has 2 or more args So I'm doing a shell in c++, I'm a noobie here.
My code is the following:
#include <iostream>

using namespace std;

int main()
{
    string action;
    bool run = true;
    while (run == true) {
        cout << "shell > ";
        cin >> action;
        if (action == "help" || action == "Help") {
            cout << "Here is a list of commands: \n";
            cout << "help - displays a list of useful commands.\n";

        }else if (action == "echo" || action == "Echo") {
            string echo_c;
            cout << "What to display? ";
            cin >> echo_c;
            cout << echo_c << "\n";
        }

    }
}

It prompts me the action and I say "echo", it asks me what to display and I say "Hello world".
Output:
shell > echo
What to display? Hello World
Hello
shell > shell >

It repeats "shell > " and cuts the "world" from "Hello world".
Someone help me plese.


text:
Q: Filewatcher is consuming most of PC resource I am developing an application which tracks directory related changes on available drives of PC and save those changes in the sqlite DB. Everything in the below code is working fine as expected. But when I tested it by copying approx 100 directory and their nested directories together, it freeze the application and also freeze copy process of Windows OS.
I am not getting the way how to manage it because this code for bulk file copying is consuming most of the PC resource. Is there any why I can optimize it? rather setting "IncludeSubDirectories = False"?
class DirWatcher
{
    private FileSystemWatcher dirWatcher = null;

    public void StartCapture()
    {
        string[] drives = Environment.GetLogicalDrives();

        foreach (string drive in drives)
        {
            DriveInfo driveInfo = new DriveInfo(drive);
            if (driveInfo.DriveType == DriveType.Fixed)
            {
                //Director Watcher
                dirWatcher = new FileSystemWatcher(drive);
                dirWatcher.NotifyFilter = NotifyFilters.DirectoryName;

                dirWatcher.Created += dirWatcher_Created;
                dirWatcher.Deleted += dirWatcher_Created;
                dirWatcher.Renamed += dirWatcher_Renamed;

                dirWatcher.IncludeSubdirectories = true;
                dirWatcher.EnableRaisingEvents = true;

            }
        }
    }

    void dirWatcher_Renamed(object sender, RenamedEventArgs e)
    {
        try
        {
            Task.Factory.StartNew(() =>
                        {
                            saveToDB("Folder",
                                     e.ChangeType.ToString(),
                                     e.FullPath,
                                     Utility.UnixDTstamp(DateTime.Now).ToString(),
                                     Environment.UserName);

                        });
        }
        finally
        {
            dirWatcher.Renamed -= dirWatcher_Renamed;
        }
    }

    void dirWatcher_Created(object sender, FileSystemEventArgs e)
    {
        try
        {
            Task.Factory.StartNew(() =>
            {
                saveToDB("Folder",
                        e.ChangeType.ToString(),
                        e.FullPath,
                        Utility.UnixDTstamp(DateTime.Now).ToString(),
                        Environment.UserName);
            });
        }
        finally
        {
            dirWatcher.Created -= dirWatcher_Created;
        }
    }

    public void StopCapture()
    {
        dirWatcher.IncludeSubdirectories = false;
        dirWatcher.EnableRaisingEvents = false;
        dirWatcher.Dispose();
    }

    public void saveToDB(string DirOrFile, string action, string path, string time, string userName)
    {
        //SavetoDB code will be here.
    }
}
}

A: One thing that may be slowing down ( or even defeating) your program are attached drives on the network. I don't believe that you can successfully set a Filewatcher on these, especially if the drivers are LINUX based. And even if you could, it would be glacial in performance
I have also found Filewatcher to miss events when watching folder hierarchies. So in general, I'd say that you need to find or write a replacement for this functionality that is so flawed it should be deprecated. Perhaps a hook that lets you watch the windows message loop?


text:
Q: Exception arose when storing the arraylist into the array I need to create pie chart using chartengine for my app, there I need to draw pie-chart for categories and their expenses.I need to get the categories inside pie chart, so I took categories into an arraylist from database and then I put them into an array.
Now it's giving exception.

10-29 21:41:22.720      878-878/com.example.username.weddingplanning
  E/AndroidRuntime﹕ FATAL EXCEPTION: main
      java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.username.weddingplanning/com.example.username.weddingplanning.pie}:
  java.lang.ArrayStoreException: source[0] of type
  com.example.username.weddingplanning.category cannot be stored in
  destination array of type java.lang.String[]
              at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2250)
              at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2304)
              at android.app.ActivityThread.access$700(ActivityThread.java:152)
              at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1284)
              at android.os.Handler.dispatchMessage(Handler.java:99)
              at android.os.Looper.loop(Looper.java:176)
              at android.app.ActivityThread.main(ActivityThread.java:5299)
              at java.lang.reflect.Method.invokeNative(Native Method)
              at java.lang.reflect.Method.invoke(Method.java:511)
              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
              at dalvik.system.NativeStart.main(Native Method)
       Caused by: java.lang.ArrayStoreException: source[0] of type com.example.username.weddingplanning.category cannot be stored in
  destination array of type java.lang.String[]
              at java.lang.System.arraycopy(Native Method)
              at java.util.ArrayList.toArray(ArrayList.java:519)
              at com.example.username.weddingplanning.pie.onCreate(pie.java:33)
              at android.app.Activity.performCreate(Activity.java:5326)
              at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1097)
              at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2213)
              at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2304)
              at android.app.ActivityThread.access$700(ActivityThread.java:152)
              at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1284)
              at android.os.Handler.dispatchMessage(Handler.java:99)
              at android.os.Looper.loop(Looper.java:176)
              at android.app.ActivityThread.main(ActivityThread.java:5299)
              at java.lang.reflect.Method.invokeNative(Native Method)
              at java.lang.reflect.Method.invoke(Method.java:511)
              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
              at dalvik.system.NativeStart.main(Native Method)

This is my DBhelper class
public class DBhelper extends SQLiteOpenHelper {

    static final String DATABASE = "wedding9.db";
    static final int VERSION = 9;
    static final String TABLE1 = "Category";
    static final String TABLE2 = "Budget";
    static final String TABLE3 = "Expenses";

    static final String C_ID = "_id";
    static final String Name = "name";
    static final String B_ID = "_id";
    static final String Description = "description";
    static final String Amount = "amount";

    public static final String ID1 = "_id";
    public static final String DATE_T1 = "date1";
    public static final String CATEGORY = "category";
    public static final String DETAIL = "detail";
    public static final String AMOUNT1 = "amount1";
    public static final String STATUS = "status";
    public static final String EX_YEAR = "exyear";
    public static final String EX_MONTH = "exmonth";

    public DBhelper(Context context) {
        super(context, DATABASE, null, VERSION);
    }

    public void onCreate(SQLiteDatabase db) {

        db.execSQL("CREATE TABLE " + TABLE1 + "(" + C_ID
                + " INTEGER PRIMARY KEY AUTOINCREMENT," + Name + " text unique not null)");

        db.execSQL("CREATE TABLE " + TABLE2 + "(" + B_ID
                + " INTEGER PRIMARY KEY AUTOINCREMENT," + Description + " text,"
                + Amount + " text, FOREIGN KEY (" + Description + ") REFERENCES " + TABLE1 + "(" + Name + "));");

        db.execSQL("CREATE TABLE " + TABLE3 + " ( "
                + ID1 + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                + DATE_T1 + " text, "
                + CATEGORY + " text, "
                + DETAIL + " text, "
                + STATUS + " text, "
                + EX_YEAR + " text, "
                + EX_MONTH + " text, "
                + AMOUNT1 + " text, FOREIGN KEY (" + CATEGORY + ") REFERENCES " + TABLE1 + "(" + Name + "));");

    }

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        db.execSQL("drop table " + TABLE1);
        onCreate(db);
    }

    public ArrayList<category> getCategories() {
        ArrayList<category> arrayList = new ArrayList<category>();
        SQLiteDatabase db = getReadableDatabase();
        Cursor c = db.query(DBhelper.TABLE1, null, null, null, null, null, null);
        while (c.moveToNext()) {
            category cat = new category(c.getInt(0), c.getString(1));
            arrayList.add(cat);

        }

        return arrayList;
    }

    public boolean checkIdExist(String name) {
        SQLiteDatabase db = getReadableDatabase();
        Cursor c = db.query(DBhelper.TABLE1, null, null, null, null, null, null);
        while (c.moveToNext()) {
            if (c.getString(1).equals(name))
                return false;
        }

        return true;
    }

    public double getTotalbudget() {
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "SELECT SUM(Amount) FROM " + TABLE2;

        Cursor c = db.rawQuery(query, null);
        //Add in the movetofirst etc here? see SO
        c.moveToFirst();
        double i = 0;
        i = c.getDouble(0);

        return i;
    }

    public double getTotalexpenses() {
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "SELECT SUM(AMOUNT1) FROM " + TABLE3;

        Cursor c = db.rawQuery(query, null);
        c.moveToFirst();
        double e = 0;
        e = c.getDouble(0);

        return e;
    }

    public boolean checkBudget(String cat) {
        SQLiteDatabase db = this.getReadableDatabase();
        String query = "SELECT e.category " +
                "FROM expenses e, budget b " +
                "WHERE e.category=b.description and e.category='" + cat +
                "' GROUP BY e.category " +
                "HAVING sum(amount1)>b.amount";

//        ArrayList<String> results = new ArrayList<String>();
        Cursor c = db.rawQuery(query, null);
        if (c.moveToNext()) {
            return true;
            //results.add(c.getString(0));
        }

        return false;
    }

    //get the category expenses
    public ArrayList<Expence> getCategoryExpences(String category) {
        ArrayList<Expence> expences = new ArrayList<Expence>();

        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int tmonth = c.get(Calendar.MONTH);
        int month = tmonth + 1;

        String query = "SELECT * FROM " + TABLE3 + " WHERE " + EX_YEAR + "='" + year + "' and " + EX_MONTH + "='" + month + "' and " + CATEGORY + "='" + category + "'";

        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.rawQuery(query, null);
        if (cursor.moveToFirst()) {
            do {
                Expence ex = new Expence();
                ex.setCategory(category);
                ex.setDate(cursor.getString(1));
                ex.setDescription(cursor.getString(3));
                ex.setStatus(cursor.getString(4));
                ex.setYear(cursor.getString(5));
                ex.setMonth(cursor.getString(6));
                ex.setAmount(cursor.getString(7));
                expences.add(ex);
            }
            while (cursor.moveToNext());
        } else {
            return null;
        }
        return expences;
    }

}

This is my pie chart class
public class pie extends ActionBarActivity {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pie);

        // Pie Chart Section Names

        ArrayList<category> bud = new DBhelper(this).getCategories();
        String[] code = bud.toArray(new String[bud.size()]);
        // Pie Chart Section Value
        double[] distribution = new double[code.length];
        for (int i=0; i<distribution.length; i++) {
            System.out.println(i);
            ArrayList<Expence> expences = new DBhelper(this).getCategoryExpences(code[i]);
            if(expences!=null){
                double total = 0.0;
                for (Expence ex : expences) {
                    total = total + Double.parseDouble(ex.getAmount());
                }
                distribution[i]=total;
            }
            else{
                distribution[i]=0.0;
            }
        }

        // Color of each Pie Chart Sections
        int[] colors = { Color.BLUE, Color.MAGENTA, Color.GREEN, Color.CYAN,Color.YELLOW,
                Color.RED };

        // Instantiating CategorySeries to plot Pie Chart
        CategorySeries distributionSeries = new CategorySeries("Expenses Graph");
        for (int i = 0; i < distribution.length; i++) {
            // Adding a slice with its values and name to the Pie Chart
            distributionSeries.add(code[i], distribution[i]);
        }

        // Instantiating a renderer for the Pie Chart
        DefaultRenderer defaultRenderer = new DefaultRenderer();
        for (int i = 0; i < distribution.length; i++) {
            SimpleSeriesRenderer seriesRenderer = new SimpleSeriesRenderer();
            seriesRenderer.setColor(colors[i]);
            seriesRenderer.setDisplayChartValues(true);
            // Adding a renderer for a slice
            defaultRenderer.addSeriesRenderer(seriesRenderer);
        }

        defaultRenderer.setChartTitle("Expenses Graph");
        defaultRenderer.setChartTitleTextSize(60);
        defaultRenderer.setLabelsTextSize(30);
        defaultRenderer.setLegendTextSize(30);
        defaultRenderer.setShowLegend(true);
        //defaultRenderer.setDisplayValues(true);
        defaultRenderer.setApplyBackgroundColor(true);
        defaultRenderer.setBackgroundColor(Color.BLACK);
        defaultRenderer.setLabelsColor(Color.WHITE);
        defaultRenderer.setZoomButtonsVisible(true);

        // Creating an intent to plot bar chart using dataset and multipleRenderer
        Intent intent = ChartFactory.getPieChartIntent(getBaseContext(), distributionSeries, defaultRenderer, "AChartEnginePieChartDemo");

        // Start Activity
        startActivity(intent);
    }

    }

A: You are retrieving the list of Category object instances, but your array called code, declared as the array of String objects. The exception you get, is about the fact, that you are trying to strore Category objects in the array of strings.
Suppose, that Code is one of the fields of the Category and you've provided getter method for it, in this case you need no itarate the categories and get it's codes, adding them into the array, like:
String[] code = new String[bud.size()];
for (int i = 0; i < bud.size(); i++) {
    code[i] = bud.get(i).getCode();
}


text:
Q: How to detect if a printer is conected with pyqt? I'm programming in Linux a windows application. In this moment I need a solution to detect if the default printer is connected.
I have the next code:
def mPrint(self, value):
    font = QFont()
    font.setPointSize(10)

    self.mEditor = QTextEdit()
    self.mEditor.setFont(font)

    self.printer = QPrinter(QPrinterInfo.defaultPrinter())
    self.printer.setColorMode(QPrinter.GrayScale)
    self.printer.setPageMargins(7, 20, 7, 7, QPrinter.Millimeter)
    self.printer.setOrientation(QPrinter.Portrait)

    try:
        if value == 1:
            self.printCommand()
        else:
            self.printDelivery()
    except self.printer.Error as e:
        print(e)

with QPrinterInfo I can get the default printer and know if it exists.
QPrinterInfo.defaultPrinter().isNull()

but it always returns true, because I have a default printer in my PC but if it is not connected, everything goes to the printer queue.
Does anyone knows how to recognize if the printer is connected and how to show a Qmessage if there is an exception?

A: I find a solution:
 self.mEditor = QTextEdit()
 self.mEditor.setFont(font)

 self.printer = QPrinter(QPrinterInfo.defaultPrinter())
 self.mEditor.document().print_(self.printer)


text:
Q: How to solve modulo equations I was hoping someone would help me on how to solve the following modulo equations (they are from an exercise book in my course which unfortunately is without conclusion):
(1) $x^{2018}=1 \pmod {21}$
(2) $5x^{2107}=75 \pmod {205}$
For (1) I have started writing $(x^{2})^{1009}=1 \pmod {21}$ but then I did not know how to proceed since I still have x raised in a high number (prime number so can not be simplified more).
And for (2) I simplified to $x^{2107}=15 \pmod {205}$ but have the same problem here as above. Unfortunately I didn't find any similar equations online so I hope someone here would like to help me on how to solve these equations.

A: Use the totient function $\phi (n).$ For $n\in \Bbb N,$ the value of $\phi(n)$ is the number of members of $$G(n)=\{j\in \Bbb N: j\le n\land gcd(j,n)=1\}.$$ If $m,n\in\Bbb N$ and $gcd(m,n)=1$ then $\phi(mn)=\phi(m)\phi(n).$ If $p$ is prime and $n\in \Bbb N$ then $\phi(p^n)=p^{n-1}(p-1).$
Multiplication mod $n$ on the set $G(n)$ is a $group$ with $\phi(n)$ members, so for every $j\in G(n)$ we have $j^{\phi(n)}\equiv 1\mod n.$ (LaGrange's Theorem on finite groups.)
If $0\ne x\in\Bbb Z$ and if $gcd(x,n)=1$ then $x\equiv j \mod n$ for some $j\in G(n)$ so $x^{\phi(n)}\equiv j^{\phi(n)}\equiv 1 \mod n.$
$(1)$. We have $\phi(21)=\phi(3)\phi(7)=2\cdot 6=12.$ If $x^{2018}\equiv 1\pmod {21}$ then $x\ne 0$ and $gcd(x,21)=1$ so $x^{12}\equiv 1 \pmod {21}.$ Hence $$1\equiv x^{2018}\equiv (x^{12})^{168}\cdot x^2\equiv x^2\pmod {21}.$$ So $(3)(7)|(x^2-1)=(x-1)(x+1).$ So $x\equiv \pm 1\pmod 3$ and $x\equiv\pm 1\pmod 7.$ So  $x\equiv y \pmod {21}$ for some (any) $y\in \{1,8,13,20\}.$
$(2)$. We have $5x^{2107}\equiv 75 \pmod {205}\iff$ $ (5)(41)=205|(5x^{2107}-75)\iff$ $ 41|(x^{2107}-15).$ We have $\phi(41)=40$ and we have $2107=(40)(52)+27.$ So $$5x^{2107}\equiv 75 \pmod {205} \implies x^{2107}\equiv 15 \pmod {41}\implies$$ $$\implies x^{27}\equiv 15 \pmod {41}\implies$$ $$\implies x\equiv (x^{40})^2\cdot x\equiv (x^{  27})^3\equiv 15^3\equiv 13\pmod {41}.$$ Note we chose to "cube it" because $(27)(3)$ is $1$ more than a multiple of $\phi(41).$
Footnote: In Number Theory, a function $f$ with domain $\Bbb N$ is called "multiplicative" if $f(m)f(n)=f(mn)$ whenever $gcd(m,n)=1.$ It does NOT mean that $f(m)f(n)$ must be $f(mn)$ for $all$ $m,n.$

A: It will be helpful if you look at Chinese Remainder theorem and Fermat's Little theorem. My solution to the second question is actually quite difficult, and it requires some knowledge of quadratic residues.

For the first question, by Chinese Remainder theorem, $x^{2018}\equiv 1\mod 21$ iff
$$x^{2018}\equiv 1\bmod 3$$
$$x^{2018}\equiv 1\bmod 7$$
To solve the first congruence, first note that clearly $gcd(x,3)=1$. This means that we can apply Fermat's Little Theorem. We have
$$x^{2018}\equiv 1\bmod 3$$
$$\left(x^2\right)^{1009}\equiv 1\bmod 3$$
$$(1)^{1009}\equiv 1\bmod 3$$
Hence, the congruence is satisfied for all $x$ coprime to $3$, which means $x\equiv 1,2\mod 3$
To solve the second congruence, first note that clearly $gcd(x,7)=1$. This means that we can apply Fermat's Little Theorem. We have
$$x^{2018}\equiv 1\bmod 7$$
$$\left(x^6\right)^{336}x^2 \equiv 1\bmod 7$$
$$(1)^{336}x^2\equiv 1\bmod 7$$
$$x^2\equiv 1\bmod 7$$
$$x\equiv -1,1\bmod 7$$
So we have that $x$ must be congruent to $-1,1\bmod 7$ and $-1,1\bmod 3$. Using Chinese Remainder theorem, we can determine that there are $2^2$ solutions for $x$ in modulo $21$. Namely, (using brute force, or other methods) these are
$$x\equiv 20,1,8,13\bmod 21$$

For the second question, after dividing by $5$ (watch out since $5|205$), we have
$$x^{2107}\equiv 15\mod 41$$
To solve this congruence, first note that clearly $gcd(x,41)=1$. This means that we can apply Fermat's Little Theorem. We have
$$x^{2107}\equiv 15\bmod 41$$
$$\left(x^{40}\right)^{52}x^{27}\equiv 15\bmod 41$$
$$(1)^{52}x^{27}\equiv 15\bmod 41$$
$$x^{27}\equiv 15\bmod 41$$
Note that we have $15+41\cdot 8=343=7^3$. Let's substitute $u=x^9$.
$$u^3\equiv 15\bmod 41$$
$$u^3-343\equiv 0\bmod 41$$
$$(u-7)(u^2+7u+8)\equiv 0\bmod 41$$
Since the discriminant of $u^2+7u+8$ is $17$ and it's not hard to show with the law of quadratic reciprocity that using the legendre notation
$$\left(\frac{17}{41}\right)$$
$$=\left(\frac{41}{17}\right)$$
$$=\left(\frac{7}{17}\right)$$
$$=\left(\frac{17}{7}\right)$$
$$=\left(\frac{3}{7}\right)$$
$$=-\left(\frac{7}{3}\right)$$
$$=-1$$
Hence, $17$ is a nonquadratic residue of $41$, so we get that the only solution to $u$ is $u\equiv 7\bmod 41$. So we now have
$$x^9\equiv 7\bmod 41$$
Now substitute $v=x^3$, we want to find the solutions to
$$v^3\equiv 7\bmod 41$$
The solutions to this are not trivial like the previous equation. However, note that by Fermat's Little theorem, we have
$$7\equiv 7^{41}\equiv 7^{81}\equiv \left(7^{27}\right)^3\bmod 41$$
Hence, one of the solutions to
$$v^3\equiv 7\bmod 41$$
is $v\equiv 7^{27}\bmod 41$. Note that
$$7^{27}\bmod 41$$
$$\equiv 15^{9}\bmod 41$$
$$\equiv \left(15^2\cdot 15\right)^{3}\bmod 41$$
$$\equiv \left(20\cdot 15\right)^{3}\bmod 41$$
$$\equiv 13^3\bmod 41$$
$$\equiv 5\cdot 13\bmod 41$$
$$\equiv 24\bmod 41$$
Hence, we have the equation
$$v^3\equiv 7\bmod 41$$
$$v^3\equiv 24^3\bmod 41$$
$$(v-24)(v^2+24v+2)\equiv 0\bmod 41$$
Note that the discriminant of $v^2+24v+2$ is $568\equiv 35\bmod 41$.
Since $\left(\frac{35}{41}\right)=\left(\frac{5}{41}\right)\left(\frac{7}{41}\right)$, we can show using similar reasoning as before with the law of quadratic reciprocity that $\left(\frac{5}{41}\right)=1$ and $\left(\frac{7}{41}\right)=-1$.
Hence, $35$ is also a quadratic nonresidue, which means that the only solution to
$$v^3\equiv 7\bmod 41$$
is $v\equiv 35\bmod 41$
So we are now finally on the last lap with
$$x^3\equiv 35\bmod 41$$
This one also does not have any trivial solutions. However, as we showed before, we know that one of the solutions will be $x\equiv 35^{27}\bmod 41$. We have
$$35^{27}\bmod 41$$
$$7^9\bmod 41$$
$$15^3\bmod 41$$
$$13\bmod 41$$
Hence, we have
$$x^3\equiv 35\bmod 41$$
$$x^3\equiv 13^3\bmod 41$$
$$(x-13)(x^2+13x+5)\equiv 0\bmod 41$$
The discriminant of $x^2+13x+5$ is $149\equiv 26\bmod 41$
Since $\left(\frac{26}{41}\right)=\left(\frac{2}{41}\right)\left(\frac{13}{41}\right)$. It follows from the second supplement of the law of quadratic reciprocity that $\left(\frac{2}{41}\right)=-1^{\frac{41^2-1}{8}}=1$.
We can show using similar reasoning as before with the law of quadratic reciprocity that $\left(\frac{13}{41}\right)=-1$. Thus, the only solution to $x^3\equiv 35\bmod 41$ is $\boxed{x\equiv 13\bmod 41}$

A:
(1) $^{2018}=1 \pmod{21}$

Since $21 = 3 \cdot7$ is the prime decomposition of 21.
\begin{align}
x^{2018} \equiv 1 \pmod {21} \leftrightarrow x^{2018} \equiv 1\pmod {3}  \wedge x^{2018} \equiv 1 \pmod {7} \end{align}
First let's check which number satisfy $x^{2018} \equiv 1\pmod {3}$:
Obviously $x=0$ doesn't work, but $x=1$ does satisfy $x^{2018} \equiv 1\pmod {3}$. We then check for $x=2$:
\begin{align}
2^{2018} \equiv 4^{1009} \equiv 1^{1009} \equiv 1 \pmod {3}
\end{align}
So the condition $x^{2018} \equiv 1\pmod {3}$ is satisfied for all $x \in \mathbb{Z}$ such that $x \equiv \pm 1 \pmod {3}.$
Let's now check which $x$ satisfy this  first condition, and also satisfy the condition $x^{2018} \equiv 1 \pmod {7}$:
Obviously $x=1$ satisfies it. Now for $x=2$ we have:
\begin{align}
2^{2018} \equiv 4\cdot2^{2016} \equiv 4\cdot8^{672} \equiv 4\cdot1^{672} \equiv 4 \pmod {7}
\end{align}
which doesn't satisfy the condition. For $x = 3$ we have:
\begin{align}
3^{2018} \equiv 9^{1009} \equiv 2^{1009} \equiv 2\cdot2^{1008} \equiv 2\cdot8^{336} \equiv 2\cdot1^{336} \equiv 2 \pmod {7}
\end{align}
For $x = 4$ we have :
\begin{align}
4^{2018} \equiv 16^{1009} \equiv 2^{1009} \equiv 2\cdot2^{1008} \equiv 2\cdot8^{336} \equiv 2\cdot1^{336} \equiv 2 \pmod {7}
\end{align}
For $x=5$ we have :
\begin{align}
5^{2018} \equiv 25\cdot 5^{2016} \equiv 4 \cdot 125^{672} \equiv 4\cdot 1^{672} \equiv 4 \pmod {7}
\end{align}
For $x = 6$ we have :
\begin{align}
6^{2018} \equiv 36^{1009} \equiv 1^{1009} \equiv 1 \pmod{7}
\end{align}
which satisfies the condition.
we conclude that the only number which satisfy the original condition $x^{2018} \equiv 1 \pmod {21}$ are all $x \in \mathbb{Z}$ such that $x \equiv \pm 1 \pmod {3}$ and $ x \equiv \pm 1 \pmod {7}$
So those are the numbers in $\{..., -1,1,8,13,20,22,... \}$
Hopefully will this help you. I don't guarantee that this is the most efficient way to solve the problem but it does the job.
I am a bit stuck for the second exercise. You can say $5x^{2107} \equiv 75 \pmod {205} \implies x^{2107} \equiv 15 \pmod {41}$. Here it would be very painful to test every 41 possibilities for $x$. But since $41$ is prime you can use the little Fermat's theorem and say:
\begin{align}
x^{41} \equiv x \pmod{41}
\end{align}
So it means :
\begin{align}
x^{2017} \equiv x^{16} \cdot (x^{41})^{51} \equiv x^{16+51} \equiv x^{26} \cdot x^{41} \equiv x^{27} \pmod{41}
\end{align}
Our problem is now $x^{27} \equiv 15 \pmod{41}$. But I don't know how to continue here either... If I was desperate and really wanted a solution, I would just try out every number from 0 to 40. Wolphrame alpha says the answer is $13 + 41\cdot k$ with $k \in \mathbb{Z}$
EDIT : now that I have seen the answer of Daniel Wainfleet I can finish this exercise.
He used a smart trick, which was to take the cube of that equation:
$x^{27\cdot 3} \equiv 15^3 \equiv 13 \pmod{41}$. But how is this helpful ? Using the little Fermat's theorem again we can say
\begin{align}
a^{p-1} \equiv 1 \pmod{p}
\end{align}
if $p$ is prime. So that means $x^{40} \equiv 1 \pmod{41}$ which implies $x^{27} \equiv x^{81} \equiv x \cdot x^{40 \cdot 2} \equiv x \pmod{41}$.
From this he concludes $x \equiv 13 \pmod{41}$.


text:
Q: CMake find_package messed up the include paths I using CMake 3.5.1 on Debian 7 for my project. Here is the code in my CMakeLists.txt
find_package(Qt5 REQUIRED COMPONENTS Core)
message(STATUS ${Qt5Core_INCLUDE_DIRS})
But the print out of ${Qt5Core_INCLUDE_DIRS} is
/usr/include/x86_64-linux-gnu/qt5//usr/include/x86_64-linux-gnu/qt5/QtCore/usr/lib/x86_64-linux-gnu/qt5//mkspecs/linux-g++-64 which has no space between the paths.
What's wrong with CMake or is anything wrong in my CMakeLists.txt? How can I fix this?
thank you!

A: Qt5Core_INCLUDE_DIRS variable is a list, that is a string delimited with ;. When printing such strings, CMake omits delimiter and concatenates elements.
Use list and foreach commands to work with list elements.


text:
Q: The associated partition function generates more partitions than there are file groups mentioned in the scheme I am trying to create a partition to hold data older than the current year in a ARCHIVE file.
However I get the following error:

The associated partition function 'pfnYears' generates more partitions than there are file groups mentioned in the scheme 'pscYears'.

code:
ALTER DATABASE CURRO_DW Add Filegroup [CURRO_DW_ARCHIVE]

Alter Database CURRO_DW Add FILE ( NAME = N'CURRO_DW_ARCHIVE', FILENAME = N'D:\Data\CURRO_DW_ARCHIVE.ndf' , SIZE = 5120KB , FILEGROWTH = 1024KB ) TO Filegroup [CURRO_DW_ARCHIVE]`

DROP PARTITION SCHEME pscYears

DROP PARTITION FUNCTION pfnYears

CREATE PARTITION FUNCTION pfnYears (INT)
AS RANGE LEFT FOR VALUES
(
2017,2020
)

CREATE PARTITION SCHEME pscYears AS PARTITION pfnYears
TO
(
[CURRO_DW_ARCHIVE],[PRIMARY]
)

A: With two boundaries you need 3 filegroups because the data is split in 3 segments:
< 2017
between 2017 and 2020
`> 2020