text:
Q: Event Brite QR code I've dug through the methods in Event Brite API but can't find any reference to QR codes generated by Eventbrite in their native IOS app.
http://developer.eventbrite.com/doc/#methods
without reverse engineering it or sniffing the web urls - can anyone shed some light on how to do this?

A: I know this is an old thread, but I'm trying to use the Eventbrite barcodes to check visitors in.  @johndpope - did you get any further in your quest?
The codes on each ticket are not QR Codes, but Datamatrix (for reading by the iOS/Android app) and Code 128 (I think).  Both codes on the ticket (and incidently, the QR Code on Conferencebadge.com's app) are simply numeric and take the following form...
{OrderID}{AttendeeID}{Seq}
for example
123456789 123456789 001  (no spaces)
Any bit of barcode generating code can recreate these, but checking people in without an API method is a bit harder.  The iOS/Android app rightly uses HTTPS and you need to be authenticated to the website to use the checkin_update URL used by the website.

A: Eventbrite barcode information is a sensitive issue - but, Eventbrite is happy to discuss specifics over email
If you just want to build a list of QR codes for the current event owner, you should be able to generate them from the barcode_ids returned from the event_list_attendees API call.


text:
Q: Is there a case-insensitive version of the `:/` tree-ish? Let's say I have git commit message Hello World.
:/"World" will find it, :/"world" will not.
Any way to make git match case-insensitively?

A: That does not seem supported by the :/<text> syntax.
This would work, as a workaround:
git log :/[Ww]orld

Or, using the -i/--regexp-ignore-case:
git log -i --grep "world"

redpajama_set_name: RedPajamaStackExchange


text:
Q: zend load js file order I include my jquery.js in layout.phtml,
  <?php $this->headScript()->appendFile($this->baseUrl('js/jquery-1.7.2.min.js')); ?>
  <?= $this->headScript() ?>

and I include my own test.js in the IndexController,
$this->view->headScript()->appendFile('js/test.js');

but zend load the test.js file first, how could I make zend load jquery first ?   because I used query code in test.js file.

A: You could do this by using "offsetSetFile(order, file)".
$this->view->headScript()->offsetSetFile(10, $this->baseUrl('js/jquery-1.7.2.min.js'));
$this->view->headScript()->offsetSetFile(20, $this->baseUrl('js/test.js'));


text:
Q: I am trying to extract text inside span_id, but getting blank output using python beautifulsoup i am tring to extract text inside span-id tag but getting blank output screen.
i have tried using parent element div text also , but fail to extract, please anyone help me.
below is my code.
 import requests
 from bs4 import BeautifulSoup

 r = requests.get('https://www.paperplatemakingmachines.com/')
 soup = BeautifulSoup(r.text,'lxml')
 mob = soup.find('span',{"id":"tollfree"})
 print(mob.text)

i want the text inside that span which is given mobile number.

A: You'll have to use Selenium as that text is not present in the initial request, or at least no without searching through <script> tags.
from bs4 import BeautifulSoup as soup
from selenium import webdriver
import time

driver = webdriver.Chrome('C:\chromedriver_win32\chromedriver.exe')

url='https://www.paperplatemakingmachines.com/'
driver.get(url)

# It's better to use Selenium's WebDriverWait, but I'm still learning how to use that correctly
time.sleep(5)

soup = BeautifulSoup(driver.page_source, 'html.parser')
driver.close()

mob = soup.find('span',{"id":"tollfree"})
print(mob.text)

A: The Data is actually rending dynamically through script. What you need to do is parse the data from script:
import requests
import re
from bs4 import BeautifulSoup

r = requests.get('https://www.paperplatemakingmachines.com/')
soup = BeautifulSoup(r.text,'lxml')
script= soup.find('script')
mob = re.search("(?<=pns_no = \")(.*)(?=\";)", script.text).group()
print(mob)

A: Another way of using regex to find the number
import requests
import re
from bs4 import BeautifulSoup as bs

r = requests.get('https://www.paperplatemakingmachines.com/',)
soup = bs(r.content, 'lxml')
r = re.compile(r'var pns_no = "(\d+)"')
data = soup.find('script', text=r).text
script = r.findall(data)[0]
print('+91-' + script)


text:
Q: Proof for an inequality(Trigonometric functions) I would appreciate if somebody could help me with the following problem
Q: How to proof
$$\sqrt{1+a^2-2a\cos t}\leq (1-a)+2a\sin\frac{t}{2}(\text{where}~~ 0\leq a\leq 1, 0\leq t\leq 2\pi)$$

A: Putting $t=2u,$
$$1+a^2-2a\cos2u=1+a^2-2a(1-2\sin^2u)=(1-a)^2+a(2\sin u)^2$$ which will be $$\le (1-a)^2+a^2(2\sin u)^2+2(1-a)a(2\sin u)$$
$$\text{iff  }a(2\sin u)^2\le a^2(2\sin u)^2+2(1-a)a(2\sin u) $$
$$\text{iff  }a\sin u\le a^2\sin u+(1-a)a \text{ as }\sin u \ge0\text{ as }0\le u\le \pi$$
$$\text{iff  }a(1-a)\sin u\le (1-a)a $$
$$\text{iff  }\sin u\le 1 \text{ as } 0\le a(1-a)\le 1 \text{ as } 0\le a\le1$$
which is true
$$\implies 1+a^2-2a\cos2u\le (1-a+2a\sin u)^2$$
Now, follow the advice by GitGud


text:
Q: Firebase query value in time range ordered by desc My goal:
I want to retrieve items from an infinite collection ordered by likes (descending). I also want to limit these results by date and result count, e.g. top 10.
Im not able to manage this case in a nice way propably. This is what I got so far, but I want only the top 10 results and this limitation is missing. If i place a limit() inside the query I dont get the correct results.
Timestamp get timeLimit {
    final limit = DateTime.now().subtract(const Duration(days: 30));
    return Timestamp.fromDate(limit);
  }

QuerySnapshot snapshot =
    await FirebaseFirestore.instance
    .collection('data')
    .where('date', isGreaterThanOrEqualTo: timeLimit)
    .orderBy('date', descending: true)
    .get();

snapshot.docs.forEach((document) {
              Data data = Data.fromJson(document.data());
              resultList.add(data);
              resultList.sort((a, b) => b.likes.compareTo(a.likes));
            });

A: You are hitting a limit of Cloud Firestore. If you have a filter with a range comparison (<, <=, >, >=), your first ordering must be on the same field. [Ref: https://cloud.google.com/firestore/docs/query-data/order-limit-data]
In your case, the second orderBy (on likes) will have an effect only within groups of exactly the same date, which will be pretty useless.

Brainstorming a solution.
(Any recommendation is welcome!)
If your goal is to keep track of the daily / weekly / monthly TOP 10, you should probably maintain that list in Firestore instead of computing the lists for each visitor.
You could have a Cloud Function running every [duration to be defined] to reset the TOP 10 lists.
This comes at a cost but the read operations will be dramatically cheaper for each visitor.
!!! Attention, the following has not been tested.
Such a function could be written as:
const admin = require('firebase-admin');
admin.initializeApp();

const db = admin.firestore();

exports.computeTopTenLists = functions.pubsub.schedule('every 2 hours').onRun((context) => {
  var millisecondsInOneDay = 24 * 60 * 60 * 1000;
  var dailyStart = new Date(Date.now() - millisecondsInOneDay);
  var weeklyStart = new Date(Date.now() - 7 * millisecondsInOneDay);
  var monthlyStart = new Date(Date.now() - 30 * millisecondsInOneDay);
  date.setDate(date.getDate() - 7);

  // Top 10 list (sorted by likes, descending)
  var dailyTopTen = [];
  var weeklyTopTen = [];
  var monthlyTopTen = [];

  db.collection('data').where("date", ">=", monthlyStart ).get().then((querySnapshot) => {
    [
      { list: dailyTopTen, start: dailyStart },
      { list: weeklyTopTen, start: weeklyStart },
      { list: monthlyTopTen, start: monthlyStart },
    ].forEach((curr) => {
      curr.list.push(querySnapshot[0].data());
      querySnapshot.slice(1).forEach((doc) => {
        var data = doc.data();
        data['id'] = doc.id;
        if (data['date'] > curr.start && data['likes'] > curr.list[curr.list.length-1]) {
          curr.list.push(data);
          curr.list.sort((a, b) => (a.likes > b.likes ? -1 : 1));
          curr.list = curr.list.slice(0, 10);
        }
      });
    });
  })

  db.collection('top-ten').document('lists').set({
    daily: dailyTopTen.map(data => ({id: data['id'], title: data['title']})),
    weekly: weeklyTopTen.map(data => ({id: data['id'], title: data['title']})),
    monthlyly: monthlyTopTen.map(data => ({id: data['id'], title: data['title']})),
  });

  return null;
});

You would get the three Top 10 lists with just one document read.


text:
Q: Remove specific rows from data frame conditional on caseid and year I'm a beginner in R, so please be gentle :)
I have a dataframe of the following form:
sampleData <- data.frame(id = c(1,1,2,2,3,4,4),
                     year = c(2010, 2014, 2010, 2014, 2010, 2010, 2014))

sampleData
    id year
  1  1 2010
  2  1 2014
  3  2 2010
  4  2 2014
  5  3 2010
  6  4 2010
  7  4 2014

I want to exclude every id, which does not have both years.
In this case: id "3" only has year "2010".
Therefore I want to conditionally remove ids, which do not have another row with the missing year.
I hope you guys can understand what I'm looking for :(
thank you in advance!

A: We can use ave and check number of rows for each id and select only those rows with length as 2.
sampleData[ave(sampleData$year, sampleData$id, FUN = length) == 2, ]

#  id year
#1  1 2010
#2  1 2014
#3  2 2010
#4  2 2014
#6  4 2010
#7  4 2014

In case if we want to check whether both "2010" and "2014" appear at least once per id we can do
sampleData[as.logical(ave(sampleData$year, sampleData$id, FUN = function(x)
                                            any(2014 %in% x) & any(2010 %in% x))), ]

A: sampleData <- data.frame(id = c(1,1,2,2,3,4,4),
                     year = c(2010, 2014, 2010, 2014, 2010, 2010, 2014))

First you count :
library(plyr)
countBy     <- ddply(unique(sampleData),
              .(id),
              summarise,
              occurence = length(year) ,
              .parallel = F )

Then you subset
sampleData[sampleData$id %in% countBy$id[countBy$occurence > 1],]

A: Here is a solution with data.table
library("data.table")
sampleData <- data.frame(id = c(1,1,2,2,3,4,4), year = c(2010, 2014, 2010, 2014, 2010, 2010, 2014))
setDT(sampleData)
sampleData[, `:=`(n, .N), by=id][n==2]

A: In case you want to make your check more explicit, i.e. not just relying on two rows per id but checking whether both "2010" and "2014" appear at least once per id, you can do something like this in base R:
x <- table(sampleData$id, sampleData$year) > 0
x
#    2010  2014
#  1 TRUE  TRUE
#  2 TRUE  TRUE
#  3 TRUE FALSE
#  4 TRUE  TRUE

ids_to_keep <- row.names(x)[rowSums(x[,c("2010", "2014")]) == 2]
ids_to_keep
#[1] "1" "2" "4"

sampleData[sampleData$id %in% ids_to_keep,]
#  id year
#1  1 2010
#2  1 2014
#3  2 2010
#4  2 2014
#6  4 2010
#7  4 2014

This approach is longer than others but it's also more robust, for example if you can have multiple occurences of the same year per id, then some other approaches may fail or, if you can have other years (not just 2010 and 2014) some other approaches may also fail if they only rely on checking number of occurences per id.

A: There is also a nice dplyr solution:
# create the sample dataset
sampleData <- data.frame(id = c(1,1,2,2,3,4,4),
                         year = c(2010, 2014, 2010, 2014, 2010, 2010, 2014))

# load dplyr library
library(dplyr)

# take the sample dateset
sampleData %>%
        # group by id - thus the function within filter will be evaluated for each id
        group_by(id) %>%
        # filter only ids which were recorded in two separate years
        filter(length(unique(year)) == 2)


text:
Q: ValueError: max() arg is an empty sequence again My code is as follows but presents me with an error message saying
ValueError: invalid literal for int() with base 10: '4\njohn'"

on the line
players.append(Player(elems[e], list(map(int, elems[e+1:e+4]))))

Code:
from __future__ import division
from operator import attrgetter

class Player(object):
    def __init__(self, name, scores):
        self.name = name
        self.scores = scores
        self.highscore = max(scores)
        self.avgscore = sum(scores) / 3

with open('classFilea.txt') as f:
for l in f:
    l = l.strip(); # Remove the end of line char (\n)
text = f.read()
players = []
elems = text.split(',')

for e in range(0,len(elems),4):
        players.append(Player(elems[e], list(map(int, elems[e+1:e+4]))))
    byhighscore = sorted(players, key=attrgetter('highscore'), reverse=True)
    byavg = sorted(players, key=attrgetter('avgscore'), reverse=True)

    print('')
    for p in byhighscore:
        print('{0} {1:g}'.format(p.name, p.highscore))

    print('')
    for p in byavg:
        print('{0} {1:g}'.format(p.name, p.avgscore))

My code is supposed to sort data sorted like :
Ahmed,1,6,4
John,5,3,5
Kali,5,4,7
Larry,4,7,6

By highest score and by average score
Edited code :
from __future__ import division
from operator import attrgetter

class Player(object):
    def __init__(self, name, scores):
        self.name = name
        self.scores = scores
        self.highscore = max(scores)
        self.avgscore = sum(scores) / 3

with open('classFilea.txt') as f:
for l in f:
    l = l.strip(); # Remove the end of line char (\n)
text = f.read()
players = []
elems = text.split(',')

for e in range(0,len(elems),4):
        players.append(Player(elems[e], list(map(int, elems[e+1:e+4]))))
    byhighscore = sorted(players, key=attrgetter('highscore'), reverse=True)
    byavg = sorted(players, key=attrgetter('avgscore'), reverse=True)

    print('')
    for p in byhighscore:
        print('{0} {1:g}'.format(p.name, p.highscore))

    print('')
    for p in byavg:
        print('{0} {1:g}'.format(p.name, p.avgscore))

Now the code is informing me that score is empty.
I printed score in a separate page and it prints "[]"  I have been informed that this is due to my logic of my code. "for l in f loop. After that the current file pointer is at the end of the file, so the following f.read() won't get any data. As PM2Ring said: "You need to reorganize the logic of your code"

A: When you add a list with strings to score:
    players.append(Player(elems[0], map(int, elems[1:])))

, and than try to obtain the max:
    self.highscore = max(scores)

You obtain the error you've mentioned. At this point in your code:
    for line in f:
         elems = line.split(',')
         players.append(Player(elems[0], map(int, elems[1:])))

you need to make sure the "elems[1:]" does not carry strings. It's a parsing problem from your file. If you always have 4 elements for each person (name and 3 numbers) just give that instruction while building a line:
    for i in range(len(elems)//4):
         players.append(Player(elems[4*i], map(int, elems[4*i+1:4*(i+1)])))

Also I would advise you to remove the "map" since it does not have "len", or just replace replace:
    self.avgscore = sum(scores) / len(scores)

by:
    self.avgscore = sum(scores) / 3

If the length of the scores is always 3.

A: If your text file only contains one line you need to handle it accordingly. Assuming there are three values between each name(edited to take into account actually having multiple lines in file):
with open('classFilea.txt') as f:
    players = []
    for line in f:
        elems = line.split(',')
        for e in range(0,len(elems),4):
            players.append(Player(elems[e], list(map(int, elems[e+1:e+4]))))

Here e loops over every fourth index of elems.
An alternative to this approach would be changing how you make the input file so that each line has only one Player data.
In addition your Type Error is probably due to you using Python 3, where map generates an iterator for performance reasons. This can be fixed by turning it back into a list.


text:
Q: string argument without an encoding with postgres and sqlalchemy I am commiting objects to my PostgreSQL database and I try to query it, throws the error
I am using flask-sqlalchemy.
Traceback (most recent call last):
  File "test_populate_questions.py", line 12, in <module>
    question = question_manager.get(id=1).first()
  File "C:\Python38\lib\site-packages\sqlalchemy\orm\query.py", line 3397, in first
    ret = list(self[0:1])
  File "C:\Python38\lib\site-packages\sqlalchemy\orm\query.py", line 3171, in __getitem__
    return list(res)
  File "C:\Python38\lib\site-packages\sqlalchemy\orm\loading.py", line 101, in instances
    cursor.close()
  File "C:\Python38\lib\site-packages\sqlalchemy\util\langhelpers.py", line 68, in __exit__
    compat.raise_(
  File "C:\Python38\lib\site-packages\sqlalchemy\util\compat.py", line 178, in raise_
    raise exception
  File "C:\Python38\lib\site-packages\sqlalchemy\orm\loading.py", line 81, in instances
    rows = [proc(row) for row in fetch]
  File "C:\Python38\lib\site-packages\sqlalchemy\orm\loading.py", line 81, in <listcomp>
    rows = [proc(row) for row in fetch]
  File "C:\Python38\lib\site-packages\sqlalchemy\orm\loading.py", line 580, in _instance
    _populate_full(
  File "C:\Python38\lib\site-packages\sqlalchemy\orm\loading.py", line 726, in _populate_full
    dict_[key] = getter(row)
  File "C:\Python38\lib\site-packages\sqlalchemy\sql\sqltypes.py", line 1707, in process
    value = impl_processor(value)
  File "C:\Python38\lib\site-packages\sqlalchemy\sql\sqltypes.py", line 945, in process
    value = bytes(value)
TypeError: string argument without an encoding

I will describe down here how it is modelled and how I am making the connection.
class Questions(db.Model):
    """ Question model """

    __tablename__ = "questions"

    id = db.Column(db.Integer, primary_key=True)
    question_url = db.Column(db.String(500), nullable=False)
    question_video_url = db.Column(db.String(500), nullable=True)
    category = db.Column(db.String(100), nullable=False)
    topics = db.Column(db.PickleType, nullable=False)
    difficulty = db.Column(db.String(100), nullable=False)
    problem_type = db.Column(db.String(100), nullable=True)
    percentile = db.Column(db.String(100), nullable=False)
    answer = db.Column(db.String(100), nullable=False)
    prompt = db.Column(db.String(1500), nullable=True)

Topics is a PickleType, that is pickled as a list of n values.
Then I have a manager on other file, just to be able to iterate through the db via code, and not needing to be making the API requests always.
Here is the base manager:
class BaseManager(ABC):
    """
    Base Manager object.
    Abstract base class to query the backend.
    """

    @abstractproperty
    def _model(self):
        pass

    def __init__(self, db_uri=constants.DB_URI):
        self.engine = create_engine(constants.DB_URI,  client_encoding='utf8')
        self.get_session = sessionmaker(bind=self.engine)

    def get(self, **filters):
        conditions = []
        for attr_name, value in filters.items():
            if value is not None:
                conditions.append(getattr(self._model, attr_name) == value)
        session = self.get_session()
        ret_values = session.query(self._model).filter(*conditions)
        session.close()
        return ret_values

    def add(self, *args, **kwargs):
        obj = self._model(*args, **kwargs)
        session = self.get_session()
        session.add(obj)
        session.commit()
        session.close()

Then, what I actually am trying to do, that is first adding a question to the table:
question_manager = QuestionManager()

for question in pd.read_csv('test_questions.csv').to_dict('records'):
    user_manager.add(**question)

To iterate through the csv to add the questions, I am using pandas and parsing it to a list of dicts.
Then when I try to get a question from the table.
question_manager = QuestionManager()
question = question_manager.get(id=1)
print(question.first()) # Here is where the error mentioned occurs

Sorry for the long code pasting, I tried to give all the context to the community help me solve this issue!
Can you guys know what is going on?
PS: when I tried with a simple local DB, sqlite, it worked, so I think is something related to postgres specifically.


text:
Q: Search View uses app icon instead of logo Android documents explain that app logo is used everywhere when it is defined. But when the search view expands, app icon is used instead of app logo and I can't find a way to show app logo when search view is in expanded state.
Here are the relevant parts.
Manifest file
<application
    android:name="MyApp"
    android:allowBackup="true"
    android:icon="@drawable/app_icon"
    android:label="@string/app_name"
    android:logo="@drawable/app_logo"
    android:theme="@style/Theme.MyTheme" >

searchable.xml (setting icon doesn't change anything)
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:icon="@drawable/app_logo"
    android:label="@string/app_name"
    android:hint="@string/search_hint" >
</searchable>

menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/menu_search"
        android:actionViewClass="com.actionbarsherlock.widget.SearchView"
        android:icon="@drawable/ic_search"
        android:showAsAction="always|collapseActionView" />

Activity Code
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = new SearchView(getSupportActionBar().getThemedContext());
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
menu.findItem(R.id.menu_search).setActionView(searchView);

NOTE: I use ABS SearchView but same thing happens when I switch to default SearchView.
EDIT : I added some screenshots for clarity.
Here I used the star image for app logo, and android image for app icon.
The first screenshot is the default view of activity.
The second one is the view when I click search button.
It shows the android image while I expect it to be the star image.

A: I had the same problem and I solved it using the following code:
menu.findItem(R.id.menu_search).setOnActionExpandListener(this);
// Your Activity/Fragment must implement the MenuItem.OnActionExpandListener interface

@Override
public boolean onMenuItemActionExpand(MenuItem item) {
    getSherlockActivity().getSupportActionBar().setIcon(R.drawable.uvweb_logo);
    return true;
}

Let me know how this works for you.

A: I achieved the solution with this simple logic:
public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()){
        case R.id.menu_search:
            getActionBar().setIcon(R.drawable.your_logo);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

A: Just remove collapseActionView from your menu Xml.

A: Set the logo drawable as your icon. Via theme attribute
<item name="android:icon">@drawable/ab_logo</item>

or in code
getSupportActionBar().setIcon(R.drawable.ab_logo);

A: To replace the icon with a logo, specify your application logo in the manifest file with the android:logo attribute, then call setDisplayUseLogoEnabled(true) in your activity.
refer this document1
document2
And please see this answer for more details

A: The only thing you need to have set is this (in onCreate of activity):
getSupportActionBar().setIcon(R.drawable.logo);

...not there is also a setLogo.
Regardless to if you have the icon in the manifest set to something different, this will tell the activity to use a different image during runtime.
I tested this with the following menu item and it works:
  <menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@+id/menu_search"
          android:icon="@drawable/ic_action_search"
          android:title="@string/search_hint"
          android:orderInCategory="1"
          android:actionViewClass="android.widget.SearchView"
          android:showAsAction="always|collapseActionView"/>

  </menu>

Inflated like normal in onCreateOptionsMenu:
getSupportMenuInflater().inflate(R.menu.search_menu, menu);

A: You're using a completely different SearchView you declared in menu.xml.
With this code you create new SearchView, which is not what you want.
SearchView searchView = new SearchView(getSupportActionBar().getThemedContext());

So try creating menu like this.
this.getSupportMenuInflater().inflate(R.menu.menu, menu);
final SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
final SearchableInfo info = searchManager.getSearchableInfo(getComponentName());
final MenuItem searchItem = menu.findItem(R.id.menu_search);
final SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setSearchableInfo(info);

And for the ActionBar, instead of setDisplayUseLogoEnabled(true) and others, try set all options at once
final ActionBar bar = getSupportActionBar();
bar.setDisplayOptions(
        ActionBar.DISPLAY_SHOW_TITLE |
        ActionBar.DISPLAY_USE_LOGO |
        ActionBar.DISPLAY_SHOW_HOME |
        ActionBar.DISPLAY_HOME_AS_UP);

This is the setup I have in my current project and never experienced any problems like these.

A: I had the same problem, (for ABS) I had:
    ActionBar actionBar = ((SherlockFragmentActivity) activity).getSupportActionBar();
    actionBar.setLogo(R.drawable.logo);

And I just added:
actionBar.setIcon(R.drawable.logo);

And the issue is gone.

A: I found the best way to solve this problem was to add the SearchView programatically to the menu like this:-
    SearchView searchView = new SearchView(getActionBar().getThemedContext());
    menu.add("Search")
            .setIcon(R.drawable.ic_action_search)
            .setActionView(searchView)
            .setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
                @Override
                public boolean onMenuItemActionExpand(MenuItem item) {
                    getActionBar().setIcon(R.drawable.ic_action_willyweather);

                    return true;
                }

                @Override
                public boolean onMenuItemActionCollapse(MenuItem item) {
                    return true;
                }
            })
            .setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW | MenuItem.SHOW_AS_ACTION_IF_ROOM);

And then use the onActionExpandListener to change the icon/logo to the correct value when then SearchView is expanded.
This solution may also work if you define the SearchView in menu.xml, but you'd then still need to setup the onActionExpandListener() in code to do the same as the above example.
Andy.


text:
Q: Twitter OAuth in console application Is it possible to authorize twitter console application without visiting authentication web page?
I need it because I'm developing app that grab direct messages from our corporate twitter. This console application is scheduled on web server and is not driven by human.
Regards,
Alexey Zakharov

A: Check out TWURL. It's command-line CURL with Twitter OAuth built in: http://github.com/marcel/twurl

A: You can ask Twitter for an access token by supplying a username and password using XAuth. This circumvents the need to redirect to OAuth webpages to get valid access without asking the user for username and password. Applications do need to ask permission from Twitter by email to be able to use this web service method. You should only use it to get a valid access token and then save that, and not persist the username/password in any way. It might be a suitable scenario for your console application?

A: Its possible to authorize any oAuth based API via Console.
if you have some sample code that your working with please share.
Also: http://p2p.wrox.com/content/articles/twitter-development-using-oauth-authenticate-against-twitter-api-walkthroughs


text:
Q: write a string on a jpanel centered I would write on a JPanel a String much bigger respect than other element.which could be the way to paint a string in terms of simply?There is a method to do this?

A: JLabel supports HTML 3.2 formating, so you can use header tags if you don't want to mess with fonts.
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class HtmlHeadersSample extends JFrame {

    public HtmlHeadersSample() {
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setSize(300,200);
    setLocation(100, 100);
    JLabel label1 = new JLabel();
    label1.setText("simple text");
    label1.setBounds(0, 0, 200, 50);
    JLabel label2 = new JLabel();
    label2.setText("
header1 text
");
    label2.setBounds(0, 20, 200, 50);
    JLabel label3 = new JLabel();
    label3.setText("
header2 text
");
    label3.setBounds(0, 40, 200, 50);
    JLabel label4 = new JLabel();
    label4.setText("
header3 text
");
    label4.setBounds(0, 60, 200, 50);

    add(label1);
    add(label2);
    add(label3);
    add(label4);

    setVisible(true);
    }

    public static void main(String[] args) {
        new HtmlHeadersSample();

    }

}

Here's how it looks like:

A: Just set the size of your font
    JLabel bigLabel = new JLabel("Bigger text");
    bigLabel.setFont(new Font("Arial", 0, 30));

A: You could add the text as a JLabel component and change its font size.
public static void main(String[] args) {
    NewJFrame1 frame = new NewJFrame1();
    frame.setLayout(new GridBagLayout());
    JPanel panel = new JPanel();
    JLabel jlabel = new JLabel("This is a label");
    jlabel.setFont(new Font("Verdana",1,20));
    panel.add(jlabel);
    panel.setBorder(new LineBorder(Color.BLACK)); // make it easy to see
    frame.add(panel, new GridBagConstraints());
    frame.setSize(400, 400);
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(NewJFrame1.EXIT_ON_CLOSE);
    frame.setVisible(true);
}

The code will run and look like this :

see also Java layout manager vertical center for more info


text:
Q: How to print a symbol for a code (in coding theory) in Latex I am trying to generate a symbol for a code in coding theory in Latex. I tried \mathcal{C}, but it did not give me the expected output. Can Anyone give me some command or Latex packages I can use?
PD: This is the expected output

and I got


text:
Q: BSON/Binary to string for MongoDB Object ID in Node JS I am working on Change Streams introduced in MongoDB Version 3.6. Change Streams have a feature where I can specify to start streaming changes from a particular change in history. In native driver for Node.js, to resume change stream, it says (documentation here)

Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document.

When I print it in console, this is what I am getting
{ _id:
   { _data:
      Binary {
        _bsontype: 'Binary',
        sub_type: 0,
        position: 49,
        buffer: <Buffer 82 5a 61 a5 4f 00 00 00 01 46 64 5f 69 64 00 64 5a 61 a5 4f 08 c2 95 31 d0 48 a8 2e 00 5a 10 04 7c c9 60 de de 18 48 94 87 3f 37 63 08 da bb 78 04> } },
        ...
}

My problem is I do not know how to store the _id of this format in a database or a file. Is it possible to convert this binary object to string so I can use it later to resume my change stream from that particular _id. Example code would be greatly appreciated.

A: Convert BSON Binary to buffer and back
const Binary = require('mongodb').Binary;
const fs     = require('fs');

Save _data from _id:
var wstream = fs.createWriteStream('/tmp/test');
wstream.write(lastChange._id._data.read(0));
wstream.close();

Then rebuild resumeToken:
fs.readFile('/tmp/test', void 0, function(err, data) {
  const resumeToken = { _data: new Binary(data) };
});


text:
Q: f:ajax don't fired with event "change" The code:
<h:inputText id="date" value="#{holidayRequestController.dates}">
                    <f:ajax execute="date" event="change"
                        listener="#{holidayRequestController.generateDates}"
                        render="generateDate" />
</h:inputText>
<h:panelGroup id="generateDate" class="span8"> ..</h:panelGroup>

With this code when i  using date picker to select a date in from h:inputText, and f:ajax will fire event and populate this date to generateDate component.
But when i change to multiDatePicker, f:ajax don't fired with event "change"(although it work with event "blur", but i have some problem to use "blur").
What should i do to use event "change" for multiDatePicker?
One other question: is there support f:ajax for tag h:inputHidden in jsf?
Thanks for support

A: That can happen if the change event is actually not fired. That can in turn happen if the input element's value is only manipulated via JavaScript and not via enduser interaction.
Basically, when JavaScript manipulates the value via element.value = newValue, and you want the change event to be fired, then the JavaScript should explicitly call element.change() on the input element being manipulated.
According to $.multiDatesPicker documentation, you can use the onSelect option to hook a function on select. In that function you can then just call element.change(). So, given an input as follows:
<h:inputText ... styleClass="multi-dates" />

then you can achieve it as follows:
$(".multi-dates").multiDatesPicker({
    onSelect: function() {
        $(this).change();
    }
});


text:
Q: Why do we use Complex numbers and not other systems? I just started studying Complex analysis and have in fact just switched field to mathematics recently and so please forgive me if this is question seems trivial for a mathematics student to ask.
Question: Why do we use Complex numbers instead of another algebraic field or number system? i.e. It is "natural" to have the hierarchy $\mathbb{N}$, $\mathbb{Z}$, $\mathbb{Q}$, $\mathbb{R}$, $\mathbb{C}$ and not others.
Attempt: I have often been told that $\mathbb{C}$ is algebraically closed (every polynomial with complex coefficients have a root in $\mathbb{C}$) and that it contains $\mathbb{R}$ as a isomorphic subfield.
But should there be other fields or number systems with the same properties as well? Did I miss anything "extra" about $\mathbb{C}$ that makes it special?

A: If an algebraically closed field $F$ contains (a copy of) the real numbers, then $F$ also contains (a copy of) the complex numbers.
Indeed, if we have $\mathbb{R}\subset F$ and $F$ is algebraically closed, then $F$ contains a root $j$ of the polynomial $X^2+1\in \mathbb{R}[X]$. Therefore it contains $\mathbb{R}[j]$, but this field is isomorphic to $\mathbb{C}$: just define $a+bi\in\mathbb{C}\to a+bj\in \mathbb{R}[j]$ and check it's an isomorphism.
The key point is that $\mathbb{C}$ is algebraically closed and algebraic over $\mathbb{R}$.

A: Reading up further, thanks to prompting in the comments, I discovered this: http://en.wikipedia.org/wiki/Algebraic_closure

Using Zorn's lemma, it can be shown that every field has an algebraic
  closure,[1] and that the algebraic closure of a field K is unique up
  to an isomorphism that fixes every member of K. Because of this
  essential uniqueness, we often speak of the algebraic closure of K,
  rather than an algebraic closure of K.

$\mathbb{C}$ is the unique algebraic closure of $\mathbb{R}$.

A: "Algebraically closed" is a heavy loaded notion. Think of the extension ${\mathbb R}\rightsquigarrow{\mathbb C}$ this way instead: We already have the real numbers ${\mathbb R}$ and are extremely successful with them in analysis, geometry,  and physics. Unfortunately the equation $x^2+1=0$, and similar ones which turn up all the time don't have a solution in ${\mathbb R}$. Therefore we need a field $K\supset{\mathbb R}$ containing a number $i$ with $i^2=-1$ as everyday computing environment. It turns out that there are such fields. The simplest one of these is ${\mathbb C}$, consisting of no more than the obviously necessary numbers $x+ y\,i$, where $x$, $y\in{\mathbb R}$.

A: I feel it is worth mentioning that there are other number systems that are of interest to mathematicians, although for different reasons, such as the $p$-adics and the quaternions. The complex numbers are most widely used though because of the algebraic properties you have already discussed, along with the fact that they play nicely with the Euclidean norm.

A: There are split-complex numbers and dual numbers, and they are used in certain fields. But the both are "worse" than $\mathbb{C}$: they are not algebraically closed and not fields (have zero divisors).
Still, they have many properties of numbers, allowing full-fledged calculus on them.


text:
Q: Recuperar tildes en c# al enviar correo Hola sucede que tengo un codigo el cual envia a un correo lo que se escibe un formulario pero al recibir el correo no muestra los acentos ni las 'ñ' correctamente, las muestra asi (y ahi deberia de decir ruben martínez nuñez):

Aqui dejo el codigo:

string sql = "SELECT nombre FROM FUsuarios WHERE Nombre = '" + Session["Nombre"] + "'";
SqlCommand cm = new SqlCommand(sql, con);
string nombre = Convert.ToString(cm.ExecuteScalar());
MailMessage Msg = new MailMessage();
MailAddress fromMail = new MailAddress("remitente@gmail.com");
Msg.From = fromMail;
Msg.To.Add(new MailAddress("destinatario@gmail.com"));

Msg.Subject = nombre;
Msg.Body += "PRE SOLICITUD DE FINANCIAMIENTO
";
Msg.Body += "CLIENTE:" + cod.Text + " - " + nom_prod.Text + "
";
Msg.Body += "STATUS: " + Status.SelectedValue;

...ETC

Msg.IsBodyHtml = true;
string sSmtpServer = "";
sSmtpServer = "smtp.gmail.com";
SmtpClient a = new SmtpClient();
a.Host = sSmtpServer;
a.Port = 587;
a.Credentials = new System.Net.NetworkCredential
("remitentet@gmail.com", "password");
a.EnableSsl = true;
a.Send(Msg);
con.Close();
return true;

A: Este problema se relaciona con el encoding, tienes que asignar
MailMessage.BodyEncoding Property
Msg.IsBodyHtml = true;
Msg.BodyEncoding =  System.Text.Encoding.UTF8;


text:
Q: How can I make I make my GUI stay maximized ONLY if a certain window is open? I have a gui that helps me automate certain things, but only certain things in a specific program. I want my GUI to minimize itself when the program I use it for is not active, and be able to maximize itself when I activate that window again. Any help is appreciated. Also keep in mind, I'm pretty new to this! Thanks.
While 1
    Sleep(100)
If WinActive("My Program") Then
   WinSetState("My GUI", "", @SW_RESTORE)
   WinSetOnTop("My GUI","",1)
Else
   WinSetState("My GUI", "", @SW_MINIMIZE)
Endif
Switch $nMsg
Case $button1
   function()
Case $button2
   function()
EndSwitch
Wend

A: Looks like your code would continuously set your GUI on top and minimize if your program is active.  This may help:
Global $ghActive
Global $ghMyProgram = WinGetHandle("My Program")
; if you're not already using a global handle for your gui
Global $ghMyGUI = WinGetHandle("My GUI")
While 1
    Sleep(100)
    $ghActive = WinGetHandle("[ACTIVE]")
    If $ghActive = $ghMyProgram Then
        WinSetState($ghMyGUI, "", @SW_RESTORE)
        WinSetOnTop($ghMyGUI, "", 1)
    ElseIf $ghActive <> $ghMyGUI And $ghActive <> $ghMyProgram Then
        WinSetOnTop($ghMyGUI, "", 0)
        WinSetState($ghMyGUI, "", @SW_MINIMIZE)
    EndIf
    Switch $nMsg
        Case $button1
            function()
        Case $button2
            function()
    EndSwitch
WEnd


text:
Q: How to add additional assembly references to Linq2SQL DBML file? I have an DBML file in which I am using the IPAddress class (System.Net) to map a field in the database. Yet, I didnt find a way to have the DBML designer remember that it should add a "using System.Net" to the generated code.
Adding it manually works until the next time I save the file. Aint there a way to specify additional assemblies? I thought that specifying, like it already does for the predefined types, would work (like in "string (System.String)" but that just messes it up because it would insert literally "IPAddress (System.Net.IPAddress)" as type.
So, how do I get non-standard types into the O/R Designer so i can edit them too?

A: Well, using the fully classified name of the type (in this case System.Net.IPAddress) it actually works. Although of course it doesnt add the "using System.Net;" so one must have it referenced already.


text:
Q: Time complexity (Big O) of nested loops, going through an array of objects, each containing an array property I'm wondering what the big O notation would be this javascript algorithm:
const a = [
  {
    b: [1, 2, 3],
  },
  {
    b: [4, 5, 6],
  },
  {
    b: [7, 8],
  },
  {
    b: [9, 10, 11, 15, 61],
  },
];

for (let i = 0; i < a.length; i++) {
  for (let j = 0; j < a[i].b.length; j++) {
    console.log(a[i].b[j]);
  }
}

where the array a contains an arbitrary number of objects, each containing an array b of arbitrary length.
Intuitively I think the complexity of the algorithm woudln't grow exponentially, so the best guess I came up with is something like O(n) + O(m). I'm wondering if that is correct and if there's a better way to write this as Big O.

A: You pass throught each final element once and only once.
So the complexity is just O(n)  with n the total number of elements.


text:
Q: No speedup with precompiled headers on gcc (but large speedup with visual studio) I'm working on a large project that must builds under multiple environment, chiefly linux/gcc and windows/msvc. To speed up the build, we use precompiled headers.
The Windows implementation is very efficient: on my quad-core hyperthreaded i7 build time goes down from 9 minutes to 1.5 minutes. However using precompiled headers doesn't seem to improve performance: in both cases it builds in 22 minutes under a virtual box on the same computer, or about 40 minutes on a real server.
So I'm thinking the obvious, that I somehow got something wrong and that the precompiled header isn't kicking in. I can't find what however.
Our Makefiles are generated by CMake, so I can copy paste the code used to compile the header and the object files that uses them.
Creating the header:
/usr/bin/c++ -O3 -DNDEBUG --no-warnings "-I/mnt/code/server a/src/game"
"-I/mnt/code/server a/src/game/vmap" "-I/mnt/code/server a/dep/include/g3dlite"
"-I/mnt/code/server a/dep/include" "-I/mnt/code/server a/src/shared"
"-I/mnt/code/server a/src/framework" "-I/mnt/code/server a/buildlinux"
"-I/mnt/code/server a/buildlinux/src/shared" -I/usr/include/mysql
"-I/mnt/code/server a/dep/acelite" -DDO_MYSQL -DHAVE_CONFIG_H
-DVERSION=\"0.6.1\" -DSYSCONFDIR=\"../etc/\" -D_RELEASE -D_NDEBUG -x c++-header
-o "/mnt/code/server a/buildlinux/src/game/pchdef.h.gch" "/mnt/code/server
a/src/game/pchdef.h"

Compiling an object file:
/usr/bin/c++ $(CXX_DEFINES) $(CXX_FLAGS) "-I/mnt/code/server
a/buildlinux/src/game" -include pchdef.h -Winvalid-pch -o
CMakeFiles/game.dir/AccountMgr.cpp.o -c "/mnt/code/server
a/src/game/AccountMgr.cpp"

Insights are appreciated, even if they don't directly derive from the snippets above.

A: There are a couple of things that you need to pay attention to when using precompiled headers in GCC. First of all, the precompiled header must be created with the same arguments as the cpp files are being compiled. Also I assume you have actually included the precompiled header in AccountMgr.cpp?
Try to compile with the -H flag, this will output which include files are being considered. Check that the pchdef-file is mentioned, and see what other include files are being parsed. To have gcc complain about invalid PCH files, consider using -Winvalid-pch.


text:
Q: Http is not working even adding Exception Domain in IBM Worklight? I am using xcode 7.3. While parsing values to http server the following log is received "App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file".
Even after adding "App transport security settings" and setting "Allow arbitrary load = Yes", the same error is received. Adding Exception domain also does the same.
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <string>YES</string>
    <key>NSExceptionDomains</key>
    <dict>

        <key>192.9.200.38</key>
        <dict>
            <key>NSIncludesSubdomains</key>
            <true/>
            <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
        <key>192.9.200.91</key>
        <dict>
            <key>NSIncludesSubdomains</key>
            <true/>
            <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>

    </dict>
</dict>

How to resolve the issue?

A: What are those IP addresses translate to...? They may be the wrong ones to use.
See the following blog post regarding IBM MobileFirst Platform and ATS: https://mobilefirstplatform.ibmcloud.com/blog/2015/09/09/ats-and-bitcode-in-ios9/
Add this (and only this, replacing whatever you have now):
<key>NSAppTransportSecurity</key>
<dict>
  <key>NSExceptionDomains</key>
  <dict>
    <key>localhost</key>
    <dict>
      <!--Include to allow HTTP requests-->
      <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
      <true/>
    </dict>
  </dict>
</dict>


text:
Q: Binding to User Control Properties in an Items Control Can someone tell me why the way I am binding data here does not work? I was able to do this fine with using a GridView.  I am not sure why the data is not being passed to the user control here, in addition it compiles fine and shows the user controls with there default text
Main.xaml.cs:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace ItemsControlSample
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();
    }

    /// <summary>
    /// Invoked when this page is about to be displayed in a Frame.
    /// </summary>
    /// <param name="e">Event data that describes how this page was reached.  The Parameter
    /// property is typically used to configure the page.</param>
    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        PopulateData();

    }

    public class someKindaOfDataHolder
    {
        public string Text1;
        public string Text2;
    }

    private void PopulateData()
    {
        List<someKindaOfDataHolder> dataAndStuff = new List<someKindaOfDataHolder>();

        for (int i = 0; i < 5; ++i)
        {
            dataAndStuff.Add(new someKindaOfDataHolder()
            {
                Text1 = "data spot 1: " + i.ToString(),
                Text2 = "data spot 2: " + (i + 2).ToString()
            });

        }

        ListOfAUserControls.ItemsSource = dataAndStuff;
    }

}
}

Main.xaml
<Page
x:Class="ItemsControlSample.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:ItemsControlSample"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
    <ScrollViewer>
            <ItemsControl x:Name="ListOfAUserControls" ItemsSource="{Binding}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                        <local:CustomUserControl DynamicText1Text="{Binding Text1}"  DynamicText2Text="{Binding Text2}" Margin="0,0,10,0"/>
                    </DataTemplate>
            </ItemsControl.ItemTemplate>
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Horizontal" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="100,46,-50,0"/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>

        </ItemsControl>
    </ScrollViewer>

</Grid>
</Page>

CustomUserControl.xaml.cs:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236

namespace ItemsControlSample
{
public sealed partial class CustomUserControl : UserControl
{

    public static readonly DependencyProperty DynamicText1Property =
     DependencyProperty.Register("DynamicText1Text", typeof(string), typeof(CustomUserControl), new PropertyMetadata(null, OnDynamicText1PropertyChanged));

    public string DynamicText1Text
    {
        get { return (string)GetValue(DynamicText1Property); }
        set { SetValue(DynamicText1Property, value); }
    }

    public static readonly DependencyProperty DynamicText2Property =
     DependencyProperty.Register("DynamicText2Text", typeof(string), typeof(CustomUserControl), new PropertyMetadata(null, OnDynamicText2PropertyChanged));

    public string DynamicText2Text
    {
        get { return (string)GetValue(DynamicText2Property); }
        set { SetValue(DynamicText2Property, value); }
    }

    public CustomUserControl()
    {
        this.InitializeComponent();
    }

    private static void OnDynamicText1PropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var obj = d as CustomUserControl;
        obj.DynamicText1.Text = e.NewValue.ToString();
    }

    private static void OnDynamicText2PropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var obj = d as CustomUserControl;
        obj.DynamicText2.Text = e.NewValue.ToString();
    }
}
}

CustomUserControl.xaml:
<UserControl
x:Class="ItemsControlSample.CustomUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:ItemsControlSample"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="800"
d:DesignWidth="800">

<Grid Background="Blue">
    <Grid.RowDefinitions>
        <RowDefinition Height="6*"/>
        <RowDefinition Height="2*"/>
    </Grid.RowDefinitions>

    <Image  Source="ms-appx:///Assets/MSIcon.png" />
    <StackPanel Grid.Row="1"   Margin="25">
        <TextBlock Text="Obay" FontSize="45" />
        <TextBlock x:Name="DynamicText1" Text="DynamicText1" FontSize="35" />
        <TextBlock x:Name="DynamicText2" Text="DynamicText2" FontSize="35" />
    </StackPanel>
</Grid>
</UserControl>

Thanks!

A: You need to set the DataContext somewhere. Without it - your bindings have no context and they fail (look at the Output window in VS when debugging Debug builds to see binding errors). You are setting ItemsSource="{Binding}" where the binding has no context.
Then again - you are overriding the ItemsSource elsewhere with your "ListOfAUserControls.ItemsSource = dataAndStuff;" call, so that is likely not the issue causing your problem in the end. The DataContext of an item in an ItemsControl should be set automatically to an item in the ItemsSource collection.
Another problem that might block you there is that someKindaOfDataHolder.Text1 in your case is a field and it should be a property to work with bindings - try this instead:
public string Text1 { get; set; }


text:
Q: .NET Reflection - Getting the Assembly object instance to a Referenced Assembly I have a solution called StoreExample
It has one web project - StoreExample.Web
It has one class library StoreExample.Core
Web has a reference to Core. What is the proper way to get an assembly reference to StoreExample.Core so I can loop over the classes in StoreExample? It seems like in LoadAssembly() method call I have to know the path to the assembly. Should I have to? If so what is the standard line of code for this? If not, what is the correct way to do it?

A: You should be able to use System.Reflection.Assembly.GetAssembly() as shown below:
Assembly.GetAssembly(typeof(StoreExample.Core.SomeClassInCore));

A: Here's a better answer if you are working with assemblies that are loaded at run time and whose type is not known at compile time. A good real-life example of this is loading 3rd party plugin modules.
http://msdn.microsoft.com/en-us/library/x4cw969y.aspx


text:
Q: Eclipse not being able to recognize special characters My problem is when comparing a branch with the trunk (or vice-versa), using the option Compare With → Branch/Tag the Eclipse I'm using (Neon) points many special characters like ç, ã, õ ... as changed, but I really didn't changed anything there. This makes harder to see the real differences.
Is there an option to disable this check?


text:
Q: Using pandas to count values for each time bin for large dataframe efficiently I have multiple large dataframes (ca. 3GB csv files with ca. 150 million rows each) that contains Unix-style timestamps and random-generated observation ids. Each observation can/will occur multiple times at different times. They look like this:
    time_utc    obs_id
0   1564617600  aabthssv
1   1564617601  vvvx7ths
2   1564618501  optnhfsa
3   1564619678  aabthssv
4   1564619998  abtzsnwe
         ...

I now want to in order to analyse the time development of observations get a data frame that contains columns for each observation id and rows for a time bin that can be changed, e.g. 1 hour, like this:
time_bin aabthssv vvvx7ths optnhfsa  ...
1               1        1        1
2               1        0        0
               ...

I have tried to do this by creating a numpy array of timestamp start points and then adding value_counts for a selection of all rows in that bin to a new, empty dataframe. This runs into MemoryError. I have tried pre-cleaning more, but even reducing the size of the raw data by a third (so 2GB, 100 million rows) still has Memory Errors occuring.
SLICE_SIZE = 3600 # example value of 1h
slice_startpoints = np.arange(START_TIME, END_TIME+1-SLICE_SIZE, SLICE_SIZE)
agg_df = pd.DataFrame()

for timeslice in slice_startpoints:
        temp_slice = raw_data[raw_data['time_utc'].between(timeslice, timeslice + SLICE_SIZE)]
        temp_counts = temp_slice['obs_id'].value_counts()
        agg_df = agg_df.append(temp_counts)
        temp_index = raw_data[raw_data['time_utc'].between(timeslice, timeslice + SLICE_SIZE)].index
        raw_data.drop(temp_index, inplace=True)

Is there a way to do this more efficiently or rather so that it works at all?
Edit: I found my efficient way to do it based on the suggestion to use crosstab. The file size did not need to be reduced. Using the following code resulted in exactly the result I was looking for.
df['binned'] = pd.cut(df['time_utc'], bins=slice_startpoints, include_lowest=True, labels=slice_startpoints[1:])
df.groupby('binned')['obs_id'].value_counts().unstack().fillna(0)

A: You can try cut with crosstab:
slice_startpoints = np.arange(START_TIME, END_TIME+SLICE_SIZE, SLICE_SIZE)
print (slice_startpoints)

df['binned'] = pd.cut(df['time_utc'],
                      bins=slice_startpoints,
                      include_lowest=True,
                      labels=slice_startpoints[1:])

df = pd.crosstab(df['binned'], df['obs_id'])

A: You could read in a large .csv with the 'chunk' iterator, and then perform the calculation on the chunk instead of the the entire .csv file. The chunksize defines the number of rows in a single chunk. That way, you have a good handle to control the memory usage. The downside will be that you will have to add some logic that will merge the results of the chunks.
import pandas as pd
df_chunk = pd.read_csv('file.csv', chunksize=1000)
for chunk in df_chunk:
    print(chunk)


text:
Q: I need to block my feed completly I'm in need a solution via coding. on how to completely hide my blog feed. I know how to optimize related hook and filter such as 'the_excerpt_rss' and 'the_post_rss'. And also understand how to limit access or make my blog private.
So, the question is more about how to blocking feed access without make my blog private ?
I hope the solution will be not some apache .htacceess. Cause I need to code it directly into my theme..

A: This should do it in functions.php without having to edit core WP files:
function fb_disable_feed() {
    wp_die( __('No feed available,please visit our homepage!') );
}

add_action('do_feed', 'fb_disable_feed', 1);
add_action('do_feed_rdf', 'fb_disable_feed', 1);
add_action('do_feed_rss', 'fb_disable_feed', 1);
add_action('do_feed_rss2', 'fb_disable_feed', 1);
add_action('do_feed_atom', 'fb_disable_feed', 1);

Also remove the feed link in your header.php


text:
Q: Unity 5, Mesh Text doesn't appear on Game view Ok so I'm trying to create a Healthbar, with text inside of it.. I also want that text to be contantly changing, so I made a script for it.
public TextMesh HealthText;

void Update()
    {
        AdjustCurrentHealth(0);
        HandleMovement();
        HandleHealth();
        Texts();
    }

    private void Texts()
    {
        HealthText.text = CurHealth.ToString() + " / " + MaxHealth.ToString();
    }

Well, I can change it on the Unity component settings, and it shows on the scene view, but when I press play, the text doesn't appear.
Thanks in advance!

A: I can't really see why it wouldn't work. I just tested the same code you have. What I did was:

*

*Create a new 3D Text game object.

*Assign this object to the public variable (HealthText) of the game object that has your script attached. (VERY IMPORTANT).

*Run the script.

I wonder if the text disappears from the scene view as well when you run?. Maybe this means theres a problem with creating the string.
I hope this helps!


text:
Q: Copying/inserting a Vector I am reading Accelerated C++ and I need few suggestions on the question posted below.

*

*What does this code do?
vector<int>u(10,100)
vector<int>v;
copy(u.begin(), u.end(), v.end());

*Provide 2 possible ways to correct the program, and list its advantages and disadvantages.
The first part was pretty straightforward, but I need help in the second part. I have provided 3 approaches and I am wondering if there are any more possible solutions.
Also, I am not sure of advantages and disadvantages of my approach. I have made an attempt, so please give me your views.

copy()
std::vector<int> u(10, 100);
std::vector<int> v;
std::vector<int> w ;
std::vector<int> x ;
std::copy(u.begin(), u.end(), back_inserter(v)); // 1st way of doing

Advantages

*

*std::copy() doesn't change the value of iterator

*Since the parameters of std::copy() don't depend on the specific container, the code can be reused with different containers

Disadvantages

*

*std::back_inserter() only works with sequential containers and hence cannot be used with maps

*Assigning the wrong iterator value to third parameter of std::copy() will not result in compiler errors but the program may behave differently

insert()
w.insert(w.end(), u.begin(), u.end() );

Advantages

*

*insert() can be used with most containers

Disadvantages
Can't think of any.

push_back()
for ( std::vector<int>::const_iterator it = w.begin(); it != w.end(); ++it )
{
    x.push_back( *it );
}

Advantages
Cant think of any.
Disadvantages

*

*Slow compared to std::copy() or vector::insert().

Is my approach correct? What other possible solutions are there?

A: Your title suggests that you're interested in copying a vector, but your code suggests you're interested in inserting into a vector (keeping in mind that despite its name std::copy is used for insertion here).
If you want to copy:
// This requires the vector types to match exactly
std::vector<int> v = u;

// In case the vector differ in their value_type
// This requires that the value_type of the source be
// convertible to the value_type of the destination
std::vector<int> v(u.begin(), u.end());

If you want to insert, then both methods you describe (using std::copy plus an iterator adaptor or calling the insert member) are appropriate. You should pick one according to whether you're working with containers or with iterators in your particular spot of code. (When working with iterators the burden of using the iterator adaptor is put on the client that passes the iterator, so there's no need to worry about push_back.) If all you have is iterators, then calling e.g. insert is simply not an option; if you do have the containers and one of the members can do the job then feel free to use it. I would not consider an error to use an algorithm though.
Try to leave the explicit loop as a last resort option.

