text:
Q: COM Interop: Marshaling .NET array property to conform to existing (C++) typelib I am trying to create a .NET assembly (language does not matter as such; C#, VB.NET or C++/CLI are all acceptable) that can serve as a drop-in replacement for an existing COM object (consumed by VB6).
In and of itself, this works nicely, using the proper attributes.
I am running into a few mapping issues, however:

*

*the existing COM object uses parametrized properties; this seems to rule out C# because it does not support them (an indexer + IndexerNameAttribute does not help, since it only supports creating one such property per interface)
Example IDL:
[propput, helpstring("prop1")]
HRESULT prop1([in] LONG ix1, [in] double prop1);

[propget, helpstring("prop1")]
HRESULT prop1([in] LONG ix1, [out, retval] double* prop1);

[propput, helpstring("prop2")]
HRESULT prop2([in] LONG ix1, [in] double prop2);

[propget, helpstring("prop2")]
HRESULT prop2([in] LONG ix1, [out, retval] double* prop2);

In C# I can have either one, but not both:
[IndexerName("prop1")]
double this[[In] long ix1] { get; set; }

[IndexerName("prop2")]
double this[[In] long ix1] { get; set; }

=> second one is flagged as duplicate by the compiler (same signature)
=> I tried inheriting from subinterfaces, each providing its own property, but with COM that inheritance is lost (and the client crashes trying to call the getter/setter)
=> not a huge problem, VB.NET remains viable (not entirely sure about C++/CLI), but see point 2 for why this is not ideal

*COM helpstring() attributes are based on .NET Description attributes; but for properties these need to be on the getter/setter, not on the property itself. Not a problem in C#, but in VB.NET there does not seem to be any way to put attributes specifically on the getter/setter of a property in an interface.
=> IL manipulation allows me to work around this, but that's not ideal; and in the end the helpstring is only a minor cosmetic issue.

*Methods taking pointer-to-safearray.
IDL:
[id(666), helpstring("A Sample Method")]
HRESULT ArrayMethod([in]  SAFEARRAY(double)* doubles,
                    [out] SAFEARRAY(BSTR)* strings);

Here the in parameter is also specified as a pointer-to-safearray; unusual but valid.
Coding this as
[DispId(666), Description("A Sample Method")]
void ArrayMethod([In] ref double[] doubles, out string[] strings);

results in an exactly matching signature in the typelib for the assembly.
However, a call to the method results in "SafeArray cannot be marshaled to this array type because it has either nonzero lower bounds or more than one dimension.". So, it looks like the marshaling code for .NET does not actually handle this case properly...

*Array property setters.
Here the problem is in the COM signature:
[id(13), propput, helpstring("A Bunch Of Doubles")]
HRESULT DoubleArray([in] SAFEARRAY(double)* array_to_set);

[id(13), propget, helpstring("A Bunch Of Doubles")]
HRESULT DoubleArray([out, retval] SAFEARRAY(double)* array_to_get);

(i.e. the propput's made to match the propget, and is more like a propputref, really).
If I have a double[] property in .NET, I get
[id(13), propput, helpstring("A Bunch Of Doubles")]
HRESULT DoubleArray([in] SAFEARRAY(double) array_to_set);

[id(13), propget, helpstring("A Bunch Of Doubles")]
HRESULT DoubleArray([out, retval] SAFEARRAY(double)* array_to_get);

instead (i.e. no extra indirection in the setter).
I seem to be unable to get the assembly to produce a typelib that includes this extra level of indirection; MarshalAs does not (seem to) support adding a VT_REF flag to VT_SAFEARRAY, nor can I find any other attribute that would let me do this.
If I register the assembly, and then replace the typelib with one that has the extra *, the Marshaler errors out (claiming a SafeArray of some huge rank (e.g. 8600) is used, which is reasonable when misinterpreting the pointer).
Alternatively, if I implement specific methods:
[DispId(13), Description("A Bunch Of Doubles")]
void set_DoubleArray([In] ref double[] value);

[DispId(13), Description("A Bunch Of Doubles")]
double[] get_DoubleArray();

I do get the signatures I want (but not flagged as properties, and with the wrong dispid). Replacing the typelib with one that matches the original results in a different marshaling error: "SafeArray cannot be marshaled to this array type because it has either nonzero lower bounds or more than one dimension." In other words, issue #3 again; so this looks like it works, at least as well as any other method with a pointer-to-safearray.
Any insight into any of these issues (and #3 in particular) would be appreciated.


text:
Q: How to set service worker with webpack encore? About everything is in the title, I would like to know how to set my service worker with Webpack Encore.
I tried to use .addEntry('sw', './assets/js/sw.js') inside webpack.config.js, but,
while navigator.serviceWorker.register("/build/sw.js") is working in dev env,
the compiled file in prod is renamed /build/sw.8346cedc.js, which doesn't match the call anymore.
What should I do to be able to call my service worker?

A: You can obtain service worker script path using {{ encore_entry_js_files('sw') }} twig function.
Create a global variable in html like following snipped.
<script>
var swPath = "{{ encore_entry_js_files('sw') | first }}";
</script>

You can still get trouble if your webpack.config.js has .splitEntryChunks() function because runtime.js is going to be seperated.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Returning values from function in python 3.5 I am aware that this question was asked before and I have checked the answers, tried the solutions but so far I couldn't achieve what I want.
Essentially I defined 2 different functions which print values from different sources. What I am trying to do is grab those values and compare them with each other.
coins_list_text_file= open("coins.text","r").read().split("\n")
coins_list_text_file = list(filter(None, coins_list_text_file))

def wazi():
    symbol = list(map(lambda x: "{}{}".format(x, "inr").lower(), coins_list_text_file))
    response = requests.get('https://api.wazirx.com/sapi/v1/tickers/24hr')
    wazirx_list = json.loads(response.content)
    filtered_list = [d for d in wazirx_list if d["symbol"] in symbol]
    for values in filtered_list:
        w_symbol = str(values["symbol"])
        w_bid_price = float(values["bidPrice"])
        w_ask_price = float(values["askPrice"])

def binance(): #check prices on binance exchange
    symbol = list(map(lambda x: "{}{}".format(x, "USDT"), coins_list_text_file))
    response = requests.get('https://api.binance.com/api/v3/ticker/24hr')
    binance_list = json.loads(response.content)
    filtered_list = [d for d in binance_list if d["symbol"] in symbol] #filter binance list
    for values in filtered_list:
        binance_symbol = str(values["symbol"])
        binance_bid_price = float(values["bidPrice"])
        binance_ask_price = float(values["askPrice"])

def compare(): #this part is not working
    if binance_symbol == w_symbol
        if binance_ask_price < w_ask_price:
            print("buy" + binance_symbol + "on Binance")
        else:
            print("buy" + binance_symbol + "on Wazirx")

compare()

A: I think you are looking for something like this, try this it will work:
import requests
import json

def compare():
  wazi_symbol = list(map(lambda x: "{}{}".format(x, "USDT").lower(), coins_list_text_file))
  response_wazi = requests.get('https://api.wazirx.com/sapi/v1/tickers/24hr')
  wazirx_list = json.loads(response_wazi.content)
  wazi_filtered_list = [d for d in wazirx_list if d["symbol"] in wazi_symbol]

  binance_symbol = list(map(lambda x: "{}{}".format(x, "USDT"), coins_list_text_file))
  binance_response = requests.get('https://api.binance.com/api/v3/ticker/24hr')
  binance_list = json.loads(binance_response.content)
  binance_filtered_list = [d for d in binance_list if d["symbol"] in binance_symbol]

  for wazir_value in wazi_filtered_list:
    for binance_value in binance_filtered_list:
      #print(str(wazir_value["symbol"]).lower()," ",str(binance_value["symbol"]).lower())
      if str(wazir_value["symbol"]).lower() == str(binance_value["symbol"]).lower():
        if float(wazir_value["bidPrice"]) < float(binance_value["bidPrice"]):
          print("buy {} on Binance".format(str(binance_value["symbol"])))
        else:
          print("buy {} on wazir".format(str(binance_value["symbol"])))

compare()

A: The reason why your code is not working is that the variables you are trying to compare
    if binance_symbol == w_symbol
        if binance_ask_price < w_ask_price:
            print("buy" + binance_symbol + "on Binance")
        else:
            print("buy" + binance_symbol + "on Wazirx")

which are binance_symbol  and w_symbol
are not defined in the scope of the function.
When defining a function, all variables defined inside the function are only available in that context. If you would like to access those variables outside the function you would either have to define them as global variables, which is not as good a solution, or return them and get them outside of that function.
You are doing neither.
You should add return statements at the end of the functions manipulating the variables you are interested in (in your case those will be wazi and binance) and, get the results and use those when doing the Comparison.


text:
Q: Convert large CSV file to excel using Python 3 this is my code covert CSV file to .xlsx file, for small size CSV file this code is working fine, but when I tried for larger size CSV files, Its shows an error.
import os
import glob
import csv
from xlsxwriter.workbook import Workbook

for csvfile in glob.glob(os.path.join('.', 'file.csv')):
    workbook = Workbook(csvfile[:-4] + '.xlsx')
    worksheet = workbook.add_worksheet()
    with open(csvfile, 'r', encoding='utf8') as f:
        reader = csv.reader(f)
        for r, row in enumerate(reader):
            for c, col in enumerate(row):
                worksheet.write(r, c, col)
    workbook.close()

the error is
File "CsvToExcel.py", line 12, in <module>
for r, row in enumerate(reader):
_csv.Error: field larger than field limit (131072)
Exception ignored in: <bound method Workbook.__del__ of
<xlsxwriter.workbook.Workbook object at 0x7fff4e731470>>
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/xlsxwriter/workbook.py", line
153, in __del__
Exception: Exception caught in workbook destructor. Explicit close() may be
required for workbook.

A: While using large files, it's better to use 'constant_memory' for controlled memory usage like:
workbook = Workbook(csvfile + '.xlsx', {'constant_memory': True}).

Ref: xlsxwriter.readthedocs.org/en/latest/working_with_memory.html

A: I found Out New Code with panda package, this code is working fine now
import pandas
data = pandas.read_csv('Documents_2/AdvMedcsv.csv')
data = data.groupby(lambda x: data['research_id'][x]).first()
writer = pandas.ExcelWriter('Documents_2/AdvMed.xlsx',engine='xlsxwriter')data.to_excel(writer)
writer.save()


text:
Q: How do I setup one GPIO of raspberry to receive float numbers So, how do I connect a wire to a gpio on my raspberry and start receiving data, like an int or a float number

A: Raspberry got great documentation for wiring a simple button to the Raspberry Pi GPIO on https://www.raspberrypi.org/learning/physical-computing-guide/pull_up_down/
To receive float numbers, you could use the Raspberry SPI peripheral. Mathworks got a great example for creating a digital voltmeter with Raspberry and the MPC3008 Analog to Digital converter on https://www.mathworks.com/examples/matlab/mw/raspberrypiio_product-raspi_build_a_digital_voltmeter-build-a-digital-voltmeter

A: Just to mention since it's not there yet (or only implicitly in the above answer): For actually reading values you need to use an AD converter, since the RPis GPIOs are digital IOs only. So, you cannot receive more then a high or low signal from them. AD conversion instead will use the I2C-Bus for reading the values comming from the converter.


text:
Q: Select values from a date column without consider seconds value in SQL I have a SQL table which has a DATETIME column(EndTime). From my code I am passing a date and I want to get the date that has an EndTime equal to that date. I used
SELECT MAX([EndTime]) FROM [dbo].[Table]  where [EndTime]=@date

What I want is if I pass 2013-06-14 10:35 to the query it should return all the records in this time. But due to the seconds value in the table it returns only the value which has 2013-06-14 10:35:000. How can I ignore the seconds part in the column?

A: Why not try something like
SELECT MAX([EndTime])
FROM [dbo].[Table]
where [EndTime]>=@date
AND [EndTime]<DATEADD(minute,1,@date)

OR even
SELECT MAX([EndTime])
FROM [dbo].[Table]
where convert(varchar(16),EndTime,120) = @date

A: You can also try below to remove seconds
SELECT MAX([EndTime])
FROM [dbo].[Table]
where   DATEadd(ss,-datepart(ss,EndTime),EndTime) = @date


text:
Q: What kind of caching machanism is used over at Wikipedia? If you open up your mozilla Firefox web browser and turn on firebug to check for incoming and outcoming network traffic, you see that, when you look at Wikipedia articles, the amount of cached content is very large.
Unless the article in question has many pictures, most of the content comes from the cache.
I'd like to know whether that is done by the browser itself or if it's some underlying PHP Caching mechanism. (is that what they call memcache?APC?) It works very well so I'd like to know how they do it.

A: Memcacahe, APC etc are server side data stores. You basically use it as a key value store so you don't have to ping your database all the time.
However, what you're actually seeing is a site being loaded on a primed cache. This is the technique of telling your web server to let the browser know that your commonly used resources haven't changed since the last time you viewed it. This effect is achieved by setting far future headers so that the browser doesn't keep requesting the resources. A lot of sites use this technique, including SO.
Here's a great source to read up on, if you want more info : http://developer.yahoo.com/performance/rules.html


text:
Q: Hibernate and Scala I have been toying with Scala and I was wondering if anyone had had any experience with using hibernate and mysql as a persistent store for scala objects? Does it work out of the box or is there a lot to do?

A: Scala Query is not Hibernate but may be interesting.

*

*http://github.com/szeiger/scala-query

*http://szeiger.de/blog/category/scala/scala-query/

*www.cs.uwm.edu/~dspiewak/papers/scalaql.pdf

A: There are issues.  Because some features of JPA leverage nested annotations, e.g. collections, you're in trouble because Scala does not yet support nested annotations.  That'll go away when 2.8 comes out.
See Wille Faler's Blog for more on this topic plus other incompatibilities.

A: Note that Scala 2.8, now in RC5 and expected to release shortly, supports nested annotations.  The release has many other cool features as well.

A: I am using hibernate with Scala. The real problem that I had to solve was how to persist Enumerations in hibernate. I've put my working solution on github
Scala-enumeration-hibernate
Basically one needs to define own UserType
abstract class EnumerationAbstractUserType(val et: Enumeration) extends UserType {
   ....
  override def nullSafeGet(resultSet: ResultSet, names: Array[String], session: SessionImplementor, owner: Object): Object = {
    val value = resultSet.getString(names(0))
    if (resultSet.wasNull()) null
    else et.withName(value)
  }

  override def nullSafeSet(statement: PreparedStatement, value: Object, index: Int, session: SessionImplementor): Unit = {
    if (value == null) {
      statement.setNull(index, Types.VARCHAR)
    } else {
      val en = value.toString
      statement.setString(index, en)
    }
 }

A: Most of the time, Scala + Hibernate works quite well, with minor bumps which could be overcome easily. For exmaple, when dealing with collections, Hibernate requires the use of java.util interfaces. But you could import scala.collection.jcl.Conversions._ if you want to tap on Scala's more powerful library.
You may want to check out Frank Sommers' post for more information.

A: I have not used Hibernate with scala directly, but I am using JPA. Hibernate provides a JPA implementation, and the way you define JPA persistent classes or Hibernate ones is not much different, so I think using Hibernate without the JPA layer is possible

A: It is definitely not a lot of work. A simple hibernate + scala example can be defined in a few tens of lines. Scala and Java can be mixed up in the same project. In particular, the hibernate-scala combination makes possible to combine the JPA framework, and a very flexible orm layer with the elegance of immutable structures and functional programming as provided by scala.
The easiest way to experiment with hibernate and scala is by using an in-memory hsqldb database via hibernate/jpa. First off, let's define the domain model. In this case, a scala class annotated according to hibernate style, about my buddies.
package nl.busa.jpa
import javax.persistence._

@Entity
@Table(name = "buddy")
class Buddy(first: String, last: String) {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    var id: Int = _

    var firstName: String = first
    var lastName: String  = last

    def this() = this (null, null)

    override def toString = id + " = " + firstName + " " + lastName
}

Note how the scala class, is much more compact than the java class, since we don't need the typical getter/setter boilerplate code. Now let's make sure, that the jpa modules and the database model is loaded. According to the hibernate specification, let's add the well known hibernate configuration file: resources/META-INF/persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
        version="2.0">
    <persistence-unit name="nl.busa.jpa.HibernateJpaScalaTutorial">
        <description>
        Persistence unit for the JPA tutorial of the Hibernate Getting Started Guide
        </description>
        <class>nl.busa.jpa.HibernateJpaScalaTutorial</class>
        <properties>
            <property name="javax.persistence.jdbc.driver" value="org.hsqldb.jdbcDriver"/>
            <property name="javax.persistence.jdbc.url" value="jdbc:hsqldb:mem:JpaScala"/>
            <property name="hibernate.show_sql" value="false"/>
            <property name="hibernate.hbm2ddl.auto" value="create"/>
        </properties>
    </persistence-unit>
</persistence>

After defining the persistency configuration, let's move on the main scala file:
package nl.busa.jpa

import javax.persistence.EntityManager
import javax.persistence.EntityManagerFactory
import javax.persistence.Persistence

import scala.collection.JavaConversions._

object HibernateJpaScalaTutorial      {

  var entityManagerFactory: EntityManagerFactory = Persistence.createEntityManagerFactory( "nl.busa.jpa.HibernateJpaScalaTutorial" )
  var entityManager: EntityManager = entityManagerFactory.createEntityManager()

  def main( args : Array[String]) {

    entityManager.getTransaction().begin()
    entityManager.persist( new Buddy( "Natalino", "Busa" ) )
    entityManager.persist( new Buddy( "Angelina", "Jolie" ) )
    entityManager.persist( new Buddy( "Kate", "Moss" ) )
    entityManager.getTransaction().commit()

    entityManager.getTransaction().begin();
    val allBuddies = entityManager.createQuery("From Buddy", classOf[Buddy]).getResultList.toList
    entityManager.getTransaction().commit();

    allBuddies foreach println

    entityManager.close();

  }
}

The code is quite straightforward. Once the JPA EntityManager is created via the factory, the data model is available for insertion, deletion, query, using the methods defined in the documentation of hibernate and jpa.
This example has been set up using sbt. After retrieving the necessary packages, and compiling the source, running the tutorial will produce the following log:
HibernateJpaScalaTutorial:-:1.0.0> run
[info] Running nl.busa.jpa.HibernateJpaScalaTutorial
1 = Natalino Busa
2 = Angelina Jolie
3 = Kate Moss
[success] Total time: 4 s, completed Dec 9, 2012 4:18:00 PM

A: Have a look at Scala version of Play Framework where there is full JPA adaptation for Scala.


text:
Q: How to read messages in flight status and delete it by boto library For testing purpose, I need to read the messages in flight and delete the messages in flight. I can't find a suitable solution so I use work around way now
to read messages in flight
 1. stop message consumer process
 2. wait for message is available and read it but not delete
 3. start message consumer process
to delete message in flight (try clear() but it only delete message available)
 1. delete queue
 2. recreate queue
Any better solution?

A: You can't view or delete messages in flight, unless you delete/view them from the consumer to whom they are currently 'in flight' to.
Messages become 'in flight' when a consumer requests them, so if you want to delete the message, you can, as long as its the same consumer that requested the message in the first place.
Its not entirely clear what you are trying to accomplish, if you gave a better explanation of the ultimate goal, perhaps someone could suggest a better solution.
BTW, you no longer need to delete a queue if you want to delete the messages in a queue all at once - there is a new 'purge queue' option just released in the last month or so - if that helps with your solution
http://docs.aws.amazon.com/cli/latest/reference/sqs/purge-queue.html


text:
Q: How to implement bluetooth pan profile in iphone I am having a iOS project which interacts with a bluetooth hardware device using bluetooth PAN profile. As i see, Apple supports bluetooth PAN profile. I tried to search for how to implement, but i have not find out the answer. Could any one help me, is it possible to implement PAN profile in iOS, or which iOS framework support? Thanks!

A: iPhone does not support PANU role APIs(to app developers), but supports NAP role in PAN. Third party devices can issue PANU connection to iPhone.


text:
Q: form submit with setTimeout not working as expected I am submitting a form based on a condition and a setTimeout statement in submit event handler, however the form is still getting submitted even when I put return false in setTimeout function.

bool = true;
$('.form-example').submit(function(e) {
    //some_stuff where I am get a value true or false in variable bool
    setTimeout(function () {
        if(bool) {
            console.log('form shouldnt submit coz the following statement is return false');
            return false;
        }else{
            return true;
        }
    }, 1000);
});

<form action="" method="post" class="form-example">

            Enter your name:
            <input type="text" name="username" id="username" required>

        <input type="submit" name="submit_user">
    </form>

A: You should use e.preventDefault() only when you don't want to submit form.

var bool = false;
$('.form-example').submit(function(e) {
    //some_stuff where I am get a value true or false in variable bool
    if(bool) {
        alert('Not submit');
         e.preventDefault();
         return false;
    } else {
         alert('Submit');
        return true;
    }
});

<form action="" method="post" class="form-example">

            Enter your name:
            <input type="text" name="username" id="username" required>

        <input type="submit" name="submit_user">
    </form>

A:

bool = false;
$('.form-example').submit(function(e) {
    e.preventDefault();
    //some_stuff where I am get a value true or false in variable bool
        if(bool) {
            alert('Not submit');
            return false;
        }else{
            alert('Submit');
            $(this).unbind("submit").submit();
            return true;
        }
});

<form action="" method="post" class="form-example">

            Enter your name:
            <input type="text" name="username" id="username" required>

        <input type="submit" name="submit_user">
    </form>


text:
Q: Integer incompatible Joda and Java lang Getting this error:
 incompatible types
    required: java.lang.Integer
    found: java.util.Map.Entry<org.joda.time.DateTime.java.lang.Integer>

and the code resulting in error:
public static void checkRange() {

        DateTime startx = new DateTime(startDate.getTime());
        DateTime endx = new DateTime(endDate.getTime());

        //produces submap
        Map<DateTime, Integer> nav = map.subMap(startx, endx);

        //this is the line causing the error:
        for (Integer capacity : map.subMap(startx, endx).entrySet()) {

        }
}
}

I have startDate and endDate defined as Date earlier then I convert them here as u can see to DateTime. I dont think that's the problem
and the map is
public static TreeMap<DateTime, Integer> map = new TreeMap<DateTime, Integer>();

Thanks,

A: The entrySet() returns the "rows" of the map, that is, the Entry objects containing both they keys and the values. To iterate over just the values, you can use map.values(), which is a collection of Integer in this case.

A: It seems like what you want is map.subMap(startx, endx).values() instead of map.subMap(startx, endx).entrySet().


text:
Q: Implementing 0..1 relationship in tsql I have a table where I would like to remove a lot of null-columns but I am unsure if I am going in the right direction.
Here is sample SQL to show what I want (removing Quantity from Products):
CREATE TABLE [Products]([Id] [int] NOT NULL,[Name] [varchar](50))
CREATE TABLE [StockProducts]([Id] [int] NOT NULL,[Quantity] [int])
go
insert into Products (Id, [Name]) values (1,'Socks')
insert into Products (Id, [Name]) values (2,'Gloves')
CREATE VIEW ProductStockView as select P.Id, SP.Quantity from Products P left join StockProducts SP on P.Id = SP.Id
go
select * from ProductStockView
go
update ProductStockView set Quantity = 2 where Id = 1

I would really like the update to give an insert in my StockProducts table, because I have all Ids from Products, and my existing code would keep working.
Is there a pattern for this, or would the preferred way just be to add an update trigger on the view? Right now the update statement gives: 0 rows affected.
Edit based on two comments: The Id of the Two tables should be considered primary keys (for use in frameworks like Entity Framework). And my real example is ofcourse that the table called Products in my example is an old table we have with 75 columns and the ProductStockView is what I would like to replace it with in parts of my code.

A: Thanks for the comments. This was exactly what I needed. I'll leave the answer here:
create trigger ProductStockViewUpdateTrigger
on ProductStockView instead of update
as
MERGE StockProducts as target
USING (SELECT Id, Quantity from inserted) as source
    ON target.Id = source.Id
WHEN MATCHED
    AND target.Quantity != source.Quantity
        THEN UPDATE
            SET target.Quantity = source.Quantity
WHEN NOT MATCHED by target
THEN
    INSERT ([Id], [Quantity])
    values (source.id, source.quantity);


text:
Q: Pass an authenticated user from application to B2C and back to application to update token We have a .net5 razor application which is connected to our B2C environment. In the application we have a process which updates some of the user's details including their name. We are currently displaying their name in the nav bar of the application and are getting this from User.Identity.Name.
So, when the user's name gets updated, then the value held in User.Identity.Name is not updated, so the name remains as it was.
Ideally we would like to pass the user to a screen in B2C to update the token which will get their updated name and then return to the application all in one go without the user having to do anything. Alternatively, we need to make a call to update the token behind the scene and then when the page reloads, then the name will be updated due to the token having been updated.
Currently we can't see a way of doing this, as the available asp-actions under the asp-area="MicrosoftIdentity" are limited to: Challenge, EditProfile, ResetPassord, SignIn and SIgnOut.
If we pass the user through the ResetPAssword user flow and then back to the application, then the token has updated and we get back the updated user's name. However, we wouldn't want to have to get through this process if they only update their name.
How can we go about doing this?

A: As Jas Suri - MSFT commented above, the way to do this is to pass the user to the SignUpSignIn policy, as because they are already authenticated, they will be passed through the policy screen and back to the application without any user interaction.


text:
Q: Wordpress Ajax Filter Custom Post Type by Category returns [found_posts":0,] I want to output the Post by category through an ajax filter. It works with the standard post type in the same setup but with the custom post type it's showing all post on page load but when I click on a category link it's only showing the right category id "Array ( [action] => filter_wb [category] => 17 )"
And when I output the $query it shows [found_posts":0,],
so I think it's not finding the category content.
I've already checked if the category is empty but when I filter it in the backend the posts are there...
All files are there. jquery works and the xhr is gets the admin-ajax.php 200.
I'm on that for way too long time and can't figure it out.
Maybe you have some tips for me.
//post template

<a class="js-filter-item-wb" href="<?= home_url(); ?>">All

                <?php
                $cat_args = array(
                    'taxonomy' => 'category_wb',
                    'exclude' => array(1),
                    'option_all' => 'All'
                );

                $categories = get_categories($cat_args);
                foreach($categories as $cat) : ?>

<a class="js-filter-item-wb" data-category="<?= ($cat->term_id); ?>" href="<?= get_category_link($cat->term_id); ?>"><?= $cat->name; ?>

                <?php endforeach; ?>

        <?php

        $args = array (
            'post_type' => 'wuerzburg',
            'posts_per_page' => -1,
        );

        $query = new WP_Query($args);

        if($query->have_posts()) :
            while($query->have_posts()) : $query->the_post();
                echo '
'; // grid-post-wrapper
                echo '
' . get_the_title() . '
';
                echo '
' . get_the_post_thumbnail() . '
';
                echo '
' . get_the_excerpt() . '
';
                echo '
Vorbeischauen
';
                echo '
'; // end of grid-post-wrapper
            endwhile;
        endif;
        wp_reset_postdata(); ?>

//jQuery filtering
(function($) {
      //$(document).ready(function(){
            $(document).on('click', '.js-filter-item-wb', function(e){
                  e.preventDefault();

                  var category = $(this).data('category');

                  $.ajax({
                        url: wp_ajax.ajax_url,
                        data: { action: 'filter_wb', category: category },
                        type: 'post',
                        success: function(result) {
                              $('.js-filter').html(result);
                              console.log('i work')
                        },
                        error: function(result) {
                        console.warn(result);
                        }

                  });
            });

      //});
})(jQuery);

//php filter

add_action( 'wp_ajax_nopriv_filter_wb', 'filter_wb_ajax' );
add_action('wp_ajax_filter_wb', 'filter_wb_ajax' );

function filter_wb_ajax() {

    $category = $_POST['category'];

    $args = array (
        'post_type' => 'wuerzburg',
        'posts_per_page' => -1,

    );

    if(isset($category)) {
        $args['category__in'] = array($category);
    }

    $query = new WP_Query($args);

    if($query->have_posts()) :
        while($query->have_posts()) : $query->the_post();
            echo '
'; // grid-post-wrapper
            echo '
' . get_the_title() . '
';
            echo '
' . get_the_post_thumbnail() . '
';

                //output testing
                echo 'i should print';
                //output testing

            echo '
' . get_the_excerpt() . '
';
            echo '
Vorbeischauen
';
            echo '
'; // end of grid-post-wrapper
        endwhile;
    endif;
    wp_reset_postdata();

    print_r($_POST);wp_die();
}


text:
Q: What is the best practice way to update a Flask page with data from complex API calls? I have built a website to display some of a user's relevant info from the game Destiny 2. It is currently technically functional and displays the correct data, but since it is meant to run while the user plays the game, it needs to update the info that it presents to the user. Right now I have it reloading the page via jQuery every minute but I am looking for guidance on how to do this properly.
This is a Flask site that uses OAuth 2.0 and a little jQuery for additional functionality. The flow essentially is: user clicks "Authorize" button on home page -> redirected to Bungie's site to log in and authorize the app -> redirected back to my site with the relevant OAuth tokens/headers/etc. -> Python code makes a bunch of calls to Bungie's Destiny 2 API with the authorized tokens (in some cases getting more tokens to make further calls) -> grabs only the data it needs from those calls and formats it into a custom dictionary -> sends that to a Flask template -> template generates the required elements with Jinja based on the data passed to it. The character data that is shown is just the bounties and milestones for each character a user has, on any of the three gaming platforms. As a user completes objectives, I need the view to update the completion percentages. (Ex. "Collect resources from Mercury. 3/10")
As a quick and dirty solution I just have the page reloading itself, but this creates an annoying window of about 5-10 seconds where the page is loading and the user can't navigate any of the page buttons, followed by a noticeable flash when the page loads and elements pop back into view. This is obviously not acceptable, so I have considered some different options but I am unsure how to implement them in my specific scenario.
AJAX
This seems like the most obvious solution (I have never worked with it), but as far as I can tell it needs to make a call to a specific endpoint or API. Having AJAX make the API calls to Bungie rather than Flask seems unreasonable, since there are many calls to make and they need the OAuth tokens and sometimes need info from previous calls. I have considered having my Python code send its final dictionary of info to a new Flask endpoint that I create (rather than to a template), and then having AJAX make a call to that new endpoint to retrieve just the info it needs as JSON. To do this Flask would have to run the Python code in the background every minute while the user was on the page so the AJAX call would be getting up-to-date info. Would this create any security risks with sensitive player data being on an endpoint that you could just visit? Will this cause any conflicts with multiple users being logged in at the same time, all posting to that endpoint?
Flask-SocketIO
I don't know too much about this, but it seems like a great quick-response tool for server and client, but again I wonder if there will be security/conflict issues with multiple users being on at the same time?
Flask Celery
Again, I don't know much about this but it sounds like it could potentially work. Maybe have the API calls and data processing done in a background Celery task and sent to the template? But then how could that data be displayed seamlessly on the page (like AJAX) without a reload?
JS Web Frameworks
I have some experience with Angular which is why I included this section, since it displays new info and updates the page very smoothly. Could Angular controllers be used to store user data, then be updated behind the scenes which would automatically update the view? Could something like React or Vue be used here too?
Any help with choosing and using the best tool for this job would be much appreciated!

A: I would personally go with AJAX here, simply because it is the most widely used, and will therefore have the best documentation to refer to if you get stuck. You mention you are already using JQuery, which will make AJAX integration very easy. I'm sure searching "flask AJAX jquery" will give you some good results right off the bat.
I also recommend posting the relevant code you have so far (Flask endpoints/logic). It would definitely help people help you, and is generally good StackOverflow etiquette.


text:
Q: when i run the jsp file,it is showing like that picture...pls give some instructions http://postimg.org/image/vp16ta97d/
Can anyone tell me why it is showing like that?
Pls give me some instruction.
I already installed JDK also,but it didn't work.
Thanks in advance.

A: http error:503 states  The request was not completed. The server is temporarily overloading or down. Make sure that your server is up and then try access your JSP
For that run this in browser http://localhost:8080. You can check server.xml for your port information


text:
Q: Memory mapped IO concept details I'm attempting to figure out what the best way is to write files in Windows. For that, I've been running some tests with memory mapping, in an attempt to figure out what is happening and how I should organize things...
Scenario: The file is intended to be used in a single process, in multiple threads. You should see a thread as a worker that works on the file storage; some of them will read, some will write - and in some cases the file will grow. I want my state to survive both process and OS crashes. Files can be large, say: 1 TB.
After reading a lot on MSDN, I whipped up a small test case. What I basically do is the following:

*

*Open a file (CreateFile) using FILE_FLAG_NO_BUFFERING | FILE_FLAG_WRITE_THROUGH.

*Build a mmap file handle (CreateFileMapping) on the file, using some file growth mechanism.

*Map the memory regions (MapViewOfFile) using a multiple of the sector size (from STORAGE_PROPERTY_QUERY). The mode I intend to use is READ+WRITE.

So far I've been unable to figure out how to use these construct exactly (tools like diskmon won't work for good reasons) so I decided to ask here. What I basically want to know is: how I can best use these constructs for my scenario?
If I understand correctly, this is more or less the correct approach; however, I'm unsure as to the exact role of CreateFileMapping vs MapViewOfFile and if this will work in multiple threads (e.g. the way writes are ordered when they are flushed to disk).

*

*I intend to open the file once per process as per (1).

*Per thread, I intend to create a mmap file handle as per (2) for the entire file. If I need to grow the file, I will estimate how much space I need, close the handle and reopen it using CreateFileMapping.

*While the worker is doing its thing, it needs pieces of the file. So, I intend to use MapViewOfFile (which seems limited to 2 GB) for each piece, process it annd unmap it again.

Questions:

*

*Do I understand the concepts correctly?

*When is data physically read and written to disk? So, when I have a loop that writes 1 MB of data in (3), will it write that data after the unmap call? Or will it write data the moment I hit memory in another page? (After all, disks are block devices so at some point we have to write a block...)

*Will this work in multiple threads? This is about the calls themselves - I'm not sure if they will error if you have -say- 100 workers.

*I do understand that (written) data is immediately available in other threads (unless it's a remote file), which means I should be careful with read/write concurrency. If I intend to write stuff, and afterwards update a single-physical-block) header (indicating that readers should use another pointer from now on) - then is it guaranteed that the data is written prior to the header?

*Will it matter if I use 1 file or multiple files (assuming they're on the same physical device of course)?

A: Memory mapped files generally work best for READING; not writing. The problem you face is that you have to know the size of the file before you do the mapping.
You say:

in some cases the file will grow

Which really rules out a memory mapped file.
When you create a memory mapped file on Windoze, you are creating your own page file and mapping a range of memory to that page file. This tends to be the fastest way to read binary data, especially if the file is contiguous.
For writing, memory mapped files are problematic.


text:
Q: Error with using defaults in copy constructor of a templated class I have the following templated classes,
template <typename Real>
class Marker {

 typedef Wm5::Vector3<Real> Position ;
 typedef Wm5::Vector3<Real> Normal ;
 typedef Wm5::Vector3<Real> Color ;

 public:

  Marker(int id = -1, Position position = Wm5::Vector3<Real>::ZERO, Normal normal = Wm5::Vector3<Real>::ZERO, Color color = Wm5::Vector3<Real>::ZERO)
: id_(id), position_(position), normal_(normal), color_(color), cluster_(-1) {}

  ~Marker() {}

 private:

  int id_ ;
  Position position_ ;
  Normal normal_ ;
  Color color_ ;
  int cluster_ ;

};

template <typename T>
class MarkerSet {

    typedef Marker<T> MarkerT ;
    typedef std::vector<MarkerT> MarkerVector ;

public:

    MarkerSet::MarkerSet(int id = -1, MarkerVector markers = MarkerVector())
   {id_ = id; markers_ = markers;}

   MarkerSet::~MarkerSet() {}

private:

    int id_ ;
    MarkerVector markers_ ;

} ;

When I try to create a MarkerSet object by
MarkerSet<double> markerSet ;

Getting this linker error,
error LNK2001: unresolved external symbol "public: __thiscall     MarkerSet<double>::MarkerSet<double>(int,class std::vector<class Marker<double>,class std::allocator<class Marker<double> > >)" (??0?$MarkerSet@N@@QAE@HV?$vector@V?$Marker@N@@V?$allocator@V?$Marker@N@@@std@@@std@@@Z)

I would be extremely grateful if somebody could give me a pointer in the right direction with regards to what I have done wrong.
Edit:
Ok I have narrowed it down to something rather odd.
in .h
  MarkerSet(int id = -1, MarkerVector markers = MarkerVector())
{id_ = id; markers_ = markers;}

builds fine
Rather than in .h
 MarkerSet(int id = -1, MarkerVector markers = MarkerVector()) ;

in .cpp
 template <typename T>
 MarkerSet<T>::MarkerSet(int id, MarkerVector markers) {

  id_ = id ;
  markers_ = markers ;

}

Errors out in the way described above.
Any thoughts?

A: Can you try using a different compiler? I tried playing with it and the following works fine for me with gcc. I eliminated the Wm5 members as I don't have those. Pasting the header and cpp:
test.h
#include <vector>

template <typename Real>
class Marker {

 public:

  Marker(int id = -1,int _position=1)
    : id_(id), position(_position){}

  ~Marker() {}

 private:

  int id_ ;
  int position ;
  Real r;

};

template <typename T>
class MarkerSet {

    typedef Marker<T> MarkerT ;
    typedef std::vector<MarkerT> MarkerVector ;

public:

    MarkerSet(int id = -1, MarkerVector markers = MarkerVector())
      {id_ = id; markers_ = markers;std::cout<<"Called"<<std::endl;}

   ~MarkerSet() {}

private:

    int id_ ;
    MarkerVector markers_ ;

} ;

test.cpp
#include <iostream>
#include <vector>
#include "test.h"

using namespace std;

int main(int argc, const char **argv) {
  cout<<"Hello"<<endl;
  MarkerSet<double> ms;
  return -1;

}

cmd:
bash$ ./test
Hello
Called
bash$

Template class definition need to be in the header:
Why do C++ template definitions need to be in the header?

A: May it be so that you do not #include actual contructor body so that the linker does not generate required code for MarkerSet<double>::MarkerSet<double>(int,class std::vector<class Marker<double>,class std::allocator<class Marker<double> > >)"?


text:
Q: how to know all INSERT SUCCESS in mysqli_multi_query i have code, and that code generate this syntax:
$sql = "INSERT.....,; INSERT......,; INSERT.....,; INSERT......;";
if(mysqli_multi_query($connection,$sql)){
    echo "SUCCESS!";
}else{
    echo "FAILED!";
}

how to know ALL INSERT IS SUCCESS from mysqli_multi_query()?,

mysqli_multi_query return a bool (true or false), but if i have many INSERT  in that function and Only 1 entered from some INSERT, that function is return TRUE.

I want to make sure all the commands run perfectly.


text:
Q: Simple random walk bound hitting problem I am trying to understand the example 2.2. from this course
It is below. However, I am struggling to understand a key step in the reasoning. Specifically, I don't understand why this statement is true.
If we let f(−B + 1) = α, then it follows that f(−B + r) = αr for all r ≤ A + B.

given this the solution is obvious algebra, but I just don't understand this at all. Any help would be appreciated.

Suppose that a gambler plays the following game. At each turn the
dealer throws an un-biased coin, and if the outcome is head the
gambler wins $1, while if it is head she loses \$1. If each coin toss
is independent, then the balance of the gambler has the distribution
of the simple random walk.
For two positive integers A and B, what is the probability that the
random walk reaches A before it reaches −B? Let τ be the first time at
which the random walk reaches either A or −B. Then Xτ = A or −B.
Define f(k) = P(Xτ = A | X0 = k), and note that our goal is to compute
f(0). The recursive formula f(k) =
0.5 f(k + 1) + 0.5 f (k −1) follows from considering the outcome of the first cointoss. We also have the boundary conditions f(A) = 1,
f(−B) = 0. If we let f(−B + 1) = α, then it follows that f( 1 −B + r)
= αr for all r ≤ A + B. Therefore, α = A+B , and it follows that

A: You can prove this by induction, and rearranging the formula to the form:
$$f(k) = 2f(k-1) - f(k-2)$$.
Supposing $f(-B + s) = \alpha s$ for $1 \leq s \leq r-1$ then
$$
\begin{align}
f(-B + r) & = 2f(-B + r-1) - f(-B +r - 2) \\
& = 2\alpha(r-1) - \alpha(r-2) \\
& = \alpha r.
\end{align}
$$


text:
Q: Java: pass object in pointer in parameter(pass by reference) I have created a list of objects and also list of threads which the parameter sent is a random object from the list. Once the thread is created, the thread should lock on the object passed in the parameter. However, although I have set the thread to sleep after creating it to form deadlock. There doesnt seem to be any deadlock formed. Based on some google research, I learned that object is pass by reference in java however I m not sure why it is not working here.
for(int i=0;i<5;i++){
   Object tempObject = new Object();
   objectList.add(tempObject);
}

Random rand = new Random();
for(int i =0;i<5;i++){
    for(int j =0;j<10;j++){
        int random = rand.nextInt(objectList.size());
        CustomThread ct = new CustomThread(i,objectList.get(random));
        ct.start();
        System.out.println();
    }
    try {
        detectDeadlock();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

public static void detectDeadlock() throws InterruptedException {
    while(true){
        ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
        long[] threadIds = threadBean.findDeadlockedThreads();
        int deadlockedThreads = threadIds != null? threadIds.length : 0;
        System.out.println("Number of deadlocked threads: " + deadlockedThreads);
        TimeUnit.MILLISECONDS.sleep(1000);
    }
}

CustomThread.java
NewThread(int processID, Object tObject) {
    this.pid = processID;
    this.object = tObject;
}

@Override
public void run() {
    synchronized (this.object) {
        Random rand = new Random();
        System.out.println("Holding an object");
        try { TimeUnit.MILLISECONDS.sleep(rand.nextInt(10000)); }
        catch (InterruptedException e) {}
    }
}

A: What is happening here is you have 5 instances of CustomThread which each get a unique object, lock on it, and go to sleep. The other 5 threads get an object which is already in use, and so when their CustomThread attempts to lock on it, they must wait a max. of 10 seconds for the first thread to complete. At this point the second thread is able to lock on the object and it does.
Your use of Random means it's not literally the first 5 get a unique object and the second 5 don't but the basic idea is the same, the second CustomThread simply waits for the first to be done.
If you want to create a true deadlock you need the first thread which holds the lock to need something from the second thread which is waiting on the lock. It needs to be a circular dependency, Thread A waiting on Thread B while at the same time Thread B is waiting on Thread A. In your case you only have Thread B waiting on Thread A.
Found a question which may point you towards how to create a deadlock;

*

*Write a program that will surely go into deadlock


text:
Q: Passing HTML from serverside to datatables I am changing my Datatables to load content from my Rails app. In one of the cells I have a big chunk of HTML, and since when using the server-side approach the cells are printed with Javascript, I would need to pass the HTML from Rails.
So, here is how it looks one of the cells with datatables WITHOUT server side fetching:

            <%= link_to 'Show pages', admin_order_pages_path(order.id), :class => 'btn btn-primary' %>

          <% if order.status.name == 'reviewed' %>

              <%= form_tag(admin_order_set_completed_status_path(order), :method => 'patch' ) do %>
                <%= submit_tag 'Complete order', class: 'btn btn-success', data: { confirm: 'Are you sure you want to complete this order?' } %>
              <% end %>

          <% end %>

          <% if order.status.name == 'queued' %>

              <%= form_tag(admin_order_process_order_path(order), :method => 'post' ) do %>
                <%= submit_tag 'Process order', class: 'btn btn-success', data: { confirm: 'Are you sure you want to process this order?' } %>
              <% end %>

          <% end %>

          <% if order.status.name != 'processing' %>

              <%= form_tag(admin_order_path(order), :method => 'delete' ) do %>
                <%= submit_tag 'Delete order', class: 'btn btn-danger', data: { confirm: 'Are you sure you want to delete this order?' } %>
              <% end %>

          <% end %>

Now, since all the data will come back from Rails, I would need to pass that HTML via a JSON. Isn't that breaking the MVC? How do you deal in these situations?

A: If you are wanting to use json with ajax for datatables you can use JBuilder or rabl to create a json document that can be easily reused.
Also there is not a need to write out form_tags wrapped around submit_tags to call different methods, with rails you can use link_to and specify the :method to accomplish the same thing.

    <%= link_to 'Show pages', admin_order_pages_path(order), :class => 'btn btn-primary' %>

  <% if order.status.name == 'reviewed' %>

      <%= link_to "Complete order", admin_order_set_completed_status_path(order), method: :patch, class: 'btn btn-success', data: { confirm: 'Are you sure you want to complete this order?' }%>

  <% end %>

  <% if order.status.name == 'queued' %>

      <%= link_to "Process order", admin_order_process_order_path(order), method: :post, class: 'btn btn-success', data: { confirm: 'Are you sure you want to process this order?' }%>

  <% end %>

  <% if order.status.name != 'processing' %>

      <%= link_to "Delete order", admin_order_path(order), method: :delete, class: 'btn btn-danger', data: { confirm: 'Are you sure you want to delete this order?' }%>

  <% end %>


text:
Q: Usage of force:navigateToComponent and force:navigateToSObject I'm using one custom lightning component to replace emailauthor.jsp for lightning experience. I'm using force:navigateToComponent event to redirect from custom object lightning page to send email lightning component. Also to return to custom object page I'm using force:navigateToSObject event. What I've noticed when using debugger in Chrome is that once created send email lightning component is never destroyed after going back to custom object lightning page. Is this something that is missing in implementation or should I destroy it explicitly. Could this result in memory leak. Also DOM of the component is still there.
Navigate to component:
btnSendEventReport: function(component, event, helper) {
    var self = this;
    var record = component.get('v.record');
    var action = component.get('c.getEmailAttributes');
    var withTeamMembers = confirm('Would you like to send this to the Client Team?');

    action.setParams({
        recordId: record.Id,
        clientId: record.Relate_to_Client__c,
        withTeamMembers: withTeamMembers
    });

    action.setCallback(self, function(result) {
        var navigateToComponent = $A.get("e.force:navigateToComponent");
        navigateToComponent.setParams({
            componentDef: "c:SendEmail",
            componentAttributes: result.getReturnValue()
        });
        navigateToComponent.fire();
    });

    $A.enqueueAction(action);
},

Returning to custom object Lightning page:
navigateToRecord : function(component) {
    var objectId = component.get("v.objectId");
    var navigateToSObject = $A.get("e.force:navigateToSObject");
    if (navigateToSObject) {
        navigateToSObject.setParams({
            recordId: objectId
        });
        navigateToSObject.fire();
    }
},

Thanks!

A: This question is a bit old but still relevant. The quote in the previous answer is not fully accurate according to developers' experience. Lightning Experience does not immediately destroy components no longer in use but rather just hides them from the UI. This is probably an optimization that prevents the browser from expending resources on the destruction that it could be spending on rendering whatever else the user needs now. If the user pokes around to enough new places, LEX eventually destroys the old components.
If you start at Lightning page A, view its DOM in Developer Tools, then start navigating to B, C, D, E, you'll see that it's still there. But notably, if you navigate to A again, A immediately gets zapped from the DOM and recreated.
Developers should take notes: Because your components are not fully destroyed, you cannot rely fully on cmp.isValid() to tell you whether your component is in active use.

A: That is a good question. Based on following excerpt from lightning component developer guide, the framework destroys the component if it was added via markup or added to a facet if dynamically created. My assumption is since the framework is creating the component when called via navigateToComponent, it destroys it once it is not in use.

Destroying Dynamically Created Components
  After a component that is declared in markup is no longer in use, the framework automatically destroys it and frees up its memory. If you create a component dynamically in JavaScript and that component isn't added to a facet (v.body or another attribute of type Aura.Component[]), you have to destroy it manually using Component.destroy() to avoid memory leaks.


text:
Q: How can I make a functioning piston elevator in SMP I've recently been trying to build a piston elevator in SMP from bedrock to the surface. However, every design I've tried (some of my own, and some from Youtube) results in me getting stuck in a block part of the way up. Are there any ways to get around this? If it's lag related would slowing the elevator down by adding an extra repeater or two between each level be sufficient?

A: To make a piston elevator I use the "staircase" design
The way this design works is by pushing you up stairs using pistons.
Here are some pictures of how this works:
Note: The first repeater is on 2-delay, and the second is on 1-delay.In the screenshots is different, sorry.


text:
Q: Microservices can't communicate using Docker for Mac I am trying to get two containers that are each running a different Go service. Both services were built with the net/http package. I have an API frontend as one and an Authentication service backend.
Here is my compose file:
version: "2"
services:
  staticfiles:
    build: ./files
    volumes:
      - /public
      - /views
  api:
    build: ./api
    environment:
      - PORT=8080
      - BASE_URL=https://example.org
      - AUTH_HOST=auth
      - AUTH_PORT=8080
      - VIEW_DIR=/views
      - PUBLIC_DIR=/public
    ports:
      - "80:8080"
    volumes_from:
      - staticfiles:ro
    links:
      - auth
    depends_on:
      - staticfiles
  db:
    build: ./postgres
    environment:
      - POSTGRES_USER=inheritor
      - POSTGRES_DB=inheritor
  auth:
    build: ./auth
    expose:
      - "8080"
    environment:
      - PORT=8080
      - DB_USER=inheritor
      - DB_NAME=inheritor
      - DB_HOST=db
      - DB_Port=5432
    links:
      - db

I know the links are working because from the api container I can ping auth and curl -X Post http://auth:8080/validate but within Go I get a dial address tcp i/o timeout. Here is the code.
var (
    authString = "http://" + env.AuthHost + ":" + env.AuthPort
)

//ValidateToken validates a token using the session in DB
func ValidateToken(req *model.ValidateRequest) (*model.JWTClaims, error) {
    client := new(http.Client)
    api := authString + "/validate"
    cont, err := model.Jsonify(req)
    if err != nil {
        return nil, exception.NewInternalError("Could not turn the request into a json object.")
    }

    request, err := http.NewRequest("POST", api, bytes.NewBuffer(cont))
    if err != nil {
        return nil, exception.NewInternalError("Could not create request: " + err.Error())
    }
    request.Header.Set("Content-type", "application/json")
    response, err := client.Do(request)
    if err != nil {
        return nil, exception.NewInternalError("Could not make the request: " + err.Error())
    }
    defer response.Body.Close()

    res := new(model.AuthResponse)
    res.Claims = new(model.JWTClaims)
    decoder := json.NewDecoder(response.Body)
    err = decoder.Decode(&res)
    spew.Dump(response.Body)
    if err != nil {
        return nil, exception.NewInternalError("Could not parse response back from auth service. " + err.Error())
    }

    if response.StatusCode != http.StatusOK {
        return nil, exception.NewInvalidJWTError(res.Error)
    }

    return res.Claims, nil
}

The client.Do(request) is what is throwing the Dial error. Now my auth service is not even being touched because I have a logger that prints to screen every request that is coming in.

*

*env.AuthHost is mapped to the AUTH_HOST environment variable.

*env.AuthPort is mapped to the Auth_PORT environment variable.

Much help is appreciated.
If it helps I am running MacOSX.
Client:
 Version:      1.12.0-rc4
 API version:  1.24
 Go version:   go1.6.2
 Git commit:   e4a0dbc
 Built:        Wed Jul 13 03:28:51 2016
 OS/Arch:      darwin/amd64
 Experimental: true

Server:
 Version:      1.12.0-rc4
 API version:  1.24
 Go version:   go1.6.2
 Git commit:   e4a0dbc
 Built:        Wed Jul 13 03:28:51 2016
 OS/Arch:      linux/amd64
 Experimental: true

Both Dockerfiles looks like this:
FROM golang:1.6
RUN mkdir -p /go/src/github.com/dixonwille/Inheritor/api
WORKDIR /go/src/github.com/dixonwille/Inheritor/api

COPY . /go/src/github.com/dixonwille/Inheritor/api

RUN go build -v -o Inheritor cmd/Inheritor/main.go

USER nobody
ENTRYPOINT ["./Inheritor"]

EDIT:
I ran net.LookupHost(env.AuthHost) within Go and it is returning a different IP address then ping, curl, and even docker inspect. Is this a Go thing then?
EDIT:
If I remove the port portion of the authString, the request goes through but get an error when parsing response. The response is a 301 redirect by NGINX which I think is strange because that is not even in my stack. The location header for the redirect is localhost, which I think is strange as well.
I have tried exposing a port on the host machine and accessing it with that port with no better luck (same hostname).
EDIT:
So it is a Mac only thing I assume. I cloned down the repo and ran on Windows 10 and I was able to connect to my auth service. Would this be Docker for Mac error? I am probably going to report it to them, but I would not consider this closed since it still is an issue for Mac users.

A: So Docker for Mac just came out with a new beta version today. This seemed to have fixed my issue with connecting. Now I did make changes to source code when I found out it worked on my Windows pc.
Here is the version of Docker for fix:
Client:
 Version:      1.12.0
 API version:  1.24
 Go version:   go1.6.3
 Git commit:   8eab29e
 Built:        Thu Jul 28 21:04:48 2016
 OS/Arch:      darwin/amd64
 Experimental: true

Server:
 Version:      1.12.0
 API version:  1.24
 Go version:   go1.6.3
 Git commit:   8eab29e
 Built:        Thu Jul 28 21:04:48 2016
 OS/Arch:      linux/amd64
 Experimental: true

And here is the compose file:
version: "2"
services:
  staticfiles:
    build: ./files
    volumes:
      - /public
      - /views
      - /migrations
  databasefiles:
    build: ./databasefiles
    volumes:
      - /var/lib/postgresql/data
  db:
    build: ./postgres
    depends_on:
      - databasefiles
    volumes_from:
      - databasefiles
    environment:
      - POSTGRES_USER=inheritor
      - POSTGRES_DB=inheritor
  auth:
    build: ./auth
    expose:
      - "8080"
    depends_on:
      - staticfiles
    volumes_from:
      - staticfiles:ro
    environment:
      - PORT=8080
      - DB_USER=inheritor
      - DB_NAME=inheritor
      - DB_HOST=db
      - DB_PORT=5432
      - MIGRATION_DIR=/migrations
    links:
      - db
  api:
    build: ./api
    environment:
      - PORT=8080
      - BASE_URL=https://example.org
      - AUTH_HOST=auth
      - AUTH_PORT=8080
      - VIEW_DIR=/views
      - PUBLIC_DIR=/public
    ports:
      - "80:8080"
    volumes_from:
      - staticfiles:ro
    links:
      - auth
    depends_on:
      - staticfiles

I did move services around but I do not see anything different that would change the communication between containers. This is just here incase others have same problem.


text:
Q: json - jolt : How to extract common value to key I am trying to convert a JSON to different format using JOLT (using NiFi JoltTransformJson processor).
Input Json
[
  {
    "date": "202001010000",
    "name": "test1",
    "val": "1",
    "status": "0"
  },
  {
    "date": "202001010000",
    "name": "test2",
    "val": "2",
    "status": "0"
  },
  {
    "date": "202001010001",
    "name": "test1",
    "val": "3",
    "status": "0"
  },
  {
    "date": "202001010001",
    "name": "test2",
    "val": "4",
    "status": "0"
  }
]

and I want to Output like
{
  "202001010000" : [ {
    "name" : "test1",
    "val" : "1",
    "status" : "0"
  }, {
    "name" : "test2",
    "val" : "2",
    "status" : "0"
  }
  ],
  "202001010001" : [ {
    "name" : "test1",
    "val" : "3",
    "status" : "0"
  }, {
    "name" : "test2",
    "val" : "4",
    "status" : "0"
  }
  ]
}

I'm trying to convert JSON format using Jolt Transform but it can't.

A: *

*Make the date node value as key for each object in the array.

*Remove the date node from the object.

Spec :
[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "date": {
          "@1": "@(2,date)"
        }
      }
    }
  },
  {
    "operation": "remove",
    "spec": {
      "*": {
        "*": {
          "date": ""
        }
      }
    }
  }
]


text:
Q: Data Security has been compromised In my Magento 1.9 store, some of the Customer's Default Billing name and Address
has been amended. I first got to know this when one of my customer complained to me about their name that has been changed in their profile and I thought it was a mistake caused at her side. However, after looking carefully into the store for the past 2 weeks, I can see some of customer names are getting amended.
I can see those customer addressed has also changed to Web agency company that claims to do Magento development (They are not Certified partner).
I have thought long enough to figure out how they have done such a thing, and I am still clueless. The access to DB is limited to localhost only, thus no one can access to DB with public address.
I can see the "Formkey validation on checkout is disabled". can this be the gateway for this security breach?

A: I don't know if that backend-setting is the cause, but I think that you may have a bigger problem. Here's what I would do:

*

*Check your store with https://www.magereport.com/ to see if you have all patches. It also checks for some more (known) vulnerabilities. This could give first answers. If you are vulnerable to the Shoplift-Bug, go to your admin panel and check for any admin accounts that should not be there; delete them.

*Take your store down. If someone is able to access customer data, that's not funny. If you operate inside the EU, even less funny after the latest GDPR law. The attacker could even make fake-orders in your shop and, depending on your billing agreements, have your real customers pay for it.

*Check for malicious scripts inside your store code base. Vulnerabilities of a store are most of the time caused by installed extensions - maybe you use a plugin that lets users upload PHP files, which means they could upload a webshell, which again means that they are localhost and can do what they want. Or you use a plugin that changes the login behaviour for your customers, or anything else - from my experience, for example, a lot of slider plugins are vulnerable to SQL injections.

*When you have identified how your shop has been compromised, close this vulnerability.

*Change all your database, admin and whatever passwords.

*The next step depends on the attack; most people would recommend it in any scenario, but if you only have a small shop and you are pretty sure that the attacker did not gain access, for example, to SSH or FTP, you may under careful consideration omit it: re-install your server including the OS. Then re-install your shop from scratch using the latest Magento version, or your current version but make sure to add all the patches.
If (3) and (4) are to complicated, you can omit them and go for (5) and (6) right away.
If this has happened before and you have no clue how they got in, think about switching your hosting company, because sometimes they also don't know what they're doing.
After that you should be able to re-open you shop safely.
Be sure to take all necessary legal actions, for example inform your customers if you store any sensitive data that could have been stolen - I mean, if I had access to your customer's addresses, a full export is the first thing I would do ;)


text:
Q: Shell output question What is the output of date -u +%W$(uname)|sha256sum|sed 's/\W//g' (on Arch Linux if it matters)?
How do I find that out?

A: date -u %W

Displays the current week of the year.
uname

Displays the kernel name.
sha256sum

Generates a SHA-256 Hash Sum.
sed 's/\W//g'

Cuts out all non-word characters.
The |'s are redirecting the output of the first command to the appending command.
Enter the line in a terminal, f.e. gnome-terminal or xterm:
date -u +%W$(uname)|sha256sum|sed 's/\W//g'

Depending on the date and the operating system installed, this will output different hashes, like this:
2aa4cb287b8a9314116f43b5e86d892d76a9589559aa69ed382e8f5dc493d955

A: 1. The 'uname' part
To answer the first question, the crucial thing is what uname without a parameter returns on Arch Linux. The man page does not define it, but uname Command says it is equivalent to uname -s:

-s   Displays the system name. This flag is on by default.

For -s, the man page says "print the kernel name". On Arch Linux uname returns

Linux

whereas on, for example, Cygwin uname returns something like:

CYGWIN_NT-5.2-WOW64

2. The 'date' part
date -u +%W returns the week number. As the last part ("Linux") is a fixed string, the final output depends on which week the command line is run in (the hash is computed on for example "07Linux"). With this knowledge the output can also be computed on Cygwin.
3. An example
The week number for 2012-02-18 is 7 and date -u +%W`uname` returns (has a leading zero, but this is expected for the task at hand)
07Linux

and the output from sha256sum (a SHA-2 hash) is:

4a65f65b40cc2b0a7aaa726e895d72425ede255021e2ce3e935dd2719e4d33b9

On Cygwin it can be computed as:
echo '07Linux'|sha256sum|sed 's/\W//g'

(This actually worked when I tried to register at ArchWiki...)


text:
Q: How to make a multiply rows with items with equal height I have a div with many items.
The height of this items can be changeable (When the locale of the site is changed).
Can I  display these items in rows and the height of these items should be equal? Maybe via CSS Grid, because Flex doesn't support this functionality. Maybe there is not JS solution?
See the  attached image:

HTML:

  <button class="index-deviceItem-1zoFC">
     PC/Workstation
  </button>

  <button class="index-deviceItem-1zoFC">
    Storage Array
  </button>

   <button class="index-deviceItem-1zoFC">
      Networking
   </button>

  <button class="index-deviceItem-1zoFC">
     Servers
  </button>

</div

A: Try this using css grid

.container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(3, 1fr);
  grid-gap: 10px;
}

.item {
  background: teal;
  padding: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

01

02

03

04

05

0606060606060 60606060606 0606060606060606 060606060606060606 060606060606 060606060606 0606060606 06060606

07

08

09


text:
Q: Find the derivative of a negative fractional exponent. Using the definition of the derivative
$$f'(x) = \lim_{h\to 0}\frac{f(x+h)-f(x)}{h}$$
Find  $f'(x)$ of $f(x) = 4x^{-3⁄2}$.
So far I have moved the the negative exponent to a denominator and made it positive.
$$f'(x) = \lim_{h\to 0}\frac{4}{h}\left(\frac {1}{(x+h)^{3/2}}-\frac {1}{x^{3/2}}\right)$$
At this point I consider how to move on, I considered re writing the denominator as a radical and then multiplying by the conjugate but I am not sure of the way forward.
$$\frac {1}{\sqrt[2]{(x+h)^{3}}}$$


text:
Q: "I know you're there. I can smell you!" I'm looking for a movie that scared the bejesus out of me as a kid. It was either a direct adaptation of the Grimm fairy tale, "Hansel and Gretel", or something with a similar story. Kids stuck in a house with an evil witch that wanted to eat them, that sort of thing.
The line that gave me nightmares happened at a moment where one of the children is watching the witch from hiding and after a while she says something like:

I know you're there. I can smell you!

Since this moment is the only thing that sticks out to me, these are the only details I can remember:

*

*I saw in maybe the mid 90s on TV

*I believe it was a movie but I suppose it could have been part of an anthology series or something

*It was live action

*It was in color and featured props/cosmetics typical of the time period I saw it in so I'd place its release no earlier than the late 80s but was probably newer than that. It didn't have any CGI that I recall so it likely predated the late 90s.

A: Could be Hocus Pocus:

A curious youngster moves to Salem, where he struggles to fit in
before awakening a trio of diabolical witches that were executed in
the 17th century.

"I can smell children" phrase: https://getyarn.io/yarn-clip/77fdb480-97d2-41ca-ae2b-246b1a62c75e

A: Sounds like Hansel and Gretel (1987).

Based on the fairy tale by The Brothers Grimm. Hansel and Gretel are abandoned after the famine strike in the village and where Hansel and Gretel are later trapped in the deceptively decorated house of the witch Griselda who wishes to fatten Hansel so that he may be baked into a delicious gingerbread treat.

According to Wikipedia, this was produced by the Cannon Group as part of a series of fairy tale-to-movie adaptations.

Cannon Movie Tales is the collective name for a series of live-action films created in the late 1980s by Cannon Group producers Menahem Golan and Yoram Globus, associate producer Patricia Ruben, and executive producer Itzik Kol. Filmed principally on location in Israel, these stories are generally fairy tales based on material by either the Brothers Grimm or Charles Perrault, among others. Major stars, from both the United States and the United Kingdom, play the leading roles, in which they are joined by a mostly all-Israeli cast. The major Israeli-born member of the crew was the series' production designer, Marek Dobrowolski. Announced as early as May 1986 (at the Cannes Film Festival), Cannon initiated the project as its answer to Disney's fairy-tale offerings, and invested US$50 million in the series. Sixteen stories, each costing US$1.5 million, were originally planned; only nine were released.

The "I know you're there... I can smell you!" line is spoken at the 56:13 mark in the YouTube video below.


text:
Q: Alcatel OneTouch KitKat surfaceView with camera bursts into infinite loop - SurfaceView(8099): updateWindow -- OnPreDrawListener, mHaveFrame = true The following code works flawlessly on my LG G Pro with Jelly Bean
but doesnt work on my Alcatel OneTouch with KitKat 4.4.2
EDIT: The worst thing is, this works on an HTC with 4.4.2, but doesnt on the Alcatel. WTF.
Here is my custom camera code:
    surfaceHolder = surfaceView.getHolder();
    surfaceHolder.addCallback(this);

@Override
public void surfaceCreated(SurfaceHolder holder) {
    Log.e("camera fragment", "surfaceCreated");

    int width = getResources().getDisplayMetrics().widthPixels;
    int height = getResources().getDisplayMetrics().heightPixels;

    // background
    Bitmap background = null;
    try {
        background = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_4444);
    } catch (OutOfMemoryError oome) {
        oome.printStackTrace();
        try {
            background = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        } catch (OutOfMemoryError oome2) {
            oome2.printStackTrace();
        }

    }

    Canvas canvas = null;
    if (background != null) {
        canvas = new Canvas(background);
        canvas.drawColor(Color.TRANSPARENT);
        // draw lines
        // vertical
        drawVerticalLine(canvas);
        // horizontal
        drawHorizontalLine(canvas);
        // draw text
        drawText(canvas);
    }

    BitmapDrawable d = new BitmapDrawable(getResources(), background);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
        surfaceView.setBackgroundDrawable(d);
    } else {
        surfaceView.setBackground(d);
    }

    if (camera == null)
        initCamera();

    startCamera(holder);

}

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    Log.e("camera fragment", "surfaceChanged");

    Camera.CameraInfo info = new android.hardware.Camera.CameraInfo();
    Camera.getCameraInfo(0, info);
    int rotation = a.getWindowManager().getDefaultDisplay().getRotation();
    int degrees = 0;
    switch (rotation) {
    case Surface.ROTATION_0:
        degrees = 0;
        break;
    case Surface.ROTATION_90:
        degrees = 90;
        break;
    case Surface.ROTATION_180:
        degrees = 180;
        break;
    case Surface.ROTATION_270:
        degrees = 270;
        break;
    }

    int result;
    if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
        result = (info.orientation + degrees) % 360;
        result = (360 - result) % 360; // compensate the mirror
    } else { // back-facing
        result = (info.orientation - degrees + 360) % 360;
    }
    if (camera != null) {
        camera.setDisplayOrientation(result);
        camera.startPreview();
    }

}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
    // Surface will be destroyed when we return, so stop the preview.
    stopCamera();
    Log.e("Camera Fragment", "surfaceDestroyed");
}

