text:
Q: Ошибка при перекодировке из 1251 в UTF8 мне нужно перекодировать файл из Windows-1251 в UTF-8, во время перекодировки получаю ошибку UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc1 in position 0: invalid start byte и в точности такую же ошибку получаю при при переводе строки в 1251 и обратно в UTF-8, как это можно исправить, почему не желает перекодировать
x='Байты'.encode('utf8')
print(x)
x='Байты'.encode('windows-1251')
print(x)
x=x.decode()
print(x)

вывод
b'\xd0\x91\xd0\xb0\xd0\xb9\xd1\x82\xd1\x8b'
b'\xc1\xe0\xe9\xf2\xfb
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc1 in position 0: invalid start byte

A: DrawnRaccoon вам правильно написал, что метод decode по умолчанию использует кодировку UTF-8, а в переменной x на момент вызова хранятся байты в кодировке cp1251. Это несоответствие фактической и ожидаемой кодировки и приводит к ошибке.
x = 'Байты'.encode('utf8')
print(x)  # В переменной x хранятся байты в кодировке utf-8

x = 'Байты'.encode('windows-1251')
print(x)  # В переменной x хранятся байты в кодировке сp1251

x = x.decode('windows-1251')
print(x)

A: import os

filename = 'in.txt'
tmpfilename = filename + '.new'

with open(filename, "r", encoding='windows-1251') as fin:
    txt = fin.read()

with open(tmpfilename, "w", encoding='utf8') as fout:
    fout.write(txt)

os.remove(filename)
os.rename(tmpfilename, filename)


text:
Q: map operator [] and bool as value We know that if we try to access a nonexistent key of std::map with the operator [] , the function will insert a new element with that key.
We have: std::map<std::string, bool> map_xxx;
Is it guaranteed that after accessing the nonexistent key of map_xxx["nonexistent_key"], the value of the second argument will always be false ?
ps. if no, any ideas how to have this behavior?

A: Yes.  The value to be inserted is guaranteed to be false.

In C++98, the mechanism was called default initialization, specified as zero initialization for non-classes; that's false for Booleans.
Since C++03, the mechanism is called value initialization, still specified as zero initialization for non-classes; and thus still false for Booleans.  For example, let's see what C++14 has to say on this.
From §23.4.4.3; just substitute bool for "T".

T& operator[](const key_type& x);

*

*Effects: If there is no key equivalent to x in the map, inserts value_type(x, T()) into the map.

*Requires: key_type shall be CopyInsertable and mapped_type shall be DefaultInsertable into
  *this.

From §8.5, digest the paragraphs from the bottom up:

To zero-initialize an object or reference of type T means:
— if T is a scalar type (3.9), the object is initialized to the value obtained by converting the integer literal 0 (zero) to T;
...
To value-initialize an object of type T means:
— if T is a (possibly cv-qualified) class type (Clause 9) with either no default constructor (12.1) or a default constructor that is user-provided or deleted, then the object is default-initialized;
— if T is a (possibly cv-qualified) class type without a user-provided or deleted default constructor, then the object is zero-initialized and the semantic constraints for default-initialization are checked, and if T has a non-trivial default constructor, the object is default-initialized;
— if T is an array type, then each element is value-initialized;
— otherwise, the object is zero-initialized.
...
An object whose initializer is an empty set of parentheses, i.e., (), shall be value-initialized.

From §4.12:

A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. For direct-initialization (8.5), a prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.

redpajama_set_name: RedPajamaStackExchange


text:
Q: redimensionar uma imagem e depois salvar no mysql A partir de um formulário eu quero redimensionar uma imagem só depois e depois salvar no mysql, ou pegar uma imagem já salva no mysql e redimensioná-la e depois atualizar o registro. Agradeço imensamente se alguém puder me ajudar.
* a tabela no mysql  *
CREATE TABLE `imagemedias` (
  `id` int(11) NOT NULL,
  `imagem` mediumblob,
  `ImagemMimeType` varchar(20) DEFAULT NULL
)

*aqui é a classe *
namespace rsi.Entities
{
    public class ImageMedia : Auxiliar
    {
        public int Id { get; set; }
        public byte[] Imagem { get; set; }
        public string ImagemMimeType { get; set; }
    }
}

* aqui é o form *
<form action="/backend/Images/imagem" method="post" name="form" id="form1" accept-charset="utf-8" enctype="multipart/form-data">
    <input type="file" name="__file"  id="__file" accept="image/*">
    <input type="submit">
</form>

*aqui é o controller *
[HttpPost]
public ActionResult imagem(HttpPostedFileBase file)
{
    if (file != null)
    {
        ImageMedia imagem = new ImageMedia();
        imagem.Imagem = new byte[file.ContentLength];
        imagem.ImagemMimeType = file.ContentType;
        file.InputStream.Read(imagem.Imagem, 0, file.ContentLength);

        return RedirectToAction("Exibir", new { imagem.Id });
    }

    return null;
}

A: Tem um pacote para isso, mas acho que não é o que você quer. Tem uma outra forma de fazer que é mais simples, usando WebImage, mas a qualidade é menor.
Exemplo:
using System.Web.Helpers;

[HttpPost]
public ActionResult imagem(HttpPostedFileBase file)
{
    if (file != null)
    {
        ImageMedia imagem = new ImageMedia();
        imagem.Imagem = new byte[file.ContentLength];
        imagem.ImagemMimeType = file.ContentType;
        file.InputStream.Read(imagem.Imagem, 0, file.ContentLength);

        WebImage webimg = new WebImage(file.InputStream);
        webimg.Resize(100, 100); // Mude pro que você precisar
        // Escreva o resto da lógica para salvar aqui

        return RedirectToAction("Exibir", new { imagem.Id });
    }

    return View(); // Aquele null estava bem errado.
}

Para obter um stream:
var stream = new MemoryStream(webimg.GetBytes());


text:
Q: EventWaitHandle access denied .NET Standard 2.0 I am using a global EventWaitHandle to implement an inter-process handshake for a named pipe. The server (running as service with admin priviliges) opens the EventWaitHandle while the client checks for the open handle before connecting to the named pipe.
Using both with the same priviliges, its fine. Running the server as admin and client normal results in:
System.UnauthorizedAccessException: Access to the path 'Global\DEMO_CONNECTION_OPEN_HANDLE' is denied.
I am using .NET Standard 2.0. Hence, simple solutions such as EventHandleRights are not available. Is there any way to set access rights (e.g. while creating the handle) or elevate the client code for the EventWaitHandle only?
Example code server:
var handshakeHandle = new EventWaitHandle(false, EventResetMode.ManualReset,
    String.Format(@"Global\{0}", $"{ConnectionName.ToUpper()}_CONNECTION_OPEN_HANDLE"));

CreateServerPipe(ConnectionName);

handshakeHandle.Set();
await serverStream.WaitForConnectionAsync();
handshakeHandle.Reset();

Example code client:
// Results in Exception:
var handshakeHandle = EventWaitHandle.OpenExisting(
    String.Format(@"Global\{0}", $"{ConnectionName.ToUpper()}_CONNECTION_OPEN_HANDLE"));

CreateClientPipe(ConnectionName);

if (!handshakeHandle.WaitOne(millisecondsTimeout))
    throw new TimeoutException($"Cannot access within timeout.");

clientStream.Connect(millisecondsTimeout);

Any hint is much appreciated!
Edit: Any recommendation for a different approach than EventWaitHandle to implement an inter-process handshake is welcome.


