text:
Q: use same datasource from already started server I have configured jBoss 7.1.1 final for datasource and used it in spring by JNDI. Everything is working fine , datasource is up and JMS queue is setup. Now I have to run a batch which will fetch records from DB and put it in JMS(already started instance) . I have to use same datasource which is configured in server but the record fetching program is a normal java program and I am using same configuration as defined in my spring-servlet.xml
    <bean id="TransactionalDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiName" value="java:/comp/env/jdbc/FRMWRKPOC_DEV"></property>
    </bean>

  <!-- Hibernate Session Factory -->
  <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="TransactionalDataSource"/>
     <property name="packagesToScan">
            <list>
                <value>entities</value>
            </list>
        </property>
    <property name="hibernateProperties">
        <props>
            <prop key="dialect">org.hibernate.dialect.Oracle10gDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.connection.autocommit">false</prop>
            <prop key="hibernate.current_session_context_class">thread</prop>
        </props>

    </property>
  </bean>

The java code to get sessionFactory is as follows:
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
                SessionFactory factory  = (SessionFactory)context.getBean("sessionFactory");
                return factory;

But it is giving me following error:
javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial

If some kind of initial context setup is required then please guide me and also tell me is it possible to get the datasource instance if the application is not running on server though server is already started(because it is normal PSVM java code)
Please find below the complete stacktrace
 org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'NonTransactionalDataSource' defined in class path resource [beans.xml]: Invocation of init method failed; nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1482)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:610)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at com.rights.client.DBConnection.getSessionFactory(DBConnection.java:33)
    at com.rights.client.SwonToSubLocMapping.main(SwonToSubLocMapping.java:146)
Caused by: javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
    at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:645)
    at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:288)
    at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:325)
    at javax.naming.InitialContext.lookup(InitialContext.java:392)
    at org.springframework.jndi.JndiTemplate$1.doInContext(JndiTemplate.java:154)
    at org.springframework.jndi.JndiTemplate.execute(JndiTemplate.java:87)
    at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:152)
    at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:178)
    at org.springframework.jndi.JndiLocatorSupport.lookup(JndiLocatorSupport.java:95)
    at org.springframework.jndi.JndiObjectLocator.lookup(JndiObjectLocator.java:105)
    at org.springframework.jndi.JndiObjectFactoryBean.lookupWithFallback(JndiObjectFactoryBean.java:201)
    at org.springframework.jndi.JndiObjectFactoryBean.afterPropertiesSet(JndiObjectFactoryBean.java:187)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1541)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1479)
    ... 13 more

A: As you are using it as a normal Java program, you have to provide details to Spring on how to access the JNDI by providing required properties. For JBOSS you can declare it like this:
<bean id="TransactionalDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
   <property name="jndiName" value="java:/comp/env/jdbc/FRMWRKPOC_DEV"></property>
   <property name="jndiEnvironment">
      <props>
         <prop key="java.naming.factory.initial">org.jnp.interfaces.NamingContextFactory</prop>
      <prop key="java.naming.provider.url">localhost:1099</prop>
      <prop key="java.naming.factory.url.pkgs">org.jboss.naming:org.jnp.interfaces</prop>
      <props>
    </property>
</bean>

A: I would suggest to write simple java program or jsp to read from JNDI. It looks like you need to pass authentication (principal & credential) and authorization (I think its optional) inforamtion while conncting to JNDI.


text:
Q: Analogy between gravitational binding energy and the binding of Atoms When atoms bind together, their total energy is less than each individual's energy. When planets come together, their total energy is also less (i.e. nature of attractive force). The mass of each stays the same before and after the binding. However, their total energy decreases.

*

*Does this mean that when planets come together, their gravitational field will be reduced in comparison to when the two was still free? I know that it will increase since when two masses come together, then of course the field will increase.

*What I mean is, will it decrease compared to when each of them was free?
e.g. in atoms, their total energy decreases when the two atoms bind together

A: This is a sensible question and the answer is: yes it does.
Your scenario starts with two planets (or stars, or whatever) with masses $m_1,m_2$ some distance apart.   At some position a long way away there will be a gravitational field.
Then for some reason the planets get closer. Gravitational potential energy is converted into some other form which is then lost (maybe gravity waves, maybe tidal forces producing heat which is radiated).  They still have masses $m_1$ and $m_2$ (as defined by their inertia or their gravitational attraction) but the total system has a mass less than the sum of the components: $M=m_1+m_2-B/c^2$ where $B$ is the binding energy.  Just like nucleons in the nucleus.
A long way away the gravitational field will be due (once the binding energy gravitational waves or IR photons or whatever  have departed) to this total $M$, a little bit smaller than $m_1+m_2$.

A:
The mass of each stays the same before and after the binding.

Actually not. The best example for this is nuclear fusion. There is a measurable mass difference between the rest mass of a nucleus and the total rest mass of the protons and neutrons.
If I understand well, your question is about the equivalence of energy and mass.

I know it's a bit confusing, but in bound and free systems, the total mass is different. With gravity it's more complicated, as in classical physics the source of gravity is the mass its self. But also in the merging of two black holes there is a mass difference, what is radiated away with gravitational waves (mostly). (I'm not sure if they can measure the mass difference directly, though.) Although in most (types of) processes the mass difference is usually negligable/unmeasurable.
These articles explain this whole stuff in more details:

*

*Nuclear binding energy

*Mass–energy equivalence

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why are all of my Airflow dags one run behind? I'm setting up Airflow right now and loving it, except for the fact that my dags are perpetually running behind. See the picture below - this was taken on 2/19 at 15:50 UTC, and you can see that for each of the dags, they should have run exactly one more time between the last time they ran and the present time (there are a couple for which this is not true - those ones are currently turned off). Is there some piece of configuration I missed?

A: False alarm! Airflow just labels execution times differently than how I expected. Turns out an hourly job that runs at 15:00 is labels "14:00" and includes data up to 14:00+1:00.
From https://airflow.apache.org/scheduler.html:

Note that if you run a DAG on a schedule_interval of one day, the run stamped 2016-01-01 will be trigger soon after 2016-01-01T23:59. In other words, the job instance is started once the period it covers has ended.
Let's Repeat That The scheduler runs your job one schedule_interval AFTER the start date, at the END of the period.

A: Execution time is the lower bound of the batch.
Ex:
Say your execution schedule is hourly and its the run corresponding to the 13:00 schedule.
Your execution_time will be 12:00.
This is because we usually run the batch for 12:00 - 13:00 at 13:00(after the data is available for the batch).
But in my experience, we sometimes use the schedule based on the time its scheduled for(because we want the schedule to start and there are checks inside of the DAG/job that verify data readiness). In those cases, I just end up using next_execution_time(13:00) instead of execution_time(12:00).


text:
Q: Skip json elements deserialization on condition have the following problem. There is a bunch of quite large json objects which I need to have as objects. But there are conditions, when I actually don't need some of them, for example, if one of inner fields is "isDeleted:true". For now I have to first automatically through JsonConvert.DeserializeObject<..>(stringJson) all the array of data and then choose in filter necessary. What I'd like to achieve is to skip some whole elements when condition isn't true. Are there any ways to achieve this beside manual conversion?
UPDATE:
json looks something like this:
{
  results:[
     around 20 fields here with inner objects,
     isDeleted:"true",
     user:{
        another dozen of fields
     },
     images:[{..},{..}]
 ]}

A: According to the docs, JsonReader:

Represents a reader that provides fast, non-cached, forward-only access to serialized JSON data.

Thus, in order to skip deleted items when deserializing a collection, you're going to need to read the JSON for each collection entry into memory somehow in order to check the isDeleted property.  If your collection item class is so heavy that you don't want to create one when not absolutely required, you could use a custom JsonConverter to load each entry into a JObject container, then check that for  isDeleted:
public class DeletetedItemSkippingCollectionConverter<T> : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(List<T>);
    }

    public override bool CanWrite { get { return false; } }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var list = (existingValue as List<T>);
        if (list == null)
            list = new List<T>();
        if (reader.TokenType != JsonToken.StartArray)
            return list;
        while (reader.Read())
        {
            if (reader.TokenType == JsonToken.EndArray)
                break;
            var obj = JObject.Load(reader);
            var deleted = obj["isDeleted"];
            if (deleted != null)
            {
                if (deleted.Type == JTokenType.Boolean && (bool)deleted)
                    continue;
            }
            if (obj != null)
            {
                list.Add((T)obj.ToObject<T>(serializer));
            }
        }
        return list;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

Then apply that to any List<T> property you want to filter:
[DataContract]
public class RootObject
{
    public RootObject()
    {
        this.ResultList = new List<Item>();
    }

    [DataMember(Name="results")]
    [JsonConverter(typeof(DeletetedItemSkippingCollectionConverter<Item>))]
    public List<Item> ResultList { get; set; }
}

Alternatively, you could load each item in the collection into its "final" representation, check it for being deleted, and dispose of it if so.  Assuming your objects all implement an interface IsDeleted, you could do:
public interface IIsDeleted
{
    bool IsDeleted { get; }  // Corresponds it "isDeleted" property in the JSON.
}

public class IsDeletetedItemSkippingCollectionConverter<T> : JsonConverter where T : IIsDeleted
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(List<T>);
    }

    public override bool CanWrite { get { return false; } }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var list = (existingValue as List<T>);
        if (list == null)
            list = new List<T>();
        if (reader.TokenType != JsonToken.StartArray)
            return list;
        while (reader.Read())
        {
            if (reader.TokenType == JsonToken.EndArray)
                break;
            var obj = serializer.Deserialize<T>(reader);
            if (obj == null || obj.IsDeleted)
            {
                var disposable = obj as IDisposable;
                if (disposable != null)
                    disposable.Dispose();
                continue;
            }
            list.Add(obj);
        }
        return list;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}


text:
Q: What is the difference between Comparable and operator compareTo? Lets say I have class A(val foo: Double).
I want to be be able to compare it to other A, Double, and Int.
If I implement Comparable, I can only compare it against one other object type.
override fun compareTo(other: A): Int {
        return when {
            this.foo == other.foo -> 0
            this.foo > other.foo -> 1
            else -> -1
        }
    }

But I've also seen extension functions overriding the compareTo operator.
operator fun A.compareTo(d: Double): Int {
    return when {
        this.foo == d -> 0
        this.foo > d -> 1
        else -> -1
    }
}

What is the difference between these and what should I be using? I'm guessing if I want to compare it to multiple types then I have to use extension functions?

A: The Comparable interface comes from Java, and, as you have seen, is defined with only a compareTo( other) method, which only provides for comparing an object to another object of the same type.
As you have also noticed, the Kotlin extension functions are additional functions allowing you to compare an object to whatever you want, as long as you define the compareTo method to take an argument of the type to which you want to compare.
So, yes, if you want to compare an object to an object of a different type, you will need to write an appropriate extension function.
Of course, in Java, if you have control of the source code of the class, you can always add a custom compareTo method.

A: Wenn you make your own objects you must implement Comparable interface and then override compareTo function
class MyClass : Comparable<MyClass> {

   override fun compareTo(other: MyClass): Int {
      // TODO Returns zero if this object is equal to the specified other object
   }

}

You can also override an operator function, for example from Int class in kotlin
fun main(args: Array<String>) {
   val a = 1
   val b = "2"
   println(a.compareTo(b))
}

operator fun Int.compareTo(i: String) : Int {
   return if (this.toString() == i) {
      0
   } else {
      1
   }
}

I hope that's helpfull from you

A: Comparable is a standard interface, it's the way you define a class as having some ordering, and every library that deals with ordering works with Comparable types. Basically, if you want to be able to order and compare your things using all the standard functions and anything anyone else might write, you need to implement the Comparable interface.
This works:
data class SportsTeam(val name: String) : Comparable<SportsTeam> {
    override fun compareTo(other: SportsTeam): Int = when {
        name == "best team" -> 1
        other.name == "best team" -> -1
        else -> 0
    }
}

fun main(args: Array<String>) {
    val best = SportsTeam("best team")
    val worst = SportsTeam("worst team")
    print("The winner is: ${maxOf(best, worst).name}")
}

but because maxOf takes a Comparable type, this won't work:
data class SportsTeam(val name: String)

fun SportsTeam.compareTo(other: SportsTeam): Int = when {
    name == "best team" -> 1
    other.name == "best team" -> -1
    else -> 0
}

fun main(args: Array<String>) {
    val best = SportsTeam("best team")
    val worst = SportsTeam("worst team")
    print("The winner is: ${maxOf(best, worst).name}")
}


text:
Q: How can I keep alive my FTP connection (over curlftpfs)? I have curlftpfs on my Ubuntu 12.10 laptop, but my wifi router is bad and drops FTP connections after 30 seconds of inactivity. Is there a keep-alive setting with curlftpfs or if not are there any other options? I have tried the built in connect to server gui, but your server disappears after reboot. SSHFS is no good either, I need to mount to a particular directory (the server is my web host), otherwise it's a pain to find my content. Google hasn't yielded any answers either.

A: You could create a bash script that does a loop and sleeps for 10 seconds, after that it should run touch /mnt/ftp/tmp and then rm /mnt/ftp/tmp.
#!/bin/bash
while [ "true" ]
do
  touch /mnt/ftp/tmp
  rm /mnt/ftp/tmp
  sleep 10
done


text:
Q: Text Documents Image Alignment I am trying different image alignment approaches to align the images containing texts using Computer Vision. I have tested following image alignment approaches:

*

*Probabilistic Houghlines Transform to align images according to the detected lines. https://medium.com/p/97b61eeffb20 is my implementation. But that didn't help me as expected.

*Implemented SIFT and ORB to detect and align images according to the template image but instead of aligning all images, it distorts the image sometimes. I have used https://pyimagesearch.com/2020/08/31/image-alignment-and-registration-with-opencv/ as a reference.

*Edge detection followed contour detection, corner detection and perspective transformation. But it doesn't work with images having different background types. This is the reference example https://pyimagesearch.com/2014/09/01/build-kick-ass-mobile-document-scanner-just-5-minutes/

*morphology followed by contour detection and masking. Reference Crop exactly document paper from image

*Trained the YOLO(You only look once) object detector to detect the documents but it detects the bounding box, my requirement is Quardilaterl with four image corners from which I can align documents using perspective transform.

*Calculating the skewness and deskewing. Reference: https://github.com/sbrunner/deskew
But I couldn't align the document(identity documents such as citizenship, passport, license etc) images with different backgrounds perfectly using the above approaches.
This is a sample test image(important information are hidden due to privacy issue).

Is there are any other approaches of image alignment which can align the document images perfectly by correcting the skewness of the available text. My main focus is to extract the information form document using OCR preserving the information sequence in the document image.
Thank you!

A: To me, the third approach seems to be the most promising. But as you said, a cluttered background is a problem. Two ideas came to me about this:

*

*Implementing a GUI as a fallback solution, so the user could select the contour.

*Render some artificial dataset of official documents against a cluttered background and train a CNN to predict a segmentation map of the document. This map could be used then, as an initialization for the edge detection / contour detection. This answer contains two links to databases of images of official documents. Maybe these are of some use for you.


text:
Q: How can I find the depth of a specific node inside a binary tree? I'm trying to figure out a recursive solution to this problem. The main thing is to return the level in the binary tree where the node is.
def find_depth(tree, node):
    if node == None:
        return 0
    else:
        return max(find_depth(tree.left))
        #recursive solution here

Using this class for the values:
class Tree:
    def __init__(self, value, left=None, right=None):
        self.value = value
        self.left  = left
        self.right = right

Example: Calling find_depth(tree, 7) should return the level where 7 is in the tree. (level 2)
   3
  / \
  7  1  <------ return that 7 is at level 2
 / \
 9 3

A: maybe this is what you are looking for
    def find_depth(tree, node):
        if node is None or tree is None:
            return 0

        if tree == node:
            return 1

        left = find_depth(tree.left, node)
        if left != 0:
            return 1 + left
        right = find_depth(tree.right, node)
        if right != 0:
            return 1 + right

        return 0

A: You need to provide information about depth in find_depth call. It might look like this (assuming 0 is a sentinel informing that node is not found):
def find_depth(tree, node, depth=1):
    if node == None:
        return 0

    if tree.value == node:
        return depth

    left_depth = find_depth(tree.left, node, depth+1)
    right_depth = find_depth(tree.right, node, depth+1)
    return max(left_depth, right_depth)

Then you call it with two parameters: x = find_depth(tree, 7).

A: Recursion is a functional heritage and so using it with functional style yields the best results -

*

*base case: if the input tree is empty, we cannot search, return None result

*inductive, the input tree is not empty. if tree.data matches the search value, return the current depth, d

*inductive, the input tree is not empty and tree.data does not match. return the recursive result of tree.left or the recursive result of find.right
def find (t = None, value = None, d = 1):
  if not t:
    return None              # 1
  elif t.value == value:
    return d                 # 2
  else:
    return find(t.left, value, d + 1) or find(t.right, value, d + 1) # 3

class tree:
  def __init__(self, value, left = None, right = None):
    self.value = value
    self.left = left
    self.right = right

t = tree \
  ( 3
  , tree(7, tree(9), tree(3))
  , tree(1)
  )

print(find(t, 7)) # 2
print(find(t, 99)) # None

You can implement the find method in your tree class too
def find (t = None, value = None, d = 1):
  # ...

class tree
  def __init__ #...

  def find(self, value)
    return find(self, value)

print(t.find(7)) # 2
print(t.find(99)) # None


text:
Q: $Y \subset X$ where $X$ and $Y$ are connected but $X-Y$ is separated by $A$ and $B$ It is known that $Y \cup A$ and $Y \cup B$ are connected given that $X$ is a connected space, $Y$ is a connected subspace of $X$, and that $X-Y$ is separated by $A$ and $B$. Is it true that $A$ and $B$ are connected as well?

A: No, this is false. Let $X \subset \Bbb{R}^2 $ be the union of two closed discs $D_1, D_2$ whose boundaries intersect in a single point $p$. Let $L$ be the line connecting $p$ to the centers of both discs, and $Y = X \cap L$. If you let $A = D_1 /Y$, $B = D_2/Y$ then $Y$, $Y \cup A$ and $Y \cup B$ are all connected and $X/Y$ is separated by $A$ and $B$, but both $A$ and $B$ are not connected.


text:
Q: Why does my jquery take so long when animating on scroll? I have a box that slides right 100px when you scroll 10px and slide back to it's default location if the scroll is less than 10px. The box does animate, however, there is a bit of a delay when it does. Can anyone help me figure this out?
HTML

CSS
#nest {
  width: 95%;
  max-width: 1000px;
  margin: auto;
  background-color: orange;
  height: 1000px;
  padding-top: 150px
}

#box {
  margin: 50px 0px 0px 0px;
  width: 100px;
  height: 100px;
  position:relative;
  background-color: green;
}

jQuery
jQuery(window).scroll(function() {
  if (jQuery(this).scrollTop() > 10) {
    jQuery('#box').animate({left:'100px'})

  } else {
    jQuery('#box').animate({left:'0px'})
}
});

My JSFIDDLE LINK
https://jsfiddle.net/ispykenny/m6ffj83g/1/
thanks in advance for your time and help!

A: The reason your animation is taking so long would be that the animate is running on every scroll event past 10px, and this is quite intensive on the client-side. There are a few options, either experiment with the .stop() functionality in jQuery, or write a a conditional if statement that checks if the animation will have started and only fires if it hasn't.
https://api.jquery.com/stop/
this is a handy resource.
var coin = false;

jQuery(window).scroll(function() {
  if (jQuery(this).scrollTop() > 10 && coin === false) {
    jQuery('#box').animate({left:'100px'});
    coin = true;
  } else if (coin === true && jQuery(this).scrollTop() <= 10) {
    jQuery('#box').animate({left:'0px'});
    coin = false;
}
});

try this!


text:
Q: UPSERT Partial JSON I am trying to add a feature by which I can update all records from a JSON payload, but the insert should only occur for those which have "archived" value = False.
below is a sample JSON. My batch job currently adds all records ,both for archived = true and false.
How ever , I would like false records to be added and existing records to get updated and even change from false to true.
But for any insert with archived = true , should not get added to SF.
I tried the trigger (after insert) approach to check for archived = true , but that bombed because as soon as SF found one record which matches the criteria (record 1 .. payload below), it prevented that insert , but even stopped update of sister roots (record 2) from the same payload.
Checking the archived condition in the controller class also worked for insert, but it won't update existing records from the same payload.
{
   "content":[
      {
         "record":1,
         "number":12345,
         "archived":"True"
      },
      {
         "record":2,
         "number":54321,
         "archived":"False"
      }
   ]
}

A: Okay team.
I finally found a way.
I did add try the scenario with a validation rule, but it did not work, as all other changes were rolled back, when one entry had archived =true.
So instead I queried all the existing records using SOQL.
Map<Decimal, List<sObject>> existingMap = GroupBy.decimals('primary_key', [SELECT Id, primary_key,Order_Id__c FROM sObject WHERE primary_key IN :parent_object_list]);

And used an if-condition to check all incoming records for boolean condition (archived == True) and use primary key to check for existing records.
If primary_key exists, I am updating the record.
If not and boolean flag is true, I am rejecting insertion.
if(list.Archived__c == True && existingMap.containsKey(list.primary_key) == False)
  {
    errors.add('Archived record insertion is rejected: ' + list.primary_key);
    recordsToIgnore.add(counter_value);
  }

In this way, all updates are successful, even when an entry is archived , while all archived insertions are rejected.
Thank you all for your input.


text:
Q: XAML SVG color change at runtime We have a set of SVGs stored within a resource dictionary.
Example:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <DrawingImage x:Key="Bell">
        <DrawingImage.Drawing>
            <DrawingGroup Opacity="1">
                <DrawingGroup.Children>
                    <DrawingGroup Opacity="1">
                        <DrawingGroup.Children>
                            <DrawingGroup Opacity="1">
                                <DrawingGroup.Children>
                                    <GeometryDrawing Brush="#FF000000" Pen="{x:Null}">
                                        <GeometryDrawing.Geometry>
                                            <PathGeometry FillRule="Nonzero" Figures="........." />
                                        </GeometryDrawing.Geometry>
                                    </GeometryDrawing>
                                </DrawingGroup.Children>
                            </DrawingGroup>
                        </DrawingGroup.Children>
                    </DrawingGroup>
                </DrawingGroup.Children>
            </DrawingGroup>
        </DrawingImage.Drawing>
    </DrawingImage>
</ResourceDictionary>

If you noticed the GeometryDrawing Brush is set to #ff000000 (black).
The problem we face is allowing a view to display this SVG and assign the color at runtime (via binding)
Our Window (view) has the Resource Dictionary with the icons inside of the Window.Resources.
We are looking for a solution like so:
<Image Source="{StaticResource Bell}" Fill="#FF884422"/>

A: Have a look at this tool:
https://github.com/BerndK/SvgToXaml
It can convert all svg's automatically to one xaml. The colors are separated and can be set for all images at once or just for a single image. Sample code for changing colors during runtime is included.
The tool is also a svg browser, viewer ...

A: By building on top of Paolo's non-working answer, I was able to solve this.
The "MyImage" class:
Public Class MyImage
    Inherits System.Windows.Controls.Image

    Public Property Color As System.Windows.Media.SolidColorBrush

End Class

Inside the resource dictionary, assign the DrawingImage to the Source setter of a MyImage style:
<Style TargetType="{x:Type local:MyImage}" x:Key="Bell">
        <Setter Property="Source">
            <Setter.Value>
                <DrawingImage>
                    <DrawingImage.Drawing>
                        <DrawingGroup Opacity="1">
                            <DrawingGroup.Children>
                                <DrawingGroup Opacity="1">
                                    <DrawingGroup.Children>
                                        <DrawingGroup Opacity="1">
                                            <DrawingGroup.Children>
                                                <GeometryDrawing
                                                    Brush="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:MyImage}}, Path=Color}"
                                                    Pen="{x:Null}" />
                                            </DrawingGroup.Children>
                                        </DrawingGroup>
                                    </DrawingGroup.Children>
                                </DrawingGroup>
                            </DrawingGroup.Children>
                        </DrawingGroup>
                    </DrawingImage.Drawing>
                </DrawingImage>
            </Setter.Value>
        </Setter>
</Style>

Inside the window's XAML file:
<Window
    ...
    xmlns:local="clr-namespace:AppNameHere">
    <Window.Resources>
        <ResourceDictionary Source="DictionaryName.xaml" />
    </Window.Resources>
    ....
    <Grid Background="Black">
        <local:MyImage Color="Chartreuse" Width="30" Height="30" Style="{StaticResource Bell}" />
    </Grid>
    ...
</Window>

Here's the result: http://i.stack.imgur.com/7JNyH.png

A: <Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication1"
    Title="MainWindow" Height="350" Width="525" >
<Window.Resources>
    <DrawingImage x:Key="Bell1">
        <DrawingImage.Drawing>
            <DrawingGroup Opacity="1">
                <DrawingGroup Opacity="1">
                    <DrawingGroup Opacity="1">
                        <GeometryDrawing  Brush="{Binding Color}" Pen="{x:Null}">
                            <GeometryDrawing.Geometry>
                                <PathGeometry FillRule="Nonzero"  Figures="M 10,100 C 10,300 300,-200 300,100" />
                            </GeometryDrawing.Geometry>
                        </GeometryDrawing>
                    </DrawingGroup>
                </DrawingGroup>
            </DrawingGroup>
        </DrawingImage.Drawing>
    </DrawingImage>
</Window.Resources>
<Grid>
    <local:MyImage DataContext="{Binding ElementName=myImage, Mode=OneWay}" x:Name="myImage"  Color="Red" Source="{StaticResource Bell1}" ></local:MyImage>

</Grid>

A: The DrawingImage will receive the same datacontext as the window, so you can bind the color to a property on the window's view model.
Dictionary1.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <DrawingImage x:Key="Bell">
        <DrawingImage.Drawing>
            <DrawingGroup Opacity="1">
                <DrawingGroup.Children>
                    <DrawingGroup Opacity="1">
                        <DrawingGroup.Children>
                            <DrawingGroup Opacity="1">
                                <DrawingGroup.Children>
                                    <GeometryDrawing Brush="{Binding IconColor}" Pen="{x:Null}">
                                        <GeometryDrawing.Geometry>
                                            <PathGeometry FillRule="Nonzero" Figures="........." />
                                        </GeometryDrawing.Geometry>
                                    </GeometryDrawing>
                                </DrawingGroup.Children>
                            </DrawingGroup>
                        </DrawingGroup.Children>
                    </DrawingGroup>
                </DrawingGroup.Children>
            </DrawingGroup>
        </DrawingImage.Drawing>
    </DrawingImage>
</ResourceDictionary>

MyTestWindow.xaml
<Window x:Class="MyTestWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Window.Resources>
        <ResourceDictionary Source="Dictionary1.xaml" />
    </Window.Resources>
    <Grid>
        <Image Source="{StaticResource Bell}" />
    </Grid>
</Window>

Then the view model will need an IconColor property.


text:
Q: How to create multi column drop-down using React Js? I want to create a multicolumn dropdown where I can display the name and its description in a single row.
But When I will select the dropdown list it should display column 1 value as the selected value.  Please refer to the attached Image. And I am clueless about where to start.

A: Since you have used react as a tag, a simple solution using React can be:-
list = [{country:"India",description:"Great"},{country:"USA",description:"Great"}]
const [selectedCountry,setCountry] =useState(null)
<DropDown>
    <DropDownHeading>
    {selectedCountry?selectedCountry:Choose Country}
    </DropDownHeading>

    <DropDownMenu>
    list.map(listItem=><DropDownItem listItem={listItem} onClick={()=>setCountry(listItem.country)}/>)
    </DropDownMenu>
    </DropDown>

Your DropDownItem's JSX can be :-

{country}

{description}

A: we achieved this using fluent UI customization dropdown.
 import * as React from 'react';
   import { Dropdown, Stack } from 'office-ui-fabric-react';
    import _ from 'lodash';

const onRenderOption = item => {
  return (

          {item.text}

            {_.get(item, 'description', '').length > 60
              ? `${item.description.substring(0, 55)}...`
              : item.description}

  );
};

export const MultiComboBox = props => (
  <Stack style={{ paddingTop: 16 }}>
    <Dropdown
      title={props.title}
      placeholder="any"
      label={props.label}
      options={props.options}
      selectedKey={props.value}
      dropdownWidth={600}
      onRenderLabel={props.selectedValue}
      onChange={(action, item) => props.onChange(item)}
      onRenderOption={onRenderOption}
    />
  </Stack>
);


text:
Q: Flask - Can't get Facebook APP ID after changing project structure I am creating a Facebook app in Flask. As this is a microframework I started simple from the tutorials and had everything in 2 files: app.py and conf.py (and others like /templates).
In the basic structure (generated mostly by heroku) it was like this:
/game
     game.py
     conf.py

app.py
FB_APP_ID = os.environ.get('FACEBOOK_APP_ID')
FB_APP_SECRET = os.environ.get('FACEBOOK_SECRET')

requests = requests.session()
app_url = 'https://graph.facebook.com/{0}'.format(FB_APP_ID)
FB_APP_NAME = json.loads(requests.get(app_url).content).get('name')
FB_APP_LOGO = json.loads(requests.get(app_url).content).get('logo_url')

app = Flask(__name__)
app.config.from_object(__name__)
app.config.from_object('conf.Config')

@app.route('/channel.html', methods=['GET', 'POST'])
def get_channel():
    return render_template('channel.html')

@app.route('/')
def index():
    return 'index'+str(FB_APP_ID)

if __name__ == '__main__':
    port = int(os.environ.get("PORT", 5000))
    print requests.headers
    if app.config.get('FB_APP_ID') and app.config.get('FB_APP_SECRET'):
        app.run(host='0.0.0.0', port=port)
    else:
        print 'Cannot start application without Facebook App Id and Secret set'

conf.py
import os

class Config(object):
    DEBUG = True
    TESTING = False
    LOG_LEVEL = os.environ.get('LOG_LEVEL', 'DEBUG')
    FBAPI_APP_ID = os.environ.get('FACEBOOK_APP_ID')
    FBAPI_APP_SECRET = os.environ.get('FACEBOOK_SECRET')
    FBAPI_SCOPE = ['user_likes', 'user_photos', 'user_photo_video_tags']

I wanted to make it perfect MVC so I used this link and the problem started.
/game
    conf.py
    runserver.py
    /game
        /templates
        /static
        __init__.py
        views.py
        models.py

runserver.py
import os
from game import app

if __name__ == '__main__':
    port = int(os.environ.get("PORT", 5000))
   # print requests.headers
    if app.config.get('FB_APP_ID') and app.config.get('FB_APP_SECRET'):
        app.run(host='0.0.0.0', port=port)
    else:
        print 'Cannot start application without Facebook App Id and Secret set'

__init__.py
from flask import Flask
import os,  requests, json

SCRIPTS='static/scripts/'

FB_APP_ID = os.environ.get('FACEBOOK_APP_ID')
FB_APP_SECRET = os.environ.get('FACEBOOK_SECRET')

requests = requests.session()
app_url = 'https://graph.facebook.com/{0}'.format(FB_APP_ID)
FB_APP_NAME = json.loads(requests.get(app_url).content).get('name')
FB_APP_LOGO = json.loads(requests.get(app_url).content).get('logo_url')

app = Flask(__name__)
app.config.from_object(__name__)
app.config.from_object('conf.Config')

import game.views
import game.models

conf.py stays the same and index view is in views.
THE PROBLEM: In the first structure (simple) os.environ got all the FB_APP_ID and FB_APP_SECRET just fine, and I could do with the data whatever I want.
Now (in the MVC) it just does not fetch the variables and what I have there is "None".
I have tried to put the __init__ == __main__ wherever I could but nothing really worked.
The conf.py has all the data put there in the beginning (like DEBUG=TRUE or LOG LEVEL). It's just the fb data that I don't get.

A: You need to set FACEBOOK_APP_ID and FACEBOOK_SECRET in your environment
Say your virtual environment is named venv
create a file called .venv in the project root (same directory that has requirements.txt, Procfile, .gitignore, etc)
add put this into the file and save:
FACEBOOK_APP_ID=1234...
FACEBOOK_SECRET=ABCD...

your FACEBOOK_APP_ID and FACEBOOK_SECRET are found by going to the basic settings of your app on developers.facebook.com


text:
Q: Error display where generate singed APK from android studio Lint found fatal errors while assembling a release target.
To proceed, either fix the issues identified by lint, or modify your build script as follows:
android {
    lintOptions {
        checkReleaseBuilds false
        // Or, if you prefer, you can continue to check for errors in release builds,
        // but continue the build even when errors are found:
        abortOnError false
    }
}

A: change on build.gradle file inside android {} like below
    android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.xxx"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-
           rules.pro'
        }
    }
    lintOptions {
        checkReleaseBuilds false
        abortOnError false
    }

}


text:
Q: auto-resize a XIB file to be as the screen size I have a View Controller which has a scrollView embedded inside. In this Scroll view I have adding 4 views which are XIB file views. The XIB files size are 'Inferred' although appear to be iphone5 sizing. When loaded they are not auto-resizing to be the size of the screen, they are staying at iphone5 size.
How can I make the XIB file be the same size as the screen it is loading into?
EDIT:
I have also tried changing the the size of the nib files through the code like this:
 // 1) Create the three views used in the swipe container view
        let AVc :AViewController =  AViewController(nibName: "AViewController", bundle: nil);
        let BVc :BViewController =  BViewController(nibName: "BViewController", bundle: nil);
        let CVc :CViewController =  CViewController(nibName: "CViewController", bundle: nil);
        let DVc :DViewController =  DViewController(nibName: "DViewController", bundle: nil);

        AVc.view.frame = CGRectMake(0 , 0, self.view.frame.width, self.view.frame.height)
        BVc.view.frame = CGRectMake(0 , 0, self.view.frame.width, self.view.frame.height)
        CVc.view.frame = CGRectMake(0 , 0, self.view.frame.width, self.view.frame.height)
        DVc.view.frame = CGRectMake(0 , 0, self.view.frame.width, self.view.frame.height)

        // 2) Add in each view to the container view hierarchy
        //    Add them in opposite order since the view hieracrhy is a stack

        self.addChildViewController(DVc);
        self.scrollView!.addSubview(DVc.view);
        DVc.didMoveToParentViewController(self);

        self.addChildViewController(CVc);
        self.scrollView!.addSubview(CVc.view);
        CVc.didMoveToParentViewController(self);

        self.addChildViewController(BVc);
        self.scrollView!.addSubview(BVc.view);
        BVc.didMoveToParentViewController(self);

        self.addChildViewController(AVc);
        self.scrollView!.addSubview(AVc.view);
        AVc.didMoveToParentViewController(self);

This still has no affect and it loads the wrong size.

A: I suggest you to use size classes  and then apply the necessary constants at first it'll be a little difficult but by time you'll learn how to apply the size classes and constants.
Here are the links where you'll find the best examples.

A: If you are not using Auto-Layout then you can add the four views simply by for loop:
let bounds = UIScreen.mainScreen().bounds
let width = bounds.size.width
let height = bounds.size.height

var yAxis: CGFloat = 0.0

for i in 0...3 {
   let rect: CGRect = CGRectMake(0, yAxis, width, height)

   swift i {
       case 0:
          view1.frame = rect
       case 1:
          view2.frame = rect
       case 2:
          view3.frame = rect
       case 3:
          view4.frame = rect
       default:
          break
   }

   yAxis = yAxis + height
}

Where view1, view2, view3 and view4 are your 4 xib views.
Also, set the content size of the scroll view to height yAxis.
Recommended, You should use AutoLayout it will reduce the lines of code.


text:
Q: Uncover sentence intersections in a corpus with NLTK I have a corpus of documents and I'm trying to uncover instances in which complete and exact sentences appear across the corpus, possibly with NLTK or some other method in Python.
For example, suppose the corpus consists of ten text files and one or many of the files contain the sentence: the cat sat on the mat. How would I go about identifying matches of that sentence across the corpus?
Something I've tried is to split the files into one sentence per line using a very clunky regex and then used set to find the intersection between two texts. This works, but isn't scaleable to big corpus.
Is anyone aware of a scaleable and more robust approach to this task in Python?


text:
Q: R - How to preserve data types and titles when converting list of lists to data frame I'm working with a list receipts of lists. Each entry in receipts contains a list representing a receipt. The structure of a receipt is consistent and looks like this.
> str(receipts[[1]])
List of 6
 $ receipt_type  : chr "SALESPERSON_ACTIVITY"
 $ timestamp     : POSIXct[1:1], format: "2020-01-01 09:29:00"
 $ receipt_number: int 1195
 $ POS           : int 1
 $ KNo           : int 12
 $ shift_number  : int 9

The receipt_number may contain NA values as well.
I'd like to convert this list into a data frame with corresponding columns (receipt_type, timestamp, receipt_number, etc..). Currently I'm using this
receipts_as_df <- as.data.frame(matrix(unlist(receipts), byrow=TRUE, ncol=length(receipts[[1]])))

This puts the data into a data frame. Sadly the unlist removes all information about the types of the data (I think everything is coerced to character). Furthermore the column names get lost as well. Thus, I have a data frame with all the data, but the types and column-names are lost.
I know that I could rename the columns and datatypes manually, but was wondering whether there is a more comfortable way of handling this situation.
Example: Currently the data frame looks like this
> head(receipts_as_df)
                        V1         V2   V3 V4 V5 V6
1     SALESPERSON_ACTIVITY 1577867340 1195  1 12  9
2 CASH_REGISTER_MONITORING 1577867340 <NA>  1 12  9
3      PAYOUT_NOTIFICATION 1577867340 1196  1 12  9
4             TSE_ACTIVITY 1577869080 <NA>  1 12  9
5   BUSINESS_MODE_ACTIVITY 1577869080 <NA>  1 12  9
6             ZERO_RECEIPT 1577869140 1197  1 12  9

A: Base R, a little more work needed:
receipts <- replicate(3, list(
  receipt_type   = "SALESPERSON_ACTIVITY",
  timestamp      = as.POSIXct("2020-01-01 09:29:00", tz = "UTC"),
  receipt_number = 1195,
  POS            = 1,
  KNo            = 12,
  shift_number   = 9
), simplify = FALSE)

out <- do.call(rbind.data.frame, c(receipts, list(stringsAsFactors = FALSE)))
out
#            receipt_type  timestamp receipt_number POS KNo shift_number
# 2  SALESPERSON_ACTIVITY 1577870940           1195   1  12            9
# 21 SALESPERSON_ACTIVITY 1577870940           1195   1  12            9
# 3  SALESPERSON_ACTIVITY 1577870940           1195   1  12            9
str(out)
# 'data.frame': 3 obs. of  6 variables:
#  $ receipt_type  : chr  "SALESPERSON_ACTIVITY" "SALESPERSON_ACTIVITY" "SALESPERSON_ACTIVITY"
#  $ timestamp     : num  1.58e+09 1.58e+09 1.58e+09
#  $ receipt_number: num  1195 1195 1195
#  $ POS           : num  1 1 1
#  $ KNo           : num  12 12 12
#  $ shift_number  : num  9 9 9
out$timestamp <- as.POSIXct(out$timestamp, origin = "1970-01-01")
out
#            receipt_type           timestamp receipt_number POS KNo shift_number
# 2  SALESPERSON_ACTIVITY 2020-01-01 01:29:00           1195   1  12            9
# 21 SALESPERSON_ACTIVITY 2020-01-01 01:29:00           1195   1  12            9
# 3  SALESPERSON_ACTIVITY 2020-01-01 01:29:00           1195   1  12            9

dplyr and data.table without extra work needed:
dplyr::bind_rows(receipts)
# # A tibble: 3 x 6
#   receipt_type         timestamp           receipt_number   POS   KNo shift_number
#   <chr>                <dttm>                       <dbl> <dbl> <dbl>        <dbl>
# 1 SALESPERSON_ACTIVITY 2020-01-01 09:29:00           1195     1    12            9
# 2 SALESPERSON_ACTIVITY 2020-01-01 09:29:00           1195     1    12            9
# 3 SALESPERSON_ACTIVITY 2020-01-01 09:29:00           1195     1    12            9
data.table::rbindlist(receipts)
#            receipt_type           timestamp receipt_number POS KNo shift_number
# 1: SALESPERSON_ACTIVITY 2020-01-01 09:29:00           1195   1  12            9
# 2: SALESPERSON_ACTIVITY 2020-01-01 09:29:00           1195   1  12            9
# 3: SALESPERSON_ACTIVITY 2020-01-01 09:29:00           1195   1  12            9


text:
Q: absolute div inside absolute div cuts off with respect to relative position I have 3 divs on top of each other having following css.
.d1 {
    position: relative;
    background-color: yellow;
    height: 50px;
    width: 100px;
    overflow: hidden;
}

.d2 {
    position: absolute;
    background-color: green;
    height: 25px;
    width: 50px;
}

.d3 {
    position: absolute;
    left: 83px;
}

and the divs that have classes are as follows:

text

and as a result I see content of d3 cut off because of overflow:hidden in d1.

How can I avoid cut off content of d3 without modifying d1?

A: Getting around the overflow..
An element can overflow from a relative or absolute positioned parent by setting its position to fixed. An element that has position: fixed will have the default left,right,top, and bottom styles set as auto. This will position .d3 to the top-left of .d2, and then the left: 83px style will push it to the left from there.
Making up the additional space..
However, to get that additional movement to the right as the original markup, you will need to add margin-left: 8px, which will make-up the additional ~8px needed to replicate the original. Further adjustments to the position of .d3 will need to be done by setting the margin style (see below).
Your updated code should look like this..
.d1 {
   position: relative;
   background-color: yellow;
   height: 50px;
   width: 100px;
   overflow: hidden;
}

.d2 {
  position: absolute;
  background-color: green;
  height: 25px;
  width: 50px;
}

.d3 {
 position: fixed;
 margin-left: 8px;
 left: 83px;
}

Some considerations and caveats..
As a previous commenter mentioned, best practice would be to fix your html markup because this solution could cause issues if you ever need to move the position of .d3. For example, setting left,right,top, or bottom will cause the default setting of this style, auto, from being unset, and the element will be positioned relative to the viewport rather than the parent relative or absolute element.


text:
Q: Regression with zero inflated continuous response variable using gradient boosting trees and random forest I have a data set with a lot of 0 values for the continuous response variable (about 50%). I want to understand how well gradient boosting/random forest deals with this problem. My colleague suggested doing a two part model with classification as the first step to predict the 0's and second step doing regression. Is this necessary?
p.s. I'm using xgboost in R.

A: Updated problem statement
Given data:

*

*comprised of 50% zero padding, 50% of something else

*sufficient in size and complexity that xgboost (or equivalent) is needed

*nonzero data is described by a multivariate linear relationship so multivariate regression is apropos

Show:

*

*HOW to split task into "is zero vs. is not" and "if not, then fit linear"

*WHEN to ...

Solution
Here is our data.

*

*We can use the Kaggle "Human Resource Analytics" challenge
dataset, but with modified goal.

*In the challenge, the goal is to predict "whether" the employee will
leave, so the output is the class, not the regression.  We have to
modify that for our purposes.  Let's suppose that the "satisfaction"
is some HR self-congratulatory hack, and poorly represents actual
satisfaction.  Let's presume also that a strongly truly satisfied
employee doesn't tend to leave, and one that is unsatisfied does tend
to leave.

Process:

*

*first we use gbm (xgboost or other) to use all columns but satisfaction level and "left" to determine if they left.

*second we use the left class to regress on satisfaction.

*finally we compare to see if there are two fundamentally different sets of "physics" driving satisfaction.

Execution

*

*I am going to use r + 'h2o', but the process and results should generalize to any gradient boosted machine including xgboost.  I like the H2O flow interface through the browser.  I also like to use a random-forest as a robust estimator of central tendency.  It is really hard to over-fit a random forest.

Fit of nominal (did employee leave)
#library
library(h2o) #gbm

#spin up h2o
h2o.init(nthreads = -1) #use this computer to the max

#import data
mydata <- h2o.importFile("HR_comma_sep.csv")

mydata[,7] <- as.factor(mydata[,7])

#split data
splits <- h2o.splitFrame(mydata,
               c(0.8))

train.hex <- h2o.assign(splits[[1]], "train.hex")
valid.hex <- h2o.assign(splits[[2]], "valid.hex")

#stage for gbm
idxx <- 1:10
idxx <- idxx[-c(1,7)]

idxy <- 7

Nn   <- 300
Lambda <- 0.1

#fit data
my_fit.gbm <- h2o.gbm(y=idxy,
                      x=idxx,
                      training_frame = train.hex,
                      validation_frame = valid.hex,
                      model_id = "my_fit.gbm",
                      ntrees=Nn,
                      learn_rate = Lambda,
                      score_each_iteration = TRUE)

h2o.confusionMatrix(my_fit.gbm)

The purpose of training/validation is to "dial in the parameters" to a decent level, and to estimate operational uncertainty.  When the dials are set, and we have estimates of how what step 1 errors are, then we train on the whole data to move to the second step.  In this case I am moving fast so that is not done here.  I predict on the model used for tuning parameters.
Convergence is fair, although the example here is nothing close to rigorous.

Here is the baseline RF
my_fit.rf <- h2o.randomForest(y=idxy,
                              x=idxx,
                              training_frame = train.hex,
                              validation_frame = valid.hex,
                              model_id = "my_fit.rf",
                              ntrees=150,
                              score_each_iteration = TRUE)

h2o.confusionMatrix(my_fit.rf)

Its confusion matrix is:
Confusion Matrix (vertical: actual; across: predicted)  for max f1 @ threshold = 0.469005852414851:
          0    1    Error        Rate
0      9008  100 0.010979   =100/9108
1        98 2762 0.034266    =98/2860
Totals 9106 2862 0.016544  =198/11968

Comparison of this with confusion matrix from the GBM fit suggests we have around 93.6% positive predictive value, and we are in the right area to not be over-fitting.
Here is the confusion matrix for the GBM:
Confusion Matrix (vertical: actual; across: predicted)  for max f1 @ threshold = 0.410323012296247:
          0    1    Error        Rate
0      9030   87 0.009543    =87/9117
1       103 2723 0.036447   =103/2826
Totals 9133 2810 0.015909  =190/11943

So let's predict the "did they leave" on the whole data, and use it to model the "satisfaction_level".
Here we predict and augment the data
pred_left.hex  <- h2o.predict(my_fit.gbm,
                         newdata = mydata,
                         destination_frame="pred_left.hex")

mydata2 <- h2o.cbind(mydata, pred_left.hex)

Here we make prediction of "satisfaction"
#stage for second gbm
idxx2 <- 1:13
idxx2 <- idxx2[-c(1,7)]

idxy2 <- 1

Nn   <- 300
Lambda <- 0.05

#split data
splits2 <- h2o.splitFrame(mydata2,
                         c(0.8))

train2.hex <- h2o.assign(splits2[[1]], "train2.hex")
valid2.hex <- h2o.assign(splits2[[2]], "valid2.hex")

#fit data
my_fit2.gbm <- h2o.gbm(y=idxy2,
                      x=idxx2,
                      training_frame = train2.hex,
                      validation_frame = valid2.hex,
                      model_id = "my_fit2.gbm",
                      ntrees=Nn,
                      learn_rate = Lambda,
                      score_each_iteration = TRUE)

As long as it is a "fair" model, the variable importance is going to show whether this has utility.
Here is the "RF as a gross reality check"
my_fit2.rf <- h2o.randomForest(y=idxy2,
                              x=idxx2,
                              training_frame = train2.hex,
                              validation_frame = valid2.hex,
                              model_id = "my_fit2.rf",
                              ntrees=150,
                              score_each_iteration = TRUE)

The RF converged

Fit metrics give mae around 0.13

Here is the GBM results

Now, I did nearly nothing in the way of real tuning.  A decent GBM can usually outperform an RF for accuracy by quite a bit.  It can also over-fit, which is a bad thing that requires a litle time and effort to resolve.
Our typical error scale of 13% (mae = mean absolute error) isn't bad.  It is consistent with the RF, but there is something much more interesting.
Here is what the GBM gives for variable importance (and the key you are looking for).

Notice that the "P0", the probability of staying, is the number 2 most informative value in the set.  It is stunningly more important than salary, work hours, accidents, or previous review.  It is, in fact, more informative than the bottom 8 variables combined even though it is a function of them.
From this we might say that any HR that claims all "satisfaction scores" are created equal, given this data, is junk; we shouldn't be as surprised as they are that the "best and most experienced employees are leaving prematurely".  With only a little work, the predictive values should be moved to the late 90's, even on real-world data.
This also shows how having the class probabilities as an input can be substantially informative.
Thoughts:

*

*If P0 was contrived as log of probability, or as log-odds, then it might be even more informative for the fundamental learner, the CART.

*Again, the GBM could be substantially improved by adjusting control parameters.  This is practically "shoot from the hip".

UPDATE:
There is also a package called "lime" that is about unpacking variable importance from black box models like random forests. (ref)


text:
Q: Replace space of a specific position in a text file with NA I have a TEXT file like this-
sfdfd
kgfkhgjk
fsdfs
sgsgggggfsdf

Node: RBS6301 CXP102051/26_R30F L17A.4-6 (C17.0_LSV198_PA24)

=================================
col1 clo2 clo3
=================================
1   avb wer21g2
---------------------------------

    =================================
empcode   Emnname   Date       DESC
12d      sf        2018-02-06      dghsjf  hfhgf jfjh
asf2     asdfw2    2018-02-16      fsfsfg  jhjhhjghk
dsf21    sdf2      2016-02-06      sdgfsgf
sdgg     dsds      dkfd-sffddfdf   aaaa
dfd      gfg       dfsdffd         aaaa
df                 dfdf            efefkhgvkjgjk kgkjjk
4fr                                freff klhlkkl
-----------------------------------

hfjh
vkgjlbljkbkjbk/n/l  jhfjhfhj kutiugjm iugiuk
hfhj
fggggggggggggggggggggggg

from above I have extracted the below portion using -
import pandas as pd
import csv

findStr = 'empcode   Emnname'
EndStr = '-----------------------------------'
tmp1 = []
tmp = []
tmp2=[]
with open('test123.txt') as f:
    out = []
    for line in f:
        if line.startswith(findStr):
            tmp.append(re.findall('\w+',line.strip()))

            for line in f:
                if line.rstrip()==EndStr:
                    out.append(tmp)
                    break
                tmp.append(re.sub('\s',' ',line.strip()))

f.close()

tmp
O/P-
[['empcode', 'Emnname', 'Date', 'DESC'],
 '12d      sf        2018-02-06      dghsjf  hfhgf jfjh',
 'asf2     asdfw2    2018-02-16      fsfsfg  jhjhhjghk',
 'dsf21    sdf2      2016-02-06      sdgfsgf',
 'sdgg     dsds      dkfd-sffddfdf   aaaa',
 'dfd      gfg       dfsdffd         aaaa',
 'df                 dfdf            efefkhgvkjgjk kgkjjk',
 '4fr                                freff klhlkkl']

However, I want NA in the whitespace area.i.e below gfgor after 4fr. Can anyone please help out. It should be like-
[['empcode', 'Emnname', 'Date', 'DESC'],
 '12d      sf        2018-02-06      dghsjf  hfhgf jfjh',
 'asf2     asdfw2    2018-02-16      fsfsfg  jhjhhjghk',
 'dsf21    sdf2      2016-02-06      sdgfsgf',
 'sdgg     dsds      dkfd-sffddfdf   aaaa',
 'dfd      gfg       dfsdffd         aaaa',
 'df       NA        dfdf            efefkhgvkjgjk kgkjjk',
 '4fr      NA        NA              freff klhlkkl']

A: Use re to extract the portion you're looking for and leverage Pandas read_fwf fixed width reader.
import re
import pandas as pd

pat = '(empcode   Emnname(.|\n)*)-----------------------------------'
txt = re.findall(pat, open('test123.txt').read())[0][0]
h, b = txt.split('\n', 1)
df = pd.read_fwf(pd.io.common.StringIO(b), header=None, names=h.split())
df

  empcode Emnname           Date                  DESC
0     12d      sf     2018-02-06    dghsjf  hfhgf jfjh
1    asf2  asdfw2     2018-02-16     fsfsfg  jhjhhjghk
2   dsf21    sdf2     2016-02-06               sdgfsgf
3    sdgg    dsds  dkfd-sffddfdf                  aaaa
4     dfd     gfg        dfsdffd                  aaaa
5      df     NaN           dfdf  efefkhgvkjgjk kgkjjk
6     4fr     NaN            NaN         freff klhlkkl

And if for some reason OP actually wanted list output
[df.columns.tolist()] + df.to_string(header=None, index=None).splitlines()

[['empcode', 'Emnname', 'Date', 'DESC'],
 '12d      sf     2018-02-06    dghsjf  hfhgf jfjh',
 ' asf2  asdfw2     2018-02-16     fsfsfg  jhjhhjghk',
 'dsf21    sdf2     2016-02-06               sdgfsgf',
 ' sdgg    dsds  dkfd-sffddfdf                  aaaa',
 '  dfd     gfg        dfsdffd                  aaaa',
 '   df     NaN           dfdf  efefkhgvkjgjk kgkjjk',
 '  4fr     NaN            NaN         freff klhlkkl']


text:
Q: JTextArea does not scroll to the bottom after a highlight When i add JTextArea to a scrollpane..
I can add messages to the textArea
eg
JTextArea.append("\n" +message);
and it will scroll to the bottom of the JTextARea
BUT!
after i highlight the text area and add a mesage again it will not scroll to the bottom automatically.
Is this java problem, or something i should implement manually. because if it is not doing after just a highlight, than it is pretty dam weird.


text:
Q: Select Random xx answer python bot How to make python bot pick a random name. For example if I provide a list of
answers.
answers = ["apple", "ball", "cat", "dog", "elephant", "frog", "gun"]

@bot.command()
async def choose(k : int):
    """Chooses between multiple choices."""
    if 0 <= k <= 50:
        await bot.say("This is your random {} pick".format(k))
        embed = discord.Embed(description='\n'.join(random.choices(answers, k=k)))
        await bot.say(embed=embed)
    else:
        await bot.say("Invalid number")

A: You can use random.choices (not choice) to select n items with replacement, if you are on Python 3.6+
@bot.command()
async def choose(k : int):
    """Chooses between multiple choices."""
    if 0 <= k <= 50:
        await bot.say("This is your random {} pick".format(k))
        embed = discord.Embed(description='\n'.join(random.choices(answers, k=k)))
        await bot.say(embed=embed)
    else:
        await bot.say("Invalid number")

@choose.error
def choose_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        await bot.say("Please specify how many")

A: import random

answers = ["apple", "ball", "cat", "dog", "elephant", "frog", "gun"]

def pick5(listOfAnswers):
    print("This is your random 5 pick:")

    for i in range(0, 5):
        myInt = random.randint(0,len(listOfAnswers)-1)
        print(listOfAnswers[myInt])
        listOfAnswers.remove(listOfAnswers[myInt])

pick5(answers)

This Python function picks 5 random elements out of a given list.
It iterates 5 times and uses a randomly selected integer to pull an element from the given list, then removes it to avoid duplicates. It uses the random module to accomplish this.
I don't know about getting it to discord, but I think this is what you were looking for.


text:
Q: How can I tell what version of Might and Magic: Heroes 6 is installed using Steam? Is there any way I can check what version (for example v1.0.2) of Might and Magic: Heroes 6 is currently installed via the Steam client?

A: If you want to know the version of the game, you can find it in the main menu in the lower right/left corner.
However, be aware that Steam does not patch Heroes 6.
It's patchable through the Ubisoft Installer application which in turn is installed by Steam when it enters the prerequisite stage of the game installation phase. Whenever you launch HOMM 6 via Steam it automatically launches the Ubisoft application which checks if there is a new patch.


text:
Q: Which is the correct way to transfer values between unions? If you have:
typedef union value {
    int i;
    float f;
} VALUE;
VALUE a, b;

if you know the type of a, should you do
b.i = a.i;
b.f = a.f;

or
if(a_type == INT)
    b.i = a.i;
if(a_type == FLOAT)
    b.f = a.f;

A: Just use b = a unless there is a particular reason not to, such as that the union occasionally contains a large amount of data, and you want to optimize the assignment for cases when it contains only a small amount.
Per C 2011 [N1570] 6.5.16.1 1, one of the acceptable situations for simple assignment is:

the left operand has an atomic, qualified, or unqualified version of a structure or union type compatible with the type of the right.

Per 6.2.7 1:

Two types have compatible type if their types are the same.

(Per 6.2.6.1 6, "The value of a structure or union object is never a trap representation, even though the value of a member of the structure or union object may be a trap representation.")

A: The most correct probably is (assuming the the same type)
memcpy(&b, &a, sizeof(b));

A: The Standard does not specify in what cases the storage associated with an aggregate may be accessed via a member-access lvalue of non-character type.  If a union member member1 is the largest type in a union and has no trap representations, a quality compiler should be able to handle operations like
objectOfMemberType = someUnion.member1;
someUnion.member1 = valueOfMemberType;

A quality compiler should also have no problem with constructs like:
memberType *p = &someUnion.member1;
*p = valueOfMemberType;

As the Standard is written, it imposes no requirements upon the behavior of either construct if the member is of non-character type, and thus the only ways to do anything with unions without invoking UB are to either use lvalue of union type to copy the entire contents of a union, use lvalues of character type to accesses pieces of the union, or use functions like memcpy.  Accessing union contents directly through member lvalues seems mostly reliable in gcc and clang (I think the cases I've found where it doesn't are unintentional bugs) but neither gcc nor clang seems to be designed to reliably support any use of union member pointers, even when the usage immediately follows the act of taking the address [as shown above].
Given the way the C Standard is written, it's hard to really determine a "correct" way of transferring values between unions, since most kinds of code which would employ unions in useful fashion invoke UB.  Which approach is best depends upon which forms of UB one is willing to trust one's compiler to process sensibly.


text:
Q: Perl script working but too slow My script is designed to read scripts of the following form:
fixedStep chrom=chr1 start=3 step=1
0.006
0.010
fixedStep chrom=chr1 start=9 step=1
0.002
0.004
0.005
fixedStep chrom=chr1 start=14 step=1
0.010
0.020
0.028
0.666
0.777
fixedStep chrom=chr1 start=22 step=1
0.005
0.009
0.012
0.555

The script works on short "practice files" of this sort.  Its output looks like:
.....
.....
.....
0.006
0.010
.....
.....
.....
.....
0.002
0.004
0.005
.....
.....
0.010
0.020
0.028
0.666
0.777
.....
.....
.....
0.005
0.009
0.012
0.555
.....
.....
.....
.....
.....

So, what the script is doing is listing in a single column two important things derived from the original file.  The first kind of important thing is all those four digit decimal numbers.  The second kind of important thing is the variable number of instances of ......  Those represent "missing" four digit numbers.  The number of ..... that occur before and after any continuous stretch of decimal numbers is calculated from the information contained in lines beginning with fixedStep....
The ultimate point of the script is to convert large versions of the practice file show here into a large version of the output. But as I said, my solution is slow. Any ideas to improve?  I do have another script already written to read the output, and that script is expecting output of the particular format I just described.
Here's the script:
#!/usr/bin/perl

use strict; use warnings;

unless(@ARGV) {
    exit;
}

my $chrpc = shift;
open( PHAST, "<$chrpc" );

This just opens up the file.  Next, I slurp the original file.  I know that is slow, but I the path I saw toward the solution started with this.  I suspect this is the most significant thing slowing stuff down. Later on the script gets a little convoluted, I admit, and that could be "cleaned up", hopefully with an impact on performance and not just for esthetics.
my @wholething = ();
while ( <PHAST> ) {
    my $line = $_;
    chomp $line;
    push( @wholething, $line );
}

Next, I start to reorganize the data. I also add in some things, like commas or the word "end", in anticipation of using those to help split/join things together at subsequent steps.  First, I make container @chunked and push into it the first line of the file and a comma.
my @chunked = ();

push ( @chunked, $wholething[ 0 ], ",");

Then a loop through @wholething, and push into @chunked the next lines of the file containing the decimal numbers and also the next line containing fixesStep, a comma, "end", and then the same line again, followed by a comma.
for ( my $i = 1; $i < scalar @wholething ; $i++ ) {
       if ( $wholething[ $i ]=~m/fixedStep/ ){
       chomp $wholething[ $i ];
       push ( @chunked, $wholething[ $i ],",", "end\n", $wholething[ $i ], ","  );
  }

  else {
      chomp $wholething[ $i ];
      push ( @chunked, $wholething[ $i ], "," );
  }
}

In the end, what we have is a bunch of "chunked" bits of file, where each of the continuous runs of decimal numbers are bracketed by adjacent fixedStep containing lines, except for the last chunk, whose run of decimal numbers is bracketed by the last fixedStep line at the front.  With the original file chunked like this, I could use the information in the flanking lines to decide how many ..... to add to represent the "missing" information. For the last chunck, I manually enter in a value to help make those decisions. But now, I join @chunked into a giant string, and then split it at all the occurrences of "end".
my $bigstring = join ( "", @chunked );
my @chunked_array = split ( "end" , $bigstring );
#print "@chunked_array\n\n";

Now with the file reorganized, I begin to make the new file. I make a container @pc_array and define $last to be some value.  Recall above that in the chunked form, each run of decimal numbers was bracketed by adjacent fixedStep lines, except for the last chunk.  The value given by $last is used to help bracket the end of the last chunk. Here, that number is huge. If it matters, this value is the final position of a chromosomal sequence. All the lines of the output correspond to base positions in chromosomes (so the files are huge). For practice files, is set $last to a much smaller number.
my @pc_array = ();
my $count = 1;
my $last = 61342429;  ## enter here value of final position for given chr.

A for loop to cycle through each chunk and figuring out how many ..... to add in between chunks. For the first time through the loop, I calculate how many ..... to add to the array before the first decimal number.  The last time through the loop I use $last to help figure out how many .... to add at the end.  For the rest, I push into the array the decimal numbers, followed by the appropriate number of ......  I also generate in the output some sanity checks to make sure things are working out correctly.  I will remove those at the end in order to generate the final form of the output.
for ( my $i = 0; $i < scalar @chunked_array  ; $i++ ) { ## $i = chunk number

      my @lines = split ( "," , $chunked_array[ $i ]);

      my $distance = scalar @lines - 2 ; ## gives number of pc score lines
      ## notice extra comma in @entries.

      my ( $position_1, $position_2 ) = ($chunked_array[ $i ] =~ /start\=(\d+)/g);
      my $post_fill = $position_2 - ( $position_1 + $distance ) ;

      if ( $i == 0 ){ ## when first chunk

           push ( @pc_array, 0, 0, ".....\n" );

           for ( my $j = 0; $j < $position_1 - 1 ; $j++ ){

                 ## fill in 'pre-missing' scores with .'s

             push ( @pc_array, $i, $count, ".....\n" );
             $count++;
       }

        ## fill in pc scores
        for( my $j = 0; $j < $distance; $j++ ){

             push( @pc_array, $i, $count, "$lines[ 1 + $j ]\n" );

             $count++;
         }

         ## fill in post-missing pc scores with .'s
         for ( my $j = 0; $j < $post_fill  ; $j++ ){
               push ( @pc_array, $i, $count, ".....\n" );
               $count++;
         }

  }

  elsif ( $chunked_array[ $i ] eq $chunked_array[ -1 ] ) {
          ## when last chunk

          ## fill in pc scores
          for( my $j = 0; $j < $distance; $j++ ){

               push( @pc_array, $i, $count, "$lines[ 1 + $j ]\n" );

               $count++;
          }

          my $final_post_fill = $last - ( $position_1 + $distance );

          ## fill is post-missing pc scores with .'s
          for ( my $j = 0; $j < $final_post_fill + 1  ; $j++ ){
               push ( @pc_array, $i, $count, ".....\n" );
               $count++;
         }

  }

  else { ## when first or else not the last chunk

        ## fill is pc scores
        for ( my $j = 0; $j < $distance; $j++ ){

             push( @pc_array, $i, $count, "$lines[ 1 + $j ]\n" );

             $count++;
         }

         ## fill is post-missing pc scores with .'s
         for ( my $j = 0; $j < $post_fill  ; $j++ ){
               push ( @pc_array, $i, $count, ".....\n" );
               $count++;
         }

   }

}

I look at the array.  The first line of the output is off by a space. There's an extra space added in at the beginning.
print @pc_array;

I do the following to remove the space but also mainly to remove the sanity checks in the output, in order to arrive at the final form of the output I require.
my @pc_col =();

for ( my $i = 2; $i < @pc_array; $i=$i+3 ) {
      chomp $pc_array[ $i ];
      print "$pc_array[ $i ]\n";
      push ( @pc_col, $pc_array[ $i ]."\n");
}

print @pc_col;
open( OUT, ">chr19_pc_col.txt");
print OUT @pc_col;

Like I said, the script works but I could use some pointers to optimize it.

A: You have got yourself very tangled up.
As far as I can tell this program seems to do what you need. I assume the step attribute is always one, or at least can be ignored, and that the chrom field is similarly irrelevant.
use strict;
use warnings;

open my $out, '>', 'chr19_pc_col.txt' or die $!;

my $last = 30;

my $line = 0;
while (<>) {
  if (/^fixedStep.*start=(\d+)/) {
    my $start = $1;
    while ($line < $start) {
      print $out ".....\n";
      ++$line;
    }
  }
  else {
    print $out $_;
    ++$line;
  }
}

print $out ".....\n" for $line .. $last;

close $out or die $!;

output
.....
.....
.....
0.006
0.010
.....
.....
.....
.....
0.002
0.004
0.005
.....
.....
0.010
0.020
0.028
0.666
0.777
.....
.....
.....
0.005
0.009
0.012
0.555
.....
.....
.....
.....
.....

A: Slurping does tend to cause performance issues with large files.
I won't do the whole thing for you, but it looks like a pattern similar to this might help get you started:
#buffer, holds a few lines of the input file
my @chunk_lines = ();

#read line-by-line until end of file
while (!eof $fh) {
    my $line = readline $fh;
    if ($line =~ /^fixedStep/) {      #if this line is the start of a new chunk...
        process_chunk(@chunk_lines);  #process data
        @chunk_lines = ();            #clear buffer
    }

    #either way, push this line onto the buffer
    push @chunk_lines, $line;
}

#process any remaining buffer
process_chunk(@chunk_lines);

If you can process each chunk individually, that's good. Anything where you push a bunch of values into an array, and then split it down for processing? That's a spot you might be able to optimize.
If passing an empty @chunk_lines to process_chunk is bad, you could avoid it simply:
process_chunk(@chunk_lines) if @chunk_lines;


text:
Q: Issues while uploading an object on S3 bucket I am trying to run AWS SDK (boto3) code on my machine. I want to upload some files on S3 bucket. However I read those files from a disk and for that I need to run the code with sudo -E. When I run the code like that, I get
ERROR:root:An error occurred (AccessDenied) when calling the PutObject operation: Access Denied error.
But when I run the same code without sudo (and after commenting disk related operations that needs sudo), it works perfectly fine.
Has anyone else faced this issue?
Can anyone help me fix this?
Reference Code - https://docs.aws.amazon.com/code-samples/latest/catalog/python-s3-put_object.py.html

A: The aws credentials need to be given read permission for your current user, so that boto client is able to read them
$ chown -R user:user .aws/


text:
Q: dbt could not find an incremental strategy macro with the name "get_incremental_insert_sql" In DBT Redshift, I have a model with this config:
{{config(
          materialized='incremental',
          incremental_strategy='insert'
        )
}}

It runs fine with dbt-core 1.2
dbt-core==1.2.4
dbt-extractor==0.4.1
dbt-postgres==1.2.4
dbt-redshift==1.2.0

But If I upgrade dbt-core/postgres/redshift to 1.3.0 it breaks with this error:
dbt could not find an incremental strategy macro with the name "get_incremental_insert_sql"
Is insert strategy not supported or do I need to alter the config?

A: I don't think insert was ever supported; it was probably invalid config being quietly ignored. They refactored this config in 1.3 (see this issue, which added validation.
Your options for Redshift are append or delete+insert. Since you haven't defined a unique key, I think you probably want append.
This should probably be better-documented here, but that page doesn't mention PG/Redshift.


text:
Q: JQuery hover function select all elements with same class name Need to highlight the current hovered element + all other elements with same colour / class name.
Example here:
https://codepen.io/Kerrys7777/pen/LkaYOW
jQuery( document ).ready(function( $ ) {
    $('.orange-cell, .green-cell, .purple-cell, .white-cell').hover(function() {
        $(this).addClass('z-relative');
        $('#darkness').fadeTo(200, 1);
    },function() {
        $(this).removeClass('z-relative');
        $('#darkness').fadeTo(200, 0, function(){
            $(this).hide();
        });
    });
});

A: Following are the changes needed for your code.
HTML CHanges:

Home

About

Contact

Num

Some text here

Home

About

Contact

Num

Some text here

Home

About

Contact

Num

JS Changes :
jQuery( document ).ready(function( $ ) {
    $('.orange-cell, .green-cell, .purple-cell, .white-cell').hover(function() {
        var color = $(this).attr('data-color');
        $("."+color+"-cell").addClass('z-relative');
        $('#darkness').fadeTo(200, 1);
    },function() {var color = $(this).attr('data-color');
        $("."+color+"-cell").removeClass('z-relative');
        $('#darkness').fadeTo(200, 0, function(){
            $(this).hide();
        });
    });
});

A: if you dont want to  change html you can do like this.
jQuery( document ).ready(function( $ ) {
    $('.orange-cell, .green-cell, .purple-cell, .white-cell').hover(function() {
        var colorClass = $(this).attr('class').split(' ')[1];
        $("."+colorClass ).addClass('z-relative');
        $('#darkness').fadeTo(200, 1);
    },function() {var colorClass = $(this).attr('class').split(' ')[1];;
        $("."+colorClass ).removeClass('z-relative');
        $('#darkness').fadeTo(200, 0, function(){
            $(this).hide();
        });
    });
});

A: Try this code. One thing that you need to note here that you need to always add color class (green-cell,orange-cell) at second place inside your li tag
jQuery(document).ready(function ($) {
    var highlitedClass;
    $('.orange-cell, .green-cell, .purple-cell, .white-cell').hover(function () {
        $(this).addClass('z-relative');
        var liClass = $(this).prop("class");
        $('#darkness').fadeTo(200, 1);
        liClass = liClass.split(' ');
        highlitedClass = liClass[1];
        $("." + highlitedClass).addClass('z-relative');

    }, function () {
        $(this).removeClass('z-relative');
        $("." + highlitedClass).removeClass('z-relative');
        $('#darkness').fadeTo(200, 0, function () {
            $(this).hide();
        });
    });
});


text:
Q: Debian Testing: Не отображаются список открытых программ в Latte Dock 0.8.4 Установлен Debian Testing с KDE Plasma 5.14. Собрал из исходников и установил Latte Dock.
Проблема: Док запустился, но на нет значков запущенных окон. Только виджет аналоговых часов. Добавлял виджет "Панель задач (только значки)". Но это не то. Раньше при первом запуске нормально отображались значки запущенных программ.
Вопрос: Как включить отображение иконок запущенных программ?

A: Чтобы включить отображение запущенных приложений, надо на док/панель добавить виджет Latte.


text:
Q: Hardware mystery I have been trying to solve for the last two years My laptop is an Asus zenbook UX430UA and I have this problem I am struggling with for the last 2 years.
It starts when windows updates installs the update from build 1809 to 1903 and above (and win 11), my laptop breaks completely. Windows takes an hour to boot and works super slow which forces me to rollback.
This triggered me and made me want to install Linux, but I have this error which I cant figure out how to solve, I made a seperate thread: Ubuntu(Or any other linux distro) stuck on retrieving clocksource, all the commandline options given did not solve the problem.
I sent my laptop back to asus repair but they told me that I need to replace the full motherboard. This does not make sense to me since I tested it and windows 7, 8, and 10(until build 1809) all work. The linux distros do work in virtualbox within win 10 1809 but when I try to install natively, I get the problem from the thread. It makes me think that the windows update and the linux kernel not willing to work natively might have a connection(BIOS Problem?).
Is there anyone who experienced this issue and knows a solution or the cause of the problem?


text:
Q: execute code just when install the application using installshield I am just wondering if it is possible to run a small code just once when the application is installing.
I would like to create a registry with the installation path. The reason why I need that because I have a windows service in my application as well, which install path always changes to system32.
I have an ini file which is created in the installation folder at installation. I need to reach that file with my service and windows form as well.

A: You don't need any extra code, just create a registry key in HKLM\software\yoursoftware-here with a key name like Installpath and a value of [INSTALLDIR] in your install, then reference that key in your service.
This assumes you are using a basic MSI project in install shield.


text:
Q: Loss of trig precision For a gravity simulation, I need to find the angle between two objects so I can apply the force. However, I am losing precision and I don't know where. Here is the minimal code that can reproduce the issue.
#include<iostream>
using namespace std;

struct Vector2f
{
    float x, y;
};

Vector2f operator-(Vector2f& left, Vector2f& right)
{
    return Vector2f{ left.x - right.x, left.y - right.y };
}

double pi = 3.141592653589793238463;

double angle(Vector2f& one, Vector2f& two)
{
    Vector2f normal(one - two);

    if (!normal.x && !normal.y)
    {
        return 0.0f;
    }

    float theta = -(atan((double)(normal.y / normal.x)) - pi / 2);

    if (normal.x < 0)
    {
        return (theta - pi / 2);
    }
    else
    {
        return (theta + pi / 2);
    }

}

int main()
{
    Vector2f one{ 0,0 };
    for (int i = -100; i <= 100; i += 100)
    {
        for (int j = -100; j <= 100; j += 100)
        {
            Vector2f two{ i,j };
            cout << i << ", " << j << endl;
            cout << "sin:\t" << sin(angle(one, two)) * 180.0f / pi << endl;
            cout << "cos:\t" << cos(angle(one, two)) * 180.0f / pi << endl;
            cout << endl;
        }
    }
    return 0;
}

For instance, where I should be getting 45 (comparing (0,0) with (100, -100) due to the grid), I am getting answers like 40.5142 and 57.2958. I understand if the precision lost were less than a degree, but this is ridiculous. I want all the output from this code to be multiples of 45, basically for those without trig knowledge. Changing the datatype of Vector2f to double does not affect the end result. Could you help me find the issue?
I am using VS 2015, but it happens similarly on VS 2013.

A: sin(angle(one, two)) * 180.0f / pi doesn't make sense.
it should be
sin(angle(one, two))

And you may print your angle
std::cout << angle(one, two)) * 180.0f / pi << " degree\n";
std::cout << angle(one, two)) << " radian\n";


text: Q: Creating more than one channel using Agora in Flutter Can I create more than one channel at a time using Agora in flutter. The documentation says that for creating a channel we need a channelId and to join in that channel we need the temp token, channelname. As per my knowledge only one token can be used at a time. What should I do to generate more than one token at the same time for different users. Sorry for my bad English.


text:
Q: Android Development - Using a PNG as a map, marker for current location I have a large PNG (around 1500 x 2000) that cut into slices and put back together using HTML because otherwise the image quality is horrible.
I want to be able to have a marker of the user's current location on this image. I'm a little lost about how to do this, especially if the image is zoomable.
Ex: How do I make the marker have variable location on the string? (codewise)
How do I know how much to change the coordinates by when they zoom in?
Help or code samples would be highly appreciated! I am very stuck.
Thanks!
Note: Please be specific, I admit I am not experienced at android development

A: Why not just store the marker position on the original image coordinates (x, y)? eg. if the user is in the middle, save their position as (750, 1000). When you zoom, everything is relative; so if you zoom to 2x, the full image would be 3000x4000, and the marker position would be (1500, 2000).
I don't see what your difficulty is :) maybe I'm underestimating what the problem is.


text:
Q: Enabling ExtJS code completion with IntelliJ IDEA How do I enable auto-complete/code completion feature of IntelliJ IDEA to work with ExtJS javascript library?
Thanks

A: This could probably be closed as a dup of this question:
Add ExtJS code assist to IntellijIDEA
The answer is here:
http://blogs.jetbrains.com/webide/2010/11/working-with-javascript-libraries-in-phpstorm-webstorm/

A: do you have the extjs javascript files in your project?    I find that when I do Intellij is somewhat good at getting methods, but it doesn't always get all the available methods.  I thinks its just a gotcha of dynamic languages -- an IDE can't know all the methods available because some are available only at runtime...


text:
Q: Proper way to 'exit' a script in PHP I have a static method named ServerResponse that basically shows a message whether on success or fail. I just want to know the proper way to actually display the message and exit the script.
Should I implement my method like this:
public static function ServerResponse($e,$m){

    print(json_encode([$e,$m]));
    exit;
}

//Sample use:
if(this happens){
    myclass::ServerResponse($x,$y);
}

or like this:
public static function ServerResponse($e,$m){
    return json_encode([$e,$m]);
}

//Sample use:
if(this happens){
    print(myclass::ServerResponse($x,$y));
    exit;
}

*

*Which one is proper and better... and why?

*is there any difference between them? (on execution time).

"Don't be hard on me I am not an expert (just yet)..."

A: For better debugging, it's advised to always make a function or method return a value. So your 2nd sample should be chosen.
exit (or die) are commonly used when the program ends with an error, giving the ability to add an exit status (as a number or a string).
I suppose there will be no significant difference about the execution time.

A: I don't know if this is common practice but I only use exit to debug. If your script comes to the end of execution it will exit on it's own.
If you must exit, do it in the main script, not in a function.
functions should have one task and do that task. So the function ServerResponse should send a response and not kill the script.


text:
Q: How to make a proper OAuth request to Dataverse API with Postman? I want to make an OAth request to the Microsoft Dataverse API to get the Bearer token, and with this token I wish to make authenticated requests to PowerAutomate. I use Postman for making the requests. I can get the Bearer token in 2 different ways, but with the same result after using these in a request: 401 Unauthorized
My settings:
Common auth url:

Auth url with TenantID:

As you can see I got a Bearer token for both, but when I try to call the simplest /WhoAmI endpoint I got 401 Unathorized error.
I have my API permissions set up properly in the Azure app:

I have my application user with the right application ID:

My first question: What am I missing? What else should I set up?
My second question: What is the difference between the two auth endpoint I am using?
Any suggestions are welcomed.

A: I tried to reproduce the same in my environment and got below results:
I registered one multitenant Azure AD application and added API permissions like below:

Now, I generated access token using client credentials flow same as you via Postman like this:
POST https://login.microsoftonline.com/<tenantID>/oauth2/v2.0/token
client_id: <appID>
grant_type:client_credentials
scope: https://org25xxxxxx.crm.dynamics.com/.default
client_secret: <secret>

Response:

When I used the above token to call /WhoAmI endpoint, I too got 401 Unauthorized error like below:
GET https://org25bexxxxx.crm.dynamics.com/api/data/v9.0/WhoamI

Response:

I got the same error when I used access token generated with common auth URL too.

To resolve the error, try using implicit flow to generate
access token.

Make sure to enable "oauth2AllowImplicitFlow" property in app's Manifest file before generating token like below:

Now, create new environment in Postman with below parameters:
url: <your Dynamics 365 URL>
clientid: <appID of Azure AD application>
version: 9.0
webapiurl: {{url}}/api/data/v{{version}}/
callback: <redirect URL of Azure AD app>
authurl: https://login.microsoftonline.com/common/oauth2/authorize?resource={{url}}

To generate access token, open new tab and select OAuth 2.0 in Authorization tab by entering details like this:

After selecting Get New Access Token option, I signed in with admin credentials and got access token successfully like below:

I selected Use token option and called /WhoAmI endpoint where I got results successfully like below:
GET {{webapiurl}}WhoAmI

Response:

What is the difference between the two auth endpoint I am using?

Common Auth URL: https://login.microsoftonline.com/common/oauth2/token is a common endpoint used to get token for any Azure AD tenant. If your application is multi-tenant, then your token endpoint will be common like below:

Auth URL with TenantID:
https://login.microsoftonline.com/{tenant_id}/oauth2/token is used to get token for particular tenant ID. If your application is single tenant, then your token endpoint will be with tenantID like below:

Reference:
Postman tool to test Dynamics 365 online Web API by Rajeev Pentyala


text:
Q: What is the notation for the empty matrix? My question: What is a notation for an empty 0x0 matrix (i.e. the matrix for the only linear map $f:\{0\}\to\{0\}$)? Is it written $()$? How can I distinguish the 0x0 matrix with for example the 0x3 matrix or the 3x0 matrix?
What I have already found out: Concerning the section "Empty matrices" of the Wikipedia article "Matrix (mathematics)" there "is no common notation for empty matrices". But unfortunately I haven't found any notation so far...
Notes: I am looking for a notation which is used in a textbook. I am not interested in how empty matrices can be created in CAS like Matlab, Mathematica, etc.
Reason for this question: In our course we had the task to draw all graphs with three vertices and to state the incidence matrix for each drawn graph. Thus, for the empty graph I have to state a 0x3 matrix, but I didn't know the right notation for it...

A: I don't think there is any universally recognizable notation for this. Whatever choice one might make, without explanation it could easily be misunderstood, is the point.
(For that matter, I can't help wondering how/why the notation would be needed in a context that wouldn't permit the simpler explanation "unique linear map from $k^0$ to $k^0$".)

A: I think the most simple notation would be to write $$ 0_{M_{0,0}}$$ for a matrix of size $0\times 0$, and $$ 0_{M_{3,0}}$$ for a matrix of size $3\times 0$.
It's very similar when you want to write the zero of an unknown field $F$, when you write $0_F$.


text:
Q: how to parse complex json data in iOS? I am new to iOS and I want to parse data but it is so complex, I don't know how to parse it. Below given is the json data.
{
    "response_code": 200,
    "last_updated": {
        "date": "2015-12-27",
        "time": "01:32:13"
    },
    "trains": [
        {
            "train": {
                "number": "04921",
                "start_time": "04:45",
                "name": "SRE-UMB MEMU SPECIAL",
                "type": "HSP"
            },
            "dest": {
                "code": "UMB",
                "name": "AMBALA CANT JN"
            },
            "source": {
                "code": "SRE",
                "name": "SAHARANPUR"
            }
        },
        {
            "train": {
                "number": "04922",
                "start_time": "20:45",
                "name": "UMB-SRE MEMU SPECIAL",
                "type": "HSP"
            },
            "dest": {
                "code": "SRE",
                "name": "SAHARANPUR"
            },
            "source": {
                "code": "UMB",
                "name": "AMBALA CANT JN"
            }
        }
    ]
}

A: { , , } - it's a dictionary
[ , , ] - it's an array
In your case you get:
First level - dictionary with keys response_code, last_updated, trains.
Where:
response_code - value
last_updated - dictionary with keys date, time
trains - array of dictionaries with keys train, dest, source
etc.

A: Use the NSJSONSerialization class, it's easy.
For example, in Objective-C:
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
if (jsonObject) {
   // jsonObject is an NSArray or NSDictionary representation of the data that you can now do something with
}