text:
Q: Iterate over 2 arrays in bash - only looping over first value in each array So i am trying to loop over two array's in bash but im struggling to get this to work, it seems to stop on the first iteration and doesn't loop the entire array, please note i am using IFS as i want to define the separator.
#!/bin/bash

protocol="udp,tcp-client,udp,"
port="1111,2222,3333,"

# split comma separated string into list from VPN_REMOTE_PROTCOL variable
IFS=',' read -a vpn_remote_protocol <<< "${protocol}"

# split comma separated string into list from VPN_REMOTE_PORT variable
IFS=',' read -a vpn_remote_port <<< "${port}"

for index in "${!vpn_remote[*]}"; do

        echo "iptables -A OUTPUT -o docker_int -p ${vpn_remote_protocol[$index]} --dport ${vpn_remote_port[$index]} -j ACCEPT"

done

output is:-
iptables -A OUTPUT -o docker_int -p udp --dport 1111 -j ACCEPT

i want the output to be:-
iptables -A OUTPUT -o docker_int -p udp --dport 1111 -j ACCEPT
iptables -A OUTPUT -o docker_int -p tcp-client --dport 2222 -j ACCEPT
iptables -A OUTPUT -o docker_int -p udp --dport 3333 -j ACCEPT

A: The most immediate problem in the original code was use of vpn_remote as the name of the array for which we're searching for keys, instead of vpn_remote_protocol or vpn_remote_port. The next problem is use of "${!array[*]}", which generates a single string concatenating all the keys together; just as for item in "two words" only runs once, with two words as the value assigned to item, looping over "${!vpn_remote_port[*]}" here would be running for index in... only once, with "0 1 2" as the item. (By contrast, with the incorrect variable name, "" is what "${!array[@]}" evaluates to; in a numeric context that's treated as 0, which is why you see the first item and no others).

Moral Of This Story
Use "${!array[@]}", never "${!array[*]}", ${!array[*]} or ${!array[@]} without understanding the differences and having an explicit reason.
Thus:
#!/bin/bash

protocol="udp,tcp-client,udp,"
port="1111,2222,3333,"

IFS=',' read -a vpn_remote_protocol <<< "${protocol}"
IFS=',' read -a vpn_remote_port <<< "${port}"

for index in "${!vpn_remote_port[@]}"; do
    echo "iptables -A OUTPUT -o docker_int -p ${vpn_remote_protocol[$index]} --dport ${vpn_remote_port[$index]} -j ACCEPT"
done

...which, when run in an online interpreter, emits as output:
iptables -A OUTPUT -o docker_int -p udp --dport 1111 -j ACCEPT
iptables -A OUTPUT -o docker_int -p tcp-client --dport 2222 -j ACCEPT
iptables -A OUTPUT -o docker_int -p udp --dport 3333 -j ACCEPT

Going Deeper: Why The Other Alternatives Are Each Wrong
Why "${!array[@]}"? Let's compare behavior of each, but in a more challenging case when our keys aren't purely numeric (though we could generate bugs by using the incorrect approaches even with purely-numeric keys, if we had numbers in our IFS value):
declare -A array=(
  ["first key"]="first value"
  ["second key"]="second value"
  ["third key"]="third value"
)

printf '%s\n' 'Using "${!array[@]}":'
printf ' - %s\n' "${!array[@]}"

printf '\n%s\n' 'Using "${!array[*]}":'
printf ' - %s\n' "${!array[*]}"

printf '\n%s\n' 'Using ${!array[*]}:'
printf ' - %s\n' ${!array[*]}

printf '\n%s\n' 'Using ${!array[@]}:'
printf ' - %s\n' ${!array[@]}

...for which we see the following output:
Using "${!array[@]}":
 - second key
 - third key
 - first key

Using "${!array[*]}":
 - second key third key first key

Using ${!array[*]}:
 - second
 - key
 - third
 - key
 - first
 - key

Using ${!array[@]}:
 - second
 - key
 - third
 - key
 - first
 - key

So:

*

*"${!arrayname[*]}" is wrong because it expands to a single string with all the keys concatenated (with the first character in IFS -- a space by default -- between them).

*${!arrayname[*]} and ${!arrayname[@]} are both wrong because the keys are subject to word-splitting and glob expansion before they can be treated as a list of items

*"${!arrayname[@]}" does the Right Thing, treating each key as a single word, not subject to operations that could mangle it first.

