text:
Q: Setting the View visibility to View.GONE, makes it invisible, still takes up space I have a view that I want to collapse, so I set the visibility to View.GONE the view becomes invisible, but it still takes up space.
I don't know what it might be, someone has ideas?
Here is an image before (View D):

Here is an image after (View D):

Here is the layout:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/mainColor"
android:clipToPadding="false"
android:fillViewport="false"
android:scrollbars="none">

<android.support.constraint.ConstraintLayout
    android:id="@+id/options_panel"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:descendantFocusability="beforeDescendants"
    android:focusableInTouchMode="true">

    <!-- other irrelevants views -->

    <TextView
        android:id="@+id/time_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="32dp"
        android:fontFamily="sans-serif"
        android:text="@string/toolbar_options_title_time"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/option_hexa_sorting" />

    <com.development.mekanius.bounce.customElements.HexaRadioGroupView
        android:id="@+id/option_hexa_time"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/time_title" />

    <Button
        android:id="@+id/option_create_post"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="32dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="32dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/option_hexa_time" />

</android.support.constraint.ConstraintLayout>

Thanks in advance

A: First of all, sorry for the late reply, but I have been stuck on finals and I didn't have much time.
Ok, the problem was a whole other story.
I'm using Spotify's Mobius as a state machine:
https://github.com/spotify/mobius
It's using a background thread to consume effects, and so acting on the UI gives an error. But for some reason the error was suppressed (was not on the logs and did't throw an exception), so I was seeing simply the view not obeying commands.
I came to this conclusion removing code lines until something worked.
Very old fashion.
Thanks for all that tried to help.

A: I spent hours debugging why this was happening to me and stumbled upon your answer. I was mutating visibility from an Rx-Java thread that was supposed to be operating on the main thread but apparently not! Doing a view.post {..} solved the issue for me! Thanks so much


text:
Q: How do I create a fixed position sidebar for my Wordpress project I am building a Wordpress site with a fixed sidebar menu on the left hand side and the main content on the right within a container. I'm not sure what is best practise for coding the menu because I have currently coded the menu to sit outside of the main container div. I have also noticed for some reason if the desktop screen size is not wide enough my content overflows into the menu on the left and also some of my menu is being cut off at the bottom (some of the links are not visible) I'm not sure if this has anything to do with the height of the screen?
HTML for the menu looks like:

        <?php wp_nav_menu( array( 'theme_location' => 'header-menu' ) ); ?>

The css is:
.menu-menu-1-container {
  position: fixed;
  left: 8.8%;
  top: 300px;
  border-right: 1px solid #D1D2D4;
  height: 10000px;
}

#menuBar {
    position: fixed;
    left: 8.15%;
    top:0;
    padding: 0 30px 0 0;
    border-right: 1px solid #D1D2D4;
    margin: 0 auto 0 auto;
}

I just want some advice as to how I should code this and whether or not there is something wrong with my code? I think it is missing something obvious but I don't know what it could be?

A: I figured out the solution to my problem; I did not realise at the time that using position: fixed; on an element takes it out of flow.
First of all unknowingly I added position:fixed; to the parent element > .menu-menu-1-container which was not required and did not help in anyway. I also removed all the other styles from this div as they were redundant.
Secondly I rectified the styles on #menuBar; I added a height of 100% to it and removed margin:0 auto; (which was doing nothing as I had not declared a width, also it did not need to be centered so this was redundant). I then added a width to #menuBar and removed the left style attribute.
Thirdly I found it to be correct to have the fixed sidebar outside of the main container div and styled the main container div with left margin and padding.
Here is a link to a fiddle with all my code and a snippet of my CSS is below:
#menuBar {
    position: fixed;
    width: 150px;
    background-color: #DDD;
    font-size: 18px;
    top: 0;
    bottom: 0;
    border-right: 1px solid #D1D2D4;
}

#menuBar a {
  display:block;
  padding:15px;
  color: #000;
  text-decoration: none;
}
.content {
  position: relative;
  margin-left: 200px;
}

Hope it helps anyone else struggling with something as simple as a fixed position sidebar.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why python dict is parsed in specific way in django template I am creating a dict and return to django template
 parsing = dict()
        for idx,title in enumerate(titles):
            link = parsing.setdefault(idx, {})
            link.setdefault('title', title)
            link.setdefault('image', image)
            # print(link['image'])
        return render(request, "blog/intro.html", {'parsing':parsing})

But can't understand why only this code works in template. Only with 1. Why?
 {% for el in parsing.items %}
   {{ el.1.title }}
{% endfor%}

EDIT:
let's say I need to put both title and image as elements of lists to dict. how can I also create list comprehension for images?
        titles = [...]
        images = [...]
        parsing = [{'title': title, 'image': image} for title in titles]


text:
Q: Optimal output by given input: looping through two lists I want to find the optimal order/combination for a vector of length 9. Optimal in the meaning that three of the same symbols are a "bingo" and I want the most bingos.
To do this I think I have to loop through two lists: the vector indices (simulating a 3x3 matrix, bingos are horizontally, vertically and diagonally) and the combinations. I have done the following:
#data
input <- sample(c("A", "B", "C"), 9, replace = TRUE)
input_perm <- combinat::permn(input)

#simulating 3x3 matrix bingos: horizontally, vertically, diaginally
m <- list(
r1 = 1:3,
r2 = 4:6,
r3 = 7:9,
c1 = c(1, 4, 7),
c2 = c(2, 5, 8),
c3 = c(3, 6, 9),
d1 = c(1, 5, 9),
d2 = c(3, 5, 7))

output <- character()
for ( i in seq_along(m)) {
output[i] <- ifelse (length(unique(input[m[[i]]])) == 1, TRUE , FALSE)
}
output <- list(output)

So I can do this for one possibility but how do I do this for all using the input_perm?
My desired output will be a list all combinations (362880)
[[1]]
[1] FALSE FALSE  TRUE  TRUE FALSE  TRUE FALSE FALSE

[[2]]
[1] FALSE FALSE FALSE FALSE  TRUE  TRUE FALSE FALSE

[[3]]
[1]  TRUE  TRUE FALSE  TRUE FALSE FALSE  TRUE FALSE

and so on...
so that I can filter the combinations with most bingos:
output[which.max(lapply(output, sum))]

But I think there will be a much better solution than looping through two list. Thanks in advance.

A: We may use a nested loop
out2 <- lapply(input_perm, function(inp)
     unname(sapply(m, function(x) length(unique(inp[x])) == 1)))

-output
head(out2)
[[1]]
[1] FALSE FALSE  TRUE FALSE FALSE  TRUE FALSE  TRUE

[[2]]
[1] FALSE FALSE  TRUE FALSE FALSE  TRUE FALSE  TRUE

[[3]]
[1] FALSE FALSE  TRUE FALSE FALSE  TRUE FALSE  TRUE

[[4]]
[1] FALSE FALSE  TRUE FALSE FALSE  TRUE FALSE  TRUE

[[5]]
[1] FALSE FALSE  TRUE FALSE FALSE  TRUE FALSE  TRUE

[[6]]
[1] FALSE FALSE  TRUE FALSE FALSE  TRUE FALSE FALSE

Or if we use the for loop
out3 <- vector('list', length(input_perm))
for(i in seq_along(out3)) {
    tmp <- logical(length(m))
    for(j in seq_along(m)) {
       tmp[j] <- length(unique(input_perm[[i]][m[[j]]])) == 1
      }
     out3[[i]] <- tmp
}

-output
head(out3)
[[1]]
[1] FALSE FALSE  TRUE FALSE FALSE  TRUE FALSE  TRUE

[[2]]
[1] FALSE FALSE  TRUE FALSE FALSE  TRUE FALSE  TRUE

[[3]]
[1] FALSE FALSE  TRUE FALSE FALSE  TRUE FALSE  TRUE

[[4]]
[1] FALSE FALSE  TRUE FALSE FALSE  TRUE FALSE  TRUE

[[5]]
[1] FALSE FALSE  TRUE FALSE FALSE  TRUE FALSE  TRUE

[[6]]
[1] FALSE FALSE  TRUE FALSE FALSE  TRUE FALSE FALSE

A: Maybe you can try the base R code below
mat <- outer(
    seq_along(input_perm),
    seq_along(m),
    FUN = Vectorize(function(p, q) length(unique(input_perm[[p]][m[[q]]])) == 1)
)
rSum <- rowSums(mat)
res <- subset(mat, rSum == max(rSum))


text:
Q: WebUSB on Android Chrome I have a website that connects to a label printer using WebUSB and prints labels. Everything works well on the computer, but unfortunately it does not work on Android. Android finds my printer "LP 433", but after nothing happens, it should print. I connect to the printer using the OTG cable. Google Chrome version: 83.
On other browsers WebUSB does not respond in any way, except firefox, it directly says that it does not support WebUSB. My site work on https.
  async findDevices() {
try {
  const navi: any = navigator;
  const devices = await navi.usb.getDevices();
  console.log(devices);
  devices.forEach(dev => {
    console.log(dev);
  });
  const device = await navi.usb.requestDevice({filters: [{vendorId: 15923}]});
  await device.open(); // Begin a session.
  await device.selectConfiguration(1); // Select configuration #1 for the device.
  await device.claimInterface(0); // Request exclusive control over interface #2.
  await device.controlTransferOut({
    requestType: 'vendor',
    recipient: 'interface',
    request: 0x01,  // vendor-specific request: enable channels
    value: 0x0013,  // 0b00010011 (channels 1, 2 and 5)
    index: 0x0001   // Interface 1 is the recipient
  })
    .then(() => device.transferIn(1, 64)) // Waiting for 64 bytes of data from endpoint #5.
    .then(result => {
      const decoder = new TextDecoder();
      console.log('Received: ' + decoder.decode(result.data));
      // document.getElementById('target').innerHTML = 'Received: ' + decoder.decode(result.data);
    })
    .catch(error => {
      console.log(error);
    });

  const imgData: any = await this.toPrintFormat();
  for (let p = 0; p < this.pcs; p++) {
    for (let i = 0; i < imgData.length; i++) {
      //   setTimeout(() => {
      const string2 =
        'sLABEL,' + imgData[i].width + ',' + imgData[i].height + '\n' +
        'sGAP,0,0\n' +
        'sTPHY,0\n' +
        'sDENSITY,7\n' +
        'sSPEED,' + this.speedp + '\n' +
        'sTHERMAL,' + this.thermop + '\n' +
        'sDIRECTION,1\n' +
        'sORIGIN,0,0\n' +
        'wSAVEB64,' + imgData[i].src.length + ',\"WLP000\",' + imgData[i].src + '\n' +
        'wLOADIMG,0,' + 0 + ',1,\"WLP000\"\n' +
        'wPRINT,1\n';
      console.log(string2);
      const encoder = new TextEncoder();
      const data = encoder.encode(string2);
      device.transferOut(2, data)
        .catch(error => {
          console.log(error);
        });
    }
  }
  // document.getElementById('target').innerHTML = 'Received: ' + decoder.decode(result.data);
} catch (error) {
  // document.getElementById('target').innerHTML = error;
}
}