A: It seems to me, the authors mean std::copy() still should be used. So the first solution would be (as you suggested):
std::copy(u.begin(), u.end(), back_inserter(v));

Another one could be:
v.resize(u.size());
std::copy( u.begin(), u.end(), v.begin() );


text:
Q: fiscal year end average returns I have data in the format below with fiscal year start month and fiscal year end month.Using the daily observation for each calendar year, I want to find the average returns for each year such that it will end in the month of fiscal year end and not the end of month for calendar year which is Dec as firms have different fiscal year end.
Thus the average ret for firm A in 1991  will start from the seventh month of 1990 and end on the 6month of 1991 or using firm B the average ret in 1991 will start from the 11 month of 1990 and end on the 10month of 1991.
How do I solve this problem?.Thanks in advance for the assistance.
Compname       Date                    Ret           Fiscal year end month
A             1/01/1990                1.5              6
A             2/01/1990                1.6              6
A             3/01/1990                1.7              6
A             4/01/1990                1.8              6
.
.
.
.
A            31/12/2016              1.8                6
B            1/01/1990                2.5                10
B            2/01/1990                2.6                10
B            3/01/1990                2.7                10
B            4/01/1990                2.8                10
.
.
B            31/12/2016               2.5                10

A: You can do this by adding months and extracting the year.  Here is a method using proc sql:
proc sql;
    select compname, year(intnx('month', date, 12 - fy_end_month)) as fyyyy, avg(ret)
    from t
    group by compname, year(intnx('month', date, 12 - fy_end_month));