A: You should iterate over ${!vpn_remote_port[*]} or ${!vpn_remote_protocol[*]}(without ")
But what exactly is happening here? Why only looping over first value in each array? The main reason is wrong array name so index var is empty and it's only one loop. Because you are looping over this "" empty string. And if we try to fetch data from ${vpn_remote_port[$index]} with empty $index it'll return first value(index 0).


text:
Q: OneToMany association is not stored with Doctrine Currently in the process of creating a Member with one or more Subscriptions. Everything works well and the output is what I expect it to be.
When the Subscription is associated with the specified Member and I dump this object before the class finishes, it is all there correctly processed.
The code:
/** @var Member $member */
foreach ($members as $member) {
    $subscription = new MemberSubscription();
    $subscription->setBillingDate(new DateTime('now'));
    $subscription->setMember($member);
    $subscription->setPaid(true);

    $this->em->persist($member);
    $this->em->persist($subscription);
    $this->em->flush();
}

The dump (snippet) after this loop:
Member {#1649 ▼
  #id: 3577
  <...>
  #subscriptions: PersistentCollection {#1616 ▼
    -snapshot: array:1 [ …1]
    -owner: Member {#1649}
    -association: array:15 [ …15]
    -em: EntityManager {#1452 …10}
    -backRefFieldName: "member"
    -typeClass: ClassMetadata {#1601 …}
    -isDirty: false
    -initialized: false
    -coll: ArrayCollection {#1628 ▼
      -_elements: array:1 [▼
        0 => MemberSubscription {#1669 ▼
          #id: 67
          #member: Member {#1649}
          #billing_date: DateTime {#1668 ▶}
          #paid: true
        }
      ]
    }
  }
}

As far as I see, everything went well. The object is not dirty anymore. Whenever the function is done, meaning I leave the page, the object does not contain it's subscriptions anymore.
Here is a dump (snippet) after I load the Member again on a different page:
array:26 [▼
  "id" => 3577
  <..>
  "paid" => PersistentCollection {#1569 ▼
    -snapshot: []
    -owner: Member {#1552 ▶}
    -association: array:15 [ …15]
    -em: EntityManager {#1396 …10}
    -backRefFieldName: "member"
    -typeClass: ClassMetadata {#1565 …}
    -isDirty: false
    -initialized: false
    -coll: ArrayCollection {#1573 ▼
      -_elements: []
    }
  }
]

My Entities;
Member
/**
 * @ORM\Entity(repositoryClass="Foo\Member\MemberRepository")
 * @ORM\Table(name="Foo_Member", options={"charset"="latin1","collate"="latin1_swedish_ci"})
 */
class Member
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     * @var int|null
     */
    protected $id;

    /**
     * @ORM\OneToMany(targetEntity="MemberSubscription", mappedBy="member")
     */
    protected $subscriptions;

    <..>

    /**
     * @return int|null
     */
    public function getId()
    {
        return $this->id;
    }

    <..>

    /**
     * @return mixed
     */
    public function getSubscriptions()
    {
        return $this->subscriptions;
    }

    /**
     * @param mixed $subscriptions
     */
    public function setSubscriptions($subscriptions)
    {
        $this->subscriptions = $subscriptions;

        return $this;
    }
}

MemberSubscription
/**
 * @ORM\Entity()
 * @ORM\Table(name="Foo_MemberSubscription", options={"charset"="latin1","collate"="latin1_swedish_ci"})
 */
class MemberSubscription
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     * @var int|null
     */
    protected $id;

    /**
     * @ORM\ManyToOne(targetEntity="Member", inversedBy="subscriptions")
     */
    protected $member;

    /**
     * @ORM\Column(type="datetime", nullable=true)
     * @var DateTime|null
     */
    protected $billing_date;

    /**
     * @ORM\Column(type="boolean", nullable=true)
     * @var bool
     */
    protected $paid;

    /**
     * @return int|null
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param int|null $id
     */
    public function setId($id)
    {
        $this->id = $id;
    }

    /**
     * @return mixed
     */
    public function getMember()
    {
        return $this->member;
    }

    /**
     * @param mixed $member
     */
    public function setMember($member)
    {
        $this->member = $member;
    }

    /**
     * @return null|DateTime
     */
    public function getBillingDate()
    {
        return $this->billing_date;
    }

    /**
     * @param null|DateTime $billing_date
     */
    public function setBillingDate($billing_date)
    {
        $this->billing_date = $billing_date;
    }

    /**
     * @return boolean
     */
    public function isPaid()
    {
        return $this->paid;
    }

    /**
     * @param boolean $paid
     */
    public function setPaid($paid)
    {
        $this->paid = $paid;
    }
}

A: Doctrine will only take care of the owning side of your relationships. Check also the documentation chapter 11: Association Updates: Owning Side and Inverse Side.
So to be able to get subscriptions from your Member entity you need to manually update the inverse side. The best way to do so is probably like this:
Inside your MemberSubscription:
//...

/**
 * @param mixed $member
 */
public function setMember($member)
{
    $this->member = $member;
    $member->addSubscription($this);
}

//...

Update:
Your subscriptions PersistentCollection will is lazy-loaded. You can see in the output that the collection is not initialized:
-initialized: false

Simply dumping the collection will not load the elements. Once you will interact with your lazy-loaded PersistentCollection Doctrine will load/initialize the collection for you and it will be populated with its Member elements.
You can also do this manually by calling initialize();. After that you will see the elements when you dump the variable again.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Automation in Excel for shift patterns Hi I have the following two tables

I am trying to get the col
I am trying to automate Column E so that every time the data changes in cell D2 it would automatically get changed based on the shift patter that the Agent is assigned on that day.
I cannot used vlookup because it will obviously just take the first text found with for example 9am-5pm - all cells would be populated with Agent 3.

A: =INDEX($A$2:$A$10,AGGREGATE(15,3,($B$2:$B$10=D3)/($B$2:$B$10=D3)*ROW($B$2:$B$10)-1,COUNTIF(D$3:D3,D3)))
As an alternate approach to ZygD's answer.
It uses AGGREGATE. It checks for the values in the B column range to equal the value in column D and divides the result by itself, which will result in 1 if True and multiplies that by the row number. The result gives the row numbers of all TRUEs and checks for the Nth smallest value based on how many of the same agent are already found in your result list above and finally shows the value of that row in your range of values in column A.

A: Seems like this array formula in E3 in part does what you want (it is entered not using usual Enter key, but instead, Ctrl + Shift + Enter).
=INDEX($A$2:$A$10,SMALL(IF(D3=$B$2:$B$10,ROW($B$2:$B$10)-ROW($B$2)+1),COUNTIF($D$3:D3,D3)))

A: Use XLOOKUP() instead. Column position does not matter with this function.


text:
Q: Enhanced E-commerce Checkout Behavior Report I'm using Google Tag Manager tag to push checkout data to Universal Analytics.
Tag

*

*Tag Type: Universal Analytics

*Track Type: Event

*Category: Ecommerce

*Action: Checkout

*Enhanced E-commerce: true

*Data Layer: true

*Fire On: Checkout
Trigger

*

*Name: Checkout

*Event: Custom Event

*Fire On: checkout
JavaScript
dataLayer.push({
  'event': 'checkout',
  'ecommerce': {
    'checkout': {
      'actionField': { 'step': step, 'option': option }
    }
  }
});

Chrome Tag Assistant extension reports show that all values are passed to Universal Analytics collect action.
In Behavior > Events > Top Events I can see that events were properly registered by UA:

Unfortunately Conversions > E-commerce > Shopping Analysis > Checkout Behavior doesn't show any data... my question is: "Why ?"

A: It looks like you are not passing product data in your dataLayer push
https://developers.google.com/tag-manager/enhanced-ecommerce#checkoutstep (edited)


text:
Q: Why is proving system consistency a problem? I'm trying to understand Godel's second incompleteness theorem, which by my understanding is equivalent to, "An axiomatic system [with certain complexity and soundness properties] $F$ cannot prove its own consistency, i.e. $F⊬(F ⊬ 0=1)$" as a specific example following on from the first incompleteness theorem stating, "There is some syntatically valid sentence that $F$ cannot prove either true or false."
I understand that consistency is a ludicrously strong statement, since it's effectively an assertion over a set of completely general, arbitararily complex sentences and because of that, I wouldn't expect it to be provable to begin with. However, the 2IT says that this statement's not merely practically unreasonable, but directly implies a contradiction. (Or has some other self-defeating implication)
So, what contradiction can be derived from the assumption that a sound theory can prove that it itself is consistent, and how?

A: No, the 2nd Incompleteness Theorem is just saying that "$F$ can't prove that $F$ can't prove that $0 = 1$". This is the same as saying that $F$ can't prove it's consistent - to say "$F$ is inconsistent" is to say "$F$ proves a contradiction", and from a contradiction you can prove anything at all, including $0 = 1$. So the statements "$F$ is inconsistent" and "$F \vdash 0 = 1$" are equivalent. What I mean is, the fact that we're now talking about a contradiction instead of consistency shouldn't be at all surprising here - they're the same thing.
As for which contradiction can be proven from a (sufficiently strong) sound theory that proves itself consistent: Any theory strong enough to handle arithmetic can prove Godel's Incompleteness Theorem. So this theory (let's call it $T$) "knows" that a sufficiently strong consistent theory cannot prove its own consistency. So $T$ proves that if $T$ is consistent, then $T$ cannot prove its own consistency. But if $T$ does prove its own consistency, it can prove that - it just has to supply the proof. So we have $T \vdash (Con(T) \implies T \nvdash Con(T))$ and $T \vdash T \vdash Con(T)$. So $T \vdash T \nvdash Con(T)$, because $T$ "knows" how implications work. Therefore $T \vdash (T \vdash Con(T) \wedge T \nvdash Con(T))$. That's a contradiction.
EDIT: The statement that $T$ "'knows' that a sufficiently strong consistent theory cannot prove its own consistency" isn't the First Incompleteness Theorem, it's the second. The Second Incompleteness Theorem states that if $T$ is "sufficiently strong" and consistent, then $T \nvdash Con(T)$. The interesting thing is that 2nd Incompleteness can be proven inside $PA$, so any sufficiently strong $T$ can actually prove that 2nd Incompleteness is true. The point is that if $T$ also proves that it itself is consistent, then it concludes that 2nd Incompleteness means it can't prove itself consistent.

A: Take any useful formal system $S$, namely one that has decidable proof validity and uniformly interprets arithmetic (see the latter section of this post for the precise definition).
$
\def\eq{\leftrightarrow}
\def\box{\square}
$
Then $S$ satisfies the Hilbert-Bernays provability conditions and the fixed point theorem (see the linked post), and hence we have both the internal and external forms of Lob's theorem (which arises from mimicking Curry's paradox in provability logic):

(L*) If $S \vdash □ P \to P$ then $S \vdash P$.
(L) $S \vdash □ ( □ P \to P ) \to □ P$.

From these applied to $P = \bot$ we immediately get Godel's second incompleteness theorem (in both external and internal form):

(GI*) If $S \nvdash \bot$ then $S \nvdash \neg □ \bot$.
(GI) $S \vdash \neg □ \bot \to \neg □ \neg □ \bot$.

To see where the contradiction comes from you can either trace through the proof of Lob's theorem and its instantiation to get the (external) first incompleteness theorem, or you can instantiate the proof from the beginning to get:

Let $P$ be a sentence such that $S \vdash P \eq \neg \box P$.
If $S \vdash \neg \box \bot$:
  Within $S$:
    $P \to \neg \box P$.   [from definition of $P$]
    $\box P \to \box \neg \box P$.   [by (D2)]
    If $\box P$:
      $\box \neg \box P$.
      $\box \box P$.   [by (D3) on last assumption]
      $\box \bot$.   [by (D2)]
      $\bot$.   [by outer assumption]
    Therefore $\neg \box P$.
    $P$.   [from definition of $P$]
    $\box P$.   [by (D1)]
    $\bot$.
  Therefore $S \vdash \bot$.

It is relatively easy to internalize the above proof of (GI*) within $S$ itself, which would give the internal form (GI).
Note also that this is for the usual definition of $\text{Con}(S) \equiv \neg \box_S \bot$. (There are possible alternatives.)


text: Q: File Manager - attach a file I am running Debian 10 Cinnamon (among others) and am wondering if there is a way to change the order in the dialog for attaching a file to an email. Currently it is strictly alphabetic and I would prefer to have folders on top (alphabetically) then files (alphabetically). My Mint Cinnamon dialog behaves this way. Knowing how versatile Linux is I presume there must be a way to accomplish this.  Thanks.


text:
Q: Using test clock with Corda DriverDSL I'm trying to use Corda DriverDSL API (OS 4.3) to run integration tests inside the JVM. It generally works fine, but I now need to test a scheduled flow and I need to move the network clock forward. There is a way to configure driver to use test clock via DriverParameters.withUseTestClock(), but I cannot seem to find an API to advance the clock after all the nodes got going. All I have are instances of NodeHandle and a DriverDSL object.
Just to be clear, it must be the whole network's clock that gets advanced, because we use TimeWindow constraints and the notary will reject the transactions if it's only the clock of one node that gets advanced.
It appears that the integration test in Corda IRS example configures the driver with the test clock, but it does not seem to actually use it, at least as far as I can tell.
What am I missing?

A: It look likes we do not currently openly support this feature as that it doesn't have any documentation around this.
However, i did went through the irs sample and found this:
@ThreadSafe
class DemoClock(delegateClock: Clock) : MutableClock(delegateClock) {
    @Synchronized
    fun updateDate(date: LocalDate): Boolean {
        val currentDate = LocalDate.now(this)
        if (currentDate.isBefore(date)) {
            // It's ok to increment
            delegateClock = Clock.offset(delegateClock, currentDate.atStartOfDay() until date.atStartOfDay())
            notifyMutationObservers()
            return true
        }
        return false
    }
}

I would think this will allow you to customize the clock time. However, I am not really sure if still works. it might be deprecated.
https://github.com/corda/corda-nexus-test/blob/c1909722f606fc64174e17afad8ccf864a105bcf/samples/irs-demo/cordapp/workflows-irs/src/main/kotlin/net.corda.irs/flows/UpdateBusinessDayFlow.kt#L22


text:
Q: How to access the metadata of a docker container from a script running inside the container? I am trying to understand whether it is possible to read the metadata (Labels, in particular) properties of a container using a bash script.
For instance, if there is a Dockerfile like:
FROM busybox
LABEL abc = abc_value1

And, if I build and run an image based on the file above, like so:
docker build . -t image1
docker run -ti image1 /bin/bash

Is there any way to access the value of the "abc" label inside the bash shell?  If so, how?

A: To get the labels (and anything from the remote API), you could pass the socket into the container and use curl >= 7.40 (it's the minimum version that supports --unix-socket flag) from within the container to access the remote API via the socket:
Dockerfile:
FROM ubuntu:16.04
RUN apt-get update \
    && apt-get install curl -y
LABEL abc = abc_value1

Build and run
docker build -t image1 .
docker run -v /var/run/docker.sock:/var/run/docker.sock -it image1 /bin/bash

From inside the container
curl --unix-socket /var/run/docker.sock http:/containers/$(hostname)/json

From here you'll have a huge chunk of JSON (similar to docker inspect). You can then use a CLI tool like jq to pluck out the labels.
See more information on docker's website: https://docs.docker.com/engine/reference/api/docker_remote_api/#/docker-remote-api
All that said-- this isn't very secure, and environment variables are probably a better bet.


text:
Q: How to copy whole vector into queue in reversed order? My vector stores the numbers of the vertices of a certain graph in ascending order. I want to add these numbers to a queue in order to run BFS later in code, but I dont know how do that in nice and fast way. I want the solution to be clear for everyone to read and what I came with is in my opinion obscure.
Disclaimer - I use static casts because i hate seeing warnings when i work with Qt. Here's what did:
Using casual for loop to iterate in reverse order through the vector starting with size-1 ending when i equals -1. Because I'm using -1 as rule I need to cast everything on int which makes code ugly.
vector<unsigned> v;
v.pushback(2);
v.pushback(3);
v.pushback(5);

queue<unsigned> q;

for(int i = static_cast<int>(v.size()-1); i>=0; i--)
    q.push(v[static_cast<unsigned>(i)];

Can someone tell me how pros do it? Cant find anything like "copy in reverse order" function that can start from .end()-1 element and copy all elements including .begin() one?

A: std::vector provides the functions rbegin and rend which return reverse iterators that you can use to iterate from the back to the front.  Using those you can use std::for_each to iterate the vector and then use a lambda as the functor to push each element into the queue.  That would look like
std::vector<int> v = {1, 2, 3};
std::queue<int> q;
std::for_each(v.rbegin(), v.rend(), [&q](auto el){ q.push(el); });


text:
Q: Match list's index based off its value I am new to Python and working on a problem where I have to match a list of indices to a list of value with 2 conditions:

*

*If there is a repeated index, then the values should be summed

*If there is no index in the list, then value should be 0

For example, below are my 2 lists: 'List of Inds' and 'List of Vals'. So at index 0, my value is 5; at index 1, my value is 4; at index 2, my value is 3 (2+1), at index 3, may value 0 (since no value associated with the index) and so on.
Input:

'List of Inds' = [0,1,4,2,2]
'List Vals' = [5,4,3,2,1]

Output = [5,4,3,0,3]

I have been struggling with it for few days and can't find anything online that can point me in the right direction. Thank you.

A: The following code works as desired. In computer science it is called "Sparse Matrix" where the data is kept only for said indices, but the "virtual size" of the data structure seems large from the outside.
import logging

class SparseVector:
    def __init__(self, indices, values):
        self.d = {}
        for c, indx in enumerate(indices):
            logging.info(c)
            logging.info(indx)
            if indx not in self.d:
                self.d[indx] = 0
            self.d[indx] += values[c]

    def getItem(self, key):
        if key in self.d:
            return self.d[key]
        else:
            return 0

p1 = SparseVector([0,1,4,2,2], [5,4,3,2,1])
print p1.getItem(0);
print p1.getItem(1);
print p1.getItem(2);
print p1.getItem(3);
print p1.getItem(4);
print p1.getItem(5);
print p1.getItem(6);

A: Answer code is
def ans(list1,list2):
    dic={}
    ans=[]
    if not(len(list1)==len(list2)):
        return "Not Possible"
    for i in range(0,len(list1)):
        ind=list1[i]
        val=list2[i]
        if not(ind in dic.keys()):
            dic[ind]=val
        else:
            dic[ind]+=val
    val=len(list1)
    for i in range(0,val):
        if not(i in dic.keys()):
            ans.append(0)
        else:
            ans.append(dic[i])
    return ans

To test:
  print(ans([0,1,4,2,2], [5,4,3,2,1]))

output:
  [5, 4, 3, 0, 3]

Hope it helps
Comment if you dont understand any step

A: what you can do is sort the indexes and values in an ascending order, and then sum it up. Here is an example code:
import numpy as np

ind = [0,1,4,2,2]
vals = [5,4,3,2,1]

points = zip(ind,vals)

sorted_points = sorted(points)

new_ind = [point[0] for point in sorted_points]
new_val = [point[1] for point in sorted_points]

output = np.zeros((len(new_ind)))

for i in range(len(new_ind)):
    output[new_ind[i]] += new_val[i]

In this code, the index values are sorted to be in ascending order and then the value array is rearranged according to the sorted index array. Then, using a simple for loop, you can sum the values of each existing index and calculate the output.

A: List_of_Inds = [0,1,4,2,2]
List_Vals = [5,4,3,2,1]
dic ={}

i = 0
for key in List_of_Inds:
    if key not in dic:
        dic[key] = 0
    dic[key] = List_Vals[i]+dic[key]
    i = i+1

output = []
for key in range(0, len(dic)+1):
    if key in dic:
        output.append(dic[key])
    else:
        output.append(0)

print(dic)
print(output)

output:
{0: 5, 1: 4, 4: 3, 2: 3}
[5, 4, 3, 0, 3]

A: This is a grouping problem. You can use collections.defaultdict to build a dictionary mapping, incrementing values in each iteration. Then use a list comprehension:
indices = [0,1,4,2,2]
values = [5,4,3,2,1]

from collections import defaultdict
dd = defaultdict(int)
for idx, val in zip(indices, values):
    dd[idx] += val

res = [dd[idx] for idx in range(max(dd) + 1)]

## functional alternative:
# res = list(map(dd.get, range(max(dd) + 1)))

print(res)
# [5, 4, 3, 0, 3]


text:
Q: Changing UITabBarItem image I have used Storyboard to set up my UITabBarController and its corresponding ViewControllers. Whenever a tab is deselected, it is gray, when it is selected it has a green tint. I would like one of these UITabBarItems to always look the same: i.e. it always has the green tint regardless of whether it is selected or deselected.  In addition, the icon image I am using for this UITabBarItem already has the green look that I want. This is important because I have tried using this method in the viewDidLoad function of the ViewController of the UITabBarItem that I would like to stay the same (I had already set an outlet between the UITabBarItem in Storyboard and the ViewController):  myTabBarItem.image = UIImage(named: "PickleTabIcon").imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)  This works great, however it is not activated until the ViewController is loaded, so a user has to tap on the TabItem to load the ViewController before this works.  I have also tried to access the image of the UITabBarItem from the initial ViewController, so that the changes go into effect as soon as the application is launched like so:  tabBarController.tabBar.items[2].image  But this throws an error and says that this API has been deprecated. Changing .image to .setImage doesn't say the API has been deprecated, but it throws an error nonetheless(unrecognized selector).  If you have any additional questions, please feel free to ask. Thanks in advance!  I am using Swift in XCode 6 Beta 6.

A: tabBar.items is an array of AnyObjects. Try casting the item to UITabBarItem
var myTabBarItem = tabBarController.tabBar.items[2] as UITabBarItem
myTabBarItem.image = UIImage(named: "PickleTabIcon").imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)


text:
Q: PARTIALLY SOLVED - React code generating ESlint error no-unused-expressions Scroll to bottom for most of a solution
I'm leaving this posted, just in case someone else has this same problem later.
I'm following a beginner's tutorial (from Wes Bos) to learn React, and I've triple-checked that my code is the same as in the tutorial, but for whatever reason it is triggering an ESlint error (even though, supposedly ESlint isn't even installed in my VS Code).
Here is my code:
import React from "react";
import { formatPrice } from "../helpers";

class Order extends React.Component {
    renderOrder = key => {
        const fish = this.props.fishes[key];
        const count = this.props.order[key];
        const isAvailable = fish.status === 'available';
        // /*eslint-disable */
        if(!isAvailable) {

                Sorry {fish ? fish.name : 'fish'} is no longer available

        }
        return (

                {count} lbs of {fish.name}
                {formatPrice(count * fish.price)}

        );
        // /*eslint-endisable */
    };
    render() {
        const orderIds = Object.keys(this.props.order);
        const total = orderIds.reduce((prevTotal,key) => {
            const fish = this.props.fishes[key];
            const count = this.props.order[key];
            const isAvailable = fish && fish.status === 'available';
            if(isAvailable) {
                return prevTotal + (count * fish.price);
            }
            return prevTotal;
        }, 0);
        return (

Order

                        {orderIds.map(this.renderOrder)}

                    Total:
                    {formatPrice(total)}

        );
    }
}

export default Order;

The error I'm getting is:
./src/components/Order.js
  Line 10:  Expected an assignment or function call and instead saw an expression  no-unused-expressions
Note: Line 10 is the start of my if function
I tried googling the error, but I guess I'm too much of a beginner to understand what I found here:
https://eslint.org/docs/rules/no-unused-expressions
I was able to get this to run (not error, although the if function doesn't seem to work) by using the /*eslint-disable */ /*eslint-endisable */ around the if function, but I'd still like to know:
1. Why is this error occurring?
2. Why is an ESlint error being triggered when I had previously disabled and then uninstalled ESlint from VS code?
Also tried cleaning up the code a little to this, but still doesn't work:
// /*eslint-disable */
        if (!isAvailable) {

Sorry {fish ? fish.name : 'fish'} is no longer available
;
        }
        // /*eslint-endisable */
        return (

                {count} lbs {fish.name}
                {formatPrice(count * fish.price)}

        );

And, if I'd just watched the tutorial for 30 more seconds, I would have found out the answer to why the IF function doesn't work, but I was stumped by the ESLint error that I got that did not happen in the tutorial video.  I still don't know why I'm getting ESLint errors, since I don't have it installed, let alone enabled.
Correct code requires a return:
renderOrder = key => {
        const fish = this.props.fishes[key];
        const count = this.props.order[key];
        const isAvailable = fish.status === 'available';
        if (!isAvailable) {
// added return below
            return
Sorry {fish ? fish.name : 'fish'} is no longer available
;
        }
        return (

                {count} lbs {fish.name}
                {formatPrice(count * fish.price)}

        );
    };

A: You're not doing anything in that conditional. You're saying, "If this is true, then this is also true" and your linter is trying to tell you that you probably wanted to do something more than just stating a thing. If you set the list item to a variable and use it elsewhere, the linter should move on.
Edit to go with OP's edit: Likely the reason you're getting ESLinter errors is because the tutorial package you installed came with it and it's own .eslintrc file for rules.


text:
Q: Explicit Euler method I am looking to find the explicit and implicit codes for Euler's method. In my search I am across the following code, I am wondering if this code is explicit? if not how could I change it to make it so?
import math
# First Order ODE (y' = f(x, y)) Solver using Euler method
# xa: initial value of independent variable
# xb: final value of independent variable
# ya: initial value of dependent variable
# n : number of steps (higher the better)
# Returns value of y at xb.
def Euler(f, xa, xb, ya, n):
      h = (xb - xa) / float(n)
      x = xa
      y = ya
      for i in range(n):
          y += h * f(x, y)
          x += h
      return y
print(Euler(lambda x, y: math.cos(x) + math.sin(y), 0, 1, 1, 1000))

A: This code implements the explicit Euler scheme.
In order to be implicit, there would be an instruction like
y = solve(z == y + h*f(x,z), z)

in the inner loop, where solve(equation, variable) is a suitable function to solve an equation (see here).


text:
Q: Weighted average in PivotTable I have a question which I just can't figure out. I have a pivot table and want to create a weighted average from that data. I have researched and people suggest to do this by using a calculated field. However, my data is structured differently, I have one measure per column. This is what my data looks like:
City        Product Measure Amount
Miami       Apple   Price   $4.0
Miami       Apple   Rating  50.0%
Miami       Pear    Price   $3.00
Miami       Pear    Rating  15.0%
Miami       Banana  Price   $13.00
Miami       Banana  Rating  85.0%
New York    Apple   Price   $2.00
New York    Apple   Rating  75.0%
New York    Pear    Price   $11.00
New York    Pear    Rating  15.0%
New York    Banana  Price   $9.00
New York    Banana  Rating  10.0%

This is what my pivot table looks like right now:

Obviously the weighted average of the Rating is different than the regular average. Is there a way to get the weighted averages in the sum fields? I don't even need the Apple, Banana and Pear in the columns, in the end what I want to achieve is just show the cities (New York, Miami) and their weighted averages.

A: What you need is you need your weighting column that lines up with price so that it looks like this:
City    Product Measure $ Ammount   % to Total
Miami   Apple   Price       $4.00   50.00%
Miami   Pear    Price       $3.00   15.00%
Miami   Banana  Price       $13.00  85.00%
New York    Apple   Price   $2.00   75.00%
New York    Pear    Price   $11.00  15.00%
New York    Banana  Price   $9.00   10.00%

You can then add in the calculated Weighted average in the pivot table by telling excel that it's the $ Amount * the percentage
You can also use the sumproduct formula for a weighted average. In this example write =SUMPRODUCT(D2:D7,E2:E7)


text:
Q: About constraints on arrays in Z3 I have two questions about how Z3 operates with regards to arrays.
1) In models, arrays have an "else" element along with a corresponding value.  Is there a way to specify constraints on the "else" element on an array in the formula?  For example, can we specify that the first element of an array is greater than 5 and all other elements are less than 5?
2) Upon checking the following formula via z3 at command line,
(set-logic QF_AX)
(declare-sort Index 0)
(declare-sort Element 0)
(declare-fun a1 () (Array Index Element))
(declare-fun i0 () Index)
(declare-fun i1 () Index)
(assert
  (let
    (
      (?v_1 (select a1 i0))
      (?v_2 (select a1 i1))
    )
    (
      not(= ?v_1 ?v_2)
    )
  )
)