text:
Q: Callback called on associated parent model I have a model Project that has many Reports (I'm shorthanding code here)...
Project
  has_many :project_reports
  has_many :reports, :through => :project_reports

ProjectReport
  belongs_to :project
  belongs_to :report

Report
  has_one :project_report
  has_one :project, :through => :project_report

I have a validation in Report that checks to make sure there isn't a report with the same date on it so I don't get duplicates with the same date in the scope of the project.
Validation
  unless self.project.reports.where(:report_date => self.report_date).empty?
    self.errors.add(:report_date, "report already exists for this date")
  end

When this validation is called in Report the callback after_update is called on Project instead of the callback in Report. Specifically this happens when I reference the project association. So even if I just do this...
Validation
  self.project

It calls after_save in Project instead of in Report. Any help or clarification would be appreciated. Thanks!


text:
Q: How to fix Git for Windows error: "could not lock config file C:/file/path/to/.gitconfig: File exists"? While trying to set up Git with my GitHub account the following error keeps persisting whenever I try to do a global config.
It works fine for repositories, but the global doesn't work.
Here's how it shows:
$ git config --global user.name "username"
error: could not lock config file C:/Path/to/.gitconfig: File exists

I'm using Git 2.21.0 on Windows 10 Pro.

A: Since you're on Windows 10, it could be an issue if your .gitconfig is located at C:.  If that's the case, try running your git bash with Administrator privileges (right-click on your executable, select More > run as Administrator) and see if that works. You need administrator privileges to work on files at the root of C:. That worked for me.

A: Check your folder where the .gitconfig file is located, and if there is a .gitconfig.lock file, delete it. I got the same error and this fixed it for me.

A: In other situation, If you don't have .gitconfig.lock file, there should be a config.lock file in .git folder of the repo.
You can delete this file and It will fixed this problem.


text:
Q: Only one user can log in at a time I have a class declaration, public abstract class CompanyHttpApplication : HttpApplication
In the CompanyHttpApplication I have
public static CompanyHttpApplication Current
{
    get { return (CompanyHttpApplication)HttpContext.Current.ApplicationInstance; }
}

and
public CompanyProfileInfo Profile
{
    get
    {
        return profile ?? (profile = ProfileManager
            .FindProfilesByUserName(ProfileAuthenticationOption.Authenticated,
                 User.Identity.Name).Cast<CompanyProfileInfo>().ToList().First());
    }

    private set { profile = value; }
}

Whenever I access the user:
CatapultHttpApplication.Current.Profile.UserName

it gets whoever is logged in last. I understand why (because it's in the application instead of the session), but I don't know how to change it. What can I do to change it so it uses the session instead of the application?


text:
Q: How to create a list from existing list in python I am having a list in below format. How can i create another list from the existing one with just selected elements.
[{'UserDiscount': 0.0, 'CostTotalInvEOPAmount': 940.0, 'WeekEndingData': u'2016-10-08', 'WeeksOnHand': 0.0, 'UnitTotalInvEOPQuantity': 250.0, 'WeeksOfSales': 0.0, 'UnitCostAmount': 3.76, 'Week': u'2016 Wk 36', 'CostReceiptAmount': 940.0, 'UnitSalesQuantity': 0.0, 'UnitReceiptQuantity': 250.0, 'Demand': 0.0, 'InventoryBOP': 0.0, 'PEMDiscount': 0.0, 'ElasticLift': 0.0, 'StoreCount': 0, 'PriceStatus': 4, 'UnitOnOrderQuantity': None, 'ReceiptSizeContributions': [{u'sizeId': u'e1656ac7-1cc1-40ce-b485-989bba9d758d', u'contribution': 1.0}], 'CostSalesAmount': 0.0, 'LifeCycleProperties': {u'IsAtRegularPrice': False, u'IsAtMarkdown': False, u'IsFinished': False, u'IsPreSeason': True}, 'MardownDiscount': 0.0, 'RecommendedReceipt': 250.0, 'RecommendedReceiptSizeContributions': [{u'sizeId': u'e1656ac7-1cc1-40ce-b485-989bba9d758d', u'contribution': 1.0}], 'UnitTotalInvBOPQuantity': 0.0, 'CostOnOrderAmount': None, 'InventoryEOP': 250.0, 'CostTotalInvBOPAmount': 0.0, 'Receipt': 250.0, 'Sales': 0.0, 'LostSales': 0.0, 'TotalDiscount': 0.0, 'RetailSalesAmount': 0.0},
 {'UserDiscount': 0.0, 'CostTotalInvEOPAmount': 940.0, 'WeekEndingData': u'2016-10-15', 'WeeksOnHand': 0.0, 'UnitTotalInvEOPQuantity': 250.0, 'WeeksOfSales': 15.784951285314385, 'UnitCostAmount': 3.76, 'Week': u'2016 Wk 37', 'CostReceiptAmount': 0.0, 'UnitSalesQuantity': 0.0, 'UnitReceiptQuantity': 0.0, 'Demand': 0.0, 'InventoryBOP': 250.0, 'PEMDiscount': 0.0, 'ElasticLift': 0.0, 'StoreCount': 0, 'PriceStatus': 4, 'UnitOnOrderQuantity': None, 'ReceiptSizeContributions': [], 'CostSalesAmount': 0.0, 'LifeCycleProperties': {u'IsAtRegularPrice': False, u'IsAtMarkdown': False, u'IsFinished': False, u'IsPreSeason': True}, 'MardownDiscount': 0.0, 'RecommendedReceipt': 0.0, 'RecommendedReceiptSizeContributions': [], 'UnitTotalInvBOPQuantity': 250.0, 'CostOnOrderAmount': None, 'InventoryEOP': 250.0, 'CostTotalInvBOPAmount': 940.0, 'Receipt': 0.0, 'Sales': 0.0, 'LostSales': 0.0, 'TotalDiscount': 0.0, 'RetailSalesAmount': 0.0}]

My new list will having below elements.
[{'UserDiscount': 0.0, 'CostTotalInvEOPAmount': 940.0, 'WeekEndingData': u'2016-10-08', 'WeeksOnHand': 0.0, 'UnitTotalInvEOPQuantity': 250.0, 'WeeksOfSales': 0.0, 'UnitCostAmount': 3.76, 'Week': u'2016 Wk 36', 'CostReceiptAmount': 940.0, 'UnitSalesQuantity': 0.0, 'UnitReceiptQuantity': 250.0, 'Demand': 0.0, 'InventoryBOP': 0.0, 'PEMDiscount': 0.0, 'ElasticLift': 0.0, 'StoreCount': 0, 'PriceStatus': 4, 'UnitOnOrderQuantity': None, 'CostSalesAmount': 0.0,  'RecommendedReceipt': 250.0, 'RetailSalesAmount': 0.0},
 {'UserDiscount': 0.0, 'CostTotalInvEOPAmount': 940.0, 'WeekEndingData': u'2016-10-15', 'WeeksOnHand': 0.0, 'UnitTotalInvEOPQuantity': 250.0, 'WeeksOfSales': 15.784951285314385, 'UnitCostAmount': 3.76, 'Week': u'2016 Wk 37', 'CostReceiptAmount': 0.0, 'UnitSalesQuantity': 0.0, 'UnitReceiptQuantity': 0.0, 'Demand': 0.0, 'InventoryBOP': 250.0, 'PEMDiscount': 0.0, 'ElasticLift': 0.0, 'StoreCount': 0, 'PriceStatus': 4, 'UnitOnOrderQuantity': None,  'CostSalesAmount': 0.0, 'RecommendedReceipt': 0.0, 'RetailSalesAmount': 0.0}]

A: You have a list with two dictionaries. To filter the dictionaries you can try
    keep=[key1,key2] #keys you wanna keep
    newList = []
    for item in mylist:
        d = dict((key,value) for key, value in item.iteritems() if key in keep)
        newlist.append(d)
    del mylist

Also using funcy you can do a
   import funcy
   mydict={1:1,2:2,3:3}
   keep=[1,2]
   funcy.project(mydict,keep)
=> {1: 1, 2: 2}

which is much prettier imho.

A: You could use the list comprehension https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions
[l for l in your_list if l['UserDiscount'] >= 1 ]
[{'UserDiscount': l['UserDiscount'],'CostTotalInvEOPAmount': l['CostTotalInvEOPAmount']}  for l in your_list ]

Using this way you can filter the elements in your list and change the structure of your dicts in the list


text:
Q: Why don't languages that have big integer support have unsigned versions? A cursory glance at C#, Java, and other languages indicates this is not a feature that's required. I tried searching for justification for this maybe from a language design team or blog, but I haven't found anything that explains why such a type is ignored.
My current best guess is applications that use big integers wouldn't save or see noticeable performance benefits so it's left out.
Are there any languages that do support both signed and unsigned big integers? Is there any written justification or mailing list posts that describe why or why not such a feature was added or not included?

A: The original reason to have unsigned integers in a language in the first place is to extend the numeric range of a fixed-size type upwards at the cost of limiting it downwards. Beneficial effects such as sane semantics of bitwise operations (in C) or implicit enforcement of a non-negative constraint are not the primary reason.
Big integers do not have the problem of insufficient range, because they grow as needed, and saving that one bit is just not worth it.

A: If you have a use case where you never have to deal with negative numbers inside of any big integer calculation, then you could use the signed big integers implementation as well, and your performance guess is what I would expect, too, the performance differences would most probably be negligible.
If you have a use case where negative intermediate results can occur, but you want them to "wraparound" to some positive value, then in a big integer context it is not inherently clear what the result should be. For example, the outcome of "4 -5" in a 32 bit unsigned integer context is typically "2^32-1" (as long as your environment does not throw an underflow error). What should it be in a context where there is no such upper limit of 32 for the number of bits?
That makes it hard to create a useful specification of how general purpose unsigned big integer should work, assumed one wants to make this a universally useful too.
Of course, this problem could be solved by introducing an artificial, configurable "maximum bitsize" into the unsigned big integer implementation, and I would be astonished if not someone somewhere in the past had implemented such a thing. However, I think authors of widely used general purpose libraries or languages will think twice if implementing such a specific requirement is worth the hassle and if there will be enough applications to justify the additional development and testing effort.

A: One of the key advantages with a (for example) 32 bit unsigned integer versus a 32 bit signed integer is overflow. Fixed precision unsigned integers operate via 2n arithmetic, a specialized form of clock arithmetic. While this may be counterintuitive, it cannot overflow. Fixed precision signed integers, on the other hard, pretend to operate via the standard rules of arithmetic we learned as children. Sometimes this pretending fails.
This advantage disappears with extended precision arithmetic. Extended precision implementations successfully use the elementary rules we learned as children, to within the limits of computer memory. On the other hand, the clock arithmetic used in fixed length unsigned integers make no sense in extended precision arithmetic. The sum of two well-implemented bignums is a bigger bignum. The only risk is running out of memory. The difference between a pair of bignums also is not a problem. Clock arithmetic makes no sense in the domain of extended precision arithmetic.


text:
Q: How to delete an In-App product from Google Play Store Developer Console I have accidentally input In-App product on Google Play Store with an incorrect id. The inputted id is already associated with another product (That i have to enter in my In-App products list).
Google's Developer Console is not displaying any delete button in the In-App Products section.
Is there any way i can Delete the inputted Product ?
Any help is highly appreciated.

A: Yes, you can delete that and its simple. You need to click on product to and go to details of that product. Then click on product status active and you can see two options deactivate and delete. Select delete.
Note: You can't reuse any deleted item again.


text:
Q: How do I check if a number lies between two members of a mathematical progression? e.g. A.P., G.P. or any other progression I want to  assign a level to a number as below:
If a number lies between 3 and 3+3^2  Level should be 2.
If a number lies between 3+3^2 and 3+3^2+3^3  Level should be 3.
If a number lies between 3+3^2+3^3 and 3+3^2+3^3+3^4  Level should be 4.
....
And so on...
I am trying this..
var level = (next_slot>3 && next_slot < 3+3**2)?1:(
                      (next_slot>3+3**2 && next_slot < 3+3**2+3+3**3)?2:(
                        next_slot>3+3**2+3**3 && next_slot < 3+3**2+3+3**3)?3:(
                          4
                      ))

Which seems complex and also there is no limit to it.
Is there any better way to solve this in javascript?

A: Use logarithm, Luke:
level = Math.ceil(Math.log(x) / Math.log(3))

A: One solution would be to make a for loop with some max constant and then exit when you find that you're in between the values

const checkLevel = function(number) {
  if (number <= 0) {
    return 0 // failsafe since 3^0 is 1
  }

  const max = 10

  for (let i = 0; i < max; i++) {
    let low = Math.pow(3,i)
    let high = Math.pow(3,(i+1))
    console.log('our low is ' + low + ' and our high is ' + high)
    console.log('lets check if ' + number + ' is between')

    if (number >= low && number < high) {
      console.log('it matches')
     return i+1
    } else {
      console.log('no match, lets continue')
    }
  }
}

const level = checkLevel(4)

console.log('level',level)

What we are doing here is:

*

*Start from 0

*Create our low value 3^0

*Create our high value 3^1

*Check if our number is between

*Return it if that's the case

*Otherwise continue

Next it will check 3^1 and 3^2 and so forth

A: From your latest edit it looks like this is no longer possible to do with logarithms, so you will need to count up instead:
function findLevel(input) {
    let level = 1;
    let limit = 3;
    let increment = 3*3;

    while (input > limit) {
        ++level;
        limit += increment;
        increment *= 3;
    }

    return level;
}

You didn't specify the behaviour for the limits themselves, i.e. whether 3 belongs to level 1 (the 0-3 range) or 2 (the 3-12 range). This assumes that it belongs to the lower level, i.e. 3 is on level 1 not 2. Change input > limit to input >= limit if that's incorrect, i.e. 3 is on level 2.
// Print the inclusive integer ranges for each level
let lastLevelStart = 0;
let lastLevel = findLevel(lastLevelStart);
for (let i = 1; i <= 10000; ++i) {
    let level = findLevel(i);
    if (level != lastLevel) {
        console.log(`level ${lastLevel}: ${lastLevelStart} to ${i-1} inclusive`);
        lastLevel = level;
        lastLevelStart = i;
    }
}

level 1: 0 to 3 inclusive
  level 2: 4 to 12 inclusive
  level 3: 13 to 39 inclusive
  level 4: 40 to 120 inclusive
  level 5: 121 to 363 inclusive
  level 6: 364 to 1092 inclusive
  level 7: 1093 to 3279 inclusive
  level 8: 3280 to 9840 inclusive

This obviously takes the output level number of loops to compute, and when reused will end up repeatedly computing the same limit values over and over again (albeit using integer maths only, so relatively cheaply). So if you call this a very large number of times or need to deal with more than a small number of levels then you may want to compute the upper bounds for the first 1000 levels (say) into an array and then just scan that to find the level, or even binary search that array to find the answer in a more constant time (checking first that the input is <= the top precomputed value, and falling back to this method if not).


text:
Q: How to connect an odbc database to my java code? I need to connect an odbc database to my java code.
I know that for connecting mdb database I need to use this code but it doesn't work:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// set this to a MS Access DB you have on your machine
String filename = "C:/porogram/pro.mdb";
String database = "jdbc:odbc:Driver={Microsoft Access Driver(*.mdb)};DBQ=";
database+= filename.trim() + ";DriverID=22;READONLY=true}"; // add on to the end
// now we can get the connection from the DriverManager
Connection con = DriverManager.getConnection( database ,"","");
Statement s = con.createStatement();

Thank you very much.

A: Currently I'm working with jdbc-odbc bridge and this my code works for me at 100%:
this.jdbcUser = PropUtil.getValue(configFile, "jdbc.user");
this.jdbcPass = PropUtil.getValue(configFile, "jdbc.pass");
this.jdbcUrl = PropUtil.getValue(configFile, "jdbc.url");
this.jdbcDriver = PropUtil.getValue(configFile, "jdbc.driver");

//Be sure to load required JDBC driver
Class.forName(jdbcDriver);
dbconn = DriverManager.getConnection(jdbcUrl, jdbcUser, jdbcPass);

Properties file:
jdbc.user=db_user
jdbc.pass=db_pass
jdbc.url=jdbc\:odbc\:Driver={Microsoft Access Driver (*.mdb)};DBQ=C\:/Data/data1.mdb
jdbc.driver=sun.jdbc.odbc.JdbcOdbcDriver

Please share more info about your problem like stacktrace or whatever.


text:
Q: Alternative proof to $(b'd)^2\leq (b'b)(d'd)$
Let $b$ and $d$ be any two $p\times 1$ vectors. Show that
  $$(b'd)^2\leq (b'b)(d'd)$$ with equality if and only if $b=cd$.

I get this proof from the book.
Let $b-xd$ where $x$ is an scalar. Since the length of $b-xd>0$ for $b-xd\neq 0$
$$0<(b-xd)'(b-xd)=b'b-xd'b-b'xd+x^2d'd$$
$$=b'b-2x(b'd)+x^2(d'd)$$
since the expression is a quadratic form in $x$
$$0<b'b-\frac{(b'd)^2}{d'd}+\frac{(b'd)^2}{d'd}-2x(b'd)+x^2(d'd)$$
$$=b'b-\frac{(b'd)^2}{d'd}+(d'd)\Big(x-\frac{b'd}{d'd}\Big)^2$$
choosing $x=\frac{b'd}{d'd}$
$$0<b'b-\frac{(b'd)^2}{d'd}$$
Then $(b'd)^2<(b'b)(d'd)$ if $b\neq xd$ for some $x$.
Note that if $b=cd$ then $0=(b-cd)'(b-cd)$ and the same argument produces $(b'd)^2=(b'b)(d'd)$
Is there any proof more intuitive? I didn't get the idea of using $b-xd$ to proof. In the last steps I see that work, but I don't understood what is the idea behind.


text:
Q: Debugging PHP Mail() and/or PHPMailer I'm quite stuck with a problem sending mail from a PHP script.
Some data:

*

*Shared hosting, no SSH access, only hosting provider panel

*PHP version 5.2.5

*Last year I built a site which had no problems sending mail with the same hosting

*Let's say the domain is "domain.com" and my private address is "myaddress@mydomain.com" for anonimity's sake in the following code.

Here's the code:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);

$to = "myaddress@mydomain.com";
$subject = "Hi";
$body = "Test 1\nTest 2\nTest 3";
$headers = 'From: info@domain.com' . "\r\n" .
    'errors-to: myaddress@mydomain.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

if (mail($to, $subject, $body, $headers)) {
    echo("Message successfully sent");
} else {
    echo("Message sending failed");
}

require('class.phpmailer.php');
$message = "Hello world";
$mail = new PHPMailer();
$mail->CharSet = "UTF-8";
$mail->AddAddress("myaddress@mydomain.com", "Agos");
$mail->SetFrom("info@domain.com","My Site");
$mail->Subject = "Test Message";
$mail->Body = $message;
$mail->Send();
?>

And here is what I get:

Message sending failed
  Could not instantiate mail function.

Which is baffling to say the least. Is there anything I can do to get at least some more meaningful errors? Why is code from the class showing up in my file?

A: It looks like the class.phpmailer.php file is corrupt. I would download the latest version and try again.
I've always used phpMailer's SMTP feature:
$mail->IsSMTP();
$mail->Host = "localhost";

And if you need debug info:
$mail->SMTPDebug  = 2; // enables SMTP debug information (for testing)
                       // 1 = errors and messages
                       // 2 = messages only


text:
Q: Add a dynamic property to a Mongoose result with _.each I want to dynamically add a property to each object of a Mongoose result, but it won't work as expected.
Font.find()
.exec(function (err, fonts) {

    if(err) return res.send(err);

    _.each(fonts, function(item, i) {
        item.joined_name = item.name + item.style.replace(/\s/g, '');
        console.log(item.joined_name); // works fine
    });

    res.send(fonts); // `joined_name` property is nonexistant
});

Must be simple, but I can't figure out why. Alternatives are welcome!

A: Mongoose documents don't allow adding properties. You need to either call the lean() method before exec() since documents returned from queries with the lean option enabled are plain javascript objects.
From the docs:
Font.find().lean().exec(function (err, docs) {
    docs[0] instanceof mongoose.Document // false
});

So your code should look like:
Font.find()
    .lean()
    .exec(function (err, fonts) {
        if(err) return res.send(err);

        _.each(fonts, function(item, i) {
            item.joined_name = item.name + item.style.replace(/\s/g, '');
            console.log(item.joined_name); // works fine
        });

        res.send(fonts);
    });

or cast the returned document to a plain object:
Font.find()
    .exec(function (err, docs) {
        if(err) return res.send(err);
        var fonts = [];
        _.each(docs, function(item, i) {
            var obj = item.toObject();
            obj.joined_name = obj.name + obj.style.replace(/\s/g, '');
            console.log(obj.joined_name);
            fonts.push(obj);
        });

        res.send(fonts);
    });


text:
Q: Python Scrape Images From a Slideshow I am trying to scrape images from the home page of my school's website. But the catch is that these images are present in a slideshow. There are 9 images in total in the slideshow and I want to scrape all of them. I have no clue how I have to go about it, because all I can do with requests is to scrape the first image of it. And I don't want to use selenium because it is very slow. How can I scrape all images from the slideshow just by using requests and BeautifulSoup? Any help would be appreciated. Thanks!
P.S: I know that I have to provide the code that I have written so far, but the problem is that I haven't tried out anything so far as I really have no idea how to go about it, because this is the first time I am scraping images from a slideshow, so please forgive me. Plus, I already went through the answers for this question, but I didn't know how to implement the answer in my program.

A: To get the 9 images in the slider, you can use this example:
import requests
from bs4 import BeautifulSoup

url = 'http://www.buddingmindsinternationalschool.com/'
soup = BeautifulSoup(requests.get(url).content, 'html.parser')

for img in soup.select('#rev_slider_2_1 img'):
    print(img['src'])

Prints:
http://www.buddingmindsinternationalschool.com/wp-content/uploads/2017/11/banner-4.jpg
http://www.buddingmindsinternationalschool.com/wp-content/uploads/2017/11/banner-2.jpg
http://www.buddingmindsinternationalschool.com/wp-content/uploads/2017/11/banner-7.jpg
http://www.buddingmindsinternationalschool.com/wp-content/uploads/2017/10/bannerfour.jpg
http://www.buddingmindsinternationalschool.com/wp-content/uploads/2017/11/bannerseven.jpg
http://www.buddingmindsinternationalschool.com/wp-content/uploads/2017/11/bannerfives-1.jpg
http://www.buddingmindsinternationalschool.com/wp-content/uploads/2017/11/banner-5.jpg
http://www.buddingmindsinternationalschool.com/wp-content/uploads/2017/11/bannereight.jpg
http://www.buddingmindsinternationalschool.com/wp-content/uploads/2017/11/banner-6.jpg

A: Try this:
import requests
from bs4 import BeautifulSoup

url = "http://www.buddingmindsinternationalschool.com/"
soup = BeautifulSoup(requests.get(url).content, "html.parser")

for tag in soup.select(".rev-slidebg"):
    img_name = tag['src'].split('/')[-1]

    with open(img_name, "wb") as f:
        req = requests.get(tag['src'])
        f.write(req.content)


text:
Q: How to iterate a row and compare with each other? For example, if the name 'Mark' is repeated and if the 'Age' value or 'Gender' value is different when compared to other rows which contain 'Mark', then such columns must be removed.
Code for creating dataframe:
df = pd.DataFrame({'Name' : ['Mark', 'Mark', 'Mark', 'Mark', 'Mark', 'Nick', 'Nick', 'John', 'Sunny', 'Sunny'],
                  'Age' : ['22', '22', '25', '25', '17', '20', '20', '17', '23', '23'],
                  'Gender' : ['F', 'F', 'F', 'F', 'F', 'F', 'F', 'M', 'M', 'M']})

The dataframe is below:
       Name   Age   Gender
0      Mark   22    F
1      Mark   22    F
2      Mark   25    F
3      Mark   25    F
4      Mark   17    F
5      Nick   20    F
6      Nick   20    F
7      John   17    M
8      Sunny  23    M
9      Sunny  23    M

The expected output is:
       Name   Age   Gender
0      Nick   20    F
1      Nick   20    F
2      John   17    M
3      Sunny  23    M
4      Sunny  23    M

For example in the 1st and 2nd rows Name is Mark and Age is 22 and Gender is F. Whereas in 3rd-row Name is Mark, Age is 25 and Gender is F, we can see Age has multiple values, then we have to remove rows which contains Mark

A: OK, this is tricky, so I'll explain each line.
import pandas as pd

df = pd.DataFrame({'Name' : ['Mark', 'Mark', 'Mark', 'Mark', 'Mark', 'Nick', 'Nick', 'John', 'Sunny', 'Sunny'],
                  'Age' : ['22', '22', '25', '25', '17', '20', '20', '17', '23', '23'],
                  'Gender' : ['F', 'F', 'F', 'F', 'F', 'F', 'F', 'M', 'M', 'M']})

print(df)

# First, drop all the rows that are exact duplicates of each other.

df1 = df.drop_duplicates()
print(df1)

# If any rows that remain have a duplicate name, those need to go.

df2 = df1.duplicated('Name')
print(df2)

# Go build a DF with just the names that were duplicated.

df3 = df1[df2]['Name']
print(df3)

# Find all the rows in the original df that have a name in this list,
# invert that set, and the result is what we want.

df4 = df[~df.Name.isin(df3)]
print(df4)

Several of those operations can be combined to make a one-liner, but I think this makes it more clear.  I've added blank lines to separate the dataframes in the output.
Output:
    Name Age Gender
0   Mark  22      F
1   Mark  22      F
2   Mark  25      F
3   Mark  25      F
4   Mark  17      F
5   Nick  20      F
6   Nick  20      F
7   John  17      M
8  Sunny  23      M
9  Sunny  23      M

    Name Age Gender
0   Mark  22      F
2   Mark  25      F
4   Mark  17      F
5   Nick  20      F
7   John  17      M
8  Sunny  23      M

0    False
2     True
4     True
5    False
7    False
8    False
dtype: bool

2    Mark
4    Mark
Name: Name, dtype: object

    Name Age Gender
5   Nick  20      F
6   Nick  20      F
7   John  17      M
8  Sunny  23      M
9  Sunny  23      M

A: A one-liner answer:
df[df.Name.isin((s:=df.drop_duplicates().groupby(['Name']).size().eq(1)).index[s])]

results in:
    Name Age Gender
5   Nick  20      F
6   Nick  20      F
7   John  17      M
8  Sunny  23      M
9  Sunny  23      M

Perhaps worth noting: the walrus-operator does still allocate memory for a variable s that Python's garbage-collector will eventually de-allocate. If you would need a Series representing whether any Name has different rows, as in below, then it'd be worth explicitly assigning it.
>>> s
Name
John      True
Mark     False
Nick      True
Sunny     True
dtype: bool

anywhere else in your calculations, it's likely worth explicitly assigning it to a variable to which you maintain a reference.

Explanation:
# from the OG df
df[
   # boolean mask if the name is in
   df.Name.isin(
                # walrus-operator to temporarily hold result
                # drop the duplicate rows (duplicates name + age + gender)
                (s:=df.drop_duplicates()
                       # group on Name
                       .groupby(['Name'])
                       # after dropping duplicates, there's only one record
                       # i.e. no different age/gender records for same name
                       .size().eq(1))
                # mask on names where no-duplicates is true, drop names where false
                ).index[s]
               # pass as series to `df.Name.isin`
               )
  ]