text:
Q: Update from inner join I can't seem to get my update from inner join method to work. I have tried to write it a few different ways to no avail. Rows get affected but the product table's values are never actually updated.
Select code to test (should return no results after update query is run):
SELECT
    [P].[ProductCode],
    [P].[PriceSelling],
    [ID].[InclPrice],
    [P].[StockQty],
    [ID].[Qty]
FROM
    dbo.Sync_ImportData AS [ID]
INNER JOIN
    dbo.Sync_Product AS [P]
ON
    [P].[ProductCode] = [ID].[ISBN]
WHERE
    ([P].[StockQty] <> [ID].[Qty] OR [P].[PriceSelling] <> [ID].[InclPrice])

Update Code:
UPDATE [P]
SET
    [P].[StockQty] = [ID].[Qty],
    [P].[PriceSelling] = [ID].[InclPrice]
FROM
    dbo.Sync_Product AS [P]
INNER JOIN
    dbo.Sync_ImportData AS [ID]
ON
    [P].[ProductCode] = [ID].[ISBN]
WHERE
    ([P].[StockQty] <> [ID].[Qty] OR [P].[PriceSelling] <> [ID].[InclPrice])

Basically I need to update the stock qty and price if the Imported Data a) has a record for the product (ISBN matches ProductCode) and b) either value needs to be updated (qty or price is different from ImportData)

A: You could see this behavior if there were more than one match between the tables.  In particular, if ISBN is not unique in Sync_ImportData:
SELECT id.ISBN, COUNT(*)
FROM dbo.Sync_ImportData id
GROUP BY id.ProductCode
HAVING COUNT(*) > 1

If there are duplicates, then one of the rows would be used for the update -- arbitrarily.  The changes would not match the second row.


text:
Q: Android viewpager automatic sliding How to handle automatic swiping of viewpager pages  together with manual swipe
i.e a set of 10 pages are there in viewpager each slides after 3 seconds but problem is when user swipes the page it moves back to sequence page what i need is following.
1>if user swipes two consecutive pages than it should not go back.
2>timer should paused when user is swiping the pages and timer should restart from screen holding the page. the code is as
@Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ten);
        timer = new Timer();

viewPager.setAdapter(adapter);

        viewPager.setCurrentItem(0);

        // Timer for auto sliding

        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (count <= alQuestion.size()) {
                            viewPager.setCurrentItem(count, true);
                            count++;
                        } else {
                            viewPager.setCurrentItem(count);
                        }
                    }
                });
            }
        }, 500, 3000);

A: I recently faced the same problem, and got solved by writing below function.
public void autoSlider(final ViewPager viewPager) {

    rr = new Runnable() {
        public void run() {
            int pos = viewPager.getCurrentItem();
            if(pos > i && pos != slidingImages.length - 1){
                i = pos;
                i++;
                        }
            else if(pos < (i-1)){
                i = pos;
                i++;
            }
            viewPager.setCurrentItem(i, true);
            i++;
            if (i >= slidingImages.length)
                i = 0;
            autoSlider(viewPager);
        }};
    handler.postDelayed(rr, 3000);
}

Hope this will help you.

A: create TimerTask  class and schedule it in Timer class
    private class SliderTimer extends TimerTask {

    @Override
    public void run() {
        SliderActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (viewPager.getCurrentItem() < color.size() - 1) {
                    viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
                } else {
                    viewPager.setCurrentItem(0);
                }
            }
        });
    }
}

Timer timer = new Timer();
timer.scheduleAtFixedRate(new SliderTimer(), 4000, 6000)

Kindly follow this link for step bye step guideline https://medium.com/@shaktisinh/auto-slider-with-indicator-in-android-a28153d42125


text:
Q: Building data structure for Dictionary I am looking for some high level thoughts/ideas help me building a data structure for Dictionary.  I have a legacy 'product (medicine) search system' which is very slow and complex in nature. We would need to completely re-architect the system for efficient and maintainable solution.
To simplify the question, I take an example of 'Dictionary' ( I expect my new system behaves like Dictionary )

*

*I should be able to store Word,description and few synonyms ( equivalent generic medicine),

*Words should not duplicate

*Synonyms will also be instance of Word ( it should carry behaviour of word, description and synonyms).

*Faster searching

UseCases

*

*When a word is searched, its meaning and synonyms displayed

*Faster Search

*Removal of synonym should be possible

*Adding new word, should be able to add to any existing word's synonyms

I created a data structure shown below
Class Word {
    String meaning;
    List<Word> synonyms;
}

To store Words, I am thinking to use  TreeSet
because

TreeSet provides an implementation of the Set interface that uses a
  tree for storage. Objects are stored in sorted, ascending order.
  Access and retrieval times are quite fast, which makes TreeSet an
  excellent choice when storing large amounts of sorted information that
  must be found quickly.

Or I can use HashMap, where the hashcode of word and synonyms word instance made equal which could enable faster retrieval.
Still I could see lot of challenges

*

*When ever new word is added how to link with its synonyms

*Look up would be slow when there are huge number of words

*Editing  word also should reflect synonyms and vice versa
Any thoughts/inputs/tricks would be highly valued

A: You could use Trie to store all words in dictionary. Add a list of synonims for each word (node).

A: For word search and word completion requirement Trie would be a fast alternative. Take a look at Java implementations:

In computer science, a trie, also called digital tree and sometimes
  radix tree or prefix tree (as they can be searched by prefixes), is an
  ordered tree data structure that is used to store a dynamic set or
  associative array where the keys are usually strings.

http://pathakalgo.blogspot.in/2012/11/trie-data-structure-implementation-in.html
https://www.google.co.in/search?q=Trie&client=ubuntu&channel=cs&oq=Trie&aqs=chrome..69i57j69i60l2.856j0j1&sourceid=chrome&ie=UTF-8
For synonym linkage, you can maintain a Map<String, LinkedList<String>>. Once a word is found using Trie, fetching associated sysnonyms would be O(1).


text:
Q: Dynamic routerLink in Angular I have a list, which contains strings and in this list I use *ngFor no problem. I use index in ngFor to determine which route to go, but i discovered the flaws in this design, so i want to change it. in the list component i have a string array, just like the list items. how can i route to this list's content using indexes.
my curent code is like this:

                {{ l }}

I want to achive something like this:

                {{ l }}

the component.ts for this list looks like this:
@Input() list: string[] = [];
  @Input() urls: string[] = [];
  @Output() btnpress = new EventEmitter<string>();

  id: string[] = [];

  constructIdList() {
    this.urls.forEach(url => {
      if(url.length > 0) {}
      let tmp = url.split('/');
      if(tmp.length > 0) {
        console.log(tmp.pop());
      }
    });
  }

A: Adding a method should do the trick:
TS
getRoute(ndx: number): string {
    return "[" + id[ndx] + "]";
}

HTML
[routerLink]="getRoute(i)"


text:
Q: Notepad++ or netbeans plugin for marking text in html I need a plugin, which can show in another color words in HTML (and PHP) code. For example
this is domain

and i need this result

this is domain

Is it possible?

And what if I have text and htm in echo?

A: You can go to Notepad++ and there Settings -> Style Configurations and from left side HTML and then modify the colors the way you like them!

A: Netbeans also have a customizable html editor that can do this job.
Go
Tools>Option>Font & Color
In the syntax tab select HTML as Language and make the appropriate changes


text:
Q: Timeshift restore to replacement SSD? Ubuntu 20.04.
I think I know what to do here but would appreciate knowing any tips or if there's anything I've missed...
I have three SSDs, one with OS, one for backups and VMs and another mounted as my home directory.
The disk with home has died (after 6 months!) so I will replace. I know how to boot to a live USB and format with GParted and then I assume I'll just edit fstab to change the disk ID for my home folder from the dead one to the new one.
I then hope I can restore a Timeshift backup once up and running but don't know if the identification of a new disk will cause problems.
Any help appreciated!


text:
Q: Getting Permission Denied error trying to move Google Analytis property I am trying to move ownership of a Google Analytics account (property) to a client that has moved on to a new company. I have had them setup a new analytics account and add me as a user to the account with all permissions checked. When I go into the admin of their current account, that I own, and go to the move property screen, I can see the new account they created. After I select the new account, check confirm changes and click the blue "Start Move" I just get a red notification at the top of the screen that says "Permission Denied".

*

*They have added me to their new account and given me all the
privileges.

*Both accounts are standard free acounts, not 360 accounts

*No AdWords, AdSense, etc are linked to either account.

Any ideas what I could be missing here?

A: Had the same issue. My work around was:

*

*Go into Admin in the Source account (your GA account)

*Create a new account i.e. "My new temp account"

*Move your Property to "My new temp account"

*Grant your client the relevant permissions to "My new temp account"

*Move the Property from "My new temp account" to the Destination account (the client's account)
It moved successfully after that. I don't know why I got "Permission denied" originally. The site I was moving was very old (10+ years), so might have been a "legacy" issue with the Google account, but that's me guessing!


text:
Q: Google Maps aerial photography I've been playing around with GeoServer, Google Maps and OpenLayers and have been reasonably successful however when using the aerial photography from Google I don't seem to be able to zoom in as far as I should be able to.
Any ideas?

A: Google has don't have unique(max) zoom level support for whole world. It differs based on location.
If you are familiar with Google Maps JS API you could do API calls to check the zoom level for the location. Here sample page: http://code.google.com/apis/maps/documentation/javascript/examples/maxzoom-simple.html


text:
Q: Laravel 5.2 - Delete duplicates from my query i have a query like this:
$players = PostBalance::where('post_id', $post->id)->orderBy('id','desc')->get();

It work well and return array with all values, Post balances have fields:
ID
score
post_id
user_id

I would like Delete user_id duplicated AND get the max score value. for example if i have:
[0] = 'id' => 1 , 'score'=> 10, 'user_id'=> 1, 'post_id' => 1
[1] = 'id' => 2 , 'score'=> 20, 'user_id'=> 1, 'post_id' => 1
[2] = 'id' => 3 , 'score'=> 30, 'user_id'=> 1, 'post_id' => 1
[3] = 'id' => 4 , 'score'=> 40, 'user_id'=> 2, 'post_id' => 1
[4] = 'id' => 5 , 'score'=> 50, 'user_id'=> 2, 'post_id' => 1
[5] = 'id' => 6 , 'score'=> 60, 'user_id'=> 2, 'post_id' => 1

I would like delete duplicates user_id and get only the user_id with max score:
RESULT:
[0] = 'id' => 3 , 'score'=> 30, 'user_id'=> 1, 'post_id' => 1
[1] = 'id' => 6 , 'score'=> 60, 'user_id'=> 2, 'post_id' => 1

A: You can use groupBy() and max() method like this (note: this will not actually delete the duplicates from DB, but work for your query):
$result = PostBalance::groupBy('user_id')
                    ->max('score');

For further reference, see Laravel Docs
Or if you want to order the results by score, you can do it like this:
$result = PostBalance::orderBy('score', 'desc')
                     ->groupBy('user_id')
                     ->get();

Note: To get max of group by, try to first run orderBy(), then run groupBy() on the query instead.
Hope this helps!


text:
Q: Unable to login to Cross Validated I frequent various SE sites on my android phone, and I've never had any issues. Only when a  while back I tried to access CV I got a connection refused error, so I gave up trying to visit the site for a few weeks. Now I can browse it normally but I get the same error when I try to login/create account. I tested with some other SE sites but I only get rejected by CV.
I managed to create an account on CV by using a proxy, but this is not a long term solution. Can anyone think of why this is happening. My location is Hong Kong using the 4g network of a large provider.
Update:
I tried a different browser: no effect.
I tried a different phone with a different provider: it works normally.
I tried the SE android app: also seems to work properly.
So specifically using a browser with my provider (pccw) seems to cause a rejection of the login page. Note it is not my login attempt that is rejected, but the page to login shows error connection refused, so I can't login...


text:
Q: in ant :BUILD EXCEPTION I am getting some problem while running ant
Here is the details of problem:
C:\jboss-5.1.0.GA\server\default\deploy\mdd_install\mc_config\ant\compile\compile.xml:30: Unable to find a javac compiler;
com.sun.tools.javac.Main is not on the classpath.
Perhaps JAVA_HOME does not point to the JDK
    at org.apache.tools.ant.taskdefs.compilers.CompilerAdapterFactory.getCompiler(CompilerAdapterFactory.java:105)
    at org.apache.tools.ant.taskdefs.Javac.compile(Javac.java:924)
    at org.apache.tools.ant.taskdefs.Javac.execute(Javac.java:757)
    at org.apache.tools.ant.Task.perform(Task.java:364)
    at org.apache.tools.ant.Target.execute(Target.java:341)
    at org.apache.tools.ant.Target.performTasks(Target.java:369)
    at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1216)
    at org.apache.tools.ant.Project.executeTarget(Project.java:1185)

