text:
Q: How to specify legend position in matplotlib in graph coordinates I am aware of the bbox_to_anchor keyword and this thread, which very helpfully suggests how to manually place the legend:
How to put the legend out of the plot
However, I'd like to use the coordinates of my x- and y-axis in the graph to specify the legend position (inside the plot), as I might need to move the figure into a large figure with a different axis environment, and I don't want to manually play around with those coordinates every time I do this. Is this possible?
Edit: A small example is here:
import numpy as n
f, axarr = plt.subplots(2,sharex=True)
axarr[1].set_ylim([0.611,0.675])
axarr[0].set_ylim([0.792,0.856])
axarr[0].plot([0, 0.04, 0.08],n.array([ 0.83333333,  0.82250521,0.81109048]), label='test1')
axarr[0].errorbar([0, 0.04, 0.08],n.array([ 0.8,  0.83,   0.82]),n.array([0.1,0.1,0.01]), label='test2')
axarr[1].plot([0, 0.04, 0.08],n.array([ 0.66666667,  0.64888304,  0.63042428]))
axarr[1].errorbar([0, 0.04, 0.08],n.array([ 0.67,  0.64,  0.62]),n.array([ 0.01,  0.05,  0.1]))
axarr[0].legend(bbox_to_anchor=(0.04, 0.82, 1., .102),labelspacing=0.1,       handlelength=0.1, handletextpad=0.1,frameon=False, ncol=4, columnspacing=0.7)

I think what confuses me is that the legend does not actually start at 0.82, and indeed for my larger plot (with 5 subplots of this type), I need to use legend coordinates bbox_to_anchor=(0.04, 1.15, 1., .102) in order to make the legend appear on coordinates (0.02, 0.83). But maybe I am getting something else wrong?

A: You can change location of legend using loc argument.
https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.legend.html?highlight=legend#matplotlib.axes.Axes.legend
import matplotlib.pyplot as plt

plt.subplot(211)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend above this subplot, expanding itself to
# fully use the given bounding box.
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
           ncol=2, mode="expand", borderaxespad=0.)

plt.subplot(223)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend to the right of this smaller subplot.
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)

plt.show()

A: Way I use very often is loc argument in the legend function. String input works well:
plt.legend(loc = "upper left")

As documentation says, for the string referencing you can use:
        ===============   =============
        Location String   Location Code
        ===============   =============
        'best'            0
        'upper right'     1
        'upper left'      2
        'lower left'      3
        'lower right'     4
        'right'           5
        'center left'     6
        'center right'    7
        'lower center'    8
        'upper center'    9
        'center'          10
        ===============   =============

A: In addition to @ImportanceOfBeingErnest's post, I use the following line to add a legend at an absolute position in a plot.
plt.legend(bbox_to_anchor=(1.0,1.0),\
    bbox_transform=plt.gcf().transFigure)

For unknown reasons, bbox_transform=fig.transFigure does not work with me.

A: According to the matplotlib legend documentation:

The location can also be a 2-tuple giving the coordinates of the lower-left corner of the legend in axes coordinates (in which case bbox_to_anchor will be ignored).

Thus, one could use:
plt.legend(loc=(x, y))

to set the legend's lower left corner to the specified (x, y) position.
Note that the x and y coordinates here are relative, meaning that x=0 is the left most point in the plot and x=1 is the rightmost point in the plot. Similarly for y=0 and y=1 along the height of the plot.

A: The loc parameter specifies in which corner of the bounding box the legend is placed. The default for loc is  loc="best" which gives unpredictable results when the bbox_to_anchor argument is used.
Therefore, when specifying bbox_to_anchor, always specify loc as well.
The default for bbox_to_anchor is (0,0,1,1), which is a bounding box over the complete axes. If a different bounding box is specified, is is usually sufficient to use the first two values, which give (x0, y0) of the bounding box.
Below is an example where the bounding box is set to position (0.6,0.5) (green dot) and different loc parameters are tested. Because the legend extents outside the bounding box, the loc parameter may be interpreted as "which corner of the legend shall be placed at position given by the 2-tuple bbox_to_anchor argument".

import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = 6, 3
fig, axes = plt.subplots(ncols=3)
locs = ["upper left", "lower left", "center right"]
for l, ax in zip(locs, axes.flatten()):
    ax.set_title(l)
    ax.plot([1,2,3],[2,3,1], "b-", label="blue")
    ax.plot([1,2,3],[1,2,1], "r-", label="red")
    ax.legend(loc=l, bbox_to_anchor=(0.6,0.5))
    ax.scatter((0.6),(0.5), s=81, c="limegreen", transform=ax.transAxes)

plt.tight_layout()
plt.show()

See especially this answer for a detailed explanation and the question What does a 4-element tuple argument for 'bbox_to_anchor' mean in matplotlib? .

If you want to specify the legend position in other coordinates than axes coordinates, you can do so by using the bbox_transform argument. If may make sense to use figure coordinates

ax.legend(bbox_to_anchor=(1,0), loc="lower right",  bbox_transform=fig.transFigure)

It may not make too much sense to use data coordinates, but since you asked for it this would be done via bbox_transform=ax.transData.


text:
Q: Month closest actual month i have this table:
Players:
ID (int)
Birthday (datetime)

I need choose 3 first players, which have birthday in the actual month...
I have this but the result is nothing.. Have you any idea?
SELECT *
FROM Players
WHERE Birthday < DATEADD(month, -2, GETDATE())

A: You need to use DATEPART function in SQL server
SELECT *
FROM Players
WHERE DATEPART(MM,Birthday) = DATEPART(MM,GETDATE())

A: Using SQL Server syntax:
select  top 3 *
from    YourTable
where   datepart(month, Birthday) = datepart(month, getdate())

redpajama_set_name: RedPajamaStackExchange


text:
Q: Static libraries with managed code issue Problem (simplified to make things clearer):

*
1. there is one statically-linked static.lib that has a function that increments:

    extern int CallCount = 0;
    int TheFunction()
    {
        void *p = &CallCount;
        printf("Function called");
        return CallCount++;
    }

2. static.lib is linked into a managed C++/CLI managed.dll that wraps TheFunction method:

    int Managed::CallLibFunc()
    {
        return TheFunction();
    }

3. Test app has a reference to managed.dll and creates multiple domains that call C++/CLI wrapper:

    static void Main(string[] args)
    {
        Managed c1 = new Managed();
        int val1 = c1.CallLibFunc();
        // value is zero

        AppDomain ad = AppDomain.CreateDomain("NewDomain");
        Managed c = ad.CreateInstanceAndUnwrap(a.FullName, typeof(Managed).FullName) as Managed;
        int val2 = c.CallLibFunc();
        // value is one
    }

Question:
Based on what I have read in Essential .NET  Vol1 The CLR by Don Box, I would expect val2 to be zero since a brand new copy of managed.dll/static.lib is loaded when CreateInstanceAndUnwrap is called. Am I misunderstanding what is happening? The static library does not seem to be respecting the appdomain boundaries since it's unmanaged code. Is there a way to get around this issue other than by creating a brand new process for instantiating Managed?
Thank you very much everyone!

A: My hunch was that, as you suspected, unmanaged DLLs are loaded in the context of the process and not in the context of the AppDomain, so any static data in unmanaged code is shared among AppDomains.
This link shows someone with the same problem you have, still not 100% verification of this, but probably this is the case.
This link is about creating a callback from unmanaged code into an AppDomain using a thunking trick. I'm not sure this can help you but maybe you'll find this useful to create some kind of a workaround.

A: After you call
Managed c1 = new Managed();

Your managed.dll wrapper will be loaded into main app domain of you application. Till it will be there domain unmanaged stuff from static.lib  will be shared with other domains.
Instead of creating separate process you just need to be sure (before each call) that managed.dll is not loaded into any application domain.
Compare with that
static void Main(string[] args)
{

    {
                AppDomain ad = AppDomain.CreateDomain("NewDomain");
                Managed c = ad.CreateInstanceAndUnwrap(a.FullName, typeof(Managed).FullName) as Managed;
                int val2 = c.CallLibFunc();
                //  Value is zero

               AppDomain.Unload(ad)
    }
    {
                AppDomain ad = AppDomain.CreateDomain("NewDomain");
                Managed c = ad.CreateInstanceAndUnwrap(a.FullName, typeof(Managed).FullName) as Managed;
                int val2 = c.CallLibFunc();
                //  I think value is zero

               AppDomain.Unload(ad)
    }

}
`

IMPORTANT and : If you add just one line JIT compiler will load managed.dll and the magic disappears.
static void Main(string[] args)
{

    {
                AppDomain ad = AppDomain.CreateDomain("NewDomain");
                Managed c = ad.CreateInstanceAndUnwrap(a.FullName, typeof(Managed).FullName) as Managed;
                int val2 = c.CallLibFunc();
                //  Value is zero

               AppDomain.Unload(ad)
    }
    {
                AppDomain ad = AppDomain.CreateDomain("NewDomain");
                Managed c = ad.CreateInstanceAndUnwrap(a.FullName, typeof(Managed).FullName) as Managed;
                int val2 = c.CallLibFunc();
                //  I think value is one

               AppDomain.Unload(ad)
    }
Managed c1 = new Managed();

}

If you don't want to depend on such lines you can create another one wrapper ManagedIsolated.dll that will reference managed.dll and will make each call in separate domain with domain unload just after the call.  Main application will depend only on ManagedIsolated.dll types and Managed.dll will not be loaded into main app domain.
That looks like a trick but may be it will be usefull for somebody.
    `

A: In short, maybe.  AppDomains are purely a managed concept.  When an AppDomain is instantiated  it doesn't map in new copies of the underlying DLLs, it can reuse the code already in memory (for example, you wouldn't expect it to load up new copies of all the System.* assemblies, right?)
Within the managed world all static variables are scoped by AppDomain, but as you point out this doesn't apply in the unmanaged world.
You could do something complex that forces a load of a unique managed.dll for each app domain, which would result in a new version of the static lib being brought along for the ride.  For example, maybe using Assembly.Load with a byte array would work, but I don't know how the CLR will attempt to deal with the collision in types if the same assembly is loaded twice.

A: I don't think we're getting to the actual issue here - see this DDJ article.
The default value of the loader optimization attribute is SingleDomain, which "causes the AppDomain to load a private copy of each necessary assembly's code". Even if it were one of the Multi domain values "every AppDomain always maintains a distinct copy of static fields".
'managed.dll' is (as its name implies) is a managed assembly. The code in static.lib has been statically compiled (as IL code) into 'managed.dll', so I would expect the same behaviour as Lenik expects....
... unless static.lib is a static export library for an unmanaged DLL. Lenik says this is not the case, so I'm still unsure what's going on here.

A: Have you tried running in separate processes? A static library should not share memory instances outside of it's own process.
This can be a pain to manage, I know. I'm not sure what your other options would be in this case though.
Edit: After a little looking around I think you could do everything you needed to with the System.Diagnostics.Process class. You would have a lot of options at this point for communication but .NET Remoting or WCF would probably be good and easy choices.

A: These are the best two articles I found on the subject

*

*http://blogs.msdn.com/cbrumme/archive/2003/04/15/51317.aspx

*http://blogs.msdn.com/cbrumme/archive/2003/06/01/51466.aspx
The important part is:

RVA-based static fields are process-global.  These are restricted to scalars and value types, because we do not want to allow objects to bleed across AppDomain boundaries.  That would cause all sorts of problems, especially during AppDomain unloads.  Some languages like ILASM and MC++ make it convenient to define RVA-based static fields.  Most languages do not.