text:
Q: Get magento2 categories with restsharp rest API I'm pretty new to magento restsharp Rest API. I just managed to get an admin access token. The next step for me is to receive te magento categories but I don't really get the way of working with the rest api commands. I think I need to use this one: GET    /V1/categories
I just don't know how to use it. I would really appreciate it if somebody could help me out with this.
Maybe good to know:
Visual Studio 2017
Rest API
C# (restsharp)
oauth2
magento 2
I don't know how to use the admin token I receive at the end of the static void.
my code thus far:
static void Main(string[] args)
        {
            //Base URL needs to be Specified
            String host = "http://beta.topprice24.com";
            //Relative URL needs to be Specified
            String endpoint = "/rest/default/V1/integration/admin/token";

            RestClient _restClient = new RestClient(host);
            var request = new RestRequest(endpoint, Method.POST);

            //Initialize Credentials Property
            var userRequest = new Credentials { username = "blabla", password = "blabla" };
            var inputJson = JsonConvert.SerializeObject(userRequest);

            //Request Header
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Accept", "application/json");
            //Request Body
            request.AddParameter("application/json", inputJson, ParameterType.RequestBody);

            var response = _restClient.Execute(request);

            var token = response.Content;
        }

        public void getCategories()
        {
            String host = "http://beta.topprice24.com";
            String endpoint = "/rest/V1/categories";
            String token = "Bearer " + magento acces token?;

            RestClient restClient = new RestClient(host);

            var request = new RestRequest(endpoint, Method.GET);
            request.AddHeader("Authorization", token);
            var rawResponse = restClient.Execute(request);
            var responseBody = rawResponse.Content;
        }

