text:
Q: How can I validate an Azure AD JWT Token in Java? I have an Azure AD JWT token that is obtained using Msal library but when I try to validate this token something is wrong:
Client: A Sharepoint Web Part
 const config = {
     auth: {
         clientId: "xxxxx",
         authority: "https://login.microsoftonline.com/yyyyyy"
     }
 };

 const myMSALObj = new UserAgentApplication(config);

 let accessTokenRequest = {
     scopes: ["user.read"],
     loginHint: this.context.pageContext.user.loginName,
     extraQueryParameters: {domain_hint: 'organizations'}
 }

 myMSALObj.acquireTokenSilent(accessTokenRequest).then(
  function(accessTokenResponse) {
  // Acquire token silent success
  let accessToken = accessTokenResponse.accessToken;

I'm trying to retrieve the publick key from:
https://login.microsoftonline.com/tenant-id/.well-known/openid-configuration but with this public key I can never redirect to: https://login.microsoftonline.com/common/discovery/keys
Is there any other way to obtain the public key in this case?
Server: Validation
public PublicKey getPublicKeyFromParams(String e, String n){

    byte[] modulusBytes = Base64.getUrlDecoder().decode(n);

    BigInteger modulusInt = new BigInteger(1, modulusBytes);

    byte[] exponentBytes = Base64.getUrlDecoder().decode(e);

    BigInteger exponentInt = new BigInteger(1, exponentBytes);

    KeyFactory keyFactory;

    RSAPublicKeySpec publicSpec = new RSAPublicKeySpec(modulusInt, exponentInt);

        try {

            keyFactory = KeyFactory.getInstance("RSA");

            return keyFactory.generatePublic(publicSpec);

        } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {

            ex.printStackTrace();

        }

    return null;

}

@Test

public void name() throws Exception {

    String jwt = "xxxxxxx";

    KeyPair keyPair = Keys.keyPairFor(SignatureAlgorithm.RS256);

    String e = Base64.getUrlEncoder().encodeToString((((RSAPublicKeyImpl) keyPair.getPublic()).getPublicExponent()).toByteArray());

    String n = Base64.getUrlEncoder().encodeToString((((RSAPublicKeyImpl) keyPair.getPublic()).getModulus()).toByteArray());

    System.out.println("Public Key: " + Base64.getUrlEncoder().encodeToString(keyPair.getPublic().getEncoded()));

    System.out.println("Public Key Exponent: " + e);

    System.out.println("Public Key Modulus: " + n);

    String jws = Jwts.builder().setSubject("pepe").signWith(keyPair.getPrivate()).compact();

    System.out.println("Generated JWS:" + jws);

    PublicKey publicKey = getPublicKeyFromParams(e, n);

    Jwt parsedJWs = Jwts.parserBuilder().setSigningKey(publicKey).build().parse(jws);

    System.out.println("Parsed JWS: " + parsedJWs);

    publicKey = getPublicKeyFromParams(eValue, nValue);

    System.out.println("Azure PublicKey fron n-e: " + publicKey);

    CertificateFactory factory = CertificateFactory.getInstance("X.509");

    Certificate cert = factory.generateCertificate(new ByteArrayInputStream(

    DatatypeConverter.parseBase64Binary("cccccccccccccccccc")));

    publicKey = cert.getPublicKey();

    System.out.println("Azure PublicKey from x5c: " + publicKey);

    Jwt jwtParsed = Jwts.parserBuilder().setSigningKey(publicKey).build().parse(jwt);

    System.out.println(jwtParsed);

}

public static PublicKey getPublicKey(String key){

    try{

        byte[] byteKey = Base64.getDecoder().decode(key);

        X509EncodedKeySpec X509publicKey = new X509EncodedKeySpec(byteKey);

        KeyFactory kf = KeyFactory.getInstance("RSA");

        return kf.generatePublic(X509publicKey);

    }

    catch(Exception e){

        e.printStackTrace();

    }

    return null;

}

A: if you want to validate Azure AD access token, we can try to use the sdk java-jwt and jwks-rsa to implememnt it.
For example

*

*Install SDK via maven

 <dependency>
      <groupId>com.microsoft.azure</groupId>
      <artifactId>azure-storage</artifactId>
      <version>8.6.2</version>
    </dependency>

    <dependency>
      <groupId>com.auth0</groupId>
      <artifactId>jwks-rsa</artifactId>
      <version>0.11.0</version>
    </dependency>

*Code
a. validate the signature
 String token="<your AD token>";
  DecodedJWT jwt = JWT.decode(token);
  System.out.println(jwt.getKeyId());

  JwkProvider provider = null;
  Jwk jwk =null;
  Algorithm algorithm=null;

  try {
      provider = new UrlJwkProvider(new URL("https://login.microsoftonline.com/common/discovery/keys"));
      jwk = provider.get(jwt.getKeyId());
      algorithm = Algorithm.RSA256((RSAPublicKey) jwk.getPublicKey(), null);
      algorithm.verify(jwt);// if the token signature is invalid, the method will throw SignatureVerificationException
  } catch (MalformedURLException e) {
      e.printStackTrace();
  } catch (JwkException e) {
      e.printStackTrace();
  }catch(SignatureVerificationException e){

     System.out.println(e.getMessage());

  }

A: With this change, the validation works fine.
let accessTokenRequest = {
    scopes:["clientId/.default"],
    loginHint: this.context.pageContext.user.loginName,
    extraQueryParameters: {domain_hint: 'organizations'}
}

A: you need to use the new keys from microsoft for the above code to work. Change:
provider = new UrlJwkProvider(new URL("https://login.microsoftonline.com/common/discovery/keys"));
to
provider = new UrlJwkProvider(new URL("https://login.microsoftonline.com/common/discovery/v2.0/keys"));
For the example above there are some dependencies missing, the correct sample should be:
<dependency>
        <groupId>com.microsoft.azure</groupId>
        <artifactId>azure-storage</artifactId>
        <version>8.6.2</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.auth0/java-jwt -->
    <dependency>
        <groupId>com.auth0</groupId>
        <artifactId>java-jwt</artifactId>
        <version>3.16.0</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.auth0/jwks-rsa -->
    <dependency>
        <groupId>com.auth0</groupId>
        <artifactId>jwks-rsa</artifactId>
        <version>0.18.0</version>
    </dependency>

And code:
String token="YOUR JWT";
        DecodedJWT jwt = JWT.decode(token);
        System.out.println(jwt.getKeyId());

        JwkProvider provider = null;
        Jwk jwk =null;
        Algorithm algorithm=null;

        try {
            provider = new UrlJwkProvider(new URL("https://login.microsoftonline.com/common/discovery/v2.0/keys"));
            jwk = provider.get(jwt.getKeyId());
            algorithm = Algorithm.RSA256((RSAPublicKey) jwk.getPublicKey(), null);
            algorithm.verify(jwt);// if the token signature is invalid, the method will throw SignatureVerificationException
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (JwkException e) {
            e.printStackTrace();
        }catch(SignatureVerificationException e){

            System.out.println(e.getMessage());

        }


text:
Q: Python convert string to dictionary How can I convert the string "k:1|k1:2|k2:3|k3:4" to a dictionary? I tried to use split() but I still can't figure it out.

A: Maybe this is what you need :
>>> s = "k:1|k1:2|k2:3|k3:4"
>>> dict(i.split(':') for i in s.split('|'))
{'k': '1', 'k1': '2', 'k2': '3', 'k3': '4'}

A: Depending on how regular a pattern that string is, I would split the string according to the | character, then split each substring again according to the : character:
text = "k:1|k1:2|k2:3|k3:4"
my_dict = {}
pairs = text.split("|")
for p in pairs:
    k, v = p.split(":")
    my_dict[k] = v

You may want to cast v as an integer. Up to you.

A: you can use double split function
mystr = "k:1|k1:2|k2:3|k3:4"
keyval = mystr.split("|")
mydic = {}
for w in keyval:
    w = w.split(":")
    mydic[w[0]] = w[1]
print(mydic)

output:
{'k': '1', 'k1': '2', 'k2': '3', 'k3': '4'}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Motion of planets: inverse square law If a body is acted on by a force which obeys the inverse square law, will it mean the body follows an ellipse, if so, equating Newton's law of universal gravitation $(f=(GMm/(r^2)))$ to centripetal force $(mv^2)/r$ is erroneous.

A: Let the interaction potential be of the form $V=kr^n$.
The eccentricity of the orbit is given by the expression (Refer "Goldstein, Classical Mechanics, 2nd edition, chapter 3)
$$e=\sqrt{1+\frac{2El^2}{mk^2}}$$
If $e>1$, the shape of the orbit is hyperbola,
If $e=1$, the shape of the orbit is parabola,
If $e<1$, the shape is ellipse,
If $e=0$, the shape is circle,
So the shape of the orbit depends on the total energy of the system, not on the form of Force. The shape of the orbit can be ellipse or hyperbola or parabola or circle depends on the total energy of the system.
The total energy of the system is given by
$$E=\frac{1}{2}mv^2+V_{eff}$$
Where $V_{eff}=V+\frac{l^2}{2mr^2}$, $l$ is the angular momentum which is a constant for a central force problem.
From Virial's theorem, it is known that, $$<T>=\frac{-1}{2}<V>$$
So $E=\frac{-k}{2r_{0}}$, if $r_{0}=\frac{l^2}{mk}$, the orbit is circular,
For Elliptical Orbit, $E=\frac{-k}{2a}$, where $a$ is the semimajor axis.
Finally only for uniform cirular motion you can equate Centripetal force with Gravitational force.

A: Yes, if you are considering uniform circular motion, then you can use
$$
mv^2\,r^{-1}=GMm\,r^{-2}.
$$
And I imagine most textbooks try to make it clear that this is valid only in that case.
However, what you want to solve is the sum of the forces:
$$
\sum F=F_g
$$
That is,
$$
m\frac{d^2r}{dt^2}-mr\omega^2=-\frac{GMm}{r^2}\tag{1}
$$
where the $r\omega^2=v^2/r$ term is the rotational acceleration and $M$ the mass of the larger body (i.e., the star). If you let $L=mr^2\omega$ be the angular momentum (which is conserved here, so it is a constant in time), then (1) can become
$$
\frac{d^2r}{dt^2}=-\frac{GM}{r^2}+r\left(\frac{L}{mr}\right)^2
$$
which, with some substitutions and work (see the section labeled "Kepler's First Law"), can be reduced to,
$$
\frac{a\left(1-e^2\right)}{r}=1+e\cos\theta
$$
where $a$ is the semi-major axis of the ellipse, $e$ the eccentricity and $r,\,\theta$ are the typical polar coordinates. And this equation is the standard equation for an ellipse


text:
Q: python matplotlib: how to use fill_between with a colormap to fill the background of a 2d plot? I'm trying to make a simple 2d plot from a 3 column data sets e.g. y=f(x) and z=f(x). I want to plot xy and would like to display z using color. For example, the rectangular regions between [x1,x2, min(y), max(y)] ... will be filled by a background color depending on the value of z. I tried to use fill_between but could not associate a colormap with it. I'm new to matplotlib and python. I would very much appreciate your comments/suggestions.
Edit: I don't have an accurate plot but I'll try to explain my query with the help of following figure   sample plot
say between x=0.5 to x=1, z=1
            x=1.0, to x=1.5, z=2 ....
so I would like to cover x=0.5 to x=1 (min(y) to max(y)] with some color that corresponds to z=1, and between x=1, x=1.5, z=2 and so on.. I want to show this variation using a colormap and to display this colorbar at the right side.

A: Here's the solution those who want cannot use contourf or need fill_between for some other reason (as in this case with irregular grid data).
import numpy as np
import matplotlib.pyplot as plt
from random import randint, sample
import matplotlib.colorbar as cbar

# from Numeric import asarray
%matplotlib inline

# The edges of 2d grid
# Some x column has varying rows of y (but always the same number of rows)
# z array that corresponds a value in each xy cell

xedges = np.sort(sample(range(1, 9), 6))
yedges = np.array([np.sort(sample(range(1, 9), 6)) for i in range(5)])
z = np.random.random((5,5))

f, ax = plt.subplots(1, sharex=True, figsize=(8,8))
f.subplots_adjust(hspace=0)
ax.set_ylabel(r'y')
ax.set_xlabel(r'x')
ax.set_ylim(0,10)
ax.set_xlim(0,10)

c = ['r','g','b','y','m']

normal = plt.Normalize(z.min(), z.max())
cmap = plt.cm.jet(normal(z))

# plot showing bins, coloured arbitrarily.
# I want each cell coloured according to z.
for i in range(len(xedges)-1):
    for j in range(len(yedges)):
        ax.vlines(xedges[i],yedges[i][j],yedges[i][j+1],linestyle='-')
        ax.hlines(yedges[i][j],xedges[i],xedges[i+1],linestyle='-')
        ax.vlines(xedges[i+1],yedges[i][j],yedges[i][j+1],linestyle='-')
        ax.hlines(yedges[i][j+1],xedges[i],xedges[i+1],linestyle='-')

        ax.fill_between([xedges[i],xedges[i+1]],yedges[i][j],yedges[i][j+1],facecolor=cmap[i][j][:])

cax, _ = cbar.make_axes(ax)
cb2 = cbar.ColorbarBase(cax, cmap=plt.cm.jet,norm=normal)

This gives

A: It sound to me like you should use contourf
http://matplotlib.org/examples/pylab_examples/contourf_demo.html
This would take x as some dependant variable, produce y = y(x) and z = z(x). It seems that your z is not dependant on y but contourf can still handle this.
As a simple example:
import pylab as plt
x = plt.linspace(0,2,100)
y = plt.linspace(0,10,100)

z = [[plt.sinc(i) for i in x] for j in y]

CS = plt.contourf(x, y, z, 20, # \[-1, -0.1, 0, 0.1\],
                        cmap=plt.cm.rainbow)
plt.colorbar(CS)
plt.plot(x,2+plt.sin(y), "--k")

The are many variations but hopefully this captures the elements you are looking for


text:
Q: what are depended package for install WeasyPrint in dockerfile? I install WeasyPrint and config it for views.py ,urls.py,admin.py and my template.
when i want convert html page to pdf , i have this error :
(process:7): Pango-CRITICAL **: 13:27:29.635: pango_font_get_hb_font: assertion 'PANGO_IS_FONT (font)' failed
base_shop_web_1 exited with code 245

my Dockerfile is :
FROM python:alpine

ENV PYTHONDONTWRITEBYTECODE 1

ENV PYTHONUNBUFFERED 1

RUN mkdir /code

ADD requirements.txt /code/

WORKDIR /code

RUN apk add --update --no-cache curl jq py3-configobj py3-pip py3-setuptools python3 python3-dev

RUN apk add cairo-dev pango-dev gdk-pixbuf-dev py-lxml shared-mime-info openjpeg-dev freetype-dev \
    libpng-dev gettext libxml2-dev libxslt-dev

RUN apk add make automake libffi-dev gcc linux-headers g++ py3-brotli  musl-dev postgresql-dev zlib-dev jpeg-dev

RUN pip3 install -r requirements.txt

EXPOSE 8000

COPY . /code/

what things i shoud to add dockerfile ?

A: for install reportlab for python:alpine we should install py-reportlab, not reportlab .


text:
Q: Switch to different app in different desktop instead same desktop I have 2 windows of Chrome opened in Display 1 & 3. Beside that, there is Terminal run in Display 1. Display 2 has some windows from other apps. In this case, I offten switch between Terminal in Display 1 and Chrome in Display 3.
When I open Terminal in Display 1 and do Cmd ⌘Tab window switch to Chrome in Display 1, instead of Display 3. Currently, I have to shift right/left the space twice to switch it.
Is there shortcut key to accomodate this case?

A: There are many variants on this question...
In short, Spaces is not designed to accommodate any app on more than one Space.
So the simple answer is, "No."
Possible alternative workarounds...

*

*Use  Cmd ⌘   `  to switch between open windows of the app you just switched to.

*Use dedicated key commands to switch to a specific Space rather than App - by default  Ctrl ⌃  plus  [number]  - & remember where each one lives. This is my preferred method, which I've been using since Spaces was invented.


text:
Q: My AndroidManifest.xml is full of errors, why? I'm trying to make my first app in Android Studio. I tried to write something on my  AndroidManifest.xml that didn't work, so I deleted it again. But now my AndroidManifest.xml is full of errors and I cant run my app. I have no idea whats wrong. I dont know so much about coding. I hope someone can help me. My AndroidManifest.xml looks like this:
    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.bobbysmedicin">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".AboutActivity"></activity>
        <activity
            android:name=".MainActivity"
            android:screenOrientation="landscape"/>
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

A:
Remove this (space or tab), then try to run your app


text:
Q: Integral of $\int \frac{xe^x}{\sqrt{1+e^x}} dx$ I need help to solve this:
$$\int \frac{xe^x}{\sqrt{1+e^x}} dx$$

A: Hint:
Let $u=\sqrt{1+e^x}$ and $du=\dfrac{e^xdx}{2\sqrt{1+e^x}}$
This transforms the integral to
$$2\int \ln(u^2-1)du=2\int \ln((u+1)(u-1))du=2\int \ln(u+1)+2\int\ln(u-1)du$$
Now, try integration by parts.


text:
Q: EclipseLink Lazy Property Throwing ConcurrencyException I have the following schema (simplified and names changed):
@Entity
@Table(name = "fubar")
@Inheritance(strategy = InheritanceType.JOINED)
public class Fubar {

  @ManyToOne(fetch = FetchType.LAZY) // LAZY was recently added
  @JoinColumn(name = "bar_id")
  private Bar bar;

  public Bar getBar() {
    return bar;
  }
}

@Entity
@Table(name = "foo")
public class Foo extends Fubar {
 // Columns omitted for brevity
}

Basically, Foo extends Fubar, which has a lazily-loaded Bar property. As my comment in the code indicates, FetchType.LAZY was recently added. Now we are getting a ConcurrencyException from EclipseLink when simply calling the getBar method after retrieving a Foo record from the database.
@Named
@RequestScoped
public class FooBean {

  @Inject
  private FooDao fooDao;

  @PostConstruct
  public void initialize() {
    long fooId = getSelectedFooId();
    Foo foo = fooDao.findById(fooId);
    foo.getBar(); // Boom! -> ConcurrencyException
  }
}

Here's a simplified version of the FooDao. We are using something very similar (but not identical) to the EntityManagerHelper described in another post (essentially just EnityManager inside of ThreadLocal). For simplicity, I'll just use the EntityManagerHelper in the code below:
public class FooDao {

  public Foo findById(long id) {
    EntityManager em = EntityManagerHelper.getEntityManager();

    List<Foo> foos = em
        .createQuery("SELECT f FROM Foo f WHERE f.id = :id", Foo.class)
        .setParameter("id", id)
        .setMaxResults(1)
        .getResultList();

    return (foos.size() > 0) ? foos.get(0) : null;
  }
}

Last, but not least, here's the stacktrace we are getting from EclipseLink:
org.eclipse.persistence.exceptions.ConcurrencyException:
Exception Description: A signal was attempted before wait() on ConcurrencyManager. This normally means that an attempt was made to
commit or rollback a transaction before it was started, or to rollback a transaction twice.
    at org.eclipse.persistence.exceptions.ConcurrencyException.signalAttemptedBeforeWait(ConcurrencyException.java:84) ~[org.eclipse.persistence.core.jar:na]
    at org.eclipse.persistence.internal.helper.ConcurrencyManager.releaseReadLock(ConcurrencyManager.java:468) ~[org.eclipse.persistence.core.jar:na]
    at org.eclipse.persistence.internal.identitymaps.CacheKey.releaseReadLock(CacheKey.java:468) ~[org.eclipse.persistence.core.jar:na]
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.cloneAndRegisterObject(UnitOfWorkImpl.java:1041) ~[org.eclipse.persistence.core.jar:na]
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.cloneAndRegisterObject(UnitOfWorkImpl.java:955) ~[org.eclipse.persistence.core.jar:na]
    at org.eclipse.persistence.internal.sessions.UnitOfWorkIdentityMapAccessor.getAndCloneCacheKeyFromParent(UnitOfWorkIdentityMapAccessor.java:209) ~[org.eclipse.persistence.core.jar:na]
    at org.eclipse.persistence.internal.sessions.UnitOfWorkIdentityMapAccessor.getFromIdentityMap(UnitOfWorkIdentityMapAccessor.java:137) ~[org.eclipse.persistence.core.jar:na]
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerExistingObject(UnitOfWorkImpl.java:3942) ~[org.eclipse.persistence.core.jar:na]
    at org.eclipse.persistence.queries.ObjectBuildingQuery.registerIndividualResult(ObjectBuildingQuery.java:448) ~[org.eclipse.persistence.core.jar:na]
    at org.eclipse.persistence.queries.ReadObjectQuery.registerResultInUnitOfWork(ReadObjectQuery.java:887) ~[org.eclipse.persistence.core.jar:na]
    at org.eclipse.persistence.queries.ObjectLevelReadQuery.checkEarlyReturn(ObjectLevelReadQuery.java:880) ~[org.eclipse.persistence.core.jar:na]
    at org.eclipse.persistence.mappings.OneToOneMapping.checkCacheForBatchKey(OneToOneMapping.java:835) ~[org.eclipse.persistence.core.jar:na]
    at org.eclipse.persistence.mappings.ForeignReferenceMapping.extractResultFromBatchQuery(ForeignReferenceMapping.java:531) ~[org.eclipse.persistence.core.jar:na]
    at org.eclipse.persistence.internal.indirection.BatchValueHolder.instantiate(BatchValueHolder.java:58) ~[org.eclipse.persistence.core.jar:na]
    at org.eclipse.persistence.internal.indirection.QueryBasedValueHolder.instantiate(QueryBasedValueHolder.java:116) ~[org.eclipse.persistence.core.jar:na]
    at org.eclipse.persistence.internal.indirection.DatabaseValueHolder.getValue(DatabaseValueHolder.java:89) ~[org.eclipse.persistence.core.jar:na]
    at org.eclipse.persistence.internal.indirection.UnitOfWorkValueHolder.instantiateImpl(UnitOfWorkValueHolder.java:173) ~[org.eclipse.persistence.core.jar:na]
    at org.eclipse.persistence.internal.indirection.UnitOfWorkValueHolder.instantiate(UnitOfWorkValueHolder.java:234) ~[org.eclipse.persistence.core.jar:na]
    at org.eclipse.persistence.internal.indirection.DatabaseValueHolder.getValue(DatabaseValueHolder.java:89) ~[org.eclipse.persistence.core.jar:na]
    at com.mycompany.model.Foo._persistence_get_bar(Foo.java)
    at com.mycompany.model.Foo.getBar(Foo.java:16)
    at com.mycompany.beans.FooBean.initialize(FooBean.java:20)
According to the EclipseLink FAQ for resolving deadlocks, developers are encouraged to make all relationships LAZY. Why are we now getting a ConcurrencyException? I need an EclipseLink expert's help on this one. Thanks!


text:
Q: Rich-snippets - Double movie authors I did not understand how to behave in the case there were multiple items of the same type, as for the writers of a movie.
I have to repeat itemprop="author" for each writer or i can include them in a single div?

    Cesare Frugoni
    Enrico Vanzina

or

    Enrico Vanzina

    Cesare Frugoni

A: The latter is right. The first snippet means that your person have two names (which is not so uncommon situation really). You can check it using Google or Yandex validators. They  will give you smth like this
person
itemType = http://schema.org/Person
name = Cesare Frugoni
name = Enrico Vanzina

And you (I believe) need
person
itemType = http://schema.org/Person
name = Enrico Vanzina

person
itemType = http://schema.org/Person
name = Cesare Frugoni

Schema.org provides good example for this case at schema.org/Movie .

Pirates of the Carribean: On Stranger Tides (2011)

Jack Sparrow and Barbossa embark on a quest to
 find the elusive fountain of youth, only to discover that Blackbeard and
 his daughter are after it too.
Director:

Rob Marshall

Writers:

Ted Elliott

Terry Rossio

, and 7 more credits
Stars:

Johnny Depp,

Penelope Cruz,

Ian McShane

BTW there were a lot of discussions around cardinality of schema.org properties. If you're interested in details you can read corresponding materials: ISSUE at tracker and W3C Wiki page.
And I personally follow the rule stated by Guha:

Right now, it is always allowed to have multiple values.

A: I think they are both correct. Imdb use frist syntax.

Writers:

    Cesare Frugoni
    Steno


text:
Q: Open  instead of  lightbox effect Is it possible to change this

Into a working lightbox effect? I suppose the final result would look something like this

And when the lightbox is opened, back to it's original state:

This is what I have right now..
$('a img').each(function() {
$('a').each(function() {
        $(this).attr('href','/google.png');
    });
});

And it should change into something like this when the lightbox is opened:
$('a img').each(function() {
$('a').each(function() {
        $(this).attr('href','http://google.com');
    });
});

If you know about a script that can do this, or if you can help out, I'd really appreciate it. Thanks in advance!

A: I think you need something like Fancybox. This a JQuery lightbox plugin.
http://fancyapps.com/fancybox/


text:
Q: Is there a way to pass array of hash to provider function in Chef I know we can pass boolean, String, Array and Hash kind_of attributes to provider functions.
However is there a way to pass Array of Hash kind_of attribute to provider functions.
What would be the right way to achieve this?
attributes/default.rb
default['test']['users'] = [
{
    'name'          =>  'haris',
    'age'           =>  '21'
},
{
    'name'          =>  'Omar',
    'age'           =>  '25'
}
]

resources/default.rb
 actions :add, :delete
 attribute :users,      :kind_of => [Array, Hash], :required => true

providers/default.rb
action :add do
users       = @new_resource.users

users.each do |user|
   user <blah blah>
end

recipes/default.rb
cbook_my_users "add users" do
    action :add
    users "#{node['test']['users']}"
end

A: Rather than making it a string, just pass through the object itself: users node['test']['users']


text:
Q: Maven best practice for creating ad hoc zip artifact Assume that I need to manage an artifact that consists of an aribtrary folder / file structure rolled up as a zip archive.  It's not clear to me how to accomplish this in Maven in a way that best fits "the Maven way."
I know that there is no "zip" packaging type.  Does this mean there is no generic lifecycle in Maven to simply take what I have in the resources folder, zip it up, and install/deploy it to my repositories?
I'm looking for options, with evaluations of how each option satisifies my requirement to follow the maven way, as I do not wish to incur the obvious penalities of straying from the golden path . . .

A: Decide what classifier you will use for your zip file, for sake of argument let's say it would be sample.
In your project create file assembly/sample.xml
Fill in assembly/sample.xml with something like this:
<?xml version="1.0" encoding="UTF-8"?>
<assembly
  xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="
    http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2
      http://maven.apache.org/xsd/assembly-1.1.2.xsd"
>
  <id>sample</id>
  <formats>
    <format>zip</format>
  </formats>
  <fileSets>
    <fileSet>
      <outputDirectory>/</outputDirectory>
      <directory>some/directory/in/your/project</directory>
    </fileSet>
  </fileSets>
  <!-- use this section if you want to package dependencies -->
  <dependencySets>
    <dependencySet>
      <outputDirectory>lib</outputDirectory>
      <excludes>
        <exclude>*:pom</exclude>
      </excludes>
      <useStrictFiltering>true</useStrictFiltering>
      <useProjectArtifact>false</useProjectArtifact>
      <scope>runtime</scope>
    </dependencySet>
  </dependencySets>
</assembly>

Add this to your pom's build section
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-assembly-plugin</artifactId>
        <executions>
          <execution>
            <id>create-distribution</id>
            <phase>package</phase>
            <goals>
              <goal>single</goal>
            </goals>
            <configuration>
              <descriptors>
                <descriptor>assembly/sample.xml</descriptor>
              </descriptors>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

As a result it should create and install you-project-name-VERSION-sample.zip.
I suggest you read chapter on assemblies from Sonatype's maven book:
https://books.sonatype.com/mvnref-book/reference/assemblies.html
Also, read assembly format specification: http://maven.apache.org/plugins/maven-assembly-plugin/assembly.html

A: Fill in assembly/sample.xml with something like this:
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
  <id>install</id>
  <baseDirectory>/</baseDirectory>
  <formats>
  <format>zip</format>
</formats>
<fileSets>
  <fileSet>
    <includes>
      <include>README*</include>
      <include>*.sh</include>
    </includes>
  </fileSet>
  <fileSet>
    <directory>target/classes/</directory>
    <outputDirectory>resources</outputDirectory>
    <includes>
      <include>*.properties</include>
       <include>*.xml</include>
    </includes>
    <lineEnding>dos</lineEnding>
  </fileSet>
  <!--
  <fileSet>
    <directory>target/</directory>
    <outputDirectory>lib</outputDirectory>
    <includes>
      <include>*.jar</include>
    </includes>
    <lineEnding>dos</lineEnding>
  </fileSet>
   -->
</fileSets>
 <!-- use this section if you want to package dependencies -->
  <dependencySets>
    <dependencySet>
      <outputDirectory>lib</outputDirectory>
      <excludes>
        <exclude>*:pom</exclude>
      </excludes>
      <useStrictFiltering>true</useStrictFiltering>
      <useProjectArtifact>true</useProjectArtifact>
      <scope>runtime</scope>
    </dependencySet>
  </dependencySets>
</assembly>

add below codes in pom.xml file.
<plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-assembly-plugin</artifactId>
            <configuration>
                <descriptor>assembly/sample.xml</descriptor>
            </configuration>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>single</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

run commands as mvn package -P dev -Dmaven.test.skip
will create the zip files that include :
     xxxx.zip
          -lib/.jar
          -resources/.xml/properties
          -readme
          -start.sh

A: In your maven project create a folder assembly.
Add zip.xml file in the assembly folder.
Add below code in zip.xml to package the content of your project in to zip.
<assembly
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
<id>zip</id>
<formats>
    <format>zip</format>
</formats>
<includeBaseDirectory>false</includeBaseDirectory>
<fileSets>
    <fileSet>
        <directory>directoryName of your project</directory>
        <outputDirectory>/</outputDirectory>
    </fileSet>
</fileSets>


text:
Q: How to make the points in google line charts hollow I am using google charts to draw a line chart but i need the points on the chart to have only boundary i.e 'o'
not completely color filled points
. Can anybody help me with this??. I have used google charts api to draw the line charts.


text:
Q: Display the values of two arrays and save it in the database using foreach in Mysql and php I have two arrays, the array that holds the child name and the other one is an array that holds the birthday of the child.
This is the design of my form that the user will fill up.

    Name of Child
    <input type="text" class="form-control" name="child[]" id="child" placeholder="FULL NAME">

    Date of Birth
    <input type="text" class="form-control date-picker" name="ch_DateOfBirth[]" id="DateOfBirth" placeholder="Date of Birth">

and this is my php code for saving the two arrays in the database.

$child_name=$_POST['child'];
$child_bday=date('Y-d-m', strtotime($_POST['ch_DateOfBirth']));
$count=count($child_name);

for ($i=0; $i < $count ; $i++) {
  $sql6="INSERT into  tbl_children (Emp_ID, Ch_Name, Ch_Bdate) values ('".$emp_id."', '".$child_name[$i]."', '".$child_bday[$i]."') ";
    $dbcon->query($sql6);
}

but whenever i tried to do so, only the name of the children are saved excluding their birthdays. How can I save it using foreach if possible?

A: Hope this will works
$child_name=$_POST['child'];
$count=count($child_name);

for ($i=0; $i < $count ; $i++) {
  $child_bday=date('Y-d-m', strtotime($_POST['ch_DateOfBirth'][$i]));
  $sql6="INSERT into  tbl_children (Emp_ID, Ch_Name, Ch_Bdate) values ('".$emp_id."', '".$child_name[$i]."', '".$child_bday."') ";
  $dbcon->query($sql6);
}


text:
Q: Sum of number of divisor of number between a and b inclusive Let there be a function g(x)=number of divisor of x. Given two integers a and b we need to find->
g(a)+g(a+1)....+g(b).
I thought this step->
for every x from a to b

sum+=number of divisor of x(in sqrt(x) complexity)

but  its given 1<=a<=b<=2^31-1
So to iterate between a and b can cost me a lot of time....for eg->if a=1 and b=2^31-1.
Is there a better way to do?

A: Here's some simple but reasonably efficient Python code that does the job.
import math

def T(n):
    "Return sum_{i=1}^n d(i), where d(i) is the number of divisors of i."
    f = int(math.floor(math.sqrt(n)))
    return 2 * sum(n // x for x in range(1, f+1)) - f**2

def count_divisors(a, b):
    "Return sum_{i=a}^b d(i), where d(i) is the number of divisors of i."
    return T(b) - T(a-1)

Explanation: it's enough to be able to compute the sum from 1 to b, then we can do two separate computations and subtract to get the sum from a to b.  Finding the sum of the divisor function from 1 to b amounts to computing sequence A006218 from the online encyclopaedia of integer sequences.  That sequence is equivalent to the sum of floor(n / d) as d ranges over all integers from 1 to n.
And now that sequence can be thought of as the number of integer-valued points under the hyperbola xy=n.  We can use the symmetry of the hyperbola around the line x = y, and count the integer points with x <= sqrt(n) and those with y <= sqrt(n).  That ends up double counting the points with both x and y less than sqrt(n), so we subtract the square of floor(sqrt(n)) to compensate.  All this is explained (briefly) in the introduction to this paper.
Remarks:

*

*the algorithm has running time O(sqrt(b)), and constant space requirements.  Improvements in running time are possible at the expense of space; see the paper referred to above.

*for really large n, you'll want a proper integer square root rather than using floor(math.sqrt(n)), to avoid problems with floating-point inaccuracies.  That's not a problem with the sort of n that you're looking at.  With typical IEEE 754 floating-point and a correctly rounded square root operation, you're not going to run into trouble until n exceeds 2**52.

*if a and b are really close, there may be more efficient solutions.

A: Because the desired result is the total number of divisors for all the numbers in a range, there's no need to count divisors of individual numbers in the range; instead, count the number of times 1 is a divisor, 2  is a divisor, etc.  This is an O(b) computation.
That is, add up b-(a-1), b/2 - (a-1)/2,  b/3 - (a-1)/3, etc. .
In the python code shown below (which uses python operator // for integer division with truncation) divisors from 2 to about b/2 are counted using a for loop.  Note that divisors that are smaller than b but larger than max(a, b/2) occur once each and need not be counted in a loop.  The code uses the expression b-max(a,(b+1)//2+1)+1 to count them.  Output is shown after the program.
When k different a,b sets are to be treated, it is possible to compute all the answers in time O(k+bₘₐₓ) where bₘₐₓ is the largest value of b.
Python code:
def countdivisors(a,b):
    mid = (b+1)//2+1
    count = b-a+1 +b-max(a,mid)+1 # Count for d=1 & d=n
    for d in xrange(2,mid):
        count += b//d - (a-1)//d
    return count
# Test it:
a=7
for b in range(a,a+16):
    print '{:3} {:3} : {:5}'.format(a, b, countdivisors(a,b))

Output:
  7   7 :     2
  7   8 :     6
  7   9 :     9
  7  10 :    13
  7  11 :    15
  7  12 :    21
  7  13 :    23
  7  14 :    27
  7  15 :    31
  7  16 :    36
  7  17 :    38
  7  18 :    44
  7  19 :    46
  7  20 :    52
  7  21 :    56
  7  22 :    60

A: We can adapt this algorithm: http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
by adding 1 to all multiples instead of flagging them as "not prime"
it  will be o(n.ln(n)) with a=1 and b=n (i think)
algorithm for 1 to n:
g: array of n elements
for i starting with 2 to n
    if g[i]== 0
        for each multiple of i <n
            g[i] += 1

A: You can sieve for the count of divisors, then sum the counts:
function divCount(a,b)
    num := makeArray(1..b, 0)
    for i from 1 to b
        for j from i to b step i
            num[j] := num[j] + 1
    sum := 0
    for i from a to b
        sum := sum + num[i]
    return sum

This is similar to a Sieve of Eratosthenes, but instead of marking off the composites it counts each divisor for every number, including both primes and composites. If b is too large, you can perform the sieving in segments.

A: Another sieve-based answer, but with a better time complexity than the others. This one also handles segmentation easily, since it only sieves numbers {a...b} on each run. The function returns an int[] with the number of divisors for each number from a to b. Just sum them up to get the final answer.
If your inputs are larger, you can split it up and add the sums from each returned segment.
Java:
public static int[] getDivisorCount(int a, int b){
    int[] sieve = new int[b - a + 1];
    double max = Math.ceil(Math.sqrt(b));
    for(int i = 1; i <= max; i++){
        int j = (a / i) * i;
        if(j < a)
            j += i;
        for( ; j <= b; j += i){
            double root = Math.sqrt(j);
            if(i < root){
                sieve[j - a] += 2;
            }else if(i == root){
                sieve[j - a]++;
            }
        }
    }
    return sieve;
}

The outer loop runs sqrt(b) times. The inner loop runs something like log(b-a) times, so unless I'm mistaken, the final complexity should be something like O(sqrt(b) * log(b)), since worst case is a=1. Feel free to correct me on that.
If you're handling large inputs and you have the space to spare, you might want to consider prepopulating a sqrt table to get it out of the inner loop. It would speed it up, and if you've got the memory to spare, there's no real down side to it.
For a quick test, here's an ideone.com example.
Edit: If you're looking for a sieve, this is fine. However, I must say that jwpat7's answer is 1)faster, 2) constant space, and 3) more elegant (IMO). There's basically no reason to use a sieve unless you're interested in the mechanics of it.


text:
Q: How do you namespace objects in the Revealing Prototype Pattern? I've been using the Revealing Module pattern and have several namespaces.
Example:
// here's the namespace setup

var myProject= myProject|| {};
var myProject.models= myProject.models || {};

myProject.models.MyModel= function(){
   var someMethod = function(){
     // do something
   };
   return{
      SomeMethod = someMethod
   };
}

I'm moving to the Revealing Prototype Pattern to gain some memory usage improvements and so I can decorate the object another function. How do I keep it in my myProject.models namespace?
This gives my JavaScript errors:
var myProject.models.MyModel= function(){
   // properties here
};

myProject.models.MyModel.prototype = (function(){
   // methods here
    var someMethod = function(){
         // do something
    };
    return{
       SomeMethod = someMethod
    };
}());

A: You have various syntax errors.
myProject = window.myProject|| {};

myProject.models = myProject.models || {};

myProject.models.MyModel = (function () {
   //declare a constructor function
   function MyModel() {
   }

   //declare a function that will be publicly available on each MyModel instances
   MyModel.prototype.someFunction = function () {
       //call the private function from within the public one
       //note: you have to be careful here since the context object (this) will be
       //window inside somePrivateFunction
       somePrivateFunction();

       //call the private function and set the context object to the current model instance
       //somePrivateFunction.call(this);
   };

   //declare a private function
   function somePrivateFunction() {
   }

   return MyModel; //return the model constructor
})();

Now you can use your model like:
var m = new myProject.models.MyModel();
m.someFunction();

A:
var myProject = myProject || {};
^^^

You are using a var statement here to declare the global myProject variable (if it hasn't been already), so that it will not throw Undefined variable exceptions. (Also you initialise it to an empty object if it had now value)

var myProject.models= myProject.models || {};

In here, you are assigning the models property to the object from above. The var keyword is out of place here; remove it and it will work.
With myProject.models.MyModel = … you did it right in the upper snippet and wrong in the second one; I'm not sure which you were trying to use. The revealing prototype pattern should look like this:
var myProject = myProject || {};
myProject.models = myProject.models || {};
myProject.models.MyModel = (function(){
    function MyModel() {
        // instance properties here
    }
    function someMethod(){
        // do something
    }
    MyModel.prototype.SomeMethod = someMethod;
    //                ^ lowercase that?
    return MyModel;
})();


text:
Q: Searching the 5 closest locations to a zip code - what way should I go? What I want:

*

*The user passes in a zip code or city name

*I search my database for the 5 closest locations

*Display the 5 closest locations near that position to the user

What I have so far:
Let's say a table of places with the following content:
(about 16000 rows)
CREATE TABLE `locations` (
 `locationID` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(150) NOT NULL,
 `firstname` varchar(100) DEFAULT NULL,
 `lastname` varchar(100) DEFAULT NULL,
 `street` varchar(100) NOT NULL,
 `city` varchar(100) NOT NULL,
 `state` varchar(100) NOT NULL,
 `zipcode` varchar(10) NOT NULL,
 `phone` varchar(20) NOT NULL,
 `web` varchar(255) DEFAULT NULL,
 `machine` enum('Unbekannt','Foo','Bar') DEFAULT 'Unbekannt',
 `surface` enum('Unbekannt','Foo','Bar','') DEFAULT 'Unbekannt',
 PRIMARY KEY (`locationID`)
) ENGINE=InnoDB AUTO_INCREMENT=25 DEFAULT CHARSET=utf8

*

*ID

*name

*zip code

*city

Now I've got a second table with all towns of the world:
(about 3.4 million rows)
CREATE TABLE `geoData` (
 `geoID` int(11) NOT NULL AUTO_INCREMENT,
 `countryCode` char(2) NOT NULL,
 `zipCode` varchar(20) NOT NULL,
 `name` varchar(180) NOT NULL,
 `state` varchar(100) NOT NULL,
 `stateCode` varchar(20) NOT NULL,
 `county` varchar(100) NOT NULL,
 `countyCode` varchar(20) NOT NULL,
 `community` varchar(100) NOT NULL,
 `communityCode` varchar(20) NOT NULL,
 `lat` mediumint(6) NOT NULL,
 `lon` mediumint(6) NOT NULL,
 PRIMARY KEY (`lon`,`lat`,`geoID`) USING BTREE,
 KEY `geoID` (`geoID`)
) ENGINE=InnoDB AUTO_INCREMENT=16482 DEFAULT CHARSET=utf8
/*!50100 PARTITION BY RANGE (lat)
(PARTITION p0 VALUES LESS THAN (-880000) ENGINE = InnoDB,
PARTITION p1 VALUES LESS THAN (-860000) ENGINE = InnoDB,
PARTITION p2 VALUES LESS THAN (-840000) ENGINE = InnoDB,
PARTITION p3 VALUES LESS THAN (-820000) ENGINE = InnoDB,
PARTITION p4 VALUES LESS THAN (-800000) ENGINE = InnoDB,
PARTITION p5 VALUES LESS THAN (-780000) ENGINE = InnoDB,
PARTITION p6 VALUES LESS THAN (-760000) ENGINE = InnoDB,
PARTITION p7 VALUES LESS THAN (-740000) ENGINE = InnoDB,
PARTITION p8 VALUES LESS THAN (-720000) ENGINE = InnoDB,
PARTITION p9 VALUES LESS THAN (-700000) ENGINE = InnoDB,
PARTITION p10 VALUES LESS THAN (-680000) ENGINE = InnoDB,
PARTITION p11 VALUES LESS THAN (-660000) ENGINE = InnoDB,
PARTITION p12 VALUES LESS THAN (-640000) ENGINE = InnoDB,
PARTITION p13 VALUES LESS THAN (-620000) ENGINE = InnoDB,
PARTITION p14 VALUES LESS THAN (-600000) ENGINE = InnoDB,
PARTITION p15 VALUES LESS THAN (-580000) ENGINE = InnoDB,
PARTITION p16 VALUES LESS THAN (-560000) ENGINE = InnoDB,
PARTITION p17 VALUES LESS THAN (-540000) ENGINE = InnoDB,
PARTITION p18 VALUES LESS THAN (-520000) ENGINE = InnoDB,
PARTITION p19 VALUES LESS THAN (-500000) ENGINE = InnoDB,
PARTITION p20 VALUES LESS THAN (-480000) ENGINE = InnoDB,
PARTITION p21 VALUES LESS THAN (-460000) ENGINE = InnoDB,
PARTITION p22 VALUES LESS THAN (-440000) ENGINE = InnoDB,
PARTITION p23 VALUES LESS THAN (-420000) ENGINE = InnoDB,
PARTITION p24 VALUES LESS THAN (-400000) ENGINE = InnoDB,
PARTITION p25 VALUES LESS THAN (-380000) ENGINE = InnoDB,
PARTITION p26 VALUES LESS THAN (-360000) ENGINE = InnoDB,
PARTITION p27 VALUES LESS THAN (-340000) ENGINE = InnoDB,
PARTITION p28 VALUES LESS THAN (-320000) ENGINE = InnoDB,
PARTITION p29 VALUES LESS THAN (-300000) ENGINE = InnoDB,
PARTITION p30 VALUES LESS THAN (-280000) ENGINE = InnoDB,
PARTITION p31 VALUES LESS THAN (-260000) ENGINE = InnoDB,
PARTITION p32 VALUES LESS THAN (-240000) ENGINE = InnoDB,
PARTITION p33 VALUES LESS THAN (-220000) ENGINE = InnoDB,
PARTITION p34 VALUES LESS THAN (-200000) ENGINE = InnoDB,
PARTITION p35 VALUES LESS THAN (-180000) ENGINE = InnoDB,
PARTITION p36 VALUES LESS THAN (-160000) ENGINE = InnoDB,
PARTITION p37 VALUES LESS THAN (-140000) ENGINE = InnoDB,
PARTITION p38 VALUES LESS THAN (-120000) ENGINE = InnoDB,
PARTITION p39 VALUES LESS THAN (-100000) ENGINE = InnoDB,
PARTITION p40 VALUES LESS THAN (-80000) ENGINE = InnoDB,
PARTITION p41 VALUES LESS THAN (-60000) ENGINE = InnoDB,
PARTITION p42 VALUES LESS THAN (-40000) ENGINE = InnoDB,
PARTITION p43 VALUES LESS THAN (-20000) ENGINE = InnoDB,
PARTITION p44 VALUES LESS THAN (0) ENGINE = InnoDB,
PARTITION p45 VALUES LESS THAN (20000) ENGINE = InnoDB,
PARTITION p46 VALUES LESS THAN (40000) ENGINE = InnoDB,
PARTITION p47 VALUES LESS THAN (60000) ENGINE = InnoDB,
PARTITION p48 VALUES LESS THAN (80000) ENGINE = InnoDB,
PARTITION p49 VALUES LESS THAN (100000) ENGINE = InnoDB,
PARTITION p50 VALUES LESS THAN (120000) ENGINE = InnoDB,
PARTITION p51 VALUES LESS THAN (140000) ENGINE = InnoDB,
PARTITION p52 VALUES LESS THAN (160000) ENGINE = InnoDB,
PARTITION p53 VALUES LESS THAN (180000) ENGINE = InnoDB,
PARTITION p54 VALUES LESS THAN (200000) ENGINE = InnoDB,
PARTITION p55 VALUES LESS THAN (220000) ENGINE = InnoDB,
PARTITION p56 VALUES LESS THAN (240000) ENGINE = InnoDB,
PARTITION p57 VALUES LESS THAN (260000) ENGINE = InnoDB,
PARTITION p58 VALUES LESS THAN (280000) ENGINE = InnoDB,
PARTITION p59 VALUES LESS THAN (300000) ENGINE = InnoDB,
PARTITION p60 VALUES LESS THAN (320000) ENGINE = InnoDB,
PARTITION p61 VALUES LESS THAN (340000) ENGINE = InnoDB,
PARTITION p62 VALUES LESS THAN (360000) ENGINE = InnoDB,
PARTITION p63 VALUES LESS THAN (380000) ENGINE = InnoDB,
PARTITION p64 VALUES LESS THAN (400000) ENGINE = InnoDB,
PARTITION p65 VALUES LESS THAN (420000) ENGINE = InnoDB,
PARTITION p66 VALUES LESS THAN (440000) ENGINE = InnoDB,
PARTITION p67 VALUES LESS THAN (460000) ENGINE = InnoDB,
PARTITION p68 VALUES LESS THAN (480000) ENGINE = InnoDB,
PARTITION p69 VALUES LESS THAN (500000) ENGINE = InnoDB,
PARTITION p70 VALUES LESS THAN (520000) ENGINE = InnoDB,
PARTITION p71 VALUES LESS THAN (540000) ENGINE = InnoDB,
PARTITION p72 VALUES LESS THAN (560000) ENGINE = InnoDB,
PARTITION p73 VALUES LESS THAN (580000) ENGINE = InnoDB,
PARTITION p74 VALUES LESS THAN (600000) ENGINE = InnoDB,
PARTITION p75 VALUES LESS THAN (620000) ENGINE = InnoDB,
PARTITION p76 VALUES LESS THAN (640000) ENGINE = InnoDB,
PARTITION p77 VALUES LESS THAN (660000) ENGINE = InnoDB,
PARTITION p78 VALUES LESS THAN (680000) ENGINE = InnoDB,
PARTITION p79 VALUES LESS THAN (700000) ENGINE = InnoDB,
PARTITION p80 VALUES LESS THAN (720000) ENGINE = InnoDB,
PARTITION p81 VALUES LESS THAN (740000) ENGINE = InnoDB,
PARTITION p82 VALUES LESS THAN (760000) ENGINE = InnoDB,
PARTITION p83 VALUES LESS THAN (780000) ENGINE = InnoDB,
PARTITION p84 VALUES LESS THAN (800000) ENGINE = InnoDB,
PARTITION p85 VALUES LESS THAN (820000) ENGINE = InnoDB,
PARTITION p86 VALUES LESS THAN (840000) ENGINE = InnoDB,
PARTITION p87 VALUES LESS THAN (860000) ENGINE = InnoDB,
PARTITION p88 VALUES LESS THAN (880000) ENGINE = InnoDB,
PARTITION p89 VALUES LESS THAN MAXVALUE ENGINE = InnoDB) */

*

*ID

*city

*zip code

*latitude

*longitude

based on this article and some other reading up on that matter I have a stored procedure which is giving me n locations/zip codes of the closest towns near a point (latitude/longitude).
My stored procedure:
    BEGIN
    DECLARE _deg2rad DOUBLE DEFAULT PI()/1800000;

    SET @my_lat := _my_lat,
        @my_lon := _my_lon,
        @deg2dist := 0.0111325,
        @start_deg := _start_dist / @deg2dist,
        @max_deg := _max_dist / @deg2dist,
        @cutoff := @max_deg / SQRT(2),
        @dlat := @start_deg,
        @lon2lat := COS(_deg2rad * @my_lat),
        @iterations := 0;

    SET @sql = CONCAT(
        "SELECT COUNT(*) INTO @near_ct
            FROM geoData
            WHERE lat    BETWEEN @my_lat - @dlat
                             AND @my_lat + @dlat
              AND lon    BETWEEN @my_lon - @dlon
                             AND @my_lon + @dlon");
    PREPARE _sql FROM @sql;
    MainLoop: LOOP
        SET @iterations := @iterations + 1;
        SET @dlon := ABS(@dlat / @lon2lat);
        SET @dlon := IF(ABS(@my_lat) + @dlat >= 900000, 3600001, @dlon);
        EXECUTE _sql;
        IF ( @near_ct >= _limit OR
             @dlat >= @cutoff ) THEN
            LEAVE MainLoop;
        END IF;
        SET @dlat := LEAST(2 * @dlat, @cutoff);
    END LOOP MainLoop;
    DEALLOCATE PREPARE _sql;

    SET @dlat := IF( @dlat >= @max_deg OR @dlon >= 1800000,
                @max_deg,
                GCDist(ABS(@my_lat), @my_lon,
                       ABS(@my_lat) - @dlat, @my_lon - @dlon) );
    SET @dlon := IFNULL(ASIN(SIN(_deg2rad * @dlat) /
                             COS(_deg2rad * @my_lat))
                            / _deg2rad
                        , 3600001);

    IF (ABS(@my_lon) + @dlon < 1800000 OR
        ABS(@my_lat) + @dlat <  900000) THEN
        SET @sql = CONCAT(
            "SELECT *,
                    @deg2dist * GCDist(@my_lat, @my_lon, lat, lon) AS dist
                FROM geoData
                WHERE lat BETWEEN @my_lat - @dlat
                              AND @my_lat + @dlat
                  AND lon BETWEEN @my_lon - @dlon
                              AND @my_lon + @dlon
                HAVING dist <= ", _max_dist, "
                ORDER BY dist
                LIMIT ", _limit
                        );
    ELSE
        SET @west_lon := IF(@my_lon < 0, @my_lon, @my_lon - 3600000);
        SET @east_lon := @west_lon + 3600000;
        SET @sql = CONCAT(
            "( SELECT *,
                    @deg2dist * GCDist(@my_lat, @west_lon, lat, lon) AS dist
                FROM geoData
                WHERE lat BETWEEN @my_lat - @dlat
                              AND @my_lat + @dlat
                  AND lon BETWEEN @west_lon - @dlon
                              AND @west_lon + @dlon
                HAVING dist <= ", _max_dist, " )
            UNION ALL
            ( SELECT *,
                    @deg2dist * GCDist(@my_lat, @east_lon, lat, lon) AS dist
                FROM geoData
                WHERE lat BETWEEN @my_lat - @dlat
                              AND @my_lat + @dlat
                  AND lon BETWEEN @east_lon - @dlon
                              AND @east_lon + @dlon
                HAVING dist <= ", _max_dist, " )
            ORDER BY dist
            LIMIT ", _limit
                        );
    END IF;

    PREPARE _sql FROM @sql;
    EXECUTE _sql;
    DEALLOCATE PREPARE _sql;
END

My Problem:
I would like to pass in a zip code or name of a town and start my search from there. So my thought was I request this information and look up my table of all towns/zip codes from the world. After that, I have the information of lat/lon if only one result was found or I would ask the user to select the right choice in that case of having multiple results.
After that, I start searching for nearest towns close to my current position. Let's say I want a list of 50 towns/cities. And with that, I'd go and look up and see if the table containing the locations matches 5 results in there.
On second thought, this sounds like a bad idea...
Approach 1:
I read up on stored procedures, sql and monster queries and try to get the following:
Passing in a zip code/city name I would look that up, take my lat/lon from the huge table (possible as the function in mysql) and with that given I'd look for the nearest towns and join right then and there the locations table and get my 5 closest locations.
Questions:

*

*How would I avoid having several matches for the same name of a city/zip code?

*Does it sound possible to do so with a simple join in order to get the 5 closest locations?

Approach 2:
Get all the lat/lon values of my locations and then run the procedure on this table instead. And just use the huge table in order to retrieve my current position?
With that, I would need to gather all the lat/lon of my locations though. But it might be the best way.
But having the huge database of all cities/zip codes just to get the locations seems like a bit of an overkill. I would hope there is an alternative then maybe... somehow...
Approach 3
To be honest, this function I want seems like written a million times before. So why should I bother reinventing the wheel? But I have no clue how to find the right articles or books in order to accomplish my goal.
Has anyone else of you an idea for the best practice for something like that?

A: First some comments...
I've seen dozens (not millions) of implementation here and on other forums; yours is better than most.
According to one data source (which I happen to have downloaded) there are about 3.2 million cities in the world.
For performance, you need to avoid checking all 3M rows.  You have made a good start with the growing bounding box.  Note that you should have
INDEX(lat, lon),
INDEX(lon, lat)

The Optimizer will choose between those and the first query (with the COUNT(*)) will see that as 'covering'.  It will be a stripe around the globe or a wedge; a definite improvement over 3M rows.  The worst latitude (+34 degrees) has 96K cities in it.  (1 degree = 69 miles / 111 km.)  For a tenth of a degree, 34.4 is the worst, with 10K cities.
(Yes, I enjoy this kind of data puzzle.)
And, I see that you handle the dateline and poles.  I don't think you can improve on having them as a special case.
(I have only glanced at the formulas and constants.)
Geohash and Z-order indexing help.  But they have a hiccup in that you need to check up to 4 areas around the target -- It's like not realizing that the integers 199999 and 200000 are really close to each other, in spite of the first digit of each is different.
"User passes in zip code or city name" -- that's a point query into one of two simple tables.  (Except that there can be dups -- over 320 each of "san jose" and "san antonio".  Pretty far down the list is the first non-Spanish name: "victoria", with only 144 cities.)
Second, my implementation...  (It has some similarities to yours.)
http://mysql.rjweb.org/doc.php/latlng
This improves on performance by using PARTITIONing to keeping the bounding box down to roughly a square, instead of a stripe or wedge.  If you are looking for the 5 nearest, my algorithm will rarely touch more than a few dozen rows, and those rows will be 'clustered' in a small number of blocks, thereby keeping the number of disk hits very low.
A critical thing in my design is to have all the necessary columns in the one table.  Once you have found the nearest 5, you can go off to other tables to get ancillary things (phone number, etc).
As for zip codes, turn them into lat/lon before starting the search for the 5 nearest.
A join inside the algorithm is very likely to destroy the performance.

A: 16K rows isn't really that much.
I have a cities table with 3.1M rows (data taken from https://www.maxmind.com/de/free-world-cities-database). I have created a "fake" locations table with 16K distinct random cityIds and some dummy data. I use one column with POINT data type instead of latitude and longitude. And this is what I get from quite simple queries on MySQL 5.7.18:
select l.*, c.*, st_distance(point(-0.127758, 51.507351), c.geoPoint) dist
from locations l
join cities c using (cityId)
order by dist
limit 5

Execution time is ~ 70ms.
That can be improved with a subquery:
select l.*, c.*, x.dist
from (
    select l.locationId, st_distance(point(-0.127758, 51.507351), c.geoPoint) dist
    from locations l
    join cities c using (cityId)
    order by dist
    limit 5
) x
join locations l using(locationId)
join cities c using(cityId)

Execution time: ~ 40ms
If you store the geoPoint (redundantly) in the locations table, you can avoid the join with the cities table.
select l.*, st_distance(point(-0.127758, 51.507351), l.geoPoint) dist
from locations l
order by dist
limit 5

Execution time: ~ 17ms
You can still join the cities table to the subquery without losing performance.
Note that all those queries will calculate the distance for all 16K rows and sort them. But the performance might though be enough for you.
If that is not fast enough or the locations table will grow over the time or if you want to search in the big table, you can still do something similar as you do with your procedure using a SPATIAL INDEX on geoPoint and MBRWithin() or MBRContains().
The algorithm:

*

*Define a small polygon around the users location.

*Increase the size of the polygon in a loop until it contains at least 5 locations.

*Use the locations within the polygon to select 5 nearest.

Note that depending on what type of polygon you use, you might need to increase the size once again after you've found one with 5 locations. For example - if you use a square (simple implementation), you should double the size (increase the length by factor sqrt(2)), to be absolutly sure that you don't miss a location outside the square, which is closer than the 5th location within the square. This is because a square is not a circle. But if you use an octagon, you might say - this is circle enough - and skip the last step.
This might be not the best algorithm. But it is quite simple to implement and should scale well enough.


text:
Q: Redistributing probability mass Consider some canonical probability space $(\Omega,\mathcal{F},\mathbb{P})$ and a random variable $X:\Omega\rightarrow[0,\infty)$ and let's assume that $X$ is unbounded, but has finite expectation.
That is, $X\in\mathcal{L}^{1}$, and for all $M\in[0,\infty)$ we have $\mathbb{P}(X \geq M)>0$.
I am wondering, if there is a way to construct a bounded random variable $\hat{X}$ with

*

*$\mathbb{E}[X] = \mathbb{E}[\hat{X}]$

*$\hat{X}(\Omega)\subset X(\Omega)$.

Intuitively, one should redistribute probability mass from the tail of the random variable into some bounded domain. But I expect some assumption on the underlying probability space for this to be possible.
Have you seen sothing similar or can you point me in the right direction? Any comments, ideas and suggestions are highly appreciated. Thank you!

A: This is not really an answer to your question, but might lead to the conclusion that such $\hat X$ cannot always be found. In the sequel $\mathbb N$ denotes the set of positive integers.
Let  $(\Omega,\mathcal F,\mathbb P)=(\mathbb N,\wp(\mathbb N),\mathbb P)$ where $\mathbb P(\{n\})=p_n$.
Let $X:\mathbb N\to[0,\infty)$ be prescribed by $n\mapsto n$.
For $n=\mathbb N=\{1,2,\dots\}$ let $p_n>0$ with (of course) $\sum_{n=0}^{\infty}p_n=1$ and also $\sum_{n=0}^{\infty}np_n<\infty$.
Question: does there exist a finite partition $\{P_1,\dots, P_m\}$ of $\mathbb N$ such that  $$\sum_{k=1}^m\sum_{n\in P_k}kp_n=\sum_{n=0}^{\infty}np_n\tag1$$
The RHS of $(1)$ equals $\mathbb EX$.
The LHS of $(1)$ equals the expectation of $\hat{X}$ determined by $\hat X^{-1}(\{k\})=P_k$.
If you can find a case of non-existence of such partition then you have found an example where no such $\hat X$ can be found.

A: Provided that your $X$ is a continuous variable, I think that the simplest strategy would be to cut not only the tail but also the head of your distribution so that the expectation value is unchanged. Then you can concentrate the probability mass you have taken away exactly on the expectation value. This should satisfy your requests: $\hat X$ goes to some interval $[\epsilon,k]$ and is constructed so that $\mathbb{E}[\hat{X}] = \mathbb{E}[X]$.


text:
Q: Authenticating FreeRadius request with Atlassian Crowd I want to authenticate users using Atlassian Crowd from FreeRADIUS and I've been unable to find a plugin or particularly good examples of how this might be done. Specifically in trying to implement the authorize and authenticate portions using an rlm_python script isn't terribly clear. Is there a more complex example where a RESTful backend is used to authenticate without needing to know the password in the authorize function?

A: With some experimentation I created a plugin using python-crowd. You need to add a new Auth-Type to the authorize file that I called CROWD and add python as the authenticator and the authorize section of that file. In mod-configs/python make sure to set the module name and enable authorize and authenticate function calls.
crowdplugin.py
#! /usr/bin/env python

import radiusd
import crowd

cs = None
app_url = ''
app_user = ''
app_pass = ''

def instantiate(p):
  global cs
  cs = crowd.CrowdServer(app_url, app_user, app_pass)

def authorize(p):
  reply = None
  config = None
  result = radiusd.RLM_MODULE_NOTFOUND

  values = dict(p)
  username = values['User-Name']
  success = cs.get_user(username)
  if success:
     config = ( ( 'Auth-Type', 'crowd' ), )
     result = radiusd.RLM_MODULE_OK
  return ( result, reply, config )

def authenticate(p):
  reply = None
  config = None
  result = radiusd.RLM_MODULE_REJECT

  values = dict(p)
  username = values['User-Name']
  password = values['User-Password']
  success = cs.auth_user(username, password)
  if success:
     reply = ( ( 'Reply-Message', 'Welcome!'), )
     result = radiusd.RLM_MODULE_OK
  return ( result, reply, config )


text:
Q: How to Deal with Environment Variables on Same Machine in Api Requests I have the following scenario:
I have two Domains: domain1.local and domain2.local . They are both set via hosts file to the ip 127.0.0.1 . The Applications on both domains use environment variables by defining them in a .env file ( Concrete5 and Laravel )
I am trying to make an api request like this:
    // executed on domain1.local
    // GuzzleHttpClient
    $client = new Client([
        'query' => ['some_query_data' => '123']
    ]);

    $response = $client->get('domain2.local/api/test');

The problem is, that both applications use Environment Variables with same names like DB_DATABASE. So if  I execute the api call to domain2.local the environment variables of domain1.local are used and a database error occures.
Is there a convenient way to deal with this issue?

A: The problem can be solved in the following way:

*

*You have not correctly specified the directories in the
configuration of your web server

*You have not correctly configured
.env files


text:
Q: Jess rule definition I use the Jess Rule Engine in Protégé.
I need to create a test rule using classes, I defined in Jess code.
Here are classes & instances definition code:
(clear)
(defclass Student
    (is-a :THING)
    (slot studId (type string))
    (slot studName (type string))
    (slot satGrade (type integer))
)
(defclass Course
    (is-a :THING)
    (slot courseId (type string))
    (slot courseName (type string))
    (slot passGrade (type integer))
)
(defclass StudentInCourse
    (is-a :THING)
    (slot studId (type string))
    (slot courseId (type string))
    (slot finalGrade (type integer))
)

(make-instance stud_01 of Student (studId "s123") (studName "Rob") (satGrade 650))
(make-instance stud_02 of Student (studId "s456") (studName "Pete") (satGrade 700))
(make-instance stud_03 of Student (studId "s789") (studName "Alex") (satGrade 770))
(mapclass Student)
(deffacts Student (Student (studId)(studName)(satGrade)))
(make-instance course_01 of Course (courseId "c123") (courseName "Calculus") (passGrade 60))
(make-instance course_02 of Course (courseId "c456") (courseName "Linear Algebra") (passGrade 70))
(mapclass Course)
(deffacts Course (Course (courseId)(courseName)(passGrade)))
(make-instance studInCourse_01 of StudentInCourse (studId "s123") (courseId "c123") (finalGrade 20))
(make-instance studInCourse_02 of StudentInCourse (studId "s123") (courseId "c456") (finalGrade 90))
(make-instance studInCourse_03 of StudentInCourse (studId "s456") (courseId "c123") (finalGrade 80))
(make-instance studInCourse_04 of StudentInCourse (studId "s789") (courseId "c456") (finalGrade 75))
(mapclass StudentInCourse)
(deffacts StudentInCourse (StudentInCourse (studId)(courseId)(finalGrade)))

Now I want to implement a check who among the students passes the course «Linear Algebra», I know how to implement it in SQL/Java/C#, but I can't understand how exactly to write it in Jess, each string I push to Jess returns a parsing/compilation error.
How exactly to implement kind of join in Jess or pass over the collection, get courseID, to compare the values according to ID and passGrade/finalGrade, for the correct values to retrieve the data from the student class and as the result to return something like: «Pete passed course Linear Algebra with grade 80»?

A: It's been ages since I touched Protege, but based on what you have above, I'm assuming you have facts like these (among others). The "deffacts" you have above must be notional at this point -- they won't do anything good (and may not even parse).
(Student (studId "s123")(studName "Rob")(satGrade 650))
(StudentInCourse (studId "s123") (courseId "c456") (finalGrade 90))
(Course (courseId "c456") (courseName "Linear Algebra") (passGrade 70))

Given that I'm right about the above, then a rule that reported each student who passed any course might look like
(defrule passed-algebra
    (Course (courseName ?cn) (courseId ?cid) (passGrade ?pg))
    (StudentInCourse (courseId ?cid) (studId ?sid) (finalGrade ?fg&:(>= ?fg ?pg))
    (Student (studName ?name) (studId ?sid))
    =>
    (printout t ?name " passed course " ?cn " with a grade of " ?fg crlf))


text:
Q: How to write to an existing excel file without breaking formulas with openpyxl? When you write to an excel file from Python in the following manner:
import pandas
from openpyxl import load_workbook

book = load_workbook('Masterfile.xlsx')
writer = pandas.ExcelWriter('Masterfile.xlsx')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)

data_filtered.to_excel(writer, "Main", cols=['Diff1', 'Diff2'])

writer.save()

Formulas and links to charts which are in the existing sheets, will be saved as values.
How to overwrite this behaviour in order to preserve formulas and links to charts?

A: Openpyxl 1.7 contains several improvements for handling formulae so that they are preserved when reading. Use guess_types=False to prevent openpyxl from trying to guess the type for a cell and 1.8 includes the data_only=True option if you want the values but not the formula.
Want to preserve charts in the 2.x series.

A: Here I address the "preserve the formulas" part of the question only.
I tried using openpyxl 1.8, which did successfully read the formulas, but when I tried to save a copy it broke. (The breakage appeared to be related to the styles, not the formulas.)
In any event, what I recommend (until openpxyl comes a tad further) is to map the formulas to a new xlsxwriter.Workbook object. I've had success using that module to create new xlsx workbooks (with formatting and formulas), and without knowing how well the formats will translate from the openpyxl object to the xlsxwriter one, I believe it will be a viable solution for preserving at least the formulas.
Now, doing this (which I wanted to and did myself) is NOT super simple because of shared formulas. I had to write a tool that 'de-shares' these shared formulas, transposes them, and applies them to each cell that refers to it.
One might first think that this approach creates inefficiencies by adding a bunch of formulas where previously there were just references to an existing formula. However, I tried writing these 'redundant' formulas with xlsxwriter and then reading that sheet back in with openpyxl again. I discovered that the formulas again were read in as shared, so either xlsxwriter or the Excel application itself is doing this optimization. (One could easily figure out which, of course; I just haven't yet.)
I'd be happy to post my solution for desharing and transposing if it would be helpful iff there's demand; currently it's integrated into a larger module and I'd have to create a standalone version. Generally speaking though, I used the shunting yard tool in the tokenizer discussed in ecatmur's response to this question to parse the formula, which is the hardest part of transposing them (which of course you have to do if you want to infer what the shared formula will look like in another 'host cell').

A: In excel:
  Home --> Find & Select --> Replace

  Replace All: "=" with "spam"

In python:
  Run python script to update excel sheets

In excel:
  Replace All: "spam" with "="

A: I know this is an older thread, but it took me a while to find a solution - xlwings allows you to write to one tab and retain charts on another.
The follow example opens an existing workbook, updates the data a chart is based on, and saves as a new version.
import xlwings as xw
import pandas as pd

#create DF
months = ['2017-01','2017-02','2017-03','2017-04','2017-05','2017-06','2017-07','2017-08','2017-09','2017-10','2017-11','2017-12']
value1 = [x * 5+5 for x in range(len(months))]
df = pd.DataFrame(value1, index = months, columns = ['value1'])
df['value2'] = df['value1']+5
df['value3'] = df['value2']+5

#load workbook that has a chart in it
wb = xw.Book('C:\\data\\bookwithChart.xlsx')

ws = wb.sheets['chartData']

ws.range('A1').options(index=False).value = df

wb = xw.Book('C:\\data\\bookwithChart_updated.xlsx')

xw.apps[0].quit()


text:
Q: How to hide content on mobile in the functions.php file - woocommerce I have inserted an image onto my woo-commerce single product page using the below hook and code written into my functions.php file:
add_action('woocommerce_after_single_product_summary', add_content_on_woocommerce_after_single_product_summary',1);

function add_content_on_woocommerce_after_single_product_summary() {

      echo "<img src='https://mywebsite/wp-content/uploads/2022/02/blocks.png' >" ;
}

I only want this image to display on mobile and not desktop. Is there any code I can add to this in my functions.php file to achieve this?

A: Probably the easiest method would be assign the image a class and display:none it based on media query.


text:
Q: Sorting through values php mysql I have a database with rows containing an ID and a value.
I randomly insert these values between the numbers 1 and 100 as I insert records, so an ID has a random value. I use a while loop to go through the records and print them to screen. However, the way I want it is if the current value of the row in the while loop is LESS than the next value, then break out of the loop. Basically what I am asking is how to refer to the next record of a database while in a while loop working with the current, simply to check a value in it.

A: Try this:
$previousRow = mysql_fetch_assoc($result);
$previousRow['ID'] = -1;

while($currentRow = mysql_fetch_assoc($result))
{
    if($currentRow['ID'] > $previousRow['ID'])
         break;

    echo $previousRow['Value'];
    $previousRow = $currentRow;
}

A: $lastRecord = Array();
foreach($records as $thisRecord){
    if($lastRecord['value'] < $thisRecord['value']){
        // do what you need to do here
    }
    $lastRecord = $thisRecord;
}

This way you always keep the previous value stored

A: Do it the other way round. Instead of breaking out based on the next element, just check on the next element based on the previous element (which you can simply store somewhere). I guess that the loop actually loops through the elements and does something; you can then just check the previous/current element first before doing anything and nobody will notice that you in fact loaded the next element.


text:
Q: How can i load a BufferedImage to my runnable JAR file? I'm trying to export a JAR file from my project and I need some of my BufferedImages to get loaded in it.
Structure is this:
-src
  -img
  -models
  -views

...
and knowing that all my image files are stored into the img package. I'm trying to do this in a JPanel from other project:
public class BelowPanel extends JPanel {

    private BufferedImage img;

    public BelowPanel() {
        initImage();
        setOpaque(false);
    }

    private void initImage() {
        try {
             img = ImageIO.read(getClass().getResourceAsStream(("/img/titan.png")));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void paint(Graphics g) {
        super.paint(g);
        Graphics2D g2 = (Graphics2D)g;
        g2.drawImage(img, 0, 0,this.getWidth(),this.getHeight(), this);
    }
}

When I run this it shows the image, but once I  generate the JAR file in my desktop, it doesn't even run.
My images of Image type, doesn't have any problem, but BufferedImages doesn't load.
So... Do you know a way to load my "titanImage", so I can generate a running JAR file which can work correctly?


text:
Q: How to set the focus of a TextField when it appears on the view in SwiftUI I want a text field to be selected when it appears on the screen, but I can't get it working. It only works in this example when I tap the button.
struct ContentView: View {
    @State var text = "Hello World"
    @FocusState var focused: Bool?
    var body: some View {
        VStack {
            TextField("Placeholder", text: $text)
                .focused($focused, equals: true)
                .onAppear {
                    focused = true
                }

            Button {
                focused = true
            } label: {
                Text("Select")
            }
        }
    }
}

A: Execute focused = true after delay, using asyncAfter().
Try like this:
struct ContentView: View {
@State var text = "Hello World"
@FocusState var focused: Bool?
var body: some View {
    VStack {
        TextField("Placeholder", text: $text)
            .focused($focused, equals: true)
            .onAppear {
              DispatchQueue.main.asyncAfter(deadline: .now() + 0.75) {
                self.focused = true
              }
            }

        Button {
            focused = true
        } label: {
            Text("Select")
        }
    }

}
}


text:
Q: Is there a way to recover the undertale genocide route after fighting mettaton NEO I was doing an undertale genocide route and I read a post that said an undertale genocide route would be cancelled if you fight Mettaton NEO before clearing Hotland/The Core. Is there a way to recover the genocide route without reseting?
I fought Mettaton NEO before clearing Hotland/The Core and I can't encounter an monster.

A: Unfortunately, the only way I know to return to genocide route after defeating mettaton NEO early, is to quit without saving. It's easy to accidentally ruin a genocide run.


text:
Q: Keeping multiple MySQL database schema's synced Is there a way to keep a lot of MySQL database schema's (not the data) synchronized so that I can update them all at once?
For example, let's say you have a lot of companies each with their own database (with their own data), but the structure of these databases have to always be the same to work with the (common) application software.
These databases are also distributed across a lot of different machines, so I can't just connect and do a SHOW DATABASES and then execute the query on each matching DB.
Is there a way to achieve this, preferably with PHP or Node.js?


text:
Q: Easiest way to recommend users to upgrade their browser? There have been a lot of buzz around IE6NoMore campaign.
What's the easiest way to recommend users to upgrade their browser?

A: Use conditional comments targeting IE. This way other browsers/bots (even when masquerading as IE) won't see it.
Make sure the message is polite and unobtrusive. Focus on benefits of change ("our website is faster and easier to use in up-to-date browsers") rather than negative aspects of IE (otherwise users could interpret this as ridicule of them or anti-Microsoft fanboyism).
Be as non-technical as possible. Average user doesn't know the difference between Internet, browser and search engine (← this video is painful to watch).

A: You can recommend things to people until you're blue in the face, but the reason people who don't instinctively upgrade their browser actually get around to doing it will always be the same. They do it because there's something they want to use, but can't unless they upgrade.
Want people to quit using an old browser ?
Quit supporting it.
It's that simple.

A: If no one supported them anymore then you wouldn't have to write code for them.  For a certain percentage of people, they upgrade through necessity, not out of choice.  If IE6 keeps working then they will keep using.  Dont make the extra effort to support IE6.

A: From a psychological point of view, users will upgrade software due to one of the following reasons:
 - Need (they have to have feature)
 - Benefit (they'd like to have a feature)
 - Fear (they perceive some sort of damage if they don't have a feature)
Based on how well you know your users, you can use one of these approaches to motivate them to upgrade. I.e., Provide extra functionality in your software that works only in new browsers (suggestion: use Ajax for better page update, without the need to call another page or refresh the current). Make those users aware that new, better, safer functionality is available, if they just upgrade their browser.
But remember the following caveats:

*

*Not everyone can upgrade on his own. OS and browser versions are often dictated by IT policies in medium-large organizations.

*Not everyone is tech-savvy enough to upgrade - you may need to explain the process.

*If the user can dictate behavior, he may require you to provide the shiny new functionality in the old browser - be careful how you present those benefits!

A: The type of people who haven't yet upgraded their browser will almost certainly be people who don't have the technical knowledge to do so; those users who do know what a browser is, does and how to upgrade (and the benefits of upgrading) will most probably have done so. From this you can see how important it is to explain clearly and concisely both the benefits of upgrading and precisely how to do so for those who aren't technically minded.


text:
Q: SQL aliasing to redirect traffic between databases on the same server In order to upgrade a database with no client disconnects, I clone an existing database and put it in a readonly mode. Now, I want all user traffic to be redirected from the original database to the cloned one (both are on the same server). I want to do it with SQL aliases. However, I see that aliasing is possible for server instances and protocols. Is there another way to go about database redirects on the same server?

A: Aliases are only for server/instances of SQL Server, not for databases.
In your case I'd create a database snapshot of the current database (so there's no need for a new read-only copy of your db), redirect all user connections there, do you update, then drop the snapshot. Please take into consideration that a snapshot can take a lot of space if forgotten there, not dropped on time.

A: Not sure if thats something easily achieved in this way. Youll probably want something similar to transactional replication / failover. Not sure how your structure has altered though. If the structure isnt changing, I would run with this solution so that you can take down the original and everything will simply divert.


text:
Q: Sort all the cases of specific variable in descending order but other will remain same using SPSS Syntax I have two variables (id and Var1) in SPSS as below. I want to sort Var1 as descending order but other variables do not change accordingly with Var1. i.e. other variable will remain same as before sort.
My data is...
id  Var1
--  ----
M-1   3
M-2   4
M-3   2
M-4   7

But I want like this..
id  Var1
--  ----
M-1   7
M-2   4
M-3   3
M-4   2

My Syntax/code is...
data list list
 /id(A3) Var1(F2.0).
begin data.
M-1   3
M-2   4
M-3   2
M-4   7
end data.

sort cases by BY Var1(D).
execute.

When I run this code it also sort id according to Var1. But I do not want to expand this sort command for entire variables. I only want to sort for current selection variable in SPSS.
Can anyone help using SPSS Syntax?

A: You Could split the dataset sort the Var1 variable and then merge them together. One way to do so would be this:
* create data.
data list list
 /id(A3) Var1(F2.0).
begin data.
M-1   3
M-2   4
M-3   2
M-4   7
end data.

DATASET NAME ids.
DATASET COPY sortvar.

* Delete sort variable (Var1) from dataset "ids".
DELETE VARIABLES Var1.

* Keep only sort variable in dataset "sortvars".
DATASET ACTIVATE sortvar.
DELETE VARIABLES id.

* sort Var1.
SORT CASES BY Var1(D).

* Merge datasets.
MATCH FILES
/FILE ids
/FILE sortvar.
EXECUTE.

If you have lots of variables to delete in the sortvar dataset you could also use the MATCH CASES command:
* Delete all variables but Var1.
DATASET ACTIVATE sortvar.
MATCH CASES
/FILE *
/KEEP Var1.

Alternativly you can use the SAVE command in combination with the KEEP or DROP options in order to split the dataset.


text:
Q: How to package React front end with Spring Boot and run the executable jar? I have a Java Spring Boot back end app containing REST services.  Just inside the main Spring Boot project folder I have a React app for the front end.  I can run the Spring Boot app and successfully access all the end points.  I can run the React app and it works too.  But now I want to create an executable jar file and run that as a single application, not two.
I create an executable fat jar file like this:
mvn clean install

It creates a jar file.  When I run it with
java -jar target/medaverter-0.0.1-SNAPSHOT.jar

the back end starts up ok but the front end does not pop up in a browser window like it does if I run it separately with
npm start

I've followed these tutorials to get where I'm at. Apparently I'm missing something.
https://medium.com/@mukundmadhav/build-and-deploy-react-app-with-spring-boot-and-mysql-6f888eb0c600#37fa
https://blogg.kantega.no/webapp-with-create-react-app-and-spring-boot/
Here is the pom.xml file.  The plugins section does the magic of merging in the React app:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>net.tekknow</groupId>
    <artifactId>medaverter</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>medaverter</name>
    <description>Demo project for Spring Security</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.1</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20190722</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.6</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
               <groupId>com.github.eirslett</groupId>
               <artifactId>frontend-maven-plugin</artifactId>
               <version>1.6</version>
               <configuration>
                   <workingDirectory>medaverter-front</workingDirectory>
                   <installDirectory>target</installDirectory>
               </configuration>
               <executions>
                   <execution>
                       <id>install node and npm</id>
                       <goals>
                           <goal>install-node-and-npm</goal>
                       </goals>
                       <configuration>
                           <nodeVersion>v8.9.4</nodeVersion>
                           <npmVersion>5.6.0</npmVersion>
                       </configuration>
                   </execution>
                   <execution>
                       <id>npm install</id>
                       <goals>
                           <goal>npm</goal>
                       </goals>
                       <configuration>
                           <arguments>install</arguments>
                       </configuration>
                   </execution>
                   <execution>
                       <id>npm run build</id>
                       <goals>
                           <goal>npm</goal>
                       </goals>
                       <configuration>
                           <arguments>run build</arguments>
                       </configuration>
                   </execution>
               </executions>
            </plugin>
            <plugin>
                <artifactId>maven-antrun-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>generate-resources</phase>
                        <configuration>
                            <target>
                                <copy todir="${project.build.directory}/classes/public">
                                    <fileset dir="${project.basedir}/medaverter-front/build"/>
                                </copy>
                            </target>
                        </configuration>
                        <goals>
                            <goal>run</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
        <pluginManagement>
            <plugins>
                <!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.-->
                <plugin>
                    <groupId>org.eclipse.m2e</groupId>
                    <artifactId>lifecycle-mapping</artifactId>
                    <version>1.0.0</version>
                    <configuration>
                        <lifecycleMappingMetadata>
                            <pluginExecutions>
                                <pluginExecution>
                                    <pluginExecutionFilter>
                                        <groupId>
                                            org.apache.maven.plugins
                                        </groupId>
                                        <artifactId>
                                            maven-antrun-plugin
                                        </artifactId>
                                        <versionRange>
                                            [1.8,)
                                        </versionRange>
                                        <goals>
                                            <goal>run</goal>
                                        </goals>
                                    </pluginExecutionFilter>
                                    <action>
                                        <ignore></ignore>
                                    </action>
                                </pluginExecution>
                            </pluginExecutions>
                        </lifecycleMappingMetadata>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

I have verified that the same files that are in the react folder, called medaverter-front, get copied over to the target/classes/public folder.
I have the following proxy set in my package.json file:
  "proxy": {
    "/api": {
      "target": "http://localhost:8080",
      "ws": true
    }
  },

If I enter into a browser:
http://localhost:8080/api/test/all
I see in the browser:
"Public Content"
as I should if I were accessing the back end directly, but the terminal shows:

n.t.m.security.jwt.AuthEntryPointJwt     : Unauthorized error: Full
  authentication is required to access this resource

If I enter into the browser:
http://localhost:8080/home
it returns "There was an unexpected error (type=Unauthorized, status=401)."
Clearly Spring Security JWT is interfering somehow but I just can't figure it out.  The home page does not require any authentication, yet something is acting like it does.  Here is the backend tree:

I should also mention that during app startup, I see several of these Exceptions:

java.sql.SQLNonTransientConnectionException: Public Key Retrieval is
  not allowed

But that doesn't stop it from running.  I solved that problem by adding "&allowPublicKeyRetrieval=true" to the spring.datasource.url in application.properties file.

A: I finally found the problem.  I added
    .antMatchers("/home/**").permitAll()
    .antMatchers("/**").permitAll()

to the configure method in the WebSecurityConfig.java file.  It now looks like this:
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors().and().csrf().disable()
        .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
        .authorizeRequests().antMatchers("/api/auth/**").permitAll()
        .antMatchers("/api/test/**").permitAll()
        .antMatchers("/home/**").permitAll()
        .antMatchers("/**").permitAll()
        .anyRequest().authenticated();

    http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}

I was confused about this method (and still am).  I had thought that if /api/test/all was handled, that was all I needed.  Apparently not.  Why did I think that?  The React flow starts at App.js which contains
      <Route exact path={["/", "/home"]} component={Home} />

home.component.js contains:
  componentDidMount() {
    UserService.getPublicContent().then(
      response => {
        this.setState({
          content: response.data
        });
      },

user.service.js contains:
const API_URL = 'http://localhost:8080/api/test/';

class UserService {
  getPublicContent() {
    return axios.get(API_URL + 'all');
  }

The SpringBoot TestController.java handles the backend calls:
@RequestMapping("/api/test")
public class TestController {
    @GetMapping("/all")
    public String allAccess() {
        return "Public Content.";
    }

Hence, / or /home ultimately calls http://localhost:8080/api/test/all which returns "Public Content".


text:
Q: Why can't the link file be found after sdk is pulled down from the server The server compilation can pass, but when I download the sdk from the server and compile it in the local environment, the following error is reported:
make[1]: leave directory "/home/lx/gk7202v300refv100r001c00spc030_cam/sdk/source/kernel/liteos/platform/bsp"
make[1]: Enter the directory "/home/lx/gk7202v300refv100r001c00spc030_cam/sdk/source/kernel/liteos/platform/bsp/common"
make[1]: do nothing for "all".
make[1]: leave directory "/home/lx/gk7202v300refv100r001c00spc030_cam/sdk/source/kernel/liteos/platform/bsp/common"
arm-gkmix100-linux-ld: cannot find /home/lx/gk7202v300refv100r001c00spc030_cam/sdk/source/kernel/liteos/liteos_tmp/wow_objs/*.o: No such file or directory
Makefile:63: recipe for target 'vs_server' failed
make: *** [vs_server] Error 1

This is my current build directory and Makefile:

/home/lx/gk7202v300refv100r001c00spc030_cam/sdk/source/kernel/liteos

LITEOSTOPDIR := $(shell if [ "$$PWD" != "" ]; then echo $$PWD; else pwd; fi)
export OS=$(shell uname -s)
ifneq ($(OS), Linux)
LITEOSTOPDIR := $(shell dirname $(subst \,/,$(LITEOSTOPDIR))/./)
endif

export LITEOSTOPDIR

-include $(LITEOSTOPDIR)/config.mk

RM = rm -rf
MAKE = make
__LIBS = libs

LITEOS_TARGET = vs_server
LITEOS_LIBS_TARGET = libs_target

all: $(OUT) $(BUILD) $(LITEOS_TARGET)
lib: $(OUT) $(BUILD) $(LITEOS_LIBS_TARGET)

##### make wow && make scatter && make wow_scatter #####
-include $(LITEOS_MK_PATH)/wow_scatter.mk

##### make dynload #####
-include $(LITEOS_MK_PATH)/dynload.mk

#-----need move when make version-----#
##### make lib #####
$(__LIBS): $(OUT) $(CXX_INCLUDE)

$(OUT): $(LITEOS_MENUCONFIG_H)
    $(HIDE)mkdir -p $(OUT)/lib
    $(HIDE)$(CC) -E $(LITEOSTOPDIR)/platform/bsp/board/$(LITEOS_PLATFORM)/board.ld.S -o $(LITEOSTOPDIR)/platform/bsp/board/$(LITEOS_PLATFORM)/board.ld -P

$(BUILD):
    $(HIDE)mkdir -p $(BUILD)

$(LITEOS_LIBS_TARGET): $(__LIBS)
    $(HIDE)for dir in $(LIB_SUBDIRS); \
        do $(MAKE) -C $$dir all || exit 1; \
    done
    $(HIDE)echo "=============== make lib done  ==============="

##### make menuconfig #####
menuconfig:
    make -C tools/menuconfig menuconfig
    $(HIDE)if [ -s $(LITEOS_MENUCONFIG_H) ]; \
    then \
        mv -f $(LITEOS_MENUCONFIG_H) $(LITEOS_PLATFORM_MENUCONFIG_H); \
    fi

savemenuconfig:
    make -C tools/menuconfig savemenuconfig
    -mv -f $(LITEOS_MENUCONFIG_H) $(LITEOS_PLATFORM_MENUCONFIG_H)
##### make #####

$(LITEOS_MENUCONFIG_H):
ifneq ($(LITEOS_PLATFORM_MENUCONFIG_H), $(wildcard $(LITEOS_PLATFORM_MENUCONFIG_H)))
    $(HIDE)+make savemenuconfig
endif
$(LITEOS_TARGET): $(__LIBS)
    $(HIDE)touch $(LOSCFG_ENTRY_SRC)

ifeq ($(LOSCFG_PLATFORM_OSAPPINIT), y)
ifeq ($(LOSCFG_KERNEL_RUNSTOP)$(LOSCFG_KERNEL_SCATTER), yy)
    $(HIDE)+make wow_scatter
else ifeq ($(LOSCFG_KERNEL_RUNSTOP), y)
    $(HIDE)+make wow
else ifeq ($(LOSCFG_KERNEL_SCATTER), y)
    $(HIDE)+make scatter
endif
endif

    $(HIDE)for dir in $(LITEOS_SUBDIRS); \
    do $(MAKE) -C $$dir all || exit 1; \
    done

ifeq ($(LOSCFG_PLATFORM_OSAPPINIT), y)
ifeq ($(LOSCFG_KERNEL_RUNSTOP)$(LOSCFG_KERNEL_SCATTER), yy)
    $(HIDE)$(SCRIPTS_PATH)/scatter_sr/scatter.sh $(CROSS_COMPILE) y y $(SCRIPTS_PATH)/scatter_sr $(SCRIPTS_PATH)/ld $(LITEOSTOPDIR)/liteos_tmp $(LIB_BIGODIR)
else ifeq ($(LOSCFG_KERNEL_RUNSTOP), y)
    $(HIDE)$(SCRIPTS_PATH)/scatter_sr/scatter.sh $(CROSS_COMPILE) y n $(SCRIPTS_PATH)/scatter_sr $(SCRIPTS_PATH)/ld $(LITEOSTOPDIR)/liteos_tmp $(LIB_BIGODIR)
else ifeq ($(LOSCFG_KERNEL_SCATTER), y)
    $(HIDE)$(SCRIPTS_PATH)/scatter_sr/scatter.sh $(CROSS_COMPILE) n y $(SCRIPTS_PATH)/scatter_sr $(SCRIPTS_PATH)/ld $(LITEOSTOPDIR)/liteos_tmp $(LIB_BIGODIR)
else
    $(HIDE)$(SCRIPTS_PATH)/scatter_sr/clear_ld.sh $(SCRIPTS_PATH)/ld
endif
else
    $(HIDE)$(SCRIPTS_PATH)/scatter_sr/clear_ld.sh $(SCRIPTS_PATH)/ld
endif

    $(LD) $(LITEOS_LDFLAGS) $(LITEOS_TABLES_LDFLAGS) $(LITEOS_DYNLDFLAGS) -Map=$(OUT)/$@.map -o $(OUT)/$@ --start-group $(LITEOS_LIBDEP) --end-group
    $(SIZE) -t --common $(OUT)/lib/*.a >$(OUT)/$@.objsize
    $(OBJCOPY) -O binary $(OUT)/$@ $(OUT)/$@.bin
    $(OBJDUMP) -t $(OUT)/$@ |sort >$(OUT)/$@.sym.sorted
    $(OBJDUMP) -Mreg-names-raw -d $(OUT)/$@ |$(LITEOSTOPDIR)/tools/stackusage/stackusage |sort -n -k 1 -r >$(OUT)/$@.stack
    $(OBJDUMP) -d $(OUT)/$@ >$(OUT)/$@.asm
    $(NM) -S --size-sort $(OUT)/$@ >$(OUT)/$@.size

ifeq ($(LOSCFG_KERNEL_SCATTER), y)
    $(HIDE)$(SCRIPTS_PATH)/scatter_sr/scatter_size.sh $(OUT)/$(LITEOS_TARGET)
endif

clean:
    $(HIDE)for dir in $(LITEOS_SUBDIRS); \
        do make -C $$dir clean|| exit 1; \
    done
    $(HIDE)make -C tools/menuconfig distclean
    $(HIDE)make wow_scatter_clean
    $(HIDE)$(RM) $(__OBJS) $(LITEOS_TARGET) $(OUT) $(BUILD) $(LITEOS_MENUCONFIG_H) *.bak *~
    $(HIDE)$(SCRIPTS_PATH)/scatter_sr/clear_ld.sh $(SCRIPTS_PATH)/ld
    $(HIDE)echo "clean $(LITEOS_PLATFORM) finish"

cleanall:
    $(HIDE)rm -rf $(LITEOSTOPDIR)/out
    $(HIDE)find platform/bsp/board/ -name board.ld -exec rm -rf {} \;
    $(HIDE)cd sample/sample_osdrv;make clean;cd ../..;
    $(HIDE)echo "clean all"
    $(HIDE)make wow_scatter_clean

.PHONY: all lib clean cleanall $(LITEOS_TARGET)

and can't find config.mk in the next level Makefile
~/gk7202v300refv100r001c00spc030_cam/sdk/source/kernel/liteos/platform/bsp$ ls
board bsp.mk common hwi Makefile mmu net random timer uart usb
lx@lx-virtual-
~/gk7202v300refv100r001c00spc030_cam/sdk/source/kernel/liteos/platform/bsp$ make
Makefile:1: /config.mk: No such file or directory
make: *** No rules to make target '/config.mk'. stop.
make target "" failed !!!

trouble

This problem has been bothering me for a long time, and I can't locate the specific location and >ask for your help. grateful!