text:
Q: Rest Framework not raising error to react native When i send fetch api request to Django backend.
when ever i return this Response:
return Response(
    {
        'message': 'Username is already taken'
    }
) , status = status.HTTP_409_CONFLICT

But in this case, React native, this method did not catch any error, why?
.catch(error_resp => {
    console.warn('error_resp : ')
    console.warn(error_resp)
})


text:
Q: How do I launch MATLAB GUI from a C# application? I designed a Knob using the MATLAB App Designer, the function accepts an arguments and sets the Knob initial value to it. Now, I want to launch the "knob" from my C# application and pass the initial value as argument from the same C# Application.Is it feasible?

A: I'm unfamiliar with MATLAB, but if it's a Windows app, you can launch it running a process.
For example, if the MATLAB app file name is C:\myapp.exe, you can run it as follows:
Process.Start(@"C:\myapp.exe");

A: using System.Diagnostics;
...
Process process = new Process();
// Configure the process using the StartInfo properties.
process.StartInfo.FileName = "path/to/matlab.exe"; //eg. C:\\abc\matlab.exe
process.StartInfo.Arguments = "-n";  //Optional
process.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
process.Start();
process.WaitForExit();// optional, waits here for the process to exit.


text:
Q: How to ignore my development project for installing a package with pip I uploaded my package to testpypi, and installed it via:
pip install -i https://test.pypi.org/simple/ myporj==0.1.6