private void initCamera() {
    Log.e("initCamera", "initCamera");
    try {
        camera = Camera.open();
    } catch (RuntimeException e) {
        e.printStackTrace();
    }

}

private void startCamera(SurfaceHolder holder) {

    try {
        camera.setPreviewDisplay(holder);
        camera.autoFocus(new AutoFocusCallback() {

            @Override
            public void onAutoFocus(boolean success, Camera camera) {
                // TODO Auto-generated method stub

            }
        });
    } catch (Exception exception) {
        if (camera != null) {
            camera.stopPreview();
            camera.release();
            camera = null;
        }
    }

}

private void stopCamera() {

    if (camera != null) {
        camera.stopPreview();
        camera.release();
        surfaceHolder.removeCallback(this);
        camera = null;
    }

}

When I start the fragment that holds this, here is what the logs show:

A: Problem was in the following code:
    camera.autoFocus(new AutoFocusCallback() {

        @Override
        public void onAutoFocus(boolean success, Camera camera) {
            // TODO Auto-generated method stub

        }
    });

I should have checked whether the device supports auto-focus, before using this code, as per documentation:
Callers should check android.hardware.Camera.Parameters.getFocusMode() to determine if
 this method should be called. If the camera does not support auto-focus,
it is a no-op and AutoFocusCallback.onAutoFocus(boolean, Camera)
 callback will be called immediately.