Z3 generates the following output.
sat
(model
  ;; universe for Index:
  ;;   Index!val!1 Index!val!0
  ;; -----------
  ;; definitions for universe elements:
  (declare-fun Index!val!1 () Index)
  (declare-fun Index!val!0 () Index)
  ;; cardinality constraint:
  (forall ((x Index)) (or (= x Index!val!1) (= x Index!val!0)))
  ;; -----------
  ;; universe for Element:
  ;;   Element!val!1 Element!val!0
  ;; -----------
  ;; definitions for universe elements:
  (declare-fun Element!val!1 () Element)
  (declare-fun Element!val!0 () Element)
  ;; cardinality constraint:
  (forall ((x Element)) (or (= x Element!val!1) (= x Element!val!0)))
  ;; -----------
  (define-fun i1 () Index
    Index!val!1)
  (define-fun a1 () (Array Index Element)
    (_ as-array k!0))
  (define-fun i0 () Index
    Index!val!0)
  (define-fun k!0 ((x!1 Index)) Element
    (ite (= x!1 Index!val!0) Element!val!0
    (ite (= x!1 Index!val!1) Element!val!1
      Element!val!0)))
)

Upon checking the same formula via Z3py, the following model is generated.
[i1 = Index!val!1,
 a1 = [Index!val!0 -> Element!val!0,
       Index!val!1 -> Element!val!1,
       else -> Element!val!0],
 i0 = Index!val!0,
 k!0 = [Index!val!0 -> Element!val!0,
        Index!val!1 -> Element!val!1,
        else -> Element!val!0]]

