text:
Q: How do you generate mean from a uniform distribution between 0 and 1 How do you generate mean from a uniform distribution between 0 and 1
with a sample size of 10? using excel?
Do you have to first generate random numbers from 0 to 1?

A: To have a "sample size of 10" we need to take 10 samples from the distribution.  In Excel, this is achieved by:
=RAND()

So type this into one cell, then click and drag this to fill 10 cells, say cells A1 to A10.  Then to compute the sample mean:
=AVERAGE(A1:A10)

The actual mean is $0.5$, so the sample mean should be somewhat close to this.
This is what it looks like on my computer:

(This is actually LibreOffice Calc, but I believe the syntax is the same.)


text:
Q: Run worker using doOnSuccess I have a following publisher:
public Mono<AuthorizationResponse> auth() {
    return authApi
            .auth()
            .onErrorMap(WebClientResponseException.class, AuthorizationException::new)
            .doOnSuccess(authResponse -> waitForConfirmation(authResponse).subscribe())
            .map(authResponse -> new AuthorizationResponse()
                    .setUrl(authResponse.getUri())
            );
}

private Mono<Void> waitForConfirmation(authResponse authResponse) {
    long numberOfRetries = authResponse.getExpiresIn().dividedBy(authResponse.getInterval());
    return authApi
            .token(authResponse.getToken())
            .retryWhen(Retry.fixedDelay(numberOfRetries, authResponse.getInterval()))
            .map(unused -> {
                //call to another service
                return unused;
            });
}

Generaly it should work like:

*

*Request to the auth() resource returns some data, which should be returned to caller (AuthorizationResponse) immediately.

*In the meantime, worker waitForConfirmation() should be started. This worker should obtain token using some kind of retry policy. When token is returned - call to another service should be done. This worker should work with background.

        auth()
          |
          |---------------- start 'worker' waitForConfirmation in background
          |
AuthorizationResponse

Now everything is ok. It's working, but I'm new in the reactive programming, so maybe is a better way to do it?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can you wheelie in Mario Kart 8? Mario Kart 8, like it's predecessor Mario Kart Wii, has motorcycles (commonly called bikes) in addition to plain karts. In Mario Kart Wii when the player was racing with a bike, he could "pop a wheelie" by raising the front tire and provide an increase in speed with a trade-off in handling.

However, in Mario Kart 8, the usual control methods of performing a wheelie have no affect. Is is possible to perform a wheelie in Mario Kart 8?

A: It is not possible to do a wheelie. However, bikes will do a wheelie when you use a mushroom. This is purely aesthetic and give you no advantage. This mechanic for bikes from Mario Kart Wii was removed.

A: Short answer: No
The decision to remove wheelies from Mario Kart 8 was an intentional one. The reason stems from the fact that, due to poor design decisions in Mario Kart Wii, the bike became an over-powered vehicle. This is a statement attested to in general by players and developers alike.
The main factors that over-powered bikes were:

*

*Overall Speed - Bikes generally had higher speeds than karts. The two fastest combinations in the game both require bikes.

*Wheelies - Gave them an additional speed advantage that karts did not have.

*Inner drifting - Allowed for sharper curves that karts could never perform.

The developers of Mario Kart Wii attempted to balance this situation by limiting how bikes boosted via drifts: granting only blue boosts, instead of the more powerful orange. This however had little impact.
Enter Mario Kart 8
The developers have made every attempt to balance bikes, while still retaining their spirit. The first and most obvious change in gameplay mechanics is the removal of wheelies as you noted. This makes them more on par with karts.
Other mechanical changes to bikes in Mario Kart 8 include:

*

*Increasing the drift angle to be less sharp.

*Giving them access to orange speed boosts, just like karts.

All of that said, as Matt has stated, when boosting via mushrooms if a player is using a bike in Mario Kart 8, the character will perform a wheelie. This is simple eye-candy and has no known effect on gameplay.


text:
Q: Spring @Cacheable, @CachePut not works from another proxy class This is my ProductServiceImpl class.
public class ProductServiceImpl implements ProductService {

@Autowired
 GalaxyService gs ;

@PostConstruct
private void init() {
   int hash = Objects.hash("Galaxy");
    gs.updateByName(hash);

}

@Override
@Cacheable(value = "products", key = "T(java.util.Objects).hash(#p0)")
public String getByName(String name) {
    System.out.println("Inside method");
    slowLookupOperation();
    return name + " : " + name;
}

@CacheEvict(value = "products", allEntries = true)
public void refreshAllProducts() {
    //This method will remove all 'products' from cache, say as a result of flush API.
}

public void slowLookupOperation() {
    try {
        long time = 5000L;
        Thread.sleep(time);
    } catch (InterruptedException e) {
        throw new IllegalStateException(e);
    }
}}

Here is my GalaxyServiceImpl:
public class GalaxyServiceImpl implements GalaxyService {

@Override
@CachePut(value = "products", key = "#key")
public String updateByName(Integer key) {
    return "Oh My Galaxy- " + key;
}}

From init() method of ProductServiceImpl, I was updating a cache element. Looks like it is Spring cache is not caching that method.
But, I do it from my Main class, it was caching the method. Main class in below:
    public mainconstructor() {

        AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        ProductService service = (ProductService) context.getBean("productService");

        GalaxyService gs = (GalaxyService) context.getBean("galaxy");

     int hash = Objects.hash("Galaxy");
     gs.updateByName(hash);

        System.out.println("Galaxy S8 ->" + service.getByName("Galaxy"));

        ((AbstractApplicationContext) context).close();
    }

My application configuration class in below:
@EnableCaching
@Configuration
@ComponentScan(basePackages = {"com.websystique.spring", "com.samsung.gs8"})
public class AppConfig {

@Bean
public CacheManager cacheManager() {
    return new EhCacheCacheManager(ehCacheCacheManager().getObject());
}

@Bean
public EhCacheManagerFactoryBean ehCacheCacheManager() {
    EhCacheManagerFactoryBean factory = new EhCacheManagerFactoryBean();
    factory.setConfigLocation(new ClassPathResource("ehcache.xml"));
    factory.setShared(true);
    factory.setAcceptExisting(false);
    return factory;
}

@Bean
public GalaxyService galaxy() {
    GalaxyService gs = new GalaxyServiceImpl();
    return gs;
}}

Completes code available at- https://github.com/pijushcse/SpringCache
My question is what is the wrong from ProductServiceImpl, if I want to update a cache item? Why it works from Main why not from other class? TIA

A: The quick answer is: It's normal. You should not initialize a cache in a @PostConstruct.
The long answer now. The CacheInterceptor is special. It gets created with initialized = false. Then, in a special callback SmartInitializingSingleton it goes in initialized = true. This callback is called after all beans have been initialized. Before that, it's not caching anything.
Bottom line, you can't pre-cache something in @PostConstruct.
The best solution is to indeed trigger caching by yourself. And it's probably cleaner anyway and it gives more flexibility. So the getBean makes sense.

A: I assume your product service isn't caching but galaxy is. You can't call the slowOperation and have it cached within the same class. caching impls. should wrap what needs cached. Extract a cache service that wraps the slow operating calls.


text:
Q: Unicode stored in C char I'm learning the C language on Linux now and I've came across a little weird situation.
As far as I know, the standard C's char data type is ASCII, 1 byte (8 bits). It should mean, that it can hold only ASCII characters.
In my program I use char input[], which is filled by getchar function like this pseudocode:
char input[20];
int z, i;
for(i = 0; i < 20; i++)
{
   z = getchar();
   input[i] = z;
}