Ok, so if you control the code in the .lib, I'd try
class CallCountHolder {
   public:
     CallCountHolder(int i) : count(i) {}
     int count;
};

static CallCountHolder cc(0);
int TheFunction()
{
    printf("Function called");
    return cc.count++;
}

Since he said that RVA-based static fields are limited to scalars and value types.  An int array might also work.


text:
Q: Pact-jvm java noob questions I have a few noob questions about Pact JVM (Java);

*

*If the providers json structure response is already known (for example by querying the api with Postman) ,is it possible to convert Postman json body automatically into a pact contract file without the need to run a (java) Consumer Fragment creation method, or for example convert it into a java PactDslJsonBody() structure?

*Is the provider (spring-boot) needed to be up and running (even if the json response structure is already known) when the pact file is being created? It would be good maybe to avoid the need to launch the spring-boot server for each and every contract creation, particularly if the contract details is already known? Particularly if creating many pact contracts for many microservices at ones.

*Is there a more advanced example of a larger returned provider json structure than this very small json body found in the tutorial example;
[1] http://the-creative-tester.github.io/Java-Consumer-Driven-Contract-Testing/
Furthermore it would be good if that additional example could be shared that only verify a subset of the structure to be returned exist since we got a lot in the responses that are random.

*Could somebody share a pact verify java code example of a pact jvm verify towards an online https (as opposed to http) rest service, like for example google, facebook or similar provider? ( or for example this: [2] https://jsonplaceholder.typicode.com/posts )

*I gotten a lot of java compilation errors with above example[1]. Are there any version level of pact (and spring) that are less likely to get mismatch with java spring framework versions?
Thanks for your time!

A: Hi Please find response below:
1)Currently there is no such functionality.Consumer Fragment is basically to define the json so skipping this step doesn't make sense.
2) The pact file creation uses Pact Mock Server. So you dont need real service to be up. The service should be up only during verification phase.
3,4,5) Version plays a critical role since this framework is actively evolving. Regarding handling complex json structures, there are quite a few examples to show usage of Pact DSL. You may use those to come up with the json structure of your service.
https://github.com/DiUS/pact-jvm/tree/master/pact-jvm-consumer-junit#dsl-matching-methods

A: For 3), See if this link helps you - http://www.briandupreez.net/2017/03/consumer-driven-testing-with-pact.html
And here are examples from the author of pact-jvm - https://github.com/DiUS/pact-jvm/tree/master/pact-jvm-consumer-junit/src/test/java/au/com/dius/pact/consumer/examples.


text:
Q: Saving data from nodes to array I want to save data from a xml file to my database, and below you can see my php code where i've tried to create an associative array to put the values into for later use. However, the actual SimpleXMLElement object is stored, not the just the pure value.
I have two questions here:

*

*How can I change my code so that the actual values (as numbers or strings) is stored instead of the SimpleXMLElement object?

*Is this a good way of storing the values for later storing with SQLLite (which I will use), or what other options do I have that works better?

php:
$theProducers = simplexml_load_file('sources/producers.xml');

$i = 0;
foreach ($theProducers->producer as $producer) {
    $producers['id'][$i] = $producer->attributes();
    $producers['name'][$i] = $producer->name;
    $producers['address'][$i] = $producer->address;
    $producers['zipcode'][$i] = $producer->zipcode;
    $producers['town'][$i] = $producer->town;
    $producers['url'][$i] = $producer->url;
    $producers['imgurl'][$i] = $producer->imgurl;

    $i += 1;
}

print_r($producers);  // outcome below

producers.xml:
<?xml version="1.0"?>
<producers>
  <producer id="8">
    <name>Emåmejeriet</name>
    <address>Grenvägen 1-3</address>
    <zipcode>577 39</zipcode>
    <town>Hultsfred</town>
    <url>http://www.emamejeriet.se</url>
    <imgurl>http://172.16.206.1/~thajo/1DV449/laboration01/producenter/images/ema.png</imgurl>
  </producer>
  <producer>
  ...

outcome from print_r($producers):
Array (
[id] => Array (
    [0] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 8 ) )
    [1] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 57 ) )
    [2] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 45 ) )
    [3] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 33 ) )
    [4] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 16 ) )
    [5] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 41 ) )
    [6] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 38 ) )
    [7] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 40 ) )
    [8] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 56 ) ) )
