Q: (AudioManager)getSystemService(Context.AUDIO_SERVICE) causing memory leak I had memory leak that was being caused by AudioManager. So I've commented out this line in my code to see if it would solve my problem:
public class FireRoomActivity extends Activity {

AudioManager am;
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
  }
}

And it did solve the problem and I don't have memory leak any more. Is that because of Context.AUDIO_SERVICE? If yes then how could I replace it?
If it matters, I have this non-static class inside my activity that is not used elsewhere outside
class GestureListener extends GestureDetector.SimpleOnGestureListener {
RelativeLayout parentLayout;

public void setLayout(RelativeLayout layout){
    parentLayout = layout;  }
@Override
public boolean onDown(MotionEvent e) {
    return true;
}
// event when double tap occurs
@Override
public boolean onDoubleTap(MotionEvent e) {
    makeArrowsVisible();
    parentLayout.findViewById(R.id.cabinet_zoomed).setVisibility(View.INVISIBLE);
    Button key = (Button)parentLayout.findViewById(R.id.key);
    if(key!=null){
        key.setVisibility(View.INVISIBLE);}
    return true;
}

Edit:
screenshot of heap dump

A: Fix mentioned in https://gist.github.com/jankovd/891d96f476f7a9ce24e2 worked for me.
public class ActivityUsingVideoView extends Activity {

  @Override protected void attachBaseContext(Context base) {
    super.attachBaseContext(AudioServiceActivityLeak.preventLeakOf(base));
  }
}

/**
 * Fixes a leak caused by AudioManager using an Activity context.
 * Tracked at https://android-review.googlesource.com/#/c/140481/1 and
 * https://github.com/square/leakcanary/issues/205
 */
public class AudioServiceActivityLeak extends ContextWrapper {

  AudioServiceActivityLeak(Context base) {
    super(base);
  }

  public static ContextWrapper preventLeakOf(Context base) {
    return new AudioServiceActivityLeak(base);
  }

  @Override public Object getSystemService(String name) {
    if (Context.AUDIO_SERVICE.equals(name)) {
      return getApplicationContext().getSystemService(name);
    }
    return super.getSystemService(name);
  }
}

Thanks to Dejan Jankov :)

A: You can avoid memory leak using application context to get audio service.

A: I found in another post that the AudioManager does keep a strong reference, but will still be properly garbage collected. See this google group conversation. Here's what I get out of it:
This means that if you manually launch a couple of garbage collections through the DDMS tab in Eclipse just before taking the head dump, this reference should not be there anymore.
This indeed solved the "problem" for me, as it turned out not to be a problem after all...
It was also mentionned that the debugger should not be on hook (i.e. use Run As... instead of Debug As...). The debugger being active could cause the references to be held by the AudioManager, thus creating a heap overflow (I have not tested this affirmation).


Q: Dynamically List contents of a table in database that continously updates It's kinda real-world problem and I believe the solution exists but couldn't find one.
So We, have a Database called Transactions that contains tables such as Positions, Securities, Bogies, Accounts, Commodities and so on being updated continuously every second whenever a new transaction happens. For the time being, We have replicated master database Transaction to a new database with name TRN on which we do all the querying and updating stuff.
We want a sort of monitoring system (  like htop process viewer in Linux) for Database that dynamically lists updated rows in tables of the database at any time.
TL;DR Is there any way to get a continuous updating list of rows in any table in the database?
Currently we are working on Sybase & Oracle DBMS on Linux (Ubuntu) platform but we would like to receive generic answers that concern most of the platform as well as DBMS's(including MySQL) and any tools, utilities or scripts that can do so that It can help us in future to easily migrate to other platforms and or DBMS as well.

A: To list updated rows, you conceptually need either of the two things:

*

*The updating statement's effect on the table.

*A previous version of the table to compare with.

How you get them and in what form is completely up to you.
The 1st option allows you to list updates with statement granularity while the 2nd is more suitable for time-based granularity.
Some options from the top of my head:

*

*Write to a temporary table

*Add a field with transaction id/timestamp

*Make clones of the table regularly

AFAICS, Oracle doesn't have built-in facilities to get the affected rows, only their count.

A: Not a lot of details in the question so not sure how much of this will be of use ...

*

*'Sybase' is mentioned but nothing is said about which Sybase RDBMS product (ASE? SQLAnywhere? IQ? Advantage?)

*by 'replicated master database transaction' I'm assuming this means the primary database is being replicated (as opposed to the database called 'master' in a Sybase ASE instance)

*no mention is made of what products/tools are being used to 'replicate' the transactions to the 'new database' named 'TRN'

So, assuming part of your environment includes Sybase(SAP) ASE ...

*

*MDA tables can be used to capture counters of DML operations (eg, insert/update/delete) over a given time period

*MDA tables can capture some SQL text, though the volume/quality could be in doubt if a) MDA is not configured properly and/or b) the DML operations are wrapped up in prepared statements, stored procs and triggers

*auditing could be enabled to capture some commands but again, volume/quality could be in doubt based on how the DML commands are executed

*also keep in mind that there's a performance hit for using MDA tables and/or auditing, with the level of performance degradation based on individual config settings and the volume of DML activity

Assuming you're using the Sybase(SAP) Replication Server product, those replicated transactions sent through repserver likely have all the info you need to know which tables/rows are being affected; so you have a couple options:

*