I echo java_home and its value is correct
I am running my aplication from jboss and try to execute it, but it is getting the above exception. I put tools.jar in jboss server lib folder ,with that it is runnig fine,but it is not correct way.

A: Make sure the case of the path to JAVA_HOME is right. Reopen the window or environment you're running ant from to make sure it's using the updated environment vars.


text:
Q: Annotate a math symbol in an itemize I would like to annotate underneath a math symbol in an itemize list. I would like to have the option of having the annotation either (a) centered or (b) left-aligned with the math symbol, like the following example I made in a word processor (looks ugly, doesn't it?):

I may also need to adjust the spacing between items so that it is obvious what the annotation is referring to.
Here is a starting point MWE. Can you please help?
\documentclass{article}

\newcommand{\dDGp}{\delta\Delta\Gamma_{+}}
\newcommand{\dDGm}{\delta\Delta\Gamma_{-}}

\begin{document}

Centered:
\begin{itemize}
  \item{for $\dDGp$ from A to B}
  \item{for $\dDGm$ from C to D}
  \item{for $\dDGp$ from E to F}
\end{itemize}

Left-aligned:
\begin{itemize}
  \item{for $\dDGp$ from A to B}
  \item{for $\dDGm$ from C to D}
  \item{for $\dDGp$ from E to F}
\end{itemize}

\end{document}

A: You can use amsmath's \underset{<under>}{<stuff>} to set <under> below <stuff>.

\documentclass{article}

\usepackage{amsmath}

\newlength\tmplen
\newcommand{\dDGp}[1][c]{%
  \settowidth{\tmplen}{$\delta\Delta\Delta\Delta\Gamma_+$}%
  \underset{\text{\makebox[\tmplen][#1]{positive}}}{\delta\Delta\Delta\Delta\Gamma_+}}
\newcommand{\dDGm}[1][c]{%
  \settowidth{\tmplen}{$\delta\Delta\Delta\Delta\Gamma_-$}%
  \underset{\text{\makebox[\tmplen][#1]{negative}}}{\delta\Delta\Delta\Delta\Gamma_-}}

\begin{document}

Centered:
\begin{itemize}
  \item{for $\dDGp$ from A to B}
  \item{for $\dDGm$ from C to D}
  \item{for $\dDGp$ from E to F}
\end{itemize}

Left-aligned:
\begin{itemize}
  \item{for $\dDGp[l]$ from A to B}
  \item{for $\dDGm[l]$ from C to D}
  \item{for $\dDGp[l]$ from E to F}
\end{itemize}

Right-aligned:
\begin{itemize}
  \item{for $\dDGp[r]$ from A to B}
  \item{for $\dDGm[r]$ from C to D}
  \item{for $\dDGp[r]$ from E to F}
\end{itemize}

\end{document}

The content is placed in a box of matching width where an optional argument is used to [c]entre, [l]eft-align or [r]ight-align the "subscript." I've enlarged the operator (<stuff>) in the example for reference.
Vertical spacing between items in a list can be managed easily via enumitem.

A: Here, I use stackengine to achieve the underset.  Optional argument determines the alignment (c by default). The following choices I made can be changed: \small under-text size, \sffamily, underset baseline 8pt below the text baseline, and the width of the anchor text determines the width of the complete stack.
\documentclass{article}
\usepackage[usestackEOL]{stackengine}
\setstackgap{L}{8pt}
\renewcommand\useanchorwidth{T}
\newcommand{\dDGp}[1][c]{\Longunderstack[#1]{$\delta\Delta\Gamma_{+}$%
  \\\small\sffamily positive}}
\newcommand{\dDGm}[1][c]{\Longunderstack[#1]{$\delta\Delta\Gamma_{-}$%
  \\\small\sffamily negative}}

\begin{document}

Centered:
\begin{itemize}
  \item for \dDGp{} from A to B
  \item for \dDGm{} from C to D
  \item for \dDGp{} from E to F
\end{itemize}

Left-aligned:
\begin{itemize}
  \item for \dDGp[l] from A to B
  \item for \dDGm[l] from C to D
  \item for \dDGp[l] from E to F
\end{itemize}

\end{document}

A: I guess that you want the text below to take no space. A \vtop with a nested \halign seems a good solution. You can do \annot[l]{whatever}{something} if you want left alignment. Actually any single letter except c will do.
\documentclass{article}
\usepackage{amsmath}

\makeatletter
\newcommand{\annot}[3][c]{%
  \leavevmode\vtop{%
    \offinterlineskip
    \ialign{%
      ##\cr
      #2\cr
      \noalign{\vskip1pt}
      \if#1c\hidewidth\fi
      \check@mathfonts\fontsize{\sf@size}{0}\sffamily\upshape#3\vphantom{Ay}%
      \hidewidth\cr
    }%
  }%
}
\makeatother

\newcommand{\dDGp}{\delta\Delta\Gamma_{+}}
\newcommand{\dDGm}{\delta\Delta\Gamma_{-}}

\begin{document}

Centered:
\begin{itemize}
  \item{for \annot{$\dDGp$}{positive} from A to B}
  \item{for \annot{$\dDGm$}{negative} from C to D}
  \item{for \annot{$\dDGp$}{loooooonger} from E to F}
\end{itemize}

Left-aligned:
\begin{itemize}
  \item{for \annot[l]{$\dDGp$}{positive} from A to B}
  \item{for \annot[l]{$\dDGm$}{negative} from C to D}
  \item{for \annot[l]{$\dDGp$}{loooooonger} from E to F}
\end{itemize}

\end{document}


text:
Q: Docker Container running error I am using  Fedora 26 Os and Docker Version is (docker-ce-18.03.0.ce).
Whenever i am using new docker container i am getting below mentioned error
Does anyone know how to solve this problem.

A: Please run:
docker image ls

and make sure the image with the name swarm is there


text:
Q: Formatting Mysql TimeStamp Jquery I'm trying to format a mysql TIMESTAMP I get using the get.json function in jquery to look like this Nov 21st 2010, tried formatting through the initial select from the php script using the DATE_FORMAT class but it is all the information is read out as undefined. I tested out the php script by itself and it worked fine.
php script, trying to format the TIMESTAMP
$mangaInfo = "SELECT manga.mangaName,chapter.chapterNumber,chapter.chapterName,chapter.chapterID, DATE_FORMAT(chapter.dateUploaded,'%b %D %Y') FROM manga INNER JOIN chapter ON manga.mangaID=chapter.mangaID ORDER BY chapter.dateUploaded DESC LIMIT 10";

Jquery script which is trying to process the date
$.getJSON('/chaptersRetrival.php', function(data)
        {
                    $.each(data, function(index, array) {
                    $("<a/>").attr({
                    href: 'http://www.neuromanga.com/mangaReader.php?chapterNo='+this['chapterID']+'&#pageNo=1',
                    title: this['mangaName']+ " " + this['chapterNumber'] +" "+ this['chapterName'] + " "
                    }).html(array.mangaName+" "+ array.chapterNumber +" "+ array.chapterName + " " + array.dateUploaded + " "+"<br />").appendTo("#mangaChapters");
                });
            });
       };

A: Here is your problem:
DATE_FORMAT(chapter.dateUploaded,'%b %D %Y')
You need to actually define it AS:
DATE_FORMAT(chapter.dateUploaded,'%b %D %Y') as dateUploaded
You are calling array.dateUploaded but none is defined in your JS result.

A: It is quite simple in php
date('M jS Y',strtotime($mysql_timestamp));


text:
Q: Vuex — handling network busy status globally? I have a Vue/Vuex app and I'm using a Boolean networkBusyStatus to store when API calls are being done.
I have a lot of different calls firing when the app loads so when I watch networkBusyStatus in one of my components and console the newVal, it's predictably alternating true, false, true, false.
What's the correct way of globally watching this to know when "false" is really the final "false". i.e. loading is officially and completely done?

A: You can use a Promise.all method to ensure that the networkBusyStatus state is mutated only when all the API calls have been resolved.
.vue file

export default {
  mounted() { // as you know, the created hook can also be used here
    this.$store.commit('loading', true)
    Promise.all([this.$store.dispatch('fetchAsyncData'), this.$store.dispatch('fetchAnotherAsyncDataOnTheSameComponent')]).then(values => {
     this.$store.commit('loading', false) // commit a mutation for changing networkBusyStatus to false when all requests have been resolved
  })
}

vuexModule.js

const store = new Vuex.Store({
  state: {
    networkStatusBusy: false // you can share networkStatusBusy state so that when multiple api calls are made on  the same component, networkStatusBusy doesn't return to false until all calls are resolved.
    data: [],
    otherAsyncData: [],
  },
  mutations: {
    loading (state, payload) {
      state.networkStatusBusy = payload
    }
    setAsyncData(state, payload) {
      state.data = payload;
    }
    setOtherAsyncData(state, payload) {
      state.otherAsyncData = payload;
    }
  }
  actions: {
    fetchAsyncData ({ commit }) {
      axios.get('path-to-api').then(result => {
        commit ('setAsyncData', result.data)
      })
    }
    fetchAnotherAsyncDataOnTheSameComponent ({ commit }) {
      axios.get('another-api-on-same-component').then(result => {
        commit('setOtherAsyncData', result.data);
      })
    }
  }

})

.vue file

import { mapState } from 'vuex';
export default {
  // ...
  computed: mapState({
    networkBusyStatus: state => state.(moduleInQuestion).networkBusyStatus,
  }),
  watch: {
    networkBusyStatus function (newVal, oldVal) {
      console.log('new value', newVal)
    }
  }
}


text:
Q: Draw an Arc - Given an angle and one segment Is given an angle £ and an segment AB. Haw can I draw an arc from A to B such the central angle corresponding to it to be £ ?

A: If you find any point $C$ such that $\angle ACB = £/2$, then the $AB$ arc of the circumcircle of $\triangle ABC$ will work.
You can do this by finding any two angles that add to $180^\circ - £/2$, and drawing one of them at $A$ and the other one at $B$, both with $AB$ as one of the angle legs, and let $C$ be where the two new angle legs intersect.


text:
Q: knockout observablearray of observables I am having problems with a Knockout ObservableArray that is made up of objects with observable properties.  My view model is fairly complicated but I have created the simple test below which will illustrate the problem.
My problem is that when I change the value of an observable property in one of the objects in the ObservableArray that value is changed for ALL objects in the array.
I have a department viewModel which has an observable array of employees in that department.  I then create 5 instances of the object personVM that gets pushed onto the employees ObservableArray.   Each instance of personVM gets a unique firstName.
Here are the models and the code to load them up.
var theDepartmentVM = {
        employees: ko.observableArray(),
        departmentName: ko.observable()
};

var personVM= {
    firstName: ko.observable()
    }

$(document).ready(function (){
    departmentVM.departmentName = "SomeDepartment";
    for (i=1; i<=5; i++){
        var person = Object.create(personVM);
        personVM.firstName("EMP - " + i.toString());
        departmentVM.employees.push(personVM);
    }
    ko.applyBindings(departmentVM);
});

This adds five name (EMP-1, EMPT-2, etc.).  Then I display the names with the following markup:

My output is the name "EMP-5" five times.  It's always the last value I added to the array.
I think the problem is that I have five instances of personVM but the firstName object in each instance points to the same observable.  Is this correct?
What do I need to do to get the desired result?

A: Try this
http://jsfiddle.net/r9sqjojL/2/

var departmentVM = {
        employees: ko.observableArray(),
        departmentName: ko.observable()
};

var personVM = function() {
        this.firstName = ko.observable();
}
departmentVM.departmentName = "SomeDepartment";
for (i=1; i<=5; i++){
        var person = new personVM();
        person.firstName("EMP - " + i.toString());
        departmentVM.employees.push( person );
}
ko.applyBindings(departmentVM);


text:
Q: Problem: After using org.apache.pdfbox.multipdf.Splitter, pages have no PDAcroForm I am using the below code to split a tax form PDF into individual pages. When using the resulting individual pages, no PDAcroForm is found on the pages.
Is this a limitation?
What am I missing?
package xxxx.util.pdf.box;

import org.apache.pdfbox.multipdf.Splitter;
import org.apache.pdfbox.pdmodel.PDDocument;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;

public class PdfSplitter {

    private static final Logger LOGGER
        = Logger.getLogger( PdfSplitter.class.getSimpleName( ) );

    public static List<byte[]> splitPdfBytes(
        byte[] pdfBytes
    ) {

        List<byte[]> pages = new ArrayList<>( );

        try (
            PDDocument document = PDDocument.load( pdfBytes );
        ) {

            Splitter splitter = new Splitter();

            List<PDDocument> docs = splitter.split( document );

            for ( PDDocument doc : docs ) {

                ByteArrayOutputStream baos = new ByteArrayOutputStream( );

                doc.save( baos );

                pages.add( baos.toByteArray( ) );

            }

        } catch ( IOException e ) {

            LOGGER.severe( e.getMessage( ) );

        }

        return pages;

    }

}

Later on:
PDDocument doc = PDDocument.load(templateStream)

PDDocumentCatalog pdDocCatalog = doc.getDocumentCatalog();

PDAcroForm acroForm = pdDocCatalog.getAcroForm();

// acroForm is null !

Are there options in the splitter class I should be taking advantage of?

UPDATE 08/25/2022:
Thank you for informing me of this limitation.
The use case is as follows:
The IRS supplies Forms 1099 in 1 pdf file with each copy or page. For example, see https://www.irs.gov/pub/irs-pdf/f1099div.pdf
My app fills out the recipient copy of the form So I only want page 4 of the PDF.
To work around this limitation, I am filling out the PDF first using AcroForm/AcroField population and then removing the pages I don't need.


text:
Q: Simple SQL: How to calculate unique, contiguous numbers for duplicates in a set? Let's say I create a table with an int Page, int Section, and an int ID identity field, where the page field ranges from 1 to 8 and the section field ranges from 1 to 30 for each page.  Now let's say that two records have duplicate page and section.  How could I renumber those two records so that the sequence of page and section numbering is contiguous?
select page, section
from #fun
group by page, section having count(*) > 1

shows the duplicates:
page 1 section 3
page 2 section 3

page 1 section 4 and page 2 section 4 are missing.  Is there a way without using a cursor to find and renumber the positions in SQL 2000 that doesn't support Row_Number()?
This rownum below of course produces exactly the same number as in section:
select page, section,
    (select count(*) + 1
     from #fun b
     where b.page = a.page and b.section < a.section) as rownum
from #fun a

I could create a pivot table having values 1 through 100, but what would I join against?
What I want to do is something like this:
update p set section = (expression that gets 4)
from #fun p
where (expression that identifies duplicate sections by page)

A: I don't have a 2000 server to test this on, but I think it should work.
Create test tables/data:
CREATE TABLE #fun
(Id INT IDENTITY(100,1)
,page INT NOT NULL
,section INT NOT NULL
)

INSERT #fun (page, section)
SELECT 1,1
UNION ALL SELECT 1,3    UNION ALL SELECT 1,2
UNION ALL SELECT 1,3    UNION ALL SELECT 1,5
UNION ALL SELECT 2,1    UNION ALL SELECT 2,2
UNION ALL SELECT 2,3    UNION ALL SELECT 2,5
UNION ALL SELECT 2,3

Now the processing:
-- create a worktable
CREATE TABLE #fun2
(Id INT IDENTITY(1,1)
,funId INT
,page INT NOT NULL
,section INT NOT NULL
)

-- insert data into the second temp table ordered by the relevant columns
-- the identity column will form the basis of the revised section number
INSERT  #fun2 (funId, page, section)
SELECT  Id,page,section
FROM    #fun
ORDER BY page,section,Id

-- write the calculated section value back where it is different
UPDATE  p
SET     section = y.calc_section
FROM    #fun AS p
JOIN
        (
            SELECT  f2.funId, f2.id - x.adjust calc_section
            FROM    #fun2 AS f2
            JOIN    (
                        -- this subquery is used to calculate an offset like
                        -- PARTITION BY in a 2005+ ROWNUMBER function
                        SELECT MIN(Id) - 1 adjust, page
                        FROM #fun2
                        GROUP BY page
                    ) AS x
            ON      f2.page = x.page
        ) AS y
ON      p.Id = y.funId
WHERE   p.section <> y.calc_section

SELECT * FROM #fun order by page, section

A: Disclaimer:  I don't have SQL Server to test.
If I understand you correctly, if you knew the ROW_NUMBER of your #fun records partitioned over (page, section) duplicates, you could use this relative ranking to increment the "section":
    UPDATE p
       SET section = section + (rownumber - 1)
      FROM #fun AS p
INNER JOIN ( -- SELECT id, ROW_NUMBER() OVER (PARTITION BY page, section) ...
            SELECT id, COUNT(1) AS rownumber
              FROM #fun a
         LEFT JOIN #fun b
                   ON a.page = b.page AND a.section = b.section AND a.id <= b.id
          GROUP BY a.id, a.page, a.section) d
            ON p.id = d.id
      WHERE rownumber > 1

That won't handle the case where the number of duplicates push you past your upper limit of 30.  It may also create new duplicates where if higher numbered sections per page already exist -- that is, one instance of (pg 1, sec 3) becomes (pg 1, sec 4), which already existed -- but you can run the UPDATE repeatedly until no duplicates exist.
And then add a unique index on (page, section).


text:
Q: How to get arabic number of total pages with \pagenumbering{Roman} In the following code, I store the number of total pages in a macro named \totalpages by means of \getpagerefnumber{LastPage}(from packages of lastpage and refcount).
Then I compare the number by \ifnum, but fail for the reason of \pagenumbering{Roman} which make page number in non-arabic format.
I wonder if there is a way to get an arabic number of total pages even if the format of the page number is non-arabic, i.e. \pagenumbering{Roman} alph, etc.
\documentclass{article}
\usepackage{lastpage,refcount}
\pagenumbering{Roman}

\begin{document}
\def\totalpages{\getpagerefnumber{LastPage}}
\ifnum\totalpages=3 ok \else not ok \fi\\
first page
\clearpage
second page
\clearpage
third page
\end{document}

A: Use the pageslts package instead of lastpage.
\documentclass{article}
\usepackage{pageslts,refcount}
\pagenumbering{Roman}

\begin{document}
\newcommand\totalpages{\getpagerefnumber{LastPages}}
\ifnum\totalpages=3 ok \else not ok \fi\\
first page
\clearpage
second page
\clearpage
third page
\end{document}

A: A current LaTeX writes the absolute page number into the aux-file. So no package is needed to retrieve it. In the first compilation the value is 1073741823.
\documentclass{article}
\pagenumbering{Roman}
\begin{document}

\makeatletter
absolute page number: \@abspage@last\\
\ifnum\@abspage@last=3 ok \else not ok \fi\\
\makeatother
first page
\clearpage
second page
\clearpage
third page
\end{document}


text:
Q: Working Around Maximum Series Size on Chart I would like to take advantage of the following posting:
C#/Excel: Working Around Maximum Series Size On Chart
Was wondering if someone can include the steps to actually running this macro and producing graph? I opened developer/Visual basic, selected my sheet (where my long column of data resides). Pasted Vincent's code into code window. Guess I should not be surprised that VBA is not recognizing C code.

A: It appears that you cannot run C# code directly from Excel workbook (as you can VBA code).
You can do the reverse: access Excel workbook from C# code (i.e. from Microsoft Visual Studio).


text:
Q: How to handle missing values in linear regression? I have a data frame with 60 variables and all variables have missing values in a way that none of the lines are complete:
complete.cases(data)
  [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
 [28] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
 [55] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
 [82] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE
[109] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[136] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE

So I guess I cannot use linear regression to impute missing values. Any idea how I can handle them so that I can perform my linear regression?

A: Handling missing values may include:

*

*It's the best to omit variables for which most observations are missing.

*Omitting the rows/observations/cases with missing values. This strategy is referenced as listwise deletion or complete case analysis. This is a possibility, if the type of missingness is MCAR (Missing Completely At Random), and there are still large enough sample after the deletions.

*Different imputation techniques: mean/median/mode substitution, regression inputation, expectation-maximization (EM), multiple inputation, etc.


text:
Q: Notation of definition As far as I know, there are several notations of equality by definition,
i.e.
$:=$, $\equiv$, $ \buildrel\triangle\over =$,$=$
What is the difference between each one?

A: Like @Travis said, the symbols generally depend on the context they're used in. You'd really have to look to the specific book or person using the symbol to know for sure.
That being said, in general, I've seen the symbols used like so:
$:=$ is "defined as" where you're declaring a statement $$x := y$$ means $x$ is defined as $y$, or $x$ is just another way to say $y$. Like others have said, I've usually used it in computer science, or computational mathematics applications.
$\equiv$ is "equivalent to" or congruent to, often used like so: $$x\equiv a\>\; (\text{mod} \;b)$$
$\buildrel\triangle\over =$ is "equal to by definition". I guess if you were trying to be really nitpicky, it might not technically be the same as defining the statement outright, you're just invoking the definition. But again, it depends on the application.


text:
Q: Wrong orientation of body box I am using the fancyhdr package to create a specific headline and footline.
My code:
\begin{document}
    \renewcommand\headrule{\textcolor{gray!60}{\rule{\textwidth}{.5pt}}}%
    \renewcommand{\footrule}{\textcolor{gray!60}{\rule{\textwidth}{.5pt}}}%
    \pagenumbering{arabic}
    \rfoot{\textcolor{gray}{\small Site: \thepage}}
    \lhead{\textcolor{gray}{\small \@title}}
    \rhead{\begin{tikzpicture}%
                \node[opacity=.4]{\includegraphics[width=.08\linewidth]{img/logo}};
           \end{tikzpicture}}
    \newgeometry{bottom = 5cm}

    My text appears here

    \newpage

    Now my text appears at the right position
\end{document}

But the text of the first page is printed into the headline. After the use of \newpage, the Text is printed as expected.
My first page:

My seccond page:

How to justify the position of the body box directly?
WikiPedia Logo from: https://commons.wikimedia.org/wiki/File:Logo_de_wikipedia.png
License: Wikimedia Foundation [CC BY-SA 3.0 (https://creativecommons.org/licenses/by-sa/3.0)]
A whole example for coppy and post:
\documentclass{scrartcl}

\title{My title}
\author{Ahrtaler}
\usepackage[english]{babel}
\usepackage{graphicx}
\usepackage[a4paper]{geometry}
\usepackage{xcolor}
\usepackage{tikz}
\usepackage{fancyhdr}
\usepackage[export]{adjustbox}
\usepackage{showframe}

\pagestyle{fancy}
\fancyhf{}

\renewcommand\headrule{\textcolor{gray!60}{\rule{\textwidth}{0pt}}}%

\begin{document}
\newgeometry{bottom = 15mm}
\pagenumbering{gobble}

\makeatletter
\centering

\vspace{3.5cm}
\Large\textbf{\@title}
\normalsize
\vfill
\raggedright
\textbf{Date:}\\
\hspace{.5cm}\@date

\vspace{1cm}
\textbf{Author:}\\
\hspace{.5cm} \@author

\centering
\includegraphics[width=0.1\linewidth]{example-image}

    \raggedright

\pagebreak

\renewcommand\headrule{\textcolor{gray!60}{\rule{\textwidth}{.5pt}}}%
\renewcommand{\footrule}{\textcolor{gray!60}{\rule{\textwidth}{.5pt}}}%
\pagenumbering{arabic}
\rfoot{\textcolor{gray}{\small Site: \thepage}}
\lhead{\textcolor{gray}{\small \@title}}
\rhead{\begin{tikzpicture}%
            \node[opacity=.4]{\includegraphics[width=.08\linewidth]{example-image}};
       \end{tikzpicture}}
\newgeometry{bottom = 5cm}

My text appears here

\newpage

Now my text appears at the right position
\end{document}


text:
Q: Sakila db SQL find total combined film length of Sci-Fi films for every actor For reference I am working on the Sakila rental DVD database outlined here (#2):
Basically, I am trying to make a query to list every actor and their total run time of sci-fi films they've been in. They should be in the table with a total run time of NULL or 0 if they've never been in a sci-fi film.
I was able to figure out how to get a list of actors who HAVE been in sci-fi but I'm not sure where I'm going wrong to exclude any actors who haven't been in a sci-fi film.
SELECT act.first_name, act.last_name, SUM(fm.length)
FROM film fm
INNER JOIN film_actor fa ON fa.film_id = fm.film_id
INNER JOIN actor act ON fa.actor_id = act.actor_id
INNER JOIN film_category fc ON fm.film_id = fc.film_id
INNER JOIN category cat ON fc.category_id = cat.category_id AND cat.name = 'Sci-Fi'
GROUP BY act.first_name, act.last_name
ORDER BY act.last_name ASC

I have tried changing to LEFT JOINs for the two rows that get the actors (the first two joins) as I thought that might solve the issue of actors without the film not being included but I ended up with the same results.

A: How about a subquery that aggregates by category before you do the left loin:
SELECT
  act.first_name,
  act.last_name,
  cat_aggregate.sum_length
FROM
  actor act
  LEFT JOIN (
    SELECT
      cat.name,
      fa.actor_id,
      SUM(fm.length) sum_length
    FROM
      film fm
      INNER JOIN film_actor    fa ON fa.film_id = fm.film_id
      INNER JOIN film_category fc ON fc.film_id = fm.film_id
      INNER JOIN category     cat ON cat.category_id = fc.category_id
    GROUP BY
      cat.name,
      fa.actor_id
  ) cat_aggregate ON cat_aggregate.actor_id = act.actor_id
WHERE
  cat_aggregate.cat_name = 'Sci-Fi'
ORDER BY
  act.last_name,
  act.first_name

Actors with no appearance in a Sci-Fi movie will show up with a sum_length of NULL.
If you want you can move the WHERE cat_aggregate.cat_name = 'Sci-Fi' into the sub-query as WHERE cat.name = 'Sci-Fi'.


text:
Q: How do you find which database a table is located in, of which you know the name (e.g. dbo.mytable1), in Microsoft SQL Server Management Studio 2005? I know the name of the table I want to find.  I'm using Microsoft SQL Server Management Studio 2005, and I want to search all databases in the database server that I'm attached to in the studio.  Is this possible?  Do I need to query the system tables?

A: You can use the sp_MSforeacheachdb.
sp_MSforeachdb 'IF EXISTS(SELECT * FROM sys.tables WHERE [Name] = ''TableName'') PRINT ''?''';

A: As above but use system function not system tables
EXEC sp_MSForEachDB 'USE [?] IF OBJECT_ID(''dbo.mytable'') IS NOT NULL PRINT ''?'''

A: use master
DECLARE @db_name varchar(128)
DECLARE @DbID int
DECLARE @sql_string nvarchar(4000)
DECLARE @TableName varchar(30)
Select @TableName = ''
set nocount on
CREATE TABLE [#tblDatabaseName] (
    [DbName] [varchar] (128) NOT NULL ,
    [TableName] [varchar] (128) NOT NULL  )
declare db_cursor cursor forward_only for
SELECT  name, DbID
FROM    master..sysdatabases
WHERE   name NOT IN ('northwind', 'pubs')
AND     (status & 32) <> 32        --loading.
AND (status & 64) <> 64        --pre recovery.
AND (status & 128) <> 128      --recovering.
AND (status & 256) <> 256      --not recovered.
AND (status & 512) <> 512      --Offline
AND (status & 32768) <> 32768  --emergency mode.
AND     DbID > 4

open db_cursor
fetch next from db_cursor into @db_name, @DbID
while @@FETCH_STATUS = 0
begin
set @sql_string = ''
+'  Insert into #tblDatabaseName '
+'  select  ''' + @db_name + ''' as ''DbName'',  '
+'          o.name as ''TableName''  '
+'  from               [' + @db_name + ']..sysobjects   o with(nolock)  '
+'  where   o.name like ''' + @TableName + '''  '

execute sp_executesql @sql_string

fetch next from db_cursor into @db_name, @DbID

end
deallocate db_cursor
select * from #tblDatabaseName
drop table #tblDatabaseName

A: sp_MSForEachDB is an undocumented proc that could do this for you. Getting the output out is a little harder so I'll leave that for you.
EXEC sp_MSForEachDB 'USE [?] IF EXISTS(SELECT * FROM Sys.Objects WHERE Type = ''U'' AND Name = ''Product'') PRINT ''?'''


text:
Q: Group by in Orange, Data mining I have a dataset for a supermarket, each transaction containing an item is represented in a row. So, if transaction 1 contained milk, bread and coffee, the items are on a separate row and the attribute transaction occurs three times. What I want to do is to group transactions by item so that all the items are concatenated in one column. Then lastly apply association rules and separate each item in a column as an itemset. Is this even possible in Orange?
Worth mentioning, I managed to do this in RapidMiner easily with the same dataset. I used the Aggregate operator, concatenated the item attributes and then grouped by transactions.

A: If I understand this correctly, you wish to aggregate columns, not rows. If so, there's Aggregate Columns widget available for that. To perform Group by on rows, there's currently Pivot, which has a Group by output. We are working on a separate Group by widget, which should be available in the next release.


text:
Q: PHP Retrieve all keys of associate array based on search I have example array below:
Array
(
    [0] => Array
        (
            [name] => 'item-1'
            [type] => typeA
            [ids] => Array(123, 456, 999)
        )

    [1] => Array
        (
            [name] => 'item-2'
            [type] => typeA
            [ids] => Array(555, 4444, 666)
        )

    [2] => Array
        (
            [name] => 'item-3'
            [type] => typeB
            [ids] => null
        )
    [3] => Array
        (
            [name] => 'item-4'
            [type] => typeB
            [ids] => Array(555)
        )
 )

As an example, I want to search the array for all entries where type is typeA or id = 555.  I just need to retrieve the name fields (or at least the keys and from there the names).  In the hypothetical example, the search would result in item-1, item-2 and item-4
I tried a few different PHP functions. For example
$keys = array_keys(array_column($parent_array, 'type'), 'typeA');

The above works for retrieving keys when search is based on the [type] field.  But doesn't work for [ids].
Any suggestions?

A: I'm going to suggest using the function array_filter to perform your searching
The main element of this is the call back function with the type or id logic
function search_my_array( $array, $type, $id )
{
  return array_filter( $array, function( $item ) use ( $type, $id ){
    return $item['type'] === $type or ( is_array( $item['ids'] ) and in_array( $id, $item['ids'] ) );
  });
}

$array = array(
  array('name'=>'item-1','type'=>'typeA','ids'=>array(123,456,789)),
  array('name'=>'item-2','type'=>'typeA','ids'=>array(555,444,666)),
  array('name'=>'item-3','type'=>'typeB','ids'=>null),
  array('name'=>'item-4','type'=>'typeB','ids'=>array(555)),
);

$result = search_my_array( $array, 'typeA', 555 );

The result is the exact same array structure, just only with the three items you want, and then you can perform your array_column call
array_column( $result, 'name' );

Also if you don't always have the type or ids field, strengthen the validation with isset
return ( isset( $item['type'] ) and $item['type'] === $type ) or ( isset( $item['ids'] ) and is_array( $item['ids'] ) and in_array( $id, $item['ids'] ) );


text:
Q: How to multiply result of predicate in prolog? How to multiply or divide returned result of predicate in prolog?
For example, I have predicate which counts how many times some element appears in list. It looks like this :
elemCount(X, [X|T], N)

where X is the element, [X|T] is the list and N is count.
When my input is (3,[1,2,3],X) I get the result X=1. But is it possible to multiply result, for example, with 2 and instead of X=1 get X=2.
I tried something like this
elemCount(X,[X|T],2*N)

but without success.


text:
Q: how to access UITextField in AppDelegate method Hi I don't know how to access my UITextField from a AppDelegate method.
I have tried to add
@implementation TestAppDelegate

@synthesize textField;

But I still get an error. I just want to know if it's possible to access it from a AppDelegate method.

A: If you have UIViewController class in your project, and you are using interface builder, and you want access your UITextField from AppDelegate, your project should look something like this:
MyViewController.h
@interface MyViewController : UIViewController
@property (strong, nonatomic) IBOutlet UITextField *textField;
@end

MyAppDelegate.h
#include "MyViewController.h"
@interface MyAppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end

MyAppDelegate.m
@implementation MyAppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    MyViewController *viewController = (MyViewController *)[_window rootViewController];
    [[viewController textField] setText:@"It should work!"]
}
@end


text:
Q: ui-route not redirecting to external page From a modal dialog I present a general terms link that should redirect the user to a new page.
I would like to re-use my layout skeleton (background, logo ans basic styles) for the terms page, without the content of the master page (eg. search function, navigation etc). To achieve this I try to inject into a new window the terms template inside the ui-view="main" used for the normal site content (where is loaded the content of the modal dialog, as instance), but I get the error Could not resolve 'terms' from state 'login' (login is the current state where the modal dialog is).
Below the termsPage module with the ui-router state I would like to load:
angular.module('termsPage').config(function ($stateProvider) {
$stateProvider
    .state('terms', {
        url: '/terms',
        views: {
            'main': {
                controller: 'TermsCtrl as Terms',
                templateUrl: '/modules/staticPages/views/termsPage.html'
            }
        }
    });
});

My index.html file:

Below the app module and view, where the content of the application is correctly loaded. Also the modal dialog from which I would like to redirect to the external page is loaded here.
angular.module('app').config(function($stateProvider){
    $stateProvider
        .state('app', {
            url: '/app',
            views:{
                'main' : {
                    controller : 'AppCtrl',
                    templateUrl: 'modules/app/views/app.html'
                }
            }
        });
});

Below app.html:

My goal would be to create a sibling of app.html, injecting in main placeholder the content of my general terms page. Inside the modal dialog controller I use $state.go for the redirection:
$state.go('terms');

A: In my case the problem was that I did not registered the new module ('termsPage') as dependency in my main module:
angular.module('myApp', ['login','forms','termsPage'], function($urlRouterProvider){ ...}
Now that the module is registered, I can navigate correctly to state 'terms'.
Hopefully the case above might help someone else, getting hints for his/her case.


text:
Q: In GNU/Linux, is there a preformace benefit of using pthread_cond_t instead of an array of semaphores? In the following scheme: awakening N control threads, then waiting for all of them to finish with that work, then repeating (finitely many times), is there a performance benefit (less time is spent on synchronizatoin) in using a single pthread_cond_t (with the corresponding mutex and plain variables to store whether the condition has happened) instead of 2 arrays of binary semaphores (2 per thread)?.
In the current solution, I'm using semaphores. To awake the threads from the control thread, I post to each thread corresponding "wake" semaphore. To synchronize the worker threads with the control thread, in the control thread I wait for each thread "done" binary semaphore. The worker threads are themselves in as loop as well; for each iteration, they wait on the "wake-up" semaphore and post on the "done" semaphore.
I suppose that using an array of semaphores uses more memory. I can't benchmark a meaningful difference because my development environment supports 2 hardware threads, and the code is intended to run on environments with much more (64). Does pthread_cond_t has to do something similar that offsets the performance advantages of using a synchronization structure instead of an array of semaphores?.
Thanks in advance.


text:
Q: Heading is overlapping on my website, it is overlapping itself? The heading is overlapping over itself, I don't know how to fix this. Here's a screenshot I've included -> https://drive.google.com/file/d/16mkj7Uapba3MRWGD7vabiCvcfNxO0jeG/view?usp=sharing
I tried
 tags but nothing worked.

Top Best Offline Music Players for Android in 2019

A: Try setting line-height: normal

A: You should reset your line height to stop the overlapping in the page


text:
Q: Sharing an LDAP connection between classes - best practices? What I need to do is connect to an LDAP, and then pass this connection to several classes, which do various steps of processing.
The problem I face is if I should pass the connection to these classes via the constructor, or if every class should manage his own connection.
The problem I see with the first approach is that the caller may not know that he is responsible for closing the stream by itself. The second approach also doesn't seem appropriate because opening/closing/reopening the connection also makes no sense.
Any ideas on this?

A: I don't know why you'd have several classes dealing with an LDAP.  Maybe you should consider combining those scattered operations into a single class that has all responsibility for LDAP operations.
If that's not possible, your instincts are correct.  The class that opens the connection should close it in a finally block.  That should be the interface-based POJO service class that knows about the unit of work for that use case.  There should be no doubt about where the responsibility lies.  If you don't have such a service, create one.
If the operations aren't part of a single unit of work, then they should be managed by separate services.  The comments from the previous paragraph still apply.
Are you pooling your LDAP connections?  I hope so.
I'd recommend looking at the Spring LDAP module, especially if you're already a Spring user.  It makes dealing with LDAP resources easy, the same way it does JDBC.

A: It is a poor practice to construct a utility class, or any other class that provides a wide variety of services. Classes should provide a single service or group of tightly controlled services, else you may as well go back to FORTRAN garbage common blocks. To share an LDAP connection between classes, encapsulate the connection (this will also serve the purpose of hiding the API details).  Then protect the methods as necessary by authenticating using accounts on the directory server. For example, a close() method should be required to authenticate to an account that has close privileges, or is the member of a close group, or whatever authn/authz you prefer. You should use the UnboundID LDAP SDK for this type of work. See also "LDAP: Programming Practices".


text:
Q: Rust async_trait return `impl Stream`? I want to write a mock for an existing async class, without changing the original class to much.
To demonstrate my problem I took the source code from Guillaume Endignoux Blog.
I want to change it to an async trait:
use std::time::{Duration, Instant};

use async_trait::async_trait;
use futures::{StreamExt as _, Stream, stream};
use lazy_static::lazy_static;
use rand::distributions::{Uniform, Distribution as _};
use tokio::time::sleep;

lazy_static! {
    static ref START_TIME: Instant = Instant::now();
}

struct Pages;

#[tokio::main]
async fn main() {
    println!("First 10 pages:\n{:?}", Pages::get_n_pages(10).await);
}

#[async_trait]
trait Page {
    async fn get_page(i: usize) -> Vec<usize>;
    async fn get_n_pages(n: usize) -> Vec<Vec<usize>>;
    fn get_pages() -> impl Stream<Item = Vec<usize>>;
}

#[async_trait]
impl Page for Pages {

    async fn get_page(i: usize) -> Vec<usize> {
        let millis = Uniform::from(0..10).sample(&mut rand::thread_rng());
        println!(
            "[{}] # get_page({}) will complete in {} ms",
            START_TIME.elapsed().as_millis(),
            i,
            millis
        );

        sleep(Duration::from_millis(millis)).await;
        println!(
            "[{}] # get_page({}) completed",
            START_TIME.elapsed().as_millis(),
            i
        );

        (10 * i..10 * (i + 1)).collect()
    }

    async fn get_n_pages(n: usize) -> Vec<Vec<usize>> {
        Self::get_pages().take(n).collect().await
    }

    fn get_pages() -> impl Stream<Item = Vec<usize>> {
        stream::iter(0..).then(|i| Self::get_page(i))
    }
}

But then I get the message:  `impl Trait` only allowed in function and inherent method return types, not in `impl` method return.
So I change it to dyn, but then I get the message: doesn't have a size known at compile-time.
Is there a way to write async traits that return a kind of impl Stream<Item = Vec<usize>>?

A: There is an unstable feature allowing impl Trait in return positions of traits, return_position_impl_trait_in_trait. With it you can
use your initial syntax at the cost of running nightly:
#![feature(return_position_impl_trait_in_trait)]

use async_trait::async_trait;
use futures::{StreamExt as _, Stream, stream};

#[async_trait]
impl Page for Pages {
    //...
    fn get_pages() -> impl Stream<Item = Vec<usize>> {
        stream::iter(0..).then(|i| Self::get_page(i))
    }
}

Playground


text:
Q: Deleting content from media storage with React-Native-FS Currently I am able to use RNFS.unlink('file path'), but this only deletes the file on disk.
How can I use RNFS to also delete the media content from the phone's gallery with a content path such as'content://media/external/images/media/#####'?


text:
Q: How do I use Excel VBA to copy specific cells from two workbooks and combine them into one? I have two excel workbooks that I am trying to read from. I need to read from a column in the first one, and compare that field to a field in the second workbook. If there is a match, I want to copy the original row to a new excel workbook, and append the name with a piece of another column. Furthermore, if another column in that row is filled, I need to duplicate the original row again into the new workbook, and append that name. That will happen up to 20 times per row, but not always.
Basically, I need to do something like this:
Workbook A:

Name         OtherData1     OtherData2
--------     ----------     ----------
Railroad     Data           Data
MailRoute    Data           Data
BoatPath     Data           Data

Workbook B:

Name          rtuTopic[1]   rtuTopic[2]   [.....]   rtuTopic[20]
--------      --------      --------                --------
Railroad      Route_01      Route_05                Route_21
MailRoute     Route_12      NULL                    NULL
BoatPath      Route_01      Route_15                NULL

Workbook C (the result I want)

Name            OtherData1     OtherData2     rtuTopic
--------        ----------     ----------     --------
Railroad_01     Data           Data           Route_01
Railroad_05     Data           Data           Route_05
...........
Railroad_21     Data           Data           Route_21
MailRoute_12    Data           Data           Route_12
BoatPath_01     Data           Data           Route_01
BoatPath_15     Data           Data           Route_15

The columns I need to append are not conveniently next to one another. They are separated by 5 or 6 other columns, give or take, and I don't know where to get started. I searched around and saw how to copy entire sheets from one workbook to another, but I didn't see how to really specifically dig down and duplicate a row the way I need to.

A: It seems more like you are asking for a solution to be written for you rather than asking a specific question but here are some pointers to get you going:
Assuming the other workbooks are already open you can refer to the otherbooks using the workbooks list i.e.
Dim workBookA As Workbook
Dim workBookB As Workbook
Dim workBookC As Workbook

Set workBookA = Workbooks("Workbook A")
Set workBookB = Workbooks("Workbook B")
Set workBookC = Workbooks("Workbook C")

The sheets in those workbooks can be referenced using the name of the sheet i.e. if you want a sheet called "Main" on Workbook A then you could use:
workBookA.Sheets("Main").Activate

Copying one column from the sheet to one call "Report" on Workbook C could be done like:
workBookA.Sheets("Main").Range("a1", workBookA.Sheets("Main").Range("a1").End(xlDown)).Copy
workBookC.Sheets("Report").Range("a1").PasteSpecial

or if this is easier to follow
workBookA.Sheets("Main").Activate
Range("a1", Range("a1").End(xlDown)).Copy
workBookC.Sheets("Report").Activate
Range("a1").PasteSpecial

Good luck


text:
Q: jQuery Mobile iScrollView error I am using jQuery Mobile and iScrollview together,
I used iscrollView
The scrolling work fine.
Problem 1:
when I click on a input text/password field, I get an extra box overlapping the whole elements, which has the same content as the input.
same problem found in
here no solution
Problem 2:
when navigating to next page, the previous page remains behind new page and when tap the mobile screen the previous page goes off from the device. this is not happening in the webbrowsers.
Any suggestions,
code for main.js
 require.config({
    paths: {
        jquery: '../lib/jquery',
        'jquery.mobile-config': 'helper/jqm-config',
        'jquery.mobile': '../lib/jquery.mobile-1.2.1.min',
        underscore: '../lib/underscore-min',
        backbone: '../lib/backbone-min',
        templates: '../templates',
        text: 'helper/text',
        config: 'helper/config',
        'backbone.subroute': '../lib/backbone.subroute',
        'cookie': '../lib/jquery.cookie',
         'maskInput': '../lib/Jquerymaskinput',
        'iscroll': '../lib/iscroll',
        'iscrollview': '../lib/jquery.mobile.iscrollview',
            }
    ,
    shim: {
        'underscore': {
            exports: "_"
        },
        'backbone': {
            //These script dependencies should be loaded before loading
            //backbone.js
            deps: ['jquery', 'underscore'],
            //Once loaded, use the global 'Backbone' as the
            //module value.
            exports: 'Backbone'
        },
        'jquery.mobile-config': ['jquery'],
        'jquery.mobile': ['jquery', 'jquery.mobile-config'],
        'backbone.subroute': ['jquery', 'underscore', 'backbone'],
        //'backbone.oauth':['jquery','underscore','backbone'],
        'iscroll': {
            deps: ['jquery.mobile']
        },
        'iscrollview': {
            deps: ['iscroll']
        },
        'config': {
            exports: 'Config'
        }

    }

});
requirejs(['jquery', 'iscroll', 'jquery.mobile', 'iscrollview'], function($, iScroll) {
    var elements = jQuery(document).find(":jqmData(iscroll)");
    elements.iscrollview();

});

require([
    'app'

], function(App) {
    App.initialize();
});

for router
define([
    'jquery',
    'underscore',
    'backbone',
    'backbone.subroute'
], function($, _, Backbone) {
    var AppRouter = Backbone.Router.extend({
        routes: {
            // general routes
            '': 'defaultAction',
            'login':'login',
            'menu': 'mainMenu',

            // Default
            '*actions': 'defaultAction'
        }
    });

    var initialize = function() {

            $('.back').live('click', function(event) {
                event.preventDefault();
                window.history.back();
                return false;
            });

        var app_router = new AppRouter;
        app_router.on('route:defaultAction', function(actions) {
            require(['views/home/register'], function(RegisterView) {
                // We have no matching route, lets display the home page
                console.log('At defaultAction');
            var registerView = new RegisterView();
            registerView.render();
               /// this.changePage(loginView, 'slide');
            });
        });
         app_router.on('route:login', function(actions) {
            require(['views/home/login'], function(LoginView) {
                // We have no matching route, lets display the home page
                console.log('At defaultAction');
            var loginView = new LoginView();
            loginView.render();
               /// this.changePage(loginView, 'slide');
            });
        });
        app_router.on('route:mainMenu', function(actions) {
            require(['views/home/menu'], function(MainMenuView) {
                console.log('At mainMenu::router');
            var mainMenuView = new MainMenuView();
            mainMenuView.render();
              //  this.changePage(mainMenuView, 'slide');
    });
        });

        Backbone.history.start();
    };
    return {
        initialize: initialize
    };
});

A: I rewrite the codes but, its more or less solved my problem updated the jqm to 1.3 and jquery to 1.9.
rewrite all css files.
Navigation to next page is fine
and at least its working now.
Thanks to Omar who helped me.
gracias mi amigo


text:
Q: JavaScript: Variable inside function is not accessible. Please explain behavior I have following code snippet to be executed,
function OuterFn(){
        var slices = 0; // variable inside Outer function
        this.getSlices = function(){
            return slices;
        }
        this.slice = function(){
            slices++;
        }
    }
    var outerFn = new OuterFn();
    console.log(outerFn.getSlices());
    console.log(outerFn.slices); // print outer function variable

Why output of this code is:
0
undefined


text:
Q: P2P from behind of routers I want to make an application for transferring data P2P. Is there a way to dynamically unlock data port in router to make connection (if it's not set manually)? Is there protocol to do it? How can I use it in cpp?

A: You can try UPnP, it has the ability to forward ports if the router supports it.
If you're looking for a free library, there's a few, like
GUPnP: https://live.gnome.org/GUPnP/
or libupnp: http://pupnp.sourceforge.net/


text:
Q: Save dataframes to csv from a pdf I am trying to extract tables from a pdf I use camelot library. Already, I am working on the first page of the pdf. There is 3 tables on this page whose 1 useless.
I did this script :
from pathlib import Path
import os
import shutil
import camelot
import pandas as pd

p = Path.cwd()
save_path= p.joinpath("Tables_csv")

tables = camelot.read_pdf("file.pdf", pages = "1",line_scale = 20)

for i in range(len(tables)):
    s = tables[i]
    sheet = s.df

    print(sheet.head)

    if sheet.head == ["a", "b", "c"]:
        sheet.to_csv(f"abcTable{i}.csv")
        shutil.move(sheet, save_path)
    elif sheet.head == ["d", "e", "f"]:
        sheet.to_csv(f"defTable{i}.csv")
        shutil.move(sheet, save_path)

I want to save in csv ["a", "b", "c"] and ["d", "e", "f"] dataframe and in an other folder. But no files are saved (I tried in the current folder too).
I have an idea why this is not working as I want, when I print(sheet.head) it shows all the dataframe between <>.
Thanks in advance.

A: This
sheet.head != ["a", "b", "c"] or ["d", "e", "f"]

is interpreted by python as
(sheet.head != ["a", "b", "c"]) or ["d", "e", "f"]

due to Operator precedence which always is true as non-empty list is considered to be truthy. Is your aim for this condition to be always True?
sheet.drop

Here you are just accessing drop. If drop is method of sheet is your aim to merely access it rather than calling it?
for i in range(len(tables)):
    ...
    for i in sheet:
        sheet.to_csv(f"sheet{i}.csv")

You use i for both loops, this is legal, but when you refence i inside nested for loop it pertains solely to inner loop, there is no way to easily access i of outside loop. Is that your aim?


text:
Q: How to import NumPy in the Python shell I have tried importing NumPy in Python, but it did not succeed:
>>> import numpy as np
    x=np.array([[7,8,5],[3,5,7]],np.int32)

   Traceback (most recent call last):
   File "<pyshell#3>", line 1, in <module>
   import numpy as np
   File "C:\Python27\lib\numpy\__init__.py", line 127, in <module>
   raise ImportError(msg)
   ImportError: Error importing numpy: you should not try to import numpy from
   its source directory; please exit the numpy source tree, and relaunch
   your Python interpreter from there.

How can I fix this?

A: The message is fairly self-explanatory; your working directory should not be the NumPy source directory when you invoke Python; NumPy should be installed and your working directory should be anything but the directory where it lives.

A: On Debian/Ubuntu:
aptitude install python-numpy

On Windows, download the installer:
http://sourceforge.net/projects/numpy/files/NumPy/

On other systems, download the tar.gz and run the following:
$ tar xfz numpy-n.m.tar.gz
$ cd numpy-n.m
$ python setup.py install


text:
Q: Physical application/interpretation of union and intersection (case example)
Suppose that one card is to be selected from a deck of 20 cards that contains 10 red cards numbered from 1 to 10 and 10 blue cards numbered from 1 to 10.  Let A be the event that a card with an even number is selected, let B be the event that a blue card is selected, and let C be the event that a card with a number less than 5 is selected.   Describe the sample space S and describe each of the following events both in words and as as a subset of S:
a.  $A \cap B \cap C$
b.  $B \cap C'$
c.  $A \cup B \cup C$
d.  $A \cap (B \cup C)$
e.  $A' \cap B' \cap C'$

So as a summary:
A=Even # card
B= Blue card
C= Card # < 5 so its {1,2,3,4}

a.  even, blue card is selected and its value is less than 5 so its either 2 or 4.
b.  blue card selected and its value is 5,6,7,8,9 or 10.
e.  odd, red card, whose value is greater than or equal to 5 so its value is 5,7 or 9.

Now the union questions throw me off.  When you say $A \cup B$, this means A alone, B alone, or BOTH.
So for part (c), I thought it would mean the following:  Either odd or even, blue or red, and number including 1-10.  But this isn't right.
I'm not sure how to interpret (d) either.  Can someone please step by step explain the thought process to interpret (c) and (d)?
Thank you in advance.

A: For (c), you have cards which are either even, blue, or numbered less than 5;  so the only cards which do NOT satisfy this property are red cards which are odd and numbered 5, ..., 10.  Therefore this gives all cards EXCEPT red cards numbered 5, 7, or 9.
For (d), you have cards which are even and also are either blue or numbered 1,...,4.  This is the same as all blue even cards AND all red cards numbered 2 or 4.

A: An element is part of the union of the sets $A_1,A_2...A_n$ if it's part of at least one of the sets $A_1,A_2...A_n$
So in the case $c)$ we have:
In order a card to be part of the subset $S = A \cup B \cup C$ it need to be part in at least one of the sets $A,B,C$
This means that the subset S contains every even number card (because every even numberd card is part of the set A), every blue card (every blue card is part of the set B) and every card with number smaller than 5 (because such card is part of the set C).
This means that every card except for $5RED$,$7RED$ and $9RED$ is part of the subset S.
And for $d)$ we have:
Let $S_1$ = $B \cup C$. Now we now that every blue card and every red card with number smaller than 5 is part of $S_1$. Now let $S = A \cap S_1$. We need to find every even numbered card in the subset $S_1$. So the subset $S$ consists of blue cards with number $2,4,6,8,10$ and red cards with number $2,4$


text:
Q: NS-3: Create a Bottleneck Link I have a client and a server, both running the Multipath TCP stack. Multiple point to point links are created between them, I want the links to share a bottleneck link before reaching the server. I looked here, but the situation is less complex than mine.
Below is the code that runs MPTCP. Could you suggest how should I make the changes to create the required topology. I am a bit confused on this. Thanks a lot for your help.
Here is the code for Topology that I have.
NodeContainer nodes;
nodes.Create(2);
client = nodes.Get(0);
server = nodes.Get(1);

MpInternetStackHelper stack;
stack.Install(client); stack.Install(server);

vector<Ipv4InterfaceContainer> ipv4Ints;
for(int i=0; i < sf; i++)
{
    PointToPointHelper p2plink;
    p2plink.SetDeviceAttribute ("DataRate", StringValue("5Mbps"));
    p2plink.SetChannelAttribute("Delay", StringValue("100ms"));

    NetDeviceContainer netDevices;
    netDevices = p2plink.Install(nodes);

    std::stringstream netAddr;
    netAddr << "10.1." << (i+1) << ".0";
    string str = netAddr.str();

    Ipv4AddressHelper ipv4addr;
    ipv4addr.SetBase(str.c_str(), "255.255.255.0");
    Ipv4InterfaceContainer interface = ipv4addr.Assign(netDevices);
    ipv4Ints.insert(ipv4Ints.end(), interface);
}


text:
Q: Xamarin Listview child binding data not being sent back to View Modal We have a child (syncfusion) combobox control in our Xamarin project that resides inside a parent ListView element as shown below.
<ListView x:Name="llistView" ItemsSource="{Binding QuantityRows}" HasUnevenRows="True" SeparatorVisibility="None" SelectionMode="None">
        <ListView.ItemTemplate>
            <DataTemplate>
                  <ViewCell>
                    <StackLayout VerticalOptions="Start" HorizontalOptions="Start" Padding="30">
                        <Label Text="{Binding FieldDescription}"></Label>
                        <combobox:SfComboBox HeightRequest="40" x:Name="comboBox"  SelectedValue="{Binding ItemSelectedFromList}" IsVisible="False" DisplayMemberPath = "Name" DataSource="{Binding Listing, Mode=TwoWay}">
                            <combobox:SfComboBox.Triggers>
                                <DataTrigger TargetType="combobox:SfComboBox"
                                Binding="{Binding FieldStringType}"
                                   Value="picklist">
                                    <Setter Property="IsVisible" Value="true" />
                                </DataTrigger>
                            </combobox:SfComboBox.Triggers>
                        </combobox:SfComboBox>
           </StackLayout>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

As shown above, the combobox is bound to the viewmodel object ItemSelectedFromList.  When we run this with the combobox outside the listview, the two way binding is perfect, and it sends back the data back correctly. However, when the combobox is put into the listview, the data can be bound from the view modal, however, when a change is made on the combobox, the data never gets sent to the view model.  Looking closer, it seems that the event does get triggered, as we tried using the handler below, and found that it does get hit when an item is selected in the combobox
 private void DataPickList_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

However the event never gets sent back to the actual viewmodel it's bound to, when it's inside the listview (Although, the event below does get hit when the control is not in the listview)
  FormattedOptions itemSelectedFromList;
        public FormattedOptions ItemSelectedFromList
        {
            get => this.itemSelectedFromList;
            set => this.RaiseAndSetIfChanged(ref this.itemSelectedFromList, value);
        }

Note that the issue is not specific to just this combolist control.  It seems that any control inside the listview doesn't get the data sent to the viewmodel.  Is there any fix or way around this?
UPDATE
As per the comment below, we added a x:Name and reference to the view model, however it the change event doesn't still doesn't get hit:
<combobox:SfComboBox HeightRequest="40" x:Name="comboBox" SelectedValue= "{Binding Source={x:Reference PagesName}, Path=BindingContext.ItemSelectedFromList}"  IsVisible="False" DisplayMemberPath = "Name" DataSource="{Binding Listing, Mode=TwoWay}">

Which references the x:Name attribute on the page
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             ....
             x:Name="PagesName">


text:
Q: Second-order non-linear differential equation with polynomial of the derivative My economic model yields the following second-order differential equation:
$$ c_1 (y(x)-1)y'(x) - (c_2 x + x^3 (c_3y(x)-c_4))y'(x)^2+c_5 x^3y'(x)^3 + xy''(x)(y(x)-1)(c_6 + x^2(c_7y(x) - c_8))=0$$
where $c_1, c_2, \ldots$ are known constants an $y(x)$ is the function of interest (it's actually a cdf, so this eventually imposes some boundary conditions).
What is the correct term for such an equation? How can it be solved?


text:
Q: Wordpress Custom Taxonomy on front-page I have registered a custom post type "Projects" and also registered a custom taxonomy for that Post Type called "Project Categories".  On my home page I have a div in which I would like to list all projects and terms fro the "Project Categories" taxonomy. Currently, I am only able to get the lists of the terms.  Can someone tell me why I am unable to get the terms to display. Currently, I have:

    <?php
    query_posts( array( 'post_type' => 'projects' ) );
    if ( have_posts() ) : while ( have_posts() ) : the_post();
    ?>

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

    <?php endwhile; endif; wp_reset_query(); ?>
    <?php $taxonomy = 'project_categories';
    $tax_terms = get_terms($taxonomy);
                            ?>
    <?php foreach ($tax_terms as $cat): ?>

<?php $cat; ?>

    <?php endforeach; ?>

Another question I have is, is it better to include the taxonomies inside or outside of the query_posts loop?

A: get_terms($taxonomy) returns a array of objects (see get_terms() in WP Codex), so in order to print the name you should use <?php echo $cat->name ?> (and don't forget the echo).
I tried to correct your code. See comments within the code block for details:
<?php
    // keep your queries outside the loop for more readable code
    query_posts( array( 'post_type' => 'projects' ) );
    $taxonomy = 'project_categories';
    $tax_terms = get_terms($taxonomy);
?>

    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

<a href="<?php echo get_the_permalink(); ?>"><?php the_title(); ?>

    <?php endwhile; endif; ?>
    <?php foreach ($tax_terms as $cat): ?>

<?php echo $cat->name; ?>

    <?php endforeach; ?>

<?php wp_reset_query(); ?>

Sidenote: Either you use <?php the_permalink(); ?> or you use <a href="<?php echo get_the_permalink(); ?>"><?php the_title(); ?>. The former will do all the magic automatically, and is recommended in this case.


text:
Q: .htaccess causes 403 error I have a working website on a free shared server. I decided to hire a dedicated server and purchase a domain for my website. I started uploading the files but things aren't working the way they should.
First of all .htaccess is not working, however I set AllowOverride from None to All in /etc/apache2/sites-available/default
DocumentRoot /var/www
<Directory />
   Options FollowSymLinks
   AllowOverride None
</Directory>
<Directory /var/www/>
   Options Indexes FollowSymLinks MultiViews
   AllowOverride All
   Order allow,deny
   allow from all
</Directory>

I restarted the server of course.
I enabled mod_rewrite:
a2enmod rewrite

and restarted the server.
This change causes a 403 forbidden access error which I am unable to work out. If I change the All back to None then .htaccess is ignored so instead of loading the website the file hierarchy is loaded (the main page is index4.php which should be opened by .htaccess). If I rename index4.php to index.php the website loads, just fyi.
The permissions on the file is 600. If I change it to 444 I get 500 Internal Server Error.
I checked the logs and I see many errors of this:
Permission denied: file permissions deny server access: /var/www/index.html

A: Usually, 403 error caused by wrong permission. The proper permission under /var/www/ is 755 for folders and 644 for files.


text:
Q: Best way to learn React with Babel from scratch? I have an idea for a game and I will try to create it.
It is a simple multiplayer game that runs in a browser.
I was recommended to use React.js and Firebase.
So I paid 60 dollars for a video tutorial that built an app using these technologies, perfect! Unfortunately, it uses the JSX transformer that was deprecated, and now I have learned that I should use something called Babel instead.
What I wonder is if you can recommend me some tutorial that teach me React with Babel from scratch. I googled a lot but I could not find anything directed at noobs

A: If you take a look at the react site tutorial (http://facebook.github.io/react/docs/tutorial.html) they show a post JSX transformer method using babel. You should also look at some of the starter packages to see what style of organizing and building react works best for you. Here are a couple;
https://github.com/jmarkstevens/ReactPatterns

A: This isn't a forum for this sort of question and the question might get flagged as off-topic, but for what it's worth, since learning this stuff is hard for beginners, I suggest going to the redux library github page and watching the 30 free tutorial videos, then downloading the examples and using their 'webpack' configuration. The examples come with the pre-installed set of tools for transpiling JSX using Babel. You could look at the "counter" example since it doesn't have much redux at all (though I suggest using it anyways).
Otherwise you could be using gulp and browserify to babelify your code but again, the question is broad and should be more of a forum post so that a thread could be started for discussion.


text:
Q: Android Service: Detect if data connection is available either Wifi or Mobile Data How can I detect continuously or by schedule if data connection is available either Wifi or Mobile Data?
I need to detect it even if the app gets in foreground, background, or get killed by the system or user.
I already seen a lot of relevant question and sample code but they say that things have change in Android N and above for security reason.

A: //This is your service class working fine just add network state permission in your manifest and at runtime

    public class MyService extends Service {
        private static final String TAG = "MyService";
        private ServiceHandler serviceHandler;
        private static final int MSG_REQUEST = 1112;
        static Context context1;
        public static void startService(Context context) {
            context1=context;
            Intent myIntent = new Intent(context, MyService.class);
            context.startService(myIntent);
        }

        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }

        private class ServiceHandler extends Handler {
            ServiceHandler(Looper looper) {
                super(looper);
            }

            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case MSG_REQUEST:
                        checkNetwork();
                        break;
                }
            }
        }

        private void checkNetwork() {
        ConnectivityManager cm = (ConnectivityManager)context1.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = cm.getActiveNetworkInfo();
        String networkType = "";
        if (info.getType() == ConnectivityManager.TYPE_WIFI) {
            Log.d("yahooooooo","WIFI");
        }
        else if (info.getType() == ConnectivityManager.TYPE_MOBILE) {

            networkType = "mobile";
            Log.d("yahooooooo","MOBILE");
        }
     if (!serviceHandler.hasMessages(MSG_REQUEST)) {
            serviceHandler.sendEmptyMessageDelayed(MSG_REQUEST, 1000);//every 1 sec
        }

        }

        @Override
        public void onCreate() {
            super.onCreate();
            HandlerThread handlerThread = new HandlerThread(TAG, Process.THREAD_PRIORITY_BACKGROUND);
            handlerThread.start();
            serviceHandler = new ServiceHandler(handlerThread.getLooper());
        }

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            if (!serviceHandler.hasMessages(MSG_REQUEST)) {
                serviceHandler.sendEmptyMessage(MSG_REQUEST);
            }

            return START_REDELIVER_INTENT;
        }

        @Override
        public void onTaskRemoved(Intent rootIntent) {
            super.onTaskRemoved(rootIntent);

            PendingIntent service = PendingIntent.getService(
                    getApplicationContext(),
                    1001,
                    new Intent(getApplicationContext(), MyService.class),
                    PendingIntent.FLAG_ONE_SHOT);

            AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            assert alarmManager != null;
            alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 1000, service);
        }

    }

//  Now call the service from Activity
    MyService.startService(MainActivity.this);

//  In Manifest
    <service
    android:name=".MyService"
    tools:ignore="InnerclassSeparator" />

A: Try Below code....
    Boolean  bs_netcheck=false;
    bs_netcheck = netCheck();
    if(!bs_netcheck)
    {
        displayAlert();
    }

public void displayAlert()
{

    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    builder.setMessage("Internet Connection Required...! \nPlease Check Your Internet Connection and Try Again");
    TextView title = new TextView(MainActivity.this);
    title.setText("Network Error");
    title.setBackgroundColor(R.color.colorAccent);
    title.setPadding(20, 20, 20, 20);
    title.setGravity(Gravity.CENTER);
    title.setTextColor(Color.WHITE);
    title.setTextSize(20);
    builder.setCustomTitle(title)
            .setPositiveButton(android.R.string.ok,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton){
                            finishAffinity();
                        }
                    });
    builder.show();
}

public boolean netCheck()
{
    ConnectivityManager conMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

    assert conMgr != null;
    if ( conMgr.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED
            || conMgr.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED ) {
//notify user you are not online
        bs_netcheck =true;

    }
    return bs_netcheck;
}

Add Below permission in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />