text:
Q: Wrap new row based on condition from column I have a dataset that has following format:
id1 a1 b2 x1;x2;x3
id2 a2 b3 x4;x5
id3 a4 b5 x6
id4 a7 b7 x7;x8

First 3 columns (id, a, b) only have 1 instance, but the last column has multiple instances, separated by ;. How can I "wrap" these into new columns? Such as:
id1 a1 b2 x1
id1 a1 b2 x2
id1 a1 b2 x3
id2 a2 b3 x4
id2 a2 b3 x5
id3 a4 b5 x6
id4 a7 b7 x7
id4 a7 b7 x8

A: We can use cSplit
library(splitstackshape)
cSplit(df1, "v4", ";", "long")
#    v1 v2 v3 v4
#1: id1 a1 b2 x1
#2: id1 a1 b2 x2
#3: id1 a1 b2 x3
#4: id2 a2 b3 x4
#5: id2 a2 b3 x5
#6: id3 a4 b5 x6
#7: id4 a7 b7 x7
#8: id4 a7 b7 x8

data
df1 <- structure(list(v1 = c("id1", "id2", "id3", "id4"), v2 = c("a1",
"a2", "a4", "a7"), v3 = c("b2", "b3", "b5", "b7"), v4 = c("x1;x2;x3",
"x4;x5", "x6", "x7;x8")), .Names = c("v1", "v2", "v3", "v4"),
 class = "data.frame", row.names = c(NA, -4L))


text:
Q: minDate function dont work correctly in date picker with time picker I using date & time picker but don't work bellow function correctly.
I guess the time picker minDate function jQuery UI have conflict with time picker
I'm change the location script and delete minDate functions in time picker but doesn't work correctly
 jQuery('.datepicker1').datetimepicker({
  onSelect: function(dateText, inst) {
      jQuery('.datepicker2').datetimepicker({
          minDate: new JalaliDate(inst['selectedYear'], inst['selectedMonth'], inst['selectedDay']),
      });
  },
});

can u help me please?

A: I use this
    jQuery("#datepicker").datepicker({minDate:"+0d",onSelect:function(tarih){
        jQuery("#datepicker2").datepicker("destroy");
        var myDate = new Date(tarih)
        myDate.setDate(myDate.getDate() + 1)
        tarih = myDate.getFullYear().toString() + "/"
        tarih += (myDate.getMonth() + 1).toString() + "/"
        tarih += myDate.getDate().toString()
        jQuery("#datepicker2").datepicker({minDate:tarih}).delay(100).val(tarih);
   }});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Remove Selected POIs from Google map I have generated an elaborate Google Map for an large local festival, I am involved with, which highlights venues throughout my local town where events will be taking place.  It has a hundred additional markers added.  Having most Points of Interest is good and highly relevant, but I would like to have a few removed from this particular map:
2 Are for car parks which will not be used as car parks for the weekend (There will be 2 or 3 additional large ones further out).
3 Are for very un-cooperative businesses who want the benefit of 50,000 extra people but don't want to contribute any money and are running their own things which are nothing to do the festival.
Here is a small segment of the map, how could I go about removing the "High Street Carpark" from this?  (This is perhaps the least important one to change but is the easiest to see).

It is marked aas similar to another question, but that has not been answered either.

A: You can use Google Map styling system and do something like:
  var styles = {
    default: null,
    hide: [
      {
        featureType: 'poi.business',
        stylers: [{visibility: 'off'}]
      },
      {
        featureType: 'transit',
        elementType: 'labels.icon',
        stylers: [{visibility: 'off'}]
      }
    ]
  };

You must find here what to hide here: https://developers.google.com/maps/documentation/javascript/3.exp/reference#MapTypeStyleFeatureType
The much easier way I could find is to use Google Map Styling Wizard:
https://mapstyle.withgoogle.com/


text:
Q: how to display a list into multiple columns in gsp In my groovy/grails app i can get my list with check boxes (and thanks for the tips).
But what I cannot seem to get is how to display the list in multiple columns.
Here is the code in my gsp:

        <g:each in="${name}" var="fileName">
               <g:checkBox checked="false" name="${ 'fileName'}"/> ${fileName

        </g:each>

i thought that the class="ul class="columns" column-count="3" would work as straight html but I was wrong. I still get a single (long) list.
What is the proper way to make this list into multiple columns in a gsp using groovy tags or the correct html code?
Thanks!
ironmantis7x
***** Successful UPDATE!!! *****
based on the answer I accepted, here is the code I wrote:

            <g:each in="${name}" var="fileName">
                 <g:checkBox checked="false" name="${ 'fileName'}"/> ${fileName}

            </g:each>

Thanks gang! You always help me expand my knowledge base and be more successful in what i love to do and that's programming software!
ironmantis7x

A: To my knowledge, column-count is a CSS property, not an attribute that can be applied to the ul tag.  You need to have column-count defined via style= or within a separate css file (the preferred way because of SoC).
.columns {
    -webkit-column-count: 3;
    -moz-column-count: 3;
    column-count: 3;
}

Also, you have a list of checkbox inputs within your ul tag.  You should have a list of li (list item) tags instead:

    <g:each in="${name}" var="fileName">

<g:checkBox checked="false" name="${ 'fileName' }"/> ${fileName}

    </g:each>

A: HTML code in gsp produces exactly same html as you wrote, will be sent to browser as is. So
 will be same
 in your browser.
But you're missing list elements, and putting just a single multiline (split by ) text block. You're probably want this:

    <g:each in="${name}" var="fileName">

<g:checkBox checked="false" name="${ 'fileName' }"/> ${fileName

    </g:each>

or most likely this (because you didn't close } in your code, and ${ 'fileName'} doesn't make any sense. also you should't put values as is, it's potential security vulnerability):

    <g:each in="${name}" var="fileName">

<g:checkBox checked="false" name="${fileName.encodeAsHTML()}"/> ${fileName.encodeAsHTML()}

    </g:each>


text:
Q: TP-Link DoS protection blocks Bonjour We have an Apple-centric office and as such we rely on Bonjour (mDNS) for auto-discovery of things like printers, AirPlay targets, and pseudo-servers (e.g. exchanging files between desktop computers).
I just installed a TP-Link T1600G L2+ switch as our core switch as a step to help manage the network as we embrace IPv6 and the proliferation of Internet-connected devices. (Eventually I want to be able to have guests sign into our WiFi, access the internet, and also access the Apple TV/AirPlay in our conference rooms, but not access any of our other internal resources, for example, but I understand that will take a full Level 3 router (on order), and that will be a different post if I run into trouble.)
For now, I just installed the T1600G, plugged the WAN router/NAT/DHCP server, all our dumb L2 switches and wireless APs, our main servers, and our IoT devices into it (intending to isolate the APs and IoT stuff via VLANs later). But I haven't even gotten as far as setting up a VLAN and already I've broken something.
In particular, I've found that enabling the T1600G "DoS Defend" protection, firmware version "1.0.3 Build 20160412 Rel.43154(s)", blocks Bonjour somehow, but I can't figure out how or why or what to do about it (other than leave the DoS protections turned off). I'm not even sure how to diagnose the problem because I don't know how to force a Bonjour advertisement to be issued.
Is there something about IPv6 multicast that looks like IPv4 DoS attack?
Update
I called TP-Link business technical support. They didn't know what Bonjour was and hung up on me.

A: The problem was the "Blat Attack" filter. A Blat Attack is a specialization of a "Land Attack", but somehow the filter evolved only to check for the specialization, not the full blown attack. In detail...
A "Land Attack" is when an attacker sends a spoofed TCP SYN packet containing the IP address of the victim as both the destination and the source IP address. The vulnerable system ends up replying to itself in a feedback loop. A "Blat Attack" is an "improvement" on the Land Attack, adding that the source and destination ports are identical, and sometimes abusing the URG flag as well.
Well, somewhere along the line someone thought that it was always malicious to send an IP packet with the same source and destination port, so the Blat Attack defense just blocks any IP packet with the same source and destination port, even though there is absolutely nothing wrong with that if the source and destination addresses are different.
Bonjour (mDNS) sends announcements both to and from the same port (5353), and the Blat Attack defense stops those packets from being forwarded. Since the Blat Attack filter is truly useless in its current implementation (Blat Attacks would be stopped by the Land Attack filter anyway), there is no reason not to turn it off, so I did, and that solved the problem.


text:
Q: Message - Update Functions Version on Azure I have upgraded some of my Azure Functions to .netstandard 2.0, that is still in beta. Whenever I publish my Functions directly from Visual Studio, I get the following message:

The csproj file containing my Functions is already is targeting .netstandard 2.0.

Here is the setting in the Function App:

How can I "upgrade" the version of my local Functions?

A: I have done some tests on my side and reproduce the message you got. Just like @Connor has said, for function in beta version, the csproj file should include AzureFunctionsVersion as the illustration shows.

Once the AzureFunctionsVersion parameter is lost, the function will be recognized as using runtime ~1  despite the TargetFramework. So when the project is published to a beta function app in portal, it will remind us of the version change.

A: I ran into the same problem today during the creation of an Azure Function project in Visual Studio 2019. It needed a lot of sorting out but below turned out to be the solution for me:
In Azure:

*

*Azure > Function App > Create

*Then go to the settings and choose the runtime version, which is ~2 by default (meaning a 2.x version with auto updates enabled).

In Visual Studio:

*

*VS Create project type C# > Cloud > 'Azure Functions'. In the second screen don't forget to choose for "Azure Functions v2 (.NET Core)".

*Via the nuget package manager update the Microsoft.NET.Sdk.Functions package.

*Also install: Microsoft.Azure.WebJobs   (v3.0.9)

*Also install: Microsoft.Azure.WebJobs.Extensions.Http   (3.0.2)

Clean + Rebuild the project. Now you should be able to Publish directly from Visual Studio to the Cloud. Right-click on the project and choose 'Publish'. Then you should see an option to Publish to an Function in Azure cloud.
If not then the most likely reason is because you have a problem with your references / nuget packages / Microsoft SDK. Or the versions of those.


text:
Q: Idris returning dependent type signature error with if statement in type definition I'm working on a red black tree implementation in Idris. In this implementation, the node, in addition to carrying information about its value and colour, also carries information about its black height (which is the number of black nodes from that node to any leaf, not including itself).
I'm trying to get specific with the node definition is relation to the black height of its children. NodeEq - both children have same bh, NodeLh means left child has bh greater than right child by 1 and NodeRh is the reverse of NodeLh.
data Colour = Red | Black

data RBTree : Nat -> Colour -> Type -> Type where
      Empty : Ord elem => RBTree Z Black elem
      NodeEq : Ord elem => (left: RBTree p X elem) -> (val: elem) -> (col: Colour) ->
                          (h: Nat) -> (right: RBTree p Y elem) -> RBTree {h: Nat | if X == Black && Y == Black then (S p) else p} col elem
      NodeLh : Ord elem => (left: RBTree (S p) _ elem) -> (val: elem) -> (col: Colour) ->
                            (h: Nat) -> (right: RBTree p _ elem) -> RBTree (S (S p)) col elem
      NodeRh : Ord elem => (left: RBTree p _ elem) -> (val: elem) -> (col: Colour) ->
                            (h: Nat) -> (right: RBTree (S p) _ elem) -> RBTree (S (S p)) col elem

I'm having problem setting the black height for the NodeEq. What I'm trying to achieve, which might be obvious in the code below, is that if both children are black nodes, then the black height should be their bh + 1, else the black height should equal their height. However, I don't know how to write that into the definition. As you can see, I'm using to general {x:b|p} format.
This is the error I'm getting
  |
9 |                           (h: Nat) -> (right: RBTree p Y elem) -> RBTree {h: Nat | if X == Black && Y == Black then (S p) else p} col elem
  |                                                                            ^
unexpected ':'
expecting dependent type signature

I've also considered creating a 'where' or 'let' block but I'm not sure how to go about it.

A: The syntax in
RBTree {h: Nat | if X == Black && Y == Black then (S p) else p} col elem

is incorrect. The first index of RBTree has type Nat so you simply want to put a Nat-typed term there:
RBTree (if X == Black && Y == Black then (S p) else p) col elem

You are probably mixing up refinement type syntax (from something like Liquid Haskell) with Idris.


text:
Q: randomly generate variable names? I've got a problem.. I've got something like...
    if(condition(TEST) == true){

     something (NAME) = new something(this);

     }

This is inside a loop where there are many TEST variables being iterated through. I don't know how many and its possible each of them would need a "(NAME)" variable so basically I want to know how would I make java "on the fly" generate a name for these variables?
Thanks!

A: Are you sure you don't want to store the results in either an array or a collection?
The closest thing would be to use a Map. Randomly generate a String or an Integer key, and use it as a key to your Something value.
// Before all
Map<String, Something> myMap = new HashMap<String, Something>();

// For each of these
if(condition(TEST) == true){
   String name = "VAR" + Math.random() // Don't remember the syntax here
   myMap.put(name, new something(this));
}

A: Unless I'm misunderstanding your problem, you won't need to do this.
Variables in Java are lexically scoped, in that they are defined solely for the block in which they exist.  On every iteration through the loop, your name parameter will refer to a different object, and will not be affected by the values it held on previous loops.
So you will only need as many parameters in your loop as there are attributes you want to operate on within the loop (possibly only one), which in all cases is something you'll know for sure when you write your code (at compile time) and is divorced from the (runtime) number of TEST objects.

A: If you're not storing them or referencing them later, and they're all the same type, you could use the same variable for all of them:
 // Outside loop ...
 something $name;

 // Inside loop ...
 if(condition(TEST) == true){

   $name = new something(this);

 }

A: The simplest way to generate in id (e.g. for a Map) is to use an AtomicInteger.
AtomicInteger counter = new AtomicInteger();

Map<String, Something> map = ...
String id = Integer.toString(counter.getAndIncrement(), 36);
map.put(id, new Something());
// later
Something s = map.get("0");

or it would be simpler to use a List which is naturally indexed.
List<Something> list = ...
list.add(new Something());
// later
Something s = map.get(0);


text:
Q: Reverse Geocode on Client Side (Google Maps V3 API) How do you do a Reverse Geocode on the clientside using Google Maps V3 API? The forward geocode from address to LatLng is straight forward (code below), but how do you do the same for reverse geocode?
Normal Geocode Code:
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
  if (status == google.maps.GeocoderStatus.OK) {
    map.setCenter(results[0].geometry.location);
    var marker = new google.maps.Marker({
    map: map,
    position: results[0].geometry.location
  });

A: The process is exactly the same, with the minor difference that instead of supplying an address object to the geocode function you supply a LatLng object
Reverse Geocode Code:
var input = document.getElementById("latlng").value;
var latlngStr = input.split(",",2);
var lat = parseFloat(latlngStr[0]);
var lng = parseFloat(latlngStr[1]);
var latlng = new google.maps.LatLng(lat, lng);

geocoder.geocode({'latLng': latlng}, function(results, status) {
  if (status == google.maps.GeocoderStatus.OK) {
    if (results[1]) {
      map.setZoom(11);
      marker = new google.maps.Marker({
          position: latlng,
          map: map
      });
      infowindow.setContent(results[1].formatted_address);
      infowindow.open(map, marker);
    } else {
      alert("No results found");
    }
  } else {
    alert("Geocoder failed due to: " + status);
  }
});

Example directly from Google
Hope that helps.


text:
Q: How to get image from firebase storage with the image url that is in firestore I am trying to get my image from the firebase storage with the help of glide.I am also getting the user's name from the firebase and it is showing up.When I directly use the url in glide the image does shoe.But I cannot do that as I first want to assign the url to a String and use the String inside glide.But when I do that no image shows up.
My java code
public class profile extends AppCompatActivity {

    CircleImageView circleImageView;
    TextView fullname;
    FirebaseAuth fAuth;
    FirebaseFirestore fStore;
    String userId;
    BottomNavigationView bottomNavigationView;
   String uri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);

        fAuth = FirebaseAuth.getInstance();
        fStore = FirebaseFirestore.getInstance();
        circleImageView = findViewById(R.id.profilepicture2);
        fullname = findViewById(R.id.nameinprofile);
        userId = fAuth.getCurrentUser().getUid();
        bottomNavigationView = findViewById(R.id.bottom_navigation2);
        bottomNavigationView.setSelectedItemId(R.id.profilelogo);

        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
               switch (item.getItemId()){
                case R.id.profilelogo:
                    return true;
                case R.id.home:
                    startActivity(new Intent(getApplicationContext(),homepage.class));
                    return true;
                   case R.id.addlogo:
                       startActivity(new Intent(getApplicationContext(), search.class));
                       return true;

            }
            return false;
        }
        });

        final DocumentReference documentReference = fStore.collection("Userdata").document(userId);
        documentReference.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
            @Override
            public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
                fullname.setText(documentSnapshot.getString("Full name"));
                 uri = documentSnapshot.getString("imageUrl");
            }
        });
        Glide.with(this).load(uri).into(circleImageView);
    }
    }