[name] => Array (
    [0] => SimpleXMLElement Object ( [0] => Emåmejeriet )
    [1] => SimpleXMLElement Object ( [0] => Ölands Örtagård AB )
    [2] => SimpleXMLElement Object ( [0] => Dövestads utegrisar & Gårdsbutik )
... and so on...

A: change structure of the out put array:
foreach ($theProducers->producer as $producer) {
    $attr = $producer->attributes();
    $producers[$i]['id'] = (int)$attr[0];
    $producers[$i]['name'] = (string)$producer->name;
    $producers[$i]['address'] = (string)$producer->address;
    $producers[$i]['zipcode'] = (string)$producer->zipcode;
    $producers[$i]['town'] = (string)$producer->towbn;
    $producers[$i]['url'] = (string)$producer->url;
    $producers[$i]['imgurl'] = (string)$producer->imgurl;

    $i += 1;
}

A: Just cast to the appropriate data type (eg. usually string, but sometimes other types, like int, may make sense):
$producers['id'][$i] = (string)$producer->attributes()['id'];
$producers['name'][$i] = (string)$producer->name;
$producers['address'][$i] = (string)$producer->address;
$producers['zipcode'][$i] = (string)$producer->zipcode;
$producers['town'][$i] = (string)$producer->town;
$producers['url'][$i] = (string)$producer->url;
$producers['imgurl'][$i] = (string)$producer->imgurl;

note: I also added ['id'] to the ->attributes() call -- assuming this is what you intended.


text:
Q: How can use DISTINCT in SQL Query for extracting records from 1 Data Extension and dumping it in another Data Extension I have 1st DataExtension names "Accessories" and 2nd as "TestAccessories". I want to dump all the unique records from Accessories to TestAccessories, My query is as follows:
SELECT DISTINCT [Customer Code], Email, Location, [Operator Code], Date, Time, [Customer Group1], GUID
FROM Accessories

In Accessories DE GUID is Primary key, and I want unique values from [customer code] field, the above given query is not giving me unique values.What is the other way?
I have tried the same query for finding Distinct emails but it's not giving required output.

A: AFAIK you will get every item out of this because you use distinct over all of your fields instead of only one column.
Workaround, because i dont know the better way atm:

*

*Create a DataExtension called DISTINCTCUSTOMERCODES with the field CustomerCode

*Create an SQL Query Automation SELECT DISTINCT [Customer Code] as CustomerCode FROM Accessories into the new Data Extension DISTINCTCUSTOMERCODES

*Create a Second SQL Query ActivitySELECT DISTINCT [Customer Code], Email, Location, [Operator Code], Date, Time, [Customer Group1], GUID
FROM Accessories as acc
INNER JOIN DISTINCTCUSTOMERCODES as dcc
ON acc.CustomerCode= dcc.CustomerCode

*Create an Automation that runs those activities after each other

I know that there is a better solution for the SQL Statement. I believe (not certain) you have to do something like this. I know the Syntax is wrong on the JOIN statement atleast, feel free to correct this.
SELECT [Customer Code], Email, Location, [Operator Code], Date, Time, [Customer Group1], GUID
FROM Accessories as acc1
INNER JOIN Accessories as acc2
(SELECT DISTINCT [Customer Code]
FROM Accessories as acc2)
ON acc1.[Customer Code]= acc2.[Customer Code]


text:
Q: Отключается Apache в Denwer после запуска После переустановки запустил denwer, но после 30 сек Apache отключается.
Пишет:

httpd.exe: Syntax error on line 163 of
  /user/local/apache/conf/httpd.conf: Cannot load
  /user/local/php5/php5apach2_2.dll into server: \xcd\xe5
  \xed\xe0\xe9\xe4\xed .....

В свое время я обновил версию php до версии 5.5 и пришлось пошаманить, чтоб он начал работать. Теперь как я понимаю опять нужно, но я не помню что именно нужно сделать.

A: Скорее за все какое-то приложение занимает порт 3306, на котором MySQL работает.
В консоли:
netstat -a -b -p tcp

И узнаешь, какое именно.
А вообще, не рекомендую использовать денвер. Wamp или Xampp в разы лучше. И разобраться очень просто.


text:
Q: Query not returning result if the join fails (how to get it to return zero) My query is trying to find monthly records with missing days, ie if month has 31 days but less than 31 records I want to detect it. This works fine unless all 31 records are missing when nothing is returned! (By the way Daily is a big table). So how do I get the transmitters with no records at all in a particular month to return zero?
  SELECT SUM(w.amount) AS MonthlyTotal,COUNT(*) AS Days,DAY(LAST_DAY('2016-06-01')) AS DaysInMonth
    FROM Daily  w,Transmitter t
    WHERE t.SiteID='1907' AND t.UtilityID='1' AND w.TransmitterID=t.TransmitterID  AND NOT t.deleted
    AND w.TimeStamp  BETWEEN '2016-06-01' AND LAST_DAY('2016-06-01') GROUP BY t.TransmitterID;

A: Before going into the main problem, there are a few more issues with the query:

*

*the use of string literals ('1907' '1')  for values that are compared with columns that seem to have integer type (SiteID, UtilityID). If the columns are integers, use integers, not strings:
WHERE ... t.SiteID = 1907 AND t.UtilityID = 1

*using BETWEEN and LAST_DAY() for datetime/timestamp comparisons. This - assuming that the w.Timestamp column is indeed a TIMESTAMP will give you incorrect results, unless all your timestamps have 00:00:00 time part. The LAST_DAY('2016-01-01') will be '2016-01-31 00:00:00' and you lose the whole last day of the month, except the very first second.
If you change that to BETWEEN '2016-06-01' AND '2016-07-01 is somewhat better but still wrong as you you'll get a few results from the next day (in July)!
One way that works correctly and with all datatypes (DATE, DATETIME, TIMESTAMP) is to use inclusive-exclusive range checks, with >= and <:
WHERE ... w.TimeStamp >= '2016-06-01' AND w.TimeStamp < '2016-07-01'

If the t.Timestamp column is of DATE type, then ok, BETWEEN can be used although I prefer the consistency of the above suggested code.

*using old ANSI syntax without JOIN. This is not an error but it's harder for debugging when there are many tables and error-prone (we might forget a joining clause):
FROM Daily w, Transmitter t
WHERE ... AND w.TransmitterID = t.TransmitterID AND ...

It's better (in my opinion) to use the new (since 1992 ;) explicit JOIN syntax. It's also easier to change an INNER join to a LEFT or RIGHT outer join:
FROM Daily w JOIN Transmitter t
     ON w.TransmitterID = t.TransmitterID
WHERE ... AND w.TransmitterID = t.TransmitterID AND ...

Now for the main problem, the solution is to start from the Trasmitter table and then LEFT JOIN the details (Daily) table:
SELECT
    t.TransmitterID,
    SUM(w.amount)                        AS MonthlyTotal,
    COUNT(w.TransmitterID)               AS Days,
    DATEDIFF('2016-07-01', '2016-06-01') AS DaysInMonth
FROM Transmitter t LEFT JOIN Daily w
               ON  w.TransmitterID = t.TransmitterID
               AND w.TimeStamp >= '2016-06-01'
               AND w.TimeStamp  < '2016-07-01'
WHERE t.SiteID = 1907
  AND t.UtilityID = 1
  AND NOT t.deleted
GROUP BY t.TransmitterID ;


text:
Q: clean VS 2015 Enterprise + Xamarin Install: error: NuGet Package restore failed for project Hello i have a clean Installation of VS2015 Enterprise + Xamarin.
Then just start a New Projekt (Xamarin Forms Portable) add a Button and want to test on Android Emu.
Then i get the Following 5 Errors and i don't know, how to solved it.
errors
start Projekt

A: Try to restore the NuGet packages manually. Navigate to Tools > Nuget Package Manager > Manage NuGet Packages for Solution. If you see the button "Restore packages," click it. Make sure the packages are up to date. Furthermore, check your Android SDK is up to date. Navigate to Tools > Android > Android SDK Manager.

A: If you don't need the UWP project, you can delete it or try yo install this nuget package: https://www.nuget.org/packages/Xamarin.Forms/2.0.0.6482
For the other errors, install this Nuget Package: https://www.nuget.org/packages/Xamarin.Android.Support.v7.MediaRouter/23.0.1.3

A: Maybe a long shot but I had similar problems when restoring packages in Visual Studio 2015, and that was caused by a custom nuget server I added to sources (with authetication). Try temporary disable any of these if you got any, in the Tools -> Options -> NuGet package manager

A: You can try the following:

*

*Remove the reference of Xamarin Forms portable library from your WinSetupDemo.UWP project, I believe Xamarin forms doesn't support UWP unless you use Xamarin Forms v2.1 and above

*Make sure that the Android Support Library is installed correctly, search for it in the Xamarin components store and follow the setup instructions, make sure it installs correctly, one of the reasons it fails is that your directory hiererchy is too deep so that file names become too long, if this is the case, try installing your Android SDK at a top level directory such as C:\Android


text:
Q: When sorting using statements with DevExpress Refactor Pro can I make it so all System namespaces are at the top? i want all of the system usings at the top (sorted alphabetically) and then all other using statements afterwards (sorted alphabetically)

A: You can make Refactor Pro to do it your way.
Open "DevExpress -> Options -> Editor -> Refactoring -> Optimize Namespace References" and set relevant options according to your preferences.

A: Don't know about RefactorPro, but since the question is tagged with "visual-studio-2008", you can do it in VS'08 by going to Tools -> Options -> Text Editor -> C# (or whatever is relevant) -> Advanced and then ticking "Place 'System' directives first when sorting usings".

A: RefactorPro / CodeRush both have refactorings to....

*

*Optimize namespaces (remove unused namespaces)

*Sort Alphabetically

*Sort by length

Additionally there are (3rd party) plugins that sort in many other ways.
For example: Refactor_SortNamespacesByScope
Additionally, although the asker does not require this, these products also work VS2005.


text:
Q: How can I monitor BizTalk Receive Location Polling? I am trying to monitor the ftp and sql polling receive locations in BizTalk 2009 and BizTalk 2010.
I want to know how often a receive location is polling, when the last time the poll took place, how long the poll took, and did the poll create a message. I can see the messages that are created when the poll is complete. I am more interested in the polling itself.
What screen or tool can I use to see this information? Can I find this information in the BizTalk database tables?

A: How often a receive location is polling will depend on the "Polling settings" you configure on the receive location. Ex: on FTP configuration there is a section called "Polling Setting" with Interval and Units.
I'm afraid there is no direct way to figure out "Did the poll created a message". If in case it retrieved a message, then you would have seen the details of the service instance with the message, but if in case it didn't pulled any message then there won't be any trace. This will apply to "last time the poll took place" as well
Again, I don't thing you will get details for "How long the poll took".

A: You could dig into using WMI for BizTalk.  I know you can get a hold of the locations status but I'm not sure about some of the other things you want.  I belive MOM using WMI so I suppose its possible to do the same thing.


text:
Q: How to move useEffect from component to custom hook I have multiple components with the same useEffect code.
fucntion MyComponent1 (props) {

 const {
        handleApiCall,
        data,
        isLoading,
        isError,
        isSuccess,
  } = useCustomAsyncHook();

 React.useEffect(() => {
   if (isSuccess && !isEmpty(data)) {
      setSnackbar({
        show: false,
        message: '',
      });
      dispatch({
        type: ACTION_TYPES.UPDATE_METADATA,
        payload: { data },
      });
    }
 }, [data, isSuccess, setSnackbar]);

 const onSave = () => {
     handleApiCall()
 }

 return (
   <button onClick={onSave}> Save </button>
 )

}

I have this useEffect hook code repeating in multiple components.
I just want to move this useEffect hook into custom hook so that I need not repeat it in multiple components.
const useMetadataUpdate = ({ data, isSuccess, setSnackbar, dispatch }) => {
    React.useEffect(() => {
        if (isSuccess && !isEmpty(data)) {
            setSnackbar({
                show: false,
                message: '',
            });
            dispatch({
                type: ACTION_TYPES.UPDATE_METADATA,
                payload: { data },
            });
        }
    }, [data, isSuccess, setSnackbar, dispatch]);
};

fucntion MyComponet1 (props) {
   const {
        handleApiCall,
        data,
        isLoading,
        isError,
        isSuccess,
  } = useCustomAsyncHook();

  useMetadataUpdate({ data, isSuccess, setSnackbar, dispatch });

  const onSave = () => {
     handleApiCall()
 }

 return (
   <button onClick={onSave}> Save </button>
 )
}

Refactoring useEffect to a separate function works.
I can't find documentation explicitly stating a hook needs to return anything, however, I cannot find an example of a hook not returning something. Can someone advise on if this approach is correct?

A: To clean up your component, you can move useEffect to a custom hook that contains the same logic as the original.
For example
// useCodeSelection.js
...
export const useCodeSelection = () => {
    useEffect(() => {
        console.log('useCodeSelection')
    }
}
...

Then inside your component just call it after you import it, like:
...
useCodeSelection()
...

A: The current issue as I can see here is that you have 3 functions namely isEmpty, setSnackbar, and dispatch tightly coupled to your components here. This restricts you from directly moving this useEffect to your custom hook. The best solution that I can think of right now is moving these functions to a custom hook(you can combine this with context API as well). After that, you can do the following in your custom hook
const useCustomAsyncHook = () => {
  // code to fetch dependenices like `data`, `isSuccess` goes here

  const { setSnackbar, isEmpty, dispatch } = useAnotherCustomHook();

  React.useEffect(() => {
    if (isSuccess && !isEmpty(data)) {
       setSnackbar({
         show: false,
         message: '',
       });
       dispatch({
         type: ACTION_TYPES.UPDATE_METADATA,
         payload: { data },
       });
     }
  }, [data, isSuccess, setSnackbar]);
};


text:
Q: SQLite - UNIQUE constraint failed: (OS error - 2:No such file or directory) I know that this question was already been asked and answered before, but i cannot find any solution for my issue.
I am having an SQLite DB i am trying to create on my Android app. I am parsing my values, everyhting seems ok, but when i try to insert values in the SQLite, i get an UNIQUE constraint failed: (OS error - 2:No such file or directory) error in the insertOrThrow line. Here is my code
public class SQLiteHandler extends SQLiteOpenHelper {

    private static final String TAG = SQLiteHandler.class.getSimpleName();

    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "user_DB";

    // Login table name
    private static final String TABLE_USER = "user";

    // Login Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";
    private static final String KEY_SURNAME = "surname";
    private static final String KEY_COUNTRY = "country";
    private static final String KEY_EMAIL = "email";
    private static final String KEY_PASSWORD = "password";
    private static final String KEY_TELEPHONE = "telephone";

    public SQLiteHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_USER + "(" + KEY_ID + " TEXT PRIMARY KEY,"
                + KEY_NAME + " TEXT," + KEY_SURNAME + " TEXT," + KEY_COUNTRY + " TEXT,"
                + KEY_EMAIL + " TEXT UNIQUE," + KEY_PASSWORD + " TEXT,"
                + KEY_TELEPHONE + " TEXT" + ")";
        db.execSQL(CREATE_LOGIN_TABLE);

        Log.d(TAG, "Database tables created");
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_USER);

        // Create tables again
        onCreate(db);
    }

    /**
     * Storing user details in database
     * */
    public void addUser(String id, String name, String surname, String country, String email, String password, String telephone) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_ID, id); // Id
        values.put(KEY_NAME, name); // Name
        values.put(KEY_SURNAME, surname); // Surname
        values.put(KEY_COUNTRY, country); // Country
        values.put(KEY_EMAIL, email); // Email
        values.put(KEY_PASSWORD, password); // Password
        values.put(KEY_TELEPHONE, telephone); // Telephone

        // Inserting Row
        long ide = db.insertOrThrow(TABLE_USER, null, values);
        db.close(); // Closing database connection

        Log.d(TAG, "New user inserted into sqlite: " + ide);
    }

    public String getData(String a){
        SQLiteDatabase db = this.getReadableDatabase();
        String s;
        Cursor c = db.rawQuery("SELECT * FROM " + TABLE_USER, null);
        c.moveToFirst();
        s=c.getString(c.getColumnIndex(a));
        db.close();

        return s;
    }

    /**
     * Re crate database Delete all tables and create them again
     * */
    public void deleteUsers() {
        SQLiteDatabase db = this.getWritableDatabase();
        // Delete All Rows
        db.delete(TABLE_USER, null, null);
        db.close();

        Log.d(TAG, "Deleted all user info from sqlite");
    }

}

The id is AUTOINCREMENT in the MySQL db i use in a server where i get the values. I just want to insert them in a SQLite db in the app. Although i get an exception

android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: user.id (Sqlite code 1555), (OS error - 2:No such file or directory)

What does the No such file or directory means?


text:
Q: NUXTJS Issue in IE11/Edge When Utilizing 3rd Party Library with Spread Operator I have a NUXTJS (v2.9.2) web application that is having rendering issues when running in IE11 and Edge.  The application works in Chrome, Safari, and FireFox.  I have tracked it down to a spread operator in a referenced 3rd party npm package (vue-mapbox).
I have read a few posts referencing this same issue and it appears in most cases the fix is to include the referenced 3rd party library in the build > transpile option in the nuxt.config.js file.
  build: {
    transpile: [
      ({ isLegacy }) => isLegacy && "vue-mapbox"
    ]
  }

This addition to the nuxt.config.js file allows the web application to load in IE11 and Edge, but now I get Javascript errors in all browsers and loss of functionality.
Listed below are the steps I took to get to this point:
ORIGINAL STATE without the transpile option in nuxt.config.js
IE11 & EDGE

*

*Console Error:

SCRIPT1003: Expected ':'

*

*JS File (withEvents.js)