The weird thing is that it works not only for ASCII characters, but for any character I imagine, such as @&@{čřžŧ¶'`[łĐŧđж←^€~[←^ø{&}čž on the input.
My question is - how is it possible? It seems to be one of many beautiful exceptions in C, but I would really appreciate explanation. Is it a matter of OS, compiler, hidden language's additional super-feature?
Thanks.

A: ASCII is 7 bits, not 8 bits.  a char [] holds bytes, which can be in any encoding - iso8859-1, utf-8, whatever you want.  C doesn't care.

A: This is the magic of UTF-8, that you don't even had to worry about how it works. The only problem is that the C data-type is named char (for character), while what it actually means is byte. there is no 1:1 correspondence between characters and the bytes that encode them.
What happens in your code is that, from the program's point of view, you input a sequence of bytes, it stores the bytes in memory and if you print the text it prints bytes. This code doesn't care how these bytes encode the characters, it's only the terminal which needs to worry about encoding them on input and correctly interpreting them on output.

A: There are of course many libraries that does the job, but to quickly decode any UTF8 unicode, this little function is handy:
typedef unsigned char utf8_t;

#define isunicode(c) (((c)&0xc0)==0xc0)

int utf8_decode(const char *str,int *i) {
    const utf8_t *s = (const utf8_t *)str; // Use unsigned chars
    int u = *s,l = 1;
    if(isunicode(u)) {
        int a = (u&0x20)? ((u&0x10)? ((u&0x08)? ((u&0x04)? 6 : 5) : 4) : 3) : 2;
        if(a<6 || !(u&0x02)) {
            int b,p = 0;
            u = ((u<<(a+1))&0xff)>>(a+1);
            for(b=1; b<a; ++b)
                u = (u<<6)|(s[l++]&0x3f);
        }
    }
    if(i) *i += l;
    return u;
}

Considering your code; you can iterate the string and read the unicode values:
int l;
for(i=0; i<20 && input[i]!='\0'; ) {
   if(!isunicode(input[i])) i++;
   else {
      l = 0;
      z = utf8_decode(&input[i],&l);
      printf("Unicode value at %d is U+%04X and it\'s %d bytes.\n",i,z,l);
      i += l;
   }
}

A: There is no magic here - The C language gives you acess to the raw bytes, as they are stored in the computer memory.
If your terminal is using utf-8 (which is likely), non-ASCII chars take more than one byte in memory. When you display then again, is our terminal code which converts these sequences into a single displayed character.
Just change your code to print the strlen of the strings, and you will see what I mean.
To properly handle utf-8 non-ASCII chars in C you have to use some library to handle them for you, like glib, qt, or many others.

A: ASCII is a 7 bit character set. In C normally represented by an 8 bit char. If highest bit in an 8 bit byte is set, it is not an ASCII character.
Also notice that you are not guaranteed ASCII as base, tho many ignore other scenarios. If you want to check if a "primitive" byte is a alpha character you can in other words not, when taking heed to all systems, say:
is_alpha = (c > 0x40 && c < 0x5b) || (c > 0x60 && c < 0x7b);

Instead you'll have to use ctype.h and say:
isalpha(c);

Only exception, AFAIK, is for numbers, on most tables at least, they have contiguous values.
Thus this works;
char ninec  = '9';
char eightc = '8';

int nine  = ninec  - '0';
int eight = eightc - '0';

printf("%d\n", nine);
printf("%d\n", eight);

But this is not guaranteed to be 'a':
alhpa_a = 0x61;

Systems not based on ASCII, i.e. using EBCDIC; C on such a platform still runs fine but here they (mostly) use 8 bits instead of 7 and i.e. A can be coded as decimal 193 and not 65 as it is in ASCII.

For ASCII however; bytes having decimal 128 - 255, (8 bits in use), is extended, and not part of the ASCII set. I.e. ISO-8859 uses this range.
What is often done; is also to combine two or more bytes to one character. So if you print two bytes after each other that is defined as say, utf8 0xc3 0x98 == Ø, then you'll get this character.
This again depends on which environment you are in. On many systems/environments printing ASCII values give same result across character sets, systems etc. But printing bytes > 127 or double byted characters gives a different result depending on local configuration.
I.e.:
Mr. A running the program gets
Jasŋ€
While Mr. B gets
Jasπß
This is perhaps especially relevant to the ISO-8859 series and Windows-1252 of single byte representation of extended characters, etc.

*

*ASCII_printable_characters , notice they are 7 not 8 bits.

*ISO_8859-1 and ISO_8859-15, widely used sets, with ASCII as core.

*Windows-1252, legacy of Windows.

*

*UTF-8#Codepage_layout, In UTF-8 you have ASCII, then you have special sequences of byes.

*

*Each sequence starts with a byte > 127 (which is last ASCII byte),

*followed by a given number of bytes which all starts with the bits 10.

*In other words, you will never find an ASCII byte in a multi byte UTF-8 representation.

That is; the first byte in UTF-8, if not ASCII, tells how many bytes this character has. You could also say ASCII characters say no more bytes follow - because highest bit is 0.
I.e if file interpreted as UTF-8:
fgetc(c);

if c  < 128, 0x80, then ASCII
if c == 194, 0xC2, then one more byte follow, interpret to symbol
if c == 226, 0xE2, then two more byte follows, interpret to symbol
...

As an example. If we look at one of the characters you mention. If in an UTF-8 terminal:

$ echo -n "č" | xxd

Should yield:

0000000: c48d                                     ..

In other words "č" is represented by the two bytes 0xc4 and 0x8d. Add -b to the xxd command and we get the binary representation of the bytes. We dissect them as follows:
 ___  byte 1 ___     ___ byte 2 ___
|               |   |              |
0xc4 : 1100 0100    0x8d : 1000 1101
       |                    |
       |                    +-- all "follow" bytes starts with 10, rest: 00 1101
       |
       + 11 -> 2 bits set = two byte symbol, the "bits set" sequence
               end with 0. (here 3 bits are used 110) : rest 0 0100

Rest bits combined: xxx0 0100 xx00 1101 => 00100001101
                       \____/   \_____/
                         |        |
                         |        +--- From last byte
                         +------------ From first byte

This give us: 00100001101 2 = 26910 = 0x10D => Uncode codepoint U+010D == "č".

This number can also be used in HTML as č == č
Common for this and lots of other code systems is that an 8 bit byte is the base.

Often it is also a question about context. As an example take GSM SMS, with ETSI GSM 03.38/03.40 (3GPP TS 23.038, 3GPP 23038). There we also find an 7bit character table, 7-bits GSM default alphabet, but instead of storing them as 8 bits they are stored as 7 bits1. This way you can pack more characters into a given number of bytes. Ie standard SMS 160 characters becomes 1280 bits or 160 bytes as ASCII and 1120 or 140 bytes as SMS.
1 Not without exception, (it is more to the story).
I.e. a simple example of bytes saved as septets (7bit) C8329BFD06 in SMS UDP format to ASCII:
                                _________
7 bit UDP represented          |         +--- Alphas has same bits as ASCII
as 8 bit hex                   '0.......'
C8329BFDBEBEE56C32               1100100 d * Prev last 6 bits + pp 1
 | | | | | | | | +- 00 110010 -> 1101100 l * Prev last 7 bits
 | | | | | | | +--- 0 1101100 -> 1110010 r * Prev 7 + 0 bits
 | | | | | | +----- 1110010 1 -> 1101111 o * Last 1 + prev 6
 | | | | | +------- 101111 10 -> 1010111 W * Last 2 + prev 5
 | | | | +--------- 10111 110 -> 1101111 o * Last 3 + prev 4
 | | | +----------- 1111 1101 -> 1101100 l * Last 4 + prev 3
 | | +------------- 100 11011 -> 1101100 l * Last 5 + prev 2
 | +--------------- 00 110010 -> 1100101 e * Last 6 + prev 1
 +----------------- 1 1001000 -> 1001000 H * Last 7 bits
                                 '------'
                                    |
                                    +----- GSM Table as binary

And 9 bytes "unpacked" becomes 10 characters.

A: There is a datatype wint_t (#include <wchar.h>) for non-ASCII characters.  You can use the method getwchar() to read them.


text:
Q: How to Get Custom Stateful Widget value in another class widget? In My Applicatios's first Page user will select the No from 1 to 10, after selecting the number my second page will display the 5 GradeScreen widget if user select 5, like wise i can create widget using below code, but i can't get the values which user selects from dropdownbutton widget in my GradeScreen widget,
Please help me to get value from this GradeScreen widget.
I'm New to Flutter.
Thanks in Advance.
import 'package:flutter/material.dart';

class CalculateCGPAScreen extends StatelessWidget {
  final int noOfSubjectsCount;

  CalculateCGPAScreen(this.noOfSubjectsCount);

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(),
      body: Column(
        children: noOfSubjects(noOfSubjectsCount),
      ),
    );
  }

  List<Widget> noOfSubjects(int subjectCount) {
    List<Widget> list = [];
    for (int i = 1; i <= subjectCount; i++) {
      list.add(GradeScreen("Subject $i", 1));
    }
    list.add(RaisedButton(
      onPressed: () {},
      color: Colors.amber,
      splashColor: Colors.amberAccent,
      child: Text("Calculate CGPA"),
    ));
    return list;
  }
}

class GradeScreen extends StatefulWidget {
  final String subjectName;
  final int gradeSystem;

  GradeScreen(this.subjectName, this.gradeSystem);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _GradeScreenState();
  }
}

class _GradeScreenState extends State<GradeScreen> {
  String selectedGrade = "S";
  List<int> creditList = [1, 2, 3, 4, 5, 6];
  int selectedCredit = 1;

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: <Widget>[
        Text(widget.subjectName),
        DropdownButton(
          items: getGradeList(widget.gradeSystem).map((String loopValue) {
            return DropdownMenuItem(
              child: Text(loopValue),
              value: loopValue,
            );
          }).toList(),
          onChanged: (String value) {
            setState(() {
              selectedGrade = value;
            });
          },
          value: selectedGrade,
        ),
        DropdownButton(
          items: creditList.map((int credit) {
            return DropdownMenuItem(
              child: Text(credit.toString()),
              value: credit,
            );
          }).toList(),
          onChanged: (int value) {
            setState(() {
              selectedCredit = value;
            });
          },
          value: selectedCredit,
        )
      ],
    );
  }

  List<String> getGradeList(int option) {
    List<String> gradeSystem;
    if (option == 1) {
      gradeSystem = ['S', 'A', 'B', 'C', 'D', 'E'];
    } else {
      gradeSystem = ['O', 'A+', 'A', 'B+', 'B'];
    }
    return gradeSystem;
  }
}

A: import 'package:flutter/material.dart';

class CalculateCGPAScreen extends StatelessWidget {
  final int noOfSubjectsCount;

  CalculateCGPAScreen(this.noOfSubjectsCount);

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(),
      body: Column(
        children: noOfSubjects(noOfSubjectsCount),
      ),
    );
  }

  List<Widget> noOfSubjects(int subjectCount) {
    List<Widget> list = [];
    for (int i = 1; i <= subjectCount; i++) {
      list.add(GradeScreen("Subject $i", 1));
    }
    list.add(RaisedButton(
      onPressed: () {
        for (var item in list) {
          if (item is GradeScreen) {
            GradeScreen gs = item;
            print(gs.grade);
            print(gs.credit);
          }
        }
      },
      color: Colors.amber,
      splashColor: Colors.amberAccent,
      child: Text("Calculate CGPA"),
    ));
    return list;
  }
}

class GradeScreen extends StatefulWidget {
  final String subjectName;
  final int gradeSystem;
  int _credit;
  String _grade;
  GradeScreen(this.subjectName, this.gradeSystem);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _GradeScreenState();
  }

  set credit(int value) {
    _credit = value;
  }

  get credit => _credit;

  set grade(String value) {
    _grade = value;
  }

  get grade => _grade;
}

class _GradeScreenState extends State<GradeScreen> {
  String selectedGrade = "S";
  List<int> creditList = [1, 2, 3, 4, 5, 6];
  int selectedCredit = 1;

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: <Widget>[
        Text(widget.subjectName),
        DropdownButton(
          items: getGradeList(widget.gradeSystem).map((String loopValue) {
            return DropdownMenuItem(
              child: Text(loopValue),
              value: loopValue,
            );
          }).toList(),
          onChanged: (String value) {
            setState(() {
              selectedGrade = value;
              widget.grade = value;
            });
          },
          value: selectedGrade,
        ),
        DropdownButton(
          items: creditList.map((int credit) {
            return DropdownMenuItem(
              child: Text(credit.toString()),
              value: credit,
            );
          }).toList(),
          onChanged: (int value) {
            setState(() {
              selectedCredit = value;
              widget.credit = value;
            });
          },
          value: selectedCredit,
        )
      ],
    );
  }

  List<String> getGradeList(int option) {
    List<String> gradeSystem;
    if (option == 1) {
      gradeSystem = ['S', 'A', 'B', 'C', 'D', 'E'];
    } else {
      gradeSystem = ['O', 'A+', 'A', 'B+', 'B'];
    }
    return gradeSystem;
  }
}

Change the dropdown value and get the result into debug console.

A: import 'package:flutter/material.dart';

class CalculateCGPAScreen extends StatelessWidget {
  final int noOfSubjectsCount;

  CalculateCGPAScreen(this.noOfSubjectsCount);

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(),
      body: Column(
        children: noOfSubjects(noOfSubjectsCount),
      ),
    );
  }

  List<Widget> noOfSubjects(int subjectCount) {
    List<Widget> list = [];
    for (int i = 1; i <= subjectCount; i++) {
      list.add(GradeScreen("Subject $i", 1));
    }
    list.add(RaisedButton(
      onPressed: () {},
      color: Colors.amber,
      splashColor: Colors.amberAccent,
      child: Text("Calculate CGPA"),
    ));
    return list;
  }
}

class GradeScreen extends StatefulWidget {
  final String subjectName;
  final int gradeSystem;
  int _data;
  GradeScreen(this.subjectName, this.gradeSystem);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _GradeScreenState();
  }

  set data(int value) {
    _data = value;
  }

  get data => _data;
}

class _GradeScreenState extends State<GradeScreen> {
  String selectedGrade = "S";
  List<int> creditList = [1, 2, 3, 4, 5, 6];
  int selectedCredit = 1;

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: <Widget>[
        Text(widget.subjectName),
        DropdownButton(
          items: getGradeList(widget.gradeSystem).map((String loopValue) {
            return DropdownMenuItem(
              child: Text(loopValue),
              value: loopValue,
            );
          }).toList(),
          onChanged: (String value) {
            setState(() {
              selectedGrade = value;
            });
          },
          value: selectedGrade,
        ),
        DropdownButton(
          items: creditList.map((int credit) {
            return DropdownMenuItem(
              child: Text(credit.toString()),
              value: credit,
            );
          }).toList(),
          onChanged: (int value) {
            setState(() {
              selectedCredit = value;
              widget.data = selectedCredit;
            });
          },
          value: selectedCredit,
        )
      ],
    );
  }

  List<String> getGradeList(int option) {
    List<String> gradeSystem;
    if (option == 1) {
      gradeSystem = ['S', 'A', 'B', 'C', 'D', 'E'];
    } else {
      gradeSystem = ['O', 'A+', 'A', 'B+', 'B'];
    }
    return gradeSystem;
  }
}


text:
Q: React State is not updating import React from 'react'

class Help extends React.Component{
  constructor(props){
    super(props);
    this.state={
      friend:[
        {
          name:"ashwani",
          id:"1",
          friend:[
            {
              name:"mayank",
              id:"2",
              friend:[
                {
                  name:"prakhar",
                  id:"3",
                  friend:[]
                }
              ]
            },
            {
              name:"anand",
              id:"4",
              friend:[]
            },
            {
              name:"manish",
              id:"5",
              friend:[]
            }
          ]
        }
      ]
    }
  }

  render(){
    return (

        {this.state.friend.map((item, index) => <Item key={index} {...item} />)}

    )
  }
}
class Item extends React.Component {
  addFriend(friend){
    friend.push({name:"GOD",friend:[]});
    console.log(friend);
  }
  render() {
    const { name, friend } = this.props;
    return (

{name}

          <button type="button" onClick={()=>this.addFriend(friend)}>add friend</button>
     strong text
          {friend && friend.map((item, index) => <Item key={index} {...item} />)}

    )
  }
}
export default Help;

