text:
Q: How can I create two columns with pictures? I need some help. I need to put some pictures in a document with two columns and right now I'm using:
\begin{figure}
\centering
\includegraphics[width=1\linewidth]{1}
\caption{Réactions catalytiques réversibles }
\label{fig:1 Réactions catalytiques réversibles }
\end{figure}

But the problem is that all the pictures I put, they appear at the top of the page. It doesn't matter were I put it in the text, it always appears at the top.
Can someone can help me?
\documentclass[11pt,a4paper,titlepage,final]{article}
\usepackage[latin1]{inputenc}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{array}
\usepackage{makeidx}
\usepackage{multicol}
\usepackage{graphicx}
\usepackage[left=2.00cm, right=2.00cm, top=2.00cm, bottom=2.00cm]{geometry}
\author{Darlin Roy  \and Otaola Franco}
\title{Récupération d'énergie thermique « basses calories » (Stockage et transport d'énergie)}
\begin{document}
    \maketitle
    \begin{twocolumn}
        \sloppy

A: This works fine
\documentclass{article}

\usepackage{multicol}
\usepackage{lipsum}
\usepackage[margin=0.5in]{geometry}
\usepackage{tikz}

\begin{document}

\begin{twocolumn}
\lipsum[1-3]
\begin{figure}[h]
\begin{tikzpicture}
 \draw[domain=0:1] plot(\x,\x*\x);
 \end{tikzpicture}
 \end{figure}
 \lipsum[4-5]
 \begin{figure}[h]
\begin{tikzpicture}
 \draw[domain=0:1] plot(\x,\x*\x);
 \end{tikzpicture}
 \end{figure}
\lipsum[6-10]
\end{twocolumn}

\end{document}


text:
Q: NLTK- Python -Cannot import a new corpus I am new to nltk. I am trying to import a new NLTK- corpus. I have added it on path C:\nltk_data\corpora. Import is working for an existing copora like brown and gutenberg. But when I am importing a new corpus using the same command, it is throwing an error:

cannot import name 'newcorpus'.

Code:
import nltk
from nltk.corpus import newcorpus

Python version 3.5.2 32 bit
NLTK version 3.2.1 32 bit
Question
Does anyone know how to resolve this error?

redpajama_set_name: RedPajamaStackExchange


text:
Q: C++ new * char aren't empty I had one question.
I developing server in ASIO and packets are in pointed char.
When i create new char (ex. char * buffer = new char[128];) i must clean it manually to nulls.
By:
for(int i =0;i<128;i++)
{
buffer[i] = 0x00;
}

I doing something wrong, that char isn't clear ?

A: Allocated memory will not be clear, it will contain random stuff instead. That's how memory allocation works. You have to either run a for-loop or use memset to clear it manually.

A: You do not have to loop over an array of un-initialized values. You can dynamically instantiate array of zeros like this:
char * buffer = new char[128](); // all elements set to 0
                             ^^

A: You also can use calloc. It initializes each elem to 0 automaticaly.
e.g:
 char* buffer = (char *) calloc (128, sizeof (char))

First param is number of blocks to be allocated. Second is size of block.
This function returns void* so you have to convert its value to (char *)
If you use calloc (or malloc or any "pure c" allocation functions) you'd better use free function to deallocate memory instead of delete.

A: There are two types of ways of calling the new operator in C++ - default initialised and zero initialised.
To default initialise (which will leave the value undefined) call:
int * i = new int;

It is then undefined behavoir to read or use this value until its been set.
To zeroinitialise (which will set to 0) use:
int * i = new int();

This also works with arrays:
int * i = new int[4]; // ints are not initialised, you must write to them before reading them
int * i = new int[4](); // ints all zero initialised

There's some more info here


text:
Q: Encryption Key Management during a asynchronous call for a short-lived key Below is the scenario I need to manage. Any thoughts on best ways to manage the  encryption keys are highly appreciated.
Bob, the client needs to pull some confidential data from Alice, the data provider. Bob and Alice agree to use Elliptic Curve Delffie-Hellman key exchange agreement. So, whenever Bob requests some data from Alice, secret key exchange using ECDH happens first. Post that Alice will prepare the data, which takes few seconds to few minutes to complete. Once the data is ready, Alice encrypts the data using the symmetric key derived from ECDH key exchange and sends the notification to Bob to pull the data. Using a call back API Bob pulls the data from Alice and decrypts using the secret key. Post this secret key generated as part of ECDH is destroyed as the requirement is that key needs to be Ephemeral.
So the question I have is, what is the best and practical way to safe keep the secret key at Bob's end for few seconds to few minutes while he waits for the data to arrive after the initial data request and ECDH key exchange?  Important to note that Bob can either send such request for data from a mobile app or from a web browser on any supported device.
Using one of the Key Management Systems out there sounds like an option. But given that key is very short-lived as the requirement is to have a new key for every transaction and there could be 100s of such transaction every day, not sure if it is financially prudent and practical to rely on a KMS in this scenario.
Note that, for certain reasons, process of data request and fulfilment, and the encryption algorithm explained above are non negotiable.
Thoughts? Suggestions?

A: Since Bob needs access to the key in order to decrypt the data he should store it in such a way that does not undermine the storage of the data that the key protects. It means that the key could be either held in memory if the data must only live in memory when it is received. The key can be stored when the data it protects must also be stored.
Keep in mind that you can re-engineer this "problem" through an additional encryption layer which moves the problem from Bob to Alice. Alice generates a random key, encrypts the data with it and stores the ciphertext on a public location (API). Then the key exchange happens which results in a second key. The second key is used to encrypt the first key and send that to Bob. Now Bob can decrypt the data as soon as the encrypted first key is received.


text:
Q: Sum values by date range in multiple columns I need to sum value by date range in multiple columns. Every date range is one week of a month. It can be shorter than 7 days if it is the start of the month or the end of the month.
For example, I have dates for February:
my_user        my_date        my_value
A              01.02.2019     100
A              02.02.2019     150
B              01.02.2019     90
Z              28.02.2019     120

How can I have in date range format such as below?
my_user   01/02-03/02   04/02-10/02   11/02-17/02  18/02-24/02  25/02-28/02
A              250      0             0            0            0
B              90       0             0            0            0
Z              0        0             0            0            120

Any suggestions? Thanks!

A: You can do this:
select *
  from (
    select to_char(dt, 'iw') - to_char(trunc(dt, 'month'), 'iw') + 1 wk, usr, val from t)
  pivot (sum(val) for wk in (1, 2, 3, 4, 5, 6))

demo
USR          1          2          3          4          5          6
--- ---------- ---------- ---------- ---------- ---------- ----------
A          250
B                                            90
Z                                                      120

Header numbers are the weeks of month. Maximum may be 6 if month starts at the end of the week and is longer than 28 days.
Similiar way you can find first and last day of each week if needed, but you can't put them as headers, or at least not easily.

Edit:

it is possible to define certain date range with pivot, simple as two
  dates? For example, I need to sum values from 5 December 2018 to 4
  January 2019, 5 January 2019 to 4 February 2019, 5 March 2019 to 4
  April 2019

Yes. Everything depends on how we count first and next weeks. Here:
to_char(dt, 'iw') - to_char(trunc(dt, 'month'), 'iw') + 1

i am subtracting week in year for given date and week in year of first day in month for this date. You can simply replace this second value with your starting date, either by hardcoding it in your query or by sending parameter to query or finding minimum date at first in a subquery:
(to_char(dt, 'iw') - to_char(date '2019-03-05', 'iw')) + 1

or
(to_char(dt, 'iw') - to_char((select min(dt) from data), 'iw')) + 1

Edit 2:
There is one problem however. When user defined period contains two or more years. to_date(..., 'iw') works fine for one year, but for two we get values 51, 52, 01, 02... We have to deal with this somehow, for instance like here:
with t(dt1, dt2) as (select date '2018-12-16', date '2019-01-15' from dual)
select min(dt) mnd, max(dt) mxd, iw, row_number() over (order by min(dt)) rn
  from (select dt1 + level - 1 dt, to_char(dt1 + level - 1, 'iw') iw
          from t connect by level -1 <= dt2 - dt1)
  group by iw

which gives us:
MND         MXD         IW         RN
----------- ----------- -- ----------
2018-12-16  2018-12-16  50          1
2018-12-17  2018-12-23  51          2
2018-12-24  2018-12-30  52          3
2018-12-31  2019-01-06  01          4
2019-01-07  2019-01-13  02          5
2019-01-14  2019-01-15  03          6

In first line we have user defined date ranges. Then I did hierarchical query looping through all dates in range assigning week, then grouped by this week, found start and end dates for each week and assigned row number rn which can be further used by pivot.
You can now simply join your input data with this query, let's name it weeks:
from data join weeks on dt between mnd and mxd

and make pivot. But for longer periods you have to find how many weeks there can be and specify them in pivot clause in (1, 2, 3, 4...). You can also add aliases if you need:
pivot ... for rn in (1 week01, 2 week02... 12 week12)

There is no simply way to avoid listing them manually. If you need it please look for oracle dynamic pivot in SO, there where hundreds similiar questions already. ;-)


text:
Q: Seamless deployment in ASP.NET (IIS kills worker process before new worker process is ready) I am trying to deploy a .NET Web application to IIS (7.5) without any hassle for the users. I have made sure that Disable Overlapped Recycle is False but i still run into the same problem every time.
Every time I upload new binaries for the site, IIS kills the worker process before it has started a new one. So every time I upload new binaries users get this error message:

Server Error in '/' Application. Could
  not load file or assembly
  'MyApplicationWeb' or one of its
  dependencies. The process cannot
  access the file because it is being
  used by another process. (Exception
  from HRESULT: 0x80070020)

I have no idea how to do this seamless. As it is now I just upload the binary; but while the upload occurs (or local copy) it will give the above quoted behaviour. I also tried using a Web garden but with same result.
What I am not looking for:

*

*How to solve it with external load balancers (it's a functional solution but it is perfomance wise a bad solution for few servers and it won't work at all if there's only one server)

*How to create a hack-around with a refresh in a custom error page (as it has some obvious problems but more importantly wont work at all with web services/ajax).

I really think this should be doable given http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/24e3c22e-79a9-4f07-a407-dbd0e7f35432.mspx?mfr=true
Update:
In article above they say:

However, because the shutdown timeout
  value of a shutdown or startup is
  configurable, the worker process can
  be terminated while it is still
  serving requests if it does not finish
  servicing existing requests within the
  time limit.

I have no idea where to find this value nor what it's default. If its less then a few second it might explain my results.
ps. I am posting it on SO rather than on SF/Webmasters etc because I think this kind of knowledge will probably be minimal amongst people who aren't active in development, I hope this is all right.

A: I agree with Smirkin's response - updating a second folder and changing the IIS home directory to point to the other folder.  Another advantage to this is that you have an easy rollback path (just switch the IIS home directory back).
I've written a post with a script on how to do this using Powershell - hope it helps: http://davidduffett.net/post/4833657659/blue-green-deployment-to-iis-with-powershell
You should be able to use this script directly from your continuous integration system.

A: Whilst Smirkin's answer provides a nice seamless way for an Admin to deploy a site with little or no downtime, and should resolve your issue with missing assemblies/references, if you have breaking changes in your code-base (i.e. removing old pages, changes to forms, etc.), then using this method could still result in some "hassle" for any users who start a process before the switch and complete it after the switch (i.e., they request a page before you switch over, start filling it in, and then submit the page after you've switched over to the new directory).
I know you don't want me to say this, but without a load-balancer with Sticky-Sessions enabled, you won't be able to allow people to continue using the old version of the site until they've finished while handling new sessions on the new version - by changing the home directory of the application, IIS will perform a re-compile of the app and restart the processes. This way you can set the old server to continue serving its current connections, but tell the load-balance not to send any new connections to it.
There is however another step you can take to help mitigate the issues often seen around this:
Configure the MachineKey to be a constant value rather than AutoGenerate - this means that when the AppPool recycles it will use the same key, and so be able to decrypt session cookies, viewstate, etc.

