text:
Q: How can I import a 3d model/mesh with python want to do some 3d model processing using Python.
I was told 3d models are made up of 4d matrices. Is it possible to import a 3d model from meshlab or blender or some other software and convert it into a matrix or something of the sort so I could do some processing?

A: Yes it is possible. You need the plyfile library. Since it's Meshlab, I am assuming the file format that you're trying to import is .ply. Use the code below.
from plyfile import PlyData

data = PlyData.read('my_data.ply')

A: While you can use a 4D matrix to apply multiple transformations in one step, for the most part I would say it is more common to access each property either as an array of three or four values or to directly access each element.
import bpy
obj = bpy.context.active_object
obj.location.x += 1.0
obj.location.y -= 0.2
obj.location.z += 0.8
obj.rotation_euler = (radians(45.0),radians(15.8), radians(0.0))

Blender includes a full python interpreter, so you should be able to do most of what you want using blender without having to export any data.
If you want to try blender, you can get more blender specific help at blender.stackexchange.


text: Q: User manager error while HWIOAuthBundel Integartion with FOSUSerBundle Could not find the manager name parameter in the container. Tried the following parameter names: "fos_user.model_manager_name", "doctrine.default_entity_manager".

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to fix navbar and sidebar to stick together when scrolling down, HTML & CSS I am having a problem whenever I scroll my page or content, the Sidebar is being scrolled down as well which leaves the navbar at the top and produce a gap in between. Here is the picture of the problem.
How to fix this UI problem. As you can see there's a gap in between, and if I scroll it down, the gap becomes larger.

.sidebar {
  margin: 0;
  padding: 0;
  width: 200px;
  background-color: #f1f1f1;
  position: fixed;
  height: 100%;
  overflow: auto;
}

.sidebar a {
  display: block;
  color: black;
  padding: 16px;
  text-decoration: none;
}

.sidebar a.active {
  background-color: #04AA6D;
  color: white;
}

.sidebar a:hover:not(.active) {
  background-color: #555;
  color: white;
}

div.content {
  margin-left: 200px;
  padding: 1px 16px;
  height: 1000px;
}

@media screen and (max-width: 700px) {
  .sidebar {
    width: 100%;
    height: auto;
    position: relative;
  }
  .sidebar a {float: left;}
  div.content {margin-left: 0;}
}