Interestingly, the reference to k!0 in a1 is "dereferenced" in Z3py, i.e., a1 refers to FuncInterp object.  Is this always the case?  Specifically, if a program is walking over the model provided by Z3py, is it safe to assume that all as_array expressions will be resolved to the underlying function definition?

A: Arrays are a bit of a special case, because they have a func_interp as a model. In the Python API we can rely on this being dereferenced, it's the get_interp function which does this for us:
def get_interp(self, decl):
...
    if decl.arity() == 0:
        r = _to_expr_ref(Z3_model_get_const_interp(self.ctx.ref(), self.model, decl.ast), self.ctx)
        if is_as_array(r):
            return self.get_interp(get_as_array_func(r)) # <-- Here.
        else:
            return r


text:
Q: WCF Server Error. The content type text/html of the response message does not match the content type of the binding I've got a WCF Service, which calls a webservice, running on my development IIS server (IIS 7). I've added it as a service reference to a C# Website Project and it adds fine.
However, when I try to call any of the service contracts, I get the following error:

The content type text/html
  of the response message does not match
  the content type of the binding
  (text/xml; charset=utf-8). If using a
  custom encoder, be sure that the
  IsContentTypeSupported method is
  implemented properly. The first 1024
  bytes of the response were:
  'Blocked Web
  Page

thanks in advance
BB

A: The error message says it clearly: you're getting back an HTML page instead of your service response. Looking at the fragment of that page listed in the error message, you're probably not authroized to use that service.
Try to connect to the service URL in a browser - you should probably see a page explaining that you're not allowed to access the page. Most likely, this is a permissions issue.

A: You need to configure WCF Tracing and find out what's happening on the server side.


text:
Q: Node.js on ubuntu16.04 - Failing to install and run nodemon I'm failing to install and run nodemon. I'm running node.js on ubuntu 16.04.. My api is working. The libs installed are:
sven@sven-MS-7264:~/Projects/APIDemo$ npm -g ls --depth=0
/usr/lib
├── npm@5.6.0
└── pm2@2.9.3

npm ERR! invalid: minizlib@1.0.3 /usr/lib/node_modules/npm/node_modules/tar/node_modules/minizlib

sven@sven-MS-7264:~/Projects/APIDemo$ npm ls --depth=0
apidemo@1.0.0 /home/sven/Projects/APIDemo
├── body-parser@1.18.2
├── cookie-parser@1.4.3
├── debug@3.1.0
├── ejs@2.5.7
├── express@4.16.2
├── morgan@1.9.0
├── mysql@2.15.0
└── serve-favicon@2.4.5

But when trying to install nodemon globally, I'm getting this:
sven@sven-MS-7264:~/Projects/APIDemo$ npm install -g nodemon
npm WARN registry Using stale data from https://registry.npmjs.org/ because the host is inaccessible -- are you offline?
npm WARN registry Using stale package data from https://registry.npmjs.org/ due to a request error during revalidation.
npm WARN checkPermissions Missing write access to /usr/lib/node_modules
npm ERR! path /usr/lib/node_modules
npm ERR! code EACCES
npm ERR! errno -13
npm ERR! syscall access
npm ERR! Error: EACCES: permission denied, access '/usr/lib/node_modules'
npm ERR!  { Error: EACCES: permission denied, access '/usr/lib/node_modules'
npm ERR!   stack: 'Error: EACCES: permission denied, access \'/usr/lib/node_modules\'',
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'access',
npm ERR!   path: '/usr/lib/node_modules' }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.

The folder permission looks like this:
sven@sven-MS-7264:~/Projects$ ls -la
total 20
drwxrwxr-x  5 sven sven 4096 Feb 20 09:50 .
drwxr-xr-x 52 sven sven 4096 Feb 20 13:59 ..
drwx------  7 sven sven 4096 Feb 20 16:27 APIDemo

How can I install and run nodemon?

A: You can't install a global module if you are not as an admin. Try to run the command with sudo if you can
sudo npm install -g nodemon

You can also install nodemon in your local folder by removing the -g option.


text:
Q: In healpy how to split mask/map into 2 parts? I have a mask/map as a fits file, downloadable here, and I can plot this mask with healpy using this code:
import healpy as hp
from healpy.newvisufunc import projview, newprojplot

wmap_map_I = hp.read_map('mask.fits')
projview(
    wmap_map_I,
    graticule=True, graticule_labels=True, xlabel="longitude", ylabel="latitude",
    projection_type="mollweide",
    coord=["E"],
    title="Histogram equalized Ecliptic",
    unit="mK",
    norm="hist",
    min=-1,
    max=1,
);

It produces this figure:

What I want to do is split the mask into 2 new masks - one should contain only part A and the other should contain only part B. I don't know how to do this, I thought of making some conditional expression about all points for which longitude + latitude < xyz and then the opposite, but the fits file doesn't contain longitude and latitude.
So how can I split the mask into 2? Thx

A: your mask was apparently defined in Galactic coordinates, with the A part centered on South Galactic pole, and the B part around the NGP.
It should appear if you run mollview with coord=['C','G'].
Are you sure the mask is stored in Ecliptic coordinates ? It looks like Celestial (or Equatorial) coordinates instead.
To split the mask, get the celestial 3D coordinates of each valid pixel with pix2vec, than rotate them to Galactic using healpy.rotate tools and put those with glat <0 in file A, and those with glat > 0 in file B.

A: I followed EHivon's answer and digged into healpy. I came up with a solution following his/her advice, but first I post 2 solutions that I discovered on the way on my own
### 1. SOLUTION: We convert to galactic coordinates and use the order of the pixels to split

# read in the map
map = hp.read_map('map.fits')

# first we define a operator that will rotate from celestial coordinates to galactic
rot_gal2eq = hp.Rotator(coord=['G', 'C'], inv=True)

# rotate the whole map
m_rotated = rot_gal2eq.rotate_map_alms(map)

# there are now some artefacts in the map so I round it
m_rotated = np.rint(m_rotated)