A: My guess is that you have a virus scanner or some other kind of indexing process that it locking the file as soon as you copy it out there.

A: When deploying ASP.Net applications I create a new folder on the server and change the home directory of the website within IIS. This provides zero downtime deployment and a quick rollback position in case of unforeseen issues. On a future update I scrap the old version and repeat the process so that there is always a single rollback position.
Update - Shutdown time limit
Details configuring the shutdown time limit for workers is detailed at http://www.iis.net/ConfigReference/system.applicationHost/applicationPools/add/processModel. The default is 1 min 30 secs. Look for the shutdownTimeLimit section in the linked page.
Update - More information
Similar question with a great answer
The gist of this is that the due to overwritting the existing files the copying mechanism takes an exclusive lock on the files and that it is not possible to have seemless deployment without use of app_offline.htm or a mechanism such as suggested above. Take a read of the linked answer as it goes into much more depth.

A: you could use app_offline.htm
this solution is not seamless, but you could use a
<meta http-equiv="refresh" content="5" />

in the htm file, so the browser automatically refreshes the without any javascript.
cheers


text:
Q: Hi! I was wondering: Nostalgia ? Wanderlust? How did these foreign terms for emotions get into English?
They all describe a feeling of something imagined. Some examples:
Nostalgia
Wanderlust
Fernweh
This group of words amazes me and makes me fascinated with the meaning behind them. English is not my first language.

A: Nostalgia is a longing for the past.
http://www.merriam-webster.com/dictionary/nostalgia
Fernweh and Wanderlust are, strictly speaking, German words but I sometimes hear them used in English conversation and literature.
http://en.wiktionary.org/wiki/Fernweh
http://en.wiktionary.org/wiki/Wanderlust
All these describe a feeling of longing for something. A similar (non-English) word would be Saudade
http://en.wiktionary.org/wiki/saudade
If you could please be a little more specific with your question I could give a better answer.


text:
Q: Case insensitive regex in JavaScript I want to extract a query string from my URL using JavaScript, and I want to do a case insensitive comparison for the query string name. Here is what I am doing:
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (!results) { return 0; }
return results[1] || 0;

But the above code does a case sensitive search. I tried /<regex>/i but it did not help. Any idea how can that be achieved?

A: Simple one liner.
In the example below it replaces every vowel with an X.
function replaceWithRegex(str, regex, replaceWith) {
  return str.replace(regex, replaceWith);
}

replaceWithRegex('HEllo there', /[aeiou]/gi, 'X'); //"HXllX thXrX"

A: For example to search word date, upper or lowercase you need to add param i
i = means incasesensitive
example
const value = "some text with dAtE";
/date/i.test(value)

or
const value = "some text with dAtE";
 new RegExp("/date/","i");

A: modifiers are given as the second parameter:
new RegExp('[\\?&]' + name + '=([^&#]*)', "i")

A: Just an alternative suggestion: when you find yourself reaching for "case insensitive regex", you can usually accomplish the same by just manipulating the case of the strings you are comparing:
const foo = 'HellO, WoRlD!';
const isFoo = 'hello, world!';
return foo.toLowerCase() === isFoo.toLowerCase();

I would also call this easier to read and grok the author's intent!

A: You can add 'i' modifier that means "ignore case"
var results = new RegExp('[\\?&]' + name + '=([^&#]*)', 'i').exec(window.location.href);


text:
Q: Why is my TabBar Color change after adding FSCalendar as a subview? My default TabBar color is dark blue, but after I run my app, und choose the 2. tab (which is an FSCalendar that was added by self.view.addSubview(calendar)) it change my TabBar Color to transparent.
I tried 1000 things to change its color in code, but after I added the subview I can not change anything on my TabBar:
After Choosing the 2. Tab it becomes transparent


text:
Q: angular-seed POST acts differently for each browser I'm not sure what is going on with my http post method.  From what I was reading, there might be something wrong with my security, but I am not really sure that is the case or how to fix it.  Any insight in the right direction would be nice.
I am trying to post to an API and retrieve a response back and return the data.  When I run the POST in IE, I get the proper response.
However when I try this in Chrome I get weird results.  My POST turns into an OPTIONS method.  With a Status Code of 200 OK, but my Response is blank.  And when I try to go to the url directly without the POST I get this displayed in the browser:

{"result":false,"error":"Authentication failed: Session authentication failed: No Host Name specified Authentication State: Invalid Login"}

Here is the test.js (controller)
var host = '255.255.255.255';
var creds = {'logintype':'1','host':host,'user':'Administrator','password':'1234','controlid':'ABC999'};
//var obj = JSON.stringify(creds);

angular.module('myApp.test', ['ngRoute'])
    .config(['$routeProvider', function($routeProvider) {
      $routeProvider.when('/test', {
      templateUrl: 'test/test.html',
      controller: 'TestCtrl',
      resolve: {
          friends: ['$http', function($http) {
          return $http({url: 'http://192.168.2.164/ISAPI/rip.dll/REST/SESSIONS/',method: 'POST', data: creds })
              .success(function (data) {
                  return data;
              })
              .error(function () {
                  return 'Error';
              });
      }]
  }
});
}])
.controller('TestCtrl', ['$scope', 'friends',function($scope,response) {
    $scope.response = response;
}]);

A: Thanks to itsananderson, I was able to resolve my issue.  I was happening because Chrome does something called a "preflight" for cross-domain requests.  I needed to move the API to be on the same server as the site was being run to avoid cross site scripting.


text:
Q: How to implement search in a table view (with FRC) The basics are simple: just implement <UISearchBarDelegate,UISearchDisplayDelegate> in your table view controller. Here is an adequate tutorial.
The trick is to realize that there are TWO controllers: a table view controller, and a search display controller. Each controller has its own table view. Hence TWO table views are in play: the normal table view and the search display table view. When delegate methods have a UITableView argument, diff which table view is passed in, and do different things accordingly.
Beyond above basics, data structure becomes a main challenge for me. More specific, how to filter and store the search results? We have three options:
A.

*

*One FRC for the normal table view

*Create an array property to store results

*Use filteredArrayWithPredicate to filter fetched objects (an array)

*Specify a cache for FRC to store fetched objects in memory to enahnce performance
B.

*

*One FRC for the normal table view

*Modify FRC's predicate to do the filter. Apple doc instructs 3 steps to do that:

*

*Delete FRC cache (better not to use one in the first place)

*Change predicate

*Invoke performFetch

C.
Two FRC, one for each table view. A detailed implementation is provided in the accepted answer of this popular post

I think A is the right way to go. My rationale include:
A does all the job well. And it only requires insignificant changes to a table view controller with FRC property. Being more specific, just diff between the two table views in every delegate methods, and add an NSArray property to store fetch results. And, of course, add the filtering code.
B has a potential drawback: FRC delegate methods will get confused on which fetch request is being used? Is the one before search, or during search, or after search? Although there might be solution out there, I don't think it worth the time provided that solution A is working.
The second drawback is that, if we want search results to change on the fly. Every single letter user types in search bar will cause FRC to performFetch, which is rather expensive.
C avoids B's first drawback by using two FRC, yet it suffers from the second for exactly same reason.
Other things to consider:

*

*Do filtering in a background queue. So when user type in search bar, screen won't get blocked no matter how expensive your filtering is.

*Create a helper method to diff between the two table views. Call the helper method in relevant delegate methods, which would make code cleaner.
Above are my understanding of implement search in table view. If there is any mistake, please help point it out. Many thanks.

A: I think there are some conceptual errors regarding UITableViews and FRC. The FRC is just a class to get data from Core Data and together with the MOC ensure that it retains data integrity, even if you have a several tabs that access the same database concurrently , each doing their own updates. Behind the scenes there are processes in play to ensure that an update in one tab gets reflected in all the other tabs. What I am actually saying is there are consequences if you bypass the recommended method.
The performFetch output can be stored in cache and skips fetching if for some reason you need to do a [tableview reloadData]; You can certainly program to get the tableview get its data from multiple sources but I do not see any reason for doing this.  If the only reason for multiple sources is to keep track of the results before the search, there should be a way to reset the predicate in order for the FRC to get all the (current) records. In the case of my app, putting all or all records in the searchbar, results in a predicate 1=1 which gets all the records. Again, this may not be that relevant in a single view app, but a tabbed app with a number of concurrent updates will require this to ensure data is current all across.


text:
Q: Docebo Api Integration I am facing an issue with implementing the API to authorize the user and make a session and launch a course.
All the full steps like making a token and passing it with REST API has been done and in the response I am receiving the success in the response token.
Now the issue is that when I am trying opening a course link, it redirects me to the login page despite landing on course. Can you please help set up a session and let me know which API is to be used to make a session so that it doesn't redirects me to the login page.

A: For those still looking for an answer, I'll show you how to generate a temporary link that will authorize a user and direct them to the desired location in Docebo.
Things you need:

*

*The username.

*The SSO secret for the token hash.
-In Docebo: Click APPS and Features on left-hand side. Click Third party integrations. Activate API and SSO, if not already activated. After API and SSO is active, click on its gear icon. Click the check box that starts with "Enable SSO with...". Enter a SSO secret in the box below the checkbox. Save.

Now, for the implementation. I myself used C# for this but hopefully it will be easily translatable to your language of choice (or lack of choice).
The basic idea is this:
1) Create an MD5 hash of three values:
(NOTE: Include commas between the values when generating the hash. Example further below...)

*

*username(lowercase!!!)

*time = Seconds since the Unix Epoch in utc.

*SSO secret (the one you typed yourself).