@media screen and (max-width: 400px) {
  .sidebar a {
    text-align: center;
    float: none;
  }
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

  App
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">

  </button>

        Home

        About

            Login

            Register

 <a class="active" href="<?php echo base_url(); ?>">Dashboard

  <a class="" href="<?php echo base_url(); ?>">Bookes
   <a class="" href="<?php echo base_url(); ?>">Clothes
    <a class="" href="<?php echo base_url(); ?>">Electronics

A:

body {margin:0;}

/*Sidebar*/

.sidebar {
  margin: 0;
  padding: 0;
  width: 200px;
  background-color: #f1f1f1;
  position: fixed;
  top:80px;
  height: 100%;
  overflow: auto;
}

/*Navbar*/

.navbar {
position:fixed;
top:0;
left:0;
height:80px;
width:100%;
background:red;
}

/*Main content*/
main {margin-top:120px; margin-left:240px;}

  App

text text text

text text text

text text text

text text text

text text text

text text text

text text text

text text text

text text text

text text text

text text text

text text text

text text text

text text text

text text text

text text text

 <a class="active" href="<?php echo base_url(); ?>">Dashboard
1
2
3
4

Both your navbar and sidebar need to be position: fixed. That way they wont be affected by the scroll.

A: I know its bit late, but still to help community.
Code:

     <a class="active" href="<?php echo base_url(); ?>">Dashboard

     <a class="" href="<?php echo base_url(); ?>">Bookes
       .
       .

CSS:
.left-sidebar {
    position: relative;
    width: 240px;
    height: 100%;
    background-color: $darkBlue;
    background: linear-gradient(180deg, #0072C0 15%, $darkBlue 100%);
    box-shadow: 1px 0px 20px rgba(0, 0, 0, 0.08);
}
.divider{
     display: block;
     border-bottom: 1px solid rgba(255,255,255,0.10);
     width: 170px;
     margin: 0 auto;
   }

A: <!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

  App
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">

  </button>

        Home

        About

            Login

            Register

 <a class="active" href="<?php echo base_url(); ?>">Dashboard

  <a class="" href="<?php echo base_url(); ?>">Bookes
   <a class="" href="<?php echo base_url(); ?>">Clothes
    <a class="" href="<?php echo base_url(); ?>">Electronics


text:
Q: Programmatically set Registry Software Policy key for all Users I need to set the following registry key for all standard user accounts. However, standard users don't have access to this location. How can I set this key programmatically, as an administer and have it available to all users when they login?
I've tried Registry Active Setup via calling reg add. However, this did not work because Active Setup runs with user permissions (I guess) which cannot set that key!
Registry key:
HKEY_CURRENT_USER\SOFTWARE\Policies\Microsoft\Office\14.0\Common\Security\Trusted Protocols\All Applications\Custom:

A: This key
HKEY_CURRENT_USER\SOFTWARE\Policies\Microsoft\Office\14.0\Common\Security\Trusted Protocols\All Applications\Custom:

Is Actually
HKEY_USERS\ Security ID (SID)\SOFTWARE\Policies\Microsoft\Office\14.0\Common\Security\Trusted Protocols\All Applications\Custom:

You could query all users in HKEY_USERS and set this key for every one. The problem here would be that this key will not be set for new users.


text:
Q: Unable to unit test a @KafkaListener annotated method I'm trying to unit test a kafka consumer class, in Spring. I want to know that if a kafka message is sent to it's topic, the listener method was called correctly. My consumer class is annotated like this:
@KafkaListener(topics = "${kafka.topics.myTopic}")
public void myKafkaMessageEvent(final String message) { ...

If I @Autowire a consumer, when I send a kafka message, the listener method is called correctly, but I can't assert that the method was called because the class isn't a mock.
If I mock a consumer, when I send a kafka message the listener method is not called at all. I can call the method directly, and assert that it worked, but that doesn't do what I want, which is to check if the method is called when I send a kafka message to it's topic.
For now I have resorted to put a counter inside the consumer, and increment it every time the listener method is called, then check that it's value has been changed. Making a variable just for testing seems like a terrible solution to me.
Is there maybe a way to make the mocked consumer receive the kafka messages too? Or some other way to assert that the non-mocked consumer listener method was called?

A: Sounds like you are requesting something similar what we have in Spring AMQP Testing Framework: https://docs.spring.io/spring-amqp/docs/2.0.3.RELEASE/reference/html/_reference.html#test-harness
So, if you are not good with extra variable you can borrow that solution and implement your own "harness".
I think that should be a good addition to the Framework so, please, raise an appropriate issue and we can together bring such a tool for the public.
UPDATE
So, according Spring AMQP foundation I did this in my test configuration:
public static class KafkaListenerTestHarness extends KafkaListenerAnnotationBeanPostProcessor {

    private final Map<String, Object> listeners = new HashMap<>();

    @Override
    protected void processListener(MethodKafkaListenerEndpoint endpoint, KafkaListener kafkaListener,
            Object bean, Object adminTarget, String beanName) {

        bean = Mockito.spy(bean);

        this.listeners.put(kafkaListener.id(), bean);

        super.processListener(endpoint, kafkaListener, bean, adminTarget, beanName);
    }

    @SuppressWarnings("unchecked")
    public <T> T getSpy(String id) {
        return (T) this.listeners.get(id);
    }

}

...

@SuppressWarnings("rawtypes")
@Bean(name = KafkaListenerConfigUtils.KAFKA_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME)
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public static KafkaListenerTestHarness kafkaListenerAnnotationBeanPostProcessor() {
    return new KafkaListenerTestHarness();
}

Then in the target test-case I use it like this:
@Autowired
private KafkaListenerTestHarness harness;
...
Listener listener = this.harness.getSpy("foo");

verify(listener, times(2)).listen1("foo");

A: Please note that the bean that will be exercised in the spring context refresh can not be mocked. If you want to mock this bean like kafkaListener, just use the @SpyBean annotation.  You can find more in this github issue of the spring boot. https://github.com/spring-projects/spring-boot/issues/16324


text:
Q: create an DNS MX Record I'm traying to create an MX record using GCP CloudDNS. I created a A record pointing to my server IP. And I wanted to creat an MX record as following:
A mail.mydomain.fake
MX @mydomain.fake mail.mydomain.fake
While creating the MX record I get the following error:
Invalid value for entity.change.additions[0].rrdata[0]
Below some screen shots:
A record:

The MX Record:

A: The issue was I miss adding priority! just put a leading number and worked.
I'm new on DNS thingy that's why I'm doing it.


text:
Q: Is the set of continuous mappings with prescribed boundary correspondence convex? Let $X \subset \mathbb{R}^n$ and $Y \in \mathbb{R}^n$ be two simply-connected bounded domains. Given a homeomorphic boundary correspondence $g: \partial X \rightarrow \partial Y$, let $F: X \rightarrow Y$ and $G: X \rightarrow Y$ be two continuous maps with a nondegenerate differential in $X$ such that $F \vert_{\partial X} = G \vert_{\partial X} = g$.
My question is, does this imply that the function $H_t: X \rightarrow \mathbb{R}^n$ with $H_t(x) \equiv (1 - t) F(x) + t G(x)$ has a nondegenerate differential for all $(x,t) \in X \times [0, 1]$ ?

A: No. $H_t$ need not have a nondegenerate differential; it need not even map into $Y$. As an example, let $X$ and $Y$ both be the closed unit disk in $D^2\subset\mathbb{R}^2$, let $g$ and $F$ be the idintity, and let $G(\vec{x})=R(\pi(1-\|\vec{x}\|^2))\vec{x}$, where $R(\theta)$ is a rotation by an angle $\theta$.
If you require that $X$ and $Y$ be convex, and drop the requirement that the maps have nondegenerate differential, then the space of such mappings will be convex.


text:
Q: Tea bag disposal plate name What is a little plate used for disposal of a tea bag called?
I find myself in a real conundrum here. Tea drinker problems.
Typical scenario: I order a cup of tea at a diner. I'm given a cup of hot water and a teabag. Said teabag is steeped for a few minutes until the tea is just how I like it: not too thin, but not too thick.
Now, said teabag must be removed, or the tea will be too strong! A small plate or saucer is immediately needed for disposal.
Establishments are often hesitant to give out these little plates, because it adds a lot of dishwashing/waste for something they seem to think is a luxury item. So, I'm left "holding the bag" as they say... and, sadly, nowhere to put it.
I must then resort to barbaric acts, such as placing the used bag:

*

*Directly on the counter, where it leaks all over.

*On my paper placemat, where it makes a big wet spot.

*On my teaspoon, which is just rude.

*Wrapping it in a napkin, which promptly turns into a soppy brown mess

*Using the paper tea bag wrapper for disposal, which really doesn't work very well.

*Into an empty water glass, which is obscene.

*Rock-bottom has to be eating a single-serve jelly, directly out of the packet with my teaspoon, and putting the used bag into the little empty plastic container.

Don't even think about putting that nasty teabag on the side of my food plate.
So I need to ask, "May I please have a little plate for my used teabag?
English SE, please tell me, what is the name of this little saucer thingy?
https://forum.thefreedictionary.com/postst39438_specific-name-for-a-tea-bag-disposal-plate.aspx

A:
[Lakeland White Porcelain] Tea Bag Rest  "Where do you put your tea
bag after you've fished it out of your mug, or taken it out of your
teapot so your brew doesn't stew? On our pretty little White Porcelain
Tea Bag Rest, of course".

Brought to you straight from the UK. [ha ha]

Also, for spoons and other utensils when cooking:
Here is a spoon rest (which I am going to buy as the one I had for 30 years broke)  from William Sonoma:

A: Amazon has the following that meet your requirements; and perhaps more that I haven't yet seen.
Tea Bag ...

*

*Dish

*Tidy

*Coaster

*Holder

*Rest

A: As has been pointed out by FumbleFingers, in a comment, some merchants who sell such things refer to them as teabag holders.
While that term is adequate in the context of a website on which it is accompanied by pictures and descriptions, it is debatable whether it would be readily understood to have this meaning in the absence of such clues; upon encountering it in isolation, some people could think that it stands for something that holds teabags before use.

A: Small Sauce Plate.
If you look up 'small sauce plate' or 'small dipping plate' online, and click 'images', you'll see lots of these kinds of tiny dishes, so I think if you ask for one of those, the waiter will understand what you mean:
https://www.amazon.com/small-dipping-plates/s?k=small+dipping+plates
I don't think there is really a name for that small-plate thingy as a specific 'tea-bag plate' per se.  Instead of asking 'may I have a small plate for my tea-bag, please' which as you say, is quite annoying, I suggest you ask for 'a small sauce plate'.
An Alternate Answer.
Teapot.
A teapot is really the correct place for the teabag. How about ordering tea by the pot?
The teabag stays in the pot - and you can request extra hot water to top up, giving you even more tea, for free!
I'm English, and a lover of tea, the teapot avoids the inelegance of this 'tea-bag problem'.
I get your little plate idea, though as I say, tea is better in a pot - however I do have a tiny, shell-shaped, white porcelain plate, only about 4-5 cm across, and quite flat. Could something like that fit in your bag? Then at the end, the used tea-bag goes in the tea-cup and the shell plate is dried with a tissue and goes back in your bag. It is really, a small sauce plate. And that's what we use it for, in my cafe.
Tea-time, for English people is a peaceful little moment around the tea-pot, where we can connect with another and share what's really important to us. So that's another lovely thing about the tea-pot - to share your tea-time with a friend!


text:
Q: ElasticSearch: Facets from child documents I have two documents in parent - child relationship and I want to get the number and also the max value of a date field from the children documents grouped by the value of the parent id. In other words, for every parent document I want to count its children and get its latest child. In addition, it would be great if the date field would have the same format and not be returned as a timestamp value.
I already tried more facets, but nothing seems to return the desired answer. Could anyone provide some insights about how to achieve this? Is it possible? Thank you in advance.

A: Seems like you should look and play around with http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-facets-terms-stats-facet.html
value field will be date
key field will be _parent
I suppose, it should return max, min, count, etc. (read docs) for each _parent, but you must play with it


text:
Q: Request Parameters validations in vertx 4.0.3 I was using vertx-Web-api-contracts in vertx 3.0 to validate my query parameters and form parameters using
HTTPRequestValidationHandler and ParameterTypeValidator
code sample :
private final ParameterTypeValidator fileIdValueValidator = new IdTypeValidator().create();
private final ParameterTypeValidator tokenTypeValidator = new TokenTypeValidator().create();

private HTTPRequestValidationHandler getDeleteRequestValidations() {
    final HTTPRequestValidationHandler validator = HTTPRequestValidationHandler.create()
        .addQueryParamWithCustomTypeValidator(PARAM__ID, IdValueValidator, true, false)
        .addHeaderParamWithCustomTypeValidator(HEADER_TOKEN, tokenTypeValidator, true, false);
    return validator;
}

Here I am using ParameterTypeValidator to provide custom logic to validate my parameters value. I am using customTypeValidator, because I need custom value validation for parameter value
for ex. I need to validate my ID Parameter should contain four parts separated by _ ( part1_part2_part3_part4 )
Now while I am trying to migrate to vertx 4.0 and vertx-Web-api-contracts is deprecated, I am forced to use vertx-web-validation, but web-validation lacks custompropertyvalidation like api-contract-validations.
How I am trying to do,
private ValidationHandler getDeleteRequestValidations(final SchemaParser parser) {
    ValidationHandler validationHandler=ValidationHandler.builder(parser)
      .queryParameter(Parameters.param(PARAM__ID, stringSchema()))
      .headerParameter(Parameters.param(HEADER_TOKEN,stringSchema()))
      .build();
    return validationHandler;
  }

But I want to know how to pass/build a custom schema instead of stringSchema() or intSchema() to validate with custom logic. Earlier I was creating Custom classes and implements ParameterTypeValidator to provide custom validation logic(like IdTypeValidator()).
Is there any way to achieve same with web-validation.

A: Not really familiar with the new validation mechanism, but will try to help you using some facts.
The new validation uses Json Schema, so you should first go for understanding that one: https://vertx.io/docs/vertx-json-schema/java/
Then, examining the Parameters.param() signature, the second parameter is just an instance of the io.vertx.json.schema.common.dsl.SchemaBuilder which is then described how to be built in this part of the docs:
https://vertx.io/docs/vertx-json-schema/java/#_building_your_schemas_from_code
I hope this will give you a direction on how to solve your problem.


text:
Q: Webpage opening as https and geting error message I have multiple webpages, the main page is index.html, and I have several others, page2.html, page3.html etc as an example.. However one of my other pages, say page2.html, when it comes up on google search, attempts to open up as https instead of http, causing an error. It is just an informational page so it does not require https or an ssl certificate.
How do I set it so that from the google search the page only attempts to open as http?
My main index.html page, from google search, opens as http as it should, and the other pages to my knowledge are configured the same?
Thanks!

A:
It is just an informational page so it does not require https or an ssl certificate.

Is just wrong.
Without https you can't guaranty integrity, witch mean that ISP, wifi hot-spot and others can (and do) manipulate you page to add tracking-cookies, ads or anything else.
It's mean you don't have confidentiality either, which your visitors could expect.

How do I set it so that from the google search the page only attempts to open as http?

https://support.google.com/webmasters/answer/139066 can help you.


text:
Q: is there a utility to automatically find 64bit versions of installed 32bit software? I migrated from Vista 32bit to Windows 7 64bit and moved my apps with PCmover. I have also upgraded Eclipse to the 64bit version.
Is there a utility (like AppSnap) that will automatically find 64bit versions of my 32bit apps?
I have gotten 3 useless off-topic answers at LinkedIn

A: Unfortunately there isn't due to the reason that you can just go to the Software Vendor's website to see if they have a 64 bit application for download, if not then you'll need to stick with the 32 bit version.
There are at times where I can get picky and want to utilize the use for my 64 bit os but like you just have to live with the 32 bit mode for some programs.
Mainly programs that get constantly updated usually have 64 bit support, but it's up to the software vendor if they wish to compile it for the 64 bit OS.


text:
Q: React semantic ui table.row set row active onclick How can i set a row with prop active={true} on click Table.Row React semantic UI
Sounds simple but I didn't find a way to do it.
in the documentation I found nothing talking about.
I tried that way, but not worked,
      selectRow(key){
         let rowStatus = this.state.rowStatus[];
         for(let i in rowStatus){
           rowStatus[i] = false;
         }

         rowStatus[key] = true;
         this.setState({rowStatus:rowStatus});

      }

      renderRowTable(data){
        let row = [];
        let rowStatus = [];

        for(let i in data){

          rowStatus.push(false);

          row.push(

{this.selectRow(i)}}>

{data[i].code}

{data[i].date}

          );
        }

        this.setState({
          row:row,
          rowStatus:rowStatus
        });

      }

  render() {

    return (

Code

Date

{this.state.row}

    )
  }

A: You can keep the activeRowId in the state, and change its value on the row onClick. And while looping the rows, you can set the active property to true if the item's id is equal to activeRowId.
I heavily refactored your code like this:
import React, { Component } from "react";
import { Table } from "semantic-ui-react";

class App extends Component {
  state = {
    data: [
      { id: 1, code: "code1", date: "date1" },
      { id: 2, code: "code2", date: "date2" },
      { id: 3, code: "code3", date: "date3" }
    ],
    activeRowId: null
  };

  setActiveRow(id) {
    this.setState({
      activeRowId: id
    });
  }

  renderRowTable() {
    let rows = this.state.data.map(item => {
      return (

 {
            this.setActiveRow(item.id);
          }}
        >

{item.code}

{item.date}

      );
    });

    return rows;
  }

  render() {
    return (

Code

Date

{this.renderRowTable()}

    );
  }
}

export default App;

Codesandbox


text:
Q: Error: Text content does not match server-rendered HTML using Context in NextJS This seems to be a fairly common question but the others seem to deal only with useState.
I have a simple shopping cart system using Context and useReducer. I've added the functionality to store the cart in cookies (with js-cookie) so the cart persists after refresh. However, when I refresh the page, the classic Error: Text content does not match server-rendered HTML. is triggered.
Getting initial state:
const initialState = {
  darkMode: false,
  cart: {
    cartItems: Cookies.get("cartItems")
      ? JSON.parse(Cookies.get("cartItems"))
      : [],
  },
};

Adding to cookies:
case "CART_ADD_ITEM": {
      const newItem = action.payload;
      const cartItems = [...state.cart.cartItems, newItem];
      Cookies.set("cartItems", JSON.stringify(cartItems));
      return { ...state, cart: { ...state.cart, cartItems } };
    }

Displaying the cart size in a simple tag for now:
<nav className="w-full h-12 bg-gray-100">
        Navbar | {cart.cartItems.length > 0 ? cart.cartItems.length : 0}
      </nav>

Solutions seem to revolve around using useEffect but I'm not sure how to implement that here. Any help appreciated.

A: Fixed it with useEffect - assigned the stored value to state variable and then checked it with useEffect
const [cartSize, setCartsize] = useState(0);

const cartSizeStore = cart.cartItems.length;

useEffect(() => {
  setCartsize(cartSizeStore);
}, [cartSizeStore]);


text:
Q: Smooth a curve in Python while preserving the value and slope at the end points I have two solutions to this problem actually, they are both applied below to a test case. The thing is that none of them is perfect: first one only take into account the two end points, the other one can't be made "arbitrarily smooth": there is a limit in the amount of smoothness one can achieve (the one I am showing).
I am sure there is a better solution, that kind-of go from the first solution to the other and all the way to no smoothing at all. It may already be implemented somewhere. Maybe solving a minimization problem with an arbitrary number of splines equidistributed?
Thank you very much for your help
Ps: the seed used is a challenging one

    import matplotlib.pyplot as plt
    from scipy import interpolate
    from scipy.signal import savgol_filter
    import numpy as np
    import random

    def scipy_bspline(cv, n=100, degree=3):
        """ Calculate n samples on a bspline
            cv :      Array ov control vertices
            n  :      Number of samples to return
            degree:   Curve degree
        """
        cv = np.asarray(cv)
        count = cv.shape[0]
        degree = np.clip(degree,1,count-1)
        kv = np.clip(np.arange(count+degree+1)-degree,0,count-degree)

        # Return samples
        max_param = count - (degree * (1-periodic))
        spl = interpolate.BSpline(kv, cv, degree)
        return spl(np.linspace(0,max_param,n))

    def round_up_to_odd(f):
        return np.int(np.ceil(f / 2.) * 2 + 1)

    def generateRandomSignal(n=1000, seed=None):
        """
        Parameters
        ----------
        n : integer, optional
            Number of points in the signal. The default is 1000.

        Returns
        -------
        sig : numpy array

        """
        np.random.seed(seed)
        print("Seed was:", seed)
        steps = np.random.choice(a=[-1, 0, 1], size=(n-1))
        roughSig = np.concatenate([np.array([0]), steps]).cumsum(0)
        sig = savgol_filter(roughSig, round_up_to_odd(n/10), 6)
        return sig

    # Generate a random signal to illustrate my point
    n = 1000
    t = np.linspace(0, 10, n)
    seed = 45136. # Challenging seed
    sig = generateRandomSignal(n=1000, seed=seed)
    sigInit = np.copy(sig)

    # Add noise to the signal
    mean = 0
    std = sig.max()/3.0
    num_samples = n/5
    idxMin = n/2-100
    idxMax = idxMin + num_samples
    tCut = t[idxMin+1:idxMax]
    noise = np.random.normal(mean, std, size=num_samples-1) + 2*std*np.sin(2.0*np.pi*tCut/0.4)
    sig[idxMin+1:idxMax] += noise

    # Define filtering range enclosing the noisy area of the signal
    idxMin -= 20
    idxMax += 20

    # Extreme filtering solution
    # Spline between first and last points, the points in between have no influence
    sigTrim = np.delete(sig, np.arange(idxMin,idxMax))
    tTrim = np.delete(t, np.arange(idxMin,idxMax))
    f = interpolate.interp1d(tTrim, sigTrim, kind='quadratic')
    sigSmooth1 = f(t)

    # My attempt. Not bad but not perfect because there is a limit in the maximum
    # amount of smoothing we can add (degree=len(tSlice) is the maximum)
    # If I could do degree=10*len(tSlice) and converging to the first solution
    # I would be done!
    sigSlice = sig[idxMin:idxMax]
    tSlice = t[idxMin:idxMax]
    cv = np.stack((tSlice, sigSlice)).T
    p = scipy_bspline(cv, n=len(tSlice), degree=len(tSlice))
    tSlice = p.T[0]
    sigSliceSmooth = p.T[1]
    sigSmooth2 = np.copy(sig)
    sigSmooth2[idxMin:idxMax] = sigSliceSmooth

    # Plot
    plt.figure()
    plt.plot(t, sig, label="Signal")
    plt.plot(t, sigSmooth1, label="Solution 1")
    plt.plot(t, sigSmooth2, label="Solution 2")
    plt.plot(t[idxMin:idxMax], sigInit[idxMin:idxMax], label="What I'd want (kind of, smoother will be even better actually)")
    plt.plot([t[idxMin],t[idxMax]], [sig[idxMin],sig[idxMax]],"o")
    plt.legend()
    plt.show()
    sys.exit()

A: Yes, a minimization is a good way to approach this smoothing problem.
Least squares problem
Here is a suggestion for a least squares formulation: let s[0], ..., s[N] denote the N+1 samples of the given signal to smooth, and let L and R be the desired slopes to preserve at the left and right endpoints. Find the smoothed signal u[0], ..., u[N] as the minimizer of
min_u (1/2) sum_n (u[n] - s[n])² + (λ/2) sum_n (u[n+1] - 2 u[n] + u[n-1])²
subject to
s[0] = u[0], s[N] = u[N] (value constraints),
L = u[1] - u[0], R = u[N] - u[N-1] (slope constraints),
where in the minimization objective, the sums are over n = 1, ..., N-1 and λ is a positive parameter controlling the smoothing strength. The first term tries to keep the solution close to the original signal, and the second term penalizes u for bending to encourage a smooth solution.
The slope constraints require that
u[1] = L + u[0] = L + s[0] and u[N-1] = u[N] - R = s[N] - R. So we can consider the minimization as over only the interior samples u[2], ..., u[N-2].
Finding the minimizer
The minimizer satisfies the Euler–Lagrange equations
(u[n] - s[n]) / λ + (u[n+2] - 4 u[n+1] + 6 u[n] - 4 u[n-1] + u[n-2]) = 0
for n = 2, ..., N-2.
An easy way to find an approximate solution is by gradient descent: initialize u = np.copy(s), set u[1] = L + s[0] and u[N-1] = s[N] - R, and do 100 iterations or so of
u[2:-2] -= (0.05 / λ) * (u - s)[2:-2] + np.convolve(u, [1, -4, 6, -4, 1])[4:-4]

But with some more work, it is possible to do better than this by solving the E–L equations directly. For each n, move the known quantities to the right-hand side: s[n] and also the endpoints u[0] = s[0], u[1] = L + s[0], u[N-1] = s[N] - R, u[N] = s[N]. The you will have a linear system "A u = b", and matrix A has rows like
0, ..., 0, 1, -4, (6 + 1/λ), -4, 1, 0, ..., 0.
Finally, solve the linear system to find the smoothed signal u. You could use numpy.linalg.solve to do this if N is not too large, or if N is large, try an iterative method like conjugate gradients.

A: you can apply a simple smoothing method and plot the smooth curves with different smoothness values to see which one works best.
def smoothing(data, smoothness=0.5):
    last = data[0]
    new_data = [data[0]]
    for datum in data[1:]:
        new_value = smoothness * last + (1 - smoothness) * datum
        new_data.append(new_value)
        last = datum
    return new_data

You can plot this curve for multiple values of smoothness and pick the curve which suits your needs. You can also apply this method only on a range of values in the actual curve by defining start and end


text:
Q: How to avoid Error in load Namespace using R Am trying to launch a shiny app using the below command.
Rscript -e "shiny::runApp('test-app', launch.browser=TRUE)"

However, I get an error as shown below
Error in loadNamespace(i, c(lib.loc, .libPaths()), versionCheck = vI[[i]]) :
  namespace 'htmltools' 0.4.0 is being loaded, but >= 0.4.0.9003 is required
Calls: :: ... getNamespace -> loadNamespace -> namespaceImport -> loadNamespace
Execution halted

I did check my library folder and see that htmltools package is present.
I also tried the below dependencies=TRUE
install.packages(pkgs,lib = "C:/Users/User/Desktop/data/library",repo = "https://cloud.r-project.org",dependencies=TRUE)

Here pkgs is a list containing list of packages that has to be installed.
The problem is same script works in my system but it doesn't work in my colleague's system. How can I resolve this?
Can help me understand what's the issue?

A: Although Kouadio has the correct answer, I found it difficult to follow those brief instructions, so I'm making them more detailed here.

*

*Quit RStudio.

*Find the RStudio launch icon, either on your desktop or in your Windows Start Menu.

*Right-click the icon and choose "Run as administrator."  Say yes when prompted that this is really what you want to do.

*In RStudio, go to the Tools menu and choose Check for Updates.

*Select all the packages and choose to update them.  Say yes to the relevant prompts.

You should then be able to use the Knit button again, but you probably want to quit RStudio and restart in non-administrative mode before doing so.

A: I found new solution ,
you need to run rstudio with admin mode for check you update
After all packages are installed
Close Rstudio
Run Rstudio in normal mode .


text:
Q: How to display a picklist based on the value chose on another picklist I need to display two picklist in VF page. I have created a picklist using selectoption (Say PickList1) which has values of '1,2,3,4,5'. Now on selecting a value from this picklist i need to display the second picklist. For eg , if I select 1 in picklist1 , second picklist needs to display 2,3,4,5.

A: From the Visualforce Developer Guide:

Adding Dependent Fields to a Page
Dependent fields provide a way to filter the field values displayed on a Visualforce page. Dependent fields consist of two parts: a controlling field that determines the filtering, and a dependent field that has its values filtered. Dependent fields can dynamically filter values in fields such as picklists, multi-select picklists, radio buttons, and checkboxes. Dependent picklists can only be displayed on Visualforce pages with Salesforce API version 19.0 or higher. For more information, see Dependent Picklists in the Salesforce online help.
For this example, we'll be adding a dependent picklist, Subcategories, to a Visualforce page. First, create this custom picklist:

*

*From the object management settings for accounts, go to the fields area, and then click New.

*Choose Picklist, and then click Next.

*Enter Subcategories for the Field Label.

*Enter the following terms for the list of values:

*

*Apple Farms

*Cable

*Corn Fields

*Internet

*Radio

*Television

*Winery

*Click Next twice, then click Save.
To define the field dependencies for Subcategories:

*

*From the object management settings for accounts, go to the fields area.

*Click Field Dependencies.

*Click New.

*Choose Industry as a controlling field, and Subcategories as a dependent field.

*Click Continue.

*Each value in the controlling field (from Industry) is listed in the top row and each value in the dependent field (from Subcategory) is displayed in the column below it. Set your field dependencies to match this image:
The Field Dependency Matrix for Subcategories

You can disregard any other Industry types that aren't shown above.
Now, create a Visualforce page called dependentPicklists that looks like this:
<apex:page standardController="Account">
    <apex:form >
        <apex:pageBlock mode="edit">
            <apex:pageBlockButtons >
                <apex:commandButton action="{!save}" value="Save"/>
            </apex:pageBlockButtons>
            <apex:pageBlockSection title="Dependent Picklists" columns="2">
            <apex:inputField value="{!account.industry}"/>
            <apex:inputField value="{!account.subcategories__c}"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

When you select Agriculture from the Industry picklist, the Subcategories picklist contains Apple Farms, Corn Fields, and Winery. If you select Communication, your Subcategories picklist contains all the Communication types defined earlier.

A: Use the Below code :

<apex:form >

    <apex:actionFunction action="{!createDependPick}" name="generateDependPick" reRender="pick2" />

    Select the Pick1:

    <apex:selectList id="pick1" value="{!Selected1}" size="1" onchange="generateDependPick()">

        <apex:selectOptions value="{!selectoption1}">

        </apex:selectOptions>

    </apex:selectList>

    Select the Pick2:

    <apex:selectList id="pick2" value="{!Selected2}" size="1">

        <apex:selectOptions value="{!selectoption2}">

        </apex:selectOptions>

    </apex:selectList>

</apex:form>

public class PickController {
public List selectoption1 {get; set;}
public List<SelectOption> selectoption2 {get; set;}
public String Selected1 {get; set;}

public String Selected2 {get; set;}
public PickController(){

    selectoption1 = new List<SelectOption>();

    selectoption2 = new List<SelectOption>();

    SelectOption option = new SelectOption('--None--', '--None--');

  selectoption1.add(option);

   selectoption2.add(option);

   option = new SelectOption('1', '1');

    selectoption1.add(option);

    option = new SelectOption('2', '2');

    selectoption1.add(option);

option = new SelectOption('3', '3');
   selectoption1.add(option);

    option = new SelectOption('4', '4');

    selectoption1.add(option);

}

public void createDependPick(){

   selectoption2.clear();

     selectoption2.add(new SelectOption('--None--', 'None'));

    if(Selected1  == '1'){

        selectoption2.add(new SelectOption('2','2'));

        selectoption2 .add(new SelectOption('3','3'));

selectoption2 .add(new SelectOption('4','4'));
selectoption2 .add(new SelectOption('5','5'));
    }

    else if(Selected1  == '2'){

       selectoption2 .add(new SelectOption('3','3'));

        selectoption2 .add(new SelectOption('4','4'));

    }

}

}

A: public class PickController {
public List selectoption1 {get; set;}
public List<SelectOption> selectoption2 {get; set;}
public String Selected1 {get; set;}

public String Selected2 {get; set;}
public PickController(){

    selectoption1 = new List<SelectOption>();

    selectoption2 = new List<SelectOption>();

    SelectOption option = new SelectOption('--None--', '--None--');

  selectoption1.add(option);

   selectoption2.add(option);

   option = new SelectOption('1', '1');

    selectoption1.add(option);

    option = new SelectOption('2', '2');

    selectoption1.add(option);

option = new SelectOption('3', '3');
   selectoption1.add(option);

    option = new SelectOption('4', '4');

    selectoption1.add(option);

}

public void createDependPick(){

   selectoption2.clear();

     selectoption2.add(new SelectOption('--None--', 'None'));

    if(Selected1  == '1'){

        selectoption2.add(new SelectOption('2','2'));

        selectoption2 .add(new SelectOption('3','3'));

selectoption2 .add(new SelectOption('4','4'));
selectoption2 .add(new SelectOption('5','5'));
    }

    else if(Selected1  == '2'){

       selectoption2 .add(new SelectOption('3','3'));

        selectoption2 .add(new SelectOption('4','4'));

    }

}

}


text:
Q: Takes last 20 record and show last register So i have a problem and i dont know how to look for him.
@app.route('/',methods=['GET', 'POST'])
def index():
    if current_user.is_authenticated:
        current_user.update_on = datetime.utcnow()
        db.session.add(current_user)
        db.session.commit()
    username = db.session.query(User.username,User.avatar).order_by(User.username,User.avatar).limit(20).all()
    nicks = [x[0]for x in username]
    base = 'http://localhost:5000/profil'
    urls = ['{}/{}'.format(base,n)for n in nicks]
    return render_template("index.html",user = username,urls=urls,nicks=nicks)

This is my code in app.py, so i want takes last 20 records from mysql, and show last records in html. Last register user will be first showed, and prelast was be second... but in html show me random Users.
My HTML file:

I dont know how repair this error, someone can help me ? or just give me a tips ? Im was start learning programming in last week
And another problem i have with  sqlalchemy.exc.OperationalError (2013, 'Lost connection to MySQL server during query') its to fast end connect, like 2min and see a error
DATABASE_URI = 'mysql://{}:{}@{}:{}/kamilos98'.format(config['user'], config['password'],config['host'], config['port'])
app.config['SQLALCHEMY_DATABASE_URI'] = DATABASE_URI
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True

A: This:
username = db.session.query( \
    User.username,User.avatar).order_by(User.username,User.avatar).limit(20).all()

Orders by user name and avatar. Change it to:
username = db.session.query( \
    User.username,User.avatar).order_by(User.update_on.desc(),User.username).limit(20).all()

to order them by the last update time instead.


text:
Q: Jsp и Hibernate Можно ли в Jsp использовать Hibernate  для быстрого подключения к базе данных? Или их лучше не смешивать?

A: Смешивать безусловно можно, вопрос стоит ли. Если нужно именно jsp и хочется использовать hibernate, то можно для работы с базой данных вынести логику работы с базой в session beans, которые в свою очередь логично использовать в jsp. Но естественно никто не запрещает создавать hibenate сессию прямо в jsp и там всю логику оставить.


text:
Q: Nuxt.js 3 load binary file from server I want to get the contents of a binary file from an api endpoint (/server/api/xxx.ts) in Nuxt.js 3.
I noticed that having the binary file under the server directory, for example /server/files/file.bin, it doesn't get bundled on build.
I believe that using hooks in the config file, somewhat similarly to the example in the docs, it can be done (didn't try yet). But it seems over-complicating.
Is there a "best practice" for something like this?
Of course it's possible to make that file available in /public/files/file.bin and fetch it from the address like http://localhost:3000/files/file.bin, and although in my case the file can be public, it seems not to be a desirable solution.


text:
Q: How to use an XML element in an XML function I know that generating fixed width text from XMl is a common need. And I know this question has been asked before, but every answer I've found is unclear to me due to my lack of understand of XSLT functions.
I have several examples of using an XSLT function to pad a string to a particular width. But none of the examples I'f found are very clear on how to use these functions.
I need to take the contents of an XML element, and pad that to a fixed with with spaces. I have found such functions at the below links.

*

*http://www.xsltfunctions.com/xsl/functx_pad-string-to-length.html

*XSL left-right justification with Padding

*http://www.exslt.org/str/functions/padding/str.padding.template.xsl.html
But in each example they pass in a string, such as "1234 Street". How do I use such functions by passing an element such as <Address>1234 Street</Address>

A: As Michael already explained, any argument is string-normalized if a function expects a string. If you take your first example from FunctX then you can do the following;
Input XML
<root>
    <address>1234 Street</address>
<root>

XSLT
In the below examples I assume you have copied the code from FunctX and bound it to a namespace (I use the funtcx prefix).
One way to do it (. refers to the context node):
<xsl:template match="address">
    <!-- we are now inside address element -->
    <xsl:value-of select="functx:pad-string-to-length(., ' ', 20)
</xsl:template>

Other way to do it:
<xsl:template match="root">
    <!-- we are now inside root element -->
    <!-- note, this will process ALL children under "root" that match "address" -->
    <xsl:value-of select="functx:pad-string-to-length(address, ' ', 20)
</xsl:template>

Basically: just use any XPath expression that selects the element you want to be passed on to the function should do it. The function has its argument defined as xs:string, which will require the processor to get the value of of the element before it passes it on to the function.
You do not need to change the function body in any way, you can just use them as-is.


text:
Q: recv return after 0x0000 byte found Here is my code:

*

*Client
Position pos(1.0,2.0,0.45);
feedback feed(12, pos, 100);
msgpack::sbuffer sbuf;
msgpack::pack(sbuf, feed);
int test = write(tcp_client.sockfd, sbuf.data(),sizeof(sbuf));

*Server :
char* buffer = new char[41];
int test = recv(TCP_server.newsockfd, buffer, 40, MSG_WAITALL );

for (int i=0; i< sizeof(buffer); i++)
std::cout << std::hex << (int)buffer[i] << " ";
std::cout << std::endl;

For the other parts of the codes, connection is established and data has been transmitted successfully.
The problem now is that I got the following output :

*

*Client :
ffffff94 b c ffffff93 ffffffca 3f ffffff80 0 0 ffffffca 40 0 0 0 ffffffca 3e ffffffe6 66 66 64

*Server :
ffffff94 b c ffffff93 ffffffca 3f ffffff80 0

Is there any reason why received data stopped after encountering the first 0x0000 char? when I send a string, everything works fine but not in this specific case.
For the records, the recv() doc doesn't help much...

A: When you call recv, you should use the returned value from that function to determine the number of bytes you should process.
Instead, you used sizeof(buffer) to determine the number of times to loop, which is not correct.  The buffer is a char *, and sizeof(char *) will usually be either 4 or 8, depending on 32 / 64 bit.
So this:
for (int i=0; i< sizeof(buffer); i++)

should be:
int test = recv(TCP_server.newsockfd, buffer, 40, MSG_WAITALL );
// assuming that test >= 0
for (int i=0; i < test; i++)


text:
Q: which scenario in http transaction is occurred? In http transaction for request and response which scenario is occurred ?

*

*client (web browser) open connection and send it's request and connection open (keep alive) until server accept and answer then close connection ?

*client (web browser) open connection and send it's request then connection is closed  and server accept and answer and reconnect and send response ?

in http1.0 and http1.1 this scenario is different ?

A: A server can't directly reconnect to a client. Hence, your scenario #2 is unlikely.
In other words, in the WEB world, "transactions" between a Client Browser and a WEB Server is always "Client Browser Initiated".

Of course, if we are talking about server-to-server communication over HTTP, it is a different story: you can make up your own rules here, provided you control at least one server ;-)

As for the difference between HTTP 1.0 and HTTTP 1.1, I don't know enough.

A: The scenario is:

*

*The client (browser) opens a connection to the web server and sends HTTP request

*The server receives the request and sends back the response to the client (browser)

If keep alive is enabled, the connection will not be closed until the keep alive timeout expires. The idea of keep alive is to use the same TCP connect to send/receive multiple requests/responses.
Persistent connection / Keep alive was officially introduced in the HTTP 1.1 specification. keep-alive was not officially documented in the specification of HTTP 1.0, however, some implementation of HTTP 1.0 supported keep alive connections.
regarding scenario 2: The server never initiate connections with browsers, the browser initiate connections with the server and the server uses the same connection to send back responses.

A: In both 1.0 and 1,1 connection is kept open until response is sent. Keep alive refers to what happens afterwards.
In HTTP 1.0 server closes the connection after sending the response. Unless client sends and server understands keep-alive header (which was not a part of HTTP 1.0 standard)
In HTTP 1.1 connection is kept open after the response unless client sends Connection: close header.
Details


text:
Q: Simplifying this equation to get sum of squares $$\frac{1}{n\sum x_{i}^2-{(\sum x_{i}})^2}$$
I have this equation above. I am trying to simplify it such that I can get: $\dfrac{1}{nSS_{x}}$
Where $SS_{x}$ is the sum of squares of $x$. Any pointers on how to achieve this?

A: It's easier to work backwards, and only compare the denominators of your fractions. The sum of squared deviations of $x$ is
$$ SS_x = \sum_i {(x_i-\bar{x})^2} $$
$$ \Rightarrow nSS_x = n\sum_i {(x_i-\bar{x})^2} $$
$$ = n\sum_i \left({x_i^2 - 2x_i\bar{x} + \bar{x}^2}\right) $$
$$ = n\sum_i {x_i^2} - n\sum_i {2x_i\bar{x}} + n\sum_i {\bar{x}^2} . $$
Since $\bar{x}$ and $\bar{x}^2$ are constants, we can factor them out of the sums:
$$ = n\sum_i {x_i^2} - 2n\bar{x}\sum_i {x_i} + n^2\bar{x}^2 , $$
Note, the extra factor of $n$ in the third term comes from the fact that $\sum_i {1} = n$. In the second term and third terms, we can substitute $n\bar{x} = \sum_i x_i$:
$$ = n\sum_i {x_i^2} - 2 \left( \sum_i x_i \right)^2 + \left( \sum_i x_i \right)^2 $$
$$ = n\sum_i {x_i^2} - \left( \sum_i x_i \right)^2 . $$


text:
Q: 3 submit buttons in multi action form I m not a so good in coding..
I want to add a form with 3 buttons with different actions..I got a code but it is not working for me..

<form id="myform" name="myform" onsubmit="return OnSubmitForm ();">
    Enter number:

    <input maxlength='10' name='get-no' placeholder='Mobile Number' type='text'>

    Enter Message:

    <input name='msg' placeholder='Message' type='text'>

    <input checked name="operation" type="radio" value="1">Call
    <input type="radio" name="operation" value="2">Sms
    <input type="radio" name="operation" value="2">Save

<input name="submit" type="submit" value="save">

</form>

I want it to show result "Details saved successfully" on the same page after submission.
Plz give me the corrected code.thank you.

A: I have seen versions of this question in many places. I too wanted more than one button. The method that works for me is to add a hidden field and have the onclick attribute set a value. That hidden field will have the value which represents the action I wish to perform.
<input id="desired-action" name="action" type="hidden" value="" >
<button class="submit-button" type="submit" onclick="set_form_value( 'desired-action', 'new');" >New</button>
<button class="submit-button" type="submit" onclick="set_form_value( 'desired-action', 'update');" >Update</button>


text:
Q: Bridging with aliased Ethernet card for Virtualizing with single Ethernet card We are having a server with good CPU and RAM,so we are planning  to do XEN virtualization on ubuntu 12.04 server to handle high traffic.
The plan is to keep the host machine only to manage VMs(no NAT ing).
A New public IP will be assigned to that VM,For that i think we need a Bridge to external network(Since my Machine has only single ethernet card aliased with 4 different Pub IP's)
Is it possible to create a bridge using aliased IP
single ethernet card aliased to 4 pub IPs
Do we need an additional Ethernet card to do Bridging.Only have ssh access to the machine.
Any suggestions will be appreciated.

A: You don't need to alias. You create a bridge out of your physical network controller and then assign the server's IP data to that bridge. Xen then makes virtual interfaces on that same bridge and the domU's will actually give them an IP (but that is not visible inside the dom0).
Xen has scripts for all this.
You might want to read this.
Also, I wrote a short manual (mostly for my own reference) here. Read it, but take it with a grain of salt, it could be outdated. And, it's Debian. Ubuntu didn't used to have the Xen Hypervisor. I see they do now, but I don't know if installing is the same on Ubuntu and Debian.

A: You do not need an additional ethernet card.
You can follow the instructions here:
https://help.ubuntu.com/community/XenProposed#Network_Configuration
The configuration that you describe is the probably the most common way to use Xen (bridged networking).
The Xen wiki page referenced above is out of date, the updated general Xen.org wiki page for networking in Xen 4.1+ is:
http://wiki.xen.org/wiki/Host_Configuration/Networking


text:
Q: Eclipse remove arrow icons When I click on some word inside the java editor, it marks it together with all occurrences, which is wonderful. As you can see in my screenshot, I've customized it to be green, this green will also show near the slide bar on the right.

What I don't like: the red marked arrows on the left, next to the line numbers. They "show" me the occurrences as well as it seems, but honestly they don't give me any profit as my bright green marking is way faster recognized by me than those arrows.
Plus, and this is the annoying part, these arrows block visibility of my debug points, which will be placed underneath such an arrow. Did you see that the second arrow is actually hiding a debug point? Me neither...
So: is there a way to disable these arrows by eclipse preferences?

A: The Vertical Ruler should be switched off.
Please search for 'Mark Occurrences' in Window -> Preferences.
Then click on the link 'Annotations' and then uncheck 'Vertical ruler'.


text:
Q: Calculating Normals across a sphere with a wave-like vertex shader This is a bit of a CS question, but more than not it's a 3D math problem.
I've been trying to get the correct normals for a sphere I'm messing with using a vertex shader. The algorithm can be boiled down simply to
vert.xyz += max(0, sin(time + 0.004*vert.x))*10*normal.xyz
This causes a wave to roll across the sphere.
In order to make my normals correct, I need to transform them as well. I can take the tangent vector at a given x,y,z, get a perpendicular vector (0, -vert.z, vert.y), and then cross the tangent with the perp vector.
I've been having some issue with the math though, and it's become a personal vendetta at this point. I've solved for the derivative hundreds of times but I keep getting it incorrect. How can I get the tangent?
Breaking down the above line, I can make a math function
f(x,y,z) = max(0, sin(time + 0.004*x))*10*Norm(x,y,z) + (x,y,z)
where Norm(..) is Normalize((x,y,z) - CenterOfSphere)
After applying f(x,y,z), unchanged normals
What is the correct f '(x,y,z)?
I've accounted for the weirdness caused by the max in f(...), so that's not the issue.
Edit: The most successful algorithm I have right now is as follows:
Tangent vector.x = 0.004*10*cos(0.004*vert.x + time)*norm.x + 10*sin(0.004*vert.x + time) + 1
Tangent vector.y = 10*sin(0.004*vert.x + time) + 1
Tangent vector.z = 10*sin(0.004*vert.x + time) + 1
2nd Tangent vector.x = 0
2nd Tangent vector.y = -norm.z
2nd Tangent vector.z = norm.y
Normalize both, and perform Cross(Tangent2, Tangent1). Normalize again, and done (it should be Cross(Tangent1, Tangent2), but this seems to have better results... more hints of an issue in my math!).
This yields this


text:
Q: Embedding Google Conversion Code in Alert I'm using Avada's template (http://theme-fusion.com/avada/contact/) and working with their contact page.  Whenever someone submit's a successful form, the page is being reloaded with an additional "alert" box that's populated with a success message.  I'm looking to embed a Google Conversion Pixel in this alert box if possible instead of having to send the user to a whole new page.  The code that creates the alert box is
<?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>

<?php echo do_shortcode( '[alert type="success" accent_color="" background_color="" border_size="1px" icon="" box_shadow="yes" animation_type="0" animation_direction="down" animation_speed="0.1" class="" id=""]' .  __( 'Thank you', 'Avada' ) . ' ' . $name . ' ' . __( 'for contacting us! Your email was successfully sent!', 'Avada' ) . '[/alert]' ); ?>

<?php } ?>

which generates

    <button type="button" class="close toggle-alert" data-dismiss="alert" aria-hidden="true">×</button>

    Thank you Test for contacting us! Your email was successfully sent!

Code looking to embed looks like this

Any help is greatly appreciated

A: Since each line has opening and closing php tags you can simply paste the html code between two php blocks (but after the "if" block). You might choose to just use the image tag from the noscript block (conversions will still be tracked).
<?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>
// just the noscript image tag, alternatively paste the whole code here

<?php
echo do_shortcode( '[alert type="success" accent_color="" background_color="" border_size="1px" icon="" box_shadow="yes" animation_type="0" animation_direction="down" animation_speed="0.1" class="" id=""]' .  __( 'Thank you', 'Avada' ) . ' ' . $name . ' ' . __( 'for contacting us! Your email was successfully sent!', 'Avada' ) . '[/alert]' ); ?>

<?php } ?>


text:
Q: Combobox to find value using loop I have userform with combobox 9 when you select combobox9 value it will show all the values into the each boxes and you can updated the textbox 19 value into sheet against the raw of the selected value in combobox9 however problem is if there's the same name e.g. twice same name in combobox9 it will only update the its 1st name on the raw and not the 2nd or even if there is 3 entry in sheet with same name.
Names are in column C and textvalue is updated its name on column H however I need to loop the column H if it is already updated against its name then same name needs to updated which is in new raw.
Below is the vba code I have but it is so far not working
If Me.ComboBox9.Value <> "" Then

If VBA.CVar(Application.Match(VBA.CVar(Me.ComboBox9.Value), sh.Range("C:C"), 0)) = True Then

MsgBox "Record Not found for this PO-Number", vbCritical

Exit Sub

Else

i = Application.Match(VBA.CStr(Me.ComboBox9.Value), sh.Range("C:C"), 0)

End If

lCol = Me.ComboBox9.Value

Set findvalue2 = sh.Range("C:C").Find(What:=lCol, LookIn:=xlValues)

If Not findvalue2 Is Nothing Then

adr = findvalue2.Address

Do

If findvalue2.Offset(0, -1).Value = Me.TextBox19 Then

sh.Unprotect "1234"

findvalue2.Offset(0, 6).Value = Me.TextBox19.Value = ""

Exit Do

End If

Set findvalue2 = sh.Range("C:C").FindNext(findvalue2)

Loop While findvalue2.Address <> adr

Set findvalue2 = Nothing

End If

A: I'm not completely sure I understand what you are trying to do but assuming you just want the same value from col C in col H when that value is selected in a combobox the beyond should do it.
I replaced your match function as the disadvantage of this function is that it will stop at the first occurrence. Additionally, arrays are much faster when using vba. On a very large dataset you could even further improve beyond code by using a "dictionary".
Sub combobox()
    Dim test As String, combobox1 As combobox, names
    Sheets(1).combobox1.List = Sheets(1).Range("c2:c4").Value
    names = Sheets(1).Range("C1:C5").Value2

    Dim j As Long, i As Long
    If Sheets(1).combobox1.Value <> "" Then
        Debug.Print Sheets(1).combobox1.Value
        For j = 1 To UBound(names)
            If (names(j, 1) = Sheets(1).combobox1.Value) Then
                Sheets(1).Cells(j, 8).Value2 = names(j, 1)
            End If
        Next j

    End If
End Sub

best of luck,


text:
Q: What model names should be prefixed with I'm having an issue with naming of my types, generally it applies to all of my projects.
I'm working with CQRS and many times i have different layers of my application that refer to similar 'context' of a data.
For example i have a Player context which is spread across query model, write model, domain model etc.
Basically my question is that if some class/struct/data type is referring to specifically 'Query' type, should i name it as PlayerQuery or QueryPlayer.
From my understanding the 'PlayerQuery' implies that it is a query of a player data, on the other hand 'QueryPlayer' implies some kind of 'Query' behavior.
It has been quite a while when i started coding but i still struggle with properly naming things.
It feels like the 'PlayerQuery' is better approach here.
Are there any books or online resources where i could tackle this issue?
Thanks much

A:
It has been quite a while when i started coding but i still struggle with properly naming things.

A great quote that is relevant here  :

There are only two hard things in Computer Science: cache invalidation
  and naming things.
-- Phil Karlton

You are having this problem because you are trying to approach the problem with a CRUD mindset, whereas CQRS (or CQS) advocates focusing on the actual interaction. Even when different parts of the application share player context, the reason for its usage will be different.
As examples, you will be:

*

*Querying for a paginated list of players

*Asking for a single player's detail

*Saving an individual player's data

*Bulk-updating an attribute in multiple player details

In each of these interactions, you should take the interaction itself as a cue to name the Query/Command/DTO object.
So the data class names could be:

*

*PlayersList

*PlayerDetailForQuery

*PlayerDetailForSave

*PlayerDetailsForBulkUpdate

An improvement would be to suffix each class name with the type of object:

*

*PlayersListParams

*PlayersListResult

*PlayerRow (or) PlayerItem (or) PlayerDetail

*PlayerEvent

*PlayerSpecification
The best implementation would be to combine the interaction with the type of object:

*

*FetchPlayerListParams

*FetchPlayerListResult

*GetPlayerDetail

*BulkUpdatePlayerParams

*SavePlayerCommand

*PlayerSavedEvent
The most important thing is, once you choose a convention (like Detail instead of Item or Row), be consistent in its usage all over the code.


text:
Q: Move reputation from one website to another website Can i move my reputation from one website (like http://meta.stackoverflow.com) to another website(like https://english.stackexchange.com/)?
Is it possible?
Thanks!

A: No, you can't transfer reputation between sites. The reputation you gain on a Stack Exchange site is a rough measure of your participation in that community. If you want reputation on a site, you have to participate there.


text:
Q: Newline escape sequence not working on php I have this piece of code and for some reason the escape sequences are not working... what could be the problem?
$handle = fopen("TransLoc.txt", "r");
if($handle){
    while(($buffer = fgets($handle)) != false){
        echo "hahahahah\t";
        echo $buffer."\n";
    }
    fclose($handle);
}

A: You probably call this script from a webserver with your browser. In fact the newline appears in the output, but browser don't render them. Look at the source of the page you called and you will see them.
If you want to get a "html"-newline, use <br/>. Or if you don't want to send HTML, use
header('Content-Type: text/plain');

for example

A: http://php.net/nl2br
that function adds a br tag to every newline in the output
try it if you use your function inside an html body

A: You could also set the header for content type to text/plain having the following line in your code before sending any other data to the browser
Header('Content-type: text/plain');

If you are just want to send plain text. Otherwise followin @KingCrunch advice.
EDIT
@KingCrunch has added the text/plain whilst I was typing in my answer!


text:
Q: Filtering JSON with PostgreSQL / Excluding elements of JSON array I want to be able to return part of a JSON using PostgreSQL.  For example if I have the JSON
{
    "dress_code": "casual",
    "design": "Solid",
    "fit": "Straight-cut",
    "aesthetic": [
        {
            "aesthetic_id": 1,
            "primary_color": "light blue",
            "secondary_color": "light gray",
            "sizes": [
                {
                    "size_id": "1",
                    "basic_size": "S",
                    "waist": 30,
                    "pictures": [
                        {
                            "angle": "front",
                            "url": "fashion.com/img1f"
                        },
                        {
                            "angle": "back",
                            "url": "fashion.com/img1b"
                        }
                    ]
                },
                {
                    "size_id": "2",
                    "basic_size": "M",
                    "waist": 33,
                    "pictures": [
                        {
                            "angle": "front",
                            "url": "fashion.com/img1f"
                        },
                        {
                            "angle": "back",
                            "url": "fashion.com/img1b"
                        }
                    ]
                }
            ]
        },
        {
            "aesthetic_id": 2,
            "primary_color": "dark blue",
            "secondary_color": "light gray",
            "sizes": [
                {
                    "size_id": "3",
                    "basic_size": "S",
                    "waist": 30,
                    "pictures": [
                        {
                            "angle": "front",
                            "url": "fashion.com/img2f"
                        },
                        {
                            "angle": "back",
                            "url": "fashion.com/img2b"
                        }
                    ]
                },
                {
                    "size_id": "4",
                    "basic_size": "M",
                    "waist": 33,
                    "pictures": [
                        {
                            "angle": "front",
                            "url": "fashion.com/img2f"
                        },
                        {
                            "angle": "back",
                            "url": "fashion.com/img2b"
                        }
                    ]
                }
            ]
        }
    ]
}

And, for example, I only want the array and information of aesthetic_id = 2 and size_id = 4, which would be:
{
    "dress_code": "casual",
    "design": "Solid",
    "fit": "Straight-cut",
    "aesthetic": [
        {
            "aesthetic_id": 2,
            "primary_color": "dark blue",
            "secondary_color": "light gray",
            "sizes": [
                {
                    "size_id": "4",
                    "basic_size": "M",
                    "waist": 33,
                    "pictures": [
                        {
                            "angle": "front",
                            "url": "fashion.com/img2f"
                        },
                        {
                            "angle": "back",
                            "url": "fashion.com/img2b"
                        }
                    ]
                }
            ]
        }
    ]
}

Is there a good way about filtering JSON data like this using PostgreSQL?


text:
Q: Ring in labyrinthian that you can't pick up? In labyrinthian, there is a pool of water with a skeleton and a chest in it. It has some ore as well if I remember correctly. Anyway, there is a large stone block in the corner of the pool with  a ring resting on it. The skeleton appears to be reaching for the ring. I can't pick the ring up though. Is this something? Should I forget about it? I'm so intrigued!

A: So, I know this reply is super late, but it turns out that the ring is a Golden Diamond ring. The problem with it is that the creators must have placed it behind an invisble wall. If you're on pc, and you use the TCL command, you can grab it by clipping through the wall. Not sure of any other method though.

A: The hitboxes in Skyrim are atrocious. I can't say exactly what you need to do for this particular ring, as I can't remember what you are referring to, but just try and move around the pedestal, and even move your cursor around it to see if you can't find the hitbox (you would be surprised how terrible the hitboxes for coins are).
The other option is to use Unrelenting Force on it, but beware! You can lose it this way!
I would recommend a save/quicksave beforehand and if you can't find it after shouting, reload and try again.


text:
Q: Count all roles in a discord server : discord.js v12 as the title states, I'm trying to count all the roles in a discord server. However, all the methods I found were members within a role. I've tried using these methods but none of them seemed to work:
var totalRoles = message.guild.roles.size;

and
const guild = client.guilds.cache.get("ID HERE");
var totalRoles = guild.roles.size;

However, I keep getting undefined as the results returned. So, is there any way I can properly count the amount of roles in a discord server?

A: That was pretty quick but I've found the answer for anyone interested in the future:
var totalRoles = message.guild.roles.cache.size;


text:
Q: Using PowerShell to replace string that contains + in the string I am trying to use PowerShell do a simple find and replace.  Essentially, I used to have some support files in a directory with the same name of a "master" file.  All but one of those support files are no longer necessary.  The "master" file has a text reference to the path of the other file.  What I want to do is modify this path in the "master" file to remove the deleted directory.
For example, let's say I have the file C:\Temp\this+that.txt  I used to have C:\Temp\this+that\this+that.dat that has now been moved to C:\Temp\this+that.dat
C:\Temp\this+that.txt has a line like this:
/temp/this+that/this+that.dat

I would like this line to become:
/temp/this+that.dat

I have lots of these files that a batch file is moving.  Everything is working fine using the powershell command below for all file names that do NOT contain a plus + sign.  For those files, the call below does not work.
powershell -Command "(gc '!CURRENT_FILE!') -replace '/!BASE_NAME!/', '/' | Set-Content '!CURRENT_FILE!'"

For the example above, CURRENT_FILE would be C:\Temp\this+that.txt and BASE_NAME would be this+that
Can anyone help me with why this isn't working for file names that contain a plus + sign?

A: @ma_il is exactly right. The '+' character is a special character in RegEx, so you will need to escape it.
powershell -Command "(gc '!CURRENT_FILE!') -replace [regex]::escape('/!BASE_NAME!/'), '/' | Set-Content '!CURRENT_FILE!'"


text:
Q: Why does the title overlap with the plot when specifying x using constrained_layout? Solved: This problem occurred with matplotlib 3.4, updating to 3.5 fixed the issue.
I am plotting multiple subplots in a graph, which all have titles, labels and subplot titles. To keep everything visible and the right size, I am using constrained_layout.
I would like to add a title that is aligned to the left. However, when I specify the x position (even as 0.5 which is the default), the title overlaps with the graph.
My plots are much more complex, but this already shows my issue:
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(figsize=(10, 5), constrained_layout=True)
gs = fig.add_gridspec(1,1)
ax1 = fig.add_subplot(gs[0,0])
fig.suptitle('Title', ha='left')

Only changing the last line of code:
fig.suptitle('Title with x-position', x=0.5, ha='left')

I was first using tight layout, but switched to constrained_layout because tight_layout did not keep the specified size of the figure when exporting it.
I have also switched from subplots to gridspec because I read that constrained_layout does not support subplots.
I know I can add extra space with fig.set_constrained_layout_pads(h_pad=0.3), but this also adds space below the plots, which I would like to avoid.
Hopefully someone can tell me why this happens and how I can get a title aligned to the left that does not overlap with the plot!

A: The problem occurred in Matplotlib 3.4, updating to 3.5 fixed the issue


text:
Q: Getting BadValueError on Google App Engine Datastore Delete I am trying to delete records in the datastore.  Unfortunately, whenever I try to delete the items, it gives me a BadValueError, saying Districts (one of the columns) is required.  Because of an issue with the bulk loader, Districts is null for all of the rows...but I still need to clean out the datastore to try to fix the bulk loader error.
What can I do?

A: Try updating your model so that the Districts field is not required (i.e., pass required=False as a keyword parameter to the Districts field).  Then the validator shouldn't complain about the existing entities and you should be able to delete the entities.
Alternatively, if you know the keys for the entities you want to delete, you can delete them directly using db.delete() without ever needing to fetch them in the first place.
You might even be able to use the datastore viewer from the Dashboard to delete them (if you don't have many entities to delete, this might be easiest).

A: Change your entities/models so that Districts is no longer a required property?


text:
Q: Java array using words rather than numbers This is the chunk of code that I am having issues with:
  public void draw() {
        double tax = 0;
        double income = values[0];
        TaxCalculator one = new TaxCalculator();
        tax = one.tax(income);
        double net = 0;
        net = one.net(income);

        for(int i = 0; i<values.length;i++){
            Bar y = new Bar();
            y.makeVisible();

            y.moveHorizontal(20 + i*20);
            y.moveVertical(197 - (int) income);
            y.changeSize(3, (int) income);
            y.changeColour(Colour.BLUE);

            Bar x = new Bar();
            x.makeVisible();

            x.moveHorizontal(20 + i*20);
            x.moveVertical(197 - (int) income - (int) tax);
            x.changeSize(3, (int) tax);
            x.changeColour(Colour.RED);

            }

what I am trying to do is create a graph using this Bar class, which is essentially just a editable rectangle.I have 2 numbers per cycle of this loop that should be input, I am calling a array in another class which inputs the first number of that array into what is currently Bar y, and in another chunk of code it is taking that number and performing an operation on it and returning tax which is Bar x, I believe my issue is stemming from the fact that I am rendering the same bar over and over, so I am wondering if there is a way to create multiple objects with different names within a for loop allowing it to progress onto the next value of my array.
If more of my code is needed to resolve this I am happy to post it

A: The loop is using the data that is initialized before the loop, so income will always be values[0], and all the bars will only represent the first value.
Moving most of the code (the TaxCalculator part can stay outside, since it's most likely reusable) will give you something along the lines of
for(int i = 0;i < values.length; i++) {
    double income = values[i];
    double tax = one.tax(income);

    Bar y = new Bar();
    ...


text:
Q: Use Video chat in background like Skype using WebRTC in Android I am trying to implement functionality like Skype i.e while having Audio/Video call I can go to another screen, but the call will continue, and again I can return to the AV calling screen. I am implementing this idea in Android platform.
The problem I am facing is when I switch the screen, the video is paused, but the audio is continuing. Is there any way to make video continue even if I switch the screen.
I used following code to start the Audio/Video conference from VideoChatActivity.java
    app.startLocalMedia(new SingleAction<Exception>() {
        @Override
        public void invoke(Exception ex) {
            if (ex == null) {
                // Start the signalling engine.
                app.startSignalling(new SingleAction<String>() {
                    @Override
                    public void invoke(String ex) {
                        if (ex != null) {
                            // alert("Could not start signalling. %s",
                            // ex.getMessage());
                            alert("Some problem occured while establishing connection");
                            Logger.error("YES-Error at startSignalling " + ex);
                        }
                    }
                }, webasyncURL);
                // Start the conference engine.
                Logger.error("YES-here-1.2");
                app.startConference(iceLinkServerAddress, roomName, video, container, wheel, audioOnlyDefaultAvatar,
                        muteControlToggle, videoOnOffToggle, speakerToggle, videoChatActivity,
                        new SingleAction<Exception>() {
                            @Override
                            public void invoke(Exception ex) {
                                if (ex != null) {
                                    // alert("Could not start conference. %s",
                                    // ex.getMessage());
                                    alert("Some problem occured while initializing video call");
                                    Logger.error("YES-Error at startconference " + ex.getLocalizedMessage());
                                }
                            }
                        });
            } else {
                // alert("Could not start local media. %s",
                // ex.getMessage());
                Logger.error("YES-Error at startLocalMedia " + ex.getLocalizedMessage());
            }
        }
    }, video, audio);

When I back to the previous activity while doing Audio/Video conference I called the service to strat startLocalMedia.
Here is my CameraService.java
VideoChatActivity.app.startLocalMedia(new SingleAction<Exception>() {
            @Override
            public void invoke(Exception ex) {

                if (ex == null) {
                    // Start the signalling engine.
                    VideoChatActivity.app.startSignalling(new SingleAction<String>() {
                        @Override
                        public void invoke(String ex) {
                            if (ex != null) {
                                // alert("Could not start signalling. %s",
                                // ex.getMessage());
                                //alert("Some problem occured while establishing connection");
                                Logger.error("YES-Error at startSignalling " + ex);
                            }
                        }
                    }, VideoChatActivity.webasyncURL);
                    // Start the conference engine.

                    VideoChatActivity.app.startConference(VideoChatActivity.iceLinkServerAddress, VideoChatActivity.roomName, VideoChatActivity.video, VideoChatActivity.container, VideoChatActivity.wheel, VideoChatActivity.audioOnlyDefaultAvatar,
                            VideoChatActivity.muteControlToggle, VideoChatActivity.videoOnOffToggle, VideoChatActivity.speakerToggle, VideoChatActivity.videoChatActivity,
                            new SingleAction<Exception>() {
                                @Override
                                public void invoke(Exception ex) {

                                    if (ex != null) {
                                        // alert("Could not start conference. %s",
                                        // ex.getMessage());
                                        //alert("Some problem occured while initializing video call");
                                        Logger.error("YES-Error at startconference " + ex.getLocalizedMessage());
                                    }
                                }
                            });
                } else {
                    // alert("Could not start local media. %s",
                    // ex.getMessage());
                    //alert("Some problem occured while getting media devices");
                    Logger.error("YES-Error at startLocalMedia " + ex.getLocalizedMessage());
                }
            }
        }, VideoChatActivity.video, VideoChatActivity.audio);

How can I implement this scenario ?


text:
Q: Is it a "driver license" or a "driver's license" or a "drivers license" or...what? I've often wondered why my Ohio license is called a "driver license". It is awkward to say it like that.
Wouldn't something like driver's license be more appropriate?
Or driving license (like hunting license)?

(Note: image above shows driver, driver's, and drivers variations.)

A: Actually, try reading it like this:

Licence of Driver.

I don't think there's anything wrong with it, although we would be more comfortable saying "driver's" or "driving"
"Driver" is just describing what kind of a license it is, not whose. Other examples would be "bar-tender license" not "bar-tender's license"

A: The answer is that the name of the document is prescribed by law. The name is just whatever was chosen when the legislation was written.

A: New Oxford American has this:

driver's license |ˈdraɪvərz ˈˈlaɪsns|
  noun
  a document permitting a person to drive a motor vehicle.
  driving licence
noun
  British term for driver's license .

A: Using of driver/ driver's or driving license depends very much on what we are trying to say:
For example I would say:
a. I lost my driving license.
b. It was about a driver license.
c. I renewed my driver's license. (Provided that it is clear that I am talking about my driver's driving license.)
But again, in daily conversations, they are used almost interchangeably thus causing such confusions.


text:
Q: How to order columns created using Proc SQL in SAS I am using Proc SQL to create Teradata views. I used Execute (pass through facility) and  passed the column names as using variables. But the views which are getting created do not have the columns in the order which was passed into the query. They are getting created at any random order. Is there a way to fix this?

A: Using the method described here:
data tmp;
aa = 1;
db = 1;
ac = 1;
bb = 1;
run;

proc sql ;
  select name into :VARLIST separated by ', '
  from dictionary.columns
  where libname = 'WORK'
    and memname = 'TMP'
  order by name ;
quit ;

proc sql ;
  create table ordered as
  select &VARLIST
  from work.tmp ;
quit ;

A: Not familiar with Teradata per se, more used to working with SAS/DB2, but what if instead of using execute() you would use something like this -- this will create the view on the SAS side (which might not be what you're after, I'm not entirely sure).
proc sql;
 connect to teradata (user=testuser password=testpass);
 create view work.myView as
   select * from connection to teradata
    (select var1, var2, var3
     from someTable);
quit;


text:
Q: Length of Array in Object doesn't match I'm trying to use the tree hierarchy in D3 and got stuck.  I thought I'm building the JSON correctly but when I looked at the object in Developer's Tool, I see the following:

Notice the first line shows the dependents array has 0 length but when expanded, you can clearly see dependents has 3 objects.  When I stringify it, I get the following:
{"attributes":{"id":0,"name":"root"},"dependents":[]}

Any idea what could be wrong?  Thanks!

A: This problem usually happens when you change the object after having logged it because Chrome doesn't deep-copy the object when you log it but simply stores a reference.
The tree isn't immediately built but only when needed and sometimes it's based on a more recent value.
If your object is light enough, you can clone it yourself if you really want to see the value at logging time :
console.log(JSON.parse(JSON.stringify(myobject)));

If your object is big or recursive, you may find it a little more difficult to clone it. Personally I have my own tool, JSON.prune.log.
As ignoring the browser's optimization comes with a cost, you should most often simply take into account this behavior and log only primitive if you want to be sure of their logging time value...


text:
Q: Looping audio in Phaser I've just started making a simple platformer with Phaser, I'm new to this.
I have managed to get music playing but cant get it to loop and Google hasn't helped.
Heres the audio code I'm using, any advice?
game.load.audio('hotttt', ['assets/audio/hotttt.mp3', 'assets/audio/hotttt.ogg']);

music = game.add.audio('hotttt');

music.play();

A: First, you load the audio file like you did, and then create the instance for the audio itselfs.
Example:
game.load.audio('background_music', ['assets/sounds/background_music.mp3', 'assets/sounds/background_music.wav']);

backgroundMusic = game.add.audio('background_music');
backgroundMusic.loop = true; // This is what you are looking for
backgroundMusic.play();

Hope it helps!

A: You will need to create a new Phaser.Sound object and enable loop.
game.load.audio('hotttt', ['assets/audio/hotttt.mp3', 'assets/audio/hotttt.ogg']);

// *true* param enables looping
music = new Phaser.Sound(game,'hotttt',1,true);

music.play();

You can refer to the documentation - Phaser.Sound

A: According to the docs for v2.4.4 (and I tested it with 2.6.1) you can pass an extra argument to the game.add.audio() function for looping
Example
game.load.audio('background', ['assets/audio/background.wav'])

const backgroundSound = game.add.audio('background', 0.5, true) // here "true" means to loop

backgroundSound.play()

That worked fine for me

A: The best solution that works for me is this:
music = game.add.audio('yourMusicFile');
music.loopFull()

A: Anyone who is looking at this thread for Phaser 3.
Load music in preload()
this.load.audio('musicaudio', 'assets/musicl.mp3');
Then in your own function or create()
var music = this.sound.add('musicaudio');
music.setLoop(true);
music.play();

I don't quite understand yet the mechanics behind initializing audio but in order do so in my Chrome environment I had to set this in the initial config declaration.
audio: {
        disableWebAudio: true,
        noAudio: false
    },

P.S. I read somewhere that you shouldn't use mp3's for looping but it works fine for me. Perhaps there is a brief pause.


text:
Q: How to get event notification in an ATL ActiveX control when a specified registry value changes for use as a windows mobile ActiveX control I have an activex control that I display in a webbrowser control on a windows mobile device using a C# forms app.
The activex control is working. I want to add a feature to the activex control where an event is raised in the activex control when a registry value changes state.
I have implemented the same (but reversed) functionality on the forms side using RegistryState with the following code. With this code my .net forms app gets notified when a registry value changes. The forms code is below.
private void TestContainer_Load(object sender, EventArgs e)
{
    RegistryKey rk = Registry.LocalMachine.OpenSubKey("MyKey");
    state = new RegistryState("HKEY_LOCAL_MACHINE\\MyKey", "MessageToHostForm");
    state.Changed += new ChangeEventHandler(state_Changed);
}

void state_Changed(object sender, ChangeEventArgs args)
{
    RegistryKey rk = Registry.LocalMachine.OpenSubKey("MyKey");

    if (rk == null)
    {
        // No value available in the created/opened subkey
    }
    else
    {
        string strOut = (string)rk.GetValue("MessageToHostForm");
        button3.Text = strOut;
        rk.Close();
    }
}

I would like to create the same functionality in the ActiveX control where an event in the control gets fired when a registry value changes.
The problen is ... from what I can tell ... Registry.State is not available in an ATL C++ app :(
How can I make my ATL ActiveX control respond to changes in registry values. (I don't want to use polling)
Is this posible?
Thanks for at least reading this... Long I know...

A: To avoid polling, you can use CRegKey::NotifyChangeKeyValue, which is in turn built on top of RegNotifyChangeKeyValue. You can have an event signaled with a change under the key. So your worker thread might be waiting for this event [possibly among others] and once your wait is satisfied you would do whatever you do in your state_Changed above.
You also have sample code there: http://msdn.microsoft.com/en-us/library/ms724892%28VS.85%29.aspx
UPD. I realized mobile platform is in question - things are somewhat different there, but still you have an event based option:

*

*MSDN: CeFindFirstRegChange http://msdn.microsoft.com/en-us/library/aa914423.aspx

*Code Snippet: Windows CE: Monitor for Registry Changes


text:
Q: cloning repository from gitweb I want to clone a git repository whose git:// server is down.
Fortunately its gitweb interface is still working and all the data required to reconstruct the git repository is available from there.
So, is there any git command or other tool able to clone a git repository from gitweb?
(I could write a bot myself, but don't want to waste my time doing it if there is another way)

A: gitweb is just a perl script (gitweb.perl):

*

*called by Apache (as in this config)

*which reads the bare repos from its server.

If enabled in the gitweb.conf, gitweb can serve "snapshots" (in zip or tag.gz format), but this isn't the full history of the repository: it is only a compressed archive of any tree or commit, as produced by git-archive.
http://<gitweburl>/gitweb.cgi?p=<repo>.git;a=snapshot;h=HEAD

If there is any command, it needs to be executed on the server.
For instance, you can ask for a bundle (git bundle):
cd /path/to/bare/repo
git bundle create ../repo.bundle --all

That will create one file, that you can sftp back to your local station, and which acts as a git repository (read only, clone/pull only, no push):
cd /path/to/repo.bundle
git clone repo.bundle
cd repo

A: You can try fetching repo using http:// instead of git://.
For instance, Linux git repo at https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/ can be cloned using http://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
Try replacing git:// with http:// or https:// and see if it does the trick.
Reconstructing git repository file-by-file may be possible, but considering that the repository still exists, it does not make much sense. You may try contacting repo owners and check if they would be willing to either fix repo access.


text:
Q: update data with connected ado.net layer I'm trying to perform update operation on winform using connected ado.net layer.
here's the code
                string insertCmdStr = "UPDATE ARTICLE(SecondId,Group,Code,Name) WHERE (ID=@P1)";
                insertCmdStr += "VALUES(@Idd,@group,@code,@name)";
                FbCommand cmd = new FbCommand(insertCmdStr, fbConn, tran);
                cmd.Parameters.AddWithValue("@P1", id);
                cmd.Parameters.AddWithValue("@Idd", idd);
                cmd.Parameters.AddWithValue("@group", group);
                cmd.Parameters.AddWithValue("@code", code);
                cmd.Parameters.AddWithValue("@name", name);
                cmd.ExecuteNonQuery();

using this query I'm getting exception

*

*$exception  {"Dynamic SQL Error\r\nSQL error code = -104\r\nToken unknown - line 1, column 15\r\n("}    System.Exception
  {FirebirdSql.Data.FirebirdClient.FbException}

A: UPDATE statements are usually constructed as follows:
UPDATE TABLE
SET Field1 = Value
, Field2 = Value
, Field3 = Value
WHERE ID = Value

Therefore you can use:
string insertCmdStr = "UPDATE ARTICLE SET SecondId = @Idd, Group = @group, code = @code, name = @name WHERE ID=@P1;"

I'd also recommend changing insertCmdStr to updateCmdStr just to clarify what you're trying to achieve.

A: Should not query be like this:
UPDATE ARTICLE
SET
    SecondId = @Idd,
    Group = @group,
    Code = @code,
    Name = @name
WHERE ID = @P1


text:
Q: How to sort the ActiveAdmin index based on a filter and a column I have a Rails application with a Movie model. The Movie model has 'name' and 'release_date' as regular attributes, as well as a scope used to search for movie names with elasticsearch.
class Movie < ActiveRecord::Base

   scope :movie_name_search, -> (term) {
     movie_ids = elasticSearch(term, :name).map(&id)
     Movie.where(id: movie_ids).reorder('').order_by_ids(movie_ids) unless movie_ids.nil?
   }

end

I then set up my active admin to show this data
ActiveAdmin.register Promotion do
  filter :movie_name_search, as: :string, label: "Movie Name"

  index do
    actions
    column :name
    column :release date, sortable: :release_date
  end

end

Putting in a movie name into the search bar works perfectly, and sorting against release_date works perfectly, but I can't do both at the same time. Once I'm using the filter for movie names, the sort by date doesn't work. It only works when I remove the reorder and new order.
scope :movie_name_search, -> (term) {
   movie_ids = elasticSearch(term, :name).map(&id)
   Movie.where(id: movie_ids) unless movie_ids.nil?
}

It would appear that the ordering I enforce in the scope takes precedence over the sort of the column but I have no idea why. Any ideas?

A: You're resetting the scope chain when you call Movie.where in movie_search_name. You want to send where to self instead (i.e. just delete the Movie. part), so that prior conditions are preserved.
scope :movie_name_search, -> (term) {
  movie_ids = elasticSearch(term, :name).map(&id)
  where(id: movie_ids) unless movie_ids.nil?
}

Edit: I understand the issue now
Like you say, Elastic Search is returning an array of ids in sorted order, but where does not respect that order. It just pulls records from the database as it finds them, so long as their ids are in the array. It's no good for us to sort the records afterwards as an array, because then ActiveRecord can't apply additional clauses to the query. It has to be done as part of the query.
SQL does provide a way to enforce an arbitrary order: ORDER BY CASE, but it's not built in to Rails. Fortunately, it's not hard to add.
Let's suppose your search results are [2, 1, 3]. In SQL, we can retrieve them in order like this:
SELECT * FROM movies
  WHERE id IN (2, 1, 3)
  ORDER BY CASE id
    WHEN 2 THEN 0
    WHEN 1 THEN 1
    WHEN 3 THEN 2
    ELSE 3 END;

To make this compatible with ActiveRecord, we can add a class method to Movie:
app/models/movie.rb
class Movie < ActiveRecord::Base

  # ...

  def self.order_by_ids_array(ids)
    order_clause = "CASE id "
    ids.each_with_index do |id, index|
      order_clause << sanitize_sql_array(["WHEN ? THEN ? ", id, index])
    end
    order_clause << sanitize_sql_array(["ELSE ? END", ids.length])
    order(order_clause)
  end
end

Now your ActiveAdmin scope uses both where and order_by_ids_array:
scope :movie_name_search, -> (term) {
  movie_ids = elasticSearch(term, :name).map(&id)
  where(id: movie_ids).order_by_ids_array(movie_ids) unless movie_ids.nil?
}

Reference:
http://www.justinweiss.com/articles/how-to-select-database-records-in-an-arbitrary-order/
Edit II: A real hack
Note: This requires a recent version of ActiveAdmin that uses Ransack.
The issue we're having is that filters don't play well with sorting. So here's
the new plan: let's add another column to our index table that shows the search
rank of each movie. This column will only appear when we've filtered by movie
name, and it will be sortable. This way there will be no "default" sort, but
you can sort by anything you want, including search ranking.
The trick is to insert a computed column into the query using a CASE like
above, but in the SELECT clause. We'll call it search_rank and it can be
accessed on any returned movie as movie.attributes['search_rank'].
app/admin/movies.rb
ActiveAdmin.register Movie do

  filter :movie_search, as: string, label: 'Movie Name'

  index do

    # only show this column when a search term is present
    if params[:q] && params[:q][:movie_search]

      # we'll alias this column to `search_rank` in our scope so it can be sorted by
      column :search_rank, sortable: 'search_rank' do |movie|
        movie.attributes['search_rank']
      end
    end

  end
end

Now in our model, we need to define the movie_search scope (as a class method)
and mark it as ransackable.
app/models/movie.rb
class Movie < ActiveRecord::Base

  def self.ransackable_scopes(opts)
    [:movie_search]
  end

  def self.movie_search(term)
    # do search here
    ids = elasticSearch(term, :name).map(&id)

    # build extra column
    rank_col = "(CASE movies.id "
    ids.each_with_index do |id, index|
      rank_col << "WHEN #{ id } THEN #{ index } "
    end
    rank_col << 'ELSE NULL END) AS search_rank'

    select("movies.*, #{ rank_col }").where(id: ids)
  end
end


text:
Q: How to find the locus of this equation? I am a beginner in math, and am stuck by this problem. The problem is,

Find the locus of the point of intersection of the lines, $x\cos\alpha$ + $y\sin\alpha$ = a and $x\sin\alpha$ - $y\cos\alpha$ = b , where "alpha" is a variable.

What they did, is that they eliminated alpha from the equations and got a relation that x^2+y^2=a^2+b^2.
But what i did is , i found out the value of x from equation 1, then i put that in equation 2 and i get y from there, then i again put y back in equation 1 and i get a relation between x and y, but i also get $\sin\alpha$ and $\cos\alpha$ in my answer with that! What does this mean? Howard where is my answer different from the answer that's given in the book?
Thanks!

A: You goal is to find the set of all $\{x,y\}$ that meet the following criteria:
$x \cos \alpha + y \sin \alpha = a\\
x \sin \alpha - y \cos \alpha = b$
These are perpendicular lines that intersect in a point.  But as we allow $\alpha$ to move, that point of intersection moves.
If we can eliminate $\alpha$ then we would have a set of points for all $\alpha$
$x \cos^2 \alpha + y \cos \alpha \sin \alpha = a \cos \alpha\\
x \sin^2 \alpha - y \cos \alpha \sin \alpha= b\sin \alpha$
$x = a \cos\alpha + b \sin \alpha$
Now here is where I would get a little tricky
$x = \sqrt {a^2 + b^2} \cos\alpha \cos \phi + b \sin \alpha \sin \phi $
where $\phi$ is a function of $a,b$ i.e. $\phi = tan^{-1} \frac ba$
but since $a,b$ are constants, $\phi$ is also constant.
$x = \sqrt {a^2 + b^2} \cos(\alpha-\phi)$
and if we solve for $y$ then:
$y = \sqrt {a^2 + b^2} \sin(\alpha-\phi)$
and that is the parametric equation of a circle.
But supposing you don't subscribe such witchcraft.
$x = a \cos\alpha + b \sin \alpha\\
y = a \sin\alpha - b \cos \alpha\\
x^2 = a^2 \cos^2 \alpha + b^2 \sin^2 \alpha + 2ab \cos\alpha \sin\alpha\\
y^2 = a^2 \sin^2 \alpha + b^2 \cos^2 \alpha - 2ab \cos\alpha \sin\alpha\\
x^2 + y^2 = (a^2 + b^2)$

A: You ended up with a formula that had $x$, $y$ and $\alpha$.  But you started with two such formulas, so you're no better off than when you started.
The point of eliminating $\alpha$ from the equations is to get a relation between $x$ and $y$ that does not have $\alpha$ in it.
Alternatively, you could get both $x$ and $y$ as functions of $\alpha$:
$$ \eqalign{x &= a \cos(\alpha) + b \sin(\alpha)\cr
            y &= a \sin(\alpha) - b \cos(\alpha)}$$
That would be a parametric representation of the locus.