# set the second half of the rotated mask to 0, since we want to split it in half
# For info, the indexing of the elements in a map follows a ring order going down from the most norther point
# to the most souther point. So the first half of the map element are all in the northern sky, the second half
# are all in the souther sky
m_rot_N = m_rotated.copy()
m_rot_N[len(m_rot_N)//2:] =0

# do the same for the south sky
m_rot_S = m_rotated.copy()
m_rot_S[:len(m_rot_N)//2] =0

# rotate back both maps
rot_inv = hp.Rotator(coord=['C', 'G'], inv=True)
m_rot_N_inv = rot_inv.rotate_map_alms(m_rot_N)
m_rot_S_inv = rot_inv.rotate_map_alms(m_rot_S)

# again, round the elements of the masks because of artefacrts
m_rot_N_inv = np.rint(m_rot_N_inv)
m_rot_S_inv = np.rint(m_rot_S_inv)

# eventually, saved the new masks
hp.fitsfunc.write_map('map_N.fits', m_rot_N_inv)
hp.fitsfunc.write_map('map_S.fits', m_rot_S_inv)

The above we can plot like this:
hp.mollview(m_rot_N, max=1)
hp.graticule();
hp.mollview(m_rot_S, max=1)
hp.graticule();

Here is another way to do the split, substitute the last lines above with these:
### 2. SOLUTION: Draw around a point a disc that splits the map as you like
# define a vector pointing at a point on the sky that you want to center on
# they we will draw a half-sky circle around that point and so we can split the map in 2
vec = hp.ang2vec(0, 0) # (0,0) are the angles on the sky pointing at the north pole
ipix_disc = hp.query_disc(nside=hp.pixelfunc.get_nside(m_rotated), vec=vec, radius=np.radians(90))

# set all the values inside the circle to 0, giving you a condition to effectively split the map
m_rot_N = m_rotated[ipix_disc] = 0

And the solution suggest by EHivon is below, I actually made a slightly more complicated structure with for demonstration purposes:
### 3. SOLUTION: turn the pixels to angles and make conditions for the angles
# get the angles of all the pixels on the map
angles = hp.pixelfunc.pix2ang(nside=hp.pixelfunc.get_nside(m_rotated), ipix=np.arange(len(m_rotated)), lonlat=True)
# set all the values 0 that fullfill a condition
m_rotated[(angles[0]<60)|(angles[0]>315)] = 0.5 #angles[0] are the longitude angles, angles[1] are the latitudes of all the pixels


text:
Q: Estou utilizando o c++ com a biblioteca da openGL Estou utilizando o c++ com a biblioteca da openGL, estou com um pouco de dificuldade na criação de um método. Preciso criar uns prédios randomicamente, mas para não criar um dentro do outro eu preciso comparar os 4 pontos do prédio. Se alguém puder me ajudar.
string localizacaoPredio[150];
int ultimaPos = 0;
for (int i = 0; i < 150; i++){
    int x = rand() % 10 + 1;
    int z = rand() % 10 + 1;
    string coordenada = x + ";" + z;

    for (int j = 0; j < ultimaPos; j++){
        if (localizacaoPredio[j].compare(coordenada)){
            x = rand() % 10 + 1;
            z = rand() % 10 + 1;
            coordenada = x + ";" + z;
            j = -1;
        }
    }
    localizacaoPredio[ultimaPos] = coordenada;
    ultimaPos++;
}
int andares[150];
for (int i = 0; i < 150; i++){
    andares[i] = rand() % 10 + 1;
}
int numDivisoes[150];
for (int i = 0; i < 150; i++){
    numDivisoes[i] = rand() % 10 + 1;
}

for (int i = 0; i < 150; i++){

    Building b1(localizacaoPredio[i], y1, andares[i], numDivisoes[i], 1, 1);
    planos.push_back(b1.predio[0].plano);
    planos.push_back(b1.predio[1].plano);
    planos.push_back(b1.predio[2].plano);
    planos.push_back(b1.predio[3].plano);
    planos.push_back(b1.predio[4].plano);
    city.push_back(b1);
}


text:
Q: Variable from simulation class is not accessible in main class I have created many variables in my simulation class and would like to access them in my main agent in the StartUp code. First I started to create parameters in the main class like in the AnyLogic tutorial and assign the variables to the Simulation class. This works, but is very time consuming. However, in my StartUp code in the main class I can't access it directly with Simulation.example_parameter even though all variables are on public. Is this simply not possible or does anyone know where a bug might have crept in here?

A: If your experiment is a "Simulation" experiment, you can use ((Simulation)getExperiment()).myVariable
PS: You can also wrap all your variables into a Java class and pass that along into 1 parameter in your model, saves a ton of effort


text:
Q: dial tcp: getsockopt: connection refused on local testing I have been using k6 for a couple of days to do load testing against and API in several different environments and chase down some bugs.
Everything was going great, until suddenly it started failing locally.
All requests result in the following error:

Request Failed   error="Get http://localhost:8000: dial tcp [::1]:8000: getsockopt: connection refused"

This only occurs in k6; I can still call the local API successfully through a browser, Postman, and cURL.
Is there any way to get more information out of k6 and figure out why it can't connect anymore?

A: The error message says that localhost is resolving to an IPv6 address (::1 in [::1]:8000) so if your API is only listening on the IPv4 127.0.0.1 but your localhost resolves to both an IPv4 and an IPv6 address (k6 supports both) then that would explain the error.
If you look in your /etc/hosts file you probably have entries for localhost that looks like this:
127.0.0.1       localhost
::1             localhost
fe80::1%lo0     localhost

I'm not sure why the lookup of localhost changed for you all of a sudden from IPv4 to IPv6, but might be that there are variables in
your system's address selection algorithm (see for example [1] for iOS/macOS, and more generally [2] which Go's internal resolver uses when it doesn't have to go through the system's resolver) that causes the switch based on things like historical TCP RTT (which is mentioned in [1] as a factor).
[1] https://www.ietf.org/mail-archive/web/v6ops/current/msg22455.html
[2] https://www.rfc-editor.org/rfc/rfc6724

A: Use 127.0.0.1 instead of localhost will solve your problem

A: The command line switch --http-debug="full" will dump the full requests and responses made by k6 while running the scripts, onto the screen.  Read this for more information.


text:
Q: Использование Сокет на примере игры в виселицу Программа имеет client и server.
Программирую игру - виселицу.
После того как server и client получили соединение происходит следующее:

*

*Server спрашивает слово, которое надо загадать и отправляет его client.
System.out.println("Please enter the word for the game:");
    word = scan.nextLine();
    out.println(word);
    System.out.println("Thank you! Now let client to guess...");

*Client получает слово и спрашивает написать букву
    String inputLine = in.readLine();
    int length = inputLine.length();

    System.out.println("Server is connected");

    String letters;

    for (int i = 1; i <= length; i++) {

        System.out.println("PLease write a letter");
        letters = scan.nextLine();
        out.println(letters);

        String fromServer = in.readLine();
        System.out.println(fromServer);

     }

*Каждая буква отправляется server, там обрабатывается и приходит в виде ответа client (есть буква или нет, и где она расположена)п.с. все можно допустить пять ошибок при угадывании слова.
char[] CharArr=word.toCharArray();
char[] star = word.toCharArray();

for(int i=0;i<star.length;i++)
{
    star[i] = '*';
    System.out.print(star[i]);
    out.print(star[i]);
}

   //only 5 prompts
   for (int i=1; i<=5; i++)
   {
    for (int j=0;j<CharArr.length; j++)
    {
      //Read letter from client
        String inputLine = in.readLine();
        char letter=inputLine.charAt(0);
        if(letter == star[j])
        {
            out.printf("This letter already exist!");
            System.out.println("This letter already exist!");
        }
        else
        {
            if(letter==CharArr[j])
            {
                star[j]=letter;
                i--;
                out.println("Correct guess!\n");
                System.out.println("Correct!");
            }
        }
    }
    out.println(star);
    switch(i+0)
    {
            case 1: out.println("Mistake 1\n");
                break;
            case 2: out.println("Mistake 2\n");
                break;
            case 3: out.println("Mistake 3\n");
                break;
            case 4: out.println("Mistake 4\n");
                break;
            case 5: out.println("Mistake 5\n");
            out.printf("You are wrong\n");
            System.out.printf("You are wrong!");
                break;

}
    out.println("\n");
    if((new String(word)).equals(new String(star)))
    {
        out.println("Yes! You are the champion!\n");
        System.out.printf("Winner!");
        break;
    }

}

1. Сlient абсолютно рандомно пишет ответы на разные буквы и я не понимаю, достаточно ли этой строчки, чтобы получать ответы от server.
String fromServer = in.readLine();
            System.out.println(fromServer);

Заранее большое спасибо!


text:
Q: iOS Printing with image and text I am trying to print an image and some text above it. When I print the image it takes up the entire page I only want it in the center and about 320 x 480 pix. Someone told me I needed to use rects but I do not know how to do this. The code below is what I have so far, it just prints the image but it has no size constraints. Thank You.
-(void)sendToPrinter{
UIPrintInteractionController *print = [UIPrintInteractionController sharedPrintController];

if(!print){

    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Print Unavailable!" message:nil delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
    [alert release];
    return;
}

pageSize = print.printPaper.paperSize;
pageSize = CGSizeMake(print.printFormatter.printPageRenderer.printableRect.size.width, print.printFormatter.printPageRenderer.printableRect.size.height);

NSUserDefaults *data = [NSUserDefaults standardUserDefaults];
NSString *projectTitle = [data stringForKey:@"pName1"];
NSString *fileName = [NSString stringWithFormat:@"%@.pdf", projectTitle];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfFileName = [documentsDirectory stringByAppendingPathComponent:fileName];

NSData *finalImageData = [NSData dataWithContentsOfFile:pdfFileName];

print.delegate = self;
UIPrintInfo *printInfo = [UIPrintInfo printInfo];
printInfo.outputType = UIPrintInfoOutputGeneral;
printInfo.jobName = [[(PageView *)[self view] representedPage] title];
printInfo.duplex = UIPrintInfoDuplexLongEdge;
print.printInfo = printInfo;
print.showsPageRange = YES;
print.printingItem = finalImageData;
UIViewPrintFormatter *viewFormatter = [self.view viewPrintFormatter];
viewFormatter.startPage = 0;

print.printFormatter = viewFormatter;

UIPrintInteractionCompletionHandler completionHandler = ^(UIPrintInteractionController *printInteractionController, BOOL completed, NSError *error) {
    if(!completed && error){
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Print Unavailable!" message:nil delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
};

[print presentAnimated:YES completionHandler:completionHandler];

}
- (void) drawText{
 CGContextRef    currentContext = UIGraphicsGetCurrentContext();
CGContextSetRGBFillColor(currentContext, 0.0, 0.0, 0.0, 1.0);

NSString *textToDraw = @"Lorem ipsum ";

UIFont *font = [UIFont systemFontOfSize:14.0];

CGSize stringSize = [textToDraw sizeWithFont:font
                           constrainedToSize:CGSizeMake(pageSize.width - 2*kBorderInset-2*kMarginInset, pageSize.height - 2*kBorderInset - 2*kMarginInset)
                               lineBreakMode:UILineBreakModeWordWrap];

CGRect renderingRect = CGRectMake(kBorderInset + kMarginInset, kBorderInset + kMarginInset + 350.0, pageSize.width - 2*kBorderInset - 2*kMarginInset, stringSize.height);

[textToDraw drawInRect:renderingRect
              withFont:font
         lineBreakMode:UILineBreakModeWordWrap
             alignment:UITextAlignmentLeft];
}

- (void) drawImage{

//paint chart

UIImage* chartImage = [self getUIImageScreenShot];;

[chartImage drawInRect:CGRectMake( (pageSize.width - chartImage.size.width/2)/2, 70, chartImage.size.width/2, chartImage.size.height/2)];
//[chartImage drawInRect:CGRectMake( (pageSize.width - chartImage.size.width/2)/2, 70, chartImage.size.width/2, chartImage.size.height/2)];}

}
- (void) generatePdfWithFilePath: (NSString *)thefilePath{
UIGraphicsBeginPDFContextToFile(thefilePath, CGRectZero, nil);

//NSInteger currentPage = 0;
BOOL done = NO;
do
{
    //Start a new page.
    UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, pageSize.width, pageSize.height), nil);

    //Draw some text for the page.
    [self drawText];

    //Draw an image
    [self drawImage];

    done = YES;
}
while (!done);

// Close the PDF context and write the contents out.
UIGraphicsEndPDFContext();}

A: seems like you are only adding the picture to the printing item
print.printingItem = imageData;

have you tried creating the whole "picture" of what you want printed out (including the text and stuff) and sending that to the printer instead?

A: I use the following to insert a simple image into and text into PDF, might point you in the right direction
- (IBAction)generatePdfButtonPressed:(id)sender{
pageSize = CGSizeMake(612, 792);

NSUserDefaults *data = [NSUserDefaults standardUserDefaults];
NSString *projectTitle = [data stringForKey:@"pName1"];
NSString *fileName = [NSString stringWithFormat:@"%@.pdf", projectTitle];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfFileName = [documentsDirectory stringByAppendingPathComponent:fileName];

[self generatePdfWithFilePath:pdfFileName];}

and then...
- (void) drawText{
CGContextRef    currentContext = UIGraphicsGetCurrentContext();
CGContextSetRGBFillColor(currentContext, 0.0, 0.0, 0.0, 1.0);

NSString *textToDraw = @"Lorem ipsum ";

UIFont *font = [UIFont systemFontOfSize:14.0];

CGSize stringSize = [textToDraw sizeWithFont:font
                           constrainedToSize:CGSizeMake(pageSize.width - 2*kBorderInset-2*kMarginInset, pageSize.height - 2*kBorderInset - 2*kMarginInset)
                               lineBreakMode:UILineBreakModeWordWrap];

CGRect renderingRect = CGRectMake(kBorderInset + kMarginInset, kBorderInset + kMarginInset + 350.0, pageSize.width - 2*kBorderInset - 2*kMarginInset, stringSize.height);

[textToDraw drawInRect:renderingRect
              withFont:font
         lineBreakMode:UILineBreakModeWordWrap
             alignment:UITextAlignmentLeft];
}