2) Get the hex value of the hash.
3) Combine the destination url with the username, time, and hex. Like so:
http[s]://[yourdomain]/lms/index.php?r=site/sso&login_user=[username]&time=[utc
time]&token=[token]{&id_course=[id_course]}{&destination=[destination]}
For my example, I didn't specify a course or a destination.
Here is the above gibberish, in C#:
    public string GenerateDoceboSSOLink()
    {
        string userName = "johnsmith"; //Note the lowercase!!
        string domain = "http://my-test.docebosaas.com";
        string ssoSecret = "MySSOSecret";

        //Getting the seconds since the Unix Epoch
        TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1));
        int time = (int)t.TotalSeconds;

        //Creating the hash...
        MD5 md5 = System.Security.Cryptography.MD5.Create();
        //Note the inclusion of the commas!
        string input = userName + "," + time + "," + ssoSecret;
        byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
        byte[] hash = md5.ComputeHash(inputBytes);

        //Getting the hex value of the hash.
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < hash.Length; i++)
        {
            sb.Append(hash[i].ToString("X2"));
        }

        string token = sb.ToString(); //the hex value, which we will call token

        //The sso link.
        string link = String.Format("{0}/lms/index.php?r=site/sso&login_user={1}&time={2}&token={3}", domain, userName, time, token);
        return link;
    }

So, I followed this
impossible-to-find documentation that led me to what you see above (I couldn't find the  url so I just shared it).


text:
Q: Facebook Unity5 I need to link my unity app with Facebook,  my game pulls data from a website, will it be possible to put it on facebook? Is there a way to also save the game status via facebook?

A: Yes you can link your app with Facebook. Have a look here at the SDK Facebook provides. Also have a look at this tutorial they provide. Think it has some mention of dealing with game status' via Facebook. Also this script shows an example of saving a score around line 126.


text:
Q: What happens when reloading records in Clojure's REPL? I just got done with a marathon debugging session that I eventually managed to reduce to the following code.
(ns test)

(defrecord Person [name])

(comment

  (def person (->Person "Sebastian"))

  (instance? Person person)

)

So if I load this file in the REPL and then evaluate the two comments in succession, the second comment will evaluate to true. But if I then reload the file and again evaluate the second comment I'll receive false until I reevaluate the first comment.
What exactly is going on here?

A: defrecord dynamically generates compiled bytecode for the class Person.
If you invoke it twice, it will generate another class with the same name. So you're asking whether the instance of the newer class is an instance of the older class, which is false.


text:
Q: Android Image button selector for all buttons BUT different background in normal state daily_event_selector.xml
     <?xml version="1.0" encoding="utf-8"?>
     <selector xmlns:android="http://schemas.android.com/apk/res/android">
         <item android:drawable="@drawable/daily_event_selected"
               android:state_pressed="true" />
 This is what I was using for ONE SPECIFIC button but I want to change this for different buttons while using the same selector
       <-- <item android:drawable="@drawable/daily_event_normal" />-->
    </selector>

So I have this selector and I want to use it on all my ImageButtons
P.S.: it's working
But I want to give a different background to each of my ImageButtons in their "normal" state.
I want to use this as a generic selector to have the same effect on all my Buttons while keeping the background different.
But since the selector is only specified (as per my knowledge) as
      android:background="@drawable/daily_event_selector"

in the background property.
So, I can't seem to find a way to add background to the Buttons.
Any idea?

A: Use different selectors for different buttons.
The selectors will only differ in their normal state.
This is the smartest way I know to do that.
Another way would be to have only 1 selector, and change it's normal state in Java.
But this would really be other-than-smart.
Because you have to do some extra work in code (therefore, eventually slowing down the CPU).


text:
Q: FlatList with onLongPress callback I have a Flatlist that I would like to empty when the user long presses it.
The problem is that surrounding the Flatlist with a TouchableOpacity prevents scrolling.
I also cannot surround each item with a Touchable opacity because it's a list with columns and an uneven number of items. This means that at the bottom of the list, there is a leftover area with no items rendered.
This leftover area should still react to the long press (as it is where most users will try to long press).
How can I achieve that?


text:
Q: Networkx spread nodes and shorten lables I have a networks bipartite graph.
this is the code:
    G = nx.Graph()
    G.add_nodes_from(USsNames, bipartite=0) # Add the node attribute "bipartite"
    G.add_nodes_from(TCsNames, bipartite=1)
    G.add_weighted_edges_from(compoundArr)

    labeldict = {}

    # Separate by group
    pos = {}

    # Update position for node from each group
    pos.update({node: [1, index] for index, node in enumerate(USsNames)})
    pos.update({node: [2, index] for index, node in enumerate(TCsNames)})

    nx.draw(G, pos, node_size=10,with_labels=False)
    for p in pos:  # raise text positions
        pos[p][1] += 0.12

    # create the dictionary with the formatted labels
    edge_labels = {i[0:2]:'{0:.2f}'.format(i[2]['weight']) for i in G.edges(data=True)}

    # add the custom egde labels
    nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels,font_size=8)
    nx.draw_networkx_labels(G, pos,font_size=8)
    plt.show()

And the output:

I need to spread the left nodes so they will spread up, and to shorten the right nodes labels (let's say first four chars).
I tried to find a solution but I didn't make it. Thank you.

A: I reconstructed your case on the generated example data.
Firstly we have this graph.

The size of the left array is far less than the size of the right array so the left array is drawn non-proportionally. To draw it properly, you should modify your position update function:
pos.update({node: [1, index] for index, node in enumerate(USsNames)})
We know that TCsNames is larger than USsNames so we can multiply every USsNames nodes Y-position to their ratio:
pos.update({node: [1, index*(len(TCsNames)/len(USsNames))] for index, node in enumerate(USsNames)})
Now we have this graph:

To crop nodes labels, you should modify your draw_networkx_labels with the labels parameter:
nx.draw_networkx_labels(G, pos, labels=node_labels, font_size=8)
with node_labels equal to:
node_labels = {i: i[:5] for i in G.nodes} (5 is the desired node label length).
And finally we have the graph you need:


text:
Q: How to trace where Xcode program crash I'm getting an error in debugger. In Thread my app crash on line:
0x37265f78:  ldr    r3, [r4, #8]

with:
Thread 1: EXC_BAD_ACCESS (code=1, address=0x50000008)

How to find out where app actually crash? There is a something like "call stack"?

A: http://www.raywenderlich.com/10209/my-app-crashed-now-what-part-1
Best tutorial for trace the error.

A: Run your app under the debugger, then when your app crashes you will have access to the call stack.
Furthermore, if you display the console window, you will get more textual information (including a call stack) at the moment of the crash.
If you are using Xcode 4, have a look at the attached picture.

A: You have to set Exception Breakpoint
Go to the Breakpoints navigator, click the + button at the bottom, and add an Exception Breakpoint.
Now you will know the exact line where any of your exception will occur (e.g. line of crash). best of luck!!


text:
Q: Add Campaign information to Visualforce Email Template I am wanting to incorporate campaign information into an email template that will be fired whenever an Opportunity is Closed Won. It appears that it is not possible to query the "Campaign Influence" object in Apex, I was wondering if anybody had an idea for a workaround?
I just want to be able to display campaign names in this template for the opportunity that triggers the email.
Thanks!

A: Primary Campaign Source is a standard field on Opportunity that's a look-up to Campaign. You shouldn't need to query Campaign if the fields on your Opportunity are properly populated prior to it being updated to closed-won.


text:
Q: How can I modify the screen resolution for AnyDesk? I use AnyDesk in Ubuntu, but the screen is too small. Is there a way to modify the screen resolution?

A: Run in a terminal:
xrandr --fb 1920x1080

A: I had a similar problem on my windows machine. I was not able to resize the anydesk window on my external monitor and it occupied the whole screen without any resize option.
Workaround:
This issue is due to scaling of your os(in my case windows)
Go to display setting scale the windows to 110% or more and then you should be able to resize the anydesk window.
Hope this helps!


text:
Q: Can There be a Process WITHOUT an Executable-Backed Image? After looking at various pages like OSR Online and NtInternals, it seems like NtCreateProcess (and ZwCreateProcess) specify that giving a handle to a memory section is optional!
Does this mean that we can have processes that are not backed by executable images? If so, what could they be (or are they) used for potentially? Does that mean we can copy an executable entirely into memory and subsequently even delete the file from the disk, and have the process continue running?? That would seem like a really useful feature.

A: If section (file mapping in win32 land) is NULL, it uses the section of the parent process. It might be possible to use NULL and allocate new memory and point EIP at it (or use a page file mapping), but using NtCreateProcess is problematic, it is undocumented and does not register with the win32 subsystem like CreateProcess does. (If you only want to use exports from ntdll, this might be ok)
On Win9x, NT4 and 2000 you can delete yourself from disk while running by using the dirty tricks listed here.
Other options:

*

*Use a driver, they can be deleted after they have been loaded (The sysinternal tools do this)

*Use a host process; start explorer.exe, cmd.exe or rundll32.exe suspended and use CreateRemoteThread+injected code (This of course means there is a exe file on disk, but none of your code is in it)

A: I just tried to create a process with a non-image-backed Section object myself. :)
The result?
NtCreateProcess returned:
STATUS_SECTION_NOT_IMAGE
// An attempt was made to query image information on a section which
// does not map an image.

So apparently every process needs to be image-backed (assuming you don't hack the kernel to do otherwise).


text:
Q: PHP session lost from HTTPS page to HTTPS I have 2 php pages :
https://mydomain/form.php and https://mydomain/paynow.php
The script form.php has the following partial code :
form.php
    session_start();

    date_default_timezone_set(@date_default_timezone_get());
    error_reporting(E_ALL & ~E_STRICT & ~E_NOTICE);

    @header("Content-Type: text/html; charset=UTF-8");
    //Some sessions are created after
    .......

The script paynow.php has the following partial code :
session_start();
date_default_timezone_set(@date_default_timezone_get());
error_reporting(E_ALL & ~E_STRICT & ~E_NOTICE);

@header("Content-Type: text/html; charset=UTF-8");
    echo "<pre>";
    print_r($_SESSION);
    echo "</pre>";

The script form.php is redirecting to the paynow.php script using:
echo "Redirecting you to the Payment page, please wait...";
echo "<script type=\"text/javascript\">top.location.replace('https://mydomain/paynow.php')</script>";

exit;

On the paynow.php the session array is empty when I change the url to top.location.replace('http://mydomain/paynow.php') it works fine.
Any thoughts why that is happening please?
My sessions configuration are like the following :


text:
Q: connect pgadmin3 to postgres runnng on server ** new to pgadmin and postgress **
my organization uses PostgreSQL on its server with ubuntu os, I try to connect it using      pgadmin 3,
these are the stapes I have taken

changed pg_hba.conf using 'sudo nano /etc/postgresql/9.3/main/pg_hba.conf'
changed listen_addresses='*'  in postgresql.conf file
sudo ufw allow 5432/tcp

but still, I am unable to connect I get this error from pg admin:
Server doesn't listen
The server doesn't accept connections: the connection library reports could not connect to server: Connection timed out Is the server running on host "103.72.131.155" and accepting TCP/IP connections on port 5432?
how can I fix it,
is there any website which can guide me step by step to connect pgadmin to PostgreSQL.


text:
Q: Unity Hand tracking issue on the quest with UI raycasting I'm working on a Unity project, trying to test the UI interaction on the Quest II with hand tracking and ray casting.
I've set up a very basic scene with all the default assets (OVRCameraRig, UIHelper) and added just a button to test the UI interaction.
This is what my scene looks like:

The issue I have is, when I run the scene, the Ray is rotated 90 degrees, and it's attached to the wrist for some reason. I made a video here to show what I mean :
https://www.youtube.com/watch?v=5f12yfpugB8
It's still interacting with the UI though.
Then after watching some online tutorials, I commented out these lines in the HandInputSelector.cs, which was attached to the UIHelper:
void SetActiveController(OVRInput.Controller c)
{
    /*
    Transform t;
    if(c == OVRInput.Controller.LTouch)
    {
        t = m_CameraRig.leftHandAnchor;
    }
    else
    {
        t = m_CameraRig.rightHandAnchor;
    }
    m_InputModule.rayTransform = t;
  */
}

and instead added a 2nd script to the UI helper, with these lines only:
public OVRHand hand;
public OVRInputModule inputModule;

private void Start()
{
    inputModule.rayTransform = hand.PointerPose;
}

Now the ray is at least attached to the correct position, but it still doesn't rotate properly with the hand movement. I made another video of it here :
Now the ray is at least attached to the correct position, but it still doesn't rotate properly with the hand movement. I made another video of it here :
https://youtu.be/q3d0eG2LwY0
My Unity version is 2021.3.1f1
Can someone please tell me what I'm doing wrong?


text:
Q: jniavutil.dll: Can't find dependent libraries When i run the code from the following link, https://github.com/sagioto/LipReading/blob/master/lipreading-gui/src/main/java/edu/lipreading/gui/MainFrame.java ; I get the following error :

Exception in thread "Thread-6" java.lang.UnsatisfiedLinkError: C:\Users\Harish ram\AppData\Local\Temp\javacpp13384533628877\jniavutil.dll: Can't find dependent libraries
      at java.lang.ClassLoader$NativeLibrary.load(Native Method)
      at java.lang.ClassLoader.loadLibrary1(Unknown Source)
      at java.lang.ClassLoader.loadLibrary0(Unknown Source)
      at java.lang.ClassLoader.loadLibrary(Unknown Source)
      at java.lang.Runtime.load0(Unknown Source)
      at java.lang.System.load(Unknown Source)
      at com.googlecode.javacpp.Loader.loadLibrary(Loader.java:418)
      at com.googlecode.javacpp.Loader.load(Loader.java:368)
      at com.googlecode.javacpp.Loader.load(Loader.java:315)
      at com.googlecode.javacv.cpp.avutil.(avutil.java:75)
      at java.lang.Class.forName0(Native Method)
      at java.lang.Class.forName(Unknown Source)
      at com.googlecode.javacpp.Loader.load(Loader.java:334)
      at com.googlecode.javacv.cpp.avcodec.(avcodec.java:85)
      at java.lang.Class.forName0(Native Method)
      at java.lang.Class.forName(Unknown Source)
      at com.googlecode.javacpp.Loader.load(Loader.java:334)
      at com.googlecode.javacv.cpp.avformat.(avformat.java:76)
      at com.googlecode.javacv.FFmpegFrameRecorder.(FFmpegFrameRecorder.java:111)
      at com.googlecode.javacv.FFmpegFrameRecorder.(FFmpegFrameRecorder.java:104)
      at com.googlecode.javacv.FFmpegFrameRecorder.(FFmpegFrameRecorder.java:107)
      at com.googlecode.javacv.FFmpegFrameRecorder.(FFmpegFrameRecorder.java:101)
      at main.java.edu.lipreading.gui.LipReaderPanel.getVideoFromSource(LipReaderPanel.java:150)
      at main.java.edu.lipreading.gui.VideoCapturePanel$1.run(VideoCapturePanel.java:89)
      at java.lang.Thread.run(Unknown Source)

I dont understand what is wrong. Can anyone help me ?

A: The code tries to use the JavaCV wrapper for FFmpeg (FFmpegFrameRecorder) you need FFmpeg installed in your system in order to use it.
Take a look at the requirements section at the main page of JavaCV and the Quick Start for OpenCV and FFmepg too.


text:
Q: Dedup is not working on Splunk Please see picture below. I inserted dedup for job_duration, but it was not showing in the search result. I only need one result to do visualisation.

A: It looks like job_min is a multi-value field, which are not supported by dedup.  Try ... | eval job_min=mvdedup(duration) | ....

A: If job_min is in a multivalue field, you should mvexpand first
And, instead of dedup, try using stats
Like this:
| mvexpand job_min
| stats count by job_min
| fields - count


text:
Q: Is there a proof via Chern-Weil theory that the first Chern numbers of two $\mathbb R$-isomorphic complex vector bundles are equal mod 2? Let $M$ be a compact, oriented surface.
If we have a complex vector bundle $E$ over $M$, then we can define the first Chern number $c_1(E)$ via Chern-Weil theory. More precisely, if $\nabla$ is a connection on $E$, then for a local frame $u_1,\ldots,u_k$ we can define the $1$-forms $A_j^i$ by the formula
$$\nabla u_j = \sum_i A_j^i u_i,
$$
and then define the curvature by
$$F := dA + A \wedge A,$$
where
$A$ is the matrix $(A_j^i)$ of $1$-forms.
The first Chern number is defined by
$$c_1(E) = \frac{1}{2\pi i}\int_M \mathrm{tr}(F),$$
and this number does not depend on the choice of connection $\nabla$.
Two complex vector bundles $E_1, E_2$ are $\mathbb C$-isomorphic if there is a diffeomorphism $f:E_1 \to E_2$ such that the diagram

commutes and $f$ restricted to the fibers is $\mathbb C$-linear. Analogously, the complex vector bundles are $\mathbb R$-isomorphic if the map $f$ restricted to the fibers is $\mathbb R$-linear.
If the $E_1$ and $E_2$ are $\mathbb C$-isomorphic, then $c_1(E_1) = c_1(E_2)$, and if they are $\mathbb R$-isomorphic, then $c_1(E_1) = c_1(E_2) \mod 2$.
Nevertheless, I only know how to prove the second property via Stiefel–Whitney numbers: in short, we have $c_1(E_1) = w_2(E_1) \mod 2$.

Question: If $f:E_1 \to E_2$ is an $\mathbb R$-isomorphism, how do I prove $c_1(E_1) = c_1(E_2) \mod 2$ direct from Chern-Weil approach, without using general characteristic classes?

If $E_1$ and $E_2$ are line bundles, then the proof is actually simple, because in this case we have $$c_1(E) = \frac{1}{2\pi i}\int_M F,$$
that coincides it the Euler number, and it is easy to prove that $c_1(E_1) = c_1(E_2)$ if $f$ preserves orientation, and $c_1(E_1) = -c_1(E_2)$ if $f$ reverses the orientation.
I would be satisfied with a proof for rank $2$.


text:
Q: How to configure 2 database/schema in a application I am using Spring Boot for application dev.
I need it to access 2  databases/schema in my app (both are in MySQL database).
How do I configure this using just annotations or application.properties file?
At present I am using single database : configured as below
context.xml of tomcat
<Resource name="jdbc/user" auth="Container" type="javax.sql.DataSource"
               username="***" password="***" driverClassName="com.mysql.jdbc.Driver"
               url="jdbc:mysql://localhost:3306/user"/>

and
application.properties  in application:
spring.datasource.jndi-name=jdbc/user

spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
spring.jpa.show-sql=false
spring.jpa.hibernate.ddl-auto=validate

How do I configure, one more database/schema say customer into this application.
Thanks in advance.

A: you should use 2 datasource
link example
https://github.com/spring-projects/spring-data-examples/tree/master/jpa/multiple-datasources

A: You dont need use two datasources, just define two beans in your xml file. And one transaccation for schema, make a reference to bean where you have the connection and properties of data base


text:
Q: Group Tree PDF Export in Crystal Reports I am trying to figure out how to export a crystal report into a PDF file from an ASP.NET application. I got it to work, however, I want the group tree to show up as bookmarks in the PDF. From what I've found on google, the way to do this is to declare an instance of the CrystalDecisions.Shared.PDFFormatOptions class, then set the GroupTree property to true. However, this class does not seem to exist. I don't know if its because I am using Crystal Reports for Visual Studio 2008 or what, but it is not there. There is a class called CrystalDecisions.Shared.PdfRtfWordFormatOptions, however, the GroupTree property does not exist in this class. Can someone tell me what I am missing?
Thanks

A: Not familiar with that class as I have never had to use it but tried this on my machine:
CrystalDecisions.Shared.PdfFormatOptions options = new CrystalDecisions.Shared.PdfFormatOptions();
        options.CreateBookmarksFromGroupTree = true;

It seemed ok to me. I have the full Crystal Reports 2008 version not the one that comes with visual studio so that could be the reason it doesn't work for you.
I would check that you have a reference in your project to the CrystalDecisions.Shared namespace in your project though.

A: If you are using a 'full' version of CR, you can enable the 'Create bookmarks from group tree' option in the File | Export | Report Export Options... dialog.  This setting is stored in the RPT file.
I didn't see this option in the CR.Net version.


text:
Q: Converting datetime to date and time only I am concatenating 2 columns in SQL Server, they both have a data type of datetime:
UPDATE dbo.Feban_stg
SET [Date & Time Posted] = CONCAT(CONVERT(VARCHAR(10), [Date Posted], 110), RIGHT(CONVERT(varchar, [Time Posted], 100), 7))

and so far I always get this error

Conversion failed when converting date and/or time from character string.

The datatype of date & time posted is datetime as well.
Thanks

A: The problem is that there is not space between the date part and time part. CANCAT just adds strings. Try this:
UPDATE dbo.Feban_stg
SET [Date & Time Posted] = CONCAT(CONVERT(VARCHAR(10), [Date Posted], 110), ' ', RIGHT(CONVERT(varchar, [Time Posted], 100), 8))

In addition, you need 8 instead 7 in RIGHT function to get the complete hour.


text:
Q: Token mismatch with ajax post request to a subdomain I am developing a web app using the Laravel framework.
When I send an ajax request from app.com to api.app.com passing the csrf token generated at app.com, I always get the TokenMismatchException.
The problem is that ajax request to api.app.com is creating a new session there.
I am using a single laravel installation for app.com and api.app.com.
Subdomain routes:
Route::group(array('domain' => 'api.app.com'), function()
{
    Route::controller('user', 'MyApp\API\UserController');
});

CSRF Filter is applied only to POST request:
Route::when('*', 'csrf', ['post']);

CSRF Filter:
Route::filter('csrf', function()
{
    $token = Input::get('_token');

    if (Session::token() != $token)
    {
        throw new Illuminate\Session\TokenMismatchException;
    }
});

My ajax request looks like this:
$.ajax({
    'url': '//api.app.com/user/hello',
    'data': {
        fields:'',
        '_token': 'output of csrf_token() from app.com'
    },
    'dataType': 'json',
    'type': 'POST'
}).done(done).fail(fail).always(always);

Everything works fine if I don't use a subdomain for my api.
I am using memcached as my session storage.
EDIT:
My session domain is set to .app.com.
'domain' => '.app.com',

A: I solved the issue by sending the Access-Control-Allow-Credentials: true header and changing my ajax request function to this:
$.ajax({
    'url': '//api.app.com/user/hello',
    'data': {
        fields:'',
        '_token': 'output of csrf_token() from app.com'
    },
    'dataType': 'json',
    'type': 'POST',
    xhrFields: {
        withCredentials: true
    }
}).done(done).fail(fail).always(always);


text:
Q: What is the best way to implement "remember me" for a website? I want my website to have a checkbox that users can click so that they will not have to log in each time they visit my website. I know I will need to store a cookie on their computer to implement this, but what should be contained in that cookie?
Also, are there common mistakes to watch out for to keep this cookie from presenting a security vulnerability, which could be avoided while still giving the 'remember me' functionality?

A: Improved Persistent Login Cookie Best Practice
You could use this strategy described here as best practice (2006) or an updated strategy described here (2015):

*

*When the user successfully logs in with Remember Me checked, a login cookie is issued in addition to the standard session management cookie.

*The login cookie contains a series identifier and a token. The series and token are unguessable random numbers from a suitably large space. Both are stored together in a database table, the token is hashed (sha256 is fine).

*When a non-logged-in user visits the site and presents a login cookie, the series identifier is looked up in the database.

*

*If the series identifier is present and the hash of the token matches the hash for that series identifier, the user is considered authenticated. A new token is generated, a new hash for the token is stored over the old record, and a new login cookie is issued to the user (it's okay to re-use the series identifier).

*If the series is present but the token does not match, a theft is assumed. The user receives a strongly worded warning and all of the user's remembered sessions are deleted.

*If the username and series are not present, the login cookie is ignored.

This approach provides defense-in-depth. If someone manages to leak the database table, it does not give an attacker an open door for impersonating users.

A: Investigating persistent sessions myself I have found that it's simply not worth the security risk. Use it if you absolutely have to, but you should consider such a session only weakly authenticated and force a new login for anything that could be of value to an attacker.
The reason being of course is that your cookies containing your persistent session are so easily stolen.
4 ways to steal your cookies (from a comment by Jens Roland on the page @splattne based his answer on):

*

*By intercepting it over an unsecure line (packet sniffing / session hijacking)

*By directly accessing the user's browser (via either malware or physical access to the box)

*By reading it from the server database (probably SQL Injection, but could be anything)

*By an XSS hack (or similar client-side exploit)

A: Store their UserId and a RememberMeToken.  When they login with remember me checked generate a new RememberMeToken (which invalidate any other machines which are marked are remember me).
When they return look them up by the remember me token and make sure the UserId matches.

A: I would store a user ID and a token. When the user comes back to the site, compare those two pieces of information against something persistent like a database entry.
As for security, just don't put anything in there that will allow someone to modify the cookie to gain extra benefits. For example, don't store their user groups or their password. Anything that can be modified that would circumvent your security should not be stored in the cookie.


text:
Q: How does one compute this bayesian probability? Assume you have a network as follow (where X->Y implies X is the parent of Y)

A->D, B->D

How does one compute $P(A,B|D)$?
A and B are independent so my intuition tells me
$P(A,B|D)= P(A|D)\times P(B|D) = [\frac{P(D|A)}{P(A)}]\times[\frac{P(D|B)}{P(B)}]$
but I am not sure.

A: No.   You cannot infer conditional independence from pairwise independence.
Applying Bayes' Rule can only obtain:
$$\begin{align}
\mathsf P(A, B\mid D) ~=~& \dfrac{\mathsf P(D\mid A, B)~\mathsf P(A,B)}{\mathsf P(D)}
\\[1ex] =~& \dfrac{\mathsf P(D\mid A, B)~\mathsf P(A)~\mathsf P(B)}{\mathsf P(D)}
\end{align}$$


text:
Q: change header image on post name I have many pages with a cover photo each that must be inserted into the header, but I cant seem to load the default header if it does not exist, or is the main blog page.
here is my code:
global $post;     // if outside the loop
if ( is_home() ) {
    echo bloginfo('template_url') . '/images/our_clients.jpg' ;
} else {
    get_post_meta($post->ID, 'cover_image', true);
}

What I need: if it is blog page, display: echo bloginfo('template_url') . '/images/our_clients.jpg' ; else display: get_post_meta($post->ID, 'cover_image', true);
any ideas?

A: The line
echo bloginfo('template_url') . '/images/our_clients.jpg' ;

will get the URL of your default image, but to display it, you will need to put that URL in an img src attribute.  So, you can change the above line to:
echo '';

Also, change
get_post_meta($post->ID, 'cover_image', true);

to
echo 'ID, 'cover_image', true); . '" />';


text:
Q: How to import query result from splunkstorm to your app? You can run query on splunkstorm and you get some specified data formed in a table. I created a project on C# and trying to retrieve data from storm to app.
What I tried: installed SDK, started splunk server. But I can't find a way to connect to my splunkstorm.com account execute queries.
The question is how can I import query result from splunkstorm.com to my app?

A: My way is to write a small BASH Script witch cll the REST API of SPLUNK and saves the data to an CSV file. Then I take the file an do something interesting (build report, make robustness check, ...). This way look complicated, but in real life it is much easier. Plus, you can test your query independly of your code. This will speed up your development and your debugging. By the way, some SPLUNK SDK Versions, Java SDK too, have nasty bugs.


text:
Q: QPython requests SSL error- no available ciphers Ive been trying to use requests.get for sometime now but I keep getting this error on Qpython
HTTPSConnectionPool(host='google.com', port=443):
Max retries exceeded with url:
 / (Caused by SSLError(
    SSLError("bad handshake: Error([('SSL routines',
'ssl_cipher_list_to_bytes', 'no ciphers available')],)",),))

This is my code
import ssl
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.poolmanager import
PoolManager
from requests.packages.urllib3.util import ssl_
CIPHERS = ( 'ECDHE-RSA-AES256-GCM-SHA384:ECDHE-
ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AElS256-
SHA384: ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-
AES128-GCM-SHA256:ECDHE-RSA-AES128-
SHA256:AES256-SHA' )

class TlsAdapter(HTTPAdapter):
    def __init__(self, ssl_options=0, **kwargs):
        self.ssl_options = ssl_options
        super(TlsAdapter, self).__init__(**kwargs)
    def init_poolmanager(self, *pool_args, **pool_kwargs):
        ctx = ssl_.create_urllib3_context(ciphers=CIPHERS,
       cert_reqs=ssl.CERT_REQUIRED,
      options=self.ssl_options)
       self.poolmanager = PoolManager(*pool_args,
       ssl_context=ctx, **pool_kwargs)

s = requests.session()
adapter = TlsAdapter()
s.mount("https://", adapter)

try:
    r = s.get('https://google.com')
    print(r)
except Exception as e:
    print(e)

Does anyone know what's going wrong here? I thought this would work splendidly. Is this a problem specific to qpython or not too. Because that would explain a lot.

A: Copied from this issue
import requests
requests.packages.urllib3.util.ssl_.DEFAULT_CIPHERS = "TLS13-CHACHA20-POLY1305-SHA256:TLS13-AES-128-GCM-SHA256:TLS13-AES-256-GCM-SHA384:ECDHE:!COMPLEMENTOFDEFAULT"

after that you can
r=requests.get("https://google.com")

print(r.status_code)


text:
Q: App behaviour changes after disconnected from xcode I am developing a new release of my app and have come across a very frustrating issue. i have some code that repositions a view on the screen after rotation(see below code) When i run it in the simulator there are no issues, when i test on a physical device there is also no issue, until i disconnect from xCode. After disconnecting from Xcode the view no longer re locates correctly. If i reconnect to Xcode and run again it still won't work as it used to/expected. I added the logging you see in the code and now know that on first execution the heigh and with are logging correctly but after disconnect they are reversed. I have also installed an adhoc distribution to a two different devices and again on first execution everything works fine(no Xcode connection this time). But if i completely close the app (double tap home and wipe up) on the next execution we get exactly the same outcome as before with the view repositioning off the screen(presumably the NSlog values will again be reversed). I have searched high and low and can't find any solutions at all.
- (void)deviceOrientationDidChangeNotification:(NSNotification*)note
{
NSLog(@"rotate");
int height = [UIScreen mainScreen].bounds.size.height;
int width = [UIScreen mainScreen].bounds.size.width;
NSLog(@"%@,%d",@"height: ",height);
NSLog(@"%@,%d",@"width: ",width);

UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];

if (UIDeviceOrientationIsPortrait(orientation)==YES){

    if ([self.vcID.text isEqualToString:@"i4"]) {
        self.addheightCont.constant = 50;

    }else{
        self.addheightCont.constant = 100.0;

    }

}else if (UIDeviceOrientationIsLandscape(orientation)==YES){

    if ([self.vcID.text isEqualToString:@"i5"]) {
        self.addheightCont.constant = 32.0;

    }else if ([self.vcID.text isEqualToString:@"i4"]) {
        self.addheightCont.constant = 32.0;

    }else{
        self.addheightCont.constant = 50.0;
    }

}

if (height==568) {

    self.imageScroller.delegate = self;

    self.imageScroller.zoomScale = 0.0;
    [self.imageScroller setContentOffset:CGPointMake(0, 0) animated:YES];

    self.LargeImage.frame = CGRectMake(0, 0, 320, 568);
    self.imageScroller.frame = CGRectMake(0, 0, 320, 568);
    self.imageScroller.minimumZoomScale = 1.0;
    self.imageScroller.maximumZoomScale = 100.0;

    if (self.CommentsView.alpha == 1.0) {
        [self.CommentsView setCenter:CGPointMake(160, 284)];
        [self.ShowCommentsButton setCenter:CGPointMake(24, 445)];
        [self.LikeButtonbutton setCenter:CGPointMake(70.5, 445)];
    }

    if (self.editCommentView.alpha == 1.0) {
        [self.editCommentView setCenter:CGPointMake(160, 284)];
    }
}else if (height==480){

        self.imageScroller.delegate = self;

        self.imageScroller.zoomScale = 0.0;
        [self.imageScroller setContentOffset:CGPointMake(0, 0) animated:YES];

        self.LargeImage.frame = CGRectMake(0, 0, 320, 480);
        self.imageScroller.frame = CGRectMake(0, 0, 320, 480);
        self.imageScroller.minimumZoomScale = 1.0;
        self.imageScroller.maximumZoomScale = 100.0;

        if (self.CommentsView.alpha == 1.0) {
            [self.CommentsView setCenter:CGPointMake(160, 240)];
            [self.ShowCommentsButton setCenter:CGPointMake(24, 445)];
            [self.LikeButtonbutton setCenter:CGPointMake(70.5, 445)];
        }

        if (self.editCommentView.alpha == 1.0) {
            [self.editCommentView setCenter:CGPointMake(160, 284)];
        }

}else if ((height==320) && (width==568)){

    self.imageScroller.delegate = self;

    self.imageScroller.zoomScale = 0.0;
    [self.imageScroller setContentOffset:CGPointMake(0, 0) animated:YES];

    self.LargeImage.frame = CGRectMake(0, 0, 568, 320);
    self.imageScroller.frame = CGRectMake(0, 0, 568, 320);
    self.imageScroller.minimumZoomScale = 1.0;
    self.imageScroller.maximumZoomScale = 100.0;

    if (self.CommentsView.alpha == 1.0) {
        [self.CommentsView setCenter:CGPointMake(277, 160)];
        [self.ShowCommentsButton setCenter:CGPointMake(24, 304)];
        [self.LikeButtonbutton setCenter:CGPointMake(70.5, 304)];

    }
    if (self.editCommentView.alpha == 1.0) {
        [self.editCommentView setCenter:CGPointMake(284, 160)];
    }
}else if ((height==320) && (width==480)){
    self.imageScroller.delegate = self;

    self.imageScroller.zoomScale = 0.0;
    [self.imageScroller setContentOffset:CGPointMake(0, 0) animated:YES];

    self.LargeImage.frame = CGRectMake(0, 0, 480, 320);
    self.imageScroller.frame = CGRectMake(0, 0, 480, 320);
    self.imageScroller.minimumZoomScale = 1.0;
    self.imageScroller.maximumZoomScale = 100.0;

    if (self.CommentsView.alpha == 1.0) {
        [self.CommentsView setCenter:CGPointMake(240, 160)];
        [self.ShowCommentsButton setCenter:CGPointMake(24, 304)];
        [self.LikeButtonbutton setCenter:CGPointMake(70.5, 304)];

    }
    if (self.editCommentView.alpha == 1.0) {
        [self.editCommentView setCenter:CGPointMake(284, 160)];
    }
}else if ((height==375) && (width==667)){
    self.imageScroller.delegate = self;

    self.imageScroller.zoomScale = 0.0;
    [self.imageScroller setContentOffset:CGPointMake(0, 0) animated:YES];

    self.LargeImage.frame = CGRectMake(0, 0, 667, 375);
    self.imageScroller.frame = CGRectMake(0, 0, 667, 375);
    self.imageScroller.minimumZoomScale = 1.0;
    self.imageScroller.maximumZoomScale = 100.0;

    if (self.CommentsView.alpha == 1.0) {
        [self.CommentsView setCenter:CGPointMake(333.5, 187.5)];
        [self.ShowCommentsButton setCenter:CGPointMake(24, 304)];
        [self.LikeButtonbutton setCenter:CGPointMake(70.5, 304)];

    }
    if (self.editCommentView.alpha == 1.0) {
        [self.editCommentView setCenter:CGPointMake(333.5, 115)];
    }
}else if (height==667) {

    self.imageScroller.delegate = self;

    self.imageScroller.zoomScale = 0.0;
    [self.imageScroller setContentOffset:CGPointMake(0, 0) animated:YES];

    self.LargeImage.frame = CGRectMake(0, 0, 375, 667);
    self.imageScroller.frame = CGRectMake(0, 0, 375, 667);
    self.imageScroller.minimumZoomScale = 1.0;
    self.imageScroller.maximumZoomScale = 100.0;

    if (self.CommentsView.alpha == 1.0) {
        [self.CommentsView setCenter:CGPointMake(187.5, 333.5)];
        [self.ShowCommentsButton setCenter:CGPointMake(24, 445)];
        [self.LikeButtonbutton setCenter:CGPointMake(70.5, 445)];
    }

    if (self.editCommentView.alpha == 1.0) {
        [self.editCommentView setCenter:CGPointMake(187.5,115)];
    }
}else if (height==736) {

    self.imageScroller.delegate = self;

    self.imageScroller.zoomScale = 0.0;
    [self.imageScroller setContentOffset:CGPointMake(0, 0) animated:YES];

    self.LargeImage.frame = CGRectMake(0, 0, 414, 736);
    self.imageScroller.frame = CGRectMake(0, 0, 414, 736);
    self.imageScroller.minimumZoomScale = 1.0;
    self.imageScroller.maximumZoomScale = 100.0;

    if (self.CommentsView.alpha == 1.0) {
        [self.CommentsView setCenter:CGPointMake(207, 333.5)];
        [self.ShowCommentsButton setCenter:CGPointMake(24, 514)];
        [self.LikeButtonbutton setCenter:CGPointMake(70.5, 514)];
    }

    if (self.editCommentView.alpha == 1.0) {
        [self.editCommentView setCenter:CGPointMake(207,115)];
    }
}else if (height==414){
    self.imageScroller.delegate = self;

    self.imageScroller.zoomScale = 0.0;
    [self.imageScroller setContentOffset:CGPointMake(0, 0) animated:YES];

    self.LargeImage.frame = CGRectMake(0, 0, 736, 414);
    self.imageScroller.frame = CGRectMake(0, 0, 736, 414);
    self.imageScroller.minimumZoomScale = 1.0;
    self.imageScroller.maximumZoomScale = 100.0;

    if (self.CommentsView.alpha == 1.0) {
        [self.CommentsView setCenter:CGPointMake(368, 187.5)];
        [self.ShowCommentsButton setCenter:CGPointMake(24, 380)];
        [self.LikeButtonbutton setCenter:CGPointMake(70.5, 380)];

    }
    if (self.editCommentView.alpha == 1.0) {
        [self.editCommentView setCenter:CGPointMake(368, 115)];
    }
}
}

A: After Fahim's suggestion i did some research on auto layout and as a result have managed to implement a fix using auto layout. I have set a constraint for the distance of the comment view from the top and sides of the top of the parent view and simply change the constant values using the code below to animate the view on and off the screen. As a result i no longer need any of the code in my question in the view rotation. Although i didn't find an answer to why the behaviour changes when the phone is disconnected from Xcode its no longer an issue with auto layout doing all the work.
To animate the view on screen i use:
[UIView animateWithDuration:0.5 animations:^{

                self.CommentViewOffset.constant = 40;
                [self.view layoutIfNeeded];
        }];

And off the screen i use:
UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
[UIView animateWithDuration:0.5 animations:^{

  if (UIDeviceOrientationIsPortrait(orientation)==YES){
     self.CommentViewOffset.constant = 750.0;
     self.editComentViewOffset.constant = 750;
     [self.view layoutIfNeeded];

  }else if (UIDeviceOrientationIsLandscape(orientation)==YES){
     self.CommentViewOffset.constant = 440;
     self.editComentViewOffset.constant = 440;
                [self.view layoutIfNeeded];
     }

Now i have no need to do anything in the deviceOrientationDidChangeNotification method as everything is handled with auto layout. I must say i have avoided auto layout completely until now and really wish i had taken the time to do the research earlier.


text:
Q: Changing label in auth.User model field How to change label for User field, e.g. for username? I'm using CustomUser model that inherits AbstractUser, and I want to change label for some fields.
I try do next in CustomUser model, but it's not working. Any ideas?
class CustomUser(AbstractUser):
    mobile = models.CharField(max_length=16)
    address = models.CharField(max_length=100)
    def __init__(self, *args, **kwargs):
        super(CustomUser,self).__init__(*args, **kwargs)
        self.username.__setattr__('label', 'Some text')

A: A Django model's fields are moved to Model._meta at class initialization, since Django 1.8, you can access them using the _meta API.
Also, label is an attribute of form fields, the equivalent for model fields is verbose_name.
This should work an Django 1.8
class CustomUser(AbstractUser):
    mobile = models.CharField(max_length=16)
    address = models.CharField(max_length=100)

    def __init__(self, *args, **kwargs):
        super(CustomUser,self).__init__(*args, **kwargs)
        self._meta.get_field('username').verbose_name = 'Some text'

Before Django 1.8 you can use self._meta.get_field_by_name('username')[0] instead of self._meta.get_field('username').


text:
Q: Fragments not visible when switch tabs using ViewPager and TabLayout I have a HostActivity that uses ViewPager and TabLayout to switch between multiple Fragments. When I switch between the tabs, the Fragments instance does get the updated data. I also see the updated data in onCreateView of the Fragment instance, but the TextView.setText does not get updated. When I check the visibility of Fragment, it always shows Invisible. How do I make the fragment visible when I switch tabs so that the view gets updated with new data? Is there something missing in the Fragment/Activity Lifecycle? I am implementing ViewPager for the first time so it will be helpful to know if I am missing something.
Fragment Class:
public class StepFragment extends Fragment { @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (getArguments() != null) {
            step = getArguments().getParcelable(SELECTED_STEP);
            mDescription = step.getDescription();
        }

        View view = inflater.inflate(R.layout.step_fragment, container, false);
        ButterKnife.bind(this,view);
        Log.e(TAG, "onCreateView: "+mDescription); **// THIS GETS UPDATED DATA**
        tvStepDescription.setText(mDescription);
        }
        return view;
    }
 }

Here is my Host Activity:
public class StepActivity extends AppCompatActivity {
...
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_step);
        fragmentSelectAdapter = new StepFragmentSelectAdapter(getSupportFragmentManager(),this,steps,recipe);
        mViewPager.setAdapter(fragmentSelectAdapter);
        mTabLayout.setupWithViewPager(mViewPager);
        stepFragment = (StepFragment) getSupportFragmentManager().findFragmentById(R.id.step_container);
        if(stepFragment == null) {
            stepFragment = StepFragment.newInstance(step, recipe);
            stepFragment.setArguments(bundle);
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.step_container, stepFragment)
                    .commit();
        } else {
            stepFragment = StepFragment.newInstance(step, recipe);
            stepFragment.setArguments(bundle);
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.step_container, stepFragment)
                    .commit();
        }
    }
}