A: Updated the answer based on the updated question code:
Modified Code:
  public String getCategories(String adminToken)
    {
        String host = "http://beta.topprice24.com";
        String endpoint = "rest/V1/categories";
        String token = "Bearer " +adminToken;

        RestClient restClient = new RestClient(host);

        var request = new RestRequest(endpoint, Method.GET);
        request.AddHeader("Authorization", token);
        var rawResponse = restClient.Execute(request);
        return rawResponse.Content;
    }

In your main function you can call the method as below
Modified Main Function:
        request.AddParameter("application/json", inputJson, ParameterType.RequestBody);
        var response = _restClient.Execute(request);

        var token = response.Content;
        var categoriesResult=getCategories(token);
        Console.WriteLine("Categories List :" + categoriesResult);


text:
Q: Is there any support for mouse wheel and Apple track-pad in Silverlight 5? One of my Silverlight applications has some users to use it on Apple Macs. They complain that the mouse wheel and track-pad don't work.
From the research I've done, it seems that this isn't supported in browser-hosted applications on Macs.
Does Silverlight 5 add improved support? Is it on Microsoft's radar for a future version of Silverlight?

A: While my initial thought was that it works in 4 and 5, I elected to test it again under the silverlight 5 beta.
Mousewheel scrolling does not seem to work for scrollviewers or similar.  I can't test the trackpad, as I don't have a mac laptop.

A: In fact I noticed the exact same issue during a recent demo to some partners. Using the trackpad, they were unabled to perform deepzoom zooming.
I am however quite sure it worked before. Therefore, it looks like a Mac Os (or Safari) update broke this Feature. It's a good thing: Mouse wheel and trackpad support on MacOs are on Silverlight features list, MS will normally correct the issue, maybe for the next release (I suggest to cross our fingers)


text:
Q: Go get private bitbucket repo giving 403 forbidden On execution of
go get bitbucket.org/../..
I get this error
yash.jain projectname % go get bitbucket.org/../..
go: bitbucket.org/../..
https://api.bitbucket.org/2.0/repositories/../..?fields=scm: 403 Forbidden
go: error loading module requirements

What I tried

*

*Setup the ssh key (Working as expected, tested by pushing and pulling the code)

*Set the go env variables to this:
 GOPRIVATE=""
 GOPROXY="direct"
 GOSUMDB="off"

*.gitconfig looks like this
 [url "git@bitbucket.org:"]
     insteadOf = https://bitbucket.org/
 [user]
     email = yash.jain@company.in
     name = yashjain

*Added keys to ssh-agent
 ssh-add -l
 ssh-add -k

*.ssh/config file looks like this
 Host bitbucket.org
   HostName bitbucket.org
   User git
   IdentityFile ~/.ssh/id_rsa
   UseKeychain yes
   StrictHostKeyChecking no

Still, I get the same error.
Please let me know If I'm doing something wrong.

A: These are the steps I tried to make it work.

*

*Setup SSH key and connect to bitbucket. I used sourcetree gui by bitbucket to connect using ssh.

*Set the GOPRIVATE=bitbucket.org/<orgname>/*
* is to allow all the repo of the org.
After these 2 steps I am able to import the package.

Note: Sourcetree is only available to Mac and Windows.

Using Commnd Line: For Linux/Mac/Windows:

*

*git config --global url."git@bitbucket.org:".insteadOf "https://bitbucket.org/"

*Set the GOPRIVATE=bitbucket.org/<orgname>/*

Update
You might receive the 404 error even after above configuration.
Error
reading https://api.bitbucket.org/2.0/repositories/xyz/privaterepo?fields=scm: 404 Not Found

Bitbucket recently update their APIs for private repository and due to which certain golang version breaks.

Users who do not have access to a private repository will receive 404 (not found) response codes instead of 403 (forbidden) response codes to mask the existence of a private repository at a given URL path.
Rolling out these changes will break previous versions of Go due to the fact that the go command relies on a 403 response to fetch repositories hosted on Bitbucket Cloud.
To ensure that you will not run into any issues, update GoLang to the latest version.

*

*Ensure you are on a supported version of GoLang: 1.18, 1.17, or 1.16.

*If you are using 1.17 or 1.16, ensure you are on the latest patch (1.17.7 or 1.16.14)

This will be in effect from June 1st 2022.
Changes to Bitbucket API Requires Latest Version of Go

A: There are Two ways I normally resolve this. But, for this you need to configure bitbucket with SSH.
1. Edit git.config
edit the global .gitconfig
nano /home/user/.gitconfig
add following lines
[url "git@bitbucket.org:"] insteadOf = https://bitbucket.org/

2. Export GOPRIVATE
export GOPRIVATE=bitbucket.org/<your repo>

A: Check first what ssh -Tv git@bitbucket.org returns, specifically the user mentioned in the Welcome message: it could be an account, which does not have access to the private repository.
As mentioned in "What's the proper way to "go get" a private repository?", try also with a private ssh key not protected by a passphrase, to make sure there is no prompt for said passphrase in the middle of the go get process.

A: you can do it via Sourcetree as well. follow the steps below:

*

*Download and install Sourcetree

*configure your bitbucket ssh key in Sourcetree inside connection

*You will be able to see your account in accounts section. Something like below

*Next step is to add your GOPRIVATE env variable

*for that run this command

go env -w GOPRIVATE="bitbucket.org/<repo>/*"


text:
Q: how to get text instead of value-php and wordpress I need help in getting the text instead of value.
I have gone through all the websites some of them says use javascript into this.
This is the plugin.(si contact form)
Here if i do $_POST it gives [array([0]=>1)] only value not text.
Below is the code i have searched where they are framing.
$string .= '<option value="' . $opts_cnt.'  "' . $selected . '>'.esc_attr($opt).'</option>'."\n";

$opts_cnt ----->value
$esc_attr($opt)-------> text
i tried changing this way
$string .= ' <option value="' . $opts_cnt.' "." '.esc_attr($opt).' "' . $selected . '>'.esc_attr($opt).'</option>'."\n";

i tried in many permutation and combination ways.
"." if i am not inserting this its gives error message
At last i need the code to be in this format
 $string .= ' <option value="' . $opts_cnt.'  '.esc_attr($opt).' "' . $selected . '>'.esc_attr($opt).'</option>'."\n";

Even this is not working.

A: If you remove the value attribute from the option tag then you should get the actual text for the option:
Try:
$string .= '<option ' . $selected . '>'.esc_attr($opt).'</option>'."\n";


text:
Q: How to map xml field to picklist field in salesforce using Dataweave flow1The below snippet is the dataweave mapping, I am getting null values for zmarket. Can anyone please tell me how to map the values for the picklist field!
<dw:set-payload><![CDATA[%dw 1.0
%output application/java
---
[{
 Zmarket__c : payload.Z0DEBMAS.IDOC.E1KNA1M.Zmarket,
}]]]></dw:set-payload>

The zmarket field is a picklist field in salesforce and below is the IDOC xml
Input xml:
<Z0DEBMAS>
  <IDOC>
    <E1KNA1M>
      <Zmarket>AY</Zmarket>
    </E1KNA1M>
  </IDOC>
</Z0DEBMAS>


text:
Q: how can i change python console encoding MAC OSX I tried all in this interesting thread
Changing default encoding of Python?
but nothing work for me.
I use sublime text and when I try :
import sys
print(sys.stdout.encoding)

Output is : US-ASCII
I have a python script that works perfectly under Windows (Output is : utf-8)
But on osx 10.10.2, I always have a problem
Another thing that might help for answer,
when I try in python shell (osX) this code :
>>> leString = '/Users/djex/Desktop/dosser\ é\ espace'
>>> type(leString)
<class 'str'>

>>> stringNew = leString.encode('utf-8')
>>> type(stringNew)
<class 'bytes'>

>>> print (stringNew)
b'/Users/djex/Desktop/dosser\\ \xc3\xa9\\ espace'

>>> print (stringNew.decode('utf-8'))
/Users/djex/Desktop/dosser\ é\ espace
>>>

All is ok.but...
when I try the same thing in sublime text (osX), it does not work
i always have this error
unicodeencodeerror 'ascii' codec can't encode character '\u0300' blabla

or error like
'str object has no attrbute decode'

I do not really understand where my problem comes
Ty for your help

A: Found,
my problem was in python.sublime-build file
this file does not have "env" line
{
"cmd": ["python3", "-u", "$file"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.python",
"encoding": "utf-8",
"env": {"LANG": "fr_FR.UTF-8"}
}


text:
Q: iOS open source build for armv7 , armv7s ,arm64 I am developing an application for iOS device,
and one of the requirement is to make use of libvpx webM, i could able to build it for armv7 architecture, but since has to be universal application, so this should also get it build for armv7s , arm64 architecture too,
now need few clarification,

*

*Since libvpx doesn't have strong build support for arm64 and armv7s and it seems  arm64 has backward support, so is it sufficient to
use armv7 library for arm64 and if this is the case, then what should
be modify in the Xcode project settings,

*or I should keep Xcode project settings as it is, but should modify library configuration using lipo or any other build tool.

In short, i want to know, if any open source which has standard ./configure , make etc... build support for arm7 being there, then how can it be used to support armv7s and arm64 bit architecture.

A: You can have arm7s support by adding arm7 built library into fat lib as arm7s architecture.
So that your lipo command looks like this:
xcrun -sdk iphoneos lipo -create -arch armv7 ios7/lib/xyz.a -arch armv7s ios7/lib/xyz.a -arch i386 ios7_x86/lib/xyz.a -output xyz.a

See that ios7/lib/xyz.a appears twice: once for arm7 and second time as arm7s.
Regarding arm64, not all libraries automatically build for arm64. Especially libraries with lots of optimized assembly code like libvpx.


text:
Q: PeerJS Server 404 on Azure I'm trying to deploy a PeerJS server on Azure. On my kudu console, running
node peerjs --port 9000

returns
Started PeerServer on ::, port: 9000, path: / (v. 0.2.8)

However, when I try to connect to the server from my client code, I get a 404. Going directly to appname.azurewebsites.net/peerjs/id in my browser also returns a 404.
I see inside their package.json file, they run
bin/peerjs --port ${PORT:=9000}

instead of just passing in 9000 directly; I assume this is an environment variable. However, trying to run this on Azure gives
Error: Error: listen EACCES ${PORT:=9000}

which I assume means Azure doesn't recognize ${PORT:=9000} as a valid port.
I know for a fact there's nothing wrong with my client side code because a) I copied it directly from PeerJS's website, and b) everything works correctly when I deployed PeerJS to Heroku. It's only not running on Azure.
Other things I've tried: I edited peerjs in the bin folder to use process.env.PORT instead of what's passed in via the command line, but that didn't work, giving the same EACCES error. When I tried to console.log(process.env.PORT), I got undefined. None of my Google searches have turned up any solutions, although this person (Custom PeerJs Server giving ERR_CONNECTION_TIMED_OUT) seems to have a similar error, not on Azure.

A: *

*Azure App Service doesn't allow us to listen on a customer port. We need to use process.env.PORT instead. See Listen additional port Microsoft Azure Nodejs.

*Azure App Service (on Windows platform) runs on Microsoft IIS. So we need to put the app files to its virtual directory (D:\home\site\wwwroot) and no longer need to manually run the app via the Kudu console.
In this case, you first need to install the library under app's root:
npm install peer

And then create a file named index.js or app.js with following content and put it to /wwwroot folder:
var PeerServer = require('peer').PeerServer;
var server = PeerServer({port: process.env.PORT, path: '/'});

As @Mikkel mentioned in a comment, PeerServer uses WebSocket protocol, so Web Sockets should be enabled in the Azure portal like this:

You also need to check out this post to add a web.config file for your app if it has not been created yet.

A: This will be a firewall problem... You will need to open port 9000 in your Azure settings panel.
From the machine itself, open up a browser to http://localhost:9000/ or http://localhost:9000/peerjs and you should see the standard Peerjs server JSON output.
Or if you only have command line, try curl http://localhost:9000/ or http://localhost:9000/peerjs


text:
Q: Laravel sanctum - vue cli not setting cookies I have laravel 8 installed on a remote server and I'm trying to use sanctum to authenticate from vue cli running in localhost.
When I post the login form It returns that i'm authenticated but it doesn't set the cookies in browser. Firefox console says: Cookie "XSRF-TOKEN" has been rejected for invalid domain. The same for the cookie "laravel_Session".
My configuration:
VUE
  import axios from 'axios';
  axios.defaults.withCredentials = true;

  export default {
    name: 'Login',

    data: () => ({
      form:{
        email: '',
        password: ''
      },
      dialog: true,
    }),
    methods: {
      login: function(){
        axios.get('http://xxx.xxx.xxx.xxx:7183/sanctum/csrf-cookie').then(response => {
          console.log(response);
          axios.post('http://xxx.xxx.xxx.xxx:7183/api/login', this.form).then(response => {
              console.log('User signed in!');
              return response;
          }).catch(error => console.log(error, response)); // credentials didn't match
        });
      }
    }

  }

LARAVEL
ApiController.php
public function login(Request $request)
    {
      try
      {
        $request->validate([
          'email' => 'email|required',
           'password' => 'required'
        ]);
        $credentials = request(['email', 'password']);
        if (!Auth::attempt($credentials))
        {
          return response()->json([
            'status_code' => 500,
            'message' => 'Unauthorized'
          ]);
        }
        $user = \App\Models\User::where('email', $request->email)->first();
        if ( ! Hash::check($request->password, $user->password, []))
        {
          throw new \Exception('Error in Login');
        }
        $tokenResult = $user->createToken('authToken')->plainTextToken;
        return response()->json([
          'status_code' => 200,
          'access_token' => $tokenResult,
          'token_type' => 'Bearer',
          'user_id' => $user->id,
          'user_name' => $user->name,
        ]);
      }
      catch (Exception $error)
      {
        return response()->json([
          'status_code' => 500,
          'message' => 'Error in Login',
          'error' => $error,
        ]);
      }
    }

config/cors.php
<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Cross-Origin Resource Sharing (CORS) Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may configure your settings for cross-origin resource sharing
    | or "CORS". This determines what cross-origin operations may execute
    | in web browsers. You are free to adjust these settings as needed.
    |
    | To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
    |
    */

    'paths' => ['api/*', 'sanctum/csrf-cookie'],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => true,

];