React state is not updating i know i have done in a wrong way but i don't have any idea how to do it so what i am trying is their is button which will add friend in nested friend array which ever friend required another friend that friend is God it can be added as many time as u click the button, button is for every friend array present so that they don't feel lonely and can add friend whenever they want , this is just a usecase in my project so, any kind of help will be greatly appreciated

A: Storing your state in such a way makes it quite difficult to deal with, but it should be possible to make it work. Your problem is, that you are trying to mutate state, which isn't allowed in React. In order to update state you have to use this.setState and in your case, some extra complex code is needed:
import React from 'react'

class Help extends React.Component{
  constructor(props){
    super(props);
    this.state={
      friend:[
        {
          name:"ashwani",
          id:"1",
          friend:[
            {
              name:"mayank",
              id:"2",
              friend:[
                {
                  name:"prakhar",
                  id:"3",
                  friend:[]
                }
              ]
            },
            {
              name:"anand",
              id:"4",
              friend:[]
            },
            {
              name:"manish",
              id:"5",
              friend:[]
            }
          ]
        }
      ]
    }
  }

  updateFriends = (friendIndex) => (newFriendValue) => {
    this.setState(prevFriends => {
      let newFriends = Array.from(prevFriends);
      newFriends[friendIndex] = newFriendValue;

      return { friend: newFriends };
    })
  }

  render(){
    return (

        {this.state.friend.map((item, index) => <Item key={index} {...item} updateFriends={this.updateFriends(index)} />)}

    )
  }
}
class Item extends React.Component {
  addFriend(friend){
    let newFriends = [...this.props.friend, {name:"GOD",friend:[]}];

    this.props.updateFriends({ name: this.props.name, friend: newFriends })
  }

  updateFriends = (friendIndex) => (newFriendValue) => {
    let newFriends = Array.from(this.props.friend);
    newFriends[friendIndex] = newFriendValue;

    this.props.updateFriends({ name: this.props.name, friend: newFriends })
  }

  render() {
    const { name, friend } = this.props;
    return (

{name}

          <button type="button" onClick={()=>this.addFriend(friend)}>add friend</button>
     strong text
          {friend && friend.map((item, index) => <Item key={index} {...item} updateFriends={this.updateFriends(index)} />)}

    )
  }
}

export default Help;

Feel free to ask for any clarifications!

A: State is not updating because you are not calling this.setState(); to set the friends in the parent.


text:
Q: Getting value of type 'text' from mySQL database
Possible Duplicate:
PHP: "Notice: Undefined variable"  and "Notice: Undefined index"

I am new to PHP and mySQL and this is a section of my program, but what happens is that it doesn't return the value of the column 'Text' from the database, rather, it says 'Undefined index 'Text''. I am 100% sure that it exists in the database. Can someone please help me?
$method_get_article = "SELECT TEXT FROM ARTICLE WHERE UID = '$user_id' LIMIT 1";
$get_article = mysql_query($method_get_article, $conn) or die (mysql_error());
$article = mysql_fetch_array($get_article);**strong text**
$text = $article['Text'];
//$row = mysql_fetch_assoc($get_article);
//$text = $row['Text'];
echo $text;

A: The error explains the problem very clearly : 'Undefined index 'Text'
In the beginning you write:
$method_get_article = "SELECT TEXT FROM ARTICLE WHERE UID = '$user_id' LIMIT 1";

which means you select the column called "TEXT", and then later you write:
$text = $article['Text'];

which gets the column called "Text".
Change them so that they are identical.


text:
Q: Why doesn't my theme show up in LightDm Greeter? I am using axiomd theme on my computer (xubuntu) but when I change the theme in /etc/lightdm/lightdm-gtk-greeter.conf it doesn't change the theme of the login screen.
Going through the LightDM GTK+ Greeter: settings doesn't work either. It only shows 4 themes I can choose from, even though I have around 20 themes in /usr/share/themes.

A: The themes have to be complete gtk themes; not just windows or icon themes, nor metacity themes.
Look in /usr/share/lightdm/lightdm-gtk-greeter.conf.d for a customization file. I usually takes precedence over /etc/lightdm/lightdm-gtk-greeter.conf.

A: For future reference, LightDM might not have access to your theme. Chmoding the theme folder worked for me.


text:
Q: Size of a bitfield member? Would anyone know how to extract the size of a bit-field member.  The below code naturally gives me the size of an integer, but how do I find out how many bits or bytes are in mybits.one? I've tried sizeof(test.one) but which clearly won't work.   I realize this is a measure of bits:
#include <iostream>

using namespace std;

int main()
{
    struct mybits {
        unsigned int one:15;
    };

    mybits test;
    test.one = 455;
    cout << test.one << endl;
    cout << "The size of test.one is:  " << sizeof(test) << endl;
}

A: The draft C++ standard says sizeof shall not be applied to a bit-field in section 5.3.3 Sizeof paragraph 1. If you have control of the source then using an enum sounds much simpler and neater:
struct mybits
{
    enum bitFieldSizes
    {
        field1 = 15,
        field2 = 2,
        field3 = 4,
        field4 = 8,
        field5 = 31
    };

    unsigned int one : field1 ;
    unsigned int two : field2 ;
    unsigned int three : field3 ;
    unsigned int four : field4 ;
    unsigned int five : field5 ;
};

If you don't have control of the source it is possible to use bit hacks to obtain the size of your bit-field and std::bitset makes it easier:
#include <iostream>
#include <bitset>

struct mybits
{
    unsigned int one : 15 ;
    unsigned int two : 2 ;
    unsigned int three : 4 ;
    unsigned int four : 8 ;
    unsigned int five : 31 ;
};

int main()
{
    mybits mb1 ;

    mb1.one   =  ~0 ;
    mb1.two   =  ~0 ;
    mb1.three =  ~0 ;
    mb1.four  =  ~0 ;
    mb1.five  =  ~0 ;

    std::bitset<sizeof(unsigned int)*8> b1(mb1.one);
    std::bitset<sizeof(unsigned int)*8> b2(mb1.two);
    std::bitset<sizeof(unsigned int)*8> b3(mb1.three);
    std::bitset<sizeof(unsigned int)*8> b4(mb1.four);
    std::bitset<sizeof(unsigned int)*8> b5(mb1.five);

    std::cout << b1 << ":" << b1.count() << std::endl ;
    std::cout << b2 << ":" << b2.count() << std::endl ;
    std::cout << b3 << ":" << b3.count() << std::endl ;
    std::cout << b4 << ":" << b4.count() << std::endl ;
    std::cout << b5 << ":" << b5.count() << std::endl ;
}

which produces the following output:
00000000000000000111111111111111:15
00000000000000000000000000000011:2
00000000000000000000000000001111:4
00000000000000000000000011111111:8
01111111111111111111111111111111:31

A: Runtime solution, the idea from this discussion: http://social.msdn.microsoft.com/Forums/en-US/7e4f01b6-2e93-4acc-ac6a-b994702e7b66/finding-size-of-bitfield
#include <iostream>
using namespace std;

int BitCount(unsigned int value)
{
    int result = 0;

    while(value)
    {
        value &= (value - 1);
        ++result;
    }

    return result;
}

int main()
{
    struct mybits {
        unsigned int one:15;
    };

    mybits test;
    test.one = ~0;

    cout << BitCount(test.one) << endl;

    return 0;
}

Prints 15.

A: A compile-time solution using constexpr:
struct S
{
    unsigned int a : 4;
    unsigned int b : 28;
};

#define GET_BIT_FIELD_WIDTH(T, f) \
    []() constexpr -> unsigned int \
    { \
        T t{}; \
        t.f = ~0; \
        unsigned int bitCount = 0; \
        while (t.f != 0) \
        { \
            t.f >>= 1; \
            ++bitCount; \
        } \
        return bitCount; \
    }()

int main()
{
    constexpr auto a = GET_BIT_FIELD_WIDTH(S, a);
    constexpr auto b = GET_BIT_FIELD_WIDTH(S, b);
    static_assert(a == 4);
    static_assert(b == 28);
}

I think it does not invoke any undefined behavior, but it does invoke some implementation-defined behavior:

*

*Wrap-around of bit-fields is implementation-defined.

*Above solution will not work for signed fields if right-shift of signed fields uses sign-extension (implemented-defined). The compiler will hit an infinite loop in that case.

A: Because of padding it is not possible to see number of bits in a bit field using sizeof operator.
The only way is to open up the header where the structure is defined, and look it up.

A: There is no way to get this information (apart from reading the declaration yourself). As per the standard, [C++11]expr.sizeof§1, it's illegal to call sizeof on a bit-field:

The sizeof operator shall not be applied to ... an lvalue that designates a bit-field.

A: Here is a little bit tricky generalized version:
#include <iostream>
#include <limits>
#include <bitset>
#include <cstring>
using namespace std;

template <class T>
T umaxof()
{
      T t;
      memset(&t, 0xFF, sizeof(T));
      return t;
}

template <class T>
size_t bitsof(const T& umax)
{
    return bitset<sizeof(T)*8>(umax).count();
}

int main()
{
    struct A
    {
        uint32_t bf1:19;
        uint32_t bf2:1;
    };

    cout << bitsof(umaxof<A>().bf1) << "\n";
    cout << bitsof(umaxof<A>().bf2) << "\n";

    return 0;
}

It can be tried out at https://ideone.com/v4BiBH
Note: Works with unsigned bit fields only.


text:
Q: Windows desktop search fails to search inside .SQL files I've set the index options for the .SQL extension to use "Plain Text filter" with "Index Properties and File Contents" selected, and ensure that the directories containing the SQL files are in the "Included Locations".
Unfortunately, Windows desktop search still fails to find anything in the .SQL files. Other file types such as .cs, .docx etc are searched successfully.
I'm running Windows XP SP2 - and it's a work machine where I can't easily install alternative search engines so I'm stuck with Windows Desktop search for indexed searching.
Obviously I can search the .SQL files using other (non-indexed) techniques, but I prefer the speed of Desktop Search - if I could get it to work.
Update: Having copied a couple of .SQL files to .SQL.TXT files in the same directory as suggested by ~quack, added .SQL.TXT as a file extension to the indexing options (using the plain text filter, with "Index Properties and File Contents" selected) and re-indexing, Desktop Search still fails to find strings in either the .SQL or .SQL.TXT files.
Additional info: after re-indexing, I checked the file types in the Desktop Search advanced options and noted that the .SQL.TXT file extension no longer appears in the list of file types.

A: This might not be relevant, but for things like this I really like using the command-line. It's really quick and allows you to specify regular expressions and other features like matching the beginning  (or end) of a line.

*

*Hold down shift, and right-click the directory you want to search

*Choose 'Open Command Window Here'

*Type findstr "order by" *.sql

*If you want to search sub-directories also, just use findstr /S "order by" *.sql
This will return all files named *.sql with the string "order by" in them. There are lots of command line switches to include things like line numbers, just type findstr /?

A: This would obviously be suboptimal, but have you tried copying the .SQL files to .TXT files?
I don't mean simply rename, since you are presumably using the SQL files as SQL files somewhere.  But if you have the space, make copies and rename those to .SQL.TXT or so.  If your SQL files change frequently, schedule a task to re-create the copies.
This would be worthwhile as an experiment -- if Windows Desktop Search can successfully index a .SQL.TXT file, there's something about the .SQL extension that it's failing on.  If it can't, something about the file's format is confusing it.

A: Just use Qytec's free Portable File Seeker instead of Windows Desktop Search. It can successfully search within files with provided extensions. You don't need to install it since it's portable. I tried it on my .SQL files and it works without any problems. Here is a screeny from my PC:

A: I think (but I'm not sure) you'll need to install an iFilter for SQL into the Windows Desktop Search engine. Take a look here.


text:
Q: Why hyperopt is giving the best loss Nan while operating in Random Forest? I am solving a Kaggle Problem: https://www.kaggle.com/c/forest-cover-type-prediction/data
I used hyperopt to find optimal hyperparameter for Random Forest. But I am stuck here, as for almost most of the iteration it is giving best loss: Nan.
My Full Code :
import pandas as pd
import numpy as np

# Lets Load the Dataset

train = pd.read_csv(r"D:\Study Material\Py_Programs\Data Sets\forest-cover-type-prediction\train.csv")
test =  pd.read_csv(r"D:\Study Material\Py_Programs\Data Sets\forest-cover-type-prediction\test.csv")

# Lets Append all together so that we can study altogether
# Lets not include test_2 for a while

test['Cover_Type'] = np.nan
data = train.append(test,ignore_index = True)
del train,test

# Lets Now do Feature Engineering
# We could do Manula Feature Engineering but lets not do it
# Lets use feature Tools
# Lets first create a simple new attribute that can later be index for Soil Enity

data['Id_Soil'] = np.arange(len(data))

import featuretools as ft
es = ft.EntitySet(id = 'forest')
es = es.entity_from_dataframe(entity_id = 'Forest_Pred',dataframe = data,index = 'Id')

>>> es
Entityset: forest
  Entities:
    Forest_Pred [Rows: 581012, Columns: 63]
  Relationships:
    No relationships

# Lets Make a Seperate Entity for Soil
Additional_Variable = data.columns[data.columns.str.startswith('Soil')]
Additional_Variable
es = es.normalize_entity(base_entity_id = 'Forest_Pred',new_entity_id = 'Soil',index = 'Id_Soil',additional_variables =
                        list(Additional_Variable))

>>>es
Entityset: forest
  Entities:
    Forest_Pred [Rows: 581012, Columns: 23]
    Soil [Rows: 581012, Columns: 41]
  Relationships:
    Forest_Pred.Id_Soil -> Soil.Id_Soil

# Lets Run DFS
feature_matrix,feature_defs = ft.dfs(entityset = es,target_entity = 'Forest_Pred')

drop_cols = []
for col in feature_matrix:
    if col == 'Cover_Type':
        pass
    else:
        if 'Cover_Type' in col:
            drop_cols.append(col)

feature_matrix = feature_matrix[[x for x in feature_matrix if x not in drop_cols]]
feature_matrix.head()

# Create correlation matrix
corr_matrix = feature_matrix.corr().abs()
# Select upper triangle of correlation matrix
upper = corr_matrix.where(np.triu(np.ones(corr_matrix.shape), k=1).astype(np.bool))
# Find index of feature columns with correlation greater than 0.95
to_drop = [column for column in upper.columns if any(upper[column] >= 0.95)]

print('There are {} columns with >= 0.95 correlation.'.format(len(to_drop)))

>>>to_drop

There are 83 columns with >= 0.95 correlation.

# These are the Redundant Columns

['New2',      # I manually created New2, Hill1 and Hill3
 'Hill1',
 'Hill3',
 'Soil.SUM(Forest_Pred.wild1)',
 'Soil.SUM(Forest_Pred.Vertical_Distance_To_Hydrology)',
 'Soil.SUM(Forest_Pred.Hillshade_Noon)',
 'Soil.SUM(Forest_Pred.Horizontal_Distance_To_Roadways)',
 'Soil.SUM(Forest_Pred.Slope)',
 'Soil.SUM(Forest_Pred.Wilderness_Area4)',
 'Soil.SUM(Forest_Pred.New4)',
 'Soil.SUM(Forest_Pred.Hill2)',
 'Soil.SUM(Forest_Pred.New2)',
 'Soil.SUM(Forest_Pred.Wilderness_Area2)',
 'Soil.SUM(Forest_Pred.Horizontal_Distance_To_Hydrology)',
 'Soil.SUM(Forest_Pred.Hillshade_9am)',
 'Soil.SUM(Forest_Pred.Aspect)',
 'Soil.SUM(Forest_Pred.Hillshade_3pm)',
 'Soil.SUM(Forest_Pred.Hill1)',
 'Soil.SUM(Forest_Pred.Hill3)',
 'Soil.SUM(Forest_Pred.Elevation)',
 'Soil.SUM(Forest_Pred.Wilderness_Area3)',
 'Soil.SUM(Forest_Pred.Horizontal_Distance_To_Fire_Points)',
 'Soil.SUM(Forest_Pred.Wilderness_Area1)',
 'Soil.MAX(Forest_Pred.wild1)',
 'Soil.MAX(Forest_Pred.Vertical_Distance_To_Hydrology)',
 'Soil.MAX(Forest_Pred.Hillshade_Noon)',
 'Soil.MAX(Forest_Pred.Horizontal_Distance_To_Roadways)',
 'Soil.MAX(Forest_Pred.Slope)',
 'Soil.MAX(Forest_Pred.Wilderness_Area4)',
 'Soil.MAX(Forest_Pred.New4)',
 'Soil.MAX(Forest_Pred.Hill2)',
 'Soil.MAX(Forest_Pred.New2)',
 'Soil.MAX(Forest_Pred.Wilderness_Area2)',
 'Soil.MAX(Forest_Pred.Horizontal_Distance_To_Hydrology)',
 'Soil.MAX(Forest_Pred.Hillshade_9am)',
 'Soil.MAX(Forest_Pred.Aspect)',
 'Soil.MAX(Forest_Pred.Hillshade_3pm)',
 'Soil.MAX(Forest_Pred.Hill1)',
 'Soil.MAX(Forest_Pred.Hill3)',
 'Soil.MAX(Forest_Pred.Elevation)',
 'Soil.MAX(Forest_Pred.Wilderness_Area3)',
 'Soil.MAX(Forest_Pred.Horizontal_Distance_To_Fire_Points)',
 'Soil.MAX(Forest_Pred.Wilderness_Area1)',
 'Soil.MIN(Forest_Pred.wild1)',
 'Soil.MIN(Forest_Pred.Vertical_Distance_To_Hydrology)',
 'Soil.MIN(Forest_Pred.Hillshade_Noon)',
 'Soil.MIN(Forest_Pred.Horizontal_Distance_To_Roadways)',
 'Soil.MIN(Forest_Pred.Slope)',
 'Soil.MIN(Forest_Pred.Wilderness_Area4)',
 'Soil.MIN(Forest_Pred.New4)',
 'Soil.MIN(Forest_Pred.Hill2)',
 'Soil.MIN(Forest_Pred.New2)',
 'Soil.MIN(Forest_Pred.Wilderness_Area2)',
 'Soil.MIN(Forest_Pred.Horizontal_Distance_To_Hydrology)',
 'Soil.MIN(Forest_Pred.Hillshade_9am)',
 'Soil.MIN(Forest_Pred.Aspect)',
 'Soil.MIN(Forest_Pred.Hillshade_3pm)',
 'Soil.MIN(Forest_Pred.Hill1)',
 'Soil.MIN(Forest_Pred.Hill3)',
 'Soil.MIN(Forest_Pred.Elevation)',
 'Soil.MIN(Forest_Pred.Wilderness_Area3)',
 'Soil.MIN(Forest_Pred.Horizontal_Distance_To_Fire_Points)',
 'Soil.MIN(Forest_Pred.Wilderness_Area1)',
 'Soil.MEAN(Forest_Pred.wild1)',
 'Soil.MEAN(Forest_Pred.Vertical_Distance_To_Hydrology)',
 'Soil.MEAN(Forest_Pred.Hillshade_Noon)',
 'Soil.MEAN(Forest_Pred.Horizontal_Distance_To_Roadways)',
 'Soil.MEAN(Forest_Pred.Slope)',
 'Soil.MEAN(Forest_Pred.Wilderness_Area4)',
 'Soil.MEAN(Forest_Pred.New4)',
 'Soil.MEAN(Forest_Pred.Hill2)',
 'Soil.MEAN(Forest_Pred.New2)',
 'Soil.MEAN(Forest_Pred.Wilderness_Area2)',
 'Soil.MEAN(Forest_Pred.Horizontal_Distance_To_Hydrology)',
 'Soil.MEAN(Forest_Pred.Hillshade_9am)',
 'Soil.MEAN(Forest_Pred.Aspect)',
 'Soil.MEAN(Forest_Pred.Hillshade_3pm)',
 'Soil.MEAN(Forest_Pred.Hill1)',
 'Soil.MEAN(Forest_Pred.Hill3)',
 'Soil.MEAN(Forest_Pred.Elevation)',
 'Soil.MEAN(Forest_Pred.Wilderness_Area3)',
 'Soil.MEAN(Forest_Pred.Horizontal_Distance_To_Fire_Points)',
 'Soil.MEAN(Forest_Pred.Wilderness_Area1)']

# Lets get the feature first
# Lets Now Look at the NULL Values

Null_Values = pd.DataFrame(train.isnull().sum()).rename(columns = {0 : 'Total'})
Null_Values['Percentage'] = Null_Values['Total']/len(train)
Null_Values.sort_values('Percentage',ascending = False)
Fully_Null_Columns = Null_Values.loc[Null_Values['Percentage'] == 1.0]
To_Remove = Fully_Null_Columns.index

Feature = list(train.columns)
for Val in To_Remove:
    Feature.remove(Val)

>>>len(Feature)
58

Pipe = Pipeline([
    ('impute',Imputer(strategy = 'median')),
    ('scaler',MinMaxScaler())
])
train = Pipe.fit_transform(train)
test = Pipe.transform(test)

######################## Hyperopt Part Begins From Here ###############################333

# Lets Apply Hyperopt to Optimize the Two Model that we think may do good Random Forest and MLP
# lETS fIRST dO For Random Forest
#Lets Define The Objective Function for it

from hyperopt import STATUS_OK

def Objective_Forest(params):
    classifier = RandomForestClassifier(**params)
    score = cross_val_score(classifier,train,Target,cv = 10,scoring = scorer)
    Best_Score = 1 - np.mean(score)
    return {'loss': Best_Score,'params':params,'status':STATUS_OK}

# lETS DEFINE THE PARAMETER SPACE FOR THE RANDOM FOREST CLASSIFIER
from hyperopt import hp
Param_grid = {
    'n_estimators': hp.choice('n_estimators',range(10,1000)),
    'max_depth' : hp.choice('max_depth',range(1,20)),
    'min_samples_split': hp.choice('min_samples_split',range(2,20)),
    'min_samples_leaf': hp.choice('min_samples_leaf',range(1,11)),
    'min_weight_fraction_leaf': hp.uniform('min_weight_fraction_leaf',0.0,1.0),
    'max_features':hp.choice('max_features',["sqrt", "log2","None",0.2,0.5,0.8]),
    'max_leaf_nodes':hp.choice('max_leaf_nodes',range(10,150)),
    'min_impurity_decrease':hp.uniform('min_impurity_decrease',0.0,1.0),
    'class_weight':hp.choice('class_weight',[None,'balanced']),
    'max_samples':hp.uniform('max_samples',0.0,1.0)
}

from hyperopt import tpe
tpe_algo = tpe.suggest

from hyperopt import Trials
bayes_trials = Trials()

from hyperopt import fmin
MAX_EVALS = 100
# Optimize
best = fmin(fn = Objective_Forest,space = Param_grid,algo = tpe_algo,max_evals = MAX_EVALS,trials = bayes_trials)

>>> [print(t['result'],end = '\n\n\n') for t in bayes_trials.trials]

{'loss': nan, 'params': {'class_weight': 'balanced', 'max_depth': 1, 'max_features': 'None', 'max_leaf_nodes': 33, 'max_samples': 0.4660771469206677, 'min_impurity_decrease': 0.45511437833393464, 'min_samples_leaf': 10, 'min_samples_split': 8, 'min_weight_fraction_leaf': 0.9339453161850745, 'n_estimators': 972}, 'status': 'ok'}

{'loss': nan, 'params': {'class_weight': None, 'max_depth': 11, 'max_features': 'log2', 'max_leaf_nodes': 49, 'max_samples': 0.14947278280397347, 'min_impurity_decrease': 0.2358674422658822, 'min_samples_leaf': 9, 'min_samples_split': 16, 'min_weight_fraction_leaf': 0.5935700756502073, 'n_estimators': 436}, 'status': 'ok'}

{'loss': nan, 'params': {'class_weight': None, 'max_depth': 16, 'max_features': 'None', 'max_leaf_nodes': 64, 'max_samples': 0.008126252217055763, 'min_impurity_decrease': 0.5860665211910298, 'min_samples_leaf': 3, 'min_samples_split': 14, 'min_weight_fraction_leaf': 0.7589621329866701, 'n_estimators': 544}, 'status': 'ok'}

{'loss': nan, 'params': {'class_weight': None, 'max_depth': 13, 'max_features': 'None', 'max_leaf_nodes': 88, 'max_samples': 0.8342507642254701, 'min_impurity_decrease': 0.29169826447891134, 'min_samples_leaf': 9, 'min_samples_split': 14, 'min_weight_fraction_leaf': 0.5732868446872494, 'n_estimators': 759}, 'status': 'ok'}

{'loss': 0.514714207538852, 'params': {'class_weight': None, 'max_depth': 4, 'max_features': 'sqrt', 'max_leaf_nodes': 104, 'max_samples': 0.10435155448150135, 'min_impurity_decrease': 0.024801820935633656, 'min_samples_leaf': 5, 'min_samples_split': 10, 'min_weight_fraction_leaf': 0.09350127980207612, 'n_estimators': 739}, 'status': 'ok'}

{'loss': 0.9642857142857143, 'params': {'class_weight': 'balanced', 'max_depth': 5, 'max_features': 'log2', 'max_leaf_nodes': 86, 'max_samples': 0.029032222646389272, 'min_impurity_decrease': 0.4459819146508117, 'min_samples_leaf': 5, 'min_samples_split': 10, 'min_weight_fraction_leaf': 0.16673304793166255, 'n_estimators': 419}, 'status': 'ok'}

{'loss': nan, 'params': {'class_weight': 'balanced', 'max_depth': 1, 'max_features': 'None', 'max_leaf_nodes': 18, 'max_samples': 0.4913763122828826, 'min_impurity_decrease': 0.35382231135300235, 'min_samples_leaf': 3, 'min_samples_split': 18, 'min_weight_fraction_leaf': 0.7421569901774066, 'n_estimators': 354}, 'status': 'ok'}

{'loss': nan, 'params': {'class_weight': 'balanced', 'max_depth': 4, 'max_features': 'sqrt', 'max_leaf_nodes': 69, 'max_samples': 0.27201985914939086, 'min_impurity_decrease': 0.486936153640398, 'min_samples_leaf': 8, 'min_samples_split': 15, 'min_weight_fraction_leaf': 0.7310520866089266, 'n_estimators': 142}, 'status': 'ok'}

{'loss': nan, 'params': {'class_weight': None, 'max_depth': 12, 'max_features': 'sqrt', 'max_leaf_nodes': 36, 'max_samples': 0.9771715541709761, 'min_impurity_decrease': 0.1971412468087903, 'min_samples_leaf': 9, 'min_samples_split': 3, 'min_weight_fraction_leaf': 0.8200016570398415, 'n_estimators': 34}, 'status': 'ok'}

{'loss': 0.9642857142857143, 'params': {'class_weight': None, 'max_depth': 10, 'max_features': 'sqrt', 'max_leaf_nodes': 73, 'max_samples': 0.45641569744506405, 'min_impurity_decrease': 0.8403030256419523, 'min_samples_leaf': 7, 'min_samples_split': 9, 'min_weight_fraction_leaf': 0.0701815156303528, 'n_estimators': 873}, 'status': 'ok'}

{'loss': 0.9642857142857143, 'params': {'class_weight': None, 'max_depth': 17, 'max_features': 'sqrt', 'max_leaf_nodes': 46, 'max_samples': 0.15866300388832533, 'min_impurity_decrease': 0.9297347852530089, 'min_samples_leaf': 7, 'min_samples_split': 6, 'min_weight_fraction_leaf': 0.18404233693328886, 'n_estimators': 121}, 'status': 'ok'}

{'loss': nan, 'params': {'class_weight': 'balanced', 'max_depth': 7, 'max_features': 'None', 'max_leaf_nodes': 104, 'max_samples': 0.0367072640631847, 'min_impurity_decrease': 0.12910648344978914, 'min_samples_leaf': 2, 'min_samples_split': 15, 'min_weight_fraction_leaf': 0.3161712810846662, 'n_estimators': 767}, 'status': 'ok'}

{'loss': nan, 'params': {'class_weight': 'balanced', 'max_depth': 3, 'max_features': 'None', 'max_leaf_nodes': 124, 'max_samples': 0.16440865223966705, 'min_impurity_decrease': 0.391904635576072, 'min_samples_leaf': 1, 'min_samples_split': 7, 'min_weight_fraction_leaf': 0.0811356314154057, 'n_estimators': 347}, 'status': 'ok'}

{'loss': nan, 'params': {'class_weight': 'balanced', 'max_depth': 12, 'max_features': 'log2', 'max_leaf_nodes': 68, 'max_samples': 0.8502406812728349, 'min_impurity_decrease': 0.7058978690401395, 'min_samples_leaf': 2, 'min_samples_split': 16, 'min_weight_fraction_leaf': 0.7016784424128134, 'n_estimators': 938}, 'status': 'ok'}

{'loss': nan, 'params': {'class_weight': 'balanced', 'max_depth': 5, 'max_features': 'log2', 'max_leaf_nodes': 99, 'max_samples': 0.23705851369580344, 'min_impurity_decrease': 0.20836965887913506, 'min_samples_leaf': 7, 'min_samples_split': 3, 'min_weight_fraction_leaf': 0.7453528956610014, 'n_estimators': 468}, 'status': 'ok'}

{'loss': nan, 'params': {'class_weight': None, 'max_depth': 15, 'max_features': 'None', 'max_leaf_nodes': 114, 'max_samples': 0.7084444118326696, 'min_impurity_decrease': 0.986092424730284, 'min_samples_leaf': 3, 'min_samples_split': 14, 'min_weight_fraction_leaf': 0.30715124274867167, 'n_estimators': 743}, 'status': 'ok'}

{'loss': 0.9642857142857143, 'params': {'class_weight': 'balanced', 'max_depth': 10, 'max_features': 'sqrt', 'max_leaf_nodes': 97, 'max_samples': 0.9199683481619908, 'min_impurity_decrease': 0.34148971488668467, 'min_samples_leaf': 5, 'min_samples_split': 10, 'min_weight_fraction_leaf': 0.006984816385200432, 'n_estimators': 386}, 'status': 'ok'}

{'loss': nan, 'params': {'class_weight': None, 'max_depth': 13, 'max_features': 'None', 'max_leaf_nodes': 20, 'max_samples': 0.38036460187991084, 'min_impurity_decrease': 0.8852038598514178, 'min_samples_leaf': 5, 'min_samples_split': 11, 'min_weight_fraction_leaf': 0.06166031048348186, 'n_estimators': 635}, 'status': 'ok'}

{'loss': nan, 'params': {'class_weight': 'balanced', 'max_depth': 5, 'max_features': 'None', 'max_leaf_nodes': 52, 'max_samples': 0.8640312159272309, 'min_impurity_decrease': 0.16823848137945396, 'min_samples_leaf': 1, 'min_samples_split': 9, 'min_weight_fraction_leaf': 0.24162088495434908, 'n_estimators': 564}, 'status': 'ok'}

{'status': 'new'}

[None,
 None,
 None,
 None,
 None,
 None,
 None,
 None,
 None,
 None,
 None,
 None,
 None,
 None,
 None,
 None,
 None,
 None,
 None,
 None,
 None]

I executed the 'fmin' for full iteration but same result. What am I doing Wrong here ???

A: Your loss in Objective_Forest is defined as (1 - np.mean(score), and score is evaluated by cross validation with cross_val_score. The loss, therefore, depends on the output of your cross_val_score function. You are using scorer as the evaluation metric in cross_val_score, but you have not defined it anywhere in your code (was probably defined somewhere else). Your NaN values are most likely due to the kind of scoring you are implementing in your cross validation.
def Objective_Forest(params):
    classifier = RandomForestClassifier(**params)
    score = cross_val_score(classifier,train,Target,cv = 10,scoring = scorer)
    Best_Score = 1 - np.mean(score)
    return {'loss': Best_Score,'params':params,'status':STATUS_OK}


text:
Q: Is there a way for users to invite their friends via LinkedIn using iPhone sdk? I am done with login using linkedIn but I did a lot of goggling and did not find a way to invite friends via LinkedIn. If Somebody have done this then please give me a guidance or tutorial to get rid of this.
Any help will be appreciated..
Thanks in advance

A: Once logged in, you should be able to invite people as friends using LinkedIn's own API. Check out the documentation here. This will involve POSTing XML to the API as described on that page.
Note that there are some "usage guidelines" you'll need to follow, too (The user must be given a choice about whether to send the invitation, etc...)


text:
Q: How to make ajax request for dependent drop down I am new to programming and learning django. I am struggling to understand how to make ajax request to fetch data to create dependent dropdown lists. I have looked around on various google searches and stackoverflow but I get more confused looking at them. Hence, I could not move forward with fetching the dependent values
My code for html looks like this
<select name ="services" id="serviceA">
                                <option disabled selected="true"> -- Select Category -- </option>
                                 {% for item in serv %}"
                                <option value="{{ item.id }}" >{{ item.name }}</option>
                                {% endfor %}
                            </select>

                        <select name ="subcategories" id="subcategoryA">
                            <option disabled selected="true"> -- Select Service -- </option>
                            {% for item2 in subcategory %}"
                            <option value="{{ item2.id }}" >{{ item2.name }}</option>
                            {% endfor %}
                        </select>

My views.py looks like this
def book(request):
employees = Employee.objects.values_list('name',flat=True)
services_ = Service.objects.values_list('name',flat=True)
services = []
serv = Service.objects.all().order_by('-id')
subcategory = SubCategory.objects.all().order_by('-id')
# subcategory = SubCategory.objects.get(pk=request.GET('service_pk'))
for i in services_:
    services.append(i)
    context = {
    'employees':employees,
    'services':services,
    'serv':serv,
    'subcategory':subcategory,
}

return render(request,'book.html',context=context)

my urls.py is set like this among others
path('service/<int:service>', services, name='services'),

my models.py looks like this
def rand_slug():
return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(8))

# Create your models here.

def path_and_rename(instance, filename):
upload_to = 'uploads/images'
ext = filename.split('.')[-1]
# get filename
if instance.pk:
    filename = '{}.{}'.format(instance.pk, ext)
else:
    # set filename as random string
    filename = "PTB-" + '{}.{}'.format(uuid.uuid4().hex[:16], ext)
# return the whole path to the file
return os.path.join(upload_to, filename)

class Service(models.Model):
name = models.CharField(max_length=100,blank=True,null=True)
description = models.CharField(max_length=100,blank=True,null=True)
startprice = models.DecimalField(max_digits=10,default=0.00,decimal_places=2, verbose_name="Starts at")
image = models.ImageField(upload_to=path_and_rename, unique=True, blank=True, null=True, max_length=255, help_text='Please upload picture of 1:1 ratio')

def __str__(self):
    return self.name

class SubCategory(models.Model):
name = models.CharField(max_length=100,blank=True,null=True)
description = models.CharField(max_length=100,blank=True,null=True)
price = models.DecimalField(max_digits=10,default=0.00,decimal_places=2)
image = models.ImageField(upload_to=path_and_rename, unique=True, blank=True, null=True, max_length=255, help_text='Please upload picture of 1:1 ratio')
service = models.ForeignKey(Service, on_delete=models.CASCADE)
slug = AutoSlugField(populate_from=name,max_length=255, unique=True)
on_sale = models.BooleanField(default=False, blank=True, null=True)
discount = models.IntegerField(blank=True,null=True)

def save(self, *args, **kwargs):
    if not self.slug:
        self.slug = slugify(rand_slug() + "_" + (self.name.split().pop(0)))
    super(SubCategory, self).save(*args, **kwargs)

class Meta:
    verbose_name = "Services List"
    verbose_name_plural = "Services Lists"

def __str__(self):
    return self.name

Now, how do you make a ajax request so that my subcategory option changes when I change my service field?
UPDATE
UPDATE I tried to solve jquery based on this video from 24:05 youtubelink  my jquery script is like this. But this does not work...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
    $(document).ready(function()
    {
        var $servicevar=$("#serviceA");
            $subcategoryvar=$("#subcategoryA");

            $options=$subcategoryvar.find('option');
            $servicevar.on('change',function()
            {
                $subcategoryvar.html($options.filter('[value="'+this.value+'"]'));
            }).trigger('change');
    };


text:
Q: How to reset document geometry on floating full page image For my thesis I want some images to use a full-page without creating a page break at the insert AND changing the page document geometry of only the image page.
I have found that \begin{figure}[p] forces a full page dedicated to the figure and this works for me.
I have found that \usepackage[<variable>]{geometry} has a \newgeometry{} and a \restoregeometry but this does not work for me (following the manual for the The geometry package)
My preamble runs \usepackage[left=8cm,right=1cm,top=2cm,bottom=4cm,marginparwidth=7cm,marginparsep=0.5cm]{geometry}
My main also runs
\pagestyle{fancy}
\fancyhf{}
\renewcommand{\headrulewidth}{0pt} % remove line in header
\setlength\headsep{3cm}
\setlength\textheight{20cm}
\setlength\footskip{4,3cm}

for the record.
I'm currently running this figure code without any luck
\begin{figure}[p]
\newgeometry{}
 \centering
 \includegraphics[width=1\textwidth]{Fig/Co_Creation/DivCon.pdf}
 \caption{Planned divergence and convergence in the co-creation process}
 \label{fig:diagramDC}
\clearpage
\restoregeometry
\end{figure}

Ideally, I'd like to remove any content in the header and footer on these pages as well.
Kind regards
Leo

A: You have to define what new geometry want. Also both \newgeometry and \restoregeometry should go outside of the figure environment.
With \pagestyle{empty} you cancel all headers and footers. You can then restore the fancy style or invoke another.

\documentclass[12pt,a4paper]{book}

\usepackage{kantlipsum} % only dummy tet <<<
\usepackage{graphicx}

\usepackage[left=8cm,right=1cm,top=2cm,bottom=4cm,marginparwidth=7cm,marginparsep=0.5cm,showframe]{geometry} % added showframe <<<

\usepackage{fancyhdr}
\pagestyle{fancy}
\fancyhf{}
\fancyhead[RO,LE]{\thepage}
\renewcommand{\headrulewidth}{0pt} % remove line in header

\begin{document}
1.  \kant[1-3]

    \newgeometry{left=3cm,right=3cm,top=2cm,bottom=3cm,marginparwidth=0cm,marginparsep=0cm}
    \pagestyle{empty} % no headers nor footers
    \begin{figure}[p]
        \centering
        \includegraphics[width=1\textwidth]{example-image}
        \caption{Planned divergence and convergence in the co-creation process}
        \label{fig:diagramDC}
    \end{figure}

    \restoregeometry
    \pagestyle{fancy} % restore headers and footers <<<

2.  \kant[2]

\end{document}


text:
Q: Amazon Web service. Upload a war I want to deploy a x.war in my tomcat of AWS, but I don't manage upload the file.
I have written this in my console.
          scp -i x.pem /home/user/folder/x.war ubuntu@52.16.43.22/folder
but ubuntu said to me, is not a directory. The directory /folder exist in my instance of AWS.

A: You forgot the : between the server and the local file path
scp -i x.pem /home/user/folder/x.war ubuntu@52.16.43.22:/folder


text:
Q: Echo text to a file in golang Is it possible to do something in Golang similar to the below in bash
GrafanaProvData()
{
cat > /etc/grafana/provisioning/datasources/datasource.yml << EOF
apiVersion: 1

deleteDatasources:
  - name: Clickhouse
    orgId: 1

datasources:

  - name: Clickhouse
    type: vertamedia-clickhouse-datasource
    access: proxy
    url: http://localhost:8123
    basicAuth: 1
    basicAuthUser: default
    basicAuthPassword: $password
    isDefault: false
    defaultDatabase:

EOF
}

i have tried command.exec but its not exactly what is needed

A: What happens in this shell script is the usage of the so-called "here document" which is piped by the shell to the standard input of the command cat whose standard output is directed to a file, which — due to the redirection set up using > — will be either created or truncated.
As commented by some folks, in Go, that would mostly amount to writing a string literal to a text file.
But note that there is a twist: when here-documents are processed by the shell it performs various expansions — including variable expansion — in the document's text before actually using it — unless special action is taken to prevent that.
So, in your example, the contents of the variable "password" would be substituted in place of $password.
With this in mind, what you'd do is something like
const tmpl = `apiVersion: 1

deleteDatasources:
  - name: Clickhouse
    orgId: 1

datasources:

  - name: Clickhouse
    type: vertamedia-clickhouse-datasource
    access: proxy
    url: http://localhost:8123
    basicAuth: 1
    basicAuthUser: default
    basicAuthPassword: %s
    isDefault: false
    defaultDatabase:
`

fd, err := os.OpenFile("/etc/grafana/provisioning/datasources/datasource.yml",
os.O_WRONLY|os.O_TRUNC, 0666)
if err != nil {
  log.Fatal(err)
}
defer fd.Close()

_, err := fmt.Fprintf(tmpl, password)
if err != nil {
  log.Fatal(err)
}

While we are at it, consider two more things:

*

*If/when the template becomes more complicated, it would become progressively harder to use the functions of the fmt.*f family to cut the task; you then might want to look at the text/template standard package.

*If/when you would need even more advanced processing of your YAML templates, it might be more convenient to stop being format-agnostic and use any YAML-handling package for Go — such as the venerable gopkg.in/yaml.v3 to first fill a variable of some custom compound type and then marshal it as a YAML-formatted document.
This might help prevent a certain class of weird erorrs (consider: what happens if your password contains letters which will be interpreted by a YAML parser as a proper YAML syntax? A "real" YAML marshaler would escape anything which would be improperly interpreted — while any "templating" approach would not.)

One more hint: when the file to be written is big (like, over 10k), it might be worthwhile to stick a bufio.Writer between the fmt.Fprint* functions and the opened file—to optimize filesystem access.


text:
Q: In 3dmax Maxscript how do i run my macro or function, when user hide some object In Maxscript  how do I run my macro or function, when user hide some object or I bind my script with 3dmax hide action

A: Register a #nodeHide callback with the function call as the script.


text:
Q: How to use square cursor in a HTML input field? How can I use this square cursor (image below) in the text <input> tags?

A: The accepted solution has a number of issues:

*

*It's painfully slow, especially when holding down keys.

*The real caret can be moved with the arrows, but you won't see where it is, as the fake square one will always be at the end.

*The input needs to be focused again manually by clicking it.

*It's not possible to properly select text, as the selection is lost as soon as you release the mouse button, and it's completelly impossible to select text using the keyboard.
A better solution might be to use CSS to make sure the "caret" element always comes after a contenteditable "input" and JS to make sure the contenteditable element is always focused. You might try to do this last thing by adding autofocus to the contenteditable element and using a  for the caret element, but that doesn't work on contenteditable elements. Note no keyboard event listeners are needed:

const input = document.getElementById('input');
const caret = document.getElementById('caret');

// Move the focus back to the input if it moves away from it:
input.addEventListener('blur', (e) => {
  input.focus();
});

// Set the focus to the input so that you can start typing straight away:
input.focus();
body {
  background: #000;
  color: #0F0;
  font-family: monospace;
  height: 100vh;
  box-sizing: border-box;
  overflow-x: hidden;
  overflow-y: scroll;
  margin: 0;
  padding: 16px;
}

#input {
  display: inline;
  word-break: break-all;
  outline: none;
  visibility: visible;
}

#caret {
  border: 0;
  padding: 0;
  outline: none;
  background-color: #0F0;
  display: inline-block;
  font-family: monospace;
}
C:\WIKIPEDIA >