Here is my FragmentPagerAdapter, which seems to be getting the correct data as per the tab position in getItem method:
public class StepFragmentSelectAdapter extends FragmentPagerAdapter {
...
   @Override
    public Fragment getItem(int position) {
        **// THIS GETS UPDATED DATA**
        Log.e(TAG, "getItem: \nDecr: "+steps.get(position).getDescription()+"\nVideo: "+steps.get(position).getVideoURL()+"\nImage: "+steps.get(position).getThumbnailURL());
        return StepFragment.newInstance(steps.get(position),recipe);
    }

    @Override
    public int getCount() {
        if (steps == null){
            return 0;
        }
        return steps.size();
    }
...
}

A: As far as I could understand about the problem that you are having there, I think you should implement an onResume function in your StepFragment which will get the updated data from some source and will display this in the TextView. However, I can think of a potential problem in your StepFragmentSelectAdapter. You are creating a new instance each time you are switching the tabs.
You should have the Fragment instances created before and if you are about to pass the data among fragments, you might consider having a BroadcasReceiver or listener function by implementing an interface.
So the PagerAdapter should look something like this.
public class StepFragmentSelectAdapter extends FragmentPagerAdapter {

   public ArrayList<StepFragment> stepFragments;

   public StepFragmentSelectAdapter(ArrayList<Step> steps) {
       stepFragments = new ArrayList<>();

       for(int i = 0; i < steps.size(); i++) {
           stepFragments.add(StepFragment.newInstance(steps.get(position),recipe));
       }
   }
...
   @Override
    public Fragment getItem(int position) {
        **// THIS GETS UPDATED DATA**
        Log.e(TAG, "getItem: \nDecr: "+steps.get(position).getDescription()+"\nVideo: "+steps.get(position).getVideoURL()+"\nImage: "+steps.get(position).getThumbnailURL());
        return stepFragments.get(position);
    }