Thanks

A: I'm using sanctum session based authentication in a slightly different configuration, with Angular 11 and Chrome navigator, on localhost and everything is Working Well.
Please make sure to carefully read the documentaion about domain configuration for SPA authentication https://laravel.com/docs/8.x/sanctum#spa-authentication and to properly set these attributes values in your .env file:

*

*SESSION_DOMAIN= value here

*SANCTUM_STATEFUL_DOMAINS= value here

*SESSION_DRIVER= value here

It seems you put your login endpoint in the API route file. Please consider moving it to the web route file so that to use session based login.

You are free to write your own /login endpoint; however, you should ensure that it authenticates the user using the standard, session based authentication services that Laravel provides. Typically, this means using the web authentication guard.

Also please notice that when using sanctum to authenticate your first-party SPAs you should not use token of any kind, as the documentation said:

Sanctum also exists to provide a simple method of authenticating single page applications (SPAs) that need to communicate with a Laravel powered API. These SPAs might exist in the same repository as your Laravel application or might be an entirely separate repository. For this feature, Sanctum does not use tokens of any kind. Instead, Sanctum uses Laravel's built-in cookie based session authentication services.

So I think you should replace this line

$tokenResult = $user->createToken('authToken')->plainTextToken;

with

$request->session()->regenerate();

Btw I noticed that you are using http status code 500 for Unauthorized. I think 401 would be a better choice. Read more about that here https://httpstatuses.com/


text:
Q: Flash overlays thickbox on Internet Explorer Here's my code:

I've got a flash slideshow on my page.  I've used thickbox for login but when someone clicks on the login, the flash overlays thickbox.
I've managed to solve the problem on Firefox, but nothing seems to work on Internet Explorer.

A: You need to use one of the following attributes in order to get Flash to sit "within" the DOM rather than over it.
wmode=transparent
-or-
wmode=opaque
Comes with the disadvantage of breaking a number of features.

A: spender is correct, but he didn't explain it much. wmode is an attribute that gets set in the html when you embed the swf, and it needs to be set to transparent. So if you were using AC_RunActiveContent you'd add "wmode", "transparent" as arguments to the embedding function, or in swfoject you'd add so.addVariable("wmode", "transparent");

A: I had the same problem with the following flash object:
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="690" height="400" id="tech" align="middle">
          <param name="allowScriptAccess" value="sameDomain" />
          <param name="movie" value="banner/banner.swf?xml_path=banner/slides.xml" />
          <param name="quality" value="high" />
          <param name="wmode" value="opaque" />
          <embed src="banner/banner.swf?xml_path=banner/slides.xml" quality="high" width="690" height="400" name="tech" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"  />

        </object>

Note the line <param name="wmode" value="opaque" />
That's the key to make it work.
Hope it helps you.
Bye

A: in the thickbox.js file you can use this:
seach for the tb_show function and add this at the end of the "try" before the "catch":

$('object').each(function(){
  this.regDisplay=this.style.display;
  this.style.display='none';
 })

and

$('#TB_window object').each(function(){
   this.style.display=this.regDisplay;
  })

search for the tb_remove function, and add this before the return:

$('object').each(function(){
  this.style.display=this.regDisplay;
 })

A: The answer of Trey works pretty well for all flash items on page.
The code for the tb_remove function
$('object').each(function(){ this.style.display=this.regDisplay; })

should be placed inside
j("#TB_window").fadeOut("fast",function(){
...
});

This way it only appears after the fadeout and not instantly...