<button id="caret" for="input"> </button>

In a more realistic example, you might want to:

*

*Avoid trapping the focus in the contenteditable element, as that would prevent selecting previous commands. Instead, focus to the contenteditable element only once the user presses some key.

*Show a different caret depending on its position: square if it's at the end of the input, line if it's somewhere else (unless overtype mode is enabled with the Ins key).

*Add a new command/entry if ↵ is pressed.

*Prevent entering formatted text and automatically split it up into multiple commands/entries when needed.

const history = document.getElementById('history');
const input = document.getElementById('input');
const cursor = document.getElementById('cursor');

function focusAndMoveCursorToTheEnd(e) {
  input.focus();

  const range = document.createRange();
  const selection = window.getSelection();
  const { childNodes } = input;
  const lastChildNode = childNodes && childNodes.length - 1;

  range.selectNodeContents(lastChildNode === -1 ? input : childNodes[lastChildNode]);
  range.collapse(false);

  selection.removeAllRanges();
  selection.addRange(range);
}

function handleCommand(command) {
  const line = document.createElement('DIV');

  line.textContent = `C:\\WIKIPEDIA > ${ command }`;

  history.appendChild(line);
}

// Every time the selection changes, add or remove the .noCursor
// class to show or hide, respectively, the bug square cursor.
// Note this function could also be used to enforce showing always
// a big square cursor by always selecting 1 chracter from the current
// cursor position, unless it's already at the end, in which case the
// #cursor element should be displayed instead.
document.addEventListener('selectionchange', () => {
  if (document.activeElement.id !== 'input') return;

  const range = window.getSelection().getRangeAt(0);
  const start = range.startOffset;
  const end = range.endOffset;
  const length = input.textContent.length;

  if (end < length) {
    input.classList.add('noCaret');
  } else {
    input.classList.remove('noCaret');
  }
});