- (void) drawImage{

//paint chart
NSData* imageData = [[NSUserDefaults standardUserDefaults] objectForKey:@"chartImageP1"];
UIImage* chartImage = [UIImage imageWithData:imageData];

[chartImageBack drawInRect:CGRectMake( (pageSize.width - chartImageBack.size.width/2)/2, 70, chartImageBack.size.width/2, chartImageBack.size.height/2)];
[chartImage drawInRect:CGRectMake( (pageSize.width - chartImage.size.width/2)/2, 70, chartImage.size.width/2, chartImage.size.height/2)];}

- (void) generatePdfWithFilePath: (NSString *)thefilePath{
UIGraphicsBeginPDFContextToFile(thefilePath, CGRectZero, nil);

NSInteger currentPage = 0;
BOOL done = NO;
do
{
    //Start a new page.
    UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, pageSize.width, pageSize.height), nil);

    //Draw some text for the page.
    [self drawText];

    //Draw an image
    [self drawImage];

    done = YES;
}
while (!done);

// Close the PDF context and write the contents out.
UIGraphicsEndPDFContext();}


text:
Q: How to make "too much load" messages I see these kinds of messages on twitter and other places.... how do they work?  Is it MySQL connections?

A: You can measure response time of each request (or a given fraction of the requests). If the response time goes up above a threshold you start rejecting requests.
If you measure SQL connection etc you need to know where your bottle necks are at a given moment. If your application is limited by bandwidth between your servers or something else counting SQL connections will not help you.

A: It might be shown if the database refused a connection or if the system load (read from /proc/loadavg) is too high. It could also be shown if too many users are logged in - but that's only likely for web applications where logged in users are expensive.. certain games for example where lots of state information must be kept while someone is logged in.


text:
Q: How to ignore certificate verification in react js I have created a responsive react app. When it executes on desktop it works well(be it in collapsed view or full view).
But when I run it specifically on mobile, the react page loads but it does not make calls to the backend server.
If it can be due to SSL Certificate, can someone please suggest me how can I make react app not to verify the SSL certificate and make successful backend calls?
Thank you!


text:
Q: Unable to send Response from Rest method Here is the rest ws POST method code:
        @POST
        @Path("/json/saveuser")
        @Consumes("application/json")
        public ResponseBuilder saveUserJSON(User user) {
            if (save(user)) {
                return Response.status(HttpStatus.SC_OK);
            }
            return Response.status(HttpStatus.SC_BAD_REQUEST);
        }

User is saved properly in DB.
But the line Response.status(HttpStatus.SC_OK); and Response.status(HttpStatus.SC_BAD_REQUEST);, is throwing below error:
Mar 06, 2015 1:38:49 PM com.sun.jersey.spi.container.ContainerResponse traceException
SEVERE: Mapped exception to response: 500 (Internal Server Error)
javax.ws.rs.WebApplicationException: com.sun.jersey.api.MessageException: A message body writer for Java class com.sun.jersey.core.spi.factory.ResponseBuilderImpl, and Java type class javax.ws.rs.core.Response$ResponseBuilder, and MIME media type application/octet-stream was not found
    at com.sun.jersey.spi.container.ContainerResponse.write(ContainerResponse.java:278)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1326)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1239)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1229)
    at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:420)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:497)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:684)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: com.sun.jersey.api.MessageException: A message body writer for Java class com.sun.jersey.core.spi.factory.ResponseBuilderImpl, and Java type class javax.ws.rs.core.Response$ResponseBuilder, and MIME media type application/octet-stream was not found
    ... 28 more

Did googling. And according to the posts in SO and other sites, added the jars as listed below (Some additional jars are also added for other dependency):
antlr-2.7.7.jar
com.sun.jersey.jersey-core-1.4.0.jar
com.sun.jersey.jersey-server-1.4.0.jar
dom4j-1.6.1.jar
gcm.server.jar
genson-0.98.jar
hibernate-commons-annotations-4.0.5.Final.jar
hibernate-jpa-2.1-api-1.0.0.Final.jar
http-core-4.1.jar
jackson-all-1.9.0.jar
jackson-annotations-2.2.2.jar
jackson-core-2.2.2.jar
jandex-1.1.0.Final.jar
javassist-3.18.1-GA.jar
jboss-logging-3.1.3.GA.jar
jboss-logging-3.1.4.GA.jar
jboss-logging-annotations-1.2.0.Beta1.jar
jboss-transaction-api_1.2_spec-1.0.0.Final.jar
jersey-bundle-1.8.jar
jersey-container-servlet-core-2.16.jar
jersey-core-1.15.jar
jersey-json.jar
json_simple-1.1.jar
lucene-core-4.10.4.jar
mysql-connector-java-5.1.31.jar
slf4j-api-1.6.1.jar
xml-apis-1.3.03.jar

Not sure what am I missing? Any suggestion?

A: Your stacktrace obviously points, that Jersey doesn't know, how to response with ResponseBuilder.
Return Response instead: change resource method signature and return result of build method, called upon builder.

A: You have to return a Response instead of a ResponseBuilder:
@POST
@Path("/json/saveuser")
@Consumes("application/json")
public Response saveUserJSON(User user) {
    if (save(user)) {
        return Response.status(HttpStatus.SC_OK).build();
    }
        return Response.status(HttpStatus.SC_BAD_REQUEST).build();
}


text:
Q: how to get current date and time in command line I am using mysqldump to backup mysql database. Now I just need to use the current date and time as file name for the generated sql file. How do I do that if my current code looks like this:
mysqldump -u root -p --add-drop-table --create-options --password= onstor >c:\sql.sql

I also found this code from this site, but I do not know how to incorporate it in my current code:
@echo off
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-2 delims=/:" %%a in ('time /t') do (set mytime=%%a%%b)
echo %mydate%_%mytime%

Please help, thanks:)

A: This will solve your problem click here


text:
Q: ASP.NET overwriting cookie I'm having trouble overwriting the value of a cookie. The first time a user submits a username the cookie stores in the browser fine and is displayed properly. But when the user tries to submit a different user name the page refreshes and the old cookie is still set. Here is my hopefully understandable code, any help is appreciated.
protected void Cookie_Encode(object sender, EventArgs e)
{
        // Encoding username in Base64
        var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(User_box.Text);
        string Encoded_user = System.Convert.ToBase64String(plainTextBytes);

        // Creating and setting the cookie
        HttpCookie myCookie = new HttpCookie("UserSettings");
        myCookie["UserName"] = Encoded_user;
        myCookie.Expires = DateTime.Now.AddDays(7d);
        Response.Cookies.Add(myCookie);

        Response.Redirect(Request.RawUrl);
}

A: Use DateTime.Now.AddDays(-1) instead of DateTime.Now.AddDays(7d).
protected void Cookie_Encode(object sender, EventArgs e)
{
    // Encoding username in Base64
    var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(User_box.Text);
    string Encoded_user = System.Convert.ToBase64String(plainTextBytes);

    // Creating and setting the cookie
    HttpCookie myCookie = new HttpCookie("UserSettings");
    myCookie["UserName"] = Encoded_user;
    myCookie.Expires = DateTime.Now.AddDays(-1);
    Response.Cookies.Add(myCookie);

    Response.Redirect(Request.RawUrl);
}


text:
Q: How to write a minimalistic Java Client for OpenMQ Please help an MQ nubee to write his first Java Client, I got a little bit lost in the Oracle docs.
I have OpenMQ up and running.
In the OpenMQ Administration Console I established a broker named "MyFirstTest"
1 of 6 services is "jms" (which seems to be the most easy to use service), this service is up and running, too (saying: Service state running).
So I come to the interesting part.
How do I connect to the broker "MyFirstTest", then to send a message in, and last but least read this message perhaps from a second client.
I think I have to find the already existing queue instead of using
new com.sun.messaging.Queue
Any example or link to is appreciated.
public class HelloWorldMessage {
public static void main(String[] args) {
    try {
        ConnectionFactory myConnFactory;
        Queue myQueue;

        myConnFactory = new com.sun.messaging.ConnectionFactory();
        Connection myConn = myConnFactory.createConnection();
        Session mySess = myConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
        myQueue = new com.sun.messaging.Queue("MyFirstTest");

        //Create a message producer.
        MessageProducer myMsgProducer = mySess.createProducer(myQueue);

        //Create and send a message to the queue.
        TextMessage myTextMsg = mySess.createTextMessage();
        myTextMsg.setText("Hello World");
        System.out.println("Sending Message: " + myTextMsg.getText());
        myMsgProducer.send(myTextMsg);

        //Create a message consumer.
        MessageConsumer myMsgConsumer = mySess.createConsumer(myQueue);

        //Start the Connection created in step 3.
        myConn.start();

        //Receive a message from the queue.
        Message msg = myMsgConsumer.receive();

        //Retreive the contents of the message.
        if (msg instanceof TextMessage) {
            TextMessage txtMsg = (TextMessage) msg;
            System.out.println("Read Message: " + txtMsg.getText());
        }

        //Close the session and connection resources.
        mySess.close();
        myConn.close();

    } catch (Exception jmse) {
        System.out.println("Exception occurred : " + jmse.toString());
        jmse.printStackTrace();
    }
}

}

A: //Assuming server supports multiple clients, your client can look like this:
//Ref: http://docs.oracle.com/javase/tutorial/networking/sockets/readingWriting.html
//untested code
class client{

 .....
 ....

 private static Socket echoSocket;

 //main can be in another class also
 public static void main(.... args[]){

   client nodeI,nodeII;
   nodeI = new client("speaker/sender");
   nodeII = new client("listener/recvr");
   nodeI.connect2Server();
   nodeI.sendMssgInstr2Server(node);

 }