However it refuse to install it by saying:
Requirement already satisfied: myproj==0.1.6 in ./projs/myproj (0.1.6)

I guess I may add the project in editable mode:
pip install --editable .

However, I know want to disable it. I tried:
python setup.py develop --uninstall

But it has no effect.

A: It may be worth creating a separate env (Virtual Environments) for the installation.
Here are some articles on this subject:

*

*https://docs.python.org/3/tutorial/venv.html

*https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/#creating-a-virtual-environment
Or does it need to be installed in the same place?
You can try to find your package pip search myporj or pip list for show all packages.
And uninstall it later pip uninstall myporj (it may require the right of sudo in linux) then install again.
Maybe you may need --no-cache-dir option to ignore the cache during installation. Here is more details: https://pip.pypa.io/en/stable/reference/pip_install/#caching


text:
Q: How to retain the values of the Spring MVC form backing object? My controller has a method to return a form backing object:
@ModelAttribute("userData")
public UserData formBackingObject() {
    return new UserData();
}

When the form submission fails its validation checks, it is redisplayed but when it is re-rendered, the userData object does not contain the user-submitted values - only the values present upon initialiation above.
@RequestMapping(method = RequestMethod.POST)
public void userData(HttpServletRequest request, @ModelAttribute("userData") UserData userData, BindingResult bindResult, ModelMap model) {

    // do validation checks

    if (bindResult.hasErrors()) {
        // perform redirect back to same page
    }

    return "userData";
}

