text:
Q: Set rigidbody.velocity to direction of mouse in Unity2d I am wondering how to set the rigidbody.velocity to the direction of the mouse pointer in unity 2d. I need the objects initial velocity to be in that direction. Afterward, it will be affected by gravity.
Here is what I tried:
float maxVel = 10f
float posTotal = Input.mousePosition.x + Input.mousePosition.y
float xVel = Input.mousePosition.x / posTotal
float yVel = Input.mousePosition.y / posTotal
Vector3 velTotal = new Vector3(xVel * maxVel, yVel * maxVel, 0)

I have tried this repeatedly, but the object seems to fire in a random direction.

A: First you add up your two mouse axis and that does not create a Vector2. Test it with
Debug.Log(Input.mousePostion.x);
Debug.Log(Input.mousePostion.y);
Debug.Log(posTotal);

the sum is nothing that really makes sense.
instead use Camera.ScreenToWorldPoint
https://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html
and substract the player.position from that WorldPoint like this
https://docs.unity3d.com/Manual/DirectionDistanceFromOneObjectToAnother.html
to get a direction. You can apply a velocity in that direction with the Vector3 from that operation.
Good luck


text:
Q: Moving WordPress Directory (same domain) - GUID issue? I have a WordPress installation on a directory within my domain. So, it is like this:
www.example.com/blog/
WordPress is placed in /blog/

I'd like to move the WordPress installation Blog Posts back to the root level. When I exported the XML file I noticed that each blog post had this GUID reference:
<guid isPermaLink="false">http://example.com/blog/?p=1275</guid>
>> notice the /blog/ in the URL <<

So, my question is - if I import the XML file into a fresh WordPress install at the root level, wont all the links be broken?
Should I change all the GUID links? My understanding is that the GUID URL should be left alone even if the domain path has changed.

A: GUIDs are not URLs, they are unique identifiers that happen to look like URLs. It was, in my opinion, a poor design choice to make them URLs, because it causes a lot of confusion.
They are essentially a way to establish the "global uniqueness" of a post, and you should not change these for content that has already been published.
The GUID is not involved in generating permalinks or resolving incoming requests, so nothing will be broken as long as the API is used correctly, however, I have seen plugin and theme authors use GUIDs as though they were URLs, so watch out for third-party code.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I compile a Go program? I got Go to compile:

0 known bugs; 0 unexpected bugs

and typed in the "hello world":
package main

import "fmt"

func main() {
  fmt.Printf("Hello, 世界\n")
}

Then I tried to compile it, but it wouldn't go:

$ 8c gotest2
gotest2:1 not a function
gotest2:1 syntax error, last name: main

This is going on on Ubuntu Linux on Pentium. Go installed and passed its tests. So where did I go wrong? Can someone tell me where to go from here?
I also tried this program:
package main

import fmt "fmt"  // Package implementing formatted I/O.

func main() {
    fmt.Printf("Hello, world; or Καλημέρα κόσμε; or こんにちは 世界\n");
}

But this was also no go (must stop making go puns):

$ 8c gotest3.go
gotest3.go:1 not a function
gotest3.go:1 syntax error, last name: main

A: For Go 1.0+ the correct build command is now: go build

A: (Update for Go1.0.x)
The  section "Compile packages and dependencies" now list go build as the way to compile in go.
You still call 8g behind the scene, and the parameters you could pass to 8g are now passed with -gcflags.
-gcflags 'arg list'

arguments to pass on each 5g, 6g, or 8g compiler invocation

A: You're using 8c, which is the c compiler. 8g will compile go, and 8l will link.

A: use go run  to run the go program. Here is the output.
$ cat testgo.go
package main

import "fmt"

func main() {
    fmt.Printf("Hello, 世界\n")
}

$go run testgo.go
Hello, 世界

A: To compile Go code, use the following commands:
go tool compile gotest3.go # To create an object file.
go tool link -o gotest3 gotest3.o # To compile from the object file.
chmod +x gotest3 # To apply executable flag.
./gotest3 # To run the binary.


text:
Q: NuGet release notes I added Property to include Package release note, but I don't see it in Nuget and visual studio Nuget Package manager.  Anyone noticed this ?
  <PropertyGroup>
    <IncludeSymbols>true</IncludeSymbols>
    <SymbolPackageFormat>snupkg</SymbolPackageFormat>
    <PackageLicenseExpression>MIT</PackageLicenseExpression>
    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
    <PackageReleaseNotes>Testing</PackageReleaseNotes>
  </PropertyGroup>

A: If you want to modify the author, description,copyright, you have to use these properties:
<PropertyGroup>
    <IncludeSymbols>true</IncludeSymbols>
    <SymbolPackageFormat>snupkg</SymbolPackageFormat>
    <PackageLicenseExpression>MIT</PackageLicenseExpression>
    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
    <PackageReleaseNotes>Testing</PackageReleaseNotes>
    <PackageId>testme</PackageId>
    <Version>2.0.0</Version>
    <Authors>me</Authors>
    <Description>mytest</Description>
    <Copyright>company</Copyright>

 </PropertyGroup>

See this document.
When I upload the nuget package on nuget.org,

And when I finish publishing it, I got it:


text:
Q: RedirectView to external site. How to append parameters? I would like to redirect from my page to external site. This external site address is defined and never changes... And I can implement it... The challenge comes from:
I have a form, which posts Q into my view function, which gives final string of parameters to pass into the pattern of url supposedly attached to the main address of this external web site after the ? mark... I just cannot find the information how to pass and attach this string to a given url. Somehow it's difficult for me, please don't judge too harsh. Parameter is only one, it is a string, which formed in view function.
I use RedirectView in urls.py:
path('do_request/found/', RedirectView.as_view(url='https://docs.djangoproject.com/'), name='found_objects'),

In views.py (there are probably some mistakes, but it's just for the purpose of the question):
class UserFoundRequestView(TemplateView):
    model=ForQuery
    template_name='found_objects.html'

    def get_results(self, request):
        our_queries = ForQuery.objects.all()
        query=self.request.GET.get("q")
        if query:
            our_object=ForQuery.objects.filter(query_id__iexact=query)
        for x in our_queries:
            if x.query_id == our_object.query_id:
                name = x.dep_station
        #context = {
        #   'name' : name,
        #}
        return name

    def get_string(request):
        base_url = 'https://docs.djangoproject.com/'
        query_name = get_results()
        query_string = urlencode(query_name)
        url = '{}?{}'.format(base_url, query_string)
        return redirect(url)

Either to append to url or just bring formed url to patterns->path...
Thank you for the help!
my template:
{% extends "base_generic.html" %}
{% block content %}

Paste value to the field

    <form method="get" action="{% url 'found_objects' %}">
        <input type="text" name="q" placeholder="search by value" class="m-1 p-1"><button class=" btn btn-outline-primary m-1 p-1" type="Submit">Search</button>
    </form>

{% endblock %}

A: You have to trigger the view by submitting the form and the view itself will return the according redirect. Between is the url mapping that links the form submit to the according view like so:
urls.py
from your_app.views import redirect_view

path('do_request/found/', redirect_view, name='found_objects'),

views.py
def redirect_view(request):

        our_queries = ForQuery.objects.all()
        query = request.GET.get("q")
        if query:
            our_object=ForQuery.objects.filter(query_id__iexact=query)
        for x in our_queries:
            if x.query_id == our_object.query_id:
                name = x.dep_station

        base_url = 'https://docs.djangoproject.com/'
        query_string = urlencode(name)
        url = '{}?{}'.format(base_url, query_string)
        return redirect(url)


text:
Q: Lag in rotation 2D I have a bitmap (web ‹img›, 2048x1365) and put a dot on it (‹div› absolute with size 1px).
When I rotate the bitmap (on server), I want to rotate the dot as well (with Javascript).
I know the equation of rotation :
$cs=cos($radian);
$sn=sin($radian);

$x2=($x*$cs)-($y*$sn);
$y2=($x*$sn)+($y*$cs);

But somehow I have a lag...
My code (in PHP) :
$width=2048;
$height=1365;

$radian=$rot*M_PI/180;

$cs=cos($radian);
$sn=sin($radian);

$center_x=$width/2;
$center_y=$height/2;

$x-=$center_x;
$y-=$center_y;

$x2=($x*$cs)-($y*$sn);
$y2=($x*$sn)+($y*$cs);

$x=$x2+$center_x;
$y=$y2+$center_y;

With $rot=6°, I must shift (about) $x2 +30, $y2 +85
With $rot=21°, I must shift $x2 +40, $2 +380
With $rot=90°, I must shift $x2 -340, $y2 -340
With $rot=180°, It's good
With $rot=270°, I must shift $x2 +340, $y2 +340

I don't understand this lag...
To help, here is an example. The dots are the centers of the square. With angle 10°, I must add x+180 and y+70 for the 3 dots.
Thank you very much for your help

A: Copy from the comments to the question:
Doesn't the image size change when it is rotated?
Compute the positions of the corners after rotation and you should get the rotated image size
(from which you then can compute the new rotation center.)


text:
Q: RSA Encryption public key? How can i create RSA encryption public key from 'Modulus' and 'Exponent' in iOS.?
I have created public key from keychain. is it possible from string 'Modulus' and 'Exponent' values?

A: See this answer over here
https://stackoverflow.com/a/10643894/584616
https://github.com/StCredZero/SCZ-BasicEncodingRules-iOS
SCZ-BasicEncodingRules-iOS
Implementation of Basic Encoding Rules to enable import of RSA keys to iOS
KeyChain using exponent. Code targets iOS 5 with ARC.
Let's say you already have a modulus and exponent from
an RSA public key as an NSData in variables named pubKeyModData and
pubKeyModData. Then the following code will create an NSData containing that RSA
public key, which you can then insert into the iOS or OS X Keychain.
NSMutableArray *testArray = [[NSMutableArray alloc] init];
[testArray addObject:pubKeyModData];
[testArray addObject:pubKeyExpData];
NSData *testPubKey = [testArray berData];

This would allow you to store the key using the addPeerPublicKey:keyBits: method from SecKeyWrapper in the Apple CryptoExercise example. Or, from the perspective of the low-level API, you can use SecItemAdd().
NSString * peerName = @"Test Public Key";

NSData * peerTag =
   [[NSData alloc]
       initWithBytes:(const void *)[peerName UTF8String]
       length:[peerName length]];

NSMutableDictionary * peerPublicKeyAttr = [[NSMutableDictionary alloc] init];

[peerPublicKeyAttr
   setObject:(__bridge id)kSecClassKey
   forKey:(__bridge id)kSecClass];
[peerPublicKeyAttr
   setObject:(__bridge id)kSecAttrKeyTypeRSA
   forKey:(__bridge id)kSecAttrKeyType];
[peerPublicKeyAttr
   setObject:peerTag
   forKey:(__bridge id)kSecAttrApplicationTag];
[peerPublicKeyAttr
   setObject:testPubKey
   forKey:(__bridge id)kSecValueData];
[peerPublicKeyAttr
   setObject:[NSNumber numberWithBool:YES]
   forKey:(__bridge id)kSecReturnPersistentRef];

sanityCheck = SecItemAdd((__bridge CFDictionaryRef) peerPublicKeyAttr, (CFTypeRef *)&persistPeer);


text:
Q: Debugging shortcode problems I am trying to get some of the Miscellaneous shortcodes working properly on my website.  In particular, I would like to use the pages shortcodes: [list-pages], [child-pages], [sibling-pages].  I am using a child of twentyfifteen with minimal changes to the template (background and font changes).
Here's the current behavior, with all of my plugins save for jetpack and akismet disabled, shortcode such as [youtube] and [archives] render properly.  I can also create a shortcode in my functions.php file:
function test_shortcode() {return 'Working';}
add_shortcode('test_shortcode', 'test_shortcode');

That works properly as well.  Using any of the pages shortcodes, however, returns just the bracketed shortcode.  My website currently contains some test pages (2 parents, one child).
I have confirmed (through deactivation) that my plugins (save for Akismet) do not alter this shortcode behavior.  I have also confirmed that the behavior is not affected by location (page/post/sidebar), post format (standard/aside), or template (twentyfifteen/twentyfourteen/twentythirteen).  I have run out of debugging ideas at this point.
Note added in proof: Since the support page I linked above does not specifically mention another plug, I have assumed that these shortcodes were integrated into the current Wordpress platform and this plugin is no longer needed.  Am I incorrect in this assumption?

A: As @Milo said, wordpress.com is a platform on its own, and everything available on wordpress.com is only available to sites hosted on wordpress.com. The jetpack plugin does however make some features available to self hosted sites but I'm not particulary sure which ones.
The shortcodes you are talking about is only available on sites hosted with wordpress.com, and not self hosted sites.
I have quickly rewritten a script I have recently done to look for filters and action in WordPress to get all shortcodes available to self-hosted sites. Here is the function
function get_all_filters_and_actions2( $path = '' )
{
    //Check if we have a path, if not, return false
    if ( !$path )
        return false;

    // Validate and sanitize path
    $path = filter_var( $path, FILTER_SANITIZE_URL );
    /**
     * If valiadtion fails, return false
     *
     * You can add an error message of something here to tell
     * the user that the URL validation failed
     */
    if ( !$path )
        return false;

    // Get each php file from the directory or URL
    $dir   = new RecursiveDirectoryIterator( $path );
    $flat  = new RecursiveIteratorIterator( $dir );
    $files = new RegexIterator( $flat, '/\.php$/i' );

    if ( $files ) {

        $output = '';
        $array  = [];
        foreach($files as $name=>$file) {
            /**
             * Match and return all instances of apply_filters(**) or do_action(**)
             * The regex will match the following
             * - Any depth of nesting of parentheses, so apply_filters( 'filter_name', parameter( 1,2 ) ) will be matched
             * - Whitespaces that might exist between apply_filters or do_action and the first parentheses
             */
            // Use file_get_contents to get contents of the php file
            $get_file_contents =  file( $file );
            foreach ( $get_file_contents as  $key=>$get_file_content ) {
                preg_match_all( '/add_shortcode\s*(\([^()]*(?:(?-1)[^()]*)*+\))/', $get_file_content, $matches );

                if ( $matches[0] )
                    $array[$name][$key+1] = $matches[0];
            }
        }

        if ( $array ) {
            foreach ( $array as $file_name=>$values ) {
                $output .= '
';
                    $output .= 'File Path: ' . $file_name .'
';
                    $output .= 'The following shortcodes are available';

                    foreach ( $values as $line_number=>$string ) {
                        $whitespaces = '       ';
                        $output .= '
Line reference ' . $line_number . $whitespaces . $string[0] . '
';
                    }
                $output .= '
';
            }
        }
        return $output;

    }

    return false;
}

Because all shortcodes available to the frontend should be in the wp-includes file, we can run the function as follow: (NOTE I have tested this on localhost)
echo get_all_filters_and_actions2( 'E:\xampp\htdocs\wordpress/wp-includes/' );

which output
File Path: E:\xampp\htdocs\wordpress/wp-includes\class-wp-embed.php
The following shortcodes are available
Line reference 31       add_shortcode( 'embed', '__return_false' )
Line reference 60       add_shortcode( 'embed', array( $this, 'shortcode' ) )

File Path: E:\xampp\htdocs\wordpress/wp-includes\media.php
The following shortcodes are available
Line reference 1379       add_shortcode('wp_caption', 'img_caption_shortcode')
Line reference 1380       add_shortcode('caption', 'img_caption_shortcode')
Line reference 1490       add_shortcode('gallery', 'gallery_shortcode')
Line reference 2021       add_shortcode( 'playlist', 'wp_playlist_shortcode' )
Line reference 2270       add_shortcode( 'audio', 'wp_audio_shortcode' )
Line reference 2525       add_shortcode( 'video', 'wp_video_shortcode' )

File Path: E:\xampp\htdocs\wordpress/wp-includes\shortcodes.php
The following shortcodes are available
Line reference 59       add_shortcode( 'footag', 'footag_func' )
Line reference 72       add_shortcode( 'bartag', 'bartag_func' )
Line reference 80       add_shortcode( 'baztag', 'baztag_func' )
Line reference 89       add_shortcode($tag, $func)

Because the shortcodes picked up by the function in wp-includes\shortcodes.php is only samples in comments, we only really have the following shortcodes available by default on self hosted sites

*

*[caption]

*[gallery]

*[playlist]

*[audio]

*[video]

*[embed]
(NOTE: This is as at WordPress 4.4)


text:
Q: How far back in time can we say $\rho_{\gamma}(t) = \rho_{\gamma, 0}a(t)^{-4}$? The equation for the density of light in the universe is
$$ \rho_{\gamma}(a) = \rho_{\gamma, 0}a^{-4} $$
where $\rho_{\gamma, 0}$ is the density of the CMB today.
I understand why this scaling relation holds.
I am wondering what is the domain of validity of the exact same equation
$$ \rho_{\gamma}(t) = \rho_{\gamma, 0}a(t)^{-4} $$
but now with everything as a function of time. It seems the same, but now I have the actual history of the universe in mind.
How far back in time can we extrapolate this relation? My worry is that when we go back in time in the universe, there could be interactions that affect the density of photons. To give an extreme case, I think this fails for the inflation era (in the inflation model), because photons haven't even been produced by the inflaton field, so presumably $\rho_{\gamma}(t) = 0$ at that time.
So how far back does this hold? Back to recombination? To big bang nucleosynthesis? To baryogenesis?

A: Observationally, we understand the expansion rate of the Universe as far back as Big Bang Nucleosynthesis (BBN). Constraints on extra relativistic degrees of freedom during BBN limit how much the expansion history can differ from $a(t)$ calculated in $\Lambda{\rm CDM}$. We don't have concrete observational information about the expansion rate before this time.
Theoretically, the key is to look at the rate of reactions that can create or destroy photons, compared to the Hubble rate. If there is an unbalanced reaction that creates a significant number of photons in a time shorter than the Hubble time, then that would cause the energy density to increase. Reheating or preheating (the proposed processes by which the inflaton field would generate matter at the end of inflation) would be a natural candidate for "photon-genesis" to occur (note: I have never seen the term "photon-genesis" before and as far as I know it is not used to describe a specific process, I am using it here just to convey the idea). It's also possible many photons were generated in electron-positron annihilations after leptogenesis, or similar kinds of annihilation processes.


text:
Q: How to get Bar instance? I have a Bar class:
function Bar() {
    this.myMethod = function() {
        $.ajax({
            ...,
            success: function(msg){
                // I can't get Bar instance with 'this'
            }
        });
    }
}

If ajax is succeeded, I want to do something with Bar instance. What should I do? Create var for the instance outside ajax call?

A: function Bar() {
    var self = this;
    this.myMethod = function() {
        $.ajax({
            ...,
            success: function(msg){
                //Use self here.
            }
        });
    }
}

A: You can either use a variable, like Alex suggests, or create a wrapper function that contains the closure:
[...]
this.myMethod = function () {
   $.ajax({
            ...,
            success: (function (context) {
              return function(msg){
                //Use context here.
              }
            }(this))
        });

   }
[...]

However, if you want to keep it simple, I'd go with Alex's suggestion, since it is more obvious what happens.


text:
Q: Preferences class (java.util.prefs) stores/calls correctly, but XML code doesn't reflect all actions When I run the ClassA.java code below, the prefs.get("key2","") call returns the stored information as expected.  But when I open the actual file(com.apple.java.util.prefs) it doesn't show key2 and value2 for the level2 node (see XML content below Java code).
Even stranger, if I remove the .put("key2", "value2") method and run it again, it still returns the correct value2.  So it's obviously being stored, but why won't any plist editors pick it up?  I used XCode and PlistEdit Pro.
ClassA.java
public class ClassA {
    public static void main(String[] args) {
      new ClassA();
    }

    public ClassA() {
        Preferences prefs = Preferences.userRoot().node("Parent/level1");
        prefs.put("key1", "value1");
        String value1 = _prefs.get("key1", "");
        System.out.println(value1);

        prefs = Preferences.userRoot().node("Parent/level1/level2");
        prefs.put("key2", "value2");
        String value2 = _prefs.get("key2", "");
        System.out.println(value2);
    }
}

Output
value1
value2

com.apple.java.util.prefs.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>/</key>
    <dict>
        <key>Parent/</key>
        <dict>
            <key>level1/</key>
            <dict>
                <key>key1</key>
                <string>value1</string>
                <key>level2/</key>
                <dict/>
            </dict>
        </dict>
    </dict>
</dict>
</plist>


text:
Q: Как создать шаблон класса и потом создать и вызвать функцию типа данного класса? Добрый день! Имеется код:
class Newclass
{
 int x;
 int y;
 type z;
}

Newclass Newfunction(parametrtype1);
Newclass Newfunction2(parametrtype1);

Newclass Newfunction (parametrtype1 parametrname)
{
 //тело функции
}
Newclass Newfunction2 (parametrtype1 parametrname)
{
 //тело функции
}

int main()
{
parametrtype1 variable;
 //вызов функции
Newfunction(variable);
Newfunction2(variable);
}

Дело в том, что по задумке член класса Newclass z - должен получить различные типы данных, в зависимости от того, что возвращает функция. Это можно реализовать с помощью шаблонов, но в данный момент я не могу разобраться, как это реализовать. Помогите пожалуйста.

A: Вот:
#include <iostream>

template<class T>
class Newclass {
public:
  int x;
  int y;
  T z;

  Newclass(T z): z(z) {}
  void Newfunction2(T value) {
    std::cout << this->z << " " << value << std::endl;
  }
};

int return_variable(){
  std::cout << "return int(1)" << std::endl;
  return 1;
}

int main() {
  auto value = return_variable();
  Newclass<decltype(value)> c(value);
  c.Newfunction2(1);
}

Это есть в документации языка.


text:
Q: Fill custom CRM fields in Bitrix via REST API I have the need to fill custom fields in Bitrix24 CRM via REST API.
When it comes to working on standard fields (like TITLE, TEL, etc) it works, but if I try to valorize a custom field by putting it's property name in the request the endpoint simply ignores it.
Here you have a snippet:
$company = CRest::call(
    'crm.company.add',
    [
        'fields' => [
              "TITLE" => "Company 1"
            , "COMPANY_TYPE" => "Customer"
            , "CURRENCY_ID" => 'EUR'
            , "REVENUE" => "123000"
            , "ADDRESS" => "st. some address"
            , "ADDRESS_CITY" => "some city"
            , "ADDRESS_POSTAL_CODE" => "12345"
            , "ADDRESS_PROVINCE" => "some province"
            , "PHONE" => [
                         ["VALUE" => "1230000000", "VALUE_TYPE" => "WORK"]
                        ,["VALUE" => "1234000000", "VALUE_TYPE" => "FAX"]
                     ]
            , "EMAIL" => [ ["VALUE" => "me@company1.com", "VALUE_TYPE" => "WORK"] ]
            , "INDUSTRY" => "MANUFACTURING"
            , "CUSTOM_FIELD" => "Hey I'm not a standard field and I'm going to be ignored"
        ]
    ]
);

Did anyone have the same need? How can I solve it?

A: I found the solution.
Simply write the Field ID instead of the Field Name. The Field ID looks like "UF_CRM_5AERER454DD4". By putting this as key and the value after " => " the property gets valorized.


text:
Q: Confusion regarding interval of a variable. Question:

The values of '$a$' if $f(x)=2e^x-ae^{-x}+(2a+1)x-3$ increases $\forall \;x \in \mathbb R$ are:
$(A)\;[0,\infty) \qquad(B)\;(-\infty,0] \qquad(C)\;(-\infty,\infty)\quad(D)\;(1,\infty)$

Answer: A

Doubt:
As it is given in the question, $f(x)$ is increasing.
$\implies f'(x)>0$
On simplifying $f'(x)>0$ a little, I finally got: $$e^x+a>0 \quad\forall\;x\in \mathbb R$$
which according to me should give $a \in (0,\infty)$, because when $a=0$, then we get $e^x>0$, but on keeping $x=-\infty$, this inequation is not satisfied.
But on putting $a=0$ in $f(x)$, I am getting $f'(x)>0$, which means that the function is increasing when $a=0$ and the answer given is correct.
Kindly explain why $0$ will be included in the interval of $a$.

A: I repeat my comment and give a complete proof inspired by Salah Fatima's answer (which is not complete).
In my comment, I say that as $x\mapsto e^{x}$ and $x\mapsto x$ are increasing functions, we know that it is also the case for $x\mapsto \alpha e^{x}+\beta x$ for any $\alpha,\beta\geq 0$. Similarly, as $x\mapsto e^{-x}$ is decreasing, $x\mapsto \gamma e^{-x}$ is increasing whenever $\gamma <0$ (this is easy to see). Thus, if we take $a\in[0,\infty)$, we know that $(2a+1)\geq 0$ and $-a<0$, thus for these $a$'s, the function
$$f:x\mapsto 2e^{x}-ae^{-x}+(2a+1)x-3$$
is increasing. This restricts the possible answers to $(A)$ and $(C)$.
Now, we could prove that it is decreasing when $a<0$. But the idea (and yours) of Salah Fatima seems better, since finding for which value of $a$ the derivative is positive or $0$ gives us the answer, as the derivative caracterizes the tonicity of a function and is a priori easier to compute.
We have $f'(x)=2e^{x}+ae^{-x}+(2a+1)$. As pointed out by Salah Fatima, this can be factorized in $f'(x)=e^{-x}(2e^{2x}+(2a+1)e^{x}+a)$ and as $e^{-x}>0$ for all $x\in\Bbb R$, it is sufficient to look for $a$ such that $2e^{2x}+(2a+1)e^{x}+a\geq 0$ for all $x\in\Bbb R$.
Let's pose $t=e^{x}$. We have $g(t):=2t^{2}+(2a+1)t+a$ with $t>0$. We know that a quadratic function such as $t\mapsto g(t)$ has the same sign as the coefficient of $t^{2}$ except between the roots. Here, we have $g(t)\geq 0$ when $t>0$ if and only if the two roots are inferior to $0$ or if it has no real roots. Computing the discriminant yields $\Delta = (2a+1)^{2}-8a=(2a-1)^2\geq 0$. Thus, $g(t)$ has always two roots (possibly equal). These roots are :
\begin{align*}
\alpha_{+} &= \frac{-(2a+1)+\vert 2a -1\vert}{4}\\
\alpha_{-} &= \frac{-(2a+1)-\vert 2a-1\vert}{4}
\end{align*}
We know that they have to be less than $0$ for $g$ to be positive everywhere for $t>0$ and thus for $f$ to be increasing. We also know that it works when $a\geq 0$ because of our initial reasoning, so we only have to check $a<0$. Suppose $a<0$. Then, $\vert 2a-1\vert = -2a+1$. Hence,
$$\alpha_{+}\le 0\iff -2a-1-2a+1\le 0\iff -4a \le 0$$
But as $a<0$, this is not possible. Hence, $\alpha_{+}$ has to be strictly positive. We deduce that $a<0$ yields a non-increasing function. Hence, $(A)$ is valid and $(C)$ is not.

A: The derivative is
$$f'(x)=e^{-x}(2e^{2x}+(2a+1)e^x+a)$$
is positive for all $x\in \Bbb R$ if the discriminant is negative.
$$\Delta=4a^2+1+4a-8a=(2a-1)^2\leq 0$$
$$\iff a=\frac{1}{2}$$


text:
Q: WooCommerce Product Title Where is the page title "blog" coming from? I would just like it to display the shop title.
https://www.sunfinityre.com/shop/hats/hat-with-logo/

A: I believe this is coming from your theme.  The HTML output is...

BLOG

Home / Blog

You may want to search your theme for closing for page-header bg or div id="page-title" perhaps and see if you can find the
 output anywhere in there as that may give you a clue.

A:

BLOG

Home / Blog

this is the code of your blog title when you inspect elements.. to do this you need to hide it in your css:

body.single-product #page-title{display:none;}


text:
Q: Set date field in newform to selected date on calendarview I'm looking for a solution where I first select a date on the calendar-view, when I add a new item, the selected date should be filled in on a field in my newform.aspx.
Is this possible out of the box? (I guess not...) Or how would you fix this?
Javascript? Infopath? Custom development?
One thing I have in mind (but it's a lot of work)
Create a custom ribbon action where you first select the date, then click on the ribbon button. With javascript you get the selected date, put it in the querystring. On newpage.aspx you get the querystring (if exists) and fill in the date on the field.

A: When you are viewing a SharePoint 2010 Calendar, if you hover over a day, it will show the "Add" link.  Clicking that will default the date to the date you hovered over.


text:
Q: Javascript как прервать выполнение кода в if? Здравствуйте, допустим есть следующий код:
if(!a) {
 a = true;
 ..
 ..
}

И появилась необходимость не выполнять код в проверке. Как это сделать кроме комментирования его? Если бы это была функция, можно было просто сделать return, но не в этот раз.

A: Смысл в том, что мы заранее пишем условие, которое равно false. Но не уверен, что это будет быстрее и легче, чем внести код в комментарии.
Попробуйте сделать так.
if(false && (!a)) {
 a = true;
 ..
 ..
}

Или вот так.
try
{
 if(!a) {
     throw "Skip";
     a = true;
     ..
     ..
    }
}
catch(e){}


text:
Q: R or id Cannot be resolved I have this problem with my android source in Eclipse. I tried to import com.R; but only the R cannot be resolved disappeared.  I got the id cannot be resolved now. I "developed" in Eclipse with Android a few months ago too, but there wasn't the ID cannot be resolved problem.
What can I do? It is a fresh installed Eclipse+Android ADT+Emulator+ eg...

A: Are you sure you're not importing android.R but instead, your generated R file, i.e. com.myproject.R?

A: I would delete R, And right click your project and go to Android Tools > Fix project properties. That should work.


text:
Q: Shape borders of button created with divs I have to create a button with the shape of a triangle in each side.
My approach was to create a div that contains 4 more divs (one per corner) so I can shape the triangles by overlapping divs, using linear-gradient and white color for the background.
The problem is that I also need to edit a border for the shape created, and it is not possible because every div has its own border.
Any way to obtain borders just for the shape of the final button?

.button {
  height: 50px;
  width: 140px;
  position: relative;
  background: darkred;
}

.button:hover {
  background: black;
}

.text {
  display: flex;
  flex-direction: column;
  justify-content: center;
  text-align: center;
  color: white;
  font-size: 15px;
  font-family: Tahoma;
}

.text:hover {
  color: red;
}

.left,
.right {
  width: 8%;
  height: 50%;
  position: absolute;
}

.left {
  right: 0;
}

.right {
  left: 0;
}

.down {
  bottom: 0;
}

.up {
  top: 0;
}

.left.up {
  background: linear-gradient(225deg, white 87%, white 87%, transparent 0%);
}

.left.down {
  background: linear-gradient(-45deg, white 87%, white 87%, transparent 0%);
}

.right.down {
  background: linear-gradient(45deg, white 87%, white 87%, transparent 0%);
}

.right.up {
  background: linear-gradient(135deg, white 87%, white 87%, transparent 0%);
}

  Discover More

A: Here is an idea with few code and CSS variables to easily adjust the shape:

.box {
  --c:green; /* color */
  --a:30deg; /* angle */
  --b:3px;   /* border thickness */
  --w:20px;  /* width of of arrow */

  padding:30px calc(var(--w) + 20px);
  text-align:center;
  margin:10px;
  background:
    linear-gradient(var(--c) 0 0) top,
    linear-gradient(var(--c) 0 0) bottom;
  background-size:calc(100% - 2*var(--w)) var(--b);
  background-repeat:no-repeat;
  overflow:hidden;
  display:inline-block;
  position:relative;
}
.box::before,
.box::after,
.box span::before,
.box span::after{
  content:"";
  position:absolute;
  box-sizing:border-box;
  left:0;
  top:0;
  height:50%;
  width:var(--w);
  border-right:var(--b) solid var(--c);
  border-bottom:var(--b) solid var(--c);
  transform-origin:0 calc(100% - var(--b)/2);
  transform:scaleY(var(--s,1)) skewY(calc(-1*var(--a)));
}
.box::after,
.box span::after{
  --s:-1;
}

.box span::before,
.box span::after {
  left:auto;
  right:0;
  border-right:0;
  border-left:var(--b) solid var(--c);
  transform-origin:100% calc(100% - var(--b)/2);
  transform:scaleY(var(--s,1)) skewY(var(--a));
}

 some text here

 some text here

 some text
 here

A: The final solution to attend full responsiveness was to create a SVG image as a Vue.js component, where size and shape (called "path" in a SVG) depend on the text inserted.

<template>

      <svg class="atc-button" :height="svgHeight" :width="svgWidth">
        <g @click="handleClickEvent()" class="atc-button-content">
          <path stroke="red" :d="svgPath"></path>
          <text
            class="atc-button-text"
            :x="icon ? '56%' : '50%'"
            y="52%"
            dominant-baseline="middle"
            text-anchor="middle"
          >{{text}}</text>
        </g>
      </svg>

        <fa-icon :icon="icon" class="atc-button-icon"></fa-icon>

</template>


text:
Q: O365 SharePoint blocked users I am trying to migrate old documents from onprem to SPO. All users have been synced via Azure AD, but employees that no longer work here, have been Blocked (Active users - but blocked).
Now it's a business requirement that the history for these documents are preserved, and therefore I need to add some of these blocked users as part of metadata is needed. It's not possible to do it via the peoplepicker in the UI (blocked users can't be found), and neither via CSOM. Is there any workaround for this?
var user = context.Web.EnsureUser(value); // The specified user xx@yy.com could not be found


text:
Q: Event.preventDefault does not work when I input cjk(korean) on number type v-text-field I am working on a vue project and this is a fix for little bug.
But it makes me so hard.
I made v-text-field is inputted only numbers and it seems to work good.
<v-text-field type="number">

And I want to input Only Number so I use keydown event for using preventDefault.
<v-text-field type="number" @keydown="testKeydown">

testKeydown(event) {
  if(event.key !== "1" && ... && event.key !== "Delete" && event.key !== "Backspace") {
    console.log("Wrong Input!!!");
    event.preventDefault();
  }
}

This code can prevent inputting exponential value 'e', 'E' and '+', '.'.
But it can not prevent Korean (maybe CJK) such as 'ㅁ'. (When I input Korean, event.key returns 'Process') And 'Wrong Input!!!' is logged my Chrome console.
Also, the value of v-text-field shown on the screen is '123ㅁ', but the value of event.target.value taken with console.log(event) is ' '.
I want to prevent Korean characters (or CJK) from being input or to erase them immediately even if they are entered without removing 'type="number"'.
What can I do for it?

A: This is called composition, it happens on certain IME when you need to type multiple strokes before composing a single character.
There are compositionstart and compositionupdate events which will fire in such cases, so you should have been able to handle these directly there and cancel them... Except that no browser supports cancelling these events yet...
So you have no choice but to wait for this composition to end, and to remove the bad inputs afterward. And the best for this is probably to listen for the input event. (Ps: you may anyway prefer to check for the input's value instead of testing all event.key, at least to catch pasted content.)


text:
Q: Log collection from Android devices I've been reading recently about Fluentd and Fluent-bit as tools for log unifying and collection.
The documentation says it supports a few Linux distributions but I couldn't find any reference to Android - either that it is supported or not supported.
Any idea if Fluent-bit can be compiled to run on Android?
Alternatively, are there other tools such as Fluent-bit for Android?
Thanks


text:
Q: red group name color Xcode shows group name with red color.

How to remove this or make it normal
I am using Xcode 9

A: Basically this problem occurs when folder miss match with original path
Step 1 Select red folder/group
Step 2 Select file inspector from right panel of Xcode and click Folder icon

Step 3 Choose correct path and enjoy...

A: Use Below Steps:-

*

*In Xcode Right click on Feed -> Show in Finder -> Copy all content

*In Xcode Right click on Feed -> Delete -> Move to Trash

*Go in Show in Finder where you have to create folder -> Create folder with name Feed -> Paste copied content -> Drag Feed folder to Xcode.


text:
Q: Difference between SMPP+ and SMPP What is the difference between smpp+ and smpp. What I understood is that SMPP+ is SMPP + Some prepaid API. But I want to know is what all are the difference in PDUs and what all additional features are there. Googling didn't give me a document worth understanding ....

A: There is no such thing as SMPP+. In real life situations there are only SMPP versions 3.3, 3.4 and 5.0; of them 3.4 being the most common by far.
The SMPP+ you mention might be some proprietary extension of SMPP by an operator or SMS gateway but there is no standard for SMPP+.

A: The SMPP+ is a proprietary version of SMPP used for USSD services. Therefore it contains some USSD-specific optional parameters, while other values of some mandatory parameters are used for USSD.
Optional parameters used for USSD in SMPP+ submit_sm:

*

*ussd_service_op

*ussd_session_id

*language_indicator

Optional parameters used for USSD in SMPP+ deliver_sm:

*

*ussd_service_op

*ussd_session_id

*language_indicator

*imsi

*hlr_address_ton

*hlr_address_npi

*hlr_address

*vlr_number_ton

*vlr_number_npi

*vlr_number_addr

A: The SMPP+ term is mostly used by telecommunication solution providers to highlight that they extended the standard protocol by introducing optional TLVs to fulfill required functionality through SMPP API. USSD, SMS and LBS gateways mostly used those special TLVs for several reasons :

*

*To present USSD session direction; Mobile originated or terminated.

*To differentiate continuous USSD session as menu and push-pull requests(e.g. like balance query)

*To track different USSD sessions as USSD session Id

*Prioritization between SMS submission from ESME applications

*Querying current cell id of MSISDN through LBS gateway

*Retrieving serving MSC and HLR addresses.


text:
Q: Space character within symbol literals I need to query a database which contains names of companies. I have list of around 50 names, for which i have to get the data. But I am unable to write a query using in command as there spaces in a name which are not being recognized. ex
select from sales where name in (`Coca Cola, `Pepsi)

This is giving me an error as 'Cola' is not being recognized. Is there a way to write such a query?

A: The spaces between the strings cause the interpreter to get confused. The `$() casts the list of characters to symbols.
q)t:([] a:1 2 3; name:`$("coca cola";"pepsi";"milk"))

q)select from t where name in `$("coca cola";"pepsi")
a name
-----------
1 coca cola
2 pepsi

You may also want to be careful of casing and either use consistently lower or upper case else that would cause unexpected empty results:
q)select from t where name in `$("Coca Cola";"Pepsi")
a name
------

q)select from t where upper[name] in upper `$("Coca Cola";"Pepsi")
a name
-----------
1 coca cola
2 pepsi

A: You need to do something like the following:
select from sales where name in `$("Coca Cola";"Pepsi")


text:
Q: Bundle vs PersistableBundle in Android I am confused about when to use PersistableBundle class instead of Bundle class. What is the advantage of using it? Could anyone clarify it?

A: Simply put, PersistableBundle is a type of bundle that is disk safe. PersistableBundle and Bundle both extend the BaseBundle class. PersistableBundle class is considered disk safe because it restricts the object types to really simple ones unlike the Bundle class. It's useful when working with Job Services and Job Schedulers.
You can check the android documentation here

A: It is exactly what it says it is.

A mapping from String keys to values of various types. The set of types supported by this class is purposefully restricted to simple objects that can safely be persisted to and restored from disk.

You can put just about anything in a regular Bundle. A PersistableBundle however only accepts certain types:
public static boolean isValidType(Object value) {
    return (value instanceof Integer) || (value instanceof Long) ||
            (value instanceof Double) || (value instanceof String) ||
            (value instanceof int[]) || (value instanceof long[]) ||
            (value instanceof double[]) || (value instanceof String[]) ||
            (value instanceof PersistableBundle) || (value == null) ||
            (value instanceof Boolean) || (value instanceof boolean[]);
}

This restriction is there in order to make it persistable. Considering a regular Bundle can contain all kinds of (custom) data, it can be complex to persist that data to disk. For PersistableBundle this is easier, because you know that it simply can't contain such complex data.


text:
Q: Dynamic method creation from block parameter I have the following structure of data
array_of_hashes = [{"key"=>"2020-10-01",
  "foo"=>"100",
  "bar"=>38,
  "baz"=>19,
  "losem"=>19,
  "ipsum"=>0,
  ...},
...
]
state =  {["", nil, nil, nil, nil]=>
          #<MySimpleObject:0x0000557fb9fe4708
          @foo=0.0,
          @bar=0.0,
          @baz=0.0,
          @lorem=0.0,
          @ipsum=0.0,
          ...}

array_of_hashes.each_with_object(state) do |stats, memo|
  state = memo['key']

  state.foo = stats['foo'].to_d
  state.bar = stats['bar'].to_d
  state.baz = stats['baz'].to_d
  state.lorem = stats['lorem'].to_d
  state.ipsum = stats['ipsum'].to_d
  ...
end

How may I follow dry in this case?
I need smth to generate and execute methods in runtime like:
query.each_with_object(shared_state) do |stats, memo|
  state = memo['key']

  columns = %w[foo bar baz lorem ipsum ...]
  columns.each { |attribute|
    define_method attribute do #??????
      state.attribute = stats[attribute.to_s].to_d
    end
  }
end

As I got it define_method is not suitable for this situation.

A: Short answer, don't! This will make your code incredible hard to read. What you have in your first example is perfectly fine in my opinion. Not everything needs to be DRY.
If you really really want to do it, you can use send
query.each_with_object(shared_state) do |stats, memo|
  state = memo['key']

  columns = %w[foo bar baz lorem ipsum ...]
  columns.each do |attribute|
    state.send("#{attribute}=", stats[attribute].to_d)
  end
end

https://apidock.com/ruby/Object/send


text:
Q: Login Security: How to Disable Multiple login I want to disable multiple login on my web. For example when a user already login on the system. System should disable the user to login again on another browser or computer. Currently I tried doing this by using the database. I have a column like login_status, Once the user is login it will update to 1 and 0 for offline. If you the user closes the the browser without logging out. It will remain login, the user should ask the admin to log him out. The problem is we want to automatically logout the user by max of 30min idle time. I'm having a hard time how to do this.
Is there a way to disable multiple login and determine if the user was idle and automatically log him out? I'm thinking about cookies and session.

A: The reason a visitor can log in from multiple locations at once is, because whenever they log in ASP.net assigns them the same authentication token.  So, the authentication token in itself doesn't allow you to distinguish between the locations the user is logging in from.
There are probably many ways around this, but in principle all you need to do is store some identifying information in the user's session state and check this on each request. E.g.  When they log in, their IP address could be stored as session data. Then for every subsequent authenticated request, the IP the request comes from could be compared to the IP of the current one. If the two don't match then log the user out.
Alternatively, if IP isn't a good enough identifier (e.g. if a user is logging in from behind a router multiple PCs will share IPs) then you can add some identifying information to the users authentication token at the point of login. Here is a tutorial on how to do that:
http://www.danharman.net/2011/07/07/storing-custom-data-in-forms-authentication-tickets/
Each time they login a unique GUID can be generated and stored both as session data and also as part of the authentication token.  On each request you compare the two, logging the user out on a fail.
These are a couple of possibilities - I'm sure there are others.
An even better way may be to influence the asp.net authentication token itself when asp.net generates it to introduce some change, but I'm not sure this is possible.
Googling gave me nothing.

A: Not ideal by all means, but add a SignInLockTime field alongside the login_status bit field and write the time of updating the login status while updating the login status. From there you can have an app-configured timeout, so if timeout time has passed since SignInLockTime you can auto-unlock.

A: From your response to your question, it seems that what you actually want to do is to prevent users being logged in from two locations simultaneously... is that correct?
How about storing the session id against the user record in your database.  When the user logs in, replace the session id in the database.  On every authorization request, you then check the supplied session id with that stored against the user record - if it's different then they are logged in elsewhere, so redirect them to the login page again.  This way, logins on other machines are possible but existing sessions on other machines will be invalidated as a result of the new login.

A: Please refer to:
When the same user ID is trying to log in on multiple devices, how do I kill the session on the other device?
Out of the box, .NET does not support this.  .NET allows for concurrent log-ins, as I'm sure you're aware.
I had this same exact requirement, and came up with a pretty slick solution, demonstrated in the link above.  In a nutshell, my requirement was to only have one user log-in happening at one time.  If that same user ID tried to log in elsewhere, then it killed the session for the first log-in by checking for an existing log-in under a different Session ID (this enabled the user ID to be logged in from multiple instances of their web browser on their computer [same Session ID], which is common, but not from a different computer [different Session ID] (possibly due to someone that stole their credentials, for example)).  Through modification of the code you could probably change the behavior of this - i.e., prevent the second log-in attempt instead of killing the first log-in that's already active and in use.
Of course, it may not fit 100% to what you're needing, so feel free to modify it to fit your needs.

A: One simple (but not good ) option is to logout user on Session_End end event.. But i am not sure this is a good option to do..


text:
Q: Improper integral $\int\limits_0^\infty x\exp (-x-x^2)\,\text dx$ Integrate $\int\limits_0^\infty
x\exp (-x-x^2)\,\text dx$
Hint: Use $\int\limits_0^\infty
\exp (-x-x^2)\,\text{d}x = 0.4965$
I don't know how to use this hint in solving the integration. Help!

A: $I= \int xe^{-x-x^2}dx = \frac{1}{2} \left[ \int (2x-1+1)e^{-x-x^2}dx\right]=\frac{1}{2} \left[ \int (2x+1)e^{-x-x^2}dx - \int e^{-x-x^2}dx \right]$
Observe that $\frac{d}{dx}(-x-x^2)=-(1+2x)$
Thus the previous expression simplifies to $\frac{1}{2} \left[ -e^{-x-x^2} - \int e^{-x-x^2}dx \right]$
On applying the limits we get $\int_0^{\infty} xe^{-x-x^2}dx=\frac{1}{2} \left[ -e^{-x-x^2} - \int e^{-x-x^2}dx \right]_0^{\infty} = \frac{1}{2} \left[0-(-1) - 0.4965\right] = \frac{1}{2} \left[ 0.5035 \right]=0.25175$

A: $$x\,e^{-x^2-x}=\frac 12(2x+1-1)\,e^{-x^2-x}=\frac 12(2x+1)\,e^{-x^2-x}- \frac 12e^{-x^2-x}$$ So, $$\int x\,e^{-x^2-x}\,dx=\frac 12\int(2x+1)\,e^{-x^2-x}\,dx- \frac 12\int e^{-x^2-x}\,dx$$ For the first integral changing variable $$x^2+x=u\implies du=(2x+1)dx$$ seems to meake the problem simple.
Concerning the value given wrong, computing $$I=\int e^{-x^2-x}\,dx$$ complete the square and change variable $x+\frac 12=y$ to get $$I=e^{\frac{1}{4}}\int e^{-y^2}\,dy=\frac{1}{2} \sqrt[4]{e} \sqrt{\pi } \text{erf}(y)=\frac{1}{2} \sqrt[4]{e} \sqrt{\pi } \text{erf}\left(x+\frac{1}{2}\right)$$ which makes $$\int_0^\infty e^{-x^2-x}\,dx=\frac{1}{2} \sqrt[4]{e} \sqrt{\pi } \text{erfc}\left(\frac{1}{2}\right)\approx 0.545641$$


text:
Q: Performing actions from accelerometer I'm very new to programming in Xcode and have already hit a brick wall.
What I am trying to do is to get a sound to play if there is sufficient acceleration detected.
Can someone please advise me on what I am doing wrong? (I suspect its everything).
CODE:
#import "LZDViewController.h"

@interface LZDViewController ()

@end

@implementation LZDViewController

- (void)viewDidLoad;{

[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
CMAccelerometerData *accelerometerData = self.motionManager.accelerometerData;
if (fabsf(accelerometerData.acceleration.x) > 1.2
    || fabsf(accelerometerData.acceleration.y) > 1.2
    || fabsf(accelerometerData.acceleration.z) > 1.2)
{
    NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/audio.wav", [[NSBundle mainBundle] resourcePath]]];
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    audioPlayer.numberOfLoops = 0;

    [audioPlayer play];

}
}

@end

EDIT:
Here is the code for my .h
#import <UIKit/UIKit.h>
#import <CoreMotion/CoreMotion.h>
#import <AVFoundation/AVFoundation.h>
@interface LZDViewController : UIViewController
//{AVAudioPlayer *audioPlayer;}

@property (strong, nonatomic) CMMotionManager *motionManager;
@property (strong, nonatomic) AVAudioPlayer *audioPlayer;

@end

I'm still not getting any joy at all, and I do apologise for the hand holding.
All I get is a white screen but the sound file never plays. I have imported the correct framework and can get the sound playing with just a button, but I really want to play with the accelerometer.
Thanks

A: Alright, the first thing you're going to want to do is define two properties in either your interface file, or in the interface extension at the top of your implementation file. These will be the motion manager, and the audio player.
@property (strong, nonatomic) CMMotionManager *motionManager;
@property (strong, nonatomic) AVAudioPlayer *audioPlayer;

Then we can get everything else done in viewDidLoad. The code below sets up a new operation queue for the motion manager to receive accelerometer events on, initializes the audio player and the motion manager, and then starts getting accelerometer updates at an interval of 30 times per second.
Finally, within the accelerometers update block, just use the same logic you already build to check the acceleration data and if it meets your requirements continue on to the next condition.
**I have configured this example to not start playing the sound again if the player is already playing
- (void)viewDidLoad
{
    [super viewDidLoad];

    NSOperationQueue *motionQueue = [NSOperationQueue new];

    NSURL *url = [NSURL URLWithString:[[NSBundle mainBundle] pathForResource:@"audioFile" ofType:@"m4a"]];
    self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    [self.audioPlayer prepareToPlay];

    self.motionManager = [CMMotionManager new];
    [self.motionManager setAccelerometerUpdateInterval:1.0f/30.0f];

    [self.motionManager startAccelerometerUpdatesToQueue:motionQueue withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
        if (fabsf(accelerometerData.acceleration.x) > 1.8 || fabsf(accelerometerData.acceleration.y) > 1.8 || fabsf(accelerometerData.acceleration.z) > 1.8) {
            NSLog(@"%@",accelerometerData);
            if (self.audioPlayer) {
                if (!self.audioPlayer.isPlaying) {
                    [self.audioPlayer play];
                }
            }
        }
    }];
}


text:
Q: Efficiently draw combinations with "maximum diversity" On can create all possible combinations with n elements from a given array like:
from itertools import combinations
[*combinations(range(4), 2)]
# [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]

I'm trying to find a way to adapt this in order to find m of these combinations with "maximum diversity". What I mean by that is probably best explained by an example:
diverse_combinations(range(4), n=2, m=3)
# either of these would be what I'm looking for
# [(0, 1), (2, 3), (0, 2)]  # or
# [(0, 1), (2, 3), (1, 2)]  # or
# [(0, 2), (1, 3), (0, 1)]  # ...

So I basically want the individual elements in the combinations of my subset to be as close uniformly distributed (or as close as possible). Therefore this is not quite what I want:
def diverse_combinations(arr, n, m):
    for idx, comb in enumerate(combinations(arr, n)):
        if idx == m:
            break
        yield comb

[*diverse_combinations(np.arange(4), n=2, m=3)]
# [(0, 1), (0, 2), (0, 3)]

Finally, the case I'm looking at is performance sensitive since it comes down to something like:
diverse_combinations(range(100), n=50, m=100)
# a list with 100 tuples of len=50 where each element appears
# ~equally often

I'm glad for any hints!

A: Okay, so I came up with this solution, which works reasonably well. I put it here in case its helpful for somebody else:
# python3
import numpy as np
from scipy.special import comb

def diverse_combinations(arr, size, count):
    if count > comb(len(arr), size):
        raise ValueError('Not enough possible combinations')
    possible_draws = np.floor(len(arr) / size).astype(int)
    combs = set()
    while len(combs) < count:
        new_combs = np.random.choice(
            arr, size=(possible_draws, size), replace=False)
        combs.update([tuple(sorted(cc)) for cc in  new_combs])
    return [*combs][:count]

Which gives a reasonable approximation of the desired behaviour:
# this case has an exact solution
np.unique(diverse_combinations(range(100), 50, 100), return_counts=True)[1]
# array([50, 50, 50, 50, 50,...

# here 50 elements appear one time more often
np.unique(diverse_combinations(range(100), 50, 101), return_counts=True)[1]
# array([50, 50, 51, 50, 51,...

# if 'arr' is not divisible by 'size' the result is less exact
np.unique(diverse_combinations(range(100), 40, 100), return_counts=True)[1]
# array([44, 45, 40, 38, 43,...


text:
Q: Reversed name in shorthand division of bibliography Using Biblatex with LyX I've managed to get a subdivided bibliography almost the the way I want it. The idea is to cite the key works with abbreviations that are conventional to my subject. For this I have used shorthands like this:
\printbibheading
\printshorthands[heading=subbibliography,title={Værker af Wittgenstein}]
\printbibliography[heading=subbibliography,title={Andre værker},notkeyword=witt]

This is an extract from the .bib file with one item with a shorthand entry and one without (I've given the shorthand items the keyword "witt", so that I can exclude them from being printed in the regular bibliography):
@BOOK{rorty_philosophy_1980,
  title = {Philosophy and the Mirror of Nature},
  publisher = {Princeton University Press},
  year = {1980},
  author = {Rorty, Richard},
}

@BOOK{wittgenstein_certainty_1979,
  title = {On certainty},
  publisher = {Blackwell},
  year = {1979},
  author = {Wittgenstein, Ludwig},
  editor = {Anscombe, {G.E.M} and Wright, {G.H.} von and Paul, Denis},
  address = {Oxford},
  shorthand = {OC},
  keywords = {witt},
}

The output is this:

The only problem is that the names in the shorthands division aren't reversed "Surname, Name"-style like the other part of the bibliography. How would I go about changing that?

A: The possible problem is in the way the biblatex style used defines the formatting instruction for the names. For the bibliography it seems it use last-first, while the standard definition for the shorthands inherit the formatting instruction form the bibliography entry, but it uses first-last formatting for the names; Namely, the  definition is:
\DeclareBibliographyDriver{shorthands}{%
  \usedriver
    {\DeclareNameAlias{sortname}{first-last}}
    {\thefield{entrytype}}%
  \finentry}

Thus, one can change the  definition above
\DeclareBibliographyDriver{shorthands}{%
  \usedriver
    {\DeclareNameAlias{sortname}{last-first}}
    {\thefield{entrytype}}%
  \finentry}

or changing last-first to default or last-first/first-last. To be sure we need a minimal working example and knowing the style used.


text:
Q: nrf24l01 transceiver on altera board de2-115 I'm trying to use the nrf24l01 transceiver on altera board de2-115. I would like to send a signal from the altera board using this spi module to another spi module and use the spi module on the receiving side to turn on an LED and a vibrating motor. Does anyone know if this board works with this spi module and how ?

A: The DE2-115 FPGA board does not have any hardware dedicated to SPI (actually, it does for loading its configuration from flash, but not for other uses), so the SPI logic must be synthesized using the FPGA fabric.
There are a few different options as to how the SPI logic will interface with other system components. In the end, all choices end up using GPIO for output. One would select four pins to use (clk, mosi, miso, and cs) and assign your module's ports to those pins.
But, there are a few different choices you have for how to interface your controlling logic with the SPI core:

*

*Use a "normal" verilog module

*Use a SPI component (Altera provides one for their Avalon bus architecture)

*Instantiate a CPU (such as NIOS) and use bit-banging to construct the SPI signals using a 4-bit "conduit".

If you're using an Avalon bus already, I'd suggest that method #2 would be the simplest. But, if you are not using SoC design techniques, you may want to investigate writing (or buying or downloading) a pre-written SPI-interface module.


text:
Q: Query changed since last execution in SSRS I have a dataset created in SSRS using VS 2017.  After the initial code created in query builder, I go the text window to add in a COUNT function.  As soon as I do this, I start getting a text window with the old code intermittently blinking with the new changes.  A warning triangle appears in the top cell of the row selector column that says "Query changed from last execution" once I hover over the triangle.  Once this happens, the window will not allow any changes.
This is, no doubt, a bug.  I also experienced this in VS 2019.  Since I can close out of VS 2017, reboot, re-open the report, the intermittent blinking still occurs.  What I have is a corrupted report and have to delete it.  I want to avoid having to create and delete projects based on a bug that I cannot find any resolution for.
Does anybody have any experience with this?

A: Faced the same problem.
Was able to fix it by using "Stored procedure" instead of "Text" in Dataset properties window.


text:
Q: Constraints related issue in scipy.optimize.minimize I've got a function g which I'm minimizing over an array coeffs subject to a list of constraints cons.
If I use
n = 2
cons2 = [{'type': 'eq', 'fun': lambda cts: 1 - sabs(apNn(n,n,np.roll(cts, - 0 * 2**(n + 1))))},
            {'type': 'eq', 'fun': lambda cts: 1 - sabs(apNn(n,n,np.roll(cts, - 1 * 2**(n + 1))))}]
ans = scipy.optimize.minimize(g, coeffs, constraints=cons2)

then everything works fine. (sabs and apNn are functions I've defined previously.).
However if I generate the constraints in a loop and use:
cons = []
for v in range(2):
    cons.append({'type': 'eq', 'fun': lambda cts: 1 - sabs(apNn(n,n,np.roll(cts, - v * 2**(n + 1))))})
ans = scipy.optimize.minimize(g, coeffs, constraints=cons)

then the optimization fails with message Singular matrix C in LSQ subproblem. Given that the for loop  is generating exactly the same thing I can't see where this difference is coming from.


text:
Q: Retrieve maximum value from a table containing duplicate values according to a condition I have a table tbl_usertests from which i want to retrieve the user who have maximum testscore for each test.
Note: User here means usertestid which is unique.
Its colums are:
    pk_usertestid   attemptdate     uploaddate  fk_tbl_tests_testid     fk_tbl_users_userid     testscore   totalquestionsnotattempted  totalquestionscorrect   totalquestionsincorrect     totalquestions  timetaken   iscurrent

data :
1;NULL;"2010-06-24 22:48:07";"11";"3";"1";"53";"1";"21";"75";"92";"1"
2;NULL;"2010-06-25 01:21:37";"11";"4";"13";"0";"13";"62";"75";"801";"1"
3;NULL;"2010-06-25 01:21:50";"10";"4";"17";"5";"17";"53";"75";"640";"1"
4;NULL;"2010-06-25 01:24:23";"11";"4";"13";"0";"13";"62";"75";"801";"1"
5;NULL;"2010-06-25 01:24:47";"10";"4";"17";"5";"17";"53";"75";"640";"1"
6;NULL;"2010-06-25 01:36:04";"11";"5";"13";"0";"13";"62";"75";"801";"1"
7;NULL;"2010-06-25 01:47:26";"7";"5";"10";"1";"10";"49";"60";"302";"1"

My Query is :
SELECT max(`testscore`) , `fk_tbl_tests_testid` , `fk_tbl_users_userid` , `pk_usertestid`
FROM `tbl_usertests`
GROUP BY `fk_tbl_tests_testid`

This query output:
max(`testscore`)    fk_tbl_tests_testid     fk_tbl_users_userid     pk_usertestid
    10                7                          5                     7
    17               10                          4                     3
    13               11                          3                     1

But the problem is that if there are two users who have same score, it displays only one user because i have used group by clause.
For. e.g. testid =10 i have two records(pk_usertestid 3 and 5) but it displays 3 only.
I want the user whose upload date is less than the other user(in case of two users having same testscore). It should display for usertestid=3 since 3 upload date is less than 5.
Right now its displaying 3 but it is due to group by clause.
I am unable to construct the query.
Please help me on this
Thanks

A: Try this:
SELECT  t.`fk_tbl_tests_testid` , t.`fk_tbl_users_userid` , t.`pk_usertestid`, maxscores.maxscore
FROM `tbl_usertests` t
JOIN (SELECT `fk_tbl_tests_testid`,max(`testscore`) as maxscore
    FROM `tbl_usertests`
    GROUP BY `fk_tbl_tests_testid`) maxscores ON t.`fk_tbl_tests_testid` = maxscores.`fk_tbl_tests_testid`

the logic behind is to separate the whole thing into two parts: get the maximum (or any other aggregate) values for each group (this is the subquery part), then for each element, join the corresponding aggregate. (JOIN it back to the riginal table)


text:
Q: How to decode a PDF file encoded with some format (probably FlateDecode) in Node.js and extract the plain text content from it?
*

*I'm building a whatsapp chatbot wherein I have to scrape the content of a pdf sent by the user to the bot.

*Whatsapp automatically downloads the file and uploads it to its the cloud and we get the url to access the pdf (but only with a USER-ACCESS-TOKEN)

*We can download that pdf using a get request to the url and it returns a 'response' object wherein, 'response.data' has the content of the pdf.

*But I'm getting the output in this format and I need to convert it to the text/binary format.

Here's the output image :
Here's the code :
const express = require("express");
const app = express();
const pdfParse = require("pdf-parse");

var axios = require('axios');
var data = '';

var config = {
  method: 'get',
  url: 'https://lookaside.fbsbx.com/whatsapp_business/attachments/?mid=915538742783704&ext=1675024946&hash=ATukNLxGTZLE0ouRUk7BehJGM57FuckuOi2fMwBGE4eHdA',
  headers: {
    'Authorization': `Bearer ${process.env.TOKEN}`
  },
  data : data
};

axios(config)
.then(function (response) {
  console.log(JSON.stringify(response.data));
})
.catch(function (error) {
  console.log(error);
});

const port = 8000;

app.listen(port,()=>{
    console.log(`\n\nApp is running at port ${port}\n\n`);
})

PS : Get request through Postman is giving the output as preview to the pdf with an option to download.


text:
Q: Selecting row value only if other rows are equal I have a table with an id column and a source column.
I want to return only the source values that all ids share.
E.g. in the table below id 1,2,3 all share 10 and 20, but id 3 is missing the source value 30, so 30 is not valid and I want to return 10 and 20.
I'm using MySQL and want to put this in a stored procedure.
How do I do this?

id
source

1
10

1
20

1
30

2
10

2
20

2
30

3
10

3
20

A: You may use COUNT(DISTINCT) function as the following:
SELECT source FROM
table_name
GROUP BY source
HAVING COUNT(DISTINCT id)=(SELECT COUNT(DISTINCT id) FROM table_name)

To do this within a stored procedure:
CREATE PROCEDURE getSourceWithAllIds()
   BEGIN
   SELECT source FROM
   table_name
   GROUP BY source
   HAVING COUNT(DISTINCT id)=(SELECT COUNT(DISTINCT id) FROM table_name);
   END

The idea is to select the count of distinct id values for each source, which is done by COUNT(DISTINCT id)... GROUP BY source, then match this count with the distinct count of all id values existed in the table; HAVING COUNT(DISTINCT id)=(SELECT COUNT(DISTINCT id) FROM table_name).
If the two counts are equal, then the source have all the distinct ids existed in the table.
i.e. All distinct ids in the table are (1, 2, 3) count = 3, and distinct ids for a source =10 are (1, 2, 3) count=3. For source = 30, the distinct ids are (1, 2) count=2 so it will not be returned by the query (2<>3).
See a demo.


text:
Q: java.net.SocketException: socket closed Здравствуйте программисты. Помогите решить очередную задачу. Второй день копаюсь и не понимаю в чём проблема.
На компьютере запущен сервер на порту 5500. К нему присоединяется клиент, в роли которого - Android приложение. Оно сразу же отправляет запрос серверу. Сервер, после обработки запроса отправляет ответ Android приложению. Но к сожалению, получить ответ не получается: java.net.SocketException: socket closed. Внизу части исходного кода, в котором, вероятно, должна быть моя ошибка.
Исходный код Android приложения:
1) Класс получения ответа от сервера
class SocketManager {

    static Socket i3;
    static Boolean i4 = false;
    static String i5;

    public static String i1(final Properties i1, final String i2) {
        try {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        i3 = new Socket();
                        i3.setSoTimeout(4000);
                        i3.connect(new InetSocketAddress(i1.getProperty("hostIp"), 5500), 4000);
                        String i6 = i1.getProperty("username") + System.lineSeparator() + i1.getProperty("password");
                        if (i2 != null) {
                            i6 += System.lineSeparator() + i2;
                        }
                        BufferedWriter i7 = new BufferedWriter(new OutputStreamWriter(i3.getOutputStream()));
                        i7.write(i6);
                        i7.flush();
                        //=== ВОТ ЭТА СТРОЧКА ВЫЛЕТАЕТ @
                        i5 = new BufferedReader(new InputStreamReader(i3.getInputStream())).readLine();
                        //===
                    } catch (Exception e1) {
                        Log.d("", e1.toString());
                        i5 = null;
                    }
                    i4 = true;
                    return;
                }
            }).start();
            while (!i4) {
            }
            i3 = null;
            return i5;
        } catch (Exception e1) {
            return null;
        }
    }

}

2) Как с помощью класса SocketManager получить ответ сервера:
Properties i1 = new Properties();
// Загружаю файл с логином и паролем. Его содержимое:
//      hostIp = мой IP-адрес
//      username = user
//      password = user
i1.load(new FileInputStream("file.properties"));
String i2 = "мой запрос на сервер";
// Получаю и показываю ответ от сервера
Toast.makeText(this, "Ответ сервера следующий:" + System.lineSeparator() + SocketManager.i1(i1, i2), Toast.LENGTH_LONG).show();

Исходный код сервера на компьютере:
public Void i1() {
    String i1 = "";
    // 'this.i1' это 'myServerSocket.accept()'
    BufferedReader i11 = new BufferedReader(new InputStreamReader(this.i1.getInputStream()));
    while (true) {
        String i2 = i11.readLine();
        if (i2 == null) {
            break;
        } else {
            i1 += System.lineSeparator() + i2;
        }
    }
    i1 = i1.substring(System.lineSeparator().length(), i1.length());
    System.out.println(i1);
    String[] i2 = i1.split(System.lineSeparator());
    // И тут определяем, что надо приложению
    if (i2[1].equals("команда 1") {
        i2("user".getBytes());
    } else {
        i2("false".getBytes());
    }
    return null;
}

private Void i2(byte[] i1) throws Exception {
    if (this.i1.isConnected() && !this.i1.isClosed()) {
        OutputStream i2 = this.i1.getOutputStream();
        i2.write(i1);
        i2.flush();
    }
    return null;
}


text:
Q: form_validation : error message array shows the default I'm working on a form_validation. I have set the error messages, but it only shows the first error I've set. Other than that, it shows the default message.
$this->form_validation->set_rules('email','Email','required|valid_email|is_unique[user.email]',
    array(
      'required'=>'Empty email',
      'is_unique[user.email]'=>'Email has been registered')
);

If I don't fill the email form, it shows 'Empty email'. If I write the email the same as in database, it shows the default error of CI : 'The Email field must contain a unique value.'
How I can show 'Email has been registered'?

A: Try:
$this->form_validation->set_rules('email','Email','required|valid_email|is_unique[user.email]',
    array(
      'required'=>'Empty email',
      'is_unique'=>'Email has been registered')
);

DOCS: https://www.codeigniter.com/userguide3/libraries/form_validation.html#cascading-rules
I suspect you aren't getting the right error message because you shouldn't repeat user.email for the errors array.


text:
Q: Shake control for Windows Phone 7 How would I use the accelerometer in WinPho7 to detect shaking the phone and have that trigger an event.  For example, to roll dice, you would shake the phone.

A: Here are 3 solutions, each with code:
http://www.j2i.net/BlogEngine/post/2010/07/31/Detect-Shaking-Motion-on-Windows-Phone-7.aspx
http://blog.markarteaga.com/ShakeDetectionOnWindowsPhone7.aspx
http://www.codeproject.com/Articles/98492/Detect-Shaking-Motion-on-Windows-Phone-7.aspx

A: You would be after the Accelerometer class in the Microsoft.Devices.Sensors namespace.
While this quick how-to is targeted at XNA game development, it gives a good example of the usage of the Accelerometer class.


text:
Q: Find duplicate files: keep older version I need a command line tool to remove duplicate files.
There are several. But I could not find one which always keeps the older files and deletes the newer versions.
I tried finddup, duff, fdupes. Maybe I was blind, but AFAIK there was not way to tell the tools to keep the older file.

A: Probably too late for the O.P. but maybe useful to others:
rmlint --rank-by m [paths]

... will search in [paths] for duplicate files and create a shell script (rmlint.sh) that you can use to delete the duplicates.  The --rank-by m option tells it to keep the file with the oldest mtime in each set.  There are also several other original selection criteria options


text:
Q: LDAP connection behaving weirdly over SSL I am trying to connect to my organization's LDAP server using JAVA. I'm using the following code of SSLPoke to test the connection.
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import java.io.*;

/** Establish a SSL connection to a host and port, writes a byte and
 * prints the response. See
 * http://confluence.atlassian.com/display/JIRA/Connecting+to+SSL+services
 */
public class SSLPoke {
    public static void main(String[] args) {
        if (args.length != 2) {
            System.out.println("Usage: "+SSLPoke.class.getName()+" <host> <port>");
            System.exit(1);
        }
        try {
            SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
            SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket(args[0], Integer.parseInt(args[1]));

            InputStream in = sslsocket.getInputStream();
            OutputStream out = sslsocket.getOutputStream();

            // Write a test byte to get a reaction :)
            out.write(1);

            while (in.available() > 0) {
                System.out.print(in.read());
            }
            System.out.println("Successfully connected");

        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
}

I imported the LDAP's certificate in my truststore. I am able to connect sometimes, while in majority of the cases I get -
sun.security.validator.ValidatorException: PKIX path building failed: sun.securi
ty.provider.certpath.SunCertPathBuilderException: unable to find valid certifica
tion path to requested target

I tried running the code with SSL debug enabled but I'm unable to identify what's wrong. Had it been a certificate issue, it wouldn't have connected at all. But I'm able to connect sometimes after subsequent tries. Any help would be appreciated.


text:
Q: set Dot for CALayer Font I am using core text for CALayer.  It is easy to change the color in each layer, but I want this type of Layer:

How can I set dots under the text in CALayer?

A: EDIT :: I was partly wrong. The CATextLayer CAN draw rich texts in the form of CTAttributedString.. which is  NSAttributedString where all the attributes are identified by their CoreText kCTAttribute constants.

WRONG (I mean.. doable but not needed):: I'd use a custom calayer. catextlayer cant draw rich text anyways. in there override dawInContext and draw the attributedstring yourself

A: i am get solution,my designer create a new custom font to solve this problem,we replace dot into star,but the character and star is not a different color, the both are same color in custom font in my project


text:
Q: URL mapping for a SharePoint Sub-Site I have a web application running with a top root site. The URL mapping for this site is created and it is accessible as http://portal.bis.local/
Now I have created a sub-site under this site collection with the name "RMS". I want to configure a different URL mapping for this new sub-site as http://rms.bis.local
Is this feasible to configure? If yes then how? Because both sub-sites are now under same site collection?


text:
Q: OOPHP public function send array to var Ok simple question but thought I would ask because I am not sure, what I need to do is the following
1) I have a public function which we will call
    public function myarraysubmit($key,$values){

}

inside this I have a Switch() which looks at the key and then should get the $values and use the array in that is sent to $values
But what I am not sure, if you are able to send an array to a var function as when I last tied it did not work, could anyone point me in the right direction if this would or would not work.
Thanks

A: Did you try....
public function myarraysubmit($key,&$values){
...
}

or
public function myarraysubmit($key){
...
return $values;
}


text:
Q: How to view the namespaces range of a Docker container to choose correct Samba domain member idmap range? I created Samba domain member file share server in a Docker container, but actually I am not sure if the namespace range which I used for samba was optimal, because at some points I got always some errors about the range, I kept trying till it worked!
I am not sure but I think that the problem was because Samba in runnung inside Docker container, which means that I have just a specific Namespaces range to use.
Could some one please tell me how can I view the namespaces used for a Docker container? I tried this but it didn't work as I couldn't find uid_map file.
cat /proc/$(docker inspect -f '{{ .State.Pid }}' redis-userns)/uid_map


text:
Q: how to use individual component from an API by calling dynamically in React? I implement a project where i have to call API. From this API enter link description here  first i show 250 countries and then create a details component where show all details individually by clicking a button or link.  But i faced some problem. Since i have a little knowledge about react and API so i didn't understand how to call API for individually show country details in my details component. I need help because i want to know that how can I dynamically call single country from 250 countries API

----------This is the component here i load all countries by calling rest API. After that i couldn't call any single country

This is my country details component where i want to load individual country details

After getting some help i understand that api is coming in useState but i can not implement
import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
const CountryDetails = () => {
const {countryName} = useParams();
const [country,setCountry] = useState([]);  //use object
console.log(countryName);
console.log(country[0]);
useEffect(()=>{
    // const url = `https://restcountries.eu/rest/v2/all`;
    const url = `https://restcountries.eu/rest/v2/name/${countryName}`;
    fetch(url)
    .then(res => res.json())
    .then(data => setCountry(data));
},[countryName])
// console.log(country);
return (

This is  {countryName}

        {/*
{country[0]}
 */}

{countryName.capital}

); }; export default CountryDetails;

this is App.js in my project
import './App.css';
import {
BrowserRouter as Router,
Switch,
Route,
Link,
useParams,
useRouteMatch
} from "react-router-dom";
import Home from './Components/Home/Home';
import CountryDetails from './Components/CountryDetails/CountryDetails';
import NotFound from './Components/NotFound/NotFound';
function App() {
return (
<Router>
  <Switch>
    <Route path="/home">
      <Home/>

    </Route>
    <Route path="/:countryName">
      <CountryDetails></CountryDetails>
    </Route>
    <Route exact path="/">
      <Home />
    </Route>
    <Route path="*">
      <NotFound></NotFound>
    </Route>
  </Switch>
 </Router>
 );
 }  export default App;

I need to implement this component for showing individual country details

A: I think the issue is with how you attempt to render the details. The country data will still be in array format. countryName is the string route parameter, so it won't have any country specific properties to call.

This is  {countryName}

    {/*
{country[0]}
 */}

{countryName.capital}
 // <-- countryName is string!!

You can simply map the country results similarly to how it was done on the main page. Destructure the detail values you want to use for rendering the details.
return country.map(({ capital, name }) => ( // <-- destructure all values needed

      Country Name: {name}

      Capital: {capital}

    <button type="button" onClick={history.goBack}>Back</button>

))

Full Demo Code:
Home page
const Home = () => {
  const [countries, setCountries] = React.useState([]);

  React.useEffect(() => {
    fetch("https://restcountries.eu/rest/v2/all")
      .then((res) => res.json())
      .then((data) => setCountries(data));
  }, []);

  const history = useHistory();

  return countries.map(({ capital, name }) => (

Country Name: {name}

Capital: {capital}

      <button
        type="button"
        onClick={() =>
          history.push({
            pathname: `/${name}`
          })
        }
      >
        Details
      </button>

  ));
};

Details page
const CountryDetails = () => {
  const { countryName } = useParams();

  const [country, setCountry] = React.useState([]);

  React.useEffect(() => {
    fetch(`https://restcountries.eu/rest/v2/name/${countryName}`)
      .then((res) => res.json())
      .then((data) => setCountry(data));
  }, [countryName]);

  const history = useHistory();

  return country.map(
    ({ capital, flag, name, nativeName, population, region, subregion }) => (

Country Name: {name}

Capital: {capital}

Region: {region}

Subregion: {subregion}

Population: {population}

Native Name: {nativeName}

        <button type="button" onClick={history.goBack}>
          Back
        </button>

    )
  );
};

App
export default function App() {
  return (

Hello CodeSandbox

Start editing to see some magic happen!

      <Router>
        <Switch>
          <Route path="/:countryName">
            <CountryDetails />
          </Route>
          <Route path="/">
            <Home />
          </Route>
        </Switch>
      </Router>

  );
}

A: You are making a mistake when accessing the data in CountryDetails component.
Instead of this

{countryName.capital}

Do this

{country[0].capital}


text:
Q: packages aren't install in project's virtual enviroment i installed django-ckeditor with pip but it goes to the "/home/def-dev/.local/lib/python3.8/site-packages" path when i'm trying to create venv manually.
but when i create project with pycharm it goes to the "./venv/lib/python3.8/site-packages" path
that this path belong's to internal project's venv .
and this make's unknown for pycharm .
what should i do to make pycharm find packages from "/home/def-dev/.local/lib/python3.8/site-packages" or when i'm creating venv manually pip save's packages into "./venv/lib/python3.8/site-packages" path.
when i create venv manually
$ pip3 install django-ckeditor

Requirement already satisfied: django-ckeditor in /home/def-dev/.local/lib/python3.8/site-
packages (5.9.0)
Requirement already satisfied: django-js-asset>=1.2.2 in /home/def-
dev/.local/lib/python3.8/site-packages (from django-ckeditor) (1.2.2)

when i create venv with pycharm
$ pip3 install django-ckeditor

Requirement already satisfied: django-ckeditor in ./venv/lib/python3.8/site-packages (5.9.0)
Requirement already satisfied: django-js-asset>=1.2.2 in ./venv/lib/python3.8/site-packages
(from django-ckeditor) (1.2.2)


text:
Q: Angular: Passing data from child1 to parent to child2 Using angular6.
I have a parent component and 2 child component. I am trying to pass data from child1 component to child2 component as below:
Below is child1 component where I created @Output
--Child1--

import { Component, OnInit, Output, EventEmitter} from '@angular/core';

@Component({
  selector: 'ct-child1',
  templateUrl: './child1.component.html',
  styleUrls: ['./child1.component.css']
})
export class Child1Component implements OnInit {
   @Output() eventClicked: EventEmitter<any> = new EventEmitter();

   //Button click event on child - need to pass some values here, below is an example
   nextClicked() {
    this.eventClicked.emit('from clause');
  }
}

Below parent component listens to child1
--Parent--

<form class="form-horizontal" role="form">

       <ct-child1 (eventClicked)="childEventClicked($event)"></ct-child1>
       <ct-child2></ct-child2>

</form>

import { Component, OnInit} from '@angular/core';

@Component({
  selector: 'ct-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit  {

public clickedEvent: string;

  childEventClicked(event) {
    this.clickedEvent = event;
  }
}

Finally below is child2 component which is trying to listen the value
--Child2--

import { Component, OnInit, Input  } from '@angular/core';

@Component({
  selector: 'ct-child2',
  templateUrl: './child2.component.html',
  styleUrls: ['./child2.component.css']
})
export class Child2Component implements OnInit {
  constructor() { }
  @Input() event: string;

  //Button click event on Child2 - But here this.event returns undefined
    ValueFromChild1() {
    alert(this.event);
  }

  ngOnInit() {
  }
}

The issue I am facing above is in the ValueFromChild1() event above in Child2Component the value of this.event is coming to be undefined. Not sure whats missing here or I am not doing
something correctly. I can see the value being passed from Child1 to parent correctly but cant get that value in child2.
Could anyone point whats missing above?
Not sure if I should create a separate question but Apart from this could you also let me know how can I create a model, populate it and then pass it instead of just passing a string as above.
Thanks
--Updated code--
--Child1--

import { Component, OnInit, Output, EventEmitter} from '@angular/core';
import { MyModel } from './data.model';

@Component({
  selector: 'ct-child1',
  templateUrl: './child1.component.html',
  styleUrls: ['./child1.component.css']
})
export class Child1Component implements OnInit {
   myModelData = {} as MyModel;
   @Output() eventClicked: EventEmitter<MyModel> = new EventEmitter();
   selectedDdlValue: string = '';
    dropDownChange() {
        if (this.selectedDdlValue == '') {
           this.eventClicked = null;
        }
    }

   //Button click event on child - need to pass some values here, below is an example
   nextClicked() {
    this.myModelData.ddlValue = this.selectedDdlValue;
    this.eventClicked.emit(this.myModelData);
  }
}

--Parent--

<form class="form-horizontal" role="form">

       <ct-child1 (eventClicked)="childEventClicked($event)"></ct-child1>
       <ct-child2 [event]="clickedEvent" *ngIf="clickedEvent"></ct-child2>

</form>

import { Component, OnInit} from '@angular/core';

@Component({
  selector: 'ct-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit  {

 public clickedEvent: string;

  childEventClicked(event) {
    this.clickedEvent = event;
  }
}

--Child2--

import { Component, OnInit, Input  } from '@angular/core';
import { MyModel } from './data.model';

@Component({
  selector: 'ct-child2',
  templateUrl: './child2.component.html',
  styleUrls: ['./child2.component.css']
})
export class Child2Component implements OnInit {
  constructor() { }
     @Input() event: MyModel;

  ngOnInit() {
  }
}

A: You have a @Input() event: string; on your Child2Component but you're not inputting anything in the template <ct-child2></ct-child2>.
Your template needs to look like:
<ct-child2 [event]="clickedEvent"></ct-child2>

If you want to pass a model to the child component:
--YourModel.ts--

export class YourModel {
    foo: string;
}

--Child1--

import { Component, OnInit, Output, EventEmitter} from '@angular/core';

@Component({
  selector: 'ct-child1',
  templateUrl: './child1.component.html',
  styleUrls: ['./child1.component.css']
})
export class Child1Component implements OnInit {
   @Output() eventClicked: EventEmitter<YourModel> = new EventEmitter();

   //Button click event on child - need to pass some values here, below is an example
   nextClicked() {
    const model = new YourModel();
    model.foo = 'bar';
    this.eventClicked.emit(model);
  }
}

--Parent--

<form class="form-horizontal" role="form">

       <ct-child1 (eventClicked)="childEventClicked($event)"></ct-child1>
       <ct-child2></ct-child2>

</form>

import { Component, OnInit} from '@angular/core';

@Component({
  selector: 'ct-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit  {

public clickedEvent: YourModel;

  childEventClicked(event) {
    this.clickedEvent = event;
  }
}

--Child2--

import { Component, OnInit, Input  } from '@angular/core';

@Component({
  selector: 'ct-child2',
  templateUrl: './child2.component.html',
  styleUrls: ['./child2.component.css']
})
export class Child2Component implements OnInit {
  constructor() { }
  @Input() event: YourModel;

  //Button click event on Child2 - But here this.event returns undefined
    ValueFromChild1() {
    alert(this.event);
  }

  ngOnInit() {
  }
}

A: By the @Input() you are basically creating a new attribute for your component. But in your case it is empty. You need to bind to the @Input property like this.
<ct-child2 [event]="clickedEvent"></ct-child2>
Or
<ct-child2 event="{{clickedEvent}}"></ct-child2>
You can also use a condition here
<ct-child2 [event]="clickedEvent !== undefined ? clickedEvent : ''"></ct-child2>
This will check if the value is undefined then it will set the @Input() event in ct-child2 to an empty string
The [] are used to determine if you will use some property as a value of this attribute you can do this with almost every attribute for example

This will bind to normal id attribute specified by attr. part.
You can also check the @Input() here

A: You shouldn't really be passing the value back up from the child anyway, if the clicked button scenario you mentioned is what you want you should just emit something to tell the parent the button was clicked and then pass the data to child two from the parent. Nice article on input and output decorators I am currently creating a micro tutorial for this situation for devs in my office.


text:
Q: Add JButtons to JPanel I want to add a number of JButtons to a JPanel using a For loop. When the user presses a button, the following code is run:
for (i = 0; i < 10; i++)
{
  JButton aButton = new JButton();
  mainPanel.add(aButton);
  mainPanel.revalidate();
  mainPanel.repaint();
  System.out.println("Added: " + (i + 1) + "buttons");
}

However, when I press the button, no JButtons are added to the JPanel, but the program prints the appropriate number of buttons that should be added.
Not sure what the problem is here =/

A: I've solved my problem. I'm using NetBeans and apparently Free Layout doesn't work, so I set the JPanel's layout to Grid Layout and voila, the buttons appear

A: I would use the following.
for (i = 0; i < 10; i++) {
    mainPanel.add(new JButton("Button text"));
    System.out.println("Added: " + (i + 1) + "buttons");
}

mainPanel.invalidate();
mainPanel.repaint();


text:
Q: How to create a while loop that adds user inputted integers into a list, then displays that list of user inputs after every failed input? Basically, the user has to guess the correct "heat", by inputting a number between 1 and 10. The correct heat is 6, and I've already got the while loop working for it, but I also want to have it print the attempted "heats" by continuously appending a list with their inputted "heats" until they correctly guess 6.
Here's the code:
heat = int(input("You can move the heat from 1 to 10. What will you turn the heat up to? "))
heats = []

while heat != 6:
  if heat < 3:
    heat = int(input("Too cold...try again. "))
    heat = int(heat)
    print("Heats used: ", heats.append(heat))
  if heat == 3:
    heat = int(input("Lukewarm...? Try again. "))
    heat = int(heat)
    print("Heats used: ", heats.append(3))
  if heat <= 5:
    heat = int(input("Get it a bit warmer...try again. "))
    heat = int(heat)
    print("Heats used: ", heats.append(heat))
  if heat >= 7:
    heat = int(input("Get it a bit cooler...try again. "))
    heat = int(heat)
    print("Heats used: ", heats.append(heat))
  if heat >= 10:
    heat = int(input("Woah, woah, woah! Too hot, too hot! Turn it down, and try again!! "))
    heat = int(heat)
    print("Heats used: ", heats.append(heat))

The idea was that the list of heats tried would begin empty and then gradually fill, but it isn't working. All it outputs is "Heats used: None" :/
Any help is greatly appreciated.

A: heat.append(heat) or any value returns None
So, you must first append and then print the list
elif would be a better option as the conditions need not be be checked repeatedly
heat = int(input("You can move the heat from 1 to 10. What will you turn the heat up to? "))
heats = []

while heat != 6:
  if heat < 3:
    heat = int(input("Too cold...try again. "))
    heat = int(heat)
    heats.append(heat)
    print("Heats used: ", heats)
  elif heat == 3:
    heat = int(input("Lukewarm...? Try again. "))
    heat = int(heat)
    heats.append(3)
    print("Heats used: ", heats)
  elif heat <= 5:
    heat = int(input("Get it a bit warmer...try again. "))
    heat = int(heat)
    heats.append(heat)
    print("Heats used: ", heats)
  elif heat >= 7:
    heat = int(input("Get it a bit cooler...try again. "))
    heat = int(heat)
    heats.append(heat)
    print("Heats used: ", heats)
  elif heat >= 10:
    heat = int(input("Woah, woah, woah! Too hot, too hot! Turn it down, and try again!! "))
    heat = int(heat)
    heats.append(heat)
    print("Heats used: ",heats)