A: ok,
after 2 days of searching the web for the answer i've found a pure JS function that fix it in all browsers!
there you go:
function fix_flash() {
    // loop through every embed tag on the site
    var embeds = document.getElementsByTagName('embed');
    for (i = 0; i < embeds.length; i++) {
        embed = embeds[i];
        var new_embed;
        // everything but Firefox & Konqueror
        if (embed.outerHTML) {
            var html = embed.outerHTML;
            // replace an existing wmode parameter
            if (html.match(/wmode\s*=\s*('|")[a-zA-Z]+('|")/i))
                new_embed = html.replace(/wmode\s*=\s*('|")window('|")/i, "wmode='transparent'");
            // add a new wmode parameter
            else
                new_embed = html.replace(/<embed\s/i, "<embed wmode='transparent' ");
            // replace the old embed object with the fixed version
            embed.insertAdjacentHTML('beforeBegin', new_embed);
            embed.parentNode.removeChild(embed);
        } else {
            // cloneNode is buggy in some versions of Safari & Opera, but works fine in FF
            new_embed = embed.cloneNode(true);
            if (!new_embed.getAttribute('wmode') || new_embed.getAttribute('wmode').toLowerCase() == 'window')
                new_embed.setAttribute('wmode', 'transparent');
            embed.parentNode.replaceChild(new_embed, embed);
        }
    }
    // loop through every object tag on the site
    var objects = document.getElementsByTagName('object');
    for (i = 0; i < objects.length; i++) {
        object = objects[i];
        var new_object;
        // object is an IE specific tag so we can use outerHTML here
        if (object.outerHTML) {
            var html = object.outerHTML;
            // replace an existing wmode parameter
            if (html.match(/<param\s+name\s*=\s*('|")wmode('|")\s+value\s*=\s*('|")[a-zA-Z]+('|")\s*\/?\>/i))
                new_object = html.replace(/<param\s+name\s*=\s*('|")wmode('|")\s+value\s*=\s*('|")window('|")\s*\/?\>/i, "<param name='wmode' value='transparent' />");
            // add a new wmode parameter
            else
                new_object = html.replace(/<\/object\>/i, "<param name='wmode' value='transparent' />\n</object>");
            // loop through each of the param tags
            var children = object.childNodes;
            for (j = 0; j < children.length; j++) {
                try {
                    if (children[j] != null) {
                        var theName = children[j].getAttribute('name');
                        if (theName != null && theName.match(/flashvars/i)) {
                            new_object = new_object.replace(/<param\s+name\s*=\s*('|")flashvars('|")\s+value\s*=\s*('|")[^'"]*('|")\s*\/?\>/i, "<param name='flashvars' value='" + children[j].getAttribute('value') + "' />");
                        }
                    }
                }
                catch (err) {
                }
            }
            // replace the old embed object with the fixed versiony
            object.insertAdjacentHTML('beforeBegin', new_object);
            object.parentNode.removeChild(object);
        }
    }
}

now you can just run in when the page loads with jQuery:
 $(document).ready(function () {
            fix_flash();
 }

A: SIMPLE WAY TO DO IT. Tested only on IE9 and FIREFOX.
Mani's Solution

*

*Wrap your flash content in a div

*Add  to your object tag

*Set wmode="transparent" in the embed tag

*Use css to set the position and z-index for your div (don't set negative z-index values as it will make your flash disappear)

The CSS
#flash {
position: relative; /*or absolute*/
z-index: 0;
}

The XHTML
<div id="flash">
<object ...>
  <param name="wmode" value="transparent">
  <embed ... wmode="transparent">
</object>
</div>

And, in Mani's words... That's It!


text:
Q: Which sentence is correct?' Which is correct? 'They are showing the tv program at the moment. ' or 'They are being shown the tv program at the moment.'

A: 'They are being shown the TV program at the moment' is probably what you mean. 'Showing' in this context has a very specific meaning:

The film is showing at 9 pm

This means that at 9 pm you can watch the film at the cinema. Note that 'showing' in this context is not a gerund, and has a separate definition in the dictionary.


text:
Q: Inserting data from web to excel sheet - VBA I need to insert data from xls file from web, to my current opened workbook. The problem is that if I run this macro several time, it always create new sheet. Ideally I would like to delete old content and replaced it with new content on same sheet. It is possible? Here is my code
Sub downloadData()

Dim wkbMyWorkbook As Workbook
Dim wkbWebWorkbook As Workbook
Dim wksWebWorkSheet As Worksheet
Dim currentDate As Date

Set wkbMyWorkbook = ActiveWorkbook

currentDate = Date

Workbooks.Open ("https://www.somewebpage.com/file.xls")

Set wkbWebWorkbook = ActiveWorkbook
Set wksWebWorkSheet = ActiveSheet

wksWebWorkSheet.Copy After:=wkbMyWorkbook.Sheets(Sheets.Count)

wkbMyWorkbook.Activate
wkbWebWorkbook.Close

End Sub

A: Assuming the sheet dumped from the web will always be the last sheet in the workbook, use this line:
Application.DisplayAlerts = False
wkbMyWorkbook.Worksheets(wkbMyWorkbook.Worksheets.Count).Delete
Application.DisplayAlerts = True

before copying new sheet.


text:
Q: Uncaught TypeError: Cannot read property 'documentElement' of null - Google Карта `var map = new google.maps.Map(document.getElementById("map"), {
        center: new google.maps.LatLng(49.216305, 28.392368),
        zoom: 13,
        mapTypeId: 'roadmap'
      });
      var infoWindow = new google.maps.InfoWindow;
  // Change this depending on the name of your PHP file
  downloadUrl("maps.php", function(data) {
    var xml = data.responseXML;
    var markers = xml.documentElement.getElementsByTagName("marker");
    for (var i = 0; i < markers.length; i++) {
      var name = markers[i].getAttribute("name");
      var address = markers[i].getAttribute("address");
      var type = markers[i].getAttribute("type");
      var photo = markers[i].getAttribute("photo");
      var point = new google.maps.LatLng(
          parseFloat(markers[i].getAttribute("lat")),
          parseFloat(markers[i].getAttribute("lng")));
      var html = "" + name + "
"+"
" + address;
      var icon = customIcons[type] || {};
      var marker = new google.maps.Marker({
        map: map,
        position: point,
        icon: icon.icon
      });
      bindInfoWindow(marker, map, infoWindow, html);
    }
  });`

A: downloadUrl("/maps.php", function(data) {
- не верно указана директория."maps.php"


text: Q: Depreciation and application braking finder I have trying to upgrade rails from 5.2 to 6.1. Fixed some depreciation warnings by manually ran the each file / pages. Can we able to get overall depreciation list using gem or some other ways like brakeman?


text:
Q: to precision -- meaning? Link to the YouTube video
Transcript:

Alright. So, you're probably wondering what the difference between the float, the double and the long double is. Well, the float is the least precise, meaning that it can store the least amount of digits. The float can only store six digits to precision. So, that means that we can only store a number with six digits inside of any float variable.

How do you guys understand that? What exactly does that mean?

A: We normally say of precision, not to precision. It is referring to the accuracy of the number. So, 6 digits of precision would be something like .333333

A:
six digits to precision.

precisely 6 digits. But other digits will not guaranteed to be exactly like those 6 digits. Most of the time it will be round up.

A: In that programming scenario, it means that float can only have 6 digits after the decimal point, an afirmation which seems to be incorrect (programming link)


text:
Q: How to use custom UIView subclass in XIB editor with Monotouch? I have added a XIB based UIViewController to my solution and dragged some UIViews into it.
Now I want some of the views not to be UIView but RoundedRectView
(https://github.com/Krumelur/RoundedRectView) which inherits from UIView.
How to achieve this? I tried to change the class in Interface Builder but that did nothing. Then I manually modified the designer.cs file but that resulted in a failure.
Then I tried modifying the fake ObjC code but that failed too.
(I'm using Xcode 4.2 and MD 2.8.6.4)

A: Your view subclass needs at least two things:

*

*Register attribute
[Register("MyView")]
public class MyView : UIView {}

*IntPtr constructor
public MyView(IntPtr handle) : base(handle) {}
You then open the XIB in Interface Builder, add a UIView and set its Class in the Identity Inspector to the name you passed to the Register attribute. When you connect it to an outlet, you will see that it has the correct type.


text:
Q: Is there a bitwise trick to increase only zero to one? In C++, is it possible to achieve the following with a bitwise trick?
(i == 0) ? 1 : i

Assume that i is an unsigned 32-bit integer.
EDIT: This is out of curiosity. The goal is not to optimize and clearly not to improve readability.

A: Until I see real results that say otherwise, I believe your code is much clearer and just as fast, but either of these accomplish the same thing without the conditional:
i + !i

Or
i | !i

If i is 0, !i is 1. Combining 0 with 1 through addition or bitwise OR always gives 1. If i is non-zero, !i is 0. Combining a non-zero value with 0 through addition or bitwise OR always gives that value. Thus, the result is 1 if i is 0 and i if not.
Again, I will be surprised if either of these actually turn out to be better for the compiler.

A: On computers with two's complement representation of negative numbers, you can use this formula:
(!(n & -2)) | n

Demo.
Explanation: Bit pattern for -2 has ones in all bit positions except the least significant one. Therefore, the expression n & -2 will be zero only when n is equal to zero or one. The ! will make one from zero and zero from any other number. Hence, zero or one will be OR-ed with one, while any other number will remain intact.


text:
Q: Characterization of analytic functions by exponential functions Let $f$ be an analytic function on domain $D$ such that $f(z) \neq 0, \forall z \in D.$
Could anyone advise me how to prove $f= e^{h},$ for some analytic $h$ on $D \ ?$ Thank you.

A: This is more of a comment really. intuitively what we are doing is as follows. Suppose that once could write $f = e^h$ for some $h$ an analytic function. Then $h' = f'/f$. Now we want to show that such an h actually exists. choose any point $z_0 \in \Omega$(any domain). Let $h(z_0) = c$. Now define
$h(z) := \int_{\gamma} h'(w)dw$
where $\gamma$ is any path in the domain connecting $z_0$ to $z$. First we need to check whether this function is well defined. That is $\gamma, \gamma'$ are two such paths then
$\int_{\gamma} h'(w)dw - \int_{\gamma'} h'(w)dw = 0$.
That is for any loop at $z_0$ say $\alpha$, $\int_{\alpha} h'(w)dw = 0$. Now if the domain is simply connected this is true using stokes theorem. Once the function $h$ is well defined on $\Omega$ then it will be analytic by definition(integral of an analytic function). We are done.


text:
Q: How to call ts function from js function in Angular 11 I have a function on the constructor that detects if a scanner device is scanning, when it's successful it will call a js function called getQRCode which is working good, but when I try to call the ts function is not working
This is inside my ts file
declare var getQRCode: any;
constructor()
  {
    window['stBrowserDidScanBarcode'] = function(type, data, stid){
      getQRCode = getQRCode(data)
      this.handleScan(getQRCode)
    };
  }

When I try to call the handleScan function is not been called, why this could be happening?
handleScan(scan: any) {
  console.log(scan)
}

This is my js file is been read ok
function getQRCode(data){
  return data;
}


text:
Q: Include tag in jaxb I have an xml file of following structure:
<root>
<paramsToInclude>
    <params id="id1">
        <param11>val1</param11>
        <param12>val2</param12>
        <param13>val3</param13>
        <param14>val4</param14>
    </params>

    <params id="id3">
        <param31>val1</param31>
        <param32>val2</param32>
    </params>
</paramsToInclude>

<process>
    <subprocess1>
        <include params="id1"/>
        <query>
            SELECT *
            FROM
            table;
        </query>
    </subprocess2>

    <subprocess1>
        <rule>rule1</rule>
        <rule>rule2</rule>
    </subprocess2>

    <subprocess3>
        <processParam>val1</processParam>
        <include params="id2"/>
        <include params="id3"/>
    </subprocess3>
</process>

I'm using jaxb to parse this xml into the java classes. Is there a way to substitute includes in the process by it's values from the begin of file?  I mean, I wan't file to be parsed as if it look's like
<root>
<paramsToInclude>
    <params id="id1">
        <param11>val1</param11>
        <param12>val2</param12>
        <param13>val3</param13>
        <param14>val4</param14>
    </params>

    <params id="id3">
        <param31>val1</param31>
        <param32>val2</param32>
    </params>
</paramsToInclude>

<process>
    <subprocess1>
        <param11>val1</param11>
        <param12>val2</param12>
        <param13>val3</param13>
        <param14>val4</param14>
        <query>
            SELECT *
            FROM
            table;
        </query>
    </subprocess2>

    <subprocess1>
        <rule>rule1</rule>
        <rule>rule2</rule>
    </subprocess2>

    <subprocess3>
        <processParam>val1</processParam>
        <param11>val1</param11>
        <param12>val2</param12>
        <param13>val3</param13>
        <param14>val4</param14>
        <param31>val1</param31>
        <param32>val2</param32>
    </subprocess3>
</process>

is it possible t do this? I've found link http://thetechietutorials.blogspot.com/2011/08/jaxb-tutorial-part-2-jaxb-with-xinclude.html how to this include from another file, but comment says that it's impossible to do this for the same file (I understand that I can put this includes in another xml, but I don't think it's a best way). Also I don't want to use hashMap because in this way included params will be stored in hashMap and processParam (from subprocess3) will be class variable.
Is there a way to do this somehow?


text:
Q: Hive not starting on CentOS I am using CDH 5.3. I have followed all the steps giving at https://github.com/cloudera/cdh-twitter-example. However, I am stuck when I try to run Hive.
[cloudera@quickstart conf]$ hive

Logging initialized using configuration in file:/etc/hive/conf.dist/hive-log4j.properties

This is the output and nothing happens. It is stuck there.
This is my hive-site.xml
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>

<configuration>
<property>
<name>javax.jdo.option.ConnectionURL</name>
<value>jdbc:mysql://localhost/metastore</value>
<description>the URL of the MySQL database</description>
</property>

<property>
<name>javax.jdo.option.ConnectionDriverName</name>
<value>com.mysql.jdbc.Driver</value>
</property>

<property>
<name>javax.jdo.option.ConnectionUserName</name>
<value>hive</value>
</property>

<property>
<name>javax.jdo.option.ConnectionURL</name>
<value>jdbc:mysql://localhost/metastore</value>
<description>the URL of the MySQL database</description>
</property>

<property>
<name>javax.jdo.option.ConnectionDriverName</name>
<value>com.mysql.jdbc.Driver</value>
</property>

<property>
<name>javax.jdo.option.ConnectionUserName</name>
<value>hive</value>
</property>

<property>
<name>javax.jdo.option.ConnectionPassword</name>
<value>mypassword</value>
</property>

<property>
<name>datanucleus.autoCreateSchema</name>
<value>false</value>
</property>

<property>
<name>datanucleus.fixedDatastore</name>
<value>true</value>
</property>

<property>
<name>hive.metastore.uris</name>
<value>thrift://localhost:9083</value>
<description>IP address (or fully-qualified domain name) and port of the metastore host</description>
</property>
</configuration>


text:
Q: get fields from all levels from 3x nested level array documents I have the following document type:
{
_id: 1,
"_a": [
{
"_aId": {
  "CC": "CA"
},
"_p": [
  {
    "_pId": {
      "CC": "CA",
       "SN":1
    },
    "s": {
      "c": {
        "t": [
          {
            sId: 1,
            language: "CA",
            format: "A4"
          },
          {
            sId: 2,
            language: "JP",
            format: "A4"
          }
        ]
      },
      "a": {
        "t": [
          {
            sId: 4,
            language: "CA",
            "format": "A4"
          },
          {
            sId: 5,
            language: "EN",
            "format": "A3"
          }
        ]
      },
      "d": {
        "t": [
          {
            sId: 10,
            language: "CA",
            "format": "A4"
          }
        ]
      }
    }
  }
 ]
 }
 ]
}

And I need faster solution to extract all subdocuments sId & _pid for language:"CA" & format:"A4" for documents with "_a._p._pid.CC":"CA"
So the expected output need to look as follow:
{_pid:{CC:"CA",SN:1},sId:1}
{_pid:{CC:"CA",SN:1},sId:4}
{_pid:{CC:"CA",SN:1},sId:10}

Playground
Thanks to @Nimrod I have the initial solution  here, but not sure how to include the _pid as well so it does not reduce performance ...
(I am using MongoDB 4.0)

A: I am not sure about performance, but you can try an option,

*

*$match your condition,

*$project,

*

*$reduce to iterate loop of _a

*

*$filter to iterate loop of _p and filter it by "_pId.CC": "CA"

*$concatArrays to concat above filtered result with previous filtered result

*$project, the process is hard to describe here but it just filters your expected fields in the result

*$unwind to deconstruct the _a
db.collection.aggregate([
  { $match: { "_a._p._pId.CC": "CA" } },
  {
    $project: {
      _id: 0,
      _a: {
        $reduce: {
          input: "$_a",
          initialValue: [],
          in: {
            $concatArrays: [
              "$$value",
              {
                $filter: {
                  input: "$$this._p",
                  cond: { $eq: ["$$this._pId.CC", "CA"] }
                }
              }
            ]
          }
        }
      }
    }
  },
  {
    $project: {
      _a: {
        $reduce: {
          input: "$_a",
          initialValue: [],
          in: {
            $concatArrays: [
              "$$value",
              {
                $map: {
                  input: {
                    $reduce: {
                      input: { $objectToArray: "$$this.s" },
                      initialValue: [],
                      in: {
                        $concatArrays: [
                          "$$value",
                          {
                            $filter: {
                              input: "$$this.v.t",
                              cond: {
                                $and: [
                                  { $eq: ["$$this.format", "A4"] },
                                  { $eq: ["$$this.language", "CA"] }
                                ]
                              }
                            }
                          }
                        ]
                      }
                    }
                  },
                  as: "p",
                  in: {
                    _pId: "$$this._pId",
                    sId: "$$p.sId"
                  }
                }
              }
            ]
          }
        }
      }
    }
  },
  { $unwind: "$_a" }
])

Playground


text:
Q: System.IO.IOException: Too many posts were made to a semaphore I'm developing an App in .net (Xamarin) and I'm trying to establish a connection
with a serial port.
Whenever I try to open the connection with the port I'm getting this error_message:
System.IO.IOException: 'Too many posts were made to a semaphore'
Can't find anything specific by googling. Any help appreciated!
Example code:
private void Open()
    {
        IsOpen = true;
        _serialPort.PortName = "COM3";
        _serialPort.BaudRate = 19200;
        _serialPort.Parity = Parity.None;
        _serialPort.DataBits = 8;
        _serialPort.StopBits = StopBits.One;
        _serialPort.Handshake = Handshake.None;
        _serialPort?.Open();
    }

A: This is because you need to add
<DeviceCapability Name="serialcommunication">
      <Device Id="any">
          <Function Type="name:serialPort" />
      </Device>
</DeviceCapability>

to your Package.appxmanifest.
Took me awhile to figure this out myself.


text:
Q: How to get all branches content on any new branch using GIT I know this question is asked many times on SO.
I just wanted to get proper way of branching and fixing mine.
My working methodology on Git branching is:

*

*Checkout to master

*Take pull of all branches one by one on master ( if there are any latest branches that are not merged on master yet but existed on remote )
Checkout new branch from master.

*Work on that branch

*Push to Git

*Now again checkout to master

*And take pull again

*And then checkout to new branch again.

*All above.

So, I know this is not the right way to doing this Git branching.
I always stumbled myself on these branching and sometime I lost work too due to wrong branching and push pull.
Can anybody explain the write way of doing this branching properly? Including best practices as well. So, I will follow those procedures for my current project.
Also, my main concern is having latest code all the time on any branch ( I think master as we checkout new branch from that branch )

A: I'll try to explain one way to work with branches. You can find other in the internet and from my point of view there is not a perfect one.

In this image, you have your master branch. The one that has the working code that is on production.
From Master branch, you have a develop branch. This branch will have your most recent code, with features that your testing and building.
From Develop branch, you have all your feature branches. The ones that you'll start new features
So, the workflow would be: "Oh, I have an idea off feature to add to this project."

*

*Create a branch from develop with the name of 'feature idea'

*Develop the feature in that branch

*Merge to develop to test

*"Oh, another idea!"

*Create another branch from develop named 'ideia 2'

*Develop in that branch

*Merge to develop

*test test test

*Merge to master
This way you'll always have a working code at master and a 'beta' version at develop


text:
Q: How can we override standard Salesforce Lightning message? We have custom logic to assign opportunity owner, when the User manually try to change the owner Apex code kicks in and assign the owner according to the logic.
Still Lightning Users are getting the lightning success message for owner change(manual input) which is misleading to user .
How can we override standard Salesforce Lightning message ?


text:
Q: Regular Expression to replace all non alphanumeric characters except / to empty("") character I want a regular expression to replace all non alphanumeric characters except '/' with ""(empty character).
This is what I did:
LibString.replaceAll(token, "[^a-zA-Z0-9]", "");

And the function implementation in LibString is:
public static String replaceAll(String source, String regex, String replacement)
    {
        Pattern pattern = new Pattern(regex, 0);
        Replacer replacer = pattern.replacer(replacement);

        String result = replacer.replace(source);
        return result;
    }

The String I gave is :

'France vs Tonga'. French International Rugby Blitz H/L 2013.
  Highlights of the French international Rugby match.

Expected result:
A list of words:
France
vs
Tonga
French
International
H/L
.. etc
Actual Result is:
'France
[empty]
Tonga'.
.French
[empty]
Please advice.
PLEASE NOTE: I am working on a system which has JVM 1.2 so cant use any of the util.regex or String Replace all kind of methods.
I have imported jregex.jar to my project to utilize the usage of regular expressions.

A: Use regex [^a-zA-Z0-9//] insted of [^a-zA-Z0-9] to escape /
 LibString.replaceAll(token, "[^a-zA-Z0-9//]", "");


text:
Q: TextView.setText() doesn't update text in ExpandableListView adapter I wrote a class that extends BaseExpandableListAdapter. When a group is clicked, I want it to expand, and then my custom indicator in the view will animate a 180 rotation. And it works.
My problem is that on the same clicklistener I want to update a TextView using setText() method, but when I run it, it doesn't update the view.
I tested if the problem was in the reference to the TextView: changing the visibility, rotating it, animating it, and they all work. Its just the setText() that doesn't works.
Here is the relevant code in the adapter class: (There are actually two TextViews I would like to update)
@Override
public void onGroupExpand(int groupPosition) {
    GroupViewHolder holder = mViewHolderSparseArray.get(groupPosition);
    Lesson lesson = (Lesson) getChild(groupPosition, 0);
    holder.indicatorView.animate().rotation(180);
    holder.teacherView.setText(lesson.getTeacher());
    holder.classroomView.setText(lesson.getClassroom());
}

@Override
public void onGroupCollapse(int groupPosition) {
    GroupViewHolder holder = mViewHolderSparseArray.get(groupPosition);
    holder.indicatorView.animate().rotation(0);
    holder.teacherView.setText("...");
    holder.classroomView.setText("");
}

I have also tried to put this code in the getGroupView() (assign an OnClickListener to the view), but I get the same results.
Some other relevant methods:
@Override
public long getGroupId(int groupPosition) {
    return groupPosition;
}

@Override
public long getChildId(int groupPosition, int childPosition) {
    return childPosition;
}

@Override
public boolean hasStableIds() {
    return true;
}

@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
    return true;
}

Any ideas why my TextView doesn't update its text?

A: According to the answer linked by @IntelliJAmiya, The setText() doesn't update because it probably didn't run on the UI thread.
Here Is what I did to fix this issue:
@Override
public void onGroupExpand(int groupPosition) {
    final GroupViewHolder holder = mViewHolderSparseArray.get(groupPosition);
    final Lesson lesson = (Lesson) getChild(groupPosition, 0);
    holder.indicatorView.animate().rotation(180);
    holder.teacherView.post(new Runnable() {
        @Override
        public void run() {
            holder.teacherView.setText(lesson.getTeacher());
            holder.classroomView.setText(lesson.getClassroom());
        }
    });
}


text:
Q: How do I pass a random string from an array into views? In my controller, I have an array of locations defined and I used sample to catch one of the random strings:
class IndexController < ApplicationController
  def index
    @location = ["England", "Scotland", "Wales", "Ireland"]
    random_location = @location.sample
  end
end

However, I don't know the code needed to display the one country in my browser.

A: Use Array#sample
class IndexController < ApplicationController
  def index
    # @location i_var will be available automatically inside the corresponding
    # view of this action to the Index controller.
    @location = ["England", "Scotland", "Wales", "Ireland"]
  end
end

Now inside the view - index.html.erb
Country is <%= @location.sample %>


text:
Q: how to pass an argument into an aws lambda from an aws state machine/step function I'm trying to pass an argument into a an aws python lambda from a state machine. I've written the following function:
{
  "Comment": "test lambda execution with state machine",
  "StartAt": "testPassInArgs",
  "States": {
    "testPassInArgs": {
      "Type": "Task",
      "Resource":"arn:aws:lambda:....function:testPassInArgs",
      "Next": "testRecieveArgs"
    },

    "testRecieveArgs": {
      "Type": "Task",
      "InputPath": "$.a",
      "Parameters": {
      "InputPath": "$.a"},
      "Resource": "arn:aws:lambda:....:function:testRecieveArgs",
      "End": true

    }

  }
}

here are the lambda functions
testPassInArgs:
import json

def lambda_handler(event, context):
    stations={}
    stations['a']='A'
    stations['b']='B'
    stations['c']='C'

    return  {
        'a':stations['a'],
        'b':stations['b'],
        'c':stations['c']
    }

the other lambda 'testRecieveArgs:
import json

def lambda_handler(event, context):
    # TODO implement
    out={}
    if type(event) == dict:
        for item in event:
            out[item+item] = event[item]+event[item]
            print(item)
            print(event[item])

    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!'),
        'event': out
    }

I would have expected that the 'Parameters' argument in the second part of the state machine would have parsed the output from the first lambda and passed in only the first part (namely 'A') to the second lambda. However it doesn't. the output of the second lambda is:
"InputPathInputPath": "$.a$.a"

The input of the second lambda is simply the output of the first.
I would like to parse the output of the first lambda and send each part to a different lambda downstream in parallel.
I must be missing a trick here? If anyone knows it would be a great help?
p.s. I'm sure I can handle the parallelising part, its just parsing the arguments and then passing them into downstream functions I'm struggling with.

A: The output of the first Lambda function is
{
  "a": "A",
  "b": "B",
  "c": "C"
}

If your second task definition were:
    "testRecieveArgs": {
      "Type": "Task",
      "InputPath": "$.a",
      "Resource": "arn:aws:lambda:....:function:testRecieveArgs",
      "End": true
    }

the second Lambda would receive "A" as its input. However, you added this
      "Parameters": {
        "InputPath": "$.a"
      },

to your second task definition, which would overwrite the input json with
{
  "InputPath": "$.a"
}

Is it a typo?


text:
Q: Using Mapbox (LeafletJS), how do I edit imported shapes from GeoJSON? Overview: I'm currently working on a project where I'm importing GeoJSON into a map using Mapbox. However, I'm wanting to be able to edit those shapes once imported into the map. I've gotten the GeoJSON imported successfully. I can see my shapes as layers in my FeatureGroup. I can see my shapes on the map as they should be rendered.
The Issue: The problem that I'm having is editing the layers after I've imported them. When I click on the "edit" button using Leaflet Draw, I'm getting an error saying "Uncaught TypeError: Cannot read property 'enable' of undefined" on line 10 of leaflet_draw.js. Also, my shapes are now empty shapes with dashed border and no edit controls. Therefore, I can't even interact with the shapes at all.
My Code: Here's the code that I've used to pull my GeoJSON into the map:
var featureGroup = L.featureGroup().addTo(map);
if (oldData) {
    var featureLayer = L.mapbox.featureLayer(oldData, {
        pointToLayer: function (feature, latlon) {
            if (feature.properties.type === 'circle') {
                return L.circle(latlon, feature.properties.radius);
            } else if (feature.properties.type === 'marker') {
                return L.marker(latlon);
            }
        },
        setStyle: function (feature) {
            return {color: feature.properties.color};
        },
        onEachFeature: function (feature, layer) {
            layer.bindPopup(feature.properties.description);
            layer.openPopup();
        }
    }).addTo(featureGroup);
}

var featureLayer = L.mapbox.featureLayer().addTo(map);
var drawControl = new L.Control.Draw({
    edit: {
        featureGroup: featureGroup
    },
    draw: {
        polygon: true,
        polyline: true,
        rectangle: true,
        circle: true,
        marker: true
    }
}).addTo(map);

Also, it may be helpful to know that I'm using Leaflet.draw version 0.2.3 and Leaflet 0.7.2 that come with Mapbox 2.2.1.
Any tips will help.

A: I never actually was able to use L.mapbox.featureLayer for this. I ended up having to use Leaflet's L.geoJson, adding featureLayer to map instead of the featureGroup, and adding the layer to the featureGroup at onEachFeature. Here's what my final code looked like:
var featureGroup = L.featureGroup().addTo(map);
if (oldData) {
    var featureLayer = L.geoJson(oldData, {
        pointToLayer: function (feature, latlon) {
            if (feature.properties.type === 'circle') {
                return L.circle(latlon, feature.properties.radius);
            } else if (feature.properties.type === 'marker') {
                return L.marker(latlon);
            }
        },
        style: function (feature) {
            return {color: feature.properties.color};
        },
        onEachFeature: function (feature, layer) {
            featureGroup.addLayer(layer);
            layer.bindPopup(feature.properties.description);
            layer.openPopup();
        }
    }).addTo(map);
}

var featureLayer = L.mapbox.featureLayer().addTo(map);
var drawControl = new L.Control.Draw({
    edit: {
        featureGroup: featureGroup
    },
    draw: {
        polygon: true,
        polyline: true,
        rectangle: true,
        circle: true,
        marker: true
    }
}).addTo(map);

Here's a Mergely diff showing the difference: http://www.mergely.com/fVq3TQvT/


text:
Q: If statement inside a While loop I have looked at some examples but don't seen to be able to find what I am looking for.
I need to make the cells in a table change colour if the amount in quantity is less than the threshold.
<?php
$result = mysql_query("SELECT * FROM stock WHERE type='hardware' ORDER BY item ASC");

echo "

Hardware Stock Item
Quantity
Location

";

while($row1 = mysql_fetch_array($result))
{
echo "
";
echo "" . $row1['item'] . "	";

if ($row1['quantity'] => $row1['threshold']) {
echo "" . $row1['quantity'] . "	";
} else {
echo "" . $row1['quantity'] . "	";
}

echo "" . $row1['location'] . "	";
echo "
";
}
echo "
";
?>

A: You did not describe what exact issue you were having, but for one thing, this line :
if ($row1['quantity'] => $row1['threshold']) {

is wrong.
Maybe you made a typo error that went unnoticed, anyway there is a syntax error and the correctly written operator does the opposite of what you expect :
=> isn't a comparison operator, it's an assignation operator when assigning array values, the correct comparison operator is >=.
Besides, >= is the lte operator, in other words it means larger than or equal.
Since you apparently intend to change the element's colour when the quantity is lesser than the threshold, you should use the lesser than operator which is < :
if ($row1['quantity'] < $row1['threshold']) {

If however the mistake is in your explanaition and you planned to include equlaty in your condition, then you should go for the lesser than or equal operator, which is <= :
if ($row1['quantity'] <= $row1['threshold']) {

A: My code is working but else part runs 2 times.
If my condition is wrong then it displays Invalid Email & Password single time but it runs multiple time. Why?
    <?php
    require_once('connection.php');
    if (isset($_POST['submit'])) {
        $email = $_POST['email'];
        $pass_wrd = $_POST['pass'];

        $qry = "SELECT email,pswd FROM registration ";
        $fetchdata = mysqli_query($con, $qry);

        while ($arraydata = mysqli_fetch_array($fetchdata)) {
            if (($email == $arraydata['email']) && ($pass_wrd == $arraydata['pswd'])) {
                echo '';
            } else {
                echo "not";
            }
        }
    }
    ?>


text:
Q: Solving $\lim_{x\to1}(4^x-3^x)^{\frac{1}{1-x}}$ and others like it without L'hospital Ok so I have issues with this specific 'type' of limits. : $\\$
$$\lim_{x\to1}(4^x-3^x)^{\frac{1}{1-x}}$$
and $\\$
$$\lim_{x\to-1}\biggr(-4\cdot\arctan(x)\cdot{\frac{1}{\pi}}\biggr)^{\frac{1}{x+1}}$$
$\\$
It seems like they are quite similar, but I'm not sure what to do. I've tried taking $\ln$ of the limit to simplify it but have reached nothing. I would appreciate any hint whatsoever.
However, I am not allowed to use L'hospital rule or integrals to solve these.
Thanks in advance!

A: Change the variable to $x=y+1$ and you have now $y\to 0$.
Next take the log so you have
$$-\frac{\ln(4^{y+1}-3^{y+1})}{y}$$
Now use that $$\frac{\ln(4^{y+1}-3^{y+1})}{4^{y+1}-3^{y+1}-1}\to 1$$ as a special instance of $\lim\limits_{t\to 0}\frac{\ln 1+t}{t}=1$.
So the problem reduces to
$$-\frac{4^{y+1}-3^{y+1}-1}{y}$$
which we write as
$$\frac{3^{y+1}-3}{y}-\frac{4^{y+1}-4}{y}=3\frac{3^{y}-1}{y}-4\frac{4^{y}-1}{y}$$
Finally we use the fact that $$\frac{a^t-1}{t}\to \ln a$$ to see that your limit is
$$3\ln 3-4\ln 4$$
But dont forget to undo the log so the real limit is $$\frac{3^3}{4^4}$$

A: I thought it might be instructive to present an approach that relies only on a set of elementary inequalities.  To that end, we begin with a primer.

PRIMER:
In THIS ANSWER, I used only the limit definition of the exponential function and Bernoulli's Inequality to show that the exponential function satisfies the inequalities
$$\bbox[5px,border:2px solid #C0A000]{1+x\le e^x\le \frac{1}{1-x}} \tag 1$$
for $x<1$, and the logarithm function satisfies the inequalities
$$\bbox[5px,border:2px solid #C0A000]{\frac{x-1}{x}\le \log(x)\le x-1} \tag2$$
for $x>0$

We note that without loss of generality, we assume that the limit is taken from the left-hand side (i.e., $x<1$).  Proceeding, let $f(x)=(4^x-3^x)^{1/(1-x)}$.  Then, using $t=e^{\log(t)}$ we can write $f(x)$ as
$$\begin{align}
f(x)=e^{\frac{\log(4^x-3^x)}{1-x}} \tag 3
\end{align}$$
Letting $g(x)=\frac{\log(4^x-3^x)}{1-x}$ and exploiting $(1)$ and $(2)$, the upper bound for $g(x)$ is
$$\begin{align}
g(x)&\le \frac{4^x-3^x-1}{1-x}\\\\
&=\frac{4e^{(x-1)\log(4)}-3e^{(x-1)\log(3)}-1}{1-x}\\\\
&\le \frac{\frac{4}{1-(x-1)\log(4)}-3(1+(x-1)\log(3))-1}{1-x}\\\\
&=\frac{3\log(3)-4\log(4)-3\log(3)\log(4)(x-1)}{(1-(x-1)\log(4))}\\\\
&\to \log\left(\frac{3^3}{4^4}\right)\,\,\,\text{as}\,\,x\to 1 \tag 4
\end{align}$$
and the lower bound for $g(x)$ is
$$\begin{align}
g(x)&\ge \frac{4^x-3^x-1}{(1-x)(4^x-3^x)}\\\\
&=\frac{4e^{(x-1)\log(4)}-3e^{(x-1)\log(3)}-1}{(1-x)(4^x-3^x)}\\\\
&\ge \frac{4(1+(x-1)\log(4))-\frac{3}{1-(x-1)\log(3)}-1}{(1-x)(4^x-3^x)}\\\\
&=\frac{3\log(3)-4\log(4)+4\log(3)\log(4)(x-1)}{4^x-3^x}\\\\
&\to \log\left(\frac{3^3}{4^4}\right)\,\,\,\text{as}\,\,x\to 1 \tag 5
\end{align}$$
Applying the squeeze theorem to $(4)$ and $(5)$ shows that $\lim_{x\to 1}g(x)=\log\left(\frac{3^3}{4^4}\right)$ whereupon using $(3)$ and exploiting the continuity of the exponential function yields the coveted limit

$$\bbox[5px,border:2px solid #C0A000]{\lim_{x\to 1}(4^x-3^x)^{1/(1-x)}}=\frac{3^3}{4^4}$$

Note that the only tools used were the inequalities in $(1)$ and $(2)$ along with the continuity of the exponential function and the squeeze theorem!


text:
Q: HTML::TokeParser finding tags _until_ a certain tag I need to read an html file and find a certain paragraph tag, with specific text in it.  Once I find that tag, I then want the text from all the next tags until I find a table tag
Example:
<asdf>
</asdf>

THE SIGNAL TO GET INFO

    <something>some good stuff in here</something>

something else

something good in here for sure

this too

 I DON'T WANT THIS

I can find the first Paragraph tag with HTML::TokeParser like this:
my $description = "";
my $tp = HTML::TokeParser->new(\$content) || die "Can't open: $!";

while (my $token = $tp->get_tag("p")) {
    my $paragraph = $tp->get_trimmed_text("/p");
    if ($paragraph =~ /On this page/) {
        until ((my $stop = $tp->get_token)->[1] eq "table") {
            if ( $stop->[0] eq "S" ) {
                print $stop->[0],"\n";
            }
        }
        return $description;
    }
}

I've tried the above code... but something is desperately wrong with it, since it won't even compile.
Thanks for your help.

A: You probably want to call $tp->get_token, storing the data until you see ["S", "table"…]
You say you couldn't get this to work.  Can you explain why/what you did see?  Perhaps provide a full example for people to play with.
Well, you didn't provide example output, so I made some assumptions.
#!/usr/bin/perl
use HTML::TokeParser;

my $content = "<asdf>
</asdf>

THE SIGNAL TO GET INFO

    <something>some good stuff in here</something>

something else

something good in here for sure

this too

 I DON'T WANT THIS

";

my $description = "";
my $tp = HTML::TokeParser->new(\$content) || die "Can't open: $!";

while (my $token = $tp->get_tag("p")) {
    my $paragraph = $tp->get_trimmed_text("/p");
    if ($paragraph =~ /THE SIGNAL TO GET INFO/) {
      while (my $toke = $tp->get_token)
      {
        last if ($toke->[1] eq "table");
#       print "<$toke->[0]> <$toke->[1]> <$toke->[2]> <$toke->[3]> <$toke->[4]>\n";
#       print " <".join("><",@{$toke->[3]}).">\n";
        if ($toke->[0] eq "T" ) {
                my $text = $toke->[1];
                $description .= $text;
        }
      }
      print $description;
      last;
    }
}

Produces:
    some good stuff in here
something else

    something good in here for sure
    this too