text:
Q: Multiplicar id con triggers Estoy intentando multiplicar el ID con un trigger, pero me devuelve el mismo resultado.
DELIMITER //
DROP TRIGGER IF EXISTS incrementID //
CREATE TRIGGER incrementID BEFORE UPDATE ON fine
FOR EACH ROW
BEGIN
UPDATE OLD.id SET NEW.id = OLD.id * 1000;
END//

A: No entiendo muy bien el UPDATE que planteas. Prueba de esta manera a ver que tal.
DELIMITER //
DROP TRIGGER IF EXISTS incrementID //
CREATE TRIGGER incrementID BEFORE UPDATE ON fine
FOR EACH ROW
BEGIN
    UPDATE fine SET id = NEW.id * 1000 WHERE id = OLD.id;
END//


text:
Q: Derive formula for volume of liquid in a cone I have a cone with $r=1$ with the tip pointing upward.
The volume of liquid in the cone is given by
$$V(h)=\pi\left(h-\frac{h^2}{3}+\frac{h^3}{27}\right)$$
With $0\leq h\leq3$
Why?
I know the volume of cone (with height t) is given by $$V(t)=\frac13 \pi r^2t$$
$V(h)$ is a proportion of $V(t)$, and the radius is equal for both. $h$ is the variable. And $V(h)$ is maximum $1/3$ of $V(t)$ (I think?) since we $h$ is max $3$, and $$V(3)=\pi$$
And for the cone itself $$V(t)=\frac13\pi t$$
$$\frac{V(h)}{V(t)}= \frac{\pi\left(h-\frac{h^2}{3}+\frac{h^3}{27}\right)}{\frac13\pi t}$$
$$\frac{3h-h^2 + \frac{h^3}{9}}{t}=\frac3t$$ for $h=3$
Hmm.. Does not look right.