A: You need to do a model.addAttribute("key", value) . This will help bind the values to the model object check http://static.springsource.org/spring/docs/current/spring-framework-reference/html/mvc.html for sample.

A: @ModelAttribute at method level is generally given to add reference data kind of data to the model. And these annotations are executed before @RequestMapping; hence your attribute "userData" is refreshed with new object before control reaches your public void userData(). method.
The solution is to add userData to the model within the method which returns your userdata form jsp to browser.


text:
Q: Error when using multipart/form-data and setting specific content-Type in stoplight I have an API where I have to pass both file and an object. The API is working properly in postman. Following image shows how I have done this in postman.

I am trying to do the same thing in stoplight. I have written the following code in yaml file.
content:
    multipart/form-data:
      schema:
        type: object
        properties:
          files:
            type: string
            format: binary
          data:
            type: object
      encoding:
        data:
          contentType: apllication/json

When I run the API in stoplight I get following error.

I have followed this link https://swagger.io/docs/specification/describing-request-body/multipart-requests/. Anyone know how can I solve this problem?
Thanks!

A: I am guessing this is about mocking your API via Stoplight. If yes, this looks like something that Stoplight mock doesn't support yet.
Also, you don't need to specify the contentType if you are using the default types. One potential issue I can see is that your data parameter is marked as object but doesn't have any properties defined.