    @Override
    public int getCount() {
        if (steps == null){
            return 0;
        }
        return steps.size();
    }
...
}

A: Thanks for the hint. I got around this problem by replacing ActionBar with a custom ToolBar with back ImageButton and using click listener to get back to the calling activity.
backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getActivity().onBackPressed();
            }
        });


text:
Q: Python socket.accept nonblocking? Is there a way I can use python's socket.accept() in a non-blocking way that simply runs it and lets me just check if it got any new connections? I really don't want to use threading.
Thanks.

A: You probably want something like select.select() (see documentation). You supply select() with three lists of sockets: sockets you want to monitor for readability, writability, and error states. The server socket will be readable when a new client is waiting.
The select() function will block until one of the socket states has changed. You can specify an optional fourth parameter, timeout, if you don't want to block forever.
Here is a dumb echo server example:
import select
import socket

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind(('', 8888))
server_socket.listen(5)
print "Listening on port 8888"

read_list = [server_socket]
while True:
    readable, writable, errored = select.select(read_list, [], [])
    for s in readable:
        if s is server_socket:
            client_socket, address = server_socket.accept()
            read_list.append(client_socket)
            print "Connection from", address
        else:
            data = s.recv(1024)
            if data:
                s.send(data)
            else:
                s.close()
                read_list.remove(s)