 public void connect2Server(){

  try {
            echoSocket = new Socket("<jms.srvr.ip>", <port#>);
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: <jms.srvr.ip>.");
            System.exit(1);
        }
 }

 public void sendMssgInstr2Server throws IOException (client RecipientClientNodeII){
   out = new PrintWriter(echoSocket.getOutputStream(), true);
   out.println("sending message:"+mssgQueue.poll() + " =>recipient client is now reading:"+RecipientClientNodeII.receive);
 }

public void receive(){
  try{
      in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
       }catch (IOException e) {
            System.err.println("Couldn't get I/O for "+"the connection to: <jms.srvr.ip>.");
            System.exit(1);
     }

  while(1)
    in.readLine();
 }

//other methods
  .......
  .......

}; //class client ends


text:
Q: Difference between javacore, thread dump and heap dump in Websphere Can someone tell me the exact difference between javacore, thread dump and heap dump? Under which situation each of these are used??

A: A thread dump is a dump of the stacks of all live threads. Thus useful for analysing what an app is up to at some point in time, and if done at intervals handy in diagnosing some kinds of  'execution' problems (e.g. thread deadlock).
A heap dump is a dump of the state of the Java heap memory. Thus useful for analysing what use of memory an app is making at some point in time so handy in diagnosing some memory issues, and if done at intervals handy in diagnosing memory leaks.
This is what they are in 'raw' terms, and could be provided in many ways. In general used to describe dumped files from JVMs and app servers, and in this form they are a low level tool. Useful if for some reason you can't get anything else, but you will find life easier using decent profiling tool to get similar but easier to dissect info.
With respect to WebSphere a javacore file is a thread dump, albeit with a lot of other info such as locks and loaded classes and some limited memory usage info, and a PHD file is a heap dump.
If you want to read a javacore file you can do so by hand, but there is an IBM tool (BM Thread and Monitor Dump Analyzer) which makes it simpler. If you want to read a heap dump file you need one of many IBM tools: MDD4J or Heap Analyzer.

A: JVM head dump is a snapshot of a JVM heap memory in a given time. So its simply a heap representation of JVM. That is the state of the objects.
JVM thread dump is a snapshot of a JVM threads at a given time. So thats what were threads doing at any given time. This is the state of threads. This helps understanding such as locked threads, hanged threads and running threads.
Head dump has more information of java class level information than a thread dump. For example Head dump is good to analyse JVM heap memory issues and OutOfMemoryError errors. JVM head dump is generated automatically when there is something like OutOfMemoryError has taken place.  Heap dump can be created manually by killing the process using kill -3 . Generating a heap dump is a intensive computing task, which will probably hang your jvm. so itsn't a methond to use offetenly. Heap can be analysed using tools such as eclipse memory analyser.
Core dump is a os level memory usage of objects. It has more informaiton than a head dump. core dump is not created when we kill a process purposely.

A: Heap dumps anytime you wish to see what is being held in memory Out-of-memory errors
Heap dumps - picture of in memory objects - used for memory analysis
Java cores - also known as thread dumps or java dumps, used for viewing the thread activity inside the JVM at a given time. IBM javacores should a lot
of additional information besides just the threads and stacks -- used to determine hangs, deadlocks, and reasons for performance degredation
System cores

A: A Thread dump is a dump of all threads's stack traces, i.e. as if each Thread suddenly threw an Exception and printStackTrace'ed that. This is so that you can see what each thread is doing at some specific point, and is for example very good to catch deadlocks.
A heap dump is a "binary dump" of the full memory the JVM is using, and is for example useful if you need to know why you are running out of memory - in the heap dump you could for example see that you have one billion User objects, even though you should only have a thousand, which points to a memory retention problem.

A: Thread dumps are javacore show snapshot of threads running in JVM, it is useful to debug hang issues, it will provide info about java level dead locks and also IBm version of javacores provides much more useful information, such as heap usage, CPU usage of each thread and overall heap usage along with number of classes laded by the JVM.
Heapdumps, provides information about Java heap usage by an JVM, which can be used to debug memory leaks. Heapdumps are generated by IBM JVMs when a JVM is runs into outofmemoryerror, Heapdumps are only for heap leaks in java, native out of memory error may result system dumps usually with an "GPF" General protection Fault.


text:
Q: Responsive template alignment I am developing a website by downloading some template from net.
I modified some width and height according to our requirement the output is fine in PC but when I check it in mobile the contents are overflowing against background.
Please help me with some solution to solve this problem.
Thanks in advance.

A: You need to consider below dimensions then you have to write accordingly in every media screen using @media queries.
/* Smartphones (portrait and landscape) ----------- */
@media only screen
and (min-device-width : 320px)
and (max-device-width : 480px) {
/* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen
and (min-width : 321px) {
/* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen
and (max-width : 320px) {
/* Styles */
}

/* iPads (portrait and landscape) ----------- */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px) {
/* Styles */
}


text:
Q: How to retain non-string objects across stages in a declarative Jenkinsfile? In a declarative-pipeline Jenkinsfile, it seems that changes in the properties on the env variable are retained across stages and across restarts of the pipeline regardless of stage.  However, it seems that everything on env must be a string.  Is there any way to retain non-string content across stages--without using env or writing to a file?
Specifically, I was thinking I might use params for this, but it seems that values in params can't be changed.  Any other ideas?

A: To retain the value of a variable across stages, define a variable outside your pipeline with @Field annotation
import groovy.transform.Field

@Field def toto

pipeline {
    agent none
    stages {
       stage('stage1') {
           steps {
               toto = { name -> println name }
           }
       }
       stage('stage2') {
           steps {
               println toto('toto')
           }
       }
    }
}

the variable will not survive restart.
To survive restart you could serialize and save your variable's value to a file and unserialize it at the first stage if the file is present


text:
Q: How do I add a note to the work item history programmatically in TFS? In Visual Studio TFS work items have History tab you can add your comments to. Build agent can also contribute to the discussion, which is nice. I would like for more tools to leave their opinion in this History.
How do I programmatically add a note to the work item history like svcTFSBuid does?

A: You can use the TFS API to add a new entry in the history. The WorkItem.History property will do the work:
Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItem testCase = new Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItem(workItemTypes["Test Case"]);
testCase.History = "created by TFS";
ArrayList workItemErrors = testCase.Validate();
if (testCase.IsValid())
{
       testCase.Save();
 }


text:
Q: Getting data from json array mysql Below is my json data which is saved in cold_storage_data column of inventory table
[{
    "qty_in_storage": "10",
    "cold_storage_id": "2",
    "cold_storage_lot_number": "678678"
}, {
    "qty_in_storage": "15",
    "cold_storage_id": "1",
    "cold_storage_lot_number": "678679"
}]

Now I want to retrieve the data based on the cold_storage_lot_number. So I have tried below solutions but none of them are working for me
SELECT
    *
FROM
    test.inventories
WHERE
    JSON_EXTRACT( cold_storage_data, "$.cold_storage_lot_number" ) = "678679";

SELECT
    *
FROM
    test.inventories
WHERE
    json_contains( cold_storage_data, "678679", "$.cold_storage_lot_number" );

SELECT
    *
FROM
    test.inventories
WHERE
    cold_storage_data->"$.cold_storage_lot_number" = "678679";

Where I am going wrong?
The query provided by @dai dbfiddle working fine with mysql version 8 when I am testing it with MariaDB version 10.3.35 it is not working.
MariaDB dbfiddle


text:
Q: How can I create a boxplot for each x value? I have a plot with a set of points for different x values:
5 points for x=0.5, 5 points for x=0.6, ..., 5 points for x=1.4, 5 points for x=1.6.
Now I want to create a boxplot for each of those x values. But somehow all my boxplots are at x=0.5. I want the boxplots to be created at the right x value. The distance between 2 x values can be different. My current x values are 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.2, 1.4 and 1.6, but they could also be different for a different plot. How would I do that?
This is the GNUPlot script for my points: https://dl.dropboxusercontent.com/u/26464165/Points.gnu
This is the GNUPlot script for my boxplots: https://dl.dropboxusercontent.com/u/26464165/Boxplots.gnu
Thanks for your time!

A: You must rearrange your data for the boxplots. The statistics are computed over complete columns. So, you must rearrange your data like:
# 1.0 1.2 1.4 ...
2.2 2.2 3.06
2.0 2.46 2.93
2.2 2.46 3.06
2.0 2.4 2.8
1.73 2.33 2.8

Then you can plot it with:
set style fill solid 0.25 border -1
set style boxplot outliers pointtype 7
set style data boxplot

set title 'My Plot' font 'Arial,14';
set xtics ('1.0' 1, '1.2' 2, '1.4' 3)
plot for [i=1:3] 'data.txt' using (i):i notitle

The result with 4.6.4 is:

Instead of writing the xtics manually, you could extract them (with Unix commandline tools), like shown e.g. in https://stackoverflow.com/a/10799204/2604213:
header = "`head -1 data.txt | cut -b 2-`"
set for [i=1:words(header)] xtics (word(header, i) i)

A: Christoph's answer is fine if you know the number of levels (columns) and their names (xtics) ahead of time. Otherwise, http://soc.if.usp.br/manual/gnuplot-doc/htmldocs/boxplot.html gives a solution with the fourth field of the using statement (using x:data:width:level).
You put all of your data in one column, with an accompanying factor column giving the level for each datum:
2.2   1.0
2.2   1.2
3.06  1.4
2.0   1.0
...

The order the data appear in doesn't matter as long as the levels are correct. The level is converted to a string, which overrides the xtics.
Modifying Christoph's script,
set style fill solid 0.25 border -1
set style boxplot outliers pointtype 7
set style data boxplot

plot "data.txt" using (1):1:(0.5):2

will generate the following:


text:
Q: Compact ball in a closed subspace of X Consider the $B$-space $X = C([0, 1])$ equipped with the norm $\Vert · \Vert_{\infty}$. And let $F$ be a closed subspace of $X$ such that every function $u\in F$ is Holder continuous, namely, for each $u \in F$ there exist $\alpha \in (0, 1]$ and $L\gt0$ such that $ |u(t) − u(s)| \le L|t − s|^{\alpha} \ \ \forall t,s \in [0,1] $.
$(i)$ Setting, for every $n\in  \mathbb{N}_{0}$
\begin{align} F_{n} = \{ u \in F : |u(t) − u(s)| \le n|t − s|^{1/n}, \ \  \forall t, s \in [0, 1] \} \end{align}
and using the Baire theorem prove that there exist $ \beta \in (0, 1]$ and $M\gt0 \ $  (both independent of $u$) such that, for all $ u\in F$ \begin{align}
  |u(t) − u(s)| \le M \Vert u \Vert_{\infty}|t − s|^{\beta}, \ \ \forall t, s \in [0, 1] \end{align}
$(ii)$ Prove that the closed unit ball $B_{F} \subset F$ centered at $0$ is compact and deduce that F is finite-dimensional.
If I have a compact ball in $F$, doesn't it contradict the fact that in a infinite-dim space ($X$ in this case) balls are never compact?

A: No.  $\alpha$-Hölder is not preserved by $\lVert-\rVert_\infty$, so $F$ is not a closed subspace of $(C([0,1]), \lVert-\rVert_\infty)$ (e.g., $F$ contains all polynomials, so its closure in sup norm is $C([0,1])$ by Stone-Weierstrass).  See also this question from a few hours ago.


text:
Q: Android Studio Gradle Version 5.1.1 Problem I have a simple Android app developed in Android studio. When I built it with Gradle 4.10.1, there was no warning or error. After I updated Gradle to Version 5.1.1, I got the following warning:
Task :app:processDebugResources UP-TO-DATE
Changing the value for a property with a final value has been deprecated. This will fail with an error in Gradle 6.0.
What do I need to do to remove this warning? Can anybody help? Thank you in advance.

A: In gradle-wrapper.properties(File Name) change URL of distributionUrl to the following:
distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-all.zip


text:
Q: How do I send my output xls files to a specific path in python? How do i make my df.to_excel function write to an output path? After my script runs, I do not see the files in the output_path directory i have defined.
import pandas as pd
from openpyxl import load_workbook
import os
import datetime

output_path = 'C:/Users/g/Desktop/autotranscribe/python/Processed'

path = 'C:/Users/g/Desktop/autotranscribe/python/Matching'