text:
Q: div not separating lines with clear or br Hey guys got a small issue here and a fix would be much appreciated, thank you for the upcoming support.
I have a form and want to post messages whenever there are issues with the login, such as wrong password, or account hasn't been activated, but when I add the bar it just shoves it next to it, instead of putting the form under the message bar.

what am I doing wrong? Here is my jsfiddle: http://www.jsfiddle.net/g1cj39ty/
I am unsure how to post code without indenting 150 lines of code.
              <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">

      <TITLE>2 Column CSS Layout</TITLE>

Please Login

Clean message box

<form id="myForm" action="login.php" method="post">
    Username
    <input type="text" id="un" placeholder="username"/>

    Password
    <input type="password" id="pw" placeholder="password"/>

    <input type="submit" value="Login">

 Forgot Password

 Register

</form>

 copyright 2014

A: Your issue is being cause the display: flex; in #content. That style enables the CSS3 flexbox layout mode which is a way to control the arrangement of elements in a container that can change dimensions. To over simply a bit it is basically a way to make columns.
You can either remove that style, or if you need it you can add flex-direction: column;(the default is row) to force the form below the bar.
This feature is fairly well supported among modern browsers. According to caniuse.com it will work in IE11, Firefox 31+, Chrome 37+, Safari 7+, and Opera 23+. There more details at the caniuse page including some mobile browsers, known issues, and links to more resources.

A: Remove display:flex;
from your #content and go from there.
    #content {
 padding:30px 0 30px 0;
        width:100%;
        background:none repeat scroll 0 0 none;

        align-items:center;
    }
    #content p {
        display: table-cell;
        vertical-align: middle;
    }

Updated Fiddle HERE

A: i think you are looking for something like this is not let me know JSFIDDLE
   body {
        margin:20px;
        font-family:"Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Geneva, Verdana, sans-serif;
        background-color:#555;
    }
    #page {
        background-color:#fff;
        margin:0 auto;
        text-align:left;
        width:755px;
        padding:0 10px;
    }
    #header {
        border-bottom:0px solid #000;
        height:30px;
        line-height:30px
    }
    /* Begin Navigation Bar Styling */
    #nav {
        text-align:center;
        line-height: 30px;
    }
    #nav ul {
        text-align:center;
        font-size:11px;
        width:100%;
        margin:0;
        padding:0;
        display:inline-block;
        list-style:none;
        background-color:#f2f2f2;
        border-bottom:1px solid #ccc;
        border-top:1px solid #ccc
    }
    #nav li {
        margin:auto;
        display:inline-block
    }
    #nav li a {
        display:block;
        padding:8px 15px;
        text-decoration:none;
        font-weight:700;
        color:#069;
        border-right:1px solid #ccc
    }
    #nav li a:hover {
        color:#c00;
        background-color:#fff
    }

    /* End navigation bar styling. */

    #content {
 padding:30px 0 30px 0;
        width:100%;
    position:relative;
        background:none repeat scroll 0 0 none;
        display:flex;
        align-items:center;
    }
    #content p {
        display: table-cell;
        vertical-align: middle;
    }
    #footer {
        height:30px;
        line-height:30px;
        border-top: 1px solid #000;
        font-size:9pt
    }
    #footer p {
        float: right;
    }
    .clear {
        clear: both;
    }

/* FORM CSS */

    form {
        margin:0 auto;
        width: 300px;
        padding: 10px 15px;
        border: #a0a0a0 solid 1px;
        background: #f5f5f5;
    }
label {
    float: left;
    width: 33%;
}

input {
    float: left;
    margin-bottom: 10px;
    width: 65%;
}

input[type=submit] {
padding:5px 15px;
background:#ccc;
border:0 none;
width: 100%;
cursor: pointer;
}
input[type=submit]:hover {
padding:5px 15px;
background:#a3a3a3;
border:0 none;
width: 100%;
cursor: pointer;
}
/* END FORM CSS */

.clean-gray{
border:solid 1px #DEDEDE;
    position:absolute;
    top:0px;
    left:15%;
background:#EFEFEF;
color:#222222;
padding:4px;
text-align:center;
width:500px;
    }


text:
Q: Create a shelf relation from multiple books for different users I have the following relations:
Books(book_id, title, author),
Members(member_id, name, username, password) and
Librarian(librarian_id, name, username, password)
I want to create the relation(s) and schema for the following statements:

*

*Create mini shelf from existing books (for Members and Librarian)

*Members also can use the shelves that are created by the  Librarian.

A: If I've understood the question correctly I would go with something like this:
Merge librarians in the member table and add IsLibrarian column to differentiate the two types of users
Members(member_id, name, username, password, islibrarian)

Shelf(shelf_id, caption, dateopened, owner, etc...)
ShelfDetails(id, shelf_id, bookid)

owner of the shelf is in members table (foreign key) and can be either a regular member or librarian.
What shelves a user can use is then up to your application. You can easily select shelves created by the user and those created by librarians using this schema.
P.S.
It would also be nice when asking questions to show your effort put into solving this like showing what's your idea.

A: Looks like you need something similar to this (non-key fields omitted for brevity):

There is a differentiation between concepts of "creating a shelf" and "using a shelf":

*

*The former is an 1:N relationship and is represented by the foreign key SHELF.USER_ID.

*The latter is an M:N relationship and is represented by the junction table USER_SHELF.

The USER - MEMBER - LIBRARIAN hierarchy1 can be represented either by a single table (possibly with some kind of "type flag") or using one of these strategies.

1 The ER term is "category", aka. subclassing, subtyping, inheritance or generalization hierarchy.