Python also has epoll, poll, and kqueue implementations for platforms that support them. They are more efficient versions of select.

A: You can invoke the setblocking(0) method on the Socket to make it non-blocking. Look into the asyncore module or a framework like Twisted.

A: You can make select non-blocking by setting the timeout parameter to 0. In that case select polls. See https://docs.python.org/3/library/select.html


text:
Q: WebApi Not Working When Deployed to Azure Website My WebApi works perfectly on my local machine, but when published to Azure (azure website) I get the following:

No HTTP resource was found that matches the request URI
  'http://myazurewebsite.domain/Api/Zipcode/GetLatLong?zip5=23423'.

But on localhost it works lovely.
http://localhost/Api/Zipcode/GetLatLong?zip5=20024

{"Latitude":38.89,"Longitude":-77.03}

I have a modified WebApi Route:
 public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultPublicApi",
            routeTemplate: "Api/{controller}/{action}/{id}/{format}",
            defaults: new { id = RouteParameter.Optional, format = RouteParameter.Optional}
        );
    }
}

ApiController Class:
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Project.Geography.Services;
using Project.WebPublic.Filters;

namespace Project.WebPublic.Controllers.WebApi
{
    public class ZipCodeController : ApiController
    {
        private readonly ZipCodeService _zipCodeService;

        public ZipCodeController(ZipCodeService zipCodeService)
        {
            _zipCodeService = zipCodeService;
        }

        [HttpGet]
        [TransactionFilter]
        public HttpResponseMessage GetLatLong(string zip5)
        {
            if (zip5.Length != 5)
                return Request.CreateResponse(HttpStatusCode.BadRequest, "Zip Code Length Not Equal to 5");

            var zip = _zipCodeService.GetByZip5(zip5);

            if (zip == null)
                return Request.CreateResponse(HttpStatusCode.NotFound, "Could not find Zip Code in Database");

            var latlong = new
            {
                Latitude = zip.Latitude,
                Longitude = zip.Longitude
            };

            return Request.CreateResponse(HttpStatusCode.OK, latlong);
        }
    }

}

A: Try adding Route as below
    [HttpGet]
    [TransactionFilter]
    [Route("api/GetLatLong")]
    public HttpResponseMessage GetLatLong(string zip5)
    {
        if (zip5.Length != 5)
            return Request.CreateResponse(HttpStatusCode.BadRequest, "Zip Code Length Not Equal to 5");

        var zip = _zipCodeService.GetByZip5(zip5);

        if (zip == null)
            return Request.CreateResponse(HttpStatusCode.NotFound, "Could not find Zip Code in Database");

        var latlong = new
        {
            Latitude = zip.Latitude,
            Longitude = zip.Longitude
        };

        return Request.CreateResponse(HttpStatusCode.OK, latlong);
    }

And then your route config would be as below
public static class WebApiConfig
{
    /// <summary>
    /// Register the http configuration for web API.
    /// </summary>
    /// <param name="config">The http configuration instances</param>
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional });

    }
}


text:
Q: Calling specific base method with multiple overloads and default parameters I'm building on top of the source code for a game and are trying to call a base virtual function with overloaded methods and default parameters. I cannot change the classes I'm deriving from and need to call the function inside my own class definition of the virtual method. I'll try to explain in more detail with code.
First we have a base class A that defines a virtual function called Foo that takes one argument.
class A
{
   public virtual string Foo(int a)
   {
      return "Class A Function 1 par";
   }
}

Then a class B that overrides Foo and defines a new overloaded virtual function for Foo with two new default parameters.
class B : A
{
   public virtual string Foo(int a, int b = 0, int c = 0)
   {
      return "Class B Function 3 par";
   }

   public override string Foo(int a)
   {
      return "Class B Function 1 par";
   }
}

Then the class I need to derive from, C. It simply overrides the one parameter Foo.
class C : B
{
   public override string Foo(int a)
   {
      return "Class C Function 1 par";
   }
}

Lastly my class D which also overrides the one parameter Foo but needs to be able to call the base method of Foo also.
class D : C
{
   public override string Foo(int a)
   {
      return base.Foo(0);
   }
}

This results in calling the three parameter Foo defined in B (returning as "Class B Function 3 par") but I want to call the Foo defined in C (would return "Class C Function 1 par"). I would think this sort of overloading of virtual functions with default parameters would cause an ambiguous compiler error but it compiles fine.
Is there a way to work around this and if not why is it allowing the structure of the classes to lock me out of accessing a base method?

A: This is an unfortunate interaction between optional parameters and the rest of the language, and a good reason why you should basically never overload methods that use optional parameters (or add overloads to methods that don't). The author of B has done something that's really bad!
The call isn't ambiguous, because the rules for method lookup don't change for base, only the rules for which method ends up invoked after overload resolution -- in effect, the overloads are determined as if the call had read ((C) this).Foo(0). For that call, B.Foo(int, int, int) is considered the only candidate because it is the nearest non-override method when walking up the inheritance chain -- it is picked before we even get to considering A.Foo(int). Had A introduced the method, there would have been no problem, as in that case the single-parameter overload would have been considered a better method.
Had optional parameters been part of C# from the start, rather than a relatively late addition to the party (with a bit of a quirky implementation where the values are expanded at the call site) this might have been considered and somehow mitigated. As it stands the most obvious way to fix this would be by actually changing the rules for base lookup so it prefers matching the methods that exactly match the signature of the method it occurs in, but that would just complicate the already complicated rules for overload resolution even more, and it can certainly break existing code, so the chances of something like that happening are slim.
If you can't change A, B and C there is still a way to write D to get the desired behavior, by exploiting (if that's the word) another fairly obscure C# feature that's even older: method groups!
class D : C
{
   public override string Foo(int a)
   {
      Func<int, string> foo = base.Foo;
      return foo(a);
   }
}

This unambiguously invokes C.Foo(int), because delegate conversions on method groups do not consider optional parameters, and thus B.Foo(int, int, int) is not a valid candidate, forcing us to go further up the chain and find A.Foo(int).


text:
Q: Create multidimensional array out of long string PHP Say I have a string like this:
all:ticket_location:is:5|||all:ticket_sub_location:is:1|||any:ticket_is:created:NULL|||any:ticket_is:updated:NULL|||action:assigned_agent_uid:admin

I need an array that looks something like this:
 array(
       [all] => Array
          (
              [ticket_location] => Array (
                                          [is]=>5
                                         )
              [ticket_sub_location] => Array (
                                              [is]=>1
                                              )
          )
       [any] => Array
          (
              [ticket_is] => Array (
                                     [created] => NULL
                                   )
              [ticket_is] => Array (
                                     [updated] => NULL
                                   )
          )
       [action] => Array
          (
              [assigned_agent_ui] => Admin
          )
)

This is my code so far but I'm failing miserably.  Hard for me to wrap my head around multidimensional arrays.
    $trigger_data = "all:ticket_location:is:5|||all:ticket_sub_location:is:1|||any:ticket_is:created:NULL|||any:ticket_is:updated:NULL|||action:assigned_agent_uid:admin";

    $parts = explode("|||",$trigger_data);
    $rules = array();
    $actions = array();
    foreach($parts as $value) {
        $pieces = explode(":",$value);
        if ($pieces[0] == "all" || $pieces[0] == "any") {
            $rules[$pieces[0]][$pieces[1]][$pieces[2]] = $pieces[3];
        }
        if ($pieces[0] == "action") {
            $actions[$pieces[0]][$pieces[1]] = $pieces[2];
        }

    }

    print_r($pieces);
    print_r($actions);
    exit;

A: Before anything else, you can't have both ticket_is keys in the same dimension inside any. Anyway, just use references, so that you can create your keys continually on the necessary depth, then use explode when needed:
$trigger_data = "all:ticket_location:is:5|||all:ticket_sub_location:is:1|||any:ticket_is:created:NULL|||any:ticket_is:updated:NULL|||action:assigned_agent_uid:admin";
$final = array();
foreach(explode('|||', $trigger_data) as $e) {
    $e = explode(':', $e);
    $result = &$final;
    $value = end($e);
    foreach($e as $parts) {
        if($value === $parts) {
            $result = $value;
        } else {
            $result = &$result[$parts];
        }

    }
}

print_r($final);

Out


text:
Q: GZipStream сжимает со степенью сжатия -150% Здравствуйте, уважаемые.
Понадобилось мне сжимать файлы. Использовал пример с MSDN для шарпа 3.5:
                    using (var origStream = new FileStream(info.FullName, FileMode.Open, FileAccess.Read)) {
                    using (var destStream = new FileStream(info.TempFullName + ".gz", FileMode.OpenOrCreate, FileAccess.Write)) {
                        using (var compressor = new GZipStream(destStream, CompressionMode.Compress)) {
                            var buffer = new byte[origStream.Length];
                            var count = origStream.Read(buffer, 0, buffer.Length);
                            compressor.Write(buffer, 0, count);
                        }
                    }
                }

Сжимает медленно довольно. Открываю результат, вижу: оригинальный файл - 1.7мб, "сжатый" файл - 2.8мб. В винраре смотрю - процент сжатия 150%.
Формат файлов на данный момент - PDF.
Что я делаю не так?
A: Такое вполне может случиться, если вы сжимаете маленькую картинку (jpeg) или музыку (mp3), в общем, любой файл, который уже пожат.
Допишите, какой тип файла вы сжимаете.