A: You can use your formula to calculate the volume of the whole cone and as you pointed out correctly, it is $\pi $.
Now if there is liquid up to a height of $h $, then the rest of the cone, the bit above, has height $3-h $ and is itself a cone right? But you know how to compute a cone's volume! All it takes is that you know its radius. You can find it with basic trigonometry but you can also use ratios:
The big cone has height $3$
The small cone has height $3 - h $
The big cone has radius $1$
The small cone has radius $\frac{3-h}{3} $ because the ratio of the lengths is $r = \frac{3-h}{3} $.
But if two solids have length ratio $r $, then their volume ratio is $r^3$ and thus the volume of the smaller cone is
$$\pi\cdot r^3 = \pi\cdot\left(\frac{3 - h}{3}\right)^3$$
Therefore the volume occupied by the liquid is
$$\pi - \pi\cdot\left(\frac{3 - h}{3}\right)^3 = \pi\cdot \left(1 - \left(\frac{3 - h}{3}\right)^3\right) $$
Which simplifies to
$$\pi\cdot\left(h-\frac{h^2}{3}+\frac{h^3}{27}\right)$$


text:
Q: Rhino Mocks - How Do You Mock 5 Calls I have 5 calls to a particular method and I wanted to return different things for each of those 5 calls.  I wanted some way in Rhino Mocks to say
For the 1st call return this
For the 2nd call return that