text:
Q: Why git rebase doesn't show commits I want to squash? I'm getting ready to initiate a pull request on a branch I'm working on.  On github, I see that I'm 5 commits ahead of master, so I'd like to squash my commits into one. I run a git log to see what the previous commits are:
git log --oneline

4363273 Updated Order_Entry with bulk UPDATE command
e7e0c64 Updated Order Entry module and Orders Schema
2cff23e Merge branch 'order_schema'
104b2ce Orders Schema
f7d57cf Order Entry updated to handle and log responses from LC
afa1b7b Merge pull request #18 from project/bugfix/mockvenue
4b2c8d8 Return correct string in mock venue API

Now I think I want to squash those top 5 commits listed above (4363273-f7d57cf).  So I then run:
git rebase -i HEAD~5

4363273 Updated Order_Entry with bulk UPDATE command
pick 44768b2 Add script to run simulation on a strategy
pick f82ec8d Implement mock venue
pick f7d57cf Order Entry updated to handle and log responses from LC
pick 4b2c8d8 Return correct string in mock venue API
pick 104b2ce Orders Schema
pick 4363273 Updated Order_Entry with bulk UPDATE command

How come the list of commits shown after running git rebase doesn't match the first 5 commits when I run git log.  Particularly, why do e7e0c64 and 2cff23e appear in git log but not git rebase?
* 4363273 Updated Order_Entry with bulk UPDATE command
*   e7e0c64 Updated Order Entry module and Orders Schema
|\
| *   2cff23e Merge branch 'order_schema'
| |\
| | * 104b2ce Orders Schema
| * |   afa1b7b Merge pull request #18 from project/bugfix/mockvenue
| |\ \
| | |/
| |/|
| | * 4b2c8d8 Return correct string in mock venue API
| |/
* | f7d57cf Order Entry updated to handle and log responses from LC
|/
*   8ed2260 Merge pull request #17 from project/mockvenue

A: Your graph shows numerous merges.  This is the source of the issue.  It's worth noting here that HEAD~5 means "five steps backwards following --first-parent".

Let's cover a bit of background first.  Generally speaking, you can't rebase a merge, and rebase usually doesn't try (it usually just discards them).  Using git rebase -p will try to preserve merges, and will often succeed, but it's very difficult to use interactively (because the edit script does not have a representation for merges).
We can see more once we understand how rebase works.  Suppose that we have a commit graph like this:
          B - C - D   <-- other-branch
        /
... - A
        \
          E - F - G   <-- your-branch

*

*Rebase takes a series of commits, and turns them into changesets / patches.  That is, if you have commits E, F, and G that follow commit A, git must produce a diff from A to E, then from E to F, and finally from F to G.  These represent "how to convert from the base commit" (which is currently A) "to the tip, as a sequence of modifications."

*Then, rebase turns to the new base commit, in this case commit D, and applies these patches in sequence.  The change from A to E, as applied to D, makes a new commit E'.  The change from E to F, applied to E', makes a new commit F'.  The final change becomes G'.
Changing a commit to a patch (by comparing it with its parent) and then applying the patch is literally a git cherry-pick.  In other words, rebase is just a series of cherry-pick operations, picking commits E, F, and G onto a new branch extending from D.  The new commit graph would look like this:
          B - C - D   <-- other-branch
        /           \
... - A               E' - F' - G'   <-- your-branch
        \
          E - F - G   [reflog only]

If we try to do this same thing with a merge commit, we run into a problem.  A merge has two (or more) parents, and cannot be cherry-picked without human assistance: you must tell git cherry-pick which parent is the one to diff against.
What git rebase -p does is redo the merge, rather than attempt a cherry-pick.  The rebase documentation has this example, in which you might rebase A onto Q:
                  X
                   \
                A---M---B
               /
       ---o---O---P---Q

They do not show the result but it should look like this (ideally, with the original A--M--B sequence greyed-out):
                  X--------
                   \       \
                A---M---B   |
               /            |
       ---o---O---P---Q     |
                       \    |
                        A'--M'--B'

Note that new commit M' has to be a merge between A' and (unchanged) commit X.  This works if the merge is a normal (non-"evil") merge but is obviously a bit tricky, at the least.

Let's get back to your particular situation, where git log --graph has given the text below (which I've modified just a bit).  It's a bit hard to turn sideways (the other graphs above have predecessor commits on the left, and successors on the right, while the git log --graph output has predecessors below and successors above), but I'll take a quick stab at it, by adding single-letter codes for each commit:
H   * 4363273 Updated Order_Entry with bulk UPDATE command
G   *   e7e0c64 Updated Order Entry module and Orders Schema
    |\
F   | *   2cff23e Merge branch 'order_schema'
    | |\
E   | | * 104b2ce Orders Schema
D   | * |   afa1b7b Merge pull request #18 from project/bugfix/mockvenue
    | |\ \
    | | |/
    | |/|
C   | | * 4b2c8d8 Return correct string in mock venue API
    | |/
B   * | f7d57cf Order Entry updated to handle and log responses from LC
    |/
A   *   8ed2260 Merge pull request #17 from project/mockvenue

Now with A as the leftmost commit and H as the rightmost:
    C---D
   /___/ \
  //__--E-F
 ///       \
A-----B-----G--H

The direct (first-parent) line of ancestry goes from H to G, then to B, then to A.  This means that HEAD~5 is a commit we can't even see (two to the left of A), and git rebase -i HEAD~5 should list all of these commits except for merges (D, F and G).  That would be five commits: A, B, C, E, and H.  But based on its log message, A is also a merge.  We're missing information here and can't draw the complete graph (which is just as well since the compact form has a lot of lines in it).
In any case, this is in fact what's happening.  The rebase command finds commits to cherry-pick by listing every commit reachable from the tip commit (HEAD, which is commit H) that is not reachable from the first excluded commit (HEAD~5, a commit two steps to the left of A, so we can't see it).  It then throws out merge commits and will cherry-pick each remaining commit to build a new, linear branch.
Whether this makes sense, and which commits you should cherry-pick, are not something anyone else can answer for you.


text:
Q: javascript adding and subtracting using input type checkbox I have code that works but was wondering if there is a way to condense it with JS loops?  I tried but I'm have trouble with it. I'm trying to build a calculator webpage for a game I plan on playing.  The "hide" is a material item for the skinning activity in the game.  I am anticipating that there will be several material items.  Thanks!

total = 0;
hide1 = 1;
hide2 = 1;
hide3 = 1;

function addUp(num, x) {
  if (x == "hide1" && hide1 == 1) {
    temp = document.theForm.ttl.value;
    tempo = parseInt(temp);
    numo = parseInt(num);
    nwTemp = tempo + numo;
    document.theForm.ttl.value = nwTemp;
    hide1 = 0;
    return hide1;
  }
  if (x == "hide1" && hide1 == 0) {
    temp = document.theForm.ttl.value;
    tempo = parseInt(temp);
    numo = parseInt(num);
    nwTemp = tempo - numo;
    document.theForm.ttl.value = nwTemp;
    hide1 = 1;
  }
  if (x == "hide2" && hide2 == 1) {
    temp = document.theForm.ttl.value;
    tempo = parseInt(temp);
    numo = parseInt(num);
    nwTemp = tempo + numo;
    document.theForm.ttl.value = nwTemp;
    hide2 = 0;
    return hide2;
  }
  if (x == "hide2" && hide2 == 0) {
    temp = document.theForm.ttl.value;
    tempo = parseInt(temp);
    numo = parseInt(num);
    nwTemp = tempo - numo;
    document.theForm.ttl.value = nwTemp;
    hide2 = 1;
  }
  if (x == "hide3" && hide3 == 1) {
    temp = document.theForm.ttl.value;
    tempo = parseInt(temp);
    numo = parseInt(num);
    nwTemp = tempo + numo;
    document.theForm.ttl.value = nwTemp;
    hide3 = 0;
    return hide3;
  }
  if (x == "hide3" && hide3 == 0) {
    temp = document.theForm.ttl.value;
    tempo = parseInt(temp);
    numo = parseInt(num);
    nwTemp = tempo - numo;
    document.theForm.ttl.value = nwTemp;
    hide3 = 1;
  }
}
<form name="theForm" style="display:block;border:1px">

    <input type="checkbox" onclick="addUp(4, 'hide1')">
Beginner's Leather Hood

    <input type="checkbox" onClick="addUp(8, 'hide2')">
Beginner's Leather Armor

    <input type="checkbox" onClick="addUp(4, 'hide3')">
Beginner's Leather Shoes

    <input type="checkbox" onclick="addUp(8, 'hide4')">
Novice's Leather Hood

    <input type="checkbox" onClick="addUp(16, 'hide5')">
Novice's Leather Armor

    <input type="checkbox" onClick="addUp(8, 'hide6')">
Novice's Leather Shoes

  Total Number:
  <input type="text" name="ttl" value=0>
</form>

A: I would consider looking at data-* attributes and event listeners.   You could have a data attribute for the value of each checkbox, and then an event listener for the change event of the checkbox.

A: This works for you?
total = 0;
var hide = [];
hide[1] = 1;
hide[2] = 1;
hide[3] = 1;

function addUp(num, x) {
    var index = parseInt(x.replace("hide",""));
    if(hide[index] == 1)
    {
        temp = document.theForm.ttl.value;
        tempo = parseInt(temp);
        numo = parseInt(num);
        nwTemp = tempo + numo;
        document.theForm.ttl.value = nwTemp;
        hide[index] = 0;
        return hide[index];
    }
    else if(hide[index] == 0)
    {
        temp = document.theForm.ttl.value;
        tempo = parseInt(temp);
        numo = parseInt(num);
        nwTemp = tempo - numo;
        document.theForm.ttl.value = nwTemp;
        hide[index] = 1;
    }

}


text:
Q: Why can't `rescue` catch exception classes other than `StandardError` by default? Why has Ruby been designed to handle only StandardError exceptions implicitly by rescue? For other exceptions, why should we need to put them explicitly with rescue?
begin
  #codes here which may generates exceptions
rescue
  #codes to handle some thing which really needed to be done when exceptions there
end

Can anyone help me understand its core?

A: I quote from here:

The chart above shows that most of the subclasses extend a class known
  as StandardError. These are the "normal" exceptions that typical Ruby
  programs try to handle. The other exceptions represent lower-level,
  more serious, or less recoverable conditions, and normal Ruby programs
  do not typically attempt to handle them.

Hope this answers your question.

A: The reason for the default behavior rescue StandardError when you don't give the type explicitly is that you'll typically not want to handle non StandardErrors in your program, at least not without explicitly mentioning them. A couple of typical non-StandardError exceptions are;
LoadError
NotImplementedError
SyntaxError

Normally, you want to know about missing script files in your program, non implemented methods and syntax errors in your code, and not accidentally handle them/ignore them in your exception code.
You can also (NOT recommended) catch any exception using the alternate syntax
rescue Exception => e


text:
Q: determining how many times each integer appears in the input (array) it keeps repeating regardless of whether it's been already calculated or not. You can see the example output. it already calculated the occurrence of 1, but when it sees 1 again, it will calculate it again!
public class SortingInLinearTime {
    public static int[][] howMany(int[] n){

        // Makes a double array list where the second value is occurrence of the first value.
        int[][] a = new int[n.length][2];
        int counter = 0;

        for(int i = 0; i != n.length; i++){
            for(int j = 0; j != n.length; j++) {

                if(n[i] == n[j]){
                    counter++;
                }
            }
            a[i][0] = n[i];
            a[i][1] = counter;
            counter = 0;
        }

        // printer helper function
        for(int i = 0; i != n.length; i++){
            System.out.print(a[i][0] + " occurs ");
            System.out.println(a[i][1] + " times");
        }
        return a;
    }

    public static void main(String[] args) {
        int[] testArray = {1, 2, 3, 1, 2, 3, 4};
        System.out.print(howMany(testArray));
    }
}

output:
1 occurs 2 times
2 occurs 2 times
3 occurs 2 times
1 occurs 2 times
2 occurs 2 times
3 occurs 2 times
4 occurs 1 times
[[I@15db9742

A: In the first loop with i, you are recounting the same values again and again.
1 appears when i = 0 and when i = 3 as well. you once counted for 1 when i == 0 and recounted again at i == 3 in array n.
However, I believe the best solution for your problem could be achieved by changing your data structure from int[][] to an hashmap.

A: Convert your array to list using Arrays.asList() and then use the collections api to get the count.
Collections.frequency(Collection c, Object o)
Updated with the implementation
import java.util.AbstractList;
import java.util.Collections;
import java.util.List;

public class SortingInLinearTime {
    public static int[][] howMany( int[] n){

        // Makes a double array list where the second value is occurrence of the first value.
        int[][] a = new int[n.length][2];

        for(int i = 0; i < n.length; i++){
            int count = Collections.frequency(asList(n), n[i]);
            a[i][0] = n[i];
            a[i][1] = count;
         }

        // printer helper function
        for(int i = 0; i < n.length; i++){
            System.out.print(a[i][0] + " occurs ");
            System.out.println(a[i][1] + " times");
        }
        return a;
    }

    public static List<Integer> asList(final int[] is)
    {
        return new AbstractList<Integer>() {
                public Integer get(int i) { return is[i]; }
                public int size() { return is.length; }
        };
    }

    public static void main(String[] args) {
        int[] testArray = {1, 2, 3, 1, 2, 3, 4};
        System.out.print(howMany(testArray));
    }
}

A: You're making this way harder than it needs to be both by looping over the array twice and by using an array to store your result. Try this:
public class SortingInLinearTime {
    public static Hashtable<Integer, Integer> howMany(int[] n){
        Hashtable<Integer, Integer> toRet = new Hashtable<Integer, Integer>();
        for (int i = 0; i < n.length; i++) {
            if (!toRet .containsKey(n[i])) {
                toRet.put(n[i], 1);
            } else {
                toRet.put(n[i], toRet.get(n[i]) + 1);
            }
        }
        return toRet;
    }

    public static void main(String[] args) {
        int[] testArray = {1, 2, 3, 1, 2, 3, 4};
        Hashtable<Integer, Integer> counts = howMany(testArray);
        Set<Integer> keys = counts.keySet();
        for(Integer key : keys){
            System.out.println(key + " occurs " + counts.get(key) + " times.");
        }
    }
}

This has several advantages. It will not break if you pass an array with large numbers, like {1, 11, 203, 203}, which your current implementation cannot handle. It does not use extra space by declaring an array with many elements that you do not need. Most important, it works.


text:
Q: Setting ivy conflict managers I am trying to set conflict managers in Ivy, but I can't find a concrete example of how to set them. For example, to set the "strict" manager, what would this look like?
<conflict-managers>
  ???
</conflict-managers>

A:
The best book on Ivy I've found is Manning's Ant in Action.

That was me. Ivy has moved on a lot since then, and so have builds
One issue with the ivy conflict managers is that it differs from maven, whose policy is "shallowest on the graph first", that picks the closest one. This is good if you explicitly ask for a version, bad if you have >1 transitive dependency when "closest" isn't what you want.
With ivy you can hit the strict resolve which says "you have to explicitly resolve every single conflict in your dependencies". This adds extra work @ build time, but has a key result: if you explicitly declare the versions of things you want, you are now in control of what you have in your classpath.

A: The Ivy reference documentation strictly follows the XML tag structure of the ivy.xml and ivy-settings.xml files. You are expected to extract the information required directly from the document structure.
Decoding from the Ivy docs:
The conflict-managers tag is for declaring what conflict managers a project may use and configuring them if they accept configuration, not for setting the conflict manager to use.
<conflict-managers>
    <latest-cm name="mylatest-conflict-manager" latest="my-latest-strategy"/>
    <compatible-cm name="my-latest-compatible-conflict-manager" latest="my-latest-strategy"/>

</conflict-managers>

The settings tag has an attribute for choosing the default conflict manager:
<settings defaultConflictManager="strict"/>

Or in an ivy.xml:
<dependencies>
    <dependency.../>
    <conflict manager="strict">
</dependencies>

Note that most of the conflict managers are more liberal in their interpretation of your intentions than you would expect. Two examples:
* Branches are considered irrelevant, if a dependency is available on two branches the "latest" family of resolvers will pick the latest available from either.
* Both the "latest-time" and "latest-revision" resolvers ignore version constraints except to set boundaries on the matching space. e.g. if a depends on b-1.0 and c-1.0 but c-1.0 depends on b-5.0 then you will get b-5.0 despite it not meeting the constraint requested.
I assume your need is result of discovering one of these design flaws.

A: <rant>
Yeah, isn't Ivy documentation a hoot! I mean, does it have to be well organized and complete? Does it really have to make sense. I mean, it's not like my job depends upon it!
Wait a second, it does...
</rant>
Sorry, I have to get the state of Ivy documentation off my chest. It makes Maven documentation look wonderful in comparison.
The best book on Ivy I've found is Manning's Ant in Action. It's a seven year old book that's out of print (but is still available as an ebook. If it wasn't for this book, (which is using Ivy 1.4), I would have been completely lost. Unfortunately, it doesn't delve deep into the Ivy settings.
There is a listing of all of the possible conflict managers buried deep in the Ivy documentation.

*

*all this conflicts manager resolve conflicts by selecting all revisions. Also called the NoConflictManager, it doesn't evict any modules.

*latest-time this conflict manager selects only the 'latest' revision, latest being defined as the latest in time. Note that latest in time is costly to compute, so prefer latest-revision if you can.

*latest-revision this conflict manager selects only the 'latest' revision, latest being defined by a string comparison of revisions.

*latest-compatible this conflict manager selects the latest version in the conflicts which can result in a compatible set of dependencies. This means that in the end, this conflict manager does not allow any conflicts (similar to the strict conflict manager), except that it follows a best effort strategy to try to find a set of compatible modules (according to the version constraints)

*strict this conflict manager throws an exception (i.e. causes a build failure) whenever a conflict is found.

I haven't played around with them, but I believe you simply do the following in the ivy-settings.xml:
<conflict-managers>
    <latest-revision/>
</conflict-managers>

You can also define conflict management in your ivy.xml too which might be a bit more practical since it can be defined on a module-by-module basis.
Of course a few examples would have gone a long way with this, but the Ivy documentation doesn't provide many.


text:
Q: Monitor outgoing specific traffic I have kinda of an idea but I want to consult. I was following this guide for finding out which php processes spawn outgoing brute force attacks. I found the culprits everything is working fine.
Now, how could I make an automatic system for all of this? Some kind of script that inserts the cron job, creates the other script, sets-up everything, finds the IP addresses with grep in the files and then analyzes the other files to give me the specific php process + domain.
Or maybe it would be simplier to have a script to check outgoing traffic for lets say matches as POST /xmlrpc.php.
Or maybe this has been solved all together and I am wasting time.
The specific guide: https://www.nocser.net/clients/index.php/knowledgebase/484/How-to-Detect-Website-Used-for-Hacking-Others.html
Thanks for any input :)

A:
I have kinda of an idea but I want to consult. I was following this guide for finding out which php processes spawn outgoing brute force attacks. I found the culprits everything is working fine.

The problem is that your approach is insane.
You have no idea if the attackers left other backdoors, and you have not patched the vulnerability. The normal response to such security issues is not to find the one script with a problem - but rather restore from backup or code repositories.
That said, there's plenty of Intrusion Detection Systems out there. But the marked is usually for finding compromised machine, not script level - for reasons I outlined above.


text:
Q: Why isalpha() doesn't recognize a letter in a string? I am new in python and I am having some problems with the isaplha() function. I would like to check whether in a variable some of the characters are letters. I have implemented a for loop that goes through all the character and check whether they are letters or not.
variable = '23 Uhr'
for character in variable:
    is_letter = variable.isalpha()
    print(character, is_letter)

The problem is that it doesn't distinguish between letters and digits and gives me 'False' as output for every character (even if it is actually a letter!). I have also tried to use the isdigit() function to verify whether it can distinguish numbers, but also in this case it always returns me 'False'. I think it is a problem that has to do with how the variable is stored. The value that I am using, indeed, is part of a bigger dataframe, but when I use the type() function, it tells me that is a part of the class string. I don't know how to solve the problem.
Thank you !

A: You have a logical error on your code. Instead of
is_letter = variable.isalpha()

it should be
is_letter = character.isalpha()

Working code:
>>> variable = '23 Uhr'
>>> for character in variable:
...     is_letter = character.isalpha()
...     print(character, is_letter)
...
2 False
3 False
  False
U True
h True
r True


text:
Q: wp_nav_menu is not visible with specific theme location In my Wordpress application, wp_nav_menu is not visible. The other menu works as intended.
This is invisible:
<?php wp_nav_menu( array('theme_location' => 'mobile_menu', 'container_class'=>'my-mobile-wrapper')); ?>

This is visible (both are in header.php)
<?php wp_nav_menu( array('theme_location' => 'header_menu', 'container_class'=>'header-menu')); ?>

I read a suggestion from somewhere, but adding this to functions.php didn't work.
add_action( 'pre_get_posts', 'my_pre_get_posts' );
    function my_pre_get_posts($query) {
        if ($query->get('post_type') === 'nav_menu_item') {
            $query->set('tax_query','');
        }
    }

I register as follows:
if (!function_exists('my_register_menus')) {
    function my_register_menus() {

        register_nav_menus(
            array(
                'header_menu' => __('Header Menu', "my"),
                'mobile_menu' =>  __('Mobile Menu', "my")
            )
        );

    }
}

add_action( 'after_setup_theme', 'my_register_menus' );

Thanks by now.

A: OK I found the answer.
I use a function to extend menu contents and I do a structural mistake at that point. I write here for the ones who might face a similar problem:
add_filter( 'wp_nav_menu_items', 'my_extend_menu_content', 10, 2 );

function my_extend_menu_content($items, $args){
    switch .... for menus other than mobile.

    // After the switch block:
    return false; // which is wrong.
    return $items; // should be this way.
}