text:
Q: When are procedural queries absolutely necessary? I know that we tend to avoid cursors and loops within SQL Server at every cost, but what are some of the situations where you absolutely need procedural queries, and set-based queries just will not give you the results?
I understand the difference between the two, I just have never come to a situation where I need to use a cursor.  I'm wondering if there are such situations.

A: In my experiences, I've run into a few times when procedural/iterative approaches were warranted.
API only allows for single-row operation
If I wanted to programmatically change the data type from real to decimal in a table that has 500 mis-typed columns like this SO question asks, a cursor is a fine approach as the DDL does not allow for altering multiple columns in a single statement.
Set based doesn't scale
If you have the SQL Server MVP Deep Dives book, chapter 4 "Set-based iteration: the third alternative" by Hugo Kornelis has some great use cases for combined cursor/set based operations. Two of classic problems that the chapter author references is the Running Totals and Bin Packing.
I used the set-based iteration approach with good success for a poorly designed process I inherited at the last job. In short, there was a process that once a year had to update 50-75M rows and attempting to do so in a single set would blow our logs. By chunking the updates into smaller batches of N rows, it allowed the log to keep up and actually finished faster than the previous year when they just allocated a metric ton more disk space.

A: When something can't be done set based.
Bleeding obvious of course. But note there is difference in "not set based" and folk using a procedural solution because they don't understand sets or don't know how to do it with set based code.
One example of procedural code would be sending an email per row that has different content per row
A lot of SQL code for DBA use is procedural. For example, looping (CURSOR or WHILE: no difference) over databases and tables to rebuild indexes and update statistics.
Some SQL constructs allow row-by-row processing in the context of a set, such as CROSS APPLY like this on SO: SELECT TOP 5 rows for each FK (note the ROW_NUMBER() solution too though)
Edit: extending @billinkc's answer...
CROSS APPLY allows set based operations with UDFs that have a "single row API"

A: I know you are asking about SQL Server, but in the Oracle world (in the past), temporary tables had a very high cost, so cursor based procedures and triggers were quicker and lower "cost" to the server. In SQL Server, cursors used to have far higher cost than temp tables, so writing cursor based code was discouraged. I'm pretty sure these discrepancies have been eliminated in the past decade.
To cope with these situations, most people have a general rule to avoid putting business logic into the database. If you can absolutely totally always do that, then there won't be any reason for procedural logic in neither T-SQL nor PL/SQL. Relational databases are great at set-based logic. Most modern programming languages are great at procedural logic. It is best to use each one for what they are good at.
Some auditing triggers that I've worked with had rather complicated rules for what had to be checked, and where things had to be updated/logged. Some were for keeping reporting systems in sync with transactional systems (it wasn't my choice, but they wanted it that way). Some were for a formulary system. A formulary is a list of drugs, and for each insurance company, what they will/won't cover, and if prescribed drug_X what replacements are covered by insurance. It was also common for different group policies at the same insurance company to pay for different drugs.


text:
Q: Warning After updating to 2008R2 AD We added a new DC server yesturday and we are getting the following issue on the new machine only.
Log Name:      Application
Source:        SceCli
Date:          18/02/2010 11:30:44
Event ID:      1202
Task Category: None
Level:         Warning
Keywords:      Classic
User:          N/A
Computer:      **
Description:
Security policies were propagated with warning. 0x57 : The parameter is incorrect.
Advanced help for this problem is available on http://support.microsoft.com. Query for "troubleshooting 1202 events".
Event Xml:

    1202
    3
    0
    0x80000000000000

    565
    Application
    **

    0x57 : The parameter is incorrect.
Advanced help for this problem is available on http://support.microsoft.com. Query for "troubleshooting 1202 events".

We are running a 2003 R2 domain and have just added a new 2008 R2 DC. Updated the scheme and everything went well.
The new 2008 R2 DC seems to be running fine apart from this error.
looked in winlogon and found the follow error repeated
Error 50: The request is not supported.
 Configuring some user rights for this account is not supported. Re-attempting configuration by ignoring unsupported operation errors.
  remove SeChangeNotifyPrivilege.
Configuring SeChangeNotifyPrivilege for this account is not supported.
  remove SeImpersonatePrivilege.
Configuring SeImpersonatePrivilege for this account is not supported.
  remove SeCreateGlobalPrivilege.
Configuring SeCreateGlobalPrivilege for this account is not supported.
Any ideas?

A: I had a conflicting group policy


text:
Q: ERROR when referencing foreign key in table Im getting this error when creating a table "Oracle (ORA-02270) : no matching unique or primary key for this column-list error".
This is the first time creating tables, but Ive created a table let say customer order, which has a primary key of customer id and product Id.
create table customer_order(
    customerID NUMBER(8),
    productID Number(8),
    PRIMARY KEY (customerID, productID),
    FOREIGN KEY (customerID) REFERENCES Customer (customerID),
    FOREIGN KEY (productID) REFERENCES Product (productID));

So this the table i orginially created, however i need to create a new table that references the customer ID and product ID from this table. When I do so I get this error. Here is an example of the table I'm trying to create:
create table purchase_order(
    ID Number(8) PRIMARY KEY,
    ProductId Number(8),
    CustomerID Number(8),
    FOREIGN KEY (customerID) REFERENCES customer_order (customerID),
    FOREIGN KEY (productID) REFERENCES customer_order (productID));

A: The primary key is composite, so you need to reference them at the same time:
create table purchase_order(
    ID Number(8) PRIMARY KEY,
    ProductId Number(8),
    CustomerID Number(8),
    FOREIGN KEY (customerID, ProductId) REFERENCES customer_order(customerID, productId)
);


text:
Q: How to use the correct "FILTER HOOK" I would like to replace the image source in the code below:
$placeholder = apply_filters( 'rocket_lazyload_placeholder', 'data:image/gif;base64,R0lGODdhAQABAPAAAP///wAAACwAAAAAAQABAEACAkQBADs=' );

$html = sprintf( '<img%1$s src="%4$s" data-lazy-src=%2$s%3$s>', $matches[1], $matches[2], $matches[3], $placeholder );

$html_noscript = sprintf( '<noscript><img%1$s src=%2$s%3$s></noscript>', $matches[1], $matches[2], $matches[3] );

I've written this code to change it, but it's not working. What's wrong?
function add_change_image_lazyload ( $output ) {
    $output = 'http://example.com/image.svg';
    return $output;
}
add_filter( 'rocket_lazyload_placeholder', 'add_change_image_lazyload' );

A: The way to change the spinner/loading image is :
add_filter( 'rocket_lazyload_placeholder', function( $placeholder ) {
    $placeholder = 'your-spinner-url-here';
    return $placeholder;
} );

Code goes in your active theme/child functions.php


text:
Q: How to enable \Twig\Extension\DebugExtension The Twig documentation for dump() says:

The dump function is not available by default. You must add the \Twig\Extension\DebugExtension extension explicitly when creating your Twig environment:
$twig = new \Twig\Environment($loader, [
    'debug' => true,
    // ...
]);
$twig->addExtension(new \Twig\Extension\DebugExtension());

Even when enabled, the dump function won't display anything if the debug option on the environment is not enabled (to avoid leaking debug information on a production server).

I have no code anywhere that looks remotely like new \Twig\Environment. It's done automatically by Symfony, so how can I set \Twig\Extension\DebugExtension on it?


text:
Q: examples of non empty subsets Our linear algebra prof gave us this problem and I am not quite sure how to go about starting or what it is asking for.
Give an example of a nonempty subset $U$ in $R^2$ such that $U$ is closed under scalar multiplication,
but $U$ is not a linear subspace of $R^2$.

A: *

*The question is asking for a set $S$ of points in the plane $\mathbb{R}^2$. Examples of sets of points in $\mathbb{R}^2$ include: "the set of points on the unit circle", "two parallel lines", "sixteen disconnected points", "the x-axis", etc.

*The set $S$ is required to be closed under scalar multiplication, which means that  if you take any multiple of a point in $S$, the result is still in $S$.

*The set $S$ should be nonempty, which just means that it has to have at least one point in it to avoid trivial examples.

*A linear subspace is a set of points in $\mathbb{R}^2$ which has certain properties. One of those properties is that it must be closed under scalar multiplication. A linear subspace must satisfy several other required properties, though (closure under addition, for example.).

*To find a set $S$ which is closed under scalar multiplication but which doesn't qualify as a linear subspace, it's enough to find a set of points which is closed under scalar multiplication but which is missing one of the other required properties.

*It may help to think visually: if a set $S$ of points in $\mathbb{R}^2$ is closed under scalar multiplication, it means that you can pick any point in the set, and draw the line passing through that point and the origin. Every point along that line must also be in $S$.

A: This is what closed means in this context:
A subset $U \subseteq \mathbb{R}^2$ is said to be closed under scalar multiplication if the following holds:
$$\text{For every } \mathbf{x} \in U \text{ and } c \in \mathbb{R},\ c\mathbf{x} \in U$$
So he wants you to find a subset $U$ satisfying the above property but is NOT a subspace.
In this context, a subset $V\subseteq \mathbb{R}^2 $ is a subspace if:

*

*$\mathbf{0} \in V$

*V is closed under scalar multiplication

*If $\mathbf{x,y}\in V$, then $\mathbf{x}+\mathbf{y} \in V$
So you need to find a subset $U$ that satisfies #2 but fails to satisfy #1 or #3. Hint: Really it will be #3 as #2 implies #1 if $U$ is non-empty.


text:
Q: How to disable jupyter/ipython saving of intermediate (anonymous variables)? When you use Jupyter, you get these "numbered inputs & outputs" you can reference like this: _3. I'm the kind of guy who uses Jupyter like a nicer REPL with persistent code blocks & comments.
As time goes on, on long sessions, these kind of outputs start eating up memory, and then I have to restart the notebook and start all over.
I have NEVER in my life needed to reference these numbered variables (ok, maybe twice. Nothing I could not live without); so my question is: is there a way to disable them? Just to be clear: I still want to see my HTML-ified DataFrame, but I don't want the real df be saved into a variable named e.g. _143.


text:
Q: raphaeljs and freetransform with the combination of clip-path i am using Raphael and Elberts FreeTransform Plugin.
this is what i tried yet MyWork
My clip path works until i do not translate or rotate the set of rectangles, just after rotation or translation it stop working properly.
I want those rectangles inside the boundary of path, as soon as they go outside they should disappear.
The answer to why i am using javascript(manually) not Raphael for clippath, is , Raphael only supports clip rect.
i need your help to sort out this one.
thanks in advance

Update:1
  My Work 2
  I solve it for translation case but in rotation case it still disturbs all the set.

A: Please check this fiddle http://jsfiddle.net/UGukL/
I have tried the problem with clip, it was not working. So decided to work with mask.
            Also i havn't implemented the drag but keept buttons for translate and rotate.
            Now the masking is working fine for both rotation and translation.

A: Creating a new g tag(group) and moving all the elements to that group and then applying clip-path to g tag works. ClipPath doesn't recognize transform of attribute of element if applied to individual elems. So it should be wrapped in g for this.
It is applied Here