and so on
Is this possible?

A: Just use Repeat.Once() after each method stub. For example:
myMock.Stub(x => x.Method()).Return(1).Repeat.Once()
myMock.Stub(x => x.Method()).Return(2).Repeat.Once()


text:
Q: Problem with the responsiveness of my site I have to make a site which presents a menu of desserts for a restaurant. I used JS to make a flip-book animation. My site should mainly be adapted for phones. The problem is that on the phone when I "open" the card, the left part of menu is off the screen and I cannot scroll to get it.
Can anyone help me?

var currentPage = 0;

$(".book").on("click", ".active", nextPage).on("click", ".flipped", prevPage);

$(".book").hammer().on("swipeleft", nextPage);
$(".book").hammer().on("swiperight", prevPage);

function prevPage() {
  $(".flipped")
    .last()
    .removeClass("flipped")
    .addClass("active")
    .siblings(".page")
    .removeClass("active");
}
function nextPage() {
  $(".active")
    .removeClass("active")
    .addClass("flipped")
    .next(".page")
    .addClass("active")
    .siblings();
}
html {
  height: 100%;
}

body {
  background-color: black;
  margin: 0;
  width: 100%;
  height: 100%;
  overflow: scroll;
}

.scene {
  width: 560px;
  height: 793px;
  margin: 80px auto;
  -webkit-perspective: 2000px;
  perspective: 2000px;
}