export default {
  methods: {
    /**
     * Emit Vue event with additional data
     *
     * @param {string} name EventName
     * @param {Object} [data={}] Additional data
     */
    $_emitEvent(name, data = {}) {
      this.$emit(name, {
        map: this.map,
        component: this,
        ...data
      });
    },

CHANGED STATE with the transpile option in nuxt.config.js
NUXTJS

*

*Compile Warning

WARN  in ./node_modules/vue-mapbox/src/components/map/mixins/withAsyncActions.js

"export 'default' (imported as 'promisify') was not found in 'map-promisified'

All Browsers

*

*Console Error (es6.promise.js - ...data (spread operator causing issue))

Uncaught (in promise) TypeError: Object(...) is not a function
    at VueComponent.$_registerAsyncActions (vendors.app.js:79061)
    at vendors.app.js:25088

error TypeError: Cannot read property 'querySourceFeatures' of null
    at VueComponent.createMapMarkers (:8080/_nuxt/pages/index.js:1418)
    at VueComponent.onIdle (:8080/_nuxt/pages/index.js:1365)
    at invokeWithErrorHandling (commons.app.js:14784)
    at VueComponent.invoker (commons.app.js:15109)
    at invokeWithErrorHandling (commons.app.js:14784)
    at VueComponent.Vue.$emit (commons.app.js:16807)
    at VueComponent.$_emitEvent (vendors.app.js:79571)
    at VueComponent.$_emitMapEvent (vendors.app.js:79584)
    at r.St.fire (vendors.app.js:53018)
    at r._render (vendors.app.js:53022)

After adding the transpile option for the one 3rd party library in the nuxt.config.js it appears that it breaks all functionality due to incompatibilities between different versions of javascript between the application and the library.

A: We were able to solve this issue by making the following additions/changes in our solution.

*

*Changed our vue-mapbox import to directly reference the umd js file in the dist folder of vue-mapbox package

import { MglMap, MglGeolocateControl, MglNavigationControl } from "vue-mapbox/dist/vue-mapbox.umd.js";

*Added a script reference to polyfill.io (specifying the features needed) to the Nuxt.config.js

const ployfillFeatures = [
  "fetch",
  "Object.entries",
  "Element.prototype.classList",
  "IntersectionObserver"
].join("%2C");

module.exports = {
  mode: "universal",
    script: [
      { src: `https://polyfill.io/v3/polyfill.min.js?features=${ployfillFeatures}`, body: true }


text:
Q: load result of async await into variable I am trying to obtain the result of this 'response' into a variable that I can manipulate later. This is what I have so far
const url = my-url
const axios = require('axios').default;

async function getUser() {
    try {
      const response = await axios.get(url);
      //console.log(response); // this is what I need
      return response.data
    } catch (error) {
      console.error(error);
    }
  }

let results = await getUser();
console.log(results) // take results and do something with it

I do not understand why I cannot access the results.

A: This is called a top-level await and not all runtimes support it
...I assumed you are not inside a function because i saw the require statement const axios = require('axios').default; on the top


text:
Q: extract substring from string given in list I have two tibbles, one with some series codes of uneven length, and one with country codes
codes <- as.tibble(c("brcomec", "frcomopf", "decombwf", "ezcomop",
       "jpcomop", "aewheob", "ezcompis", "decomipf"))
countries <- as.tibble(c("br", "fr", "advecos", "af", "africa", "al", "dz", "as", "ad",
                     "ao", "ai", "aq", "ag"))

How do I extract the countries from "code" given the information in countries, i.e. I wish to have something like
dta <- data.frame(
~country , ~ rest ,
br       , comec  ,
fr       , comopf ,
...
)

I tried with filter(str_detect(code, paste(countries))) but this did not work out, so any help is kindly appreciated.

A: Do you want something like this?
library(tidyverse)
codes1 <- substr(codes$value, start = 1, stop = 2)
codes2 <- substr(codes$value, start = 3, stop = 10)

codes3 = tibble(codes1, codes2)
codes3

Which returns this?
# A tibble: 8 x 2
  codes1 codes2
  <chr>  <chr>
1 br     comec
2 fr     comopf
3 de     combwf
4 ez     comop
5 jp     comop
6 ae     wheob
7 ez     compis
8 de     comipf


text:
Q: Journaling calls to a function taking inline code as argument / macro param in horizontal mode issue In the code below \Foo evaluates inline code. \Baz is a 'journal-ed' version, meaning it writes calls to \Foo to a file. Reading the file fails (Hook 2) due to a "'macro parameter character #' in horizontal mode." issue. With the transformation ##1->#1 (Hook 3) the file can be read and produces the desired output. Is there a way to solve this problem within LaTeX?
PS: How to use xparse's 's' parameter? (Hook 1)
    \documentclass{l3doc}
    \usepackage{xparse}
    \ExplSyntaxOn

    \iow_new:N \__erw_write_stream
    \AtEndDocument{\iow_close:N \__erw_write_stream}
    \iow_open:Nn \__erw_write_stream{erwlog}
    \cs_new_protected:Nn \__erw_write:n
    {
      \iow_now:Nn \__erw_write_stream{#1}
    }

    \NewDocumentCommand{\Foo}
    {m}
    {
      \cs_gset_protected:Nn \__erw_foo:n {#1}
      \__erw_foo:n{World}
    }
    \NewDocumentCommand{\Baz} % (journaled version of \Foo)
    {
      % s m % Hook 1.a
      o m
    }
    {
      \Foo{#2}

      \IfValueT{#1}
      {
        (*)
    %    \__erw_write:n{\Foo{#2}} % Hook 2.a
        \__erw_write:n{\Baz{#2}} % Hook 2.b
      }

    }
    \NewDocumentCommand{\Qux} % recover calls to \Foo
    {}
    {
      \file_input:n{erwlog}
    }

    \NewDocumentCommand\Test
    {}
    {
    %  \Baz*{Hello,~##1!}                   % Hook 1.b % Always (*)
      \Baz[]{Hello,~##1!}                   % OK if Hook 2.c commented out

      \iow_close:N \__erw_write_stream

    %  \Qux                                 % Hook 2.c
    %ERROR: You can't use `macro parameter character #' in horizontal mode.
    %
    %--- TeX said ---
    %
    %\__erw_foo:n #1->Hello, ##
    %                          1!
    %l.1 \Baz {Hello, ##1!}
    %
    %--- HELP ---
    %The special character # has appeared in ordinary text. You probably
    %meant to type \#.

    % erwlogbis:                         % Hook 3.a
    % \Baz {Hello, #1!}
      \file_input:n{erwlogbis}

    }

    \ExplSyntaxOff

    \begin{document}

    \Test

    \end{document}

A: \write doubles parameter tokens (# with category code 6) when writing to a file (cf. TeXbook p. 228). I don't know if there is a way to avoid this doubling, but you can cope with it by simply wrapping the interesting things in a temporary macro definition. When the macro is expanded, the catcode 6-## in its replacement text will become single #, thus the technique will do what you intended. In other words, in your example, the journal contains:
\begingroup \def \tmp {\Baz {Hello, ##1!}}\expandafter \endgroup \tmp

The \begingroup ... \endgroup pair is only here to avoid polluting with our \tmp macro. Given a private enough name, you could dispense with it. But the interesting code is executed after \endgroup, so the grouping used for the definition of \tmp shouldn't affect your code in any way.
Your \__erw_write_stream variable should have an \l_ or \g_ prefix and an _iow suffix (see 1. Naming functions and variables in interface3.pdf). I renamed it to \g__erw_journal_iow.
Regarding your question:

How to use xparse's s parameter?

I enabled the star form of \Baz. You need \IfBooleanTF (or \IfBooleanT, etc.) to test the presence of the star argument, not \IfValueTF which is for optional arguments such as those declared with the o argument type.
Please note: your questions would be much easier to understand if you directly used the macros we all know (here: \cs_gset_protected:Nn, \iow_now:Nn, \file_input:n) instead of obscurely-named custom wrappers. This would make your code much shorter and clearer for all of us. You can of course use the wrappers you want in your own code, but please skip them in the questions you ask here. A good MWE is short and to the point. Also, better use the article class unless the question is class-specific. Here, l3doc is not really relevant: all this works exactly the same with the article class.
Here is the full example with my changes:
\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn
\iow_new:N \g__erw_journal_iow

\AtEndDocument { \iow_close:N \g__erw_journal_iow }

\iow_open:Nn \g__erw_journal_iow { erwlog }

\cs_new_protected:Nn \__erw_write:n
  {
    \iow_now:Nn \g__erw_journal_iow {#1}
  }

\NewDocumentCommand \Foo { m }
  {
    \cs_gset_protected:Nn \__erw_foo:n {#1}
    \__erw_foo:n { World }
  }

% Journaled version of \Foo
\NewDocumentCommand \Baz { s m }
  {
    \Foo{#2}
    \IfBooleanT {#1}
      {
        (*)
        \__erw_write:n
          { \begingroup \def \tmp { \Baz {#2} } \expandafter \endgroup \tmp }
      }
  }

% Read (execute) the journal
\NewDocumentCommand \Qux { }
  {
    \file_input:n { erwlog }
  }

\NewDocumentCommand \Test { }
  {
    % Define \__erw_foo:n, execute it and write to the journal
    \Baz* { Hello,~##1! }
    \iow_close:N \g__erw_journal_iow
    \Qux                                 % execute the journal
  }
\ExplSyntaxOff

\begin{document}

\Test

\end{document}

If you have difficult tokens to write to files, you might be interested in \iow_char:N. I tried it to avoid the # doubling here, but apparently, it doesn't. Just in case it helps you for further work, the code was:
\cs_new_protected:Nn \__erw_write_wrapper:n
  {
    \__erw_write:n { \Baz {#1} }
  }

\cs_generate_variant:Nn \__erw_write_wrapper:n { x }

...

\NewDocumentCommand \Baz { s m }
  {
    \Foo{#2}
    \IfBooleanT {#1}
      {
        (*)
        \tl_set:Nn \l_tmpa_tl {#2}
        \regex_replace_all:nnN { \cP\# } { \c{iow_char:N} \c{##} } \l_tmpa_tl
        \__erw_write_wrapper:x { \tl_use:N \l_tmpa_tl }
      }

  }

...

\NewDocumentCommand \Test { }
  {
    \Baz* { Hello,~##1! }
  }


text:
Q: Error while connecting exchange server from WCF Service I am using exchange listener inside wcf service.
Recently we moved the applications to new Server.
we have installed SSL certificate as well in IIS.
we are getting error in ExchangeService.AutodiscoverUrl(string emailAddress) method in new server.
in old server it is working fine.
In the event viewer we are able to see the below error.
An SSL 3.0 connection request was received from a remote client application, but none of the cipher suites supported by the client application are supported by the server. The TLS connection request has failed.

A: The TLS encryption protocol is not enabled on Windows Server. This may cause the connection failure of applications that connect via HTTPS protocol and TLS encryption.
You can determine which protocols are enabled by viewing the following registry keys:

To enable SSL3.0, please follow the steps below:
Using regedit to add the following keys:
1.Right click on protocols -> new -> key -> "SSL 3.0" then "TLS 1.0"
2.Under each of the keys above you need to create additional keys "Client" and "Server"
3.create DWORD (32bit) value called "Enabled" under each "Client" and "Server" key for "SSL 3.0 and TLS 1.0"
DWORD (32bit) Value
Value name = Enabled
Value date = 0
Value date can be set to "1" - Enabled or "0" – Disabled
4、restart your computer to implement the change


text:
Q: Parsing lines of text from external file in Ruby I am trying to parse a raw email. The desired result is a hash of the lines that contain specific headers.
This is the Ruby file:
raw_email = File.open("sample-email.txt", "r")
parsed_email = Hash.new('')

raw_email.each do |line|
  puts line
  header = line.chomp(":")
  puts header
  if header == "Delivered-To"
    parsed_email[:to] = line
  elsif header == "From"
    parsed_email[:from] = line
  elsif header == "Date"
    parsed_email[:date] = line
  elsif header == "Subject"
    parsed_email[:subject] = line
  end
end

puts parsed_email

And this is the raw email:
Delivered-To: user1@example.com
From: John Doe <user2@example.com>
Date: Tue, 12 Dec 2017 13:30:14 -0500
Subject: Testing the parser
To: user1@example.com
Content-Type: multipart/alternative;
boundary="123456789abcdefghijklmnopqrs"

--123456789abcdefghijklmnopqrs
Content-Type: text/plain; charset="UTF-8"

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec
odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla
quis sem at nibh elementum imperdiet. Duis sagittis ipsum.

--123456789abcdefghijklmnopqrs
Content-Type: text/html; charset="UTF-8"

Lorem ipsum dolor sit amet, consectetur adipiscing
elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam.
Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis
ipsum.

--089e082c24dc944a9f056028d791--

The puts statements are just for my own testing to see if data is being passed along.
What I am getting is each full line put twice and an empty hash put at the end.
I have also tried changing different bits to strings or arrays and I've also tried using line.split(":", 1) instead of line.chomp(":")
Can someone please explain why this isn't working?

A: Try this
raw_email = File.open("sample-email.txt", "r")
parsed_email = {}

raw_email.each do |line|
  case line.split(":")[0]
  when "Delivered-To"
    parsed_email[:to] = line
  when "From"
    parsed_email[:from] = line
  when "Date"
    parsed_email[:date] = line
  when "Subject"
    parsed_email[:subject] = line
  end
end

puts parsed_email
=> {:to=>"Delivered-To: user1@example.com\n", :from=>"From: John Doe <user2@example.com>\n", :date=>"Date: Tue, 12 Dec 2017 13:30:14 -0500\n", :subject=>"Subject: Testing the parser\n"}

Explanation
You need to split line on : and select first. Like this line.split(":")[0]


text:
Q: Import sql with 2 merged columns Hello I received an large sql to import into my database with 9k lines. The problem is the structure is not really the same.
The header of the table is:
Name,Bday,Email,Phone

and i received it like this
INSERT INTO `Persons` (`Firstname`, `Lastname`, `Bday`, `Email`, `Phone`) VALUES
('DRAGHICI', 'CLAUDIA', '1963-03-06', '', '0730010099'),
('CIMPEANU', 'ADRIAN GEORGE', '1975-03-06', '', '0747137312'),
('SIRBU', 'CRISTINA', '1985-05-17', '', '0726498751'),
('GHITA', 'DORU AURELIAN', '1962-04-20', '', '0722628325'),
('PALL', 'PETRISOR', '1980-06-24', '', '0745524485'),
('ZMARAND', 'MIHAELA', '1983-10-13', '', '23365646'),
('CHIRIAC', 'PETRE', '1948-04-26', '', '0745789651'),
('ZABAD', 'OMRAN MOHSEN', '1986-06-14', '', '0723368085'),
('TARA', 'SERGIU', '1974-12-01', '', '0722457299'),
('DRACULET', 'CLAUDIA OLIMPIA', '1978-01-22', '', '0745617755'),
('CINDEA', 'PETRISOR', '1970-01-17', '', '0351404534'),
('SAVESCU', 'ADRIANA MADALINA', '1980-09-12', 'madalina_savescu@yahoo.com', '0740699853'),
('POPA', 'SIMINA CLAUDIA', '1980-03-24', '', '0727 346126'),
('GHEORGHE', 'CONSTANTIN', '1986-02-04', '', '0760 244 833'),
('GEORGESCU', 'MARIETA', '1959-08-14', '', '0351422999'),
('SARBU', 'IULIAN', '1947-06-22', '', '0726565154'),
('CALAFETEANU', 'EMIL', '1954-03-20', '', '0745481772'),
('SURPATEANU', 'GEORGETA', '1952-01-26', '', '0743331284'),
('LIMBAN', 'DELIA MIHAELA', '1987-07-15', '', '222356'),
('MARCIU', 'ION', '1944-05-13', '', '0351407891'),

I need to merge firstname lastname into column name

A: Just do what @ganesh_devlekar suggested except make this change in last query:
insert into OriginalTable (Name,Bday,Email,Phone)
select CONCAT(FNamem,' ',LName),Bday,Email,Phone
from TempTable

A: Create Some Other Table
create table TempTable(FName varchar(100),
LName varchar(100),Bday datetime,Email varchar(30),Phone int)

then insert theses values
insert into TempTable(FNamem,LName,Bday,Email,Phone)
-- 9 k rows

then do something like this:
insert into OriginalTable (Name,Bday,Email,Phone)
select FNamem,LName,Bday,Email,Phone
from TempTable


text:
Q: Where does the money gained after trainer battles come from? In the mainline Pokemon games, generally speaking, after a trainer battle, you get some money if you win.
Is there any in-universe explanation of:

*

*Where this money is coming from (the other trainer? somewhere else?);

*How the amount of money won is determined?

I wondered about this after defeating a preschooler in a trainer battle in Pokemon Moon, and winning some money.  Did I just win his lunch money from him?

A: In the first 3 generations the amount of money lost is simply half of the money the player has. In Pokémon FRLG and all games from Generation IV onwards, the money lost is calculated depending on your team level and the badges earned, as you can see here.
For other trainers there's a similar behaviour which depends on the trainer's team level and a base payout depending on the trainer class. More info on Bulbapedia.
It's reasonable to think that you win a part of other trainers' money.


text:
Q: How to get the value of a column in the row with the first occurrence of another value in a particular column in MySQL? I have a SQL table with the following columns:
|    Date    |    Pass/Fail    |
--------------------------------
| yyyy-mm-dd |      PASS       |

| yyyy-mm-dd |      FAIL       |

How do I obtain the value in the "Date" column of the row with the first occurrence (ordered by date) of "PASS" in the "Pass/Fail" column?

A: You can use order by with limit 1
select * from tablename
where PassFailCol='Pass'
order by date
limit 1

A: If you wanted to also capture more than one passing record should two or more records be tied as being first, then we can try using a subquery:
SELECT Date, PassFail
FROM yourTable
WHERE
    PassFail = 'Pass' AND
    Date = (SELECT MIN(Date) FROM yourTable WHERE PassFail = 'Pass');


text:
Q: How does one properly test within the sandbox for apple in-app purchases? I have a brand new app, has not been published yet. I added an in-app purchase to the code, went through the process of adding the product to the app in "app store connect", and added a sandbox user there as well.
To test, I plug in my phone to the mac, and from xcode (13.3.1) I run the app on my phone. The app runs, and I see the product show up in the app. When I hit the button to "buy", I immediately get a dialog to enter credentials. I enter the sandbox credentials, then get another alert saying "Apple ID verification, open settings to continue signing in with.."
I do that, then it pops up a 2-factor dialog saying a code has been sent, but the dialog just goes away after the code is sent via sms to that same device. There's no place to enter that code, as if it knew "oh, the code is being sent to the device that wants it". After a couple of seconds, I end up in Settings->App store, and I don't see anything useful there.
I then go back to the app, and w/o doing anything in the app I immediately get messages in the debug console:
Payment Queue Error: Optional(Error Domain=SKErrorDomain Code=0 "An unknown error occurred" UserInfo={NSLocalizedDescription=An unknown error occurred, NSUnderlyingError=0x28160ee80 {Error Domain=ASDErrorDomain Code=500 "Unhandled exception" UserInfo={NSUnderlyingError=0x2816dc150 {Error Domain=AMSErrorDomain Code=100 "Authentication Failed" UserInfo={NSMultipleUnderlyingErrorsKey=(
    "Error Domain=AMSErrorDomain Code=2 \"An unknown error occurred. Please try again.\" UserInfo={NSLocalizedDescription=An unknown error occurred. Please try again.}",
    "Error Domain=AMSServerErrorDomain Code=-5000 \"(null)\" UserInfo={failureType=-5000, m-allowed=false, pings=(\n), cancel-purchase-batch=true, customerMessage=The Apple\U00a0ID you entered couldn\U2019t be found or your password was incorrect. Please try again.}"
), NSLocalizedDescription=Authentication Failed, NSLocalizedFailureReason=The authentication failed.}}, NSLocalizedFailureReason=An unknown error occurred, NSLocalizedDescription=Unhandled exception}}})

I know the account credentials are correct (tried several times and verified them). It's almost as if I'm not really hitting the "sandbox" user db, more like production. But everything I read says I should be in development mode when I run things like this (based on What is a "development-signed version" of an iOS app? How do I run a development-signed version of my app?)
Is there some more precise way of determining whether or not I'm in development mode? Maybe some setting got tweaked or something.

A: Sorry, my bad. I had created the test account in the "regular user" section, not the "sandbox user" section up at "App store connect" (that's why I was getting the auth errors).
Things work fine with a real sandbox tester account.


text:
Q: Tkinter: Place buttons in dynamically creating frames everybody! I'm just learning python GUI and I can't figure out what am I doing wrong.
I'm trying to draw a tree of buttons. I've created a first button in a frame then when I click it, I expect two more frames to be placed in a parent frame and two more buttons place in these new frames and so on. But when I'm clicking the button on a second iteration it adds new frames not to the button's frame but in the LAST FRAME that was created.
from Tkinter import *
class my_class():

def __init__(self,frame):
    self.frame=frame
def create_frames(self):
    Frames=[]
    p=2
    for k in range(p):

        New_frame=Frame(self.frame, highlightbackground="green", highlightcolor="green", highlightthickness=1,
                          width=100, height=100, bd=0)

        New_frame.pack(side=LEFT)
        Frames.append(New_frame)
        obj=my_class(Frames[k])
        but=Button(obj.frame, text='but', command=lambda:obj.create_frames())
        but.pack()

my_app=Tk()
obj=my_class(my_app)
but=Button(my_app,text='butt',command=lambda:obj.create_frames())
but.pack()
my_app.mainloop()

1-iteration
2-iteration (I pressed the first button)


text:
Q: Cannot boot my BeagleBoard into Angstrom I have an original BeagleBoard Rev C5 (NOT xM).
I followed this tutorial to boot it into linux, but I am stuck and need help solving this issue.
Currently I have two problems:
**First: **
When starting the board (connected to serial console) I get this:
Texas Instruments X-Loader 1.5.0 (Jun 14 2011 - 22:04:07)
Beagle Rev C5
Reading boot sector
Loading u-boot.bin from mmc

U-Boot 2011.03-rc1-00000-g9a3cc57-dirty (Apr 01 2011 - 17:41:42)

OMAP3530-GP ES3.1, CPU-OPP2, L3-165MHz, Max CPU Clock 720 mHz
OMAP3 Beagle board + LPDDR/NAND
I2C:   ready
DRAM:  256 MiB
NAND:  512 MiB
MMC:   OMAP SD/MMC: 0
In:    serial
Out:   serial
Err:   serial
Beagle Rev C4
timed out in wait_for_pin: I2C_STAT=0
No EEPROM on expansion board
Die ID #415a000400000000040398da01025012
Hit any key to stop autoboot:  0
The user button is currently NOT pressed.
SD/MMC found on device 0
usage: fatload <interface> <dev[:part]> <addr> <filename> [bytes]
Loading file "/boot/uImage" from mmc device 0:2 (xxa2)
3203076 bytes read
Booting from mmc ...
## Booting kernel from Legacy Image at 80200000 ...
   Image Name:   Angstrom/2.6.32/beagleboard
   Image Type:   ARM Linux Kernel Image (uncompressed)
   Data Size:    3203012 Bytes = 3.1 MiB
   Load Address: 80008000
   Entry Point:  80008000
   Verifying Checksum ... OK
   Loading Kernel Image ... OK
OK

Starting kernel ...

Uncompressing    Linux..........................................................................................................

After that the above message restarts again over and over in an infinite loop.
Second:
When I connect the display through DVI interface, this message appears - also in a loop-
Texas Instruments X-Loader 1.5.0 (Jun 14 2011 - 22:04:07)
Beagle Rev C5
Reading boot sector
Loading u-boot.bin from mmc

U-Boot 2011.03-rc1-00000-g9a3cc57-dirty (Apr 01 2011 - 17:41:42)

OMAP3530-GP ES3.1, CPU-OPP2, L3-165MHz, Max CPU Clock 720 mHz
OMAP3 Beagle board + LPDDR/NAND
I2C:
Texas Instruments X-Loader 1.5.0 (Jun 14 2011 - 22:04:07)
Beagle Rev C5

Any help, please!!

A: Ok, I found the problem.
The answer was in the power supply, you should use a power supply that provides at least (5V-1A)...
USB OTG cable doesn't supply that much so board keeps rebooting


text:
Q: finding the last weekday of the month using later.js I am using later.js and trying to get the last working day of the month.
ref: http://bunkat.github.io/later/
var r = later.parse.recur().last().dayOfMonth().onWeekday();

It eats up the last day of the month which are weekends.
Example: Ex. May 2014 - last day is 31st and it falls on a saturday. What we need is to get 30th the Friday which is a weekday.
I got this reply from the developer
"You'll need a composite schedule that matches 'last day of the month if it is a weekday, or if it is a weekend use the last Friday of the month'. Check out http://bunkat.github.io/later/time-periods.html#day-of-week-count for information on the day of week count time period which is what you will need to use to find the last Friday of the month."
I could not understand yet.


text:
Q: Is the sequence of composite numbers aperiodic?
Let $a_1,a_2,\ldots$ be the composite numbers in strictly increasing order and consider the sequence $x_i \equiv a_i \pmod{2}$ where $x_i \in \{0,1\}$. Is the sequence $\{x_i\}$ aperiodic?  That is, does there not exist $T$ and $n_0$ such that for all $n \geq n_0$, $x_{n+T} = x_n$?

The sequence starts out as
$$0,0,0,1,0,0,0,1,0,0,0,1,0,0,1,0,1,0,0,0,\\1,0,1,0,0,1,0,0,0,1,0,0,1,0,1,0,0,1,0,1,\\0,0,0,1,0,1,0,0,1,0,0,0,1,0,1,0,0,1,0,0,\\1,0,1,0,0,1,0,1,0,1,0,0,1,0$$
and I couldn't find any points where it could be periodic. How could we show, if it is, aperiodic?

A: It is aperiodic. First notice that there exist arbitrarily long sequences of consecutive composite positive integers: $n!+2,n!+3,\dots,n!+n$ are all composite. Therefore, if the sequence $(x_n)$, after some point, keeps repeating a cycle, then it must be that the cycle is alternating $1$'s and $0$'s. But the sequence can't be alternating $1$'s and $0$'s after some point since there are arbitrarily large (odd) primes.

A: Recall that we can find consecutive strings of composite numbers of arbitrary length.  It's easy to see that, in fact, we can find such strings wherein the least element is larger than any preset level.  Now, suppose we have produced $n_0,T$ as desired.  Find a consecutive string of composites of length greater than $T$ far enough out so as to be in the periodic range.  That is to say, we have produced a consecutive string $x_i,x_{i+1},\cdots, x_{i+T}$ where $i>n_0$.  Of course these alternate $\pmod 2$.  But every larger $j$ is congruent $\pmod T$ to exactly one of those subscripts $i+k$ for suitable $k\in [0,T-1]$.  It would follow that the composites alternate in parity beyond a certain point.  But this is absurd.


text:
Q: How to find datatype of all the fields in Mongo I have a doc
{_id:NumberLong(1),gender:"M",vip:false}.

How to extract the type of individual field in Mongo with a query..
How to use typeof operator:
https://docs.mongodb.org/manual/core/shell-types/

A: Question title asks for all fields and answers tell how to make it with one field. Here's an all document fields approach (just change your_collection part at the beginning):
[db.your_collection.findOne()].forEach( function(my_doc) { for (var key in my_doc) { print(key + ': ' + typeof my_doc[key]) } } )

First you get an document from the collection, then convert it to an array with [] so we can apply a function with forEach, and finally in the function we iterate over the document fields to print their key and type as we want. This should output something like:
_id: object
gender: string
vip: boolean

A: > db.test.findOne()
{ "_id" : NumberLong(1), "gender" : "M", "vip" : false }
> db.test.findOne().gender
M
> typeof db.test.findOne().gender
string

A: You can for example query the type of gender field:
typeof db.getCollection('your_collection').findOne({"_id": NumberLong(1)}).gender


text:
Q: Idiomatic way to change data before serialization In a project I'm currently working on, suppose I have a model called Company and an attribute of that is name. Now imagine that this model has a one-to-many relationship with a model called User. That is, Company has_many Users. The User model has a foreign key 'company_id' to keep track of what it belongs to.
Now imagine that I want to send this User record over to the front-end (Ember + Ember-data) for some reason, and I would want to convert the company_id to the company name. Is there an idiomatic way for doing this other than
render json: {Company.find(user.company_id), ...}

that wouldn't require typing out all the attributes?
Many thanks in advance,
Alex.

A: Use gem 'active_model_serializers'
https://github.com/rails-api/active_model_serializers
Its good.


text:
Q: SSRS not loaded dll from .NET framework 4.5 I've created .dll in .NET Framework 4.5 and put it into SQL Server - Reporting Services - Report Server - Bin folder, and when deploy report from developer machine, i got this error:
Error while loading code module: '{namespace}, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
Details: Could not load file or assembly '{namespace}, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies.
This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.

Can someone explainme what is wrong and how to fix it?

A:
This assembly is built by a runtime newer than the currently loaded
  runtime and cannot be loaded.

It seems like your assembly is built using newer version of .NET Framework (4.5) which is not installed on the machine where you are deploying your solution.
Either install the .NET Framework version 4.5 or build your assembly using a version which is installed on the server.


text:
Q: too many values to unpack (expected 2) - Django SQL exception I am writing basic sign up view code with the Django framework.
I have the following code:
def register(request):

    if request.method == 'POST':

        username = request.POST.get("username")
        password = request.POST.get("password")
        email = request.POST.get("email")
        firstname = request.POST.get("firstname")
        lastname = request.POST.get("lastname")

        userObj = User.objects.filter(username)
        if userObj.exists():
            return HttpResponse("username already exists")
        emailObj = User.objects.filter(email)
        if emailObj.exists():
            return HttpResponse("email already exists")
        newUser = User.objects.create_user(username, email, password, first_name=firstname, last_name=lastname)
        if newUser is not Null:
            newUser.save()
            # render main menu page
            return HttpResponse("user successfully registered")
        else:
            return HttpResponse("error creating newUser")

The failure is because of the lines  userObj = User.objects.filter(username) and  emailObj = User.objects.filter(email)
Here is part of the trace:
Traceback (most recent call last):
  File "G:\Program Files\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "G:\Program Files\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "G:\Program Files\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "G:\Programming\project3\orders\views.py", line 21, in register
    userObj = User.objects.filter(username)
  File "G:\Program Files\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "G:\Program Files\lib\site-packages\django\db\models\query.py", line 904, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "G:\Program Files\lib\site-packages\django\db\models\query.py", line 923, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "G:\Program Files\lib\site-packages\django\db\models\sql\query.py", line 1350, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "G:\Program Files\lib\site-packages\django\db\models\sql\query.py", line 1377, in _add_q
    child_clause, needed_inner = self.build_filter(
  File "G:\Program Files\lib\site-packages\django\db\models\sql\query.py", line 1247, in build_filter
    arg, value = filter_expr

Exception Type: ValueError at /register
Exception Value: too many values to unpack (expected 2)

What can be done to avoid this, because I am doing only the basic Django sign up as required by documentation itself.. ?

A: User.objects.filter(username) makes no sense, you have to use something like User.objects.filter(username=username)


text:
Q: Finding neighbors to Points in an ArrayList I've recently started learning Java and though doing a "Conway's Game of Life" style program would be a good thing to start out with. Everything works fine but I'm having some serious performance issues with this part:
static List<Point> coordList = new ArrayList<Point>();

public int neighbors(int x, int y){

    int n = 0;

    Point[] tempArray = { new Point(x-1, y-1), new Point(x, y-1), new Point(x+1, y-1),
                          new Point(x-1, y  ),                    new Point(x+1, y  ),
                          new Point(x-1, y+1), new Point(x, y+1), new Point(x+1, y+1)};
    for (Point p : tempArray) {
        if (coordList.contains(p))
            n++;
        }

    return n;
}

The method is used when iterating the ArrayList coordList filled with Points and checking every element how many neighbors they have. When the list size gets to about 10000 Points every cycle takes about 1 seconds and for 20000 Points it takes 7 seconds.
My question is, what would be a more effective way to do this? I know there are several other programs of this kind with source code available too look at, but I wan't do do as much as I can by my self since the point of the project is me learning Java. Also, I don't want to use a regular array because of the limitations.

A: If your points are unique, you could store them in a HashSet instead of an ArrayList. The contains method will then become an O(1) operation vs. O(n) in your current setup. That should speed up that section significantly.
Apart from the declaration, your code should remain mostly unchanged as both implement the Collection interface, unless you call List-specific method such as get(i) for example.

A: Performance-wise, I think your best bet is to have a plain numeric (effectively Boolean) array representing the grid. Since this is a learning exercise, I'd start with a simple one-element-per-cell array, and then perhaps progress to packing eight adjacent cells into a single byte.
It is not entirely clear what you mean by "the limitations".
The following has some interesting pointers: Optimizing Conway's 'Game of Life'

A: Your current code scales in a quadratic manner O(n^2). You have only given part of the program. If you look at your whole program there will be a loop that calls neighbors() and you will see that neighbors() is called n times. Also the operation contains() is linear in n, so the time is proportional to their product n*n.
Quadratic scaling is a common problem but can often be reduced to linear by using indexed data structures such as HashSet.


text:
Q: How to fix .htaccess issue in Laravel 5.8 I am trying to change .htaccess file.But changes are not reflecting. Laravel home page works properly even if .htaccess file contains errors.
I have gone through the checking of mod_rewrite enable and apache2.conf files.Everything is perfect but unable to find the issue.
gfdghfguf;l;..
hfjffgfgh
lghkjgkjg
jfghkfhjfgh ghggggggggggggb

        Options -MultiViews -Indexes

RewriteEngine On
gb gjf  jfhgj jfhg jhfjf g

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

It have to give 500 internal server error but it works fine.


text:
Q: Use jQuery to playback video when mouse moves on x axis I'm using this little bit of jQuery to scrub back & forth through a video when the cursor moves on the x axis.
var mouseX;

$(document).mousemove( function moveFunc(e) {
mouseX = e.clientX;
var timV = $("#deko_vid").get(0).duration;
var valV = (timV*mouseX/$(document).width());
$("#deko_vid").get(0).currentTime = valV;

});

Codepen Example
But I've run into a few issues:
-Works as expected in Safari, but lags considerably in Chrome (haven't tested IE/Edge).
I looked for questions that were similar to mine, and found this, but I'm unsure about how best to move forward. Do I need to create a div that covers the document and bind .mousemove() to that? Find a different solution? Create a tween using greensock?
Any advice, ideas on how to move forward, constructive criticism is much appreciated!

A: There are a bunch of issues with mousemove in Chrome. The event shows a serious lag on certain html elements (document is one of them - because the event it's not firing constantly). So moving the event listener to another element can help. It is also helpful to disable the user selection of the element which captures the mousemove.
Finally in your case it seems to help to reduce the precision of the calculated time. The result is still not as smooth as in safari, but... well decide yourself: updated codepen demo here.
In Javascript it's just the modified selector and the rounding of the time.
var mouseX;
// using the video element instead of the complete document
$('video').mousemove( function moveFunc(e) {
    mouseX = e.clientX;
    var valV = (timV * mouseX/ $(document).width()),
        timV = $("#deko_vid").get(0).duration;
    // reducing the precision of calculation
    valV = Math.round(valV * 100) / 100;
    $("#deko_vid").get(0).currentTime = valV;
});

In CSS the syntax to avoid user selection.
video  {
  display: block;
   -moz-user-select: none;
   -webkit-user-select: none;
   user-select:none;
   ::selection: none;
}


text:
Q: Cannot copy databases in PHPMyAdmin I try to copy a database within PHPMyAdmin and I get the error - cannot copy database 'does not exist'.
If I then hit 'go' again, error message says 'cannot copy databse already exists'.
I have previously also tried 'creating database' and then trying to copy. The error message is as the second instance. Cannot copy, as db already exists.
This has only started happening recently (Mid July 2013). But means I cannot copy outwith 'export/import'.
Anyone with any ideas. I'm using PHPMyAdmin from within Cpanel on a shared webserver.


text:
Q: How to Make Up Comebacks when Somebody Calls You? I heard when I called somebody they answered "You" or "Yo" . .
Which one is correct? and what does it mean?

A: They most likely answered "Yo." I use this myself.
It's a concise and snappy way of saying "Hello, I'm paying attention to you." It is also used to attract someone's attention – as in "Yo, buddy!"
http://www.merriam-webster.com/dictionary/yo


text:
Q: For Loop Outputs Same "ev" Values After Every Iteration this is a long script, but I feel that presenting all the information is important in order to understand what is going on. The main issue occurs when I try to calculate "ev" which is the energy of an electron in eV and "cs" which is a cross sectioanl area function based on eV, given the velocity components inputs. I made this so that velocity components randomly change at every time step, however, no matter what velocity is accepted by the system, the "ev" and "cs" matrices stay the same values. I cannot figure out why because when I tested each function without a for-loop, they run correctly and generate different values.
"ev" function that is referenced in the main script:
function [ev] = evfun(vx,vy,vz)

m_e = 9.11E-31; %Mass of electron
jtoev = 6.24E+18; %Joules to eV conversion

ev = jtoev*(0.5*(m_e)*(vx.^2+vy.^2+vz.^2));
%ev = log(nonfitev);

end

"cs" function that is referenced in main script"
function cs = crosecarc(ev)

nonfitcs = 34*exp(-((ev-500)/350)^2); %In units of 1E-16 cm^2
cs = nonfitcs*(1E-4); %Converts to 10^-16 m^2

end

Main Script:
filename = 'evtestsheet'; %Specify file name to print to
evmatsheet = 1; %Specify sheet in Excel File
evmatxlRange = 'G3'; %Specify evmat matrix start cell in Excel File
inputvelsheet = 1; %Specify sheet in Excel File
inputvelxlRange = 'D3'; %Specify inputvel matrix start cell in Excel File
inputpossheet = 1; %Specify sheet in Excel File
inputposxlRange = 'A3'; %Specify inputpos matrix start cell in Excel File

%Defining Space and Particle Density based on Pressure PV = nkT
mTorr = 500; %Define pressure in mTorr (From metter reading)
P = (mTorr/1000)*133.322; %mTorr to Pascal conversion to define pressure
k = 1.38E-23; %Boltzman Constant
T = 290; %Temperature in Kelvin. Converted from C  and @ room temp
N = 1; %Total number of particles
ChamTotalV = 1;

%Particle sweep volume is defined later because it depends on electron energy
tstep = 0.05E-8; %Defining time step
%modstep = 2*tstep; %Used when calculating volume swept since the DOE solver splits itself up into 3 times within each time step
tfin = 1.1E-8; %Defining final time
intspan = [0:tstep:tfin]; %Total time span
intspancol = intspan(:); %For Excel plotting purposes
[introw,intcol] = size(intspan);

%This section is just for generating matrices that will be populated later
tindex = [0:1:intcol-2];
tindexcol = tindex(:); %Purely for Excel plotting purposes
[tinrow,tincol] = size(tindex);
PCPmat = zeros(tincol,1);
choicemat = zeros(tincol,1);
colnewv = zeros(intcol,3);
Vsweepmat = zeros(intcol,1);
vmagmat = zeros(intcol,1);
evmat = zeros(intcol,1);
crossareamat = zeros(intcol,1);
inputpos = zeros(intcol,3);
inputvel = zeros(intcol,3);

%Test Initial Conditions
spart = [0.1 0.1 0.];
vpart = [-1.0585E+7 -1.0585E+7 0.5585E+7];

%for p = 1:1:size(s0parts) %particle count
    for t = 0:1:intcol-2; %complete time interval and time step

        [trow,tcol] = size(t);
        %spart = s0parts(p:p,1:3);
        %vpart = v0parts(p:p,1:3);

        %Defining relative position and velocity
        x = spart(1);
        y = spart(2);
        z = spart(3);
        vx = vpart(1);
        vy = vpart(2);
        vz = vpart(3);

        inputvel(t+1,1:3) = [vx vy vz];
        inputpos(t+1,1:3) = [x y z];

        r = sqrt(x.^2 + y.^2 + z.^2);
        vmag = sqrt(vx.^2 + vy.^2 + vz.^2);

        ev = evfun(vx,vy,vz); %Plugs in velocity components of electron into the "evfun" function defined in seperate file to find energy in eV
        cs = crosecarc(ev); %Plugs in energy of electron into the "crosecarc" function defined in seperate file to find crossectional area
        crossarea = cs*4;
        Vsweep = crossarea*vmag*tstep; %Volume of space swept out by particle Vsweep = (area cross section)*(vmag)*(time step)
        %nden = N/ChamTotalV; %Number of particles per unit volume
        nden = 1/Vsweep; %Test line to force collision at every time step
        PCP = nden*Vsweep; %Probability of collision
        choice = rand(1); %Generate random number "choice" between 0 and 1

        %Populate the previously generated matrices with current values
        evmat(t+1,1) = ev;
        crossareamat(t+1,1) = crossarea;
        vmagmat(t+1,1) = vmag;
        Vsweepmat(t+1,1) = Vsweep;
        PCPmat(t+1,1) = PCP;
        choicemat(t+1,1) = choice;

        if choice <= PCP %If the choice by system is accepted within probability amplitude, then collision occurs
            %Assign new, velocity components based on energy prior to collision
            vxrand = 2*rand()-1; %Random # generation for component x between -1 and 1
            vyrand = 2*rand()-1; %Random # generation for component y between -1 and 1
            vzrand = 2*rand()-1; %Random # generation for component z between -1 and 1

            vmagrand = sqrt(vxrand.^2 + vyrand.^2 + vzrand.^2); %Normalize the randomly generated components
            vx = (vxrand/vmagrand)*vmag; %Multiply normalized, random x component by original velocity magnitude
            vy = (vyrand/vmagrand)*vmag; %Multiply normalized, random y component by original velocity magnitude
            vz = (vzrand/vmagrand)*vmag; %Multiply normalized, random z component by original velocity magnitude
        else
            newv = [0 0 0];
        end

        %Redfine the velocity and position components to reference on next if-loop run
        spart(1) = x;
        spart(2) = y;
        spart(3) = z;
        vpart(1) = vx;
        vpart(2) = vy;
        vpart(3) = vz;
        ev = [];
         %Clears ev matrix
    end

    xlswrite(filename,inputvel,inputvelsheet,inputvelxlRange)
xlswrite(filename,inputpos,inputpossheet,inputposxlRange)
    xlswrite(filename,evmat,evmatsheet,evmatxlRange)


text:
Q: Lightning: Edit recurring event series causes trigger to fire twice In trying to create a trigger for recurring events, I'm noticing the trigger firing twice.
I'm doing this on a new and clean developer org, so no existing workflows, processes, flows, or triggers.
Also, only happens with Lightning (not Classic).
I've also gone down the path of using a static variable for testing if it gets set in the same run.
Here is my code:
TestLightningEventTrigger
trigger TestLightningEventTrigger on Event (before insert, after insert, before update, after update) {
     if (Trigger.isUpdate) {
        if (Trigger.isAfter) {
            if (TestLightningEventTriggerHandler.firstRun) {
                System.debug('>>>' + TestLightningEventTriggerHandler.firstRun);
                TestLightningEventTriggerHandler.firstRun = false;
                System.debug('>>>' + TestLightningEventTriggerHandler.firstRun);
            }
        }
    }
}

TestLightningEventTriggerHandler
public class TestLightningEventTriggerHandler {
    public static Boolean firstRun = true;
}

Any thoughts on what might be happening?

A: I don't have documentation that outright says this, but clicking on "edit series" in the UI seems to have the following occur:

*

*First transaction with the single event you were on in the UI

*Second transaction where that single event + all the other events in the series are updated

You can see this by doing the following on the event trigger
trigger testing on Event (after update) {
    for(Event evt : trigger.new){
        System.debug(evt.Id);
    }
}

You'll see two logs created for every event series edit. One with just one record (the record you edited in the UI to bring up the edit series modal) and then the other log with all the events in the series (including the event from the first transaction). That 2nd transaction is handled out-of-the-box.
This might explain the following limitation (apex event trigger cannot handle batch operations on recurring events) since this could easily balloon if they allowed multiple event series in the same transaction.
Probably useful to point out another limitation also exists where there is no series Id for you to identify they all belong to the same series if you're looking to do some sort of exclusion logic to this behavior

Lightning Experience event series have no series ID, so it's not
possible to locate other occurrences in the series. In Salesforce
Classic recurring events, you can use RecurrenceActivityId to locate
other occurrences.


text:
Q: What's the correct way to rename a heroku app? Doesn't seem to be a way to do it from the command line, and when I do this from the site, I run into this issue when I try to git push heroku master:
 !  No such app as [previous app name].

Is this as simple as changing how I point to the app in git?

A: Did you try heroku apps:rename NEWNAME?

A: Why use all caps?
heroku apps:rename my_new_app_name

Here is a great place to find out more:
How to rename your Heroku application
In case anyone is curious this method does not require any further configuration, your modifications should be immediate. At the time of this writing I was able to change the name of my app in seconds, and then do so again if I wished. Hope this helps.

A: If you are changing the name of the app on the webpage
you should Updating Git remotes
git remote rm heroku
heroku git:remote -a newname
https://devcenter.heroku.com/articles/renaming-apps

A: Use this:
heroku apps:rename --app old_name new_name

A: Try this command:
heroku rename new_app_name

A: heroku rename new-name-app

always works for me but for additional information on rules, follow this page.

A: to rename app use:
heroku apps:rename --app <old_name> <new_name>

then, remove remote heroku:
git remote rm heroku

and add new one:
heroku git:remote -a <new_name>

and push changes:
git push heroku <branch_name>:main

A: heroku apps:rename new_name --app old-app-name
^ worked for me

A: If you want to rename your heroku app use:  heroku apps:rename new_name
Please replace "new_name" with the name you want to give your app. make sure you do not include any "https://" because this will give you an issue. simply replace new_name with your app name
e.g  heroku apps:rename grapefruitblog
After doing this, heroku requires that you  update git remotes for all other local checkouts of the app. you can do this by running this command: heroku git:remote -a new_name
Again, replace new_name with the name you previously put in
e.g heroku git:remote -a grapefruitblog


text:
Q: LinkedIn API Field Selectors I started reading and testing LinkedIn's API recently and i am having problems when using   field selectors
My goal is to use the API to fetch information about people, like its first-name,last-name,current-company and title for example.
By default,the people-search api returns only id,first-name and last-name.
I've read that,i can use some field-selectors to refine the result, but my question is, how do i use the field selectors with the parameters i want them to match aswell.
I've tried :
http://api.linkedin.com/v1/people-search?first-name=marcello&last-name=lins:(id,first-name,last-name,current-company,title)

But it does not work,throws me an exception saying that it is a Bad request.
Do i have to make two requests ?
1: https://api.linkedin.com/v1/people-search?first-name=marcello&lastname=lins
2: https://api.linkedin.com/v1/people-search?:(first-name,last-name,current-company,title)

Thanks in advance for the attention and feel free to edit my thread if it is not fitting any XDA-Pattern.

A:
This API is now only available for the Linkedin Partners

Per the documentation, the following pattern is used on the People Search API:
http://api.linkedin.com/v1/people-search:(people:(id,first-name,last-name,picture-url,headline),num-results)?first-name=Steve&last-name=Smith

All of the querystring parameters are optional (a full list is on the docs page), and the specified field selectors can be found on this page.
The reason that you need to specify that the field selectors are 'people' is that the People Search API can also return 'facets' which can be used in your search UI to give information about the results. In this case, we'll return the location facets which we could parse and turn into a set of checkboxes, similar to those found on the LinkedIn.com search page:
http://api.linkedin.com/v1/people-search:(facets:(code,buckets:(code,name)),people:(id,first-name,last-name,picture-url,headline),num-results)?first-name=Steve&last-name=Smith&facets=location

You can test all of these queries on the REST Console.


text:
Q: How to scale buildbot in a company I've been looking into buildbot lately, and the lack of good documentation and sample configurations makes it hard to understand how buildbot is commonly used.
According to the buildbot manual, each buildmaster is responsible for 1 code base. That means that a company that wants to use buildbot on, say, 10 projects, needs to maintain 10 different sets of buildbot installations (master-slaves configurations, open ports, websites with output etc.). Is this really the way things are done? Am I missing an option that creates a mash-up that is easy to maintain and monitor?
Thanks!

A: At my place of work we use Buildbot to test a single program over several architectures and versions of Python.  I use one build master to oversee about 16 slaves.  Each set of slaves pulls from a different repo and tests it against Python 2.X.
From my experience, it would be easy to configure a single build master to run a mash-up of projects.  This might not be a good idea because the waterfall page (where the build slaves report results) can get very congested with more than a few slaves.  If you are comfortable scrolling through a long waterfall page, then this will not be an issue.
EDIT:
The update command in master.cfg:
test_python26_linux.addStep(ShellCommand, name = "update pygr",
    command = ["/u/opierce/PygrBuildBot/update.sh","000-buildbot","ctb"], workdir=".")

000-buildbot and ctb are additional parameters to specify which branch and repo to pull from to get the information.  The script update.sh is something I wrote to avoid an unrelated git problem.  If you wanted to run different projects, you could write something like:
builder1.addStep(ShellCommand, name = "update project 1",
    command = ["git","pull","git://github.com/your_id/project1.git"], workdir=".")

 (the rest of builder1 steps)

builder2.addStep(ShellCommand, name = "update project 2",
    command = ["git","pull","git://github.com/your_id/project2.git"], workdir=".")

(the rest of builder2 steps)

The two projects don't have to be related.  Buildbot creates a directory for each builder and runs all the steps in that directory.

A: FYI, BuildBot 0.8.x supports several repositories on one master, simplifying things a bit.


text:
Q: How to make XML::RSS::Parser to get input from URL instead of a file I have this short Perl script that uses XML::RSS::Parser to pull some information out of an XML file.
#!/usr/bin/perl -w
use strict;

use XML::RSS::Parser;
use FileHandle;
use Data::Dumper;
use URI;

my $p = XML::RSS::Parser->new;
my $fh = FileHandle->new('ronicky-doone-by-max-brand.xml');

my $feed = $p->parse_file( $fh );
print $p->errstr;

my $feed_title = $feed->query('/channel/title');
print $feed_title->text_content;

my $feed_desc = $feed->query('/channel/description');
print $feed_desc->text_content;

I know there is a parse_uri method but I do not seem to be able to turn my URL, http://librivox.org/bookfeeds/ronicky-doone-by-max-brand.xml into a URI that I could pass a parameter to XML::RSS::Parser::parse_uri.

A: I don't know what you have tried, but it is very straightforward. perhaps the use of FileHandle confused you?
This version of your code works fine. Note that the -w command-line option was replaced many years ago by use warnings, except for short command-line Perl programs. Also I have had to set STDOUT to expect UTF-8 as there are some extended characters in this RSS feed.
use strict;
use warnings;

use XML::RSS::Parser;

binmode STDOUT, ':encoding(UTF-8)';

my $parser = XML::RSS::Parser->new;
my $feed = $parser->parse_uri('http://librivox.org/bookfeeds/ronicky-doone-by-max-brand.xml');

printf "Title: %s\n", $feed->query('/channel/title')->text_content;

printf "Description: %s\n", $feed->query('/channel/description')->text_content;

output
Title: Librivox: Ronicky Doone by Brand, Max
Description:  Frederick Schiller Faust (1892-1944), is best known today for his western fiction. Faust was born in Seattle, Washington and at an early age moved with his parents to the San Joaquin Valley in California where he worked as a ranchhand. After a failed attempt to enlist in the Great War in 1917 and with the help of Mark Twain's sister he met Robert Hobart Davis, editor of All-Story Weekly and became a regular contributor writting under his most used pseudonym "Max Brandâ€. He wrote in many genres during his career and produced more than 300 western novels and stories. His most famous characters were Destry and Dr. Kildare, both of which were produced in film. Faust was killed in Italy in 1944 as a front line war correspondent at the age of 51. He is buried in the Sicily-Rome American Cemetery in Nettuno, Italy.

Ronicky Doone (1926) is a hero of the west, respected by the law-abiding citizen and hated by bushwhacking bandits. Bill Gregg is a man in love, not about to be deflected from meeting his lady love for the first time, and willing to stand up to the living legend to reach her. This initial meeting leads to a friendship between the two and they travel east to New York City on the trail of the girl. When they find the girl, Caroline Smith, and she refuses to leave, Ronicky must discover the secret that holds her. They encounter the sinister John Mark and the beautiful Ruth Tolliver and are exposed to the horrors and vices of big city life as they attempt to rescue Caroline and find their way back to the mountain-desert of the west. (Summary by Rowdy Delaney)


text:
Q: Is there a formula to calculate $\sin(\theta^2)$ from $\sin\theta$? I'm aware of the existence of trig formulas such as double angle and half angle formulas. I was curious are there any for exponential angles.
What I mean is: If I were presented with the expression $\sin(\theta^2)$, and if I know $\sin(\theta)$, is there a formula that allows me to find it?


text:
Q: A domain satisfying the weak cone condition but not the strong cone condition In the 1977 paper "Cone Conditions and Properties of Sobolev Spaces" by Adams and Fournier, the authors say that an open set $\Omega\subset\mathbb{R}^n$ satisfies the cone condition if each $x\in\Omega$ is the vertex of a cone $C_x$ contained in $\Omega$ congruent to a fixed cone $C$.
They then go on to define the weak cone condition.
Let $x\in\Omega$. Let $R(x)$ consist of all points $y\in\Omega$ such that the line segment from $x$ to $y$ lies completey $\Omega$. Let $\Gamma(x)=\{y\in R(x) : |x-y|<1\}$. $\Omega$ satisfies the weak cone condition if there is a number $\delta>0$ such that $\mu_n(\Gamma(x))\geq \delta$. Here $\mu_n(\Gamma(x))$ denotes the Lebesgue measure of $\Gamma(x)$.
The authors note that there are many domains satisfying the weak cone condition, but not the "strong" cone condition. Does anyone know an example of such a domain? I've tried to construct one but have had no luck.
Here are a couple of my thoughts:

*

*Any domain $\Omega$ failing the cone condition must not contain a smallest cone. That is, there cannot be an $x\in\Omega$ such that for any other $y\in\Omega$, the cone $C_x$ may be rigidly transformed to have its vertex coincide with $y$, and $C_x\subset C_y$. If such an $x$ exists, then we can take our fixed reference cone to be $C_x$ and then $\Omega$ satisfies the cone condition.

*If $\Omega$ fails the cone condition, but satisfies the weak cone condition, then there should be a sequence $\Gamma(x_n)$ for which the diameter of the interior of $\Gamma(x_n)$ tends to 0 as $n\to\infty$. If the diameter of the interior of $\Gamma(x)$ was bounded below for all $x$, there there would be a smallest ball contained in $\Gamma(x)$ for all $x$, and thus a smallest cone.

A: A simplistic example, but you can build others like it, in 2 and higher dimensions.
The idea is to start with the domain above the graph of the absolute value function, then fix a countable dense of points on the unit circle and delete the (open) line segments passing through the origin and these points (Draw a picture!). Denseness ensures no cone will fit centered at 0, while the countable property (and polar coordinates) ensure that $R(0)$ has full measure.
The above set is not open, however we can fix that in the following way (noting that we won't affect the failure of the cone property): Call $A_k$ the portion of our "domain" that lives at distance $d$ from the origin, with $2^{-k-1}<d\leq 2^{-k}$ from the origin (so the portion of our domain in an annulus with inner radius $2^{-k-1}$ and outer radius $2^{-k}$). Let $(a_j)_{j\geq0}$ be our dense set of points from before and $(l_j)_j$ the corresponding line segment. From $A_k$ we'll add back in the portions of $(l_j)_{j\geq k}$ (so from the outermost annulus $A_0$ we add all of them; on $A_1$ we add all except $l_0$, on $A_2$ we add all except $l_0,l_1$, and so on).
The new set, call it $\Omega$ is the union of $A_k'$, where these last sets are the $A_k$ with the corresponding portions of line segments added. Since $A_k'$ is a half open, half closed annulus with a finite number of segments, the only possible issue (we're trying to fit a small ball around every point in $\Omega$) is at the boundary of these sets. Here however, the only problem is if we're on a line segment that is deleted from $A_{k+1}'$ but not from $A_k'$, but this lies in the complement of $\Omega$ so we're in good shape.
Hopefully the above paragraph is no too obfuscating; the basic idea is: In deleting the "dense" set of line segments, we broke the open property of our set. So instead we delete one line segment at a time (this operation does preserve openness) and  then we just arrange this so that as we tend to 0, we recover the dense set of directions (this is why we do things in $A_k$).
Added: I just noticed that if you keep the "upper" endpoints of your line segments in each $A_k'$ instead of the whole segments, it's easier to check that the weak cone condition is verified throughout the whole domain.
Another, less complicated (though also less satisfying somewhat), example is to take the absolute value function and scale it horizontally and translate it, so that as you move to $\infty$ in the horizontal direction, you get narrower and narrower corners. Added: This last example only works as one for which both properties fail.