input.addEventListener('input', () => {
  // If we paste HTML, format it as plain text and break it up
  // input individual lines/commands:
  if (input.childElementCount > 0) {
    const lines = input.innerText.replace(/\n$/, '').split('\n');
    const lastLine = lines[lines.length - 1];

    for (let i = 0; i <= lines.length - 2; ++i) {
      handleCommand(lines[i]);
    }

    input.textContent = lastLine;

    focusAndMoveCursorToTheEnd();
  }

  // If we delete everything, display the square caret again:
  if (input.innerText.length === 0) {
    input.classList.remove('noCaret');
  }
});

document.addEventListener('keydown', (e) => {
  // If some key is pressed outside the input, focus it and move the cursor
  // to the end:
  if (e.target !== input) focusAndMoveCursorToTheEnd();
});

input.addEventListener('keydown', (e) => {
  if (e.key === 'Enter') {
    e.preventDefault();

    handleCommand(input.textContent);
    input.textContent = '';
    focusAndMoveCursorToTheEnd();
  }
});

// Set the focus to the input so that you can start typing straigh away:
input.focus();
body {
  background: #000;
  color: #0F0;
  font-family: monospace;
  height: 100vh;
  box-sizing: border-box;
  overflow-x: hidden;
  overflow-y: scroll;
  word-break: break-all;
  margin: 0;
  padding: 16px;
}

#input {
  display: inline;
  outline: none;
  visibility: visible;
}

/*
  If you press the Insert key, the vertical line caret will automatically
  be replaced by a one-character selection.
*/
#input::selection {
  color: #000;
  background: #0F0;
}

#input:empty::before {
  content: ' ';
}

@keyframes blink {
  to {
    visibility: hidden;
  }
}

#input:focus + #caret {
  animation: blink 1s steps(5, start) infinite;
}

#input.noCaret + #caret {
  visibility: hidden;
}

#caret {
  border: 0;
  padding: 0;
  outline: none;
  background-color: #0F0;
  display: inline-block;
  font-family: monospace;
}

C:\WIKIPEDIA >

<button id="caret" for="input"> </button>

In general, it's usually a bad idea to listen for keyboard events (keydown / keypress / keyup) to handle text input or cursors, as the value of the input can also be updated by pasting or dropping text into it and there are many edge cases, such as arrows, delete, escape, shortcuts such as select all, copy, paste... so trying to come up with an exhaustive list of all the keys we should take care of is probably not the best approach.
Moreover, that won't work on mobile, where most keys emit the same values e.key = 'Unidentified', e.which== 229 and e.keyCode = 229.
Instead, it's usually better to rely on other events such as input and use KeyboardEvents to handle very specific keys, like ↵ in this case.
If you need to check KeyboardEvent's properties values such as e.key, e.code, e.which or e.keyCode you can use https://keyjs.dev. I will add information about these kinds of cross-browser incompatibilities soon!

Disclaimer: I'm the author.

A: Sample

I've changed how it works, and it seems to solve a few issues :)

*

*Accepts any text a normal input can

*Backspace works

*Theoretically can support pasting text

Usual caveats apply still, most notably the inability to visually see where the caret is.
I'd think long and hard whether this solution is worth implementing, based on its drawbacks and usability issues.

$(function() {
  var cursor;
  $('#cmd').click(function() {
    $('input').focus();
    cursor = window.setInterval(function() {
      if ($('#cursor').css('visibility') === 'visible') {
        $('#cursor').css({
          visibility: 'hidden'
        });
      } else {
        $('#cursor').css({
          visibility: 'visible'
        });
      }
    }, 500);

  });

  $('input').keyup(function() {
    $('#cmd span').text($(this).val());
  });

  $('input').blur(function() {
    clearInterval(cursor);
    $('#cursor').css({
      visibility: 'visible'
    });
  });
});
#cmd {
  font-family: courier;
  font-size: 14px;
  background: black;
  color: #21f838;
  padding: 5px;
  overflow: hidden;
}
#cmd span {
  float: left;
  padding-left: 3px;
  white-space: pre;
}
#cursor {
  float: left;
  width: 5px;
  height: 14px;
  background: #21f838;
}
input {
  width: 0;
  height: 0;
  opacity: 0;
}

<input type="text" name="command" value="" />

A: AFAIK, that's not possible for html text box, you could style the input itself but you can do nothing about the cursor other than applying the cursor options that are already available :(

A: you can't. which means: you could do it yourself by using a fixed-with font, use a blinking gif als background which position is set dynamicaly by calculating the with of the already typed text - but there will be the "normal" cursor above your gif, making this solution ugly

A: For <input> tags, there's not much you can do. If you didn't mind it being a horrible hack, you could always use JavaScript to resize the text box as needed (set width = *something* * count), and have an  with the cursor to the right.
I don't think there are any less 'ugh' solutions, bar handling the text input yourself, which is probably overkill.

A: You would have to 1) roll your own textbox and 2) hide the real cursor by continually focusing it elsewhere. Then, capture the key events at the document/body level, and insert that value into your own element.  The cursor would then be an animated GIF that was always positioned at far right of your "textbox".
You will run into issues with #2, and the whole thing is generally inadvisable. HTML 5 opens up some new possibilities, but it's still an awful lot of work for a cursor.


text:
Q: How to deploy Worklight war from Jenkins From an ant script, I'm able to use the app-deployer, adapter-deployer with the worklightServerhost property to publish apps
<!-- Deploys adapter file to configured host & project -->
<target name="adapterDeployer" depends="init">
    <echo.timestamp message="Deploying adapter ${adapterFile}" />
    <adapter-deployer worklightServerHost="${WLSERVERHOST}/${project.name}"
        deployable="${adapterFile}" />
</target>

Why, when I want to publish the project WAR file do I need to reference installdir ?
My CI environment isn't running Liberty profile.
<target name="deployWar" depends="init">
    <updateapplicationserver>
        <project warfile="${build.dir}/${project.name}.war" />
        <applicationserver>
            <websphereApplicationserver installdir="WTH this is a CI server" />
        </applicationserver>
    </updateapplicationserver>
</target>

Are there any shortcuts or do i need to scp my war to a different box & run a different ant script?

A: We have a similar scenario, where we are deploying in an automated way from Jenkins, and the answer is basically 'yes'; you need to SCP your WAR to the target box, along with a small ANT script to deploy it with, and then run that 'locally' (we use a remote SSH command to do that). When you are using <adapter-deployer> (or <app-deployer>) you are basically connecting to an existing deployed Worklight server (which essentially is the .war file). However, getting the WAR file on there in the first place involves using the <updateapplicationserver> ANT task (in fact, in our scenario, we use <unconfigureapplicationserver>, followed by <configureapplicationserver>, as this gives the chance to update the JNDI properties also).


text:
Q: Android remove variable content on concat or merge variables in this below code as :
String marketUUid = "bc76b7a5-3166-11e6-b8fe-ec9a74f8851a";

String filePath = imagePath + "/" + marketUUid + "/" + "banners";
File   checkMarketBannerFolder = new File(filePath);

when i try to merge or concat marketUUid with other variables such as imagePath and put it to filePath, its removed from this operation and i dont have that variable, it means after merge variables my filePath have:
/storage/emulated/0/Signal/image/banners

but this code doesn't have any problem:
String filePath = imagePath + "/" + "bc76b7a5-3166-11e6-b8fe-ec9a74f8851a" + "/" + "banners";

whats happen ?

A: There is a by far more clean and readable way to format your strings:
String marketUUid = "bc76b7a5-3166-11e6-b8fe-ec9a74f8851a";
String imagePath = "image";

String filePath = String.format(
        "%s/%s/banners",
        imagePath,
        marketUUid
);


text:
Q: Как прекратить отправку формы и продолжить по условию? Имеется форма, в которой есть такой блок:
<fieldset class="box tabular" id="project_members">
    <legend>Members</legend>

      <input value="Robert Kovacik" name="members[[1][name]]" id="members_[1][name]" type="text">
          <input class="users_email" placeholder="Email, requred for new user" readonly="readonly" name="members[[1][email]]" id="members_[1][email]" type="text">

            <input name="[members][1][role_ids][0]" value="13" type="checkbox"> CEO
            <input name="[members][1][role_ids][1]" value="3" type="checkbox"> Project Manager
            <input name="[members][1][role_ids][2]" value="4" type="checkbox"> Consultant / Support
            <input name="[members][1][role_ids][3]" value="7" type="checkbox"> Sales Representative
            <input name="[members][1][role_ids][4]" value="10" type="checkbox"> Client
            <input name="[members][1][role_ids][5]" value="12" type="checkbox"> IT expert

      <input value="Dominka Helpdesk Coordinator" name="members[[2][name]]" id="members_[2][name]" type="text">
          <input class="users_email" placeholder="Email, requred for new user" readonly="readonly" name="members[[2][email]]" id="members_[2][email]" type="text">

            <input name="[members][2][role_ids][0]" value="13" type="checkbox"> CEO
            <input name="[members][2][role_ids][1]" value="3" type="checkbox"> Project Manager
            <input name="[members][2][role_ids][2]" value="4" type="checkbox"> Consultant / Support
            <input name="[members][2][role_ids][3]" value="7" type="checkbox"> Sales Representative
            <input name="[members][2][role_ids][4]" value="10" type="checkbox"> Client
            <input name="[members][2][role_ids][5]" value="12" type="checkbox"> IT expert

.............................. и т.д.
</fieldset>

До и после этого блока есть другие поля, у некоторых есть атрибут required.
Что хочу получить:
 У каждого блока member-roles-selection должна быть выбрана хотя бы одна роль, если не выбрана, то форму не отправлять и выдать ошибку. Так же должны работать html5 валидации.
Я пытался сделать это примерно таким образом:
$('#issue_tree').click(function(event) {
        var result = false;
        $(".member-roles-selection").each(function() {
            result = $(this).find(':checkbox:checked').length > 0;
            console.log(result);
            if(result === false){
                event.preventDefault();
                alert('error');
                return false;
            } else {
                result = false;
            }
        });
    });

Конкретно у этого кода проблема в том, что если один раз была показана ошибка, то форма не отправится уже никогда.
Если поменять else ветку на:
else {
    result = false;
    $('form').submit();
}

то игнорируются html5 валидации.

A: Грамотно поставленный вопрос - половина ответа. Как это часто бывает, сразу после вопроса, самостоятельно находится ответ.
Сейчас у меня js выглядит примерно так:
$('#issues_tree').click(function(event) {
        var result = false;
        $(".member-roles-selection").each(function() {
            result = $(this).find(':checkbox:checked').length > 0;
            if(!result){
                event.preventDefault();
                alert('error');
            } else {
                result = false;
            }
        });
    });


text:
Q: Set up a column based on another column and outside list in a Pandas Dataframe I am trying to create a new column in a Pandas dataframe which takes only one array from a list of 5 arrays (the list is titled cluster_centre) and puts that array into the dataframe. It would take the array at the index that matches the value in the 'labels' column of the same dataframe (which has values of 0,1,2,3 or 4). So for instance, if the sentence in that row was given a label of 2 i.e. the 'labels' column value for that row would be 2, then the value of the 'cluster_centres' column in the df at that row would be cluster_centre[2]. How can I do this? The code I have attempted is pasted below:
from sentence_transformers import SentenceTransformer
from sklearn.cluster import KMeans
import pandas as pd

with open('JWN_Nordstrom_MDNA_overview_2017.txt', 'r') as file:
    initial_corpus = file.read()

corpus = initial_corpus.split('. ')

# Extract sentence embeddings
embedder = SentenceTransformer('bert-base-wikipedia-sections-mean-tokens')
corpus_embeddings = embedder.encode(corpus)

# Perform KMeans clustering
num_clusters = 5
clustering_model = KMeans(n_clusters=num_clusters)
clustering_model.fit(corpus_embeddings)
cluster_assignment = clustering_model.labels_
cluster_centre = clustering_model.cluster_centers_

# Create dataframe
All_data_df = pd.DataFrame()
All_data_df['sentences'] = corpus
All_data_df['embeddings'] = corpus_embeddings
All_data_df['labels'] = cluster_assignment

# The line below creates a ValueError
All_data_df['cluster_centres'] = cluster_centre[All_data_df['labels']]
print(All_data_df.head())

I get this error: ValueError: Wrong number of items passed 768, placement implies 1
UPDATE: I did some new stuff and tried this:
All_data_df = pd.DataFrame()
All_data_df['sentences'] = corpus
All_data_df['embeddings'] = corpus_embeddings
All_data_df['labels'] = cluster_assignment
#All_data_df['cluster_centres'] = 0

for index, row in All_data_df.iterrows():
    iforval = cluster_centre[row['labels']]
    All_data_df.at[index, 'cluster_centres'] = iforval
print(All_data_df.head())

But get a new error: ValueError: Must have equal len keys and value when setting with an iterable. I printed iforval inside the loop and it does indeed return 29 correct arrays from the cluster_centre list, which matches the 29 rows present in the dataframe. Now I just need to put them into the new column of the dataframe, but .at[] didn't work, not sure if I am using it correctly.
EDIT/UPDATE: Ok I found a sort of solution, don't know why I didn't realise this before, I just created a list beforehand and made that into the new column, ended up being much simpler.
cluster_centres_list = [cluster_centres[label] for label in cluster_assignment]

all_data_df = pd.DataFrame()
all_data_df['sentences'] = corpus
all_data_df['embeddings'] = corpus_embeddings
all_data_df['labels'] = cluster_assignment
all_data_df['cluster_centres'] = cluster_centres_list
print(all_data_df.head())


text:
Q: Volume control pressing in Android game I'm developing a simple Android game that plays sound in background by service. When game starts, the sound is playing good. But when pressing volume up key or down button, the app exits immediately.
public class PlayAudio extends Service{
    private static final String LOGCAT = null;
    MediaPlayer objPlayer;

    public void onCreate(){
        super.onCreate();
        Log.d(LOGCAT, "Service Started!");
        objPlayer = MediaPlayer.create(this,R.raw.relax);
    }

    public int onStartCommand(Intent intent, int flags, int startId){
        objPlayer.start();
        Log.d(LOGCAT, "Media Player started!");
        if(objPlayer.isLooping() != true){
            Log.d(LOGCAT, "Problem in Playing Audio");
        }
        return 1;
    }

    public void onStop(){
        objPlayer.stop();
        objPlayer.release();
    }

    public void onPause(){
        objPlayer.stop();
        objPlayer.release();
    }

    public void onDestroy(){
        objPlayer.stop();
        objPlayer.release();
    }

    @Override
    public IBinder onBind(Intent objIndent) {
        return null;
    }
}

this code to start playing sound
public void playAudio() {
    Intent objIntent = new Intent(this, PlayAudio.class);
    startService(objIntent);
}

A: Problem solved. I just missed the condition:
if (keyCode == KeyEvent.KEYCODE_BACK){}


text:
Q: Save HTML DIV as an image with save as pop up I want to make a web app which makes comics. It's very basic and I don't know Canvas very well. The user can upload 2 images and they appear in two divs. Then these divs are in one whole div along with other comic elements. What I want is that when the user clicks on a button, a 'save as' dialog box pops up which saves the whole div as an image.

This page does that but it works in flash!

Please don't rate in negative or say it's a possible copy or something! I've been finding a solution for hours on the net. Canvas2Image and Html2Canvas ain't for me because I ain't using canvas. Also I tried "Joel Schlundt" answer on capture div into image using html2canvas using that. Please tell a possible solution or maybe how I can make that div come into canvas as an image automatically and then save that canvas as an image.

A: Yes, you can easily use canvas to combine your cartoon image with the user's images.
Here's how to create a canvas on the fly and combine all the images:
// create a temporary canvas and size it
var canvas=document.createElement("canvas");
var ctx=canvas.getContext("2d");
canvas.width=awindow.width;
canvas.height=awindow.height;

// draw all 3 images into 1 combined image
ctx.drawImage(back,0,65);
ctx.drawImage(person,0,0,person.width,person.height,200,125,71,200);
ctx.drawImage(awindow,0,0);

// save the combined canvas to an image the user can download by right-clicking
var result=document.getElementById("composition");
result.src=canvas.toDataURL();

Since you're using images from different domains, I assume you've already worked through any CORS issues.  You might have to bounce the images off your server.

This example fiddle must be viewed with Chrome or Firefox (IE throws a CORS violation):
http://jsfiddle.net/m1erickson/5JTtd/
Here is example code:
<!doctype html>

<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" />

Source images

Combined result exported from canvas

To Save: Right-click and Save picture as...


text:
Q: Let-renaming function breaks code While iterating my code towards a correct version, I came across the following curiosity:
{-# LANGUAGE RankNTypes #-}

module Foo where

import Data.Vector.Generic.Mutable as M
import Control.Monad.Primitive

-- an in-place vector function with dimension
data DimFun v m r =
  DimFun Int (v (PrimState m) r -> m ())

eval :: (PrimMonad m, MVector v r) => DimFun v m r -> v (PrimState m) r -> m ()
eval = error ""

iterateFunc :: (PrimMonad m, MVector v r)
            => (forall v' . (MVector v' r) => DimFun v' m r) -> DimFun v m r
iterateFunc = error ""

f :: (PrimMonad m, MVector v r)
      => DimFun v m r
f = error ""

iteratedF :: (MVector v r, PrimMonad m)
           => v (PrimState m) r -> m ()
iteratedF y =
    let f' = f
    in eval (iterateFunc f') y

This code does not compile:
Testing/Foo.hs:87:14:
    Could not deduce (MVector v0 r) arising from a use of 'f'
    from the context (MVector v r, PrimMonad m)
      bound by the type signature for
                 iteratedF :: (MVector v r, PrimMonad m) =>
                              v (PrimState m) r -> m ()
      at Testing/Foo.hs:(84,14)-(85,39)
    The type variable 'v0' is ambiguous
    Relevant bindings include
      f' :: DimFun v0 m r (bound at Testing/Foo.hs:87:9)
      y :: v (PrimState m) r (bound at Testing/Foo.hs:86:11)
      iteratedF :: v (PrimState m) r -> m ()
        (bound at Testing/Foo.hs:86:1)
    In the expression: f
    In an equation for 'f'': f' = f
    In the expression: let f' = f in eval (iterateFunc f') y

Testing/Foo.hs:88:26:
    Couldn't match type 'v0' with 'v''
      because type variable 'v'' would escape its scope
    This (rigid, skolem) type variable is bound by
      a type expected by the context: MVector v' r => DimFun v' m r
      at Testing/Foo.hs:88:14-27
    Expected type: DimFun v' m r
      Actual type: DimFun v0 m r
    Relevant bindings include
      f' :: DimFun v0 m r (bound at Testing/Foo.hs:87:9)
    In the first argument of 'iterateFunc', namely 'f''
    In the first argument of 'eval', namely '(iterateFunc f')'
Failed, modules loaded: none.

However, if I change the definition of iteratedF to
iteratedF y = eval (iterateFunc f) y

the code compiles wtih GHC 7.8.2. This question is not about the strange-looking signatures or data types, it is simply this: why does renaming f to f' break the code? This seems like it has to be a bug to me.

A: The problem is of course not the renaming, but the binding to a new variable. Since iterateFunc is Rank-2, it needs a polymorphic argument function. Of course, f is polymorphic in v, so it can be used. But when you write f' = f, it's not clear what type f' should be: the same polymorphic type as f, or some monomorphic type, possibly depending some relation to another type variable in iteratedF which the compiler hasn't deduced yet.
The compiler defaults to the monomorphic option; as chi says this is the monomorphism restriction's fault here so if you turn it off your code actually compiles.
Still, the same problem can turn up even without the monomorphism restriction in RankNTypes code, it can't be avoided completely. The only reliable fix is a local signature, usually necessitating ScopedTypeVariables.

A: Disabling the monomorphism restriction, I can compile your code. So, just add
{-# LANGUAGE NoMonomorphismRestriction #-}

at the beginning of your file.
The reason for the type error is that the definition
let f' = f

does not use a function pattern (e.g. f' x y = ...), so the monomorphism restriction kicks in and forces f' to be monomorphic, while iterateFunc requires a polymorphic function.
Alternatively, add a type annotation
let f' :: (PrimMonad m, MVector v r) => DimFun v m r
    f' = f


text:
Q: Не все со всех страниц возвращается html. Выводит 301 ошибку Moved Я хочу сделать подобие функции wget в линуксе.
Проблема в том, что нормальный html ответ я получаю только для www.google.com
вот что например возвращается для www.mail.ru
HTTP/1.1 301 Moved Permanently
Server: nginx/1.6.2
Date: Tue, 04 Dec 2018 05:56:28 GMT
Content-Type: text/html
Location: http://mail.ru/
X-Frame-Options: SAMEORIGIN
Content-Length: 184
Connection: close
Age: 0

<title>301 Moved Permanently</title>

301 Moved Permanently

nginx/1.6.2

Ниже код запроса, я думаю проблема в этом сообщении:

GET / HTTP/1.1\r\nHost: %s\r\nUser-Agent: fetch.c\r\n\r\n

Его я отправляю в функции read()
Вот так я создаю сокет:
int socket_desc = socket(AF_INET, SOCK_STREAM, 0);

if (socket_desc == -1)
{
    puts("could not create socket");

}

char* ip = new char;
getHost_byName(hostname, ip);
int success = read(ip, socket_desc, hostname);
if (success != 0)
{
    puts("Error");
}

close(socket_desc);

В этой функции посылаю сообщение и получаю ответ:
int read(char* address, int socket_desc, char* hostname)
{
    struct sockaddr_in server;

    server.sin_addr.s_addr = inet_addr(address);
    server.sin_family = AF_INET;
    server.sin_port = htons( 80 );
    //Connect to remote server
    if (connect(socket_desc , (struct sockaddr *)&server , sizeof(server)) < 0)
    {
        puts("connect error");
        return 1;
    }

    puts("Connected\n");
    puts(hostname);

    char* message;
    const char * format = "GET / HTTP/1.1\r\nHost: %s\r\nUser-Agent: fetch.c\r\n\r\n";
    int status = asprintf(& message, format, hostname);
    if (status == -1)
    {
        printf("asprintf doesn't work");
        return 1;
    }
    //puts(message);
    if (send(socket_desc, message, strlen(message), 0) < 0)
    {
        puts("send failed");
        return 1;
    }

    puts("data send");

    //-recv - calls are used to receive messages from a socket
    int size_recv , total_size= 0, BLOCK_SIZE = 512;
    char chunk[BLOCK_SIZE];

    ofstream fout(getFileName(hostname));
    //loop
    while(1)
    {
        memset(chunk ,0 , BLOCK_SIZE);  //clear the variable
        if((size_recv = recv(socket_desc , chunk , BLOCK_SIZE, 0) ) < 0)
        {
            break;
        }
        else
        {
            fout << chunk;
            printf("%s" , chunk);
        }
    }

    fout.close();
    return 0;
}


text:
Q: WebSocketChannelException: HandshakeException - Flutter app with Laravel Websockets on custom server Cerificated with Cpanel I have Laravel web application includes live chat relying on Laravel Websockets https://docs.beyondco.de/laravel-websockets/
For now i am making Flutter app for same service and i am facing problem Connecting to websocket i already made on wss (I have this code)
var channel = IOWebSocketChannel.connect("wss://site.com:6001/app/123456789");

channel.sink.add(json.encode({
  "event": "pusher:subscribe",
  "data": {"channel": "channel-name"}
}));

channel.stream.listen((_data) {
  print(_data.toString());
}, onError: (error) {
  print("Socket: error => " + error.toString());
}, onDone: () {
  print("Socket: done");
});

I am getting this problem : CERTIFICATE_VERIFY_FAILED which i searched about it a lot and nothing helped - one of the things i tried is to make a SecureSocket
SecureSocket secureSocket = await SecureSocket.connect(
    'www.site.com', 6001,
    onBadCertificate : (X509Certificate cert) => true).then((SecureSocket secureSocket) {

  secureSocket.listen((List<int> event) {
    print(utf8.decode(event));
  });

}).catchError((error) {
  print(error);
});

This code returns no error but it didn't connecting at all.
Note: same code working on ios simualtors but not on android
Also i tested my ssl certificate and it shows this result :
https://ibb.co/chyFPtX
Please can anyone help me fixing this problem?

A: The laravel websockets connection support a pusher driver, try using a pusher client instead that already has the protocol built-in.

A: For anyone who is new to the issue
Laravel Websocket here
Flutter
import 'package:web_socket_channel/io.dart';

final _channel = IOWebSocketChannel.connect(
    Uri.parse(
        'ws://127.0.0.1:6001/app/aap-key'),
  );

  @override
  void initState() {
    _channel.sink.add(json.encode({
      "event": "pusher:subscribe",
      "data": {"channel": "test-channel1"}
    }));

    _channel.stream.listen((_data) {
      print(_data.toString());
    }, onError: (error) {
      print("Socket: error => " + error.toString());
    }, onDone: () {
      print("Socket: done");
    });
    super.initState();
  }

  @override
  void dispose() {
    _channel.sink.close();
  }

Laravel Event
<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class TestEvent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new Channel('test-channel1');
    }

    public function broadcastWith()
    {
        return ['data' => 'testing channel, testing message'];
    }
}