cols_to_drop =  ['PSI ID','PSIvet Region','PSIvet region num','Fax','County']

column_name_update_map = {'Account name': 'Company Name','Billing address':'Address','Billing city':'City','Billing State':'State'}

for file in os.listdir("C:/Users/g/Desktop/autotranscribe/python/Matching"):
    if file.startswith("PSI") and "(updated headers)" not in file:
        dfs = pd.read_excel(file, sheet_name=None,skiprows=5)
        output = dict()
        for ws, df in dfs.items():
            if ws.startswith("Cancelled Members"): df = df.drop('Active date', axis=1)
            if any(ws.startswith(x) for x in ["New Members","PVCC"]):
                continue
            #if ws in ["New Members 03.22","PVCC"]:   #sheetstoavoid
            temp = df
            dt = pd.to_datetime(os.path.getctime(os.path.join(path,file)),unit="s").replace(nanosecond=0)
            output[ws] = temp
        writer = pd.ExcelWriter(f'{file.replace(".xlsx","")} (updated headers).xlsx')
        for ws, df in output.items():
            df.to_excel(writer, index=None, sheet_name=ws)
        writer.save()
        writer.close()

I tried df.to_excel(writer,output_path, index=None, sheet_name=ws)
But i get an error
File "", line 36, in
df.to_excel(writer,output_path, index=None, sheet_name=ws)
TypeError: to_excel() got multiple values for argument 'sheet_name'.

A: A few comments:

*

*The function os.listdir() only returns "unqualified" file names, so before using file, we need to prepend path using something like input_file_name = f'{path}/{file}'.

*Similarly, pd.ExcelWriter() will need a qualified file name (that is, including the path as well as the "unqualified" file name), which we can get by doing this: output_file_name = f'{output_path}/{file.replace(".xlsx","")} (updated headers).xlsx'.

*There are some elements of the code in your question that may not be getting used, but rather than comment on or change those, I provide a working version with minimal changes below.

I created directories named Matching and Processed. I placed a file named PSI 123.xlsx in Matching with a tab named Cancelled Members containing the following:
will skip
will skip
will skip
will skip
will skip
Col1        Col2    Col3    Active date
xx          NY      110     789

I then ran the following modification to your code (note the changes to output_path and path for testing purposes in my environment):
import pandas as pd
from openpyxl import load_workbook
import os
import datetime

#output_path = 'C:/Users/g/Desktop/autotranscribe/python/Processed'

#path = 'C:/Users/g/Desktop/autotranscribe/python/Matching'

output_path = './Processed'
path = './Matching'

cols_to_drop =  ['PSI ID','PSIvet Region','PSIvet region num','Fax','County']

column_name_update_map = {'Account name': 'Company Name','Billing address':'Address','Billing city':'City','Billing State':'State'}

for file in os.listdir(path):
    if file.startswith("PSI") and "(updated headers)" not in file:
        input_file_name = f'{path}/{file}'
        dfs = pd.read_excel(input_file_name, sheet_name=None,skiprows=5)
        output = dict()
        for ws, df in dfs.items():
            if ws.startswith("Cancelled Members") and 'Active date' in df.columns: df = df.drop('Active date', axis=1)
            if any(ws.startswith(x) for x in ["New Members","PVCC"]):
                continue
            #if ws in ["New Members 03.22","PVCC"]:   #sheetstoavoid
            temp = df
            dt = pd.to_datetime(os.path.getctime(os.path.join(path,file)),unit="s").replace(nanosecond=0)
            output[ws] = temp
        output_file_name = f'{output_path}/{file.replace(".xlsx","")} (updated headers).xlsx'
        writer = pd.ExcelWriter(output_file_name)
        for ws, df in output.items():
            df.to_excel(writer, index=None, sheet_name=ws)
        writer.save()
        writer.close()

After running, the code had created a new file in Processed named PSI 123 (updated headers).xlsx with sheets named as in the input. The sheet Cancelled Members contained the following:
Address State   Zip Status  Status.1    Date    Partner
Col1    Col2    Col3
xx      NY      110


text:
Q: cannot write script in sting c# can someone please tell me why I cant do this
<script language="c#" runat="server">
public void Page_Load(object sender, EventArgs e)
{
  string jj = "</script>";
}
</script>

 ends up not being a string and it breaks up my ending tags in the aspx page.

A: You need to escape your string, either "<//script>" or @"</string>".


text:
Q: Using private key to decrypt file.(RSA) I need someone help.
In my android phone I create public key( to encrypt file) and private key to decrypt. I save them in 2 file. It is ok when I decrypt by android. But when I copy private key file and use it to decrypt in my PC (java), I get exception:
at sun.security.rsa.RSAPadding.unpadV15(Unknown Source)
    at sun.security.rsa.RSAPadding.unpad(Unknown Source)
    at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:356)
    at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:382)
    at javax.crypto.Cipher.doFinal(Cipher.java:2087)
    at com.molisy.decryptfile.Main.RSADecrypt(Main.java:193)
    at com.molisy.decryptfile.Main$2.actionPerformed(Main.java:309)
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$200(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

I do not know how to fix. But Value of the private key file is not same if I print it in my android and my pc.
In my android apps: OpenSSLRSAPrivateKey{modulus=a9a141d6ef0050e27f00ec381f2fcfeb47781dcfb14f9b3eb378bd361b92b6da7feb8f2be7466314794d7543eb99c818d260d48b898c9995db3a3af76b23013ff935f77b8a89edcbd9d16a583b60591e55f7cb8271fa4cfae53fd759f3d8e1b522485e2cf29e89034223329322b4357c84fc848348b004136d6d360f8c9a70cb,privateExponent=7eaff2ee455da50b23f35a78a7c21bb50a9189223eb8c7a7527ed04182e2563265eb55e862384d73530d28916b7a54d944f610878e5935b39821ab3c720598be28d747de099ff8fac6558f235b983815efc61cbc574be39d97dc7ac57e6cf82161f4301dfe777c3c33c58d7c75f581de5cc0db83b079de7d79864a6189667171,
and in my java apps: sun.security.rsa.RSAPrivateKeyImpl@4dd8f
why it is so difference. and how to fix

A: Here is my code:
public void RSADecrypt(String inFileName, String outFileName) {
        try {
            /* Get the encrypted message from file. */
            FileInputStream cipherfile = new FileInputStream(inFileName);

            byte[] ciphertext = new byte[cipherfile.available()];
            cipherfile.read(ciphertext);
            cipherfile.close();
            PrivateKey privatekey =readPrivateKeyFromFile("D:\\Private.key");

            /* Create cipher for decryption. */
            Cipher decrypt_cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            decrypt_cipher.init(Cipher.DECRYPT_MODE, privatekey);
            FileOutputStream plainfile = new FileOutputStream(outFileName);
            int n = ciphertext.length / 128;
            System.out.println("len: " + n);
            byte[] data1 = new byte[128];
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < 128; j++) {
                    data1[j] = ciphertext[128 * i + j];
                }
                byte[] descryptedData = decrypt_cipher.doFinal(data1);
                plainfile.write(descryptedData);

            }

            plainfile.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
public PrivateKey readPrivateKeyFromFile(String fileName)
            throws IOException {
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        try {
            fis = new FileInputStream(new File(fileName));
            ois = new ObjectInputStream(fis);

            BigInteger modulus = (BigInteger) ois.readObject();
            BigInteger exponent = (BigInteger) ois.readObject();

            // Get Private Key
            RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(
                    modulus, exponent);
            KeyFactory fact = KeyFactory.getInstance("RSA");
            PrivateKey privateKey = fact.generatePrivate(rsaPrivateKeySpec);
            System.out.println("get key ok: " + privateKey.toString());
            return privateKey;

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ois != null) {
                ois.close();
                if (fis != null) {
                    fis.close();
                }
            }
        }
        return null;
    }

I decrypt 128bytes/time. Because data too long to decrypt. It work ok in android. readPrivateKeyFromFile method return other value of private key( not same as in android although I use the same code).

A: I try a lot and find out. If you encrypt in moblie youn can only decrypt on mobile, and same in PC. because of different enviroiment Is that true?


text:
Q: Mongoose: search for users with certain regex query I have a mongoose query that searches for users that match a certain regex

       let { q } = req.query;
        // prettier-ignore
        q = q.replace(".", '\.');

        // find user
        const users = await db.User.find({
            email: new RegExp(`${q}`, "ig"),
        });

I am trying to match the exact character  < . > DOT but for some reason, it doesn't work and the result is the regex < . > DOT "the any character notation".
which results in wrong logical results.
I want to match for the exact character < . > DOT   how to achieve this?
Example response for query "s.":
[
    {
        "name": "hoo hoo",
        "email": "ahmeds.g.aafer@gmail.com",
        "img": "09b37a7b29eae24507192185957dc7c7"
    },
    {
        "name": "someuser",
        "email": "someuser@gmail.com",
        "img": "c226d980ff0d72d3799cb75c641fdd09"
    }
]

What I want the response to be:
[
    {
        "name": "hoo hoo",
        "email": "ahmeds.g.aafer@gmail.com",
        "img": "09b37a7b29eae24507192185957dc7c7"
    },

]

A: \\. instead of \. will make it work, \. says . is the spetial character when \ is the actual spetial one.


text:
Q: Using a session My app uses information over a server. I have one line of code that connects to my database at runtime called 'stream'. Its primary function is to retrieve user device tokens from a database table named photos.
$result = query("INSERT INTO login(username, pass, device_token) VALUES('%s','%s','%s')", $user, $pass, $token);

This is very valuable information for my app. Can someone help me store the $token value from the statement above to a session so that it can be used in this method?
function handleMessage()
{
    $userId = $this->getUserId();
    /*$text = $this->getString('text', self::MAX_MESSAGE_LENGTH, true);*/

    // First, we get the record for the sender of the message from the
    // active_users table. That gives us the nickname, device token, and
    // secret code for that user.

    $stmt = $this->pdo->prepare('SELECT * FROM active_users WHERE user_Id = ? LIMIT 1');
    $stmt->execute(array($userId));
    $user = $stmt->fetch(PDO::FETCH_OBJ);

    if ($user !== false)
    {
        // Put the sender's name and the message text into the JSON payload
        // for the push notification.
        $payload = $this->makePayload($user->nickname/*, $text*/);

        // Find the device tokens for all other users who are registered
        // for this secret code. We exclude the device token of the sender
        // of the message, so he will not get a push notification. We also
        // exclude users who have not submitted a valid device token yet.

        $stmt = $this->pdo->prepare("SELECT device_token FROM active_users WHERE secret_code = ? AND device_token <> ? AND device_token <> '0'");
        $stmt->execute(array($user->secret_code, $user->device_token));
        $tokens = $stmt->fetchAll(PDO::FETCH_COLUMN);

        // Send out a push notification to each of these devices.
        foreach ($tokens as $token)
        {
            $this->addPushNotification($token, $payload);
        }
    }
}

I know it sounds complicated but I'm sure it can be done.