*route a copy of the transactions to another database where you can capture the transactions in whatever format you need [you'll need to design the database and/or any customized repserver function strings]

*consider using the Sybase(SAP) Real Time Data Streaming product (yeah, additional li$ence is required) which is specifically designed for scenarios like yours, ie, pull transactions off the repserver queues and format for use in downstream systems (eg, tibco/mqs, custom apps)

I'm not aware of any 'generic' products that work, out of the box, as per your (limited) requirements.  You're likely looking at some different solutions and/or customized code to cover your particular situation.


Q: New browser tabs for pdf files from glob-created list? To list a large number of sheet-music pdfs on a website, I'm using this at the top of my php/html file:
<?php
header('Content-Type: text/html; charset=utf-8');
function getFiles(){
    $files=array();
    if($dir=opendir('.')){
        while($file=readdir($dir)) {
            if($file!='.' && $file!='..'){
                $files[]=($file);
            }
        }
        closedir($dir);
    }
    natsort($files); //sort
    return $files;
}
?>

... then in the ul bit of the html section I have this:
 <? foreach (glob("*.pdf") as $file)
    echo "
$file
";
    ?>

It works fine, except that when clicked, the pdf replaces the web page content in the browser, and I would prefer it to appear in a separate browser tab.
I've tried inserting "_blank" in various places but it kills the page, so I'm obviously not doing it right (I'm a musician, not a programmer!).
Similar questions on here seem to relate to different set-ups and I don't have the knowledge to apply the answers to my situation.
How can I get my otherwise successful website set-up to trigger a new browser tab for each tune clicked?  Thanks.

A: "I've tried inserting "_blank" in various places" -- the correct place is in the a element:
The code of your template should read:
<?php
foreach (glob("*.pdf") as $file) {
    echo '
'.$file.'
';
}
?>


Q: Can we use props to pass variable in vue? Slall question:
I have a 2 parent components nesting the same child component inside of them.
I use props so the parents can tell the child what title to show.
this child component is a photo gallery. It makes a query to the database, download photos and show them up. classic.
I need the parents to tell the child where to get the photos from:
Get the photos from All users, for the home page
or
get only the photos from a specific user for a user's page.
I'm wondering if I can pass this information through a prop.
Is that possible? Can we use the info from a prop as a varialble inside of the setup() function?
Is there a better way to do this?

A: Passing objects from one component to a child component is the purpose of props.
You can pass many items through props. VueJS has the following types built-in:

*

*String

*Number

*Boolean

*Array

*Object

*Function

*Promise

In the V3 VueJS guide it gives the following example of a prop being passed into a component and then being logged to the console inside the setup() method.
export default {
  props: {
    title: String
  },
  setup(props) {
    console.log(props.title)
  }
}

However, when using props, you should always mark whether the is required, what its type is and what the default is if it is not required.
For example:
export default {
  props: {
    title: String, // This is the type
    required: false, // If the prop is required
    default: () => 'defaultText' // Default needed if required false
  },
  setup(props) {
    console.log(props.title)
  }
}

It's important to note that when using default, the value must be returned from a function. You cannot pass a default value directly.


Q: Uncaught ReferenceError: jQuery is not defined at file I am using phonegap and every time it gives me error at this line .I am trying to submit the form through phonegap , javascript works but with jquery it always me this errro Uncaught ReferenceError: jQuery is not defined at file
  jQuery(function() {

Here Is my code
<!DOCTYPE HTML>
<html>
  <head>

  <script type="text/javascript" charset="utf-8" src="cordova-1.5.0.js">
  </script>
  <script type="text/javascript" src="jquery-1.6.4.min.js"></script>

  <script>
  function validation()
  {
    alert('validation');
  }

  jQuery(function() {

    alert("login");
    /* stop form from submitting normally */
    event.preventDefault();

    /*clear result div*/

    /* get some values from elements on the page: */
    //var values = $(this).serialize();
    var values = "user";
    /* Send the data using post and put the results in a div */
    jQuery.ajax({
      url: server_url,
      type: "post",
      data: values,
      success: function() {
        alert("success");
        jQuery("#result").html('submitted successfully');
      },
      error: function() {
        alert("failure");
        jQuery("#result").html('there is error while submit');
      }
    });
  });

  </script>
</head>

A: You need to have jQuery file in the folder your current page is, also try to get the latest jQuery file you are using quite old, you can download latest here.

A: Is Cordova based on jQuery ? If so, you have to include jQuery first.
If not, your jQuery file is probably not found. Press Ctrl+u to see the source code, and then click on the link jquery-1.6.4.min.js in the head, and see if it opens your file ?


Q: K-Means Clustering having error of "Too many indexers" when multiple columns are given The code below is of K-Means Clustering copied from www.analyticsvidhya.com
K=3

# Select random observation as centroids
Centroids = (X.sample(n=K))
plt.scatter(X["DATE_ID"],X.iloc[:,-1],c='black')
plt.scatter(Centroids["DATE_ID"],Centroids.iloc[:,-1],c='red')
plt.xlabel('Number of Days')
plt.ylabel('POI1 Sales')
plt.show()

Output of above code

diff = 1
j=0

while(diff!=0):
    XD=X
    i=1
    for index1,row_c in Centroids.iterrows():
        ED=[]
        for index2,row_d in XD.iterrows():
            d1=(row_c["DATE_ID"]-row_d["DATE_ID"])**2
            d2=(row_c.iloc[:,-1]-row_d.iloc[:,-1])**2
            d=np.sqrt(d1+d2)
            ED.append(d)
        X[i]=ED
        i=i+1

C=[]
for index,row in X.iterrows():
    min_dist=row[1]
    pos=1
    for i in range(K):
        if row[i+1] < min_dist:
            min_dist = row[i+1]
            pos=i+1
    C.append(pos)
X["Cluster"]=C
Centroids_new = X.groupby(["Cluster"]).mean()[[X.iloc[:,-1],"DATE_ID"]]
if j == 0:
    diff=1
    j=j+1
else:
    diff = (Centroids_new[:,-1] - Centroids[:,-1]).sum() + (Centroids_new['DATE_ID'] - Centroids['DATE_ID']).sum()
    print(diff.sum())
Centroids = X.groupby(["Cluster"]).mean()[[X.iloc[:,-1],"DATE_ID"]]

The error I am having:
---------------------------------------------------------------------------
IndexingError                             Traceback (most recent call last)
<ipython-input-24-19f3132fec6e> in <module>()
      9         for index2,row_d in XD.iterrows():
     10             d1=(row_c["DATE_ID"]-row_d["DATE_ID"])**2
---> 11             d2=(row_c.iloc[:,-1]-row_d.iloc[:,-1])**2
     12             d=np.sqrt(d1+d2)
     13             ED.append(d)

3 frames
/usr/local/lib/python3.7/dist-packages/pandas/core/indexing.py in _validate_key_length(self, key)
    790     def _validate_key_length(self, key: Sequence[Any]) -> None:
    791         if len(key) > self.ndim:
--> 792             raise IndexingError("Too many indexers")
    793
    794     def _getitem_tuple_same_dim(self, tup: tuple):

IndexingError: Too many indexers

The problem
How can I pass multiple columns in it? the 1st column I have is DATE_ID (it's in float format) and the other columns are sales of different stores (also in float format)
I'm trying to implement this code but the code mentioned in the link before is implemented on only 2 columns, whereas I have to implement it on multiple columns while keeping the DATE_ID column fixed.

A: Here's scikit learns' k-means:
from sklearn.cluster import KMeans
import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('stack_overflow.csv')
X = df.iloc[:,1:]

plt.scatter(
   X['DATE_ID'], X.iloc[:, -1],
   c='white', marker='o',
   edgecolor='black', s=50
)
plt.show()

k = 3

km = KMeans(
    n_clusters=k, init='random',
    n_init=10, max_iter=300,
    tol=1e-04, random_state=0
)
y_km = km.fit_predict(X)
X['label'] = y_km

Output:

Now use the labels to graph the clusters:
import matplotlib.pyplot as plt
# plot the 3 clusters
plt.scatter(
    X[X['label'] == 0]['DATE_ID'], X[X['label'] == 0].iloc[:,-2],
    s=50, c='lightgreen',
    marker='s', edgecolor='black',
    label='cluster 1'
)

plt.scatter(
    X[X['label'] == 1]['DATE_ID'], X[X['label'] == 1].iloc[:,-2],
    s=50, c='orange',
    marker='o', edgecolor='black',
    label='cluster 2'
)

plt.scatter(
    X[X['label'] == 2]['DATE_ID'], X[X['label'] == 2].iloc[:,-2],
    s=50, c='lightblue',
    marker='v', edgecolor='black',
    label='cluster 3'
)

# plot the centroids
plt.scatter(
    km.cluster_centers_[:, 0], km.cluster_centers_[:, 1],
    s=250, marker='*',
    c='red', edgecolor='black',
    label='centroids'
)
plt.legend(scatterpoints=1)
plt.grid()
plt.show()

Output:


Q: Rails validate uniqueness between two models I'm still new to rails and I'm having trouble validating across models.
I have two models, Artists and Songs associated with a many to many relationship. I would like to have a validation in the song model that checks that song url_slug is unique for each artist.  I have tried using :scope but I don't seem to be able to call the associated artist id.
I'm pretty lost here so any help would be appreciated.
Thanks,
Here is my song model:
class Song< ActiveRecord::Base
 has_and_belongs_to_many:artists

 #creates Url Slug
 #before_create :generate_slug

 before_update :generate_slug

 validates_uniqueness_of :song_url_slug, :scope => self.artist.id

   protected
 def generate_slug
     self.song_url_slug = song_name.gsub(/\W+/, ' ').strip.downcase.gsub(/\ +/, '-')
 end

#def url_slug_uniqueness
  #artist_song = self.song_name.find(:artist_id])
     #if self.exists?(:conditions => {:song_name => artist_song})
      # errors.add(:song_name, :name_taken, :song_name=> "#{artist_song}1")
    #end
# end
#end

A: The first thing to do is try getting rid of the before_create :generate_slug and before_update :generate_slug lines and replace them with
  before_validation :generate_slug

Your uniqueness validation may work then.


Q: Regex Java word context what I want to achieve is that I want to obtain the context of an acronym. Can you help me pls with the regular expression?
I am looping over the text (String) and looking for dots, after match I am trying to get the context of the particular found acronym, so that I can do some other processing after that, but I cant get the context. I need to take at least 5 words before and 5 words after the acronym.
//Pattern to match each word ending with dot
    Pattern pattern = Pattern.compile("(\\w+)\\b([.])");

    Matcher matchDot = pattern.matcher(textToCorrect);
    while (matchDot.find()) {
        System.out.println("zkratka ---"+matchDot.group()+" ---");

        //5 words before and after tha match = context
     //   Matcher matchContext = Pattern.compile("(.{25})("+matchDot.group()+")(.{25})").matcher(textToCorrect);
        Pattern patternContext = Pattern.compile("(?:[a-zA-Z'-]+[^a-zA-Z'-]+){0,10}"+matchDot.group()+"(?:[^a-zA-Z'-]+[a-zA-Z'-]+){0,10}");
        Matcher matchContext = patternContext.matcher(textToCorrect);
        if (matchContext.find()) {
             System.out.println("context: "+matchContext.group()+" :");

    //       System.out.println("context: "+matchContext.group(1)+" :");
    //       System.out.println("context: "+matchContext.group(2)+" :");
        }

    }

Example:
input:
Some 84% of Paris residents see fighting pol. as a priority and 54% supported a diesel ban in the city by 2020, according a poll carried out for the Journal du Dimanche.
output:
1-st regex will find pol.
2-nd regex will find "of Paris residents see fighting pol. as a priority and 54%"
Another example with more text
I need to loop through this once and every time I match an acronym to get the context of this particular acronym. After that I am processing some datamining. Here's the original text

neklidná nemocná, vyš. je možné provést pouze nativně
Na mozku je patrna hyperdenzita v počátečním úseku a. cerebri media
  vlevo, vlevo se objevuje již smazání hranic mezi bazálními ganglii a
  okolní bílou hmotou a mírná difuzní hypointenzita v periventrikulární
  bílé hmotě. Kromě těchto čerstvých změn jsou patrné  staré
  postmalatické změny temporálně a parietookcipitálně vlevo. Oboustranně
  jsou patrné vícečetné vaskulární mikroléze v centrum semiovale bilat.
  Nejsou známky nitrolebního krvácení. skelet kalvy orientačně nihil tr.
Z á v ě r: Známky hyperakutní ischemie v povodí ACM vlevo, staré
  postmalatickéé změny T,P a O vlevo, vaskulární mikroléze v centrum
  semiovale bilat.
CT AG: vyš. po bolu k.l..
Po zklidnění nemocné se podařilo provést CT AG. Na krku je naznačený
  kinkink na ACC vlevo a ACI vlevo pod bazí. Kalcifikace  v karotických
  sifonech nepůsobí hemodynamicky významné stenozy. Intrakraniálně je
  patrný konický uzávěr operkulárního úseku a. cerebri media vlevo pro
  parietální lalok. Ostatní nález na intrakraniálním tepenném řečišti je
  v mezích normy.
Z á v ě r: uzávěr operkulárního úseku a. cerebri media vlevo.

Of course if it matches end of sentence is ok for me :-) The question is to find all the acronyms even if they are before new line (\n)

A: I would try this out:
(?:\w+\W+){5}((?:\w.?)+)(?:\w+\W+){5}

Though natural language processing with regular expressions cannot be accurate.

A: ((?:[\w!@#$%&*]+\s+){5}([\w!@#$%&*]+\.)(?:\s+[\w!@#$%&*]+){5})

Try this.See demo.
https://regex101.com/r/aQ3zJ3/9


Q: imap function is not working for me with PHP I try to access my gmail account with PHP, but I get an error message in line 2. IMAP is enabled in Gmail, while POP is not enabled.
$mbox = imap_open("{imap.gmail.com:993/ssl}", "email@gmail.com", "password");

echo "
Mailboxes
\n";
$folders = imap_listmailbox($mbox, "{imap.gmail.com:993}", "*");

if ($folders == false) {
    echo "Call failed
\n";
}
else {
    foreach ($folders as $val) {
        echo $val . "
\n";
    }
}

echo "
Headers in INBOX
\n";
$headers = imap_headers($mbox);

if ($headers == false) {
    echo "Call failed
\n";
}
else {
    foreach ($headers as $val) {
        echo $val . "
\n";
    }
}

imap_close($mbox);

A: You need to enable imap in your php.ini.

I used the wamp menu to edit the php.ini. I enabled the php_imap.dll.

-> http://www.wampserver.com/phorum/read.php?2,23447,printview,page=1

A: I got the solution:
I am running Windows 7 64bit environment with WAMP server, it has two php.ini files:
1] C:\wamp\bin\apache\apache2.2.22\bin
   Enable php_imap.dll extension by removing ; at beginning of string

2] C:\wamp\bin\php\php5.3.13
   Enable php_imap.dll extension by removing ; at beginning of string

And it works now !


Q: Validation loss and accuracy has a lot of 'jumps' Hello everyone so I made this cnn model.
My data:
Train folder->30 classes->800 images each->24000 all together
Validation folder->30 classes->100 images each->3000 all together
Test folder->30 classes -> 100 images each -> 3000 all together
-I've applied data augmentation. ( on the train data)
-I got 5 conv layers with filters 32->64->128->128->128
each with maxpooling and batch normalization
-Added dropout 0.5 after flattening layers
Train part looks good. Validation part has a lot of 'jumps' though. Does it overfit?
Is there any way to fix this and make validation part more stable?
Note: I plann to increase epochs on my final model I'm just experimenting to see what works best since the model takes a lot of time in order to train. So for now I train with 20 epochs.

A:
Train part looks good. Validation part has a lot of 'jumps' though. Does it overfit?

the answer is yes. The so-called 'jumps' in the validation part may indicate that the model is not generalizing well to the validation data and therefore your model might be overfitting.

Is there any way to fix this and make validation part more stable?

To fix this you can use the following:

*

*Increasing the size of your training set

*Regularization techniques

*Early stopping

*Reduce the complexity of your model

*Use different hyperparameters like learning rate

A:
I've applied data augmentation (on the train data).

What does this mean? What kind of data did you add and how much? You might think I'm nitpicking, but if the distribution of the augmented data is different enough from the original data, then this will indeed cause your model to generalize poorly to the validation set.
Increasing your epochs isn't going to help here, your training loss is already decreasing reasonably. Training your model for longer is a good step if the validation loss is also decreasing nicely, but that's obviously not the case.
Some things I would personally try:

*

*Try decreasing the learning rate.

*Try training the model without the augmented data and see how the validation loss behaves.

*Try splitting the augmented data so that it's also contained in the validation set and see how the model behaves.


Q: Git delete stash by name/message As far as I know Git can not delete a stash by name/message (despite it can save it by name with git stash save "name"). However, I really like to have this option for a 'combined alias' that I want to create for my workflow (especially for colleagues that are not that familiar with git and should respect the workflow)
I know I can create a bash script myself but I was thinking maybe someone already has made such a script!? So that I can delete a stash by name...
My "update" alias is roughly like this:
git stash save -u "tempstash"
git fetch origin
[apply our workflow/update strategy]
git stash pop --index (should be: git stash delete "tempstash")

The problem with the current alias is that if there is nothing to stash, it will restore an old stash.
An other option would be to check if stashing is needed but I always wanted a git stash delete by name option so thats why im asking this.
PS: im using posh-git but bash commands should work within an alias.
Thanks

A: You can overcome the problem with checking whether there is anything to stash first. You can use one of the ways to check whether an index is dirty that are suggested in Checking for a dirty index or untracked files with Git
For instance this command will not output anything if there are no changes to stash:
git status --porcelain

Using this command, the script may look like this:
is_stashing=$(git status --porcelain)
test -n "$is_stashing" && git stash save -u
git fetch origin
[apply our workflow/update strategy]
test -n "$is_stashing" && git stash pop --index

A: A solution would be to search the git reflog stash using the name of the stash as a regexp and obtaining its name in the stash@{<number>} format.
Then you can create an alias in git for using it as a command.
A quick and dirty solution, that can be greatly improved, is something like:
[alias]
   sshow = "!f() { git stash show `git reflog stash | egrep $* | awk '{printf $2}' | sed 's/://' `; }; f"
   ssdrop = "!f() { git stash drop `git reflog stash | egrep $* | awk '{printf $2}' | sed 's/://' `; }; f"

By adding this two aliases in your .git/config you can see the files modified in the stash with:
git sshow <regexp matching the name of the stash>

and you can drop the stash with:
git ssdrop <regexp matching the name of the stash>

A: I found a way to drop a stash by name. You can do it like this:
git stash drop stash@{$((git stash list | grep -w NAME_OF_THE_STASH) | cut -d "{" -f2 | cut -d "}" -f1)}

Here is the breakdown of the script:

*

*I am using the standard git stash drop stash@{n} structure

*We need to get the n of the stash with the name you want to delete. So to do that we list the stashes and grep the item with the matching name. To do that I used the script: git stash list | grep -w NAME_OF_THE_STASH

*Out of that item we need to extract the index which is within brackets {}. We can extract that number by adding to the script in item 2 the following: | cut -d "{" -f2 | cut -d "}" -f1
I tested it and it works great for me.
By the way, if you enter a name that does not exist then nothing gets erased.
Also, only the exact name match will be erased. If you don't want an exact match necessarily then remove the -w after grep.


Q: Image on top of text changing it's color I'm trying to find out how to build something like this (see attachment).
I do not know how to when a image (assuming it's an svg) goes on top of a H1 or any text it changes the text color.
The attachment i print here has a breathing effect on the blob, i wont have that but still it would be great to know.
Thank you.
BlobText


Q: (ionic solution) Disable android hardware back button for specific view. Back button should work as expected for other views in app On the tap of hardware back button on a specific view, it should not do anything. By Default it nav pop the view but here I don't want to back navigate on click of hardware back button. I want it to stay on that page/view.
I checked all possible solution available but no luck. This is not a duplicate too.
Ionic 2 - Disabling back button for a specific view this is for nav back button. I want a solution for hardware back button.

A: You can Try this
*Simply Override Empty onBackPressed *
@Override
public void onBackPressed(){
// do nothing.

}

A: You can Try this
*Simply Override Empty onBackPressed *
@Override
public void onBackPressed(){
 // do nothing.}

A: You have to write an override method
@Override
public void onBackPressed() {
    \\you can do whatever you want to here.
    \\don't call **super**, if u want disable back button in current screen.
}

A: In your Activity you have to override method:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        return !disableBackKey ;
    }

    return super.onKeyDown(keyCode, event);
}

And make disableBackKey True/False depend upon your requirement.

A: If you are using Activity, please add below function to your activity
@Override
public void onBackPressed() {
    //super.onBackPressed();
}

if you are using Fragment, please add below function to your fragment
public boolean onKeyDown(int keyCode, KeyEvent event) {
    switch (keyCode) {
    case KeyEvent.KEYCODE_BACK:
       return true
    }
            return false;
}

A: Answer for Ionic 2 or 3
Call the below method at the end of constructor.
Registration in the below code is your class name of current page or component.
if you don't want to do anything on back button, simply remove the code in IF condition below.
overrideHardwareBackButton() {
            this.platform.ready().then(() => {
                this.platform.registerBackButtonAction(() => {
                    let activeView:ViewController = this.navCtrl.getActive();
                    if (activeView != null && ((<any> activeView).instance instanceof Registration)) {
                        console.log("Registration -> Home");
                        this.nav.setRoot(HomePage);
                    } else {
                        console.log("Somthing is wrong");
                    }
                });
            });
        }


Q: Angular best practice for sharing single API call between two active components I'm trying to figure out what the best practice is for the following situation:
I have two components A and B which are both are integrated on one page. Both components need access to data set C. Data set C is received by an API Call from the server. It should only be received initially and not twice for every component.
My first approach was using observables, but then the API call was done twice. So i switched to BehaviourSubjects, but when called from the controller the initial value was of course null. So i replaced it with ReplySubjects, which are working fine. But im struggling with the intial call. I got it working fine but im looking for the best pracice. Here is the code:
Component A and B are similar
getDataC(): void {
    this.dataCService.getData().subscribe(data=>{this.data = data})
}

I want to have the data in my service as well, so i can make a UPDATE on the API with the object to modify the data on the Server. My approach is working fine, but im not sure if i have to subscribe inside my service the this variable or keep it clean.
Then my Service:
import { Injectable } from '@angular/core';
import { DataCAPIService } from '../resources/resources.service'
import { Observable, of, BehaviorSubject, ReplaySubject } from 'rxjs';

@Injectable({
    providedIn: 'root'
})
export class DataCService {

    public dataC = new ReplaySubject<any>(1)
    dataCInsideService: any

    constructor(private dataCAPIService: DataCAPIService) {

    }

    getDataCAPICall() {
        if (this.dataC.observers.length < 2)
            this.dataCAPIService.getAll({}).subscribe(data => {
                this.dataC.next(data);
                this.dataC.subscribe(data => this.dataCInsideService = data)
            })
    }

    getData() {
        this.getDataCAPICall();
        return this.dataC;
    }

    saveDataC() {
        this.dataCAPIService.update(this.dataCInsideService, {}).subscribe(data => {
            this.dataC.next(this.dataCInsideService);
        })
    }
}

Thanks for any opinions or solutions to a better style.

A:
I have two components A and B which are both are integrated on one
page. Both components need access to data set C.

As long as they are being used in one page, why you are calling them from each components? I think you can call it from the page component and send it to children.
Children can get the data using @Input() decorator. You can send the data directly or you can send it as observable (it's fine if it is behavior subject or subject).
I hope this could help you.


Q: Regular expression in Python sentence extractor I have a script that gives me sentences that contain one of a specified list of key words. A sentence is defined as anything between 2 periods.
Now I want to use it to select all of a sentence like 'Put 1.5 grams of powder in'  where if powder was a key word it would get the whole sentence and not '5 grams of powder'
I am trying to figure out how to express that a sentence is between to sequences of period then space. My new filter is:
def iterphrases(text):
    return ifilter(None, imap(lambda m: m.group(1), finditer(r'([^\.\s]+)', text)))

However now I no longer print any sentences just pieces/phrases of words (including my key word). I am very confused as to what I am doing wrong.

A: if you don't HAVE to use an iterator, re.split would be a bit simpler for your use case (custom definition of a sentence):
re.split(r'\.\s', text)

Note the last sentence will include . or will be empty (if text ends with whitespace after last period), to fix that:
re.split(r'\.\s', re.sub(r'\.\s*$', '', text))

also have a look at a bit more general case in the answer for Python - RegEx for splitting text into sentences (sentence-tokenizing)
and for a completely general solution you would need a proper sentence tokenizer, such as nltk.tokenize
nltk.tokenize.sent_tokenize(text)

A: Here you get it as an iterator. Works with my testcases. It considers a sentence to be anything (non-greedy) until a period, which is followed by either a space or the end of the line.
import re
sentence = re.compile("\w.*?\.(?= |$)", re.MULTILINE)
def iterphrases(text):
    return (match.group(0) for match in sentence.finditer(text))

A: If you are sure that . is used for nothing besides sentences delimiters and that every relevant sentence ends with a period, then the following may be useful:
matches = re.finditer('([^.]*?(powder|keyword2|keyword3).*?)\.', text)
result = [m.group() for m in matches]


Q: R: Make a new column filled from value in a row I have multiple dataframes all structured as below but with thousands of observations.
(df <- data.frame(
col1 = c("Elem_A", "String", "String", "String", "Elem_A", "String", "String", "Elem_A", "String", "String", "String", "String"),
col2 = c("DOI_1", "String", "String", "String", "DOI_2", "String", "String", "DOI_3", "String", "String", "String", "String")))

#>     col1   col2
#> 1 Elem_A  DOI_1
#> 2 String String
#> 3 String String
#> 4 String String
#> 5 Elem_A  DOI_2
#> 6 String String
#> 7 String String
#> 8 Elem_A  DOI_3
#> 9 String String
#> 10 String String
#> 11 String String
#> 12 String String

I am wanting to structure it as below, pulling specifically the value that begins with "DOI" into a new column and filling that value down until it reaches the row with the next "DOI" value.
(df <- data.frame(
col1 = c("Elem_A", "String", "String", "String",
    "Elem_A", "String", "String", "Elem_A", "String", "String", "String", "String", "String", "String", "String"),
col2 = c("DOI_1",
    "String", "String", "String", "DOI_2", "String", "String",
    "DOI_3", "String", "String", "String", "String", "String", "String", "String"),
col3 = c("DOI_1", "DOI_1", "DOI_1", "DOI_1",
    "DOI_2", "DOI_2", "DOI_2", "DOI_3", "DOI_3", "DOI_3", "DOI_3", "DOI_3")))

#>     col1   col2  col3
#> 1 Elem_A  DOI_1 DOI_1
#> 2 String String DOI_1
#> 3 String String DOI_1
#> 4 String String DOI_1
#> 5 Elem_A  DOI_2 DOI_2
#> 6 String String DOI_2
#> 7 String String DOI_2
#> 8 Elem_A  DOI_3 DOI_3
#> 9 String String DOI_3
#> 10 String String DOI_3
#> 11 String String DOI_3
#> 12 String String DOI_3

I was thinking I should somehow incorporate str_detect but the issue is that sometimes "DOI" is also the beginning of some of the "Strings" values within the same column that the "DOI" values are in.

A: We can use str_detect with case_when/ifelse to retrieve the row element and then use fill to fill the NA values with the previous non-NA
library(dplyr)
library(tidyr)
library(stringr)
df <- df %>%
   mutate(col3 = case_when(str_detect(col2, "DOI_") ~ col2)) %>%
   fill(col3)

-output
df
 col1   col2  col3
1  Elem_A  DOI_1 DOI_1
2  String String DOI_1
3  String String DOI_1
4  String String DOI_1
5  Elem_A  DOI_2 DOI_2
6  String String DOI_2
7  String String DOI_2
8  Elem_A  DOI_3 DOI_3
9  String String DOI_3
10 String String DOI_3
11 String String DOI_3
12 String String DOI_3

If 'DOI_\\d+' is a substring, then use str_extract to extract the substring
df <- df %>%
        mutate(col3 = str_extract(col2, "DOI_\\d+")) %>%
        fill(col3)

-output
df
 col1   col2  col3
1  Elem_A  DOI_1 DOI_1
2  String String DOI_1
3  String String DOI_1
4  String String DOI_1
5  Elem_A  DOI_2 DOI_2
6  String String DOI_2
7  String String DOI_2
8  Elem_A  DOI_3 DOI_3
9  String String DOI_3
10 String String DOI_3
11 String String DOI_3
12 String String DOI_3

A: With Base R way
s <- unlist(gregexpr("DOI_\\d+" , df$col2))

df$col3 <- unlist(Map(\(x,y) rep(df$col2[x] ,length.out = y + 1) ,
                  which(s > -1) , rle(s)$lengths[which(rle(s)$values == -1)]))

*

*output

     col1   col2  col3
1  Elem_A  DOI_1 DOI_1
2  String String DOI_1
3  String String DOI_1
4  String String DOI_1
5  Elem_A  DOI_2 DOI_2
6  String String DOI_2
7  String String DOI_2
8  Elem_A  DOI_3 DOI_3
9  String String DOI_3
10 String String DOI_3
11 String String DOI_3
12 String String DOI_3


Q: trying to create a loop that returns a logo in the list images and the name cryptolist i have a Widget that is called CoinCard which shows a cyrptoLogo,name and price.
now instead of calling that widget 3 times and providing image and a name, i wanted to create a loop which will return a image from images and the name from cryptoList. code below:

List<String> images = [
  "Bitcoin.svg.png",
  "256px-Ethereum_logo_2014.svg.png",
  "litecoin-ltc-logo.png"
];
const List<String> cryptoList = ['BTC', 'ETH', 'LTC'];

class _HomePageState extends State<HomePage> {
  List<Widget> getCard() {
    List<CoinCard> cards = [];

    for (String image in images) {
      cards.add(
        CoinCard(
          cryptoname: "ggg",
          logo: image,
          price: "5001918556",
        ),
      );
    }
    return cards;
  }

A: you can use ListView.builder to create dynamic list
example :
class HomePage extends StatelessWidget {
  List<String> images = [
  "Bitcoin.svg.png",
  "256px-Ethereum_logo_2014.svg.png",
  "litecoin-ltc-logo.png"
];
  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount:images.length ,
      itemBuilder: (context, index) => CoinCard(
          cryptoname: "ggg",
          logo: images[index],
          price: "5001918556",
        ),
      );
  }
}


Q: Modify/clean field values before applying a query filter in MongoDB like in SQL Server? I have a SQL Server query that I need to convert into a Mongo Query. As we all know that we can clean up fields in SQL before applying conditions to them e.g
In the 3rd line we are applying ltrim,rtrim on the clinics field before applying the like condition to it. Same with the reverse field in the query multiple times. If this was a single step query I would have done something maybe using aggregation but this is a multistep cleanup using replace, convert, ltrim, rtrim etc in different places.
Can someone please throw some light on how I could convert it. If someone is an expert in this domain and can convert it into Mongo, that would be great as well. Thanks :)
select rule from rules where
isnull(status,0) = '1' AND isnull(deleted,0) = '0'
AND (((ltrim(rtrim(isnull(clinics,'0'))) like '0%') OR
( ',' + replace(replace(isnull(clinics,'0'),' ','') ,' ','') + ','
like '%,' + convert(varchar,"""+category+""") + ',%')) AND
(',' + replace(replace(isnull(clinics,'0'),' ','') ,' ','') + ','
not like '%,-' + replace(convert(varchar,"""+category+"""),' ','') + ',%')) AND
((( (ltrim(rtrim(isnull(reverse,'0'))) like '0%') OR
(( ','+ replace(replace(isnull(reverse,'0'),' ','') ,' ','') + ','
like '%,' + convert(varchar,"""+primary+""") + ',%')))
AND (',' + replace(replace(isnull(reverse,'0'),' ','') ,' ','') + ','
not like '%,-' + replace(convert(varchar,"""+primary+"""),' ','') + ',%') ))


Q: Boost serialization of class handling a possible null pointer I want to serialize the following class wrapping a pointer which can handle a null m_element as you can see when calling the default constructor. This follows this question.
Live MCVE on Coliru
template <typename T>
struct Ptr { // Ptr could use init constructor here but this is not the point
    Ptr() { m_elem = 0; }
    Ptr(const T* elem) {
        if (elem)
            m_elem = new T(*elem);
        else
            m_elem = 0;
    }
    Ptr(const T& elem)
    {
        m_elem = new T(elem);
    }
    Ptr(const Ptr& elem)
    {
        if (elem.m_elem)
            m_elem = new T(*(elem.m_elem));
        else
            m_elem = 0;
    }
    virtual ~Ptr() { delete m_elem; m_elem = 0; };

    const T& operator*() const { return *m_elem; };
    T& operator*() { return *m_elem; };

    const T* operator->() const { return m_elem; };
    T* operator->() { return m_elem; };

    T* m_elem;
};

namespace boost { namespace serialization {

    // Not sure about the approach to manage null m_elem here
    template<class Archive, class T>
    void save(Archive & ar, const Ptr<T> &ptr, const unsigned int version)
    {
        T elem = 0;
        if (ptr.m_elem != 0)
            ar& boost::serialization::make_nvp("data", *ptr.m_elem);
        else
            ar& boost::serialization::make_nvp("data", elem);
    }

    // How to implement load ?
    template<class Archive, class T>
    void load(Archive & ar, Ptr<T> &ptr, const unsigned int version)
    {
        ar& boost::serialization::make_nvp("data", *ptr.m_elem);
    }

    template<class Archive, class T>
    void serialize(Archive & ar, Ptr<T> &ptr, const unsigned int version)
    {
        boost::serialization::split_free(ar, ptr, version);
    }

}} // end namespace

int main()
{
    {
        Ptr<A> p;
        std::ostringstream oss;
        boost::archive::xml_oarchive oa(oss);
        oa << BOOST_SERIALIZATION_NVP(p);
        std::cout << oss.str() << std::endl;

        // segfault

        Ptr<double> po;
        std::istringstream iss;
        iss.str(oss.str());
        boost::archive::xml_iarchive ia(iss);
        ia >> BOOST_SERIALIZATION_NVP(po);

    }
    {
        Ptr<double> p(new double(2.0));
        std::cout << *(p.m_elem) << std::endl;

        std::ostringstream oss;
        boost::archive::xml_oarchive oa(oss);
        oa << BOOST_SERIALIZATION_NVP(p);
        std::cout << oss.str() << std::endl;

        // segfault

        Ptr<double> po;
        std::istringstream iss;
        iss.str(oss.str());
        boost::archive::xml_iarchive ia(iss);
        ia >> BOOST_SERIALIZATION_NVP(po);

    }
}

The serialization seems to work but the deserialization gives a segfault. I am working in C++0x.

*

*How can I provide safe save and load functions to serialize Ptr without changing Ptr if possible ?

*If I need to modify Ptr, what do you propose ?

Edit : thanks to Jarod42 comment I came up with the following save/load functions using a boolean to detect null pointer or not. Now I do not have a segfault anymore when m_elem is null but I have a one when it is not null.
template<class Archive, class T>
void save(Archive & ar, const Ptr<T> &ptr, const unsigned int version)
{
    bool is_null;
    if (ptr.m_elem != 0) {
        is_null = false;
        ar& boost::serialization::make_nvp("is_null", is_null);
        ar& boost::serialization::make_nvp("data", *ptr.m_elem);
    }
    else
    {
        is_null = true;
        ar& boost::serialization::make_nvp("is_null", is_null);
    }
}

template<class Archive, class T>
void load(Archive & ar, Ptr<T> &ptr, const unsigned int version)
{
    bool is_null;
    ar& boost::serialization::make_nvp("is_null", is_null);
    if (is_null == true) {
        ptr.m_elem = 0;
    }
    else
    {
        ar& boost::serialization::make_nvp("data", *ptr.m_elem);
    }
}

A: boost::archive's save and load methods understand the difference between pointers and object references. You don't need to specify *m_elem. m_elem will do (and work correctly). Boost will understand if the pointer is null and will simply store a value indicating a null pointer, which will be deserialised correctly.
(simplified) example:
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <iterator>

#include <boost/archive/xml_iarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/serialization/access.hpp>
#include <boost/serialization/nvp.hpp>
#include <boost/serialization/split_free.hpp>

struct A {
    A() : a(0) {}
    A(int aa) : a(aa) {}
    int a;
    template <class Archive>
    void serialize(Archive& ar, const unsigned int /*version*/)
    {
        ar& BOOST_SERIALIZATION_NVP(a);
    }
};

std::ostream& operator<<(std::ostream& os, const A& a) {
    os << "A{" << a.a << "}";
    return os;
}

template <typename T>
struct Ptr { // Ptr could use init constructor here but this is not the point
    Ptr()
    : m_elem(0)
    {}

    Ptr(T elem)
    : m_elem(new T(elem))
    {
    }

private:
    // no copies
    Ptr(const Ptr&);
    Ptr& operator=(const Ptr&);
public:
    // delete is a NOP when called with nullptr arg
    virtual ~Ptr() { delete m_elem; };

    T* get() const {
        return m_elem;
    }

    T& operator*() const {
        return *m_elem;
    }

    template <class Archive>
    void serialize(Archive& ar, const unsigned int /*version*/)
    {
        ar& BOOST_SERIALIZATION_NVP(m_elem);
    }

private:
    T* m_elem;
};

template<class T>
std::ostream& operator<<(std::ostream& os, const Ptr<T>& p) {
    if (p.get()) {
        os << *p;
    }
    else {
        os << "{nullptr}";
    }
    return os;
}

int main()
{
    std::string payload;

    {
        Ptr<A> p;
        std::cout << p << std::endl;
        std::ostringstream oss;
        boost::archive::xml_oarchive oa(oss);
        oa << BOOST_SERIALIZATION_NVP(p);
        payload = oss.str();
//        std::cout << payload << std::endl;

        Ptr<A> p2(A(6));
        std::cout << p2 << std::endl;
        oa << BOOST_SERIALIZATION_NVP(p2);
        payload = oss.str();
//        std::cout << payload << std::endl;
    }
    {

        Ptr<A> po;
        std::istringstream iss(payload);
        boost::archive::xml_iarchive ia(iss);
        ia >> BOOST_SERIALIZATION_NVP(po);
        std::cout << po << std::endl;

        Ptr<A> po2;
        ia >> BOOST_SERIALIZATION_NVP(po2);
        std::cout << po2 << std::endl;
    }
}

expected output:
{nullptr}
A{6}
{nullptr}
A{6}

A: Thanks to Jarod42 comment,

You should serialize a boolean to know if pointer is nullptr or not
  (and if not, serialize also its content). for loading, retrieve this
  boolean and allocate a default element when needed that you load.

we came with the following save and load functions :
template<class Archive, class T>
void save(Archive & ar, const Ptr<T> &ptr, const unsigned int version)
{
    bool is_null = !ptr.m_elem;
    ar & boost::serialization::make_nvp("is_null", is_null);
    if(!is_null) ar & boost::serialization::make_nvp("data", *ptr.m_elem);
}

template<class Archive, class T>
void load(Archive & ar, Ptr<T> &ptr, const unsigned int version)
{
    bool is_null;
    ar & boost::serialization::make_nvp("is_null", is_null);

    if (!is_null) {
        ptr.m_elem = new T;
        ar& boost::serialization::make_nvp("data", *ptr.m_elem);
    }
}

Live on Coliru
Had an issue in the load function when is_null is false. A storage is indeed needed for ptr in this case.


Q: I want to dynamically query WHERE clause using string builder I want to dynamically build the WHERE clause for my query using string builder.
private void btnquery_Click(object sender, EventArgs e)
{
    StringBuilder strQuery = new StringBuilder();
    StringBuilder strWhereClass = new StringBuilder();
    strQuery.Append("SELECT * FROM [dbo].[poi5] ");

    if (namecb.Checked)
    {
        if (string.IsNullOrEmpty(nametxt.Text))
        {   MessageBox.Show("Please enter the name!!!");
            nametxt.Focus();
            return;
        }
        else
        {
            if (strWhereClass.Length == 0)
            { strWhereClass.Append("WHERE [Name_POI] ='" + nametxt.Text + "';");
            } else{ trWhereClass.Append(" AND [Name_POI]] ='" + nametxt.Text + "';");
            }
        }
    }

    if (versioncb.Checked)
    {
        if (string.IsNullOrEmpty(versiontxt.Text))
        {  MessageBox.Show("Please enter the version!!!");
            versiontxt.Focus();
            return;
        }
        else
        {
            if (strWhereClass.Length == 0)
            {
                strWhereClass.Append("WHERE [Version] = '" versiontxt.Text + "'");
            }
            else
            {
                strWhereClass.Append(" AND [Version] = '" + versiontxt.Text + "'");
            }
        }
    }

    con = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=POIFINALLY;Integrated Security=True;");

    cmd = new SqlCommand(strQuery.ToString() + strWhereClass.ToString(), con);
    con.Open();
    da = new SqlDataAdapter(cmd);
    da.Fill(ds);
    dataGridView1.DataSource = ds.Tables[0];
}

A: Write a stored Procedure that takes the filter query dynamically according to cases
    Create procedure GetPoi (@Name nvarchar (100),@Version nvarchar (100))
    as
    begin
    declare @Command nvarchar(max)
    set @Command = 'select * from tablename where name ='''+@Name+''' and Version='''+@Version+''''
    exec sp_executeSql @Command
    end

Also you have to make a test to check if the Parameters provided are empty strings and modify your where clause accordingly.
Check Dynamic SQL for more info


Q: Does github limit the number of personal access tokens per user Using Github Enterprise, I have a service/bot account where I'd like to generate a number of Personal Access tokens and provide to a number of teams.
Is there any limit in how many Personal Access Tokens can be generated per user?

A: As far as I'm aware, there is no limit, but if you want to be sure, you should ask either the GitHub support team or on the GitHub community forums.
GitHub itself has such a bot account and PATs are frequently used there, but do be aware that the UI may be a little (or, depending on how many tokens you issue, very) slow, since it isn't designed for people to have huge numbers of PATs.
You may find it more desirable to use deploy keys if you're accessing a repo, since these have a smaller scope (one repository) and won't have the UI problems mentioned above, but of course that won't work for the API.


Q: How to add textFileds in Dropdown Reactjs I want to add textField - autocomplete in Dropdown? Could you help me how to do it?

The source code in here: Source Code in Sanbox

A: Since you are using Material-UI, you can use their autocomplete component with a TextField as input, have a look at the "Combo box" here:
https://material-ui.com/components/autocomplete/#combo-box


Q: Sprint Wireless Toolkit 3.3.2 vs Sun Wireless Toolkit Anyone know the diference between Sprint Wireless Toolkit 3.3.2 and Sun Wireless Toolkit?

A: AFAIK both are same. But I feel some differents between Sprint toolkit and Sun toolkit. These are,
Sprint toolkit having Nokia, Samsung, LG emulators. But Sun java toolkit having their own toolkit.
Sprint support touch emulators. Sun toolkit doesn't have touch emulators.
Zooming emulator screen supports Sprint. Sun toolkit doesn't support.


Q: Javascript displaying text in quotes. How do I remove it? Edit: Turns out the api produces the quotes.
Excuse me, as I have pretty much no knowledge of js/jquery, but I found a code I wanted to use. It uses tumblr's api. http://www.tumblr.com/docs/en/api/v1.
Now, the problem is titles[i] shows text wrapped in quotes. So instead of

This is the titles i. I want this.
,
it shows

"This is the titles i. I don't want the quotes!"

in the html. I don't want that (for reasons not worth explaining).
Can somebody help me remove the quotes?
Here's the full code.
(function() {
var config = new Object();
var titles = [];
var links = [];
var images = [];
var items = [];
var types = [];
var $j = jQuery.noConflict()

var scripts = document.getElementsByTagName('script');
var this_script = scripts[scripts.length - 1];
var params = this_script.src.replace(/^[^\?]+\??/,'').split('&');

var url_base = ((typeof(config.url) == 'undefined') ? ('http://' + document.domain + '/') : ('http://' + config.url + '/'));

for(var i=0; i<params.length; i++) {
    var tmp = params[i].split("=");
    config[tmp[0]] = unescape(tmp[1]);
}

if(typeof(config.tags)=='undefined'){ error(0); return; }
if(typeof(config.num)=='undefined'){ config.num=8; }
if(typeof(config.len)=='undefined'){ config.len=60; }
if(typeof(config.title)=='undefined'){ config.title='Related Posts:'; }
if(typeof(config.type)=='undefined'){ config.type=''; }

switch(config.css) {
case ('simple'):
  document.write('<link rel="stylesheet" type="text/css" ' +
  'href="http://example.com/resource/simple.css" media="screen" />');
break;
case ('complete'):
  document.write('<link rel="stylesheet" type="text/css" ' +
  'href="http://example.com/resource/complete.css" media="screen" />');
break;
case ('light'):
  document.write('<link rel="stylesheet" type="text/css" ' +
  'href="http://example.com/resource/light.css" media="screen" />');
break;
case ('dark'):
  document.write('<link rel="stylesheet" type="text/css" ' +
  'href="http://example.com/resource/dark.css" media="screen" />');
break;}

  document.write(
    '
' +
        '

' +
        '

'+
        '

' +
        '' +
    '
'
);

var tags = config.tags.slice(0,-1).split(',');

$j(document).ready(function() {
    function getRelated() {
        var req;
        for(var i=0; i<tags.length; i++){
            req=$j.getJSON(url_base+'api/read/json?callback=?&filter=text&num='+config.num+'&start=0&type='+config.type+'&tagged='+escape(tags[i]), function(data) {
                $j(data.posts).each(function(i, post) {
                    var text='';
                    if(post.type=='regular') text=post['regular-title']+''+post['regular-body'];
                    else if(post.type=='link') text+=post['link-text'];
                    else if(post.type=='quote') text+=post['quote-text'];
                    else if(post.type=='photo') text+=post['photo-caption'];
                    else if(post.type=='conversation') text+=post['conversation-title'];
                    else if(post.type=='video') text+=post['video-caption'];
                    else if(post.type=='audio') text+=post['audio-caption'];
                    else if(post.type=='answer') text+=post['question'];
                    if(text.length>config.len){ text=text.slice(0,config.len); text+='...';}
                    var image ='';
                    if(post.type=='photo') image+=post['photo-url-100'];
                    else if(post.type=='link') image+=['link-text'];
                    else if(post.type=='quote') image+=['quote-text'];
                    else if(post.type=='photo') image+=['photo-caption'];
                    else if(post.type=='conversation') image+=['conversation-title'];
                    else if(post.type=='video') image+=['video-caption'];
                    else if(post.type=='audio') image+=['audio-caption'];
                    else if(post.type=='answer') image+=['question'];
                    titles.push(text);
                    links.push(post['url-with-slug']);
                    images.push(image);
                    types.push(post['type'])
                });

            }).complete(getList);
        }

    }
    function getList(){
        for(var i=0; i<titles.length; i++){
            var regex = new RegExp('('+links[i]+')');
            var html = $j("#inlink-list").html();

            if(links[i]!=document.location&&!html.match(regex)){
                if(config.num--<=0) return;

                var item='

'+titles[i]+'

';
                $j("#inlink-list").append(item);
            }
        }
        $j("#inlink-title").html('
'+config.title+'
');
        $j("#inlink-loading").html('');
    }
    getRelated();

});

function getError(e){
    var msg="error: ";
    switch(e){
        case 0: msg+='no tags defined'; break;
        case 1: msg+='tumblr API problem'; break;
    }
    $j("#inlink-loading").html(msg);
}})();

A: I am going to assume the quotes are coming from the Tumblr API. In this case, you just need to strip the quotes:

'+titles[i].substring(1, titles[i].length - 2)+'

substring(1, titles[i].length - 2) will remove the first character (index 0) and the last character (index length - 1) from the string.
Docs


Q: Create bitmap of a DOMElement Objective C I have a Webkit DOMElement, a div for example.
Now I want a renderized NSImage or NSBitmapImageRep of it.
It's like a screenshot of a DOMElement.

A: Public API choices:
-[NSView cacheDisplayInRect:toBitmapImageRep:]
-[NSBitmapImageRep initWithFocusedViewRect:]

Private WebKit method:
-[DOMElement renderedImage]


Q: SQL help to identify the Missing Data I have the following COMPANY_TABLE table
SOURCE  UNIQUE_COMPANY_D    RECORD_STATE    SUB_COMPANY_ID  PARENT  PRIMARY_PARENT
ABC 111 Secondary   123     999
XYZ 111 Primary     456
YYY 222 Secondary   895     888        888
TTT 222 Primary     902                888
VVV 333 Primary     101     777        777
RRR 333 Secondary   187                777

IN WHERE UNIQUE_COMPANY_ID = '111' is the issue.
PRIMARY_PARENT IS NOT POPULATED, It should populate based on PARENT. If the PARENT field has Value it should Populate for both rows. if null it has to grab the value from secondary row and populate PRIMARY_PARENT Value. I have like 10 million rows where I need to find the scenarios where Parent is populated and Primary parent is not populated. based on the above criteria. (If the PARENT field has Value it should Populate for both rows. if null it has to grab the value from secondary row and populate PRIMARY_PARENT Value) I want to identify all the error records from 10 million rows.
And I created the SQL below :
SELECT * FROM COMPANY_TABLE WHERE PARENT IS NOT NULL AND PRIMARY_PARENT IS NULL;

But all its showing me single row. I need something which can get me two rows in order and able to differentiate the issue.

A: You have missed one of the conditions. You also want whenever PARENT is NULL the Value of PRIMARY_PARENT be equal to the value of PARENT in the next row. You can take care of it this way:
SELECT * FROM
(SELECT *, LEAD(PARENT) OVER(Order BY (SELECT NULL)) as LeadParent FROM     COMPANY_TABLE) T
WHERE PARENT IS NOT NULL AND PRIMARY_PARENT IS NULL
     OR ((PARENT IS NULL) AND LeadParent != PRIMARY_PARENT);

A: As Kumar stated, you could try and test to see if the values Parent and Primary_Parent by default are NULL's or blanks.
Did you try:
SELECT * FROM COMPANY_TABLE WHERE PARENT <> '' AND PRIMARY_PARENT <> ''


Q: Put a Variable in List Name Essentially, I want to create and fill a list based on the contents of a variable. The relevant data is being read from a (JSON) text file.
#Check if a game was won, and assign a variable to `outcome`
if game['stats']['win'] == True:
                outcome = "victory"
            else:
                outcome = "defeat"

#put the no. objectives taken in that game in a 'wins' or 'losses' list
objectives_in_(outcome).append(game['stats']['objectives_taken'])

So outside of a useful for-loop, I would want something a result which looks something like this:
print(objectives_in_victory)

7

In case my question remains unclear, I am reading a file that will contain data on whether a match was won, and how many objectives were secured. If the game was won, the number of objectives in that game will be assigned to a 'win list' and visa versa for losses.
I tried using a dictionary which was suggested elsewhere on SO for approaching similar tasks, but matches which have the same outcome and no. objectives are not duplicated making averaging impossibe and causing data to be excluded. It took me a long time to realise this..

A: You could use a dict of lists that looks like this:
objectives_in = {"victory": [], "defeat": []}

You can use it similar to what you have in your example:
objectives_in[outcome].append(game['stats']['objectives_taken'])

# Example stats:
count = len(objectives_in["victory"])
print("Number of victories:", count)
print("Average objectives:", sum(objectives_in["victory"]) / count)


Q: How to melt and plot multiple datasets over different ranges on the same set of axis? This is my first time posting here, I hope my question is clear and appropriate. I have a set of data the head of which looks like this:
   wl     ex421  wl     ex309  wl      ex284  wl      ex347
1 431 0.6168224 321 0.1267943 301 0.06392694 361 0.15220484
2 432 0.6687435 322 0.2416268 302 0.05631659 362 0.08961593
3 433 0.6583593 323 0.4665072 303 0.05327245 363 0.13134187
4 434 0.6832814 324 0.3576555 304 0.00000000 364 0.32432432
5 435 0.6427830 325 0.2194976 305 0.12328767 365 0.50308203
6 436 0.7393562 326 0.1866029 306 0.08675799 366 0.34660977

and so on. The 'wl' columns represent wavelength, and there are four different ranges. The other four columns represent measurements (normalized) taken over the 'wl' ranges. The ranges are of different lengths, too. All of them partially overlap somewhere in the middle of the dataset.
What I need to achieve is a plot showing all four sets of 'ex###' data on the same set of axis and plotted over their respective ranges. The x-axis needs to accommodate all four 'wl' ranges. However, I haven't yet succeeded.
When I had to plot multiple sets of data like this in the past I just melted the data and it always worked. Something like this:
df_melt <- melt(df, id.var = 'wl')

And then I'd plot it like this:
fluor_plt <- ggplot(fluor_ref2_melt, aes(x=wl,y=value,color=variable)) +
geom_point(shape = 1, fill = NA) + geom_path(data = fluor_ref2_melt,size = 1) +
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) +
  scale_colour_manual(values = colvec)

However, because I have multiple columns with the name 'wl', which also have different ranges, what happens is that R only takes the first 'wl' column and discards all the other ones. It then basically shifts all the 'ex###' values into that range by using the row index... so I get a plot of the frame below:
   wl     ex421    ex309    ex284      ex347
1 431 0.6168224 0.1267943 0.06392694 0.15220484
2 432 0.6687435 0.2416268 0.05631659 0.08961593
3 433 0.6583593 0.4665072 0.05327245 0.13134187
4 434 0.6832814 0.3576555 0.00000000 0.32432432
5 435 0.6427830 0.2194976 0.12328767 0.50308203
6 436 0.7393562 0.1866029 0.08675799 0.34660977

Needless to say, this is entirely wrong...
So one way I tried to circumvent the issue is going into Excel and manually moving columns up and down, so that in the dataframe each row corresponds to one 'wl' value, whether there are any measured values associated with it or not. This got rid of the values being 'shifted', but R still discards the 'wl' columns after the first one. Instead of getting an entirely wrong plot, I get a section of the right one. The first set of observations (ex421) is plotted over its entire range; pieces of the other ones are seen where ranges overlap.
I've looked at some similar cases which were asked about here in the past, like this -  Reshape data frame from wide to long with re-occuring column names in R.
But I'm new to R and I don't think I could fully understand the proposed solutions. I didn't succeed in reshaping my data in the way I want it to be reshaped (keeping different 'wl' ranges for different sets) and I had no idea which arguments to give to ggplot afterwards. I've tried using data.table, but then I don't know what to give it for value.name and variable.name.
To reiterate, what I want to achieve is what one would get from plotting the four datasets in the spreadsheet by making a single Scatter plot in Excel and adding four different series to it.
Any input would be greatly appreciated!

A: I can think of this solution:
# data:
dt <- structure(list(wl = 431:436,
     ex421 = c(0.6168224, 0.6687435, 0.6583593, 0.6832814, 0.642783, 0.7393562),
     wl = 321:326,
     ex309 = c(0.1267943, 0.2416268, 0.4665072, 0.3576555, 0.2194976, 0.1866029),
     wl = 301:306,
     ex284 = c(0.06392694, 0.05631659, 0.05327245, 0, 0.12328767, 0.08675799),
     wl = 361:366,
     ex347 = c(0.15220484, 0.08961593, 0.13134187, 0.32432432, 0.50308203, 0.34660977)),
   row.names = c(NA,     -6L),
   class = c("data.table", "data.frame"))

# get vectors with wl names
wls <- grep("wl", names(dt))

# get vectors with ex_numbers names
exs <- grep("ex", names(dt))

# reformat the data:
newDt <- cbind(stack(dt, select = wls), stack(dt, select = exs))

# Assign reasonable names:
names(newDt) <- c("wlNumber", "wlInd", "exValue", "exNumber")

Now the data is ready to be plotted with any command:
ggplot(newDt, aes(x = wlNumber, y = exValue, color = exNumber))+geom_point()+geom_line()

The main advantage of this approach is that you can have the table spread into many columns. It doesn't matter, as long as their name has "wl" on it ("ex" for the other variables).

A: Here I load a data frame with your data, making sure to allow repeated names with check.names = F, otherwise it would rename the wl columns to be distinct:
df <- read.table(
  header = T, check.names = F,
  stringsAsFactors = F,
  text = "   wl     ex421  wl     ex309  wl      ex284  wl      ex347
 431 0.6168224 321 0.1267943 301 0.06392694 361 0.15220484
 432 0.6687435 322 0.2416268 302 0.05631659 362 0.08961593
 433 0.6583593 323 0.4665072 303 0.05327245 363 0.13134187
 434 0.6832814 324 0.3576555 304 0.00000000 364 0.32432432
 435 0.6427830 325 0.2194976 305 0.12328767 365 0.50308203
 436 0.7393562 326 0.1866029 306 0.08675799 366 0.34660977")

Then here's a way to reshape, by just stacking subsets of the data. Since there weren't too many column pairs, I thought a semi-manual method would be ok. It preserves the distinct column headers so we can gather those into long form and map to color like in your plot.
library(tidyverse)
df2 <- bind_rows(
  df[1:2],
  df[3:4],
  df[5:6],
  df[7:8]
) %>%
  gather(variable, value, -wl) %>%
  drop_na()

ggplot(df2, aes(x=wl,y=value,color=variable)) +
  geom_point(shape = 1, fill = NA) +
  geom_path(size = 1) +
  theme(panel.grid.major = element_blank(),
        panel.grid.minor = element_blank())


Q: Unable to find Artifactory Project in Visual Studio Extensions and Updates I am using Visual Studio 2017. I am trying to add JFrog Artifactory Project to push artifacts to Artifactory.
To add Artifactory project I need to install it from tools--> Extensions and Updates--> search for Artifactory. But the search results is zero.
So how can i install JFrog Artifactory in Visual Studio 2017. It is working fine with Visual studio 2015.


Q: In Java, how do I create a bitmap to solve "knapsack quandary" I'm in my first programming course and I'm quite stuck right now. Basically, what we are doing is we take 16 values from a text file (on the first line of code) and there is a single value on the second line of code. We read those 16 values into an array, and we set that 2nd line value as our target. I had no problem with that part.
But, where I'm having trouble is creating a bitmap to test every possible subset of the 16 values, that equal the target number.
IE, say we had these numbers:
12   15   20   4   3   10   17   12   24   21   19   33   27   11   25   32

We then correspond each value to a bitmap
 0    1    1   0   0    0    0    1    1    1    0    1    0    0    1    0

Then we only accept the values predicated with "1"
     15   20                     12   24   21        33             25

Then we test that subset to see if it equals the "target" number.
We are only allowed to use one array in the problem, and we aren't allowed to use the math class (haven't gotten to it yet).
I understand the concept, and I know that I need to implement shifting operators and the logical & sign, but I'm truly at a loss. I'm very frustrated, and I just was wondering if anybody could give me any tips.

A: To generate all possible bit patterns inside an int and thus all possible subsets defined by that bit map would simply require you to start your int at 1 and keep incrementing it to the highest possible value an unsigned short int can hold (all 1s). At the end of each inner loop, compare the sum to the target. If it matches, you got a solution subset - print it out. If not, try the next subset.
Can someone help to explain how to go about doing this? I understand the concept but lack the knowledge of how to implement it.

A: OK, so you are allowed one array. Presumably, that array holds the first set of data.
So your approach needs to not have any additional arrays.
The bit-vector is simply a mental model construct in this case. The idea is this: if you try every possible combination (note, NOT permutation), then you are going to find the closest sum to your target. So lets say you have N numbers. That means you have 2^N possible combinations.
The bit-vector approach is to number each combination with 0 to 2^N - 1, and try each one.
Assuming you have less that 32 numbers in the array, you essentially have an outer loop like this:
int numberOfCombinations = (1 << numbers.length - 1) - 1;
for (int i = 0; i < numberOfCombinations; ++i) { ... }

for each value of i, you need to go over each number in numbers, deciding to add or skip based on shifts and bitmasks of i.

A: So the task is to what an algorithm that, given a set A of non-negative numbers and a goal value k, determines whether there is a subset of A such that the sum of its elements is k.
I'd approach this using induction over A, keeping track of which numbers <= k are sums of a subset of the set of elements processed so far. That is:
boolean[] reachable = new boolean[k+1];
reachable[0] = true;
for (int a : A) {
    // compute the new reachable
    // hint: what's the relationship between subsets of S and S \/ {a} ?
}
return reachable[k];

A bitmap is, mathematically speaking, a function mapping a range of numbers onto {0, 1}. A boolean[] maps array indices to booleans. So one could call a boolean[] a bitmap.
One disadvanatage of using a boolean[] is that you must process each array element individually. Instead, one could use that a long holds 64 bits, and use bitshifting and masking operations to process 64 "array" elements at a time. But that sort of microoptimization is error-prone and rather involved, so not commonly done in code that should be reliable and maintainable.

A: I think you need something like this:
public boolean equalsTarget( int bitmap, int [] numbers, int target ) {
  int sum = 0; // this is the variable we're storing the running sum of our numbers
  int mask = 1; // this is the bitmask that we're using to query the bitmap
  for( int i = 0; i < numbers.length; i++ ) { // for each number in our array
    if( bitmap & mask > 0 ) { // test if the ith bit is 1
        sum += numbers[ i ]; // and add the ith number to the sum if it is
    }
    mask <<= 1; // shift the mask bit left by 1
  }
  return sum == target; //if the sum equals the target, this bitmap is a match
}

The rest of your code is fairly simple, you just feed every possible value of your bitmap (1..65535) into this method and act on the result.
P.s.: Please make sure that you fully understand the solution and not just copy it, otherwise you're just cheating yourself. :)
P.p.s: Using int works in this case, as int is 32 bit wide and we only need 16. Be careful with bitwise operations though if you need all the bits, as all primitive integer types (byte, short, int, long) are signed in Java.

A: There are a couple steps in solving this.  First you need to enumerate all the possible bit maps.  As others have pointed out you can do this easily by incrementing an integer from 0 to 2^n - 1.
Once you have that, you can iterate over all the possible bit maps you just need a way to take that bit map and "apply" it to an array to generate the sum of the elements at all indexes represented by the map.  The following method is an example of how to do that:
private static int bitmapSum(int[] input, int bitmap) {
    // a variable for holding the running total
    int sum = 0;

    // iterate over each element in our array
    // adding only the values specified by the bitmap
    for (int i = 0; i < input.length; i++) {
        int mask = 1 << i;
        if ((bitmap & mask) != 0) {
            // If the index is part of the bitmap, add it to the total;
            sum += input[i];
        }
    }

    return sum;
}

This function will take an integer array and a bit map (represented as an integer) and return the sum of all the elements in the array whose index are present in the mask.
The key to this function is the ability to determine if a given index is in fact in the bit map.  That is accomplished by first creating a bit mask for the desired index and then applying that mask to the bit map to test if that value is set.
Basically we want to build an integer where only one bit is set and all the others are zero.  We can then bitwise AND that mask with the bit map and test if a particular position is set by comparing the result to 0.
Lets say we have an 8-bit map like the following:
map:       1 0 0 1 1 1 0 1
           ---------------
indexes:   7 6 5 4 3 2 1 0

To test the value for index 4 we would need a bit mask that looks like the following:
mask:      0 0 0 1 0 0 0 0
           ---------------
indexes:   7 6 5 4 3 2 1 0

To build the mask we simply start with 1 and shift it by N:
1:            0 0 0 0 0 0 0 1
shift by 1:   0 0 0 0 0 0 1 0
shift by 2:   0 0 0 0 0 1 0 0
shift by 3:   0 0 0 0 1 0 0 0
shift by 4:   0 0 0 1 0 0 0 0

Once we have this we can apply the mask to the map and see if the value is set:
map:             1 0 0 1 1 1 0 1
mask:            0 0 0 1 0 0 0 0
                 ---------------
result of AND:   0 0 0 1 0 0 0 0

Since the result is != 0 we can tell that index 4 is included in the map.


Q: Map String to Object using Jackson with inheritance I have the QueueContent class that it has is a superclass of two others.
I get a String in JSON format that contains the information I need to extract. The super class is:
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class QueueContent {

    private String empresa;
    private String empresa_cor;
    private String empresa_contato;
    private String empresa_url;
    private String empresa_telefone;
    private String empresa_idioma;

    public QueueContent(String empresa, String empresa_cor, String empresa_contato, String empresa_url, String empresa_telefone, String empresa_idioma) {
        this.empresa = empresa;
        this.empresa_cor = empresa_cor;
        this.empresa_contato = empresa_contato;
        this.empresa_url = empresa_url;
        this.empresa_telefone = empresa_telefone;
        this.empresa_idioma = empresa_idioma;
    }

    public QueueContent() {
    }
}

I'm using Lombok to generate Getters / Setters)
This is the child class:
@Data
public class EmailCameraOffline extends  QueueContent {
    private Timestamp camera_last_online;
    private String camera_nome;
    private String empresa_url_plataforma;

    public EmailCameraOffline(String empresa, String empresa_cor, String empresa_contato, String empresa_url, String empresa_telefone, String empresa_idioma, Timestamp camera_last_online, String camera_nome, String empresa_url_plataforma) {
        super(empresa, empresa_cor, empresa_contato, empresa_url, empresa_telefone, empresa_idioma);
        this.camera_last_online = camera_last_online;
        this.camera_nome = camera_nome;
        this.empresa_url_plataforma = empresa_url_plataforma;
    }

    public EmailCameraOffline() {
    }
}

So I've done:

 EmailCameraOffline infosEmail = new ObjectMapper().readValue(content, EmailCameraOffline.class);
                System.out.println(infosEmail);

And the output is:
 EmailCameraOffline (camera_last_online = 2020-03-12 03: 01: 45.0, camera_nome = Pier Cam 1, empresa_url_platform = null)

How do I get my EmailCameraOffline object to have the superclass attributes initialized?

A: Everything should be loaded and initialized just fine, so calling:
System.out.println(infosEmail.getEmpresa());

should give expected value.
Problem
The problem is in the default implementation of toString() method (done via @Data) at EmailCameraOffline class, which does not include inherited fields.
Solution
To fix this you can "override" @Data's toString() implementation to include inherited fields as well using Lombok as:
@Data
@ToString(callSuper = true)
public class EmailCameraOffline extends QueueContent {
...
}


Q: SOLR - DataImportHandler - how to map multiple objects inside one list of json objects I am new to SOLR,I am trying to index oracle DB query results using SOLR. I have written config.xml and added indexes in schema.xml as well.
I have multiple queries as sub-entities(with child=true) in my config.xml file. Many of the queries are returning multiple rows. For example I have one entity as
<entity name="example_subentity" child="true" query="SELECT A,B from table_temp">
    <field column="A" name="a" />
    <field column="B" name="b" />
</entity>

which returns output as
"response":{"numFound":1,"start":0,"docs":[
      {
        "unique_key":"4493234234",
        "_version_":1560479076226957312,
        "_childDocuments_":[
        {
          "a" : "value_a_1",
          "b" : "value_b_1",
        },
        {
          "a" : "value_a_2",
          "b" : "value_b_2",
        }]
      }]}

what I am trying to achieve here is, something like
 "_childDocuments_":[
      {"table_temp_response" :[
        {
          "a" : "value_a_1",
          "b" : "value_b_1",
        },
        {
          "a" : "value_a_2",
          "b" : "value_b_2",
        }]
        }]

Can anyone guide me, how I can get this kind of output using DIH?
Just a update I am looking for a server side solution, I can do this using java or SOLRJ in client side. But I have multiple client which are going to consume SOLR query response.

A: if you use Solrj
JSONArray jArray = new JSONArray();

        for (int i = 0; i < docList.size(); i++) {
            JSONObject json = new JSONObject(docList.get(i));
            jArray.put(json);
        }

>

for (int i = 0; i < jArray.length(); i++) {
            JSONObject obj = objs.getJSONObject(i);
            obj.getString("a"));


Q: how to detect execution environment? I would like to have a pair ofdb-specmaps with my database configuration for development and production.
But I can't find an easy way to detect the current execution environment. Need something like (defn db-spec [] (if (is-dev?) { dev-spec-here } { prod-spec-here })).
Maybe it can detect the current lein profile. No matter how I ask to google. Can't find how.

A: I'm fond of using environment variables for this (which can be set system wide for example in /etc/profile amongst other places). others prefer to pass a -D definition to the JVM

A: your code is okay, detect it depend your environment, like hostname, IP arrdress, global variable etc.


Q: why do i get a circular import error on whichever module that comes first but not on the second? I am making a simple inventory program for college assignment. however i keep getting a circular import error on one of the module. i get the error on the module import that comes first and not on the second. but the strange thing is, if i were to switch the import order, the previous erroneous import works and the previously working import returns an error.
Elaboration:
when running as this, import A has circular import error and import B works fine.
import A
import B

But if i run the program as this, import B has circular import error and import A works fine
import B
import A

why is this happening? what is the problem here?
This is the main module.
import purchase
import addition

def choices():
    print("Press any of following number for a course of action")
    print("1. To Purchase Bikes")
    print("2. To Add Bikes in the Stock")
    print("3. Exit the program\n")
    value = 0

    while not value in range(1, 5):
        try:
            value = int(input("Enter your desired number: "))
        except:
            print("\n\nPlease enter a valid number between 1-5:\n")

    if value > 3 or value < 1:
        print("\nInvalid Input!! Please select from the given.\n")
        choices()

    elif(value == 1):
        purchase.purBikes()

    elif(value == 2):
        addition.addStock()

    elif(value == 3):
        quit()

choices()

The whole program is available here. i know its a lot to look through but i didn't know what parts to remove to make a minimalized reproduceable example.
https://filebin.net/zgr985zo5wao5c0e

A: You have to rethink the design.
addition.py:
import Main
def addStock():
    # The 2 last lines
    Main.choices()
    return shipCost

A module is a library of reusable components, so they can not depend on some "Main", they must work anyhere, specially on unit tests.
Also, you call addition.addStock() in Main.choices(), so there is a circular call. When does it return shipCost?

A: First off, your welcome function is not defined(I dont see it if it is)
Second, module purchase doesnt exist publicly so it may be the problem


Q: ggplot/qqplotr returns error on data format I am trying to create a QQ and/or PP plot from the air_time data inside the flights data frame belonging to the nycflights13 package. I am using ggplot with qqplotr.
This is my code:
library(nycflights13)
library(qqplotr)

ggplot(data = flights$air_time, mapping = aes(sample = norm)) +
  stat_qq_band() +
  stat_qq_line() +
  stat_qq_point() +
  labs(x = "Theoretical Quantiles", y = "Sample Quantiles")

When I try to run this I get the error:
Error: `data` must be a data frame, or other object coercible by `fortify()`, not a numeric vector

What is causing this error and how do I fix it? I normally call ggplot as follows so I do not know if there could be issues there:
ggplot(flights, air_time, aes(sample = norm))

A: Change the sample argument to reflect the variable inside the data.
Air_time <- flights[, "air_time"] # Or select a random sample to save time
ggplot(data = Air_time, mapping = aes(sample = air_time)) +
  stat_qq_band() +
  stat_qq_line() +
  stat_qq_point()


Q: "Fragment file is not indexed" in Signac/R I am currently running an snATAC-seq analysis and performed the following command:
chrom_assay <- CreateChromatinAssay(
   counts = counts,
   sep = c(":", "-"),
   genome = 'mm10',
   fragments = '../vignette_data/atac_v1_pbmc_10k_fragments.tsv',
   min.cells = 10,
   min.features = 200
)

Now, my error comes out as
Error in CreateFragmentObject(path = fragments, cells = cells,
validate.fragments = validate.fragments,
:Fragment file is not indexed.

Could someone provide possible solutions to mitigate this?

A: As written in the documentation of the function CreateChromatinAssay, the fragments =  file should be a tabix file (ending in .tbi) containing the index with fragments of your data, or a Fragments object in R.
Apparently, first you will need to create the Fragments object in R from your tsv data, using the function CreateFragmentObject(). Take a look at: https://satijalab.org/signac/reference/fragments .

A: Based on the advise from the Signac developer in https://github.com/timoast/signac/issues/7#issuecomment-513934624 , the folder with the fragments file should also contain the fragment index file (.tbi). For example, for the human 10X PBMC vignette data (https://satijalab.org/signac/articles/pbmc_vignette.html): atac_v1_pbmc_10k/atac_v1_pbmc_10k_fragments.tsv.gz and
atac_v1_pbmc_10k/atac_v1_pbmc_10k_fragments.tsv.gz.tbi should be in the same folder. Hope this helps. Thanks.

A: Please see this Github issue to regenerate .tbi file
Briefly, run the following cmds in linux/unix terminal :

*

*gzip -d <fragment.tsv.gz>

*bgzip <fragment.tsv>

*tabix -p bed <fragment.tsv.gz>


Q: When i press Stop and then Play the sound dont works i have a simple app with 2 buttons. When i press Play, the sound run correctly, but when i press Pause and then play, the sound don´t works.
Why?
Here my code:
    import android.app.Activity;
    import android.media.MediaPlayer;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
public class MainActivity extends Activity {

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

final MediaPlayer mp = MediaPlayer.create(this, R.raw.sound);

 Button Play = (Button) findViewById(R.id.button1);
    Play.setOnClickListener(new OnClickListener(){

    @Override
    public void onClick(View v) {
        mp.start();
    }});

    final Button button2 = (Button) findViewById(R.id.button2);
    button2.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

         mp.stop();
         //mp.reset();

        }
    });

}
}

A: change to this:
button2.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
    if (mp != null) {
         mp.stop();
         mp.release();
    }
    }
});

A: Don't use stop() for pausing media. Use pause() and check isPlaying() or not before pausing() it.


Q: How to round up a floating variable in c upto 2/3/4....n digits precision without using  and printf(".n%f") float f = 2.8386483,g ;
//Suppose I am having f = 2.8386483..... I want to store k = 2.8.... to n positions where n=a natural //number
//e.g. g= 2.83 to 2 decimal precision/n=2
    //   g = 2.838 to 3 decimal precision/n=3

A: Without using math.h, or printf(“.n%f”), the other answer will work for you.
But regarding your phrase I want to store k = 2.8.... to n positions.  It may be interesting to you that this has less to do with rounding than it has to do with type, and how much memory is required to store each type.
float, double and long double require differing amounts of memory to store the precision (numbers to the right of ".") required by the type, regardless of how you format them for display.   That is:
A displayed representation of a float may look like 2.83
while in memory, a float will contain memory sufficient to 7 digits precision 2.8368361 (on 32 bit system)
And for a type double representation of the same number might stored as 2.836836100000001.
Again, the way a number has little to do with how it is stored.
Edit: (Rounding a float to n decimal places)
#include <ansi_c.h>//I did not realized that this header INCLUDEs math.h, oops
int main(void)
{
    int p;

    float a,c;

    printf("Enter the floating point value:-");

    scanf("%f",&a);

    printf("Enter the precision value:-");

    scanf("%d",&p);

    if(a>0)
    {
        c=((int)(a*pow(10,p)+0.5)/(pow(10,p)));
        printf("Value Rounding Off:-%f",c);
    }

    else

    {
        c=((int)(a*pow(10,p)+0.5)/(pow(10,p)));
        printf("Value Rounding Off:-%f",c);
    }
    getchar();
    getchar();
}

From HERE (thanks to H. Gupta)

A: If you want to have n digits, then you can first start with multiplying your number f with 10^n. After that you can turn it into an integer so that the rest of the decimals "disappear" - turn it again into an float and divide by 10^n
However, remember to check for if the number needs to be rounded up or down :)

*

*2 places = 10^2

*2.836836 * 10^2 = 283.6836

*rounding rules: add 0.5 to the number

*283.6836 + 0.5 = 284.1836

*(int) 284.1836 = 284

*284 * 1.0 / 10^2 = 2.84

=>
float f = 10^2 * f + 0.5
int newint = (int) f f = newint * 1.0 / 10^2

A: Scale x and then round.  Make sure to deal with negative numbers correctly if rounding to nearest.
Thanks to @David Heffernan C : x to the power n using repeated squaring without recursive function
float pow10f(unsigned exponent) {
  float base = 10.0;
  float result = 1.0;
  while (exponent > 0) {
    while ((exponent & 1) == 0) {
      exponent /= 2;
      base *= base;
    }
    exponent--;
    result *= base;
  }
  return result;
}

float RoundToNPlaces(float x, unsigned n) {
  if (x < 0.0) {
    return -RoundToNPlaces(-x, n);
  }
  float scale = pow10f(n);  // fix per @Michael Burr
  x *= scale;
  uintmax_t u = (uintmax_t) (x + 0.5);  // Add 0.5 if rounding to nearest.
  x = (float) u;
  x /= scale;
  return x;
}

Does have a range limit though but likely wider than int.

[Edit] per @Michael Burr comment
(int) (RoundToNPlaces( 2.8386483, 2) * 100) --> 283 rather than the expected 284.  What happened though, is correct.  Rounded to 2 places the result of 2.8386483 is mathematically 2.84 but is not representable with typical float.  The 2 closest float to 2.84 are
2.8399999141693115234375000
2.8400001525878906250000000

and RoundToNPlaces( 2.8386483, 2) resulted in the closer one: 2.8399999141693115234375.
Now performing (int) (2.8399999141693115234375f * 100) --> (int) 283.99999141693115234375f --> 283.
This exhibits the necessary compromise to the OP's original goal, finding 2.8386483f rounded to 2 decimal places does not typically lead to an exact answer.  Hence subsequent operations like * 100 and then int conversion lead to unexpected results, not because the best answer was not found in the round to 2 decimal places step, but because the best answer still will not exhibit all the properties of the mathematical exact answer.


Q: Regex return all characters I was using the (.) to match all characters but it return back too with too many matches. How do i make it so it only 1 match?
 private MatchCollection RegexMatchingV2(string data, string regex)
    {
        MatchCollection col = null;
        try
        {
            col = Regex.Matches(data, regex, RegexOptions.IgnoreCase);
        }
        catch (Exception ex)
        {
            Response.Write("RegexMatching ERROR:" + ex.Message);
        }
        return col;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
       MatchCollection col= RegexMatchingV2("return all of this data in 1 match", "(.)");
       Response.Write(col.Count);//Too much matches
    }

A: To make it a single match use (.*)
The single . matches a single character.  The additional * means "zero or more".
Edit In response to the comment about two matches (the first match contains the string, and the second is an empty match):  The Matches documentation indicates that it gives empty matches special treatment.  There is a good example on that page to show the behavior.  But the end result is that after the match, it does not do forward movement, so it picks up an empty match.  To prevent that, you could use beginning of line and end of line anchors:  (^.*$) or use the + to force at least one character to be included:  (.+).

A: Since you want to match any number of any characters, change the . to .* to match zero or more, or .+ to match one or more.


Q: Adding TextView to content_main in Navigation Drawer Template I'm trying to add a TextView to the content_main layout while the setContentView is at activity_main. I am currently using the Navigation Drawer template when you create a new project in Android Studio. Activity_main includes app_bar_main which includes content_main.
Content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:id="@+id/content_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="org.test.testy.test"
    tools:showIn="@layout/app_bar_main"
    android:weightSum="1">

</LinearLayout>

The code I'm trying to use is this:
    LayoutInflater inflater;
    inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = (View) inflater.inflate(R.layout.content_main, null);
    LinearLayout layout = (LinearLayout) view.findViewById(R.id.content_main);
    //Card view create
    CardView cv = new CardView(layout.getContext());
    cv.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
    cv.setVisibility(View.VISIBLE);
    TextView tv = new TextView(layout.getContext());
    tv.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
    tv.setText("Test");
    tv.setVisibility(View.VISIBLE);
    cv.addView(tv);
    layout.addView(cv);

Everything below //Card view create was tested in a blank app, which worked perfectly fine. I also tried to put a TextView in the xml of content_main with an id and trying to read the text, which also returned the correct text. If I am able to access the layout and the code for adding to view is fine, then why is it not working?

A: Two things I was doing wrong:

*

*I had to id each of the <include>s with the EXACT name that it was going to and

*I had to go through each includes because I had two:
LinearLayout layout = (LinearLayout) findViewById(R.id.app_bar_main).findViewById(R.id.content_main);


Q: What is the difference between WPF and Silverlight application? What is the difference between WPF and Silverlight application? Are they the same?

A: Silverlight is a subset of WPF. Once it was known as WPF/E (WPF everywhere). In fact, the base framework is similar, but not the same.
See this for further information:  Silverlight "WPF/E" first steps: Getting started with simple analog clock, Introduction - What is WPF/E?

A: Silverlight is Microsoft’s latest development platform for building next-generation Web client applications
(WPF) is Microsoft’slatest development platform forbuilding next-generation Windows client applications
Silverlight is generally considered to be a subset of
WPF, and is a XAML
WPF is generally considered to be a subset of .NET Framework
Silverlight Support Cross OS, cross browser, cross device
WPF for Windows client users.
in order to run Silverlight applications at client machines, we need to install Silverlight
software on the client machine once
WPF, on the other hand, does notsupport any plug-in mechanism;instead, we need to install a
completed WPF client application
Silverlight applications are hosted within a webserver and a web page.
WPF applications can be deployed as standalone applications,

A: WPF is based off of the desktop CLR which is the full version of the CLR.
Silverlight is based on a much smaller and more compact CLR which provides a great experience but does not have the full breadth of CLR features.  It also has a much smaller version of the BCL.

A:
Silverlight (codenamed WPF/E) is a cross-platform, cross-browser, browser plugin which contains WPF-based technology (including XAML)[17] that provides features such as video, vector graphics, and animations to multiple operating systems including Windows Vista, Windows XP, and Mac OS X, with Microsoft sanctioned 3rd party developers working ports for Linux distributions.[18] Specifically, it is currently provided as an add-on for Mozilla Firefox, Internet Explorer 6 and above, and Apple Safari. Silverlight and WPF only share the XAML presentation layer.

WIKI

A: WPF is essentially the replacement to Winforms in that it is a desktop application platform built on the .Net (3+) platform.
Silverlight represents a subset of WPF that is delivered through a browser plug-in, much like Flash/Flex.

A: Silverlight is a subset of WPF and therefore has fewer features but is more portable.  WPF can be ran in both a browser or as a WinForms style application in Windows while Silverlight can only be ran in a browser.  WPF is intended to run on Windows systems while Silverlight runs on Windows or Mac, also Linux via Moonlight.
If confused on when to use each, I found a useful blog better explaining this: http://blogs.msdn.com/b/jennifer/archive/2008/05/06/when-should-i-use-wpf-vs-silverlight.aspx

A: wpf is window application and  Silverlight  is web application

A: A detailed comparison can be found here: http://wpfslguidance.codeplex.com/


Q: Vertically aligning block element to image? I'm looking for a way to vertically align a block element to an image. On my site this image would dynamically change in height and width so I'd need the vertical alignment to adapt for whatever the image size is. For example:

img { float: left; }

#box { float: right; width: 200px; height: 150px; background-color: #666; }

So I'd want this div to vertically align itself to the image. How can this be done?
Thanks.

A: The trick is to add a couple layers of wrapper-divs. The first layer is set to white-space: nowrap and max-width:50% which means that the elements inside can't wrap, and are constrained to 50% of the width of the parent.
Then you set the white space back to normal, and make the second layer display:inline-block so that these divs have to play by text alignment rules. Then you set both of them to vertical-align:middle; Just one won't work because vertical align is relative to the baseline of the text, not the containing block element.
So in this way we have constrained ourselves to one line of "text", composed of two div elements both aligned such their middle is at the text baseline, and ensured that their size must be no more than 50% of the parent container.
EDIT: I discovered after little more playing that you need to add some max-width:100% to keep the image from pushing the text out the right hand side.
EDIT 2: I should have mentioned that this requires IE-8 standards mode, added meta-equiv to tell IE-8 to behave itself, but giving a proper doctype or sending an http response header can achieve the same thing google IE8 standards mode for all that stuff.

    <title>Test</title>
    <meta http-equiv="X-UA-Compatible" content="IE=8" />

        Lorem ipsum dolor sit amet, consectetur adipisicing elit,
        sed do eiusmod tempor incididunt ut labore et dolore magna
        aliqua. Ut enim ad minim veniam, quis nostrud exercitation
        ullamco laboris nisi ut aliquip ex ea commodo consequat.
        Duis aute irure dolor in reprehenderit in voluptate velit
        esse cillum dolore eu fugiat nulla pariatur. Excepteur sint
        occaecat cupidatat non proident, sunt in culpa qui officia
        deserunt mollit anim id est laborum