.book {
  position: relative;
  width: 100%;
  height: 100%;
  -webkit-transform-style: preserve-3d;
  transform-style: preserve-3d;
}

.page {
  cursor: pointer;
  position: absolute;
  color: black;
  width: 100%;
  height: 100%;

  -webkit-transition: 1.5s -webkit-transform;

  transition: 1.5s transform;
  -webkit-transform-style: preserve-3d;
  transform-style: preserve-3d;
  -webkit-transform-origin: left center;
  -ms-transform-origin: left center;
  transform-origin: left center;
}

.front,
.back {
  position: absolute;

  width: 100%;
  height: 100%;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;

  -webkit-backface-visibility: hidden;

  backface-visibility: hidden;
  background: -webkit-gradient(
    linear,
    0% 0%,
    100% 100%,
    from(#ffffff),
    to(#cccccc)
  );
  background: -webkit-gradient(
    linear,
    left top,
    right bottom,
    from(#fff),
    to(#ccc)
  );
  background: -webkit-linear-gradient(top left, #fff, #ccc);
  background: linear-gradient(to bottom right, #fff, #ccc);
}

.back {
  -webkit-transform: rotateY(180deg);
  transform: rotateY(180deg);
}

.page.active {
  z-index: 1;
}
.page.flipped {
  -webkit-transform: rotateY(-180deg);
  transform: rotateY(-180deg);
}
.page.flipped:last-of-type {
  z-index: 1;
}

p {
  margin: 0;
}
<!DOCTYPE html>

Thank you in advance.


text:
Q: Uncaught mysqli_sql_exception: You have an error in your SQL syntax I cant get my update button to work, my SQL syntax isnt targeting the datebase properly, this is the syntax im using
$sql = ("UPDATE crud SET name='$name', last='$last', email='$email', birthday='$birthday' WHERE id=$id") or
    die($mysqli->error);

i tried using different syntaxs but it doesnt update the database

Fatal error: Uncaught mysqli_sql_exception: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version

<!DOCTYPE html>

  <title>Using PHP and a Database</title>

   <form action="people-list.php" method="post">
    <input type="hidden" name="id" value="<?php echo $id; ?>">

        First Name:
        <input type="text" name="name" value="<?php echo $name; ?>" />

        Last Name:
        <input type="text" name="last" value="<?php echo $last; ?>" />

        Email Address:
        <input type="text" name="email" value="<?php echo $email; ?>" />

        birthday
        <input type="text" name="birthday" value="<?php echo $birthday; ?>" />

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

    <button type="submit" class="btn" name="save">save</button>

                <button type="submit" class="btn" name="savechange">Save Changes</button>

</form>

Using PHP and a Database

Here is a list of all the records in our people table:

  <?php

$id = 0;

    // first, set general PHP error reporting and mysqli error reporting
  // in order to be sure we will see every error in the script
  ini_set('display_errors',1);
  error_reporting(E_ALL);
  mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

  // Connect to our MySQL server
  $host = "localhost";
  $user_id = "crud";
  $password = "password";
  $database = "crud";
  $mysqli = new mysqli(
    $host, $user_id, $password, $database
  );

  if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: ("
      . $mysqli->connect_errno
      . ") "
      . $mysqli->connect_error
    ;
  }
  echo $mysqli->host_info . "\n";

  // Create the SQL command

if (isset($_POST['save']))
{
$name = $_POST['name'];
$last = $_POST['last'];
$email = $_POST['email'];
$birthday = $_POST['birthday'];

$sql = "INSERT INTO crud (name, last, email, birthday)
VALUES ('$name', '$last', '$email', '$birthday')";

}

if (isset($_GET['delete']))
{
$id = $_GET['delete'];
$sql = ("DELETE FROM crud WHERE id=$id") or die($mysqli->error());

}

 if(isset($_GET['edit'])) {
    $id = $_GET['edit'];

    $results = $mysqli->query("SELECT * FROM crud WHERE id=$id") or die($mysqli->error());
     if ($results){
         $row = $results->fetch_array();
         $name = $row['name'];
         $last = $row['last'];
         $email = $row['email'];
         $birthday = $row['birthday'];
     }

 }

if(isset($_POST['savechange'])) {
       $id = $_POST['id'];
       $name = $_POST['name'];
       $last = $_POST['last'];
       $email = $_POST['email'];
       $birthday = $_POST['birthday'];

    $sql = ("UPDATE crud SET name='$name', last='$last', email='$email', birthday='$birthday' WHERE id=$id") or
        die($mysqli->error);

    $_SESSION['MSG_TYPE'] = "WARNING";

}

  //     $sql = ("UPDATE crud SET (name, last, email, birthday) VALUES ('$name', '$last', '$email', '$birthday') WHERE id=$id");
//if (isset($_GET['update']))
//{
//$id = $_GET['update'];
//$sql = ("SELECT FROM crud WHERE id=$id") or die($mysqli->error());

//}

    if ($mysqli->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "
" . $mysqli->error;
}

$sql = "SELECT * FROM crud";
$results = mysqli_query($mysqli, $sql); // First parameter is just return of "mysqli_connect()" function
echo "
";
echo "
";
while ($row = mysqli_fetch_assoc($results)) { // Important line !!! Check summary get row on array ..
      echo "
";
    echo "" . $row['id'] . "	";
    echo "" . $row['name'] . "	";
        echo "" . $row['last'] . "	";
        echo "" . $row['email'] . "	";
        echo "" . $row['birthday'] . "	";

         echo "delete	";
         echo "update	";

        //"htmlspecialchars()" function.

     echo "
";
}

    $mysqli->close();

    ?>

sql

-- PHP Version: 7.2.1

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `crud`
--

-- --------------------------------------------------------

--
-- Table structure for table `crud`
--

CREATE TABLE `crud` (
  `id` int(255) NOT NULL,
  `name` varchar(100) NOT NULL,
  `last` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL,
  `birthday` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `crud`
--

INSERT INTO `crud` (`id`, `name`, `last`, `email`, `birthday`) VALUES
(21, '', '', '', ''),
(22, '', '', '', ''),
(23, 'hhh', 'hhh', 'hh', 'jjj'),
(26, 'hi', 'ff', 'ff', 'dd'),
(27, '111', '222', '222', '222'),
(28, 'ddd', 'sss', 'sss', 'ddd'),
(29, 'hhh', 'hhh', 'hhh', 'hhh'),
(33, 'nnn', 'fffqf', 'fff', 'fff'),
(34, 'nnnn', 'nn', 'nnn', 'nnn'),
(35, 'ssaa', 'sss', 'sss', 'sss'),
(36, 'hi ', 'fff', 'fff', 'fff'),
(37, 'hh', 'hh', 'hh', 'hh');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `crud`
--
ALTER TABLE `crud`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `crud`
--
ALTER TABLE `crud`
  MODIFY `id` int(255) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=38;COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

A: This is just an example using your SQL. This takes no more time to code than what you started with.
<?php
error_reporting(E_ALL);
ini_set('display_errors', true);

    $host = '127.0.0.1';
    $db   = 'test';
    $user = 'admin';
    $pass = 'howtoforge';

    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    try{
        $con = mysqli_connect($host, $user, $pass, $db);
    }catch (Exception $e){
        echo $e->getMessage();
        exit;
    }

    $name = 'NameF';
    $last = 'O\'Conner';
    $email = 'none@none.com';
    $birthday = '12/01/9999';
    $id = '1';

    try{
    $stmt = $con->prepare('
     UPDATE
        crud
     SET
        name     = ?,
        last     = ?,
        email    = ?,
        birthday = ?
     WHERE
        id = ?;
    ');
    $stmt->bind_param('ssssi', $name, $last, $email, $birthday, $id);
    $stmt->execute();
    }catch (Exception $e){
        echo $e->getMessage();
        exit;
    }

A: You need to escape your post inputs as some of the inputs might contain illegal characters which is causing the MySQL error. Do it this way:
$id = mysqli_real_escape_string($mysqli, $_POST['id']); and the error will be gone.
As others have mentioned, however, you shouldn't use input from user without validation and sanitization to avoid SQL injection attack or just use prepared statements instead.


text:
Q: Dropdown javascript block I have a problem with javascript dropdown clicking menu.
I need show some content after clicking header of box.
HTML

                    Test

                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus mollis magna sed scelerisque hendrerit.

CSS
  #cookiemenu {
  width:100%;
  overflow: hidden;
  display:block;

}
#cookiemenu div.cookiemenu_header {
  width:100%;
  display:block;
  margin-top: 0px;
  background-color: #0B3954;
  color:#FFFFFF;
  text-align: center;
  height: 25px;
  font-size: 20px;
  line-height: 25px;
}
#cookiemenu div.cookiemenu_header:hover, div.cookiemenu_header:target {
  cursor: hand;
  text-decoration: underline;
}
div.cookiemenu_content {
}
.ShowCookieBox {
  display:block;
  border:2px solid #red;
}

JS

It's not working at all. Can someone tell me why?
And the second question. Is there any chance to change the JS so It could save "status" of box (showed or hidden) in cookies? So user can leave it, close page and on the next visit it stays as he leaved it?

A: You have two typos.
The id of the div should be cookiemenu_dropdown on the div, but it is currently cookiemenu_dropwdown.
Also the color is just red not #red.

function ShowCookieBox() {
 document.getElementById("cookiemenu_dropdown").classList.toggle("ShowCookieBox");
}
 #cookiemenu {
  width:100%;
  overflow: hidden;
  display:block;

}
#cookiemenu div.cookiemenu_header {
  width:100%;
  display:block;
  margin-top: 0px;
  background-color: #0B3954;
  color:#FFFFFF;
  text-align: center;
  height: 25px;
  font-size: 20px;
  line-height: 25px;
}
#cookiemenu div.cookiemenu_header:hover, div.cookiemenu_header:target {
  cursor: hand;
  text-decoration: underline;
}
div.cookiemenu_content {
}
.ShowCookieBox {
  display:block;
  border:2px solid red;
}

    Test

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus mollis magna sed scelerisque hendrerit.

A: Change your CSS rules to
div.cookiemenu_content.ShowCookieBox {
    display: block;
    border:2px solid red;
}
div.cookiemenu_content {
    display: none;
}

The display: block from .ShowCookieBox was being overwritten by display: none from the div.cookiemenu_content rules when the ShowCookieBox class was applied.
Check the jsfiddle


text:
Q: Computing certain polynomials related to symmetric functions and $\lambda$-rings in Sage The definition of a $\lambda$-ring (https://en.wikipedia.org/wiki/%CE%9B-ring) makes use of certain "universal" polynomials $P_n$ and $P_{n,m}$, which basically give you the formulas for computing expressions such as (respectively) $\lambda^n(xy)$ or $\lambda^n(\lambda^m(x))$.
There is no need to know anything about $\lambda$-rings to compute those polynomials, they have elementary descriptions in terms of symmetric functions. Namely, let $(x_i)_{i\in \mathbb{N}}$ and $(y_i)_{i\in \mathbb{N}}$ be two families of indeterminates, and let $e_k$ (resp. $f_k$) be the $k$th elementary symmetric function in the $x_i$ (resp. the $y_i$). Then $P_{n,m}(T_1,\dots,T_{nm})\in \mathbb{Z}[T_1,\dots,T_{nm}]$ is the unique polynomial such that $P_{n,m}(e_1,\dots,e_{nm})$ is the coefficient of $t^n$ in
$$\prod_{1\leqslant i_1 < \dots < i_m\leqslant nm}(1+t\cdot x_{i_1}\cdots x_{i_m}),$$
and $P_n(S_1,\dots,S_n,T_1,\dots,T_n)\in \mathbb{Z}[S_1,\dots,S_n,T_1,\dots,T_n]$ is the unique polynomial such that $P_n(e_1,\dots,e_n,f_1,\dots,f_n)$ is the coefficient of $t^n$ in
$$\prod_{1\leqslant i,j\leqslant n}(1+t\cdot x_iy_j).$$
It turns out these polynomials are very annoying to actually compute by hand except for very small cases, and I haven't been able to find a reference with enough examples (usually only 3 or 4 examples are given in a book).
Is there a function in some computer algebra system (preferably Sage as I have access to it) to compute these polynomials? They do not see a huge amount of usage, but they are not completely unknown either, so I thought someone might have already implemented that.
If not, I would be very grateful if someone could help me write code to compute them (preferably in Sage, again). I'm not very proficient with those algebra systems, but I figure that it should be relatively easy for anyone who is used to them (especially with functions regarding symmetric polynomials).

A: Here is a direct computation of $P_{n,m}$ from the definition, in SageMath:
def P(n, m):
    Rx = PolynomialRing(QQ, n*m, names='x')
    x = Rx.gens()
    Rt.<t> = PolynomialRing(Rx)
    from itertools import combinations
    f = prod(1 + t*prod(x[i[k]] for k in range(m)) for i in combinations(range(n*m), m))
    e = SymmetricFunctions(QQ).elementary()
    f_e = e.from_polynomial(f[n])
    RT = PolynomialRing(QQ, n*m, names=['T{}'.format(k+1) for k in range(n*m)])
    f_T = sum(c*prod(RT.gen(k-1) for k in m) for (m,c) in f_e)
    return f_T

For example:
sage: P(1,1)
T1
sage: P(1,2)
T2
sage: P(2,1)
T2
sage: P(2,2)
T1*T3 - T4
sage: P(2,3)
T2*T4 - T1*T5 + T6
sage: P(3,2)
T1^2*T4 + T3^2 - 2*T2*T4 - T1*T5 + T6

And here is $P_n$ directly from the definition, in SageMath:
def PP(n):
    Rx = PolynomialRing(QQ, n, names='x')
    Ry = PolynomialRing(Rx, n, names='y')
    from itertools import product
    Rt.<t> = PolynomialRing(Ry)
    f = prod(1 + t*Rx.gen(i)*Ry.gen(j) for i,j in product(range(n),repeat=2))
    SymRx = SymmetricFunctions(Rx).elementary()
    SymRx._prefix = 'f'
    f_f = SymRx.from_polynomial(f[n])
    Sym = SymmetricFunctions(QQ).elementary()
    RST = PolynomialRing(QQ, 2*n, names=['S{}'.format(k+1) for k in range(n)] + ['T{}'.format(k+1) for k in range(n)])
    S = RST.gens()[:n]
    T = RST.gens()[n:]
    result = 0
    for m, c in f_f:
        prefactor = prod(T[k-1] for k in m)
        for m2, c2 in Sym.from_polynomial(c):
            result += prefactor*c2*prod(S[k-1] for k in m2)
    return result

For example:
sage: PP(1)
S1*T1
sage: PP(2)
S2*T1^2 + S1^2*T2 - 2*S2*T2
sage: PP(3)
S3*T1^3 + S1*S2*T1*T2 + S1^3*T3 - 3*S3*T1*T2 - 3*S1*S2*T3 + 3*S3*T3


text:
Q: issue with DHTMLX2.5 calendar I am using DHTMLX 2.5 calendar. I am attaching calendar to an input field.
<script src="../dhtmlx_suite/js/dhtmlxcommon.js"></script>
<link rel="stylesheet" type="text/css" href="../dhtmlx_suite/skins/dhtmlxcalendar_dhx_skyblue.css" />
<link rel="stylesheet" type="text/css" href="../dhtmlx_suite/css/dhtmlxcalendar.css" />
<script src="../dhtmlx_suite/js/dhtmlxcalendar.js"></script>
<script>
var myCalendar;
function doOnLoad() {
    myCalendar = new dhtmlXCalendarObject(["calendar"]);

}

</script>

    <div style="position:relative;height:280px;">
        <input type="text" id="calendar">
    </div>
<script>
doOnLoad();
</script>

When I enter some invalid date e.g 'xyz' in the input field, and click the input field, it replaces the value with string 'NaN-NaN-NaN'. How could avoid this? and keep the user eneted value as it is in the textfield. So when there is an invalid date in the input field I expect calendar popup to ignore that and just open the current month.

A: You can create a validator function which checks whether the content of your input is syntactically correct. If it is not correct, you can put back the old value to the input and prevent other actions.