My xml file
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".profile">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:layout_marginBottom="383dp"
        android:orientation="vertical"
        android:background="@drawable/borderbottomgrey"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <de.hdodenhof.circleimageview.CircleImageView
            android:id="@+id/profilepicture2"
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:layout_gravity="center"
            android:layout_marginTop="30dp"
            android:src="@drawable/profile" />

        <TextView
            android:id="@+id/nameinprofile"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="10dp"
            android:text=""
            android:textColor="#000000" />
    </LinearLayout>

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottom_navigation2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="@drawable/bordertopgrey"
        app:itemIconTint="#000000"
        app:itemTextColor="#000000"
        app:layout_constraintBottom_toBottomOf="parent"
        app:menu="@menu/menu_navigation"
        tools:ignore="MissingConstraints" />

</androidx.constraintlayout.widget.ConstraintLayout>

My firestore collection

A: Note that .addSnapshotListener in asynchronous (runs on a different thread).
The code that loads the image most probably gets executed before you get the URL from Firebase.
Try placing the Glide call inside onEvent callback
final DocumentReference documentReference = fStore.collection("Userdata").document(userId);
        documentReference.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
            @Override
            public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
                fullname.setText(documentSnapshot.getString("Full name"));
                 uri = documentSnapshot.getString("imageUrl");

                 Glide.with(YourActivity.this).load(uri).into(circleImageView);

            }
        });


text:
Q: On checkbox checked, wrap a parent DIV with a border using css and/or jQuery I hope someone could help me with the following.
If a user checks checkbox1 then a border (border: 1px solid green;) is added to the DIV SmallSquarePhoto using pure CSS or a combination of CSS and jQuery. Otherwise checkbox1 has a transparent color (border: 4px solid transparent;).
Any help would be appreciated...Thanks
<div id="SmallSquarePhoto" class="SmallSquarePhoto" style="background-image: url(/Members/images/background/<%# Eval("BG_fileName") %>)">

<input id="checkbox1" name="BG_list" type="checkbox" runat="server" value='<%# Eval("BG_fileName") %>' />

A: JS
$('#checkbox1').on('click', function () {
    $('#SmallSquarePhoto').toggleClass('green-border', $(this).is(':checked'));
});

CSS
.green-border{
   border: 1px solid green;
}
#SmallSquarePhoto #checkbox1 {
    border: 4px solid transparent;
}
#SmallSquarePhoto.green-border {
    border: 1px solid green;
}
#SmallSquarePhoto.green-border #checkbox1 {
    border: 0;
}

Fiddle: http://jsfiddle.net/y9chau9o/

A: On clicking check box adding border, Demo
$('#checkbox1').click(function(){
    $('#SmallSquarePhoto').toggleClass('green-border');
});


text:
Q: WordPress Facebook comments error "Can't download" I want Facebook comments on my images on WordPress. I'm using the Social Gallery Lite plugin for WordPress.  It shows a comment lightbox for each image.
I have two problems:

*

*The comments are not appearing in my moderation tool / I'm not getting notifications of new comments

*Every time I add a new comment, I get an errormessage saying "Can't download", nothing more.  When I refresh, the comment is added.  When I add another comment on the same image, I don't get any errors.  When I add another comment on another image, I get the error again.
This is what I did:

*

*installed and acitvated the plugin

*created a new app on facebook

*copy pasted the APP ID in my plugin

*made sure that I am the admin of the app

*published the app (not even sure if this was necessary)
Am I missing a step?

A: Not really a coding related question here. So possibly on the wrong forum, best asked on the Wordpress community.
However, will attempt an answer here, it would seem that on the plugin itself does not need a facebook app to be created screenshot for app ID, it has a native app to do that. What you need to do is to provide your admin ID to the plugin to access your comments screenshot for admin access.


text:
Q: How to add values from outside of the producer class to producer thread(blocking queue implementation) I want to add some strings from outside class to sharedQueue; what is the best practice to accomplish that?

*

*Adding from outside class itself directly to sharedQueue and pass through constructor

*Send that value to constructor and adding from there

*Any other method?

If answer is 1 or 2 then why do all the examples show integer values putting in run method of producer and taking out in consumer method?
class Producer implements Runnable {

    private final BlockingQueue<String> sharedQueue;

    public Producer(BlockingQueue<String> sharedQueue) {
        this.sharedQueue = sharedQueue;
    }

    @Override
    public void run() {
        try {
            sharedQueue.put("value passed from outside class");
        } catch (InterruptedException ex) {
            Logger.getLogger(Producer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}


text:
Q: React-Native async Array.map = undefined is not an Object I try to create my first hybrid App with ReactNative. I have an issue with my Array.map…
class HomeScreen extends React.Component {

  state = {
    isLoading: false,
    captured: false,
    wished: false,
    exchanged: false,
    data: {}
  };

  async getPokemonFromApiAsync() {
    try {
      this.setState({isLoading: true});
      let response = await fetch('https://pokeapi.co/api/v2/pokemon/?limit=0&offset=20');
return this.setState({
        isLoading: false,
        data: await response.json()
       });
    } catch (error) {
      console.error(error);
  }

  (...)

  componentWillMount() {
      this.getPokemonFromApiAsync()
  }

  (...)

  result = (result = this.state.data.results) => {
      console.log('test', this.state.data);
      return (
         <View>

             (...)

             result.map( (item, index) => {

             (...)

             }
         </View>
      )
  }
}

I don't understand, why my function getPokemonFromApiAsync is empty. iOS Simulator returns a TypeError: Undefined is not an object (evaluating 'result.map')
And when adding a constructor like:
constructor(props) {
   super(props)
   this.getPokemonFromApiAsync = This.getPokemonFromApiAsync.bind(this)
}

I have an many errors in console:
Warning: Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to this.state directly or define a state = {}; class property with the desired state in the %s component., setState, HomeScreen
For me, it's normal…
What is a good lifecycle for an asynchronous Http request?

A: Best way using axios library github link
npm install axios

Finally, weekly downloads are more than 4,000,000+ Github Starts 50,000+

A: A better way is to implement your state values when your promise is resolved using "then".
let response = fetch('https://pokeapi.co/api/v2/pokemon/?limit=0&offset=20')
  .then((response) => {
     this.setState({
       isLoading: false,
       data: response.json()
     });
  });

Maybe you can process your data (result.map) in the Promise callback and directly insert the result in your component.
And by the way, XHR calls are generally processed in the componentDidMount method.

A: Your error is caused by how you have set up your initial data in state.
You have set it up as:
state = {
  isLoading: false,
  captured: false,
  wished: false,
  exchanged: false,
  data: {} // <- here you define it as an object, with no parameters
};

You should be setting it as an object with a results parameter`. So your initial state should look like
state = {
  isLoading: false,
  captured: false,
  wished: false,
  exchanged: false,
  data: { results: [] } // <- here you should define the results inside the object
};

The reason you are getting the error:
TypeError: Undefined is not an object (evaluating 'result.map')

Is because on the initial render, before your fetch response has come back, it is trying to map over this.state.data.results which doesn't exist. You need to make sure that there is an initial value for results in the state.
That should stop the initial error, however you will have to make sure that what you are saving into state for data is also an array, otherwise you will continue to get the same error.

componentWillMount has been deprecated and you should be using componentDidMount.
Also as you are calling an async function inside you componentWillMount you should refactor it in the following way:
async componentDidMount() {
  await this.getPokemonFromApiAsync()
}

So that the mounting doesn't occur until the fetch request has been completed.

I would also refactor your getPokemonFromApiAsync so that you get the response.json() before trying to set it into state. You also don't need the return statement as this.setState doesn't return anything.
async getPokemonFromApiAsync() {
  try {
    this.setState({isLoading: true});
    let response = await fetch('https://pokeapi.co/api/v2/pokemon/?limit=0&offset=20');
    let data = await response.json(); // get the data
    this.setState({
      isLoading: false,
      data: data // now set it to state
    });
  } catch (error) {
    console.error(error);
}

Snack:
Here is a very simple snack showing the code working https://snack.expo.io/@andypandy/pokemon-fetch
Code for snack:
export default class App extends React.Component {

  state = {
    isLoading: false,
    captured: false,
    wished: false,
    exchanged: false,
    data: { results: [] } // <- here you should define the results inside the object
  };

  getPokemonFromApiAsync = async () => {
    try {
      this.setState({ isLoading: true });
      let response = await fetch('https://pokeapi.co/api/v2/pokemon/?limit=0&offset=20');
      let data = await response.json(); // get the data
      this.setState({
        isLoading: false,
        data: data // now set it to state
      });
    } catch (error) {
      console.error(error);
    }
  }

  async componentDidMount () {
    await this.getPokemonFromApiAsync();
  }

  render () {
    return (
      <View style={styles.container}>
        {this.state.data.results.map(item => <Text>{item.name}</Text>)}
      </View>
    );
  }
}

A: The reason you are getting the error TypeError: Undefined is not an object (evaluating 'result.map') is that you are getting the result from this.state.data.results, but because data is async, at the first time it renders, data is {} (because you set it in the state), so data.result is undefined and you can't use .map() in a undefined.
To solve this, you can check if data.result is not undefined, before render it.
  return (
     <View>

         (...)

         result && result.map( (item, index) => {

         (...)

         }
     </View>
  )


text:
Q: Changing owner of profile folder I have this script
$dir = '\\knesmbmdc001\profiles'
$logFile = 'C:\user_done.txt'
Get-ChildItem -Directory $dir | % {
$user = $_.Name
$acl = Get-Acl –LiteralPath $_.FullName
$userIdentity = New-Object System.Security.Principal.NTAccount $user
$acl.SetOwner($userIdentity)
Set-Acl –LiteralPath $_.FullName -AclObject $acl
Add-Content $logFile $user
}

I get this error
Exception calling "SetOwner" with "1" argument(s): "Some or all identity references could not be translated."
Set-Acl : The security identifier is not allowed to be the owner of this object.

I'm trying to take the name of the folder(Users name) and set it as the owner.

A: The name of the folder is not a valid username. You should output $user in your script to see which one fails. I'll assume this is roaming profiles for a Windows domain. I see two potential problems:

*

*Does the user exist? Roaming profiles aren't deleted when a user is deleted from the domain, so it might be a deleted user

*Profiles in Vista and newer might have a version number at the end to avoid mixing profiles between different OSes, ex. username.v2. So you need to just extract the name from this.

If (cause -eq 2), try:
$user = $_.Name.Split(".")[0]


text:
Q: Filter SharePoint Page based on a User's Logged with javascript In my company's Sharepoint website, each user account includes Display Name (LastName, FirstName and Initial).
I need a selective View based on the User's name. I'm not using People Picker, so I can't use [Me] for filter by "Created by" or "Modified by". I will have a page where a user may have an approval section, so what I'm looking for is when ever the user appears on the form, display the item as part of the filter view. I'm currently using Sharepoint 2013 soon going to O365 SharePoint. Thank you for your inputs.
How can I do this using Javascript


text:
Q: Is there a nicer way to prepend if not nil in Ruby? I have a bunch of environment variables with my config in them:
DB_HOSTNAME=something.rds.amazonaws.com
DB_PORTNUM=9999
DB_USERNAME=production
DB_PASSWORD=xyzzy

To make a DB connect string from them it's something like:
"postgres://" +
"#{ENV['DB_USERNAME']}#{ENV['DB_PASSWORD'] ? ":#{ENV['DB_PASSWORD']}" : nil}" +
"@#{ENV['DB_HOSTNAME']}#{ENV['DB_PORTNUM'] ? ":#{ENV['DB_PORTNUM']}" : nil}" +
"/proper_scraper_#{$environment}"

That way it works in development/test where DB_PASSWORD and DB_PORTNUM aren't set, and works in production where they are. But this bit is ugly:
ENV['DB_PASSWORD'] ? ":#{ENV['DB_PASSWORD']}" : nil

The desired semantics are: prepend if not nil and return nil otherwise. Ideally it would be something like this:
ENV['DB_PASSWORD'].try(:prepend, ':')

Using Object.try something like this:
  def try method, *args
    send(method, *args) if respond_to? method
  end

But that doesn't work because prepend mutates the string (why?) and env strings are frozen. The alternative:
ENV['DB_PASSWORD'].dup.try(:prepend, ':')

But this doesn't work when the environment variable is not set because you can't dup nil.
Is there a nice one-liner here or am I stuck with the messiness?

A: It's unfortunate that both String#insert and String#prepend modify the strings, but String#sub should work:
ENV['DB_PASSWORD'].try(:sub,'',':')

Or with a bit more intention:
ENV['DB_PASSWORD'].try(:sub,/^/,':')

A: Use objects and the standard library:
require 'uri'

u = URI::Generic.build(
    scheme: "postgres",
    host: ENV["DB_HOSTNAME"],
    port: ENV["DB_PORTNUM"],
    path: "/proper_scraper_#{$environment}",
)

u.user = ENV["DB_USERNAME"]
u.password = ENV["DB_PASSWORD"]

puts u.to_s

A: If Object#try happens to support blocks (like ActiveSupport's),
ENV['DB_PASSWORD'].try { |s| ":#{s}" }

A: From ruby 2.3 you can use the safe navigation operator in combination with String#sub (As @Matt pointed out)
ENV["DB_PASSWORD]&.sub(/^/, ":")

A: Ugh. Your readability has really suffered because you're trying to do it all in a single line. Don't do that.
I'd do something like:
Set up the ENV for the example...
ENV['DB_HOSTNAME'] = 'something.rds.amazonaws.com'
ENV['DB_PORTNUM'] = '9999'
ENV['DB_USERNAME'] = 'production'
ENV['DB_PASSWORD'] = 'xyzzy'

The real code starts here:
$environment = 'production'
db_hostname, db_portnum, db_username, db_password = %w[
  DB_HOSTNAME
  DB_PORTNUM
  DB_USERNAME
  DB_PASSWORD
].map{ |e| ENV[e] }

db_password = ':' + db_password if db_password
db_portnum = ':' + db_portnum if db_portnum

DSN = "postgres://%s%s@%s%s%s" % [
  db_username,
  db_password,
  db_hostname,
  db_portnum,
  "/proper_scraper_#{$environment}"
]
DSN # => "postgres://production:xyzzy@something.rds.amazonaws.com:9999/proper_scraper_production"

Ternary statements are replacements for if/then/else statements, not for simple if/then. Trying to make them fit only results in confusing code, so don't go there.
People get enamored with cramming code all in one line, and, a long time ago, back when we used interpreted BASIC, it helped speed up the code, but today's languages rarely benefit from that. Instead, what happens is it makes code indecipherable. Writing code that is indecipherable is a fast path to being called up to explain yourself in a code-review, followed by being told to rewrite it and never do it again.


text: Q: How to run the same application or several windows in a separate process? Webviews can run in a different process as described here. How to run the same application in a separate process? Can I run different windows of the application in a different process?


text:
Q: Getting Json object as View Model from ajax call & insert that using Entity Framework Core I get view model data from Ajax with this code:
  $.ajax({
            url: '@Url.Action("Create", "Invoice")',
            type: "POST",
            contentType: 'application/json',
            data: JSON.stringify(invoiceViewModel),
            success: function (response) {
                alert(response + " records inserted.")
            },
            error: function (response) {
                alert(response + " records not inserted.")
            }
        });

Then I want to insert that into a Create action in my controller.
How can I insert using Entity Framework Core?

A:
I want to insert that into a Create action in my controller. How can I insert using Entity Framework Core?

Firstly, you may need to create data model and database context class, and register your database context as a service during application startup.
services.AddDbContext<MyDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

For more information about using EF Core in an ASP.NET MVC, please refer to this doc about "get started with EF Core in an ASP.NET MVC".
Note: if you have created corresponding model class(es) and registered required service(s), please skip this step.
After you setup EF Core in your MVC project, the DbContext can then be used in controllers (or other services) through constructor injection.
public class InvoiceController : Controller
{
    private readonly MyDbContext _context;

    public InvoiceController(MyDbContext context)
    {
        _context = context;
    }

And to add new record to database with following code snippet.
if (ModelState.IsValid)
{
    _context.Add(invoice);
    await _context.SaveChangesAsync();
}

Besides, to protect your controller from over-posting, please only include properties in the [Bind] attribute that you want to change.


text:
Q: How to determine if carry out occuurs in C I'm writing an ARM11 emulator and now I'm trying to set CPRS flags which are N(negative result), Z(zero), C(carry out) and V(overflow)
this is what the spec says:

The C bit in logical operations (and, eor, orr, teq, tst and mov) will be set to the carry out from
  any shift operation (i.e.the result from the barrel shifter). In arithmetic operations (add, sub, rsb
  and cmp) the C bit will be set to the carry out of the bit 31 of the ALU.

My question is, how do I determine the carry out from logical and arithmetic operations?
Operations work on two uint32_t, e.g. my eor operation simply returns x ^ y, and after that I need to set CPRS flags.
EDIT:
For addition, C is set
to 1 if the addition produced a carry (unsigned over
ow), it is set to 0 otherwise. For subtraction
(including comparison), the bit C is set to 0 if the subtraction produced a borrow, otherwise is set
to 1.

A: Logical operations are a bit of a red herring here - obviously eor r0, r1, r2 isn't going to produce overflow or carry. However, it's not the logical operations themselves that we care about:

The C bit in logical operations (and, eor, orr, teq, tst and mov) will be set to the carry out from any shift operation (i.e.the result from the barrel shifter).

Remember that optional shift on any data processing instruction? Given eor r0, r1, r2 lsl #3, the carry you care about is whatever r2 lsl #3 generates. However you're implementing flag-setting for shifts*, do that.
* if you're stuck on that too, I saw plenty of good ideas in a quick flick through the related questions over there -->

A: I posit that the code snippet below is probably as close as you're going to get with standard C and using logic operations to determine carry out and signed arithmetic overflow.  This approach is an adaptation of how look ahead carry circuits are generated for arbitrary word lengths in FPGA's.
The basic sequence is to first determine which bit pairs will generate a carry and which will propagate a carry.  In this presentation, the initial carry-in is presumed to be zero.  A mask is marched along the "generate" and "propagate" words and with some logic and previous carry, determine carry to the next iteration.  At the end of iteration, the carry flag will be set (or not) depending on the word pair bits to be added.  The downside, is that this programming loop would be repeated every time you wanted to determine carry out and overflow for a given word pair - no such penalty in physical circuits or FPGA.
As a bonus, it's super easy to determine an overflow flag, which indicates whether the 2's compliment addition will be representable from the summation.
See the reference links below.
The code is for 32-bit integers, however could be adapted for longer or shorter types.
http://www.righto.com/2012/12/the-6502-overflow-flag-explained.html
https://en.wikipedia.org/wiki/Carry-lookahead_adder
// Global carry and overflow flags
// Set by carryLookahead()
bool carry, ov;

// Determines presence of carry out and overflow from 2's compliment addition
//
bool carryLookahead(int32 f1, int32 f2){
unsigned long mask;
unsigned long g,p;
unsigned char i;
// uses & sets global carry and ov flag variables

    mask=1;
    carry=ov=false; // initial carry and overflow flag assumed to be zero

    g = f1 & f2;  // bit pairs that will generate carry
    p = f1 | f2;  // bit pairs that will propagate a carry

    for(i=0; i < 32; ++i, mask <<= 1){
        ov=carry; // set ov to last carry
        carry = (g&mask) || (p&mask) && carry;  // use logical rather than bitwise logic to set the current carry;
        ov=ov^carry; // ov is xor of last and current carries
    }

    return(carry);

}


text:
Q: form not showing when i click on custom module menu Form not showing when clicking on custom module menu.
Here's my code:

/home1/dukaania/public_html/testing2/app/code/Test/Banners/etc/adminhtml/menu.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Backend:etc/menu.xsd">
<menu>
    <add id="Test_Banners::first_level_demo"
         title="Shipping Vendor"
         module="Test_Banners"
         sortOrder="9999"
         resource="Magento_Backend::content" />

    <add id="Test_Banners::second_level_demo"
         title="Shipping Vendor Cost"
         module="Test_Banners"
         sortOrder="0"
         action="uiform/"
         parent="Test_Banners::first_level_demo"
         resource="Magento_Backend::content" />
</menu>

/home1/dukaania/public_html/testing2/app/code/Test/Banners/etc/adminhtml/routes.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="admin">
        <route id="uiform" frontName="uiform">
            <module name="Test_Banners"/>
        </route>
    </router>
    /home1/dukaania/public_html/testing2/app/code/Test/Banners/view/adminhtml/layout/ui_component/employee_form.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
        <argument name="data" xsi:type="array">
            <item name="js_config" xsi:type="array">
                <item name="provider" xsi:type="string">employee_form.employee_form_data_source</item>
                <item name="deps" xsi:type="string">employee_form.employee_form_data_source</item>
            </item>
            <item name="label" xsi:type="string" translate="true">Employee Information</item>
            <item name="config" xsi:type="array">
                <item name="dataScope" xsi:type="string">data</item>
                <item name="namespace" xsi:type="string">employee_form</item>
            </item>
            <item name="template" xsi:type="string">templates/form/collapsible</item>
        </argument>
        <dataSource name="employee_form_data_source">
            <argument name="dataProvider" xsi:type="configurableObject">
                <argument name="class" xsi:type="string">Test\Banners\Model\DataProvider</argument>
                <argument name="name" xsi:type="string">employee_form_data_source</argument>
                <argument name="primaryFieldName" xsi:type="string">id</argument>
                <argument name="requestFieldName" xsi:type="string">id</argument>
            </argument>
            <argument name="data" xsi:type="array">
                <item name="js_config" xsi:type="array">
                    <item name="component" xsi:type="string">Test/Banners/form/provider</item>
                </item>
            </argument>
        </dataSource>
        <fieldset name="employee_details">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="collapsible" xsi:type="boolean">true</item>
                    <item name="label" xsi:type="string" translate="true">Employee Details</item>
                    <item name="sortOrder" xsi:type="number">20</item>
                </item>
            </argument>
            <field name="employee_id">
                <argument name="data" xsi:type="array">
                    <item name="config" xsi:type="array">
                        <item name="dataType" xsi:type="string">text</item>
                        <item name="label" xsi:type="string" translate="true">Employee Id</item>
                        <item name="formElement" xsi:type="string">input</item>
                        <item name="source" xsi:type="string">employee</item>
                        <item name="dataScope" xsi:type="string">employee_id</item>
                    </item>
                </argument>
            </field>
            <field name="employee_name">
                <argument name="data" xsi:type="array">
                    <item name="config" xsi:type="array">
                        <item name="dataType" xsi:type="string">text</item>
                        <item name="label" xsi:type="string" translate="true">Employee Name</item>
                        <item name="formElement" xsi:type="string">input</item>
                        <item name="source" xsi:type="string">employee</item>
                        <item name="dataScope" xsi:type="string">employee_name</item>
                    </item>
                </argument>
            </field>
            <field name="employee_salary">
                <argument name="data" xsi:type="array">
                    <item name="config" xsi:type="array">
                        <item name="dataType" xsi:type="string">text</item>
                        <item name="label" xsi:type="string" translate="true">Employee Salary</item>
                        <item name="formElement" xsi:type="string">input</item>
                        <item name="source" xsi:type="string">employee</item>
                        <item name="dataScope" xsi:type="string">employee_salary</item>
                    </item>
                </argument>
            </field>
            <field name="employee_address">
                <argument name="data" xsi:type="array">
                    <item name="config" xsi:type="array">
                        <item name="dataType" xsi:type="string">text</item>
                        <item name="label" xsi:type="string" translate="true">Employee Address</item>
                        <item name="formElement" xsi:type="string">textarea</item>
                        <item name="source" xsi:type="string">employee</item>
                        <item name="dataScope" xsi:type="string">employee_address</item>
                    </item>
                </argument>
            </field>
        </fieldset>

/home1/dukaania/public_html/testing2/app/code/Test/Banners/Controller/Adminhtml/Employee/Index.php

<?php
namespace Test\Banners\Controller\Adminhtml\Employee;

use Magento\Framework\Controller\ResultFactory;

class Index extends \Magento\Backend\App\Action\Action
{
protected $_pageFactory;

/**
 * Index constructor.
 * @param \Magento\Framework\App\Action\Context $context
 * @param \Magento\Framework\View\Result\PageFactory $pageFactory
 */
public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Magento\Framework\View\Result\PageFactory $pageFactory)
{
    $this->_pageFactory = $pageFactory;
    return parent::__construct($context);
}

/**
 * @return \Magento\Framework\View\Result\Page
 */
public function execute()
{
    return $this->_pageFactory->create();
}
}

A: From here looking at your question you have worng path of ui component
wrong path
/home1/dukaania/public_html/testing2/app/code/Test/Banners/view/adminhtml/layout/ui_component/employee_form.xml

correct path
/home1/dukaania/public_html/testing2/app/code/Test/Banners/view/adminhtml/ui_component/employee_form.xml

and change in menu.xml
<add id="Test_Banners::second_level_demo"
         title="Shipping Vendor Cost"
         module="Test_Banners"
         sortOrder="0"
         action="uiform/employee"
         parent="Test_Banners::first_level_demo"
         resource="Magento_Backend::content" />

because your controller path uiform/employee/index


text:
Q: How to map an XML to Java objects by XPaths? Given the XML example:
<fooRoot>
  <bar>
    <lol>LOLOLOLOL</lol>
  </bar>
  <noob>
    <boon>
      <thisIsIt></thisIsIt>
    </boon>
  </noob>
</fooRoot>

Which should be mapped to:
class MyFoo {
  String lol;
  String thisIsIt;
  Object somethingUnrelated;
}

Constraints:

*

*XML should not be transformed, it is provided as a parsed org.w3c.dom.Document object.

*Class does not and will not map 1:1 to the XML.

*I'm only interested to map specific paths of the XML to specific fields of the object.

My dream solution would look like:
@XmlMapped
class MyFoo {

  @XmlElement("/fooRoot/bar/lol")
  String lol;

  @XmlElement("/noob/boon/thisIsIt")
  String thisIsIt;

  @XmlIgnore
  Object somethingUnrelated;
}

Does anything likewise exists? What I've found either required a strict 1:1 mapping (e.g. JMX, JAXB) or manual iteration over all fields (e.g. SAX, Commons Digester.)
JiBX binding definitions come the nearest to what I'm lokking for. However, this tool is ment to marshall/unmarshall complete hierarchy of Java objects. I only would like to extract parts of an XML document into an existing Java bean at runtime.

A: Note:  I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB 2 (JSR-222) expert group.
You can do this with MOXy:
@XmlRootElement(name="fooRoot")
class MyFoo {

  @XmlPath("bar/lol/text()")
  String lol;

  @XmlElement("noob/boon/thisIsIt/text()")
  String thisIsIt;

  @XmlTransient
  Object somethingUnrelated;
}

For More Information

*

*http://blog.bdoughan.com/2010/07/xpath-based-mapping.html

*http://blog.bdoughan.com/2010/09/xpath-based-mapping-geocode-example.html

*http://blog.bdoughan.com/2011/03/map-to-element-based-on-attribute-value.html

*http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html

A: Try XStream. It's super easy. Hope it helps! I don't have time now for a full example :)

A: One option could be write a custom annotation which will take the XPath expression as input and do the bindings.


text:
Q: Finite integral with removable singularity I wanted to integrate $\frac{(exp(-x) -1)^2}{x}$ from $x=0$ to $x=a$ where $a$ is finite. Since the integrand, viz., $\frac{(exp(-x) -1)^2}{x}$ has a removable singularity at $x=0$ , I can take the lower limit to be zero for the integration. Further, if I use finite integration upper limit, I cannot use Jordan's Lemma. What approach do I use? Is there any other method? Or is there a way out using contour integration??
Thank You!

A: Probably the best way is to regularise the integral by adding an $x^s$, calculate it in terms of incomplete Gamma functions, then let $s \to 0$. We have
$$ \int_0^a x^{s-1}(e^{-x}-1)^2 \, dx = \int_0^a x^{s-1}(e^{-2x}-2e^{-x}+1) \, dx = \frac{a^s}{s} - 2\gamma(s,a) + 2^{-s}\gamma(s,2a), $$
in terms of the lower incomplete gamma function. In terms of the upper incomplete gamma function, this is
$$ \frac{a^s}{s} + (2^{-s}-2)\Gamma(s) + 2\Gamma(s,a) - 2^{-s} \Gamma(s,2a). $$
The last two terms are analytic in $s$, so we can happily take $s=0$ in them. For the former, we have
$$ \frac{a^s}{s} = \frac{1}{s} + \log{a} + O(s), $$
using the usual series expansion for a power, and
$$ (2^{-s}-2)\Gamma(s) = \left(-1-s\log{2}+O(s^2)\right) \left( \frac{1}{s} -\gamma + O(s) \right) = -\frac{1}{s} + \gamma - \log{2} + O(s), $$
using the Laurent series of $\Gamma$ at $0$.
Adding these, the divergent $s^{-1}$s cancel as they should, and we get
$$ \int_0^a x^{-1}(e^{-x}-1)^2 \, dx = \log{a}-\log{2}+\gamma + 2\Gamma(0,a) - \Gamma(0,2a). $$
(The latter two terms can also be written using exponential integrals if so desired.)

Edited to add:
Recall a possible definition of $a^s$ is $a^s = e^{s\log{a}}$. Since we know how to expand the exponential function as a power series, we obtain the expansion
$$ a^s = e^{s\log{a}} = \sum_{k=0}^{\infty} \frac{(\log{a})^k}{k!} s^k. $$
(alternatively, consider the definition of $e^x$ as the limit of $(1+x/n)^n$: rearranging this allows us to write
$$ \log{y} = \lim_{n \to \infty} n(y^{1/n}-1) = \lim_{s \to 0} \frac{y^s-1}{s}, $$
which we recognise as the derivative quotient of $y^s$ at $s=0$.)
$\gamma$ is the Euler-Mascheroni constant, which is basically defined as $-\Gamma'(1)$: for our purposes, it comes from the integral
$$ \int_0^{\infty} e^{-t}\log{t} \, dt = -\gamma, $$
in which you can recognise the derivative of $x^{s-1} e^{-x} $ with respect to $s$ at $s=1$.


text:
Q: play videos from your computer on your Android, without copying them to your device http://www.howtogeek.com/120882/how-to-access-shared-windows-folders-and-stream-videos-over-wi-fi-on-android/
Look at this link. It has a demo in which they use ES File Explorer and play a video/movie directly on android device without copying.
So my simple question is,
What protocol do they ( i.e ES File Explorer) use / how exactly they manage to stream or broadcast this video file on to android device ? Is there any specific protocol for this to perform ?  Can i do the same thing in an android app ?
I've no idea in this so i had to start with very basic. Thank you in advance

A:
What protocol do they ( i.e ES File Explorer) use

They appear to use SMB, based on the first screenshot.

Is there any specific protocol for this to perform ?

SMB (also known as CIFS) is a protocol. It has been in use on Windows networks for a couple of decades.

Can i do the same thing in an android app ?

I am not aware of any Android-specific libraries for this, though I know that some people have been trying jCIFS for this. I do not know the details of how they get that to work for playing back videos. However, this open source media player app uses jCIFS and, AFAIK, can play back videos using it.


text:
Q: Android: have no permission to write data to SDCard In my app, I need to download some mp4 files to storage. There is a option menu to select the location of mp4 files(phone storage or sdcard storage).
I get the phone storage path and sdcard storage path by reflect android SDK.as below:
public class StorageUtils {

    private static final String TAG = "===StorageUtil===";

    public static String getPrimaryStoragePath(Context context) {
        try {
            StorageManager sm = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
            Method getVolumePathsMethod = StorageManager.class.getMethod("getVolumePaths", null);
            String[] paths = (String[]) getVolumePathsMethod.invoke(sm, null);
            // first element in paths[] is primary storage path
            return paths[0];
        } catch (Exception e) {
            Log.e(TAG, "getPrimaryStoragePath() failed", e);
        }
        return null;
    }

    public static String getSecondaryStoragePath(Context context) {
        try {
            StorageManager sm = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
            Method getVolumePathsMethod = StorageManager.class.getMethod("getVolumePaths", null);
            String[] paths = (String[]) getVolumePathsMethod.invoke(sm, null);
            // second element in paths[] is secondary storage path
            return paths[1];
        } catch (Exception e) {
            Log.e(TAG, "getSecondaryStoragePath() failed", e);
        }
        return null;
    }

    public static String getStorageState(Context context, String path) {

        try {
            StorageManager sm = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
            Method getVolumeStateMethod = StorageManager.class.getMethod("getVolumeState", new Class[]{String.class});
            String state = (String) getVolumeStateMethod.invoke(sm, path);
            return state;
        } catch (Exception e) {
            Log.e(TAG, "getStorageState() failed", e);
        }
        return null;
    }
}

And my test code as below:
public class StorageTestActivity extends AppCompatActivity {

    private TextView primaryStoragePath;
    private TextView slaveStoragePath, tvStatus;
    private Button btn1, btn2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_storage_test);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        primaryStoragePath = (TextView) findViewById(R.id.primaryStoragePath);
        slaveStoragePath = (TextView) findViewById(R.id.slaveStoragePath);

        //state: mounted, shared, removed
        final String path1 = StorageUtils.getPrimaryStoragePath(this);
        String state1 = StorageUtils.getStorageState(this, path1);
        StringBuilder sb1 = new StringBuilder().append("path1:").append(path1).append("\n").append("state1=").append(state1);
        primaryStoragePath.setText(sb1.toString());

        final String path2 = StorageUtils.getSecondaryStoragePath(this);
        String state2 = StorageUtils.getStorageState(this, path2);
        StringBuilder sb2 = new StringBuilder().append("path2:").append(path2).append("\n").append("state2=").append(state2);
        slaveStoragePath.setText(sb2.toString());

        btn1 = (Button) findViewById(R.id.btnWriteToPrimaryStorage);
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                currentType = 0;
                writeData(path1);
            }
        });

        btn2 = (Button) findViewById(R.id.btnWriteToSDCard);
        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                currentType = 1;
                writeData(path2);
            }
        });

        tvStatus = (TextView) findViewById(R.id.tvStatus);

    }

    private int currentType = 0;
    private void writeData(final String path) {

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                String state = StorageUtils.getStorageState(StorageTestActivity.this, path);
                if(!"mounted".equals(state)) {
                    Snackbar.make(slaveStoragePath, "state is " + state, Snackbar.LENGTH_LONG).show();
                    return;
                }

                String tmpPath = path+File.separator+"Android/data/com.example.fjz.myapplication/";
                File directory = new File(tmpPath);

                if (!directory.exists()) {
                    Log.e("========", "create directories.");
                    directory.mkdirs();
                }

                File file = new File(tmpPath + "abcdefg.txt");
                if (file.exists()) {
                    file.delete();
                }

                try {
                    file.createNewFile();
                    handler.sendEmptyMessage(currentType);
                } catch (IOException e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(3);
                }

                Log.e("storage test activity:", file.getAbsolutePath());

            }
        };

        new Thread(runnable).start();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            if(msg.what == 0) {
                tvStatus.setText("Write primary success");
            } else if(msg.what == 1) {
                tvStatus.setText("Write SD card success");
            } else {
                tvStatus.setText("Write failed.");
            }
        }
    };

Then error:

01-18 16:05:12.819 30125-30601/com.example.myapplication W/System.err:
  java.io.IOException: open failed: EACCES (Permission denied) 01-18
  16:05:12.819 30125-30601/com.example.myapplication W/System.err:
  at java.io.File.createNewFile(File.java:978) 01-18 16:05:12.819
  30125-30601/com.example.myapplication W/System.err:     at
  com.example.fjz.demo.StorageTestActivity$4.run(StorageTestActivity.java:108)
  01-18 16:05:12.819 30125-30601/com.example.myapplication W/System.err:
  at java.lang.Thread.run(Thread.java:841) 01-18 16:05:12.819
  30125-30601/com.example.myapplication W/System.err: Caused by:
  libcore.io.ErrnoException: open failed: EACCES (Permission denied)
  01-18 16:05:12.819 30125-30601/com.example.myapplication W/System.err:
  at libcore.io.Posix.open(Native Method) 01-18 16:05:12.819
  30125-30601/com.example.myapplication W/System.err:     at
  libcore.io.BlockGuardOs.open(BlockGuardOs.java:110) 01-18 16:05:12.819
  30125-30601/com.example.myapplication W/System.err:     at
  java.io.File.createNewFile(File.java:971) 01-18 16:05:12.819
  30125-30601/com.example.myapplication W/System.err:   ... 2 more

In manifest file, I have declared the permissions:

help me, Thanks very much

A: You need to add write permission in your AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

A: I declared the permissions as below:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Fortunately, I get it.
1)I get the sdcard path as /storaget/sdcard1
2)Then I make the path /storaget/sdcard1/Android/data/com.example.sdcard.demo
3)Try to mkdirs(path), then return false, so I have no permission to create 'Android/data/com.example.sdcard.demo' directory.
4 )I can call the api:getExternalCacheDir which can create this directory success.


text:
Q: Masking an image using CGLayerRef and CGContextDrawLayerInRect I want to mask an image by another image using CGLayerRef in off-screen rendering since it's suitable for high-quality rendering as it's mentioned in documentation

Core Graphics Layer Drawing :
  CGLayer objects allow your application to use layers for drawing.
  Layers are suited for the following: High-quality offscreen rendering
  of drawing that you plan to reuse.

But I couldn't find any example in objective-c that I could understand how it works. On my context, I want to mask an image with a shape image (solid color shape) I used to do it this way
//The context I use to mask my image with the mask image.
CGColorSpaceRef colorSpace= CGColorSpaceCreateDeviceRGB();
    CGContextRef mainViewContentContext = CGBitmapContextCreate (NULL, _bigImageRect.size.width, _bigImageRect.size.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);
CGColorSpaceRelease(colorSpace);

//Mask image
CGContextClipToMask(mainViewContentContext,
                       CGRectMake(0,
                                   -_bigImageRect.origin.y,
                                   _bigImageRect.size.width,
                                   _bigImageRect.size.height),
                                   _maskImage.CGImage);

//Drawing the image on the mask image.
CGContextDrawImage(mainViewContentContext,
                       CGRectMake(0,
                                  0,
                                  _bigImageRect.size.width,
                                  _bigImageRect.size.height),
                                  _ImageToBeMasked.CGImage);

CGImageRef mainViewContentBitmapContext = CGBitmapContextCreateImage(mainViewContentContext);
CGContextRelease(mainViewContentContext);
UIImage*maskedImage = [UIImage imageWithCGImage:mainViewContentBitmapContext];
CGImageRelease(mainViewContentBitmapContext)
return maskedImage;

But how can I mask using CGLayers as below? I appreciate any help.
CGLayerRef layer = CGLayerCreateWithContext(mainViewContentContext, _bigImageRect.size, NULL);
CGContextDrawLayerInRect(mainViewContentContext, _bigImageRect, layer);
CGLayerRelease(layer);
//And then.. how can I do the masking using this CGLayerRef???

A: I normaly write Swift code, but once I also had to deal with masking and CGLayer.
I solved the problem with the following steps:

*

*Draw your mask

*Change blend mode to CGBlendMode.sourceIn

*Draw your "color" image.

This works because CGBlendMode.sourceIn tells the context to multiply the alpha value of the source image with the color of the existing pixel. Therefore invisible parts of the mask (alpha = 0.0) will stay invisible.
Apple docs for CGBlendMode: https://developer.apple.com/documentation/coregraphics/cgblendmode

A: It doesn't really answer the question but I finally ended up using the conventional methods such as CGContextClipToMask and CGContextDrawImage but I managed to gain my desired high-quality before masking. Again, I need to mention that this works just in my case (which was masking an image with a rendered bezier path on it but at image's full resolution) If you have the same problem for more information you can check my other related question here
Masking an image using bezierpath with image's full resolution
and my github working project as well.
https://github.com/Reza-Abdolahi/HighResMasking
Here's the code that worked for me:
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGImageRef maskImageRef = [_maskImage CGImage];
    CGContextRef myContext = CGBitmapContextCreate (NULL, _highResolutionImage.size.width, _highResolutionImage.size.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);
    CGColorSpaceRelease(colorSpace);
    if (myContext==NULL)
        return NULL;

    CGFloat ratio = 0;
    ratio = _maskImage.size.width/ _highResolutionImage.size.width;
    if(ratio * _highResolutionImage.size.height < _maskImage.size.height) {
        ratio = _maskImage.size.height/ _highResolutionImage.size.height;
    }

    CGRect rectForMask  = {{0, 0}, {_maskImage.size.width, _maskImage.size.height}};
    CGRect rectForImageDrawing  = {{-((_highResolutionImage.size.width*ratio)-_maskImage.size.width)/2 , -((_highResolutionImage.size.height*ratio)-_maskImage.size.height)/2},
        {_highResolutionImage.size.width*ratio, _highResolutionImage.size.height*ratio}};

    CGContextClipToMask(myContext, rectForMask, maskImageRef);
    CGContextDrawImage(myContext, rectForImageDrawing, _highResolutionImage.CGImage);
    CGImageRef newImage = CGBitmapContextCreateImage(myContext);
    CGContextRelease(myContext);
    UIImage *theImage = [UIImage imageWithCGImage:newImage];
    CGImageRelease(newImage);
    return theImage;


text:
Q: Can't page break to work without messing up the table formatting I have been having issues with page breaks in tables. Thought I had a solution as it was working fine in this SO question:
Inserting a page break into of
 in React app
This worked fine for a table with one column, but nowt that I am working with multiple columns, it is a mess.
Basically I have to include display: block to get the page break to work properly, but that makes it go from a well formatted table to this:

I have gone down the list in MDN just trying anything that might work.
https://developer.mozilla.org/en-US/docs/Web/CSS/display
Furthermore, page breaks are only working when on their own separate
 which is undesirable since it generates a blank page. Got this sorted out by moving the pagebreak to the
 instead of the .
I haven't been able to resolve these issues; any suggestions on how to approach this problem?
Not sure how useful a JSFiddle will be given the printing issue, but here is the compiled HTML. I can never get JSFiddle working with React:
https://jsfiddle.net/5gz62d91/
Best would probably be the Github repo:
https://github.com/ishraqiyun77/page-breaks
Here is the code separately:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';

import styles from '../assets/scss/app.scss';

class PageBreakIssues extends Component {

    // Render the data points
    renderDataPoint() {
        let dataPoint = [];
        for (let i = 1; i <= 3; i++) {
            let num = (Math.random() * 100).toFixed(2);
            dataPoint.push(

                    { num < 25 ? null : num }

            )
        }
        return dataPoint;
    }

    // Start generating the row data
    renderDataRow() {
        let dataRow = [];
        for (let i = 1; i <= 5; i++) {
            dataRow.push(

                    Test - { i }
                    { this.renderDataPoint() }

            )
        }
        return dataRow;
    }

    // Start generating table sections with the section name
    // COMMENT THIS OUT TO TRY WITOUT ADDING A BLANK ROW
    renderSections() {
        let sections = [];
        for (let i = 1; i <= 10; i++) {
            sections.push(

                            Section - { i }

                    { this.renderDataRow() }
                    {
                        i % 2 === 0
                            ?

                            :
                            null
                    }

            )
        }
        return sections;
    }

    // Start generating table sections with the section name
    // UNCOMMENT THIS SECTION TO TRY WITHOUT INSERT BLANK TR
    // renderSections() {
    //     let sections = [];
    //     for (let i = 1; i <= 10; i++) {
    //         sections.push(
    //

    //

    //
    //                         Section - {i}
    //
    //

    //                 {this.renderDataRow()}
    //

    //         )
    //     }
    //     return sections;
    // }

    // Render the table with
    render() {
        return (

                        Results
                        1
                        2
                        3

                { this.renderSections() }

        )
    }
}

ReactDOM.render(<PageBreakIssues />, document.getElementById('app'));

@mixin borders {
    border: 1px solid black;
}

%borders {
    @include borders;
}

table {
    border-spacing: 0;

    th {
        text-align: center;
    }

    tr {
        th{
            @extend %borders;
        }

        td {
            @extend %borders;
            &.data-name {
                padding: 3px 100px 3px 3px;
            }

            &.data-point {
                text-align: center;
                padding: 3px 10px;
            }

            &.section-name {
                background-color: #999;
            }
        }
    }
}

@media print {
    tr {
        display: block;
    }

    .pagebreak {
        break-before: always !important;
        page-break-before: always !important;
        page-break-inside: avoid !important;
    }
}

A: I figure out an even more hard-coding method (so call perfectly solve your problem). I must said it is not elegant.
My method's main idea is changing tbody to display:block (as usual), but adding the .pagebreak to target tbody as well.
However, this method unattach tbody from the table and thus no longer align with thead. That's why I add a tr for printing thead, and remove the origin thead when print.
Added printing th, don't show in normal view
//Thead part, add a printing thead only shown in Print
//As originaly thead will has alloction problem
{ i % 2 === 1 ?

    Results
    1
    2
    3

 : null
}
....
...
//Corrected Page break

...

Corresponding CSS
table {
  border-spacing: 0;
  table-layout: fixed;
  th {
    text-align: center;
  }
  tr {
    th {
      @extend %borders;
    }
    td {
      @extend %borders;
      &.data-name {
        padding: 3px 100px 3px 3px;
      }
      &.data-point {
        text-align: center;
        padding: 3px 10px;
      }
      &.section-name {
        background-color: #999;
      }
    }
  }
  tr.printing-thead {
    display: none;
  }
}

@media print {
  thead {
    display: none;
  }
  tbody {
    display: block;
    tr.printing-thead {
      display: contents;
      font-weight: bold;
      text-align: center;
    }
  }
  .pagebreak {
    height: 0px;
    break-before: always !important;
    page-break-before: always !important;
    page-break-inside: avoid !important;
    td {
      display: none;
    }
  }
}

The JSfiddle.
And the react version
JSfiddle React Version


text:
Q: Stack Overflow After 15 Recursions with Javascript Class Function I have the following code sample to illustrate my point.  When I load this in IE8 on Vista I get the error "Stack Overfow at line:16"
If I recurse using a top level function (outside of the testClass object) I can recurse millions of times without a stack overflow.
Why is this happening? Ultimately I just implemented a Function Que instead of using recursion, but just doesn't make sense to me, and I'd like to understand the cause.
-- code --
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN">
<html>
    <head>
        <title>Recusion Test</title>
        <body>
        </body>

        <script type="text/javascript">

            function testClass() {
                this.x = 15;
                this.recurse = function() {
                    this.x--;
                    this.recurse();
                }
            }

            var wtf = new testClass();
                wtf.recurse();

            alert('done');
        </script>
    </head>
</html>

A: There is no terminating condition for your recursive statement therefore it will run forever.
It appears that you want...

            function testClass() {
                this.x = 15;
                this.recurse = function() {
                    if (this.x--)
                        this.recurse();
                }
            }

            var wtf = new testClass();
                wtf.recurse();

            alert('done');

A: Ok, here's some more insight into the issue I was having.  After going back and fixing what I thought was the problem with my application I was still having the issue.  The part that made me pursue the issue was that if I recursed only 14 times it would complete successfully.
First, I was executing the original code in an HTA and not Internet Explorer.  I'm writing a VIM based code editor similar to FCKEditor.
Second, the structure of my code is as follows:
-HTA
--EditorClass
---DivManagerClass
----KeyBindingClass
In my KeyBindingClass I had a codebase similar to the example provided (except it has a terminating condition)
In my KeyBindingClass I have a repeater property that would repeat the last keystrok N-times if a numeric modifier was pressed.  For those that don't know pressing the keys '3' and 'x' in visual mode in vim will delete three characters.
Everything worked fine until I used a numeric modifier greater than 14.
I kept trying to reproduce this issue with a small test harness and couldn't.  I was able to recurse up to 3000 in a basic test harness.  So I started recreating the scenario as best I could.  First I moved the call to the recurse method into another class/method.  That limited my call stack to somewhere around 1600 (almost half the stack just vanished.)
Then I added jQuery to the mix and moved the call to the ParentClass.recurse method into a keybinding event inside the document.onready jquery handler.  That reduced my callstack to about 1300.
Then I moved my code into an HTA which cut my call stack in half again!  After mimicking my codebase as best I could and as quickly as I could I reached a callstack of about 515.
After doing some reasearch I have found the IE uses available memory space to determine callstack size.  I'm guessing the HTA is a little more strict in that regard.  I haven't figured out what other factor has limited my application to such a low callstack given the class structure, but it is definitely code structure that's the issue.
I can put my basic recursion test in a top level execution script tag and get about 1473 calls before reaching a stack overflow.
I can still use a function queue to fix my problem, but I just wanted others to know that A. I wouldn't post such a simple problem to Stack Overflow, and B. that your call stack limit can be vastly affected by the class structures surrounding functions, even though they aren't separate levels of what you'd traditionally consider a function stack.


text:
Q: Understanding Dirichlet Process Mixtures I have been reading a ton of stuff online and have a question about my understanding of Dirichlet Process Mixtures. First some basics on what I understand:
Dirichlet Distribution:  multivariate generalization of beta distribution
Probability measure: function that assigns subsets to values in [0,1] (a probability)
Dirichlet Process (DP): $P$, a probability measure, is a DP if for every finite disjoint partition $S_1,S_2,\dots S_n$ of space $\omega$, the following is true:
($P(S_1), P(S_2),\dots P(S_n)$)  has Dirichlet Distribution with parameters $\alpha *P_0(S_1), \alpha * P_0(S_2),\dots\alpha * P_0(S_n)$
where $E(P(S_i)) =  P_0$
Ok, I get it so far. Let's move onto Dirichlet Process MIXTURES
Dirichlet Process Mixture =  hierarchical model where

*

*$x_i |  \theta_i$ has distribution $f_\theta$

*$\theta_1, \theta_2\dots\theta_n$  has distribution $P$

*$P$ is a Dirichlet Process with params $\alpha$ and $P_0$
So let me check to see if I understand these 3 lines correctly
What first line is saying:
a point $x$ comes from a distribution, let's say $f_\theta$ = normal with parameters $\mu = 0$ and $\sigma = 1$
What the second and third line are saying is:
My space omega is partitioned into parameter subsets. So let's say our components are normals. So $\theta_1$ = mean 0 with std 1, $\theta_2$ = mean 3 with std 5, ...
So in essence $\omega = \theta_1 \cup \theta_2 \cup \dots$
So $P(\theta_i)$ = probability of us getting the parameter set $i$
Since $P$ is a DP,
$(P(\theta_1), P(\theta_2)\dots)$ has distribution $\mathrm{Dir}(\alpha * P_0(\theta_1), \alpha * P_0(\theta_2)\dots)$
Am I correct?

A: Probably it is better to describe how one would generate data from a Dirichlet process mixture. Each line is understood to be conditional on all lines above it.

*

*Sample $P \sim \operatorname{DP}(\alpha P_0)$.

*Sample $\theta_1, \ldots, \theta_n \sim P$ independently.

*Sample $X_1, \ldots, X_n$ independently such that $X_i \sim f_{\theta_i}$.

That's all there is to it. The only thing different from drawing from a DP versus a DP-mixture is that if you are just drawing data from a DP you stop after step 2 and take the $\theta_i$'s as your data. For a DP mixture, the $\theta_i$'s are not observed but instead represent latent variables.


text:
Q: Rails URL question If I have a Users model, and then an individual user, say, person1, is there a way to have the url: www.myapp.com/person1 show what www.myapp.com/users/person1 would? What would that be called?
Thank you!

A: You should define a route in your routes.rb file:
match "/:user" => "users#show"

and you'll get the username given in params[:user]. But you need to know that this kind of route could override other routes defined, because it will match any string, so you should at least define some constraints on the username.
For example if your usernames matches a regexp you could define it as a constraint
match "/:user" => "users#show", :constraints => { :user => /some-regexp/ }

and don't forget to set this route as the last one in your routes file, otherwise it will clash for sure with other routes.
Read this for full reference

A: add "two" routes for the same thing to your app.
 # Shorter url to show store items by tags
map.connect '/s/tags',
  :controller => 'music',
  :action     => 'show_by_tags'
map.connect '/music/s/tags',
  :controller => 'music',
  :action     => 'show_by_tags'


text:
Q: slick + анимация wow js Есть горизонтальный сайт который работает через slick и работает по блочно.
Нужно чтобы, при скролле на следующий слайд запускалась анимация элементов на этом слайде, (facts-item-hint). Тут наглядный пример, как это должно работать https://lore1ei.github.io/ на первом слайде все нормально, а второй запускается вместе с первым, а должен только когда он находится в видимости окна браузера.

SM-Marketing

Методика №1

по скоростному получению клиентов из интернета

или
 как с полного нуля,
 всего через пару дней
 начать получать первые заявки

как найти новых клиентов

как получать больше заявок

как построить систему лидогенерации

Факт №1

Заявки  это сырьё для продаж

                    Не будет заявок – не будет и продаж

Факт №2

Прямо сейчас ваши конкуренты используют маркетинговые

                    инструментыи поэтому у них всё впорядке с клиентами

Тут Css слайдера
.slider
    width: 100%
    height: 100vh

.slick-list,
.slick-track
    width: 100%
    height: 100%

.slider__item
    width: 100%
    height: 100%

Тут как работает сам сайт на слайдере
$(function () {
    $('.slider').slick({
      infinite: false,
      arrows: false
    });

    $('.slider').mousewheel(function (e) {
      if (e.deltaY !== 1) {
        $('.slider').slick('slickNext');
      } else {
        $('.slider').slick('slickPrev');
      }

      e.preventDefault();
    });
  });

Пробывал с оффсетом на вертикальной прокрутки он работает нормально, а на горизонтальной все элементы сразу запускают анимацию.

A: Оригинал тут - codepen.io/joxxce
Пример именно для Вашего слайдера:

$('.slider').on('init', function(e, slick) {
  var $firstEl = $('.slider_item:first-child').find('[data-animation]');
  doAnimation($firstEl);
});
$('.slider').on('beforeChange', function(e, slick, currentSlide, nextSlide) {
  var $animationEl = $('.slider_item[data-slick-index="' + nextSlide + '"]').find('[data-animation]');
  doAnimation($animationEl);
});

$('.slider').slick({
  infinite: false,
  arrows: false,
});

$('.slider').mousewheel(function (e) {
  if (e.deltaY !== 1) {
    $('.slider').slick('slickNext');
  } else {
    $('.slider').slick('slickPrev');
  }

  e.preventDefault();
});

function doAnimation(elements) {
  var animationEndEvents = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
  elements.each(function() {
    var $this = $(this);
    var $animationDelay = $this.data('delay');
    var $animationType = 'animated ' + $this.data('animation');
    $this.css({
      'animation-delay': $animationDelay,
      '-webkit-animation-delay': $animationDelay
    });
    $this.addClass($animationType).one(animationEndEvents, function() {
      $this.removeClass($animationType);
    });
  });
}

// new WOW({
//   offset: 100
// }).init();
* {
  box-sizing: border-box;
}

html,
body {
  padding: 0;
  margin: 0;

  width: 100%;
  height: 100%;
}

.slider,
.slick-list,
.slick-track,
.slider__item {
  width: 100%;
    height: 100vh;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.2/animate.min.css" />

<link rel="stylesheet" href="https://cdn.jsdelivr.net/jquery.slick/1.5.7/slick.css" />

SM-Marketing

Методика №1

по скоростному получению клиентов из интернета

или
 как с полного нуля,
 всего через пару дней
 начать получать первые заявки

как найти новых клиентов

как получать больше заявок

как построить систему лидогенерации

Факт №1

Заявки  это сырьё для продаж

            Не будет заявок – не будет и продаж

Факт №2

Прямо сейчас ваши конкуренты используют маркетинговые

            инструментыи поэтому у них всё впорядке с клиентами

Суть в том, что плагин wow тут не используется, а используется только animate.css.

A: CodePen Готовый пример slick-slider + wow.js

function animateSlider(elements){
  var animationEndEvents = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
  elements.each(function(){
    var $this = $(this);
    var $animationType = 'animated ' + $this.data('animation');
    $this.addClass($animationType).one(animationEndEvents, function() {
      $this.removeClass($animationType);
    });
  })
}
$("#animation-slider").on("beforeChange", function(e, slick, currentSlide, nextSlide) {
  var $animatingElements = $('.slick-slide[data-slick-index="' + nextSlide + '"]').find('[data-animation]');
  animateSlider($animatingElements);
})
$('#animation-slider').on('init', function(e, slick) {
  var $firstAnimatingElements = $('.slick-slide:first-child').find('[data-animation]');
  animateSlider($firstAnimatingElements);
});
$('.hero-carousel').slick({
  infinite: true,
  slidesToShow: 1,
  slidesToScroll: 1,
  dots: true,
  arrows: true,
  speed: 300,
  fade: true,
  cssEase: 'linear',
  // autoplay: true,
  // autoplaySpeed: 3000,
});
.hero-carousel__item
  border: 1px solid black
  text-align: center
  padding: 20px
.hero-carousel#animation-slider
  .hero-carousel__item
    h1(data-animation="fadeInDown" data-delay="0.3s") Пример анимации
    .buttin(data-animation="fadeInUp" data-delay="0.3s")
      button Кнопка
  .hero-carousel__item
    h1(data-animation="fadeInDown" data-delay="0.3s") Пример анимации
    .buttin(data-animation="fadeInUp" data-delay="0.3s")
      button Кнопка
  .hero-carousel__item
    h1(data-animation="fadeInDown" data-delay="0.3s") Пример анимации
    .buttin(data-animation="fadeInUp" data-delay="0.3s")
      button Кнопка
  .hero-carousel__item
    h1(data-animation="fadeInDown" data-delay="0.3s") Пример анимации
    .buttin(data-animation="fadeInUp" data-delay="0.3s")
      button Кнопка


text:
Q: SharePoint List/Excel to Ms Access splitting at delimiter I have a SharePoint list, employees go in and fill in information, then I export the list to Excel (in my company, Access and SharePoint don't play well with each other) and import it into Access to run reports. It's great, except for one column. Employees can work in multiple counties, so on SharePoint I have a look up column where they can select multiple counties...the problem is, when I export it to Excel it looks like this:
[County] Outagamie;#1
[County] Ashland;#35;#Bayfield;#66;#Douglas;#67;#Iron;#68
I only want the county names:
[County] Outagamie
[County] Ashland, Bayfield, Douglas, Iron
Again some employees may have one county, some could have 5 or 6. I know I can do a formula in excel, but I'm trying to make this easy on other people who will run this report, so I would like to just import the Excel file and run the reports based on queries.
For the love of God, you would think this would be an easy thing in an Access query, but when I research this, I only find ways to do it in Excel. There has to be a way to do it in Access.  Please Help...

A: Hummm, seems like Find/Replace would do the trick.

A: You can create a small helper function like this:
Public Function CleanString(ByVal Value As String) As String

    Dim Parts   As Variant
    Dim Part    As Integer
    Dim Result  As String

    Parts = Split(Value, ";#")
    For Part = LBound(Parts) To UBound(Parts)
        If Part Mod 2 = 0 Then
            If Result <> "" Then
                Result = Result & ", "
            End If
            Result = Result & Parts(Part)
        End If
    Next

    CleanString = Result

End Function


text:
Q: Transform DataFrame: place values in right columns as new rows I am analyzing a consumer survey and there are both Dutch (NL) and French (FR) respondents. Depending on the answer they gave when we asked about their mother language they got the same questionnaire but translated in Dutch or French. The problem is that the output of Qualtrics (the survey software) gave us the following output:

User_Language
Q1_NL
Q2_NL
...
Q1_FR
Q_FR
...

NL
1
3
...

...

NL
4
4
..

...

NL
1
3
...

...

NL
2
5
...

...

...
...
...
...
...
...
...

FR

...
3
2
...

FR

..
4
3
...

FR

...
2
5
...

FR

...
1
2
...

As you can see the answers for the Dutch-speaking participants were recorded in the first n columns, while the French answers were recorded in the following n columns.
How can I cut the French answers from the last n columns and append them on the bottom of the DataFrame as those are answers to the exact same questions?
Thanks!
EDIT: Solutions that make use of grouping by the strings "Q1" or "Q2" are unfortunately not viable as the column names are actually the questions, this was just an example value. I do know the exact range of the French answers and the Dutch answers.

A: If there aren't any overlapping values you could simply split the data frame into two data frames based on where the dutch values "stop" and the french "start" rename the value columns of those two data frames   Q2_NL and so on to simply Q2 ... and then concatenate those frames again into one.

A: IIUC, you can add a helper column, rename the columns to something common, and stack/unstack
(df
 .assign(index=df.groupby('User_Language').cumcount())
 .set_index(['User_Language', 'index'])
 .rename(columns=lambda c: c.split('_')[0])
 .stack().unstack()
 .droplevel('index').reset_index()
)

output:
  User_Language  Q1  Q2
0           FR   3   2
1           FR   4   3
2           FR   2   5
3           FR   1   2
4           NL   1   3
5           NL   4   4
6           NL   1   3
7           NL   2   5

A: One approach would be to group the dataframe along column axis and select the first  non null value per row
s = df.set_index('User_Language')
s.groupby(s.columns.str.split('_').str[0], axis=1).first()

              Q1 Q2
User_Language
NL             1  3
NL             4  4
NL             1  3
NL             2  5
FR             3  2
FR             4  3
FR             2  5
FR             1  2


text:
Q: Why bitwise-or doesn't result in a constant expression, but addition does In one of my C files, I'm declaring an array foo. Then I'm assigning the address of that variable to an integer type, and I want to bitmask it with 3 to set the lowest two bits. However, the bitmask fails during compiling but adding +3 seems to work. Why?
uint64_t foo[1];
uint64_t bar = (uint64_t)foo | 3;

This fails with:
main.c:6:16: error: initializer element is not constant
 uint64_t bar = (uint64_t)foo | 3;

But this works:
uint64_t foo[1];
uint64_t bar = (uint64_t)foo + 3;

As I understand it, the location of foo is not known at compile time because it's global (will be in the .data or .bss section). However, an entry is put into the relocation section so that the linker can patch the address in while linking.
How is it handling the the bitwise-or and the addition? Why does one work while the other doesn't?

A: Initial values for static objects must be constant expressions or string literals. (C 2018 6.7.9 3: "All the expressions in an initializer for an object that has static or thread storage duration shall be constant expressions or string literals.")
6.6 7 specifies forms of constant expressions for initializers:

More latitude is permitted for constant expressions in initializers. Such a constant expression shall be, or evaluate to, one of the following:
— an arithmetic constant expression,
— a null pointer constant,
— an address constant, or
— an address constant for a complete object type plus or minus an integer constant expression.

Consider uint64_t bar = (uint64_t)foo + 3;. foo is nominally the static array declared earlier, which is automatically converted to a pointer to its first element. This qualifies as an address constant (6.6 9: "An address constant is … a pointer to an lvalue designating an object of static storage duration,… However, it is cast to uint64_t, which no longer qualifies as an address constant, an address constant plus or minus a constant expression, or a null pointer constant.
Is it an arithmetic constant expression? 6.6 8 excludes it:

… Cast operators in an arithmetic constant expression shall only convert arithmetic types to arithmetic types,…

Thus, (uint64_t)foo + 3 does not qualify as any form of constant expression required by the C standard. However, 6.6 10 says:

An implementation may accept other forms of constant expressions.

So a C implementation may accept (uint64_t) foo + 3 or (uint64_t) foo | 3 as a constant expression. Our question is then why does your C implementation accept the former but not the latter.
A common feature of linkers and object module formats is that the object module can record placeholders for certain expressions, and the linkers can evaluate these expressions and replace the placeholders with calculated values. A primary purpose of this feature is to allow for code in a program to refer to places in data or other code whose locations are not completely known during compilation but that will be decided (at least relative to some base reference point) during linking.
Places in data or code are measured relative to symbols (names) defined in the object modules (or relative to the starts of sections or segments). Thus, a place may be described, in effect, as "34 bytes after the start of routine bar" or "8 bytes after the start of object baz". So the object module has support for placeholders that are composed of a displacement and a symbol name. After the linker assigns addresses to symbols, it reviews each placeholder, adds the displacement to the assigned address, and replaces the placeholder with the calculated result.
It appears your compiler, in spite of the uint64_t cast, is able to recognize that (uint64_t) foo is still the address of foo, and therefore (uint64_t) foo + 3 may be implemented by the regular use of one of these placeholders.
In contrast, the bitwise OR operator is not supported for use in these placeholders, and therefore the compiler is unable to implement (uint64_t) foo | 3. It cannot evaluate the expression itself (because it does not know the final address for foo), and it cannot write a placeholder for the expression. So it does not accept this as a constant expression.

A: When you say
sometype *p = f(x);

where p is a global variable (or one with static duration) and where f(x) is not an actual function call but rather, some sequence of compile-time operations involving the address of another symbol x which won't be known until link time, the compiler obviously can't compute the initial value immediately.  It actually emits an assembly language directive which causes the assembler to construct a relocation record which causes the linker to evaluate f(x) once the final location of the symbol x is known.
So f(x) (whatever sequence of operations it actually is) has to be, in effect, a function that the linker knows how to evaluate (and that there's a relocation record for, and if necessary an assembly language directive for).  And while conventional linkers are good at performing addition and subtraction (because they do it all the time), they don't necessarily know how to perform other kinds of arithmetic.
So in consequence of all this, there are some additional rules on what kinds of arithmetic you can do while constructing pointer constants.
I'm in a hurry this morning and don't have time to dig through the Standard, but I'm pretty sure there's a sentence in there somewhere stating that among other restrictions on constant expressions, when you're initializing a pointer, you're limited to an address plus or minus an integer constant expression (since that's all the C Standard is willing to assume the linker is going to know how to do).
Your question has the additional complication that you're not actually initializing a pointer variable, but rather, an integer.  In that case you get, in effect, the worst of both worlds: you're either not allowed to do it at all, or if the compiler lets you, the initializer on the right (since it involves an address/pointer), is limited to the kinds of arithmetic you can do while constructing pointer constants, as described above.  You don't get to do the arbitrary arithmetic you'd be able to get away with (perhaps with confounding casts) in an integer expression at run time.

A: According to the standard, the result of casting a pointer to an integer type is not a constant expression.  So both of your examples may be rejected by a conforming compiler.
However there is the clause C11 6.6/10:

An implementation may accept other forms of constant expressions.

which unfortunately means that any particular compiler could accept none, one, or both of your examples.