text:
Q: is my proof correct for $\int_{0}^{x^2}g(t)dt=x$, is true only in $x=0$? Given $g(x)$ is continuous in $[0,1]$ and $g(x)<\frac{1}{2}\frac{1}{\sqrt{x}}$ in $(0,1]$.
How to prove that the equation $\int_{0}^{x^2}g(t)dt=x$ is true only if $x=0$?
I solve it like this.
If $g(t)=\frac{1}{2}\frac{1}{\sqrt{t}}$, then $\int_{0}^{x^2}\frac{1}{2}\frac{1}{\sqrt{t}}dt=x^2/2$, but $x^2/2=x$ only when $x=0$, and because $g(x)<\frac{1}{2}\frac{1}{\sqrt{x}}$ in $(0,1]$, then in these domain, the integral won't equal $x$ for any other $x$, so in the domain $[0,1]$, $\int_{0}^{x^2}g(t)dt=x$ is possible only if $x=0$.
Does that enough for the proof?

A: You've made a mistake on your integral. $\int_0^{x^2}\frac1{2\sqrt{t}}dt$ is $x$, not $x^2/2$. And you haven't explained your logic in the rest of the argument well (probably because the integral mistake will keep the rest of the argument from working correctly).
What you want to prove is:
"If $x\in(0,1]$, then $\int_0^{x^2}g(t)dt\neq x$."
So start by assuming $x\in(0,1]$. Then $x^2\in(0,1]$ as well (you should be able to prove this statement carefully if someone asks). So $g(t)<\frac1{2\sqrt{t}}$ for $t\in(0,x^2)$. Since $g$ is smaller than that function on the range you want to integrate, we can say that
$$
\int_0^{x^2}g(t)dt<\int_0^{x^2}\frac1{2\sqrt{t}}dt=\left.\left(\frac22\sqrt{t}\right)\right|_{t=0}^{x^2}=x.
$$
(If someone asks, you should be able to carefully prove that integrals of functions get the same inequality sign between them as the functions themselves. This might be a theorem in your book.)
So $\int_0^{x^2}g(t)dt$ is less than $x$ and they can't be equal. In other words, $\int_0^{x^2}g(t)dt\neq x$, which is what you wanted to prove.
One more suggestion: try break your proofs into multiple sentences. If you feel like you want to jam the whole thing into once sentence, it may be because there is something that you don't know how to explain and you're trying to rush past it.


text:
Q: Ubuntu 12.04 cannot wake up from sleep I've upgraded my Toshiba Portege R500 from Ubuntu 10.04 LTS to 12.04 LTS this weekend.  The new system works smoothly, but if it enters the sleep mode, that is, if my laptop idles more than 15 minutes, the screen goes dim and turn to dark, and cannot wake up anymore.  I've tried to press the Ctrl-Alt-F? and other keys, nothing works, the keyboard hangs.  The mouse/keypad cannot work, either. The only workable key is the 'power'.  If I encounter this problem, the only way I can do is to press the 'power' more than 3 second, and turn my laptop off... It's totally inconvenience.
In general, the hanging situation appears if the computer idles awhile and enters the sleep mode. That is, both the login screen and the working environment after login into the system, have the same problem.
Anyone could help me to fix this problem?
Thank you

A: You should set the lock switch off in the System Settings/Brightness and Lock.
You can enter the System Settings with pressing down the "windows button" and type system settings.
Well this is not an elegant resolution, but works,

redpajama_set_name: RedPajamaStackExchange


text:
Q: Как восстановить данные из бэкапа всей ноды в mariadb/mysql? Мне нужно сделать бекап всей ноды mariadb. Из документации ясно как я могу сделать бэкап базы данных и таблицы. Я могу указать параметр --all-databases в команде, как указано в той же документации:
mysqldump --databases INFORMATION_SCHEMA sys PERFORMANCE_SCHEMA --all-databases > backup-file.sql

Как можно восстановить все базы данных с их таблицами включая системные таблицы из такого бекапа? С одной базой все просто, можно запустить mysql db_name < backup-file.sql Если в бекап была помещена всего одна база. Как распредилить данные по новым базам правильно если таких баз много в backup файле?


text:
Q: Tensorflow object detection API using cnn Tensorflow object detection API using cnn
Traceback (most recent call last):
File "export_inference_graph.py", line 147, in tf.app.run()
File "C:\Users\Ali Salar\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\platform\app.py", line 126, in run_sys.exit(main(argv))
File "export_inference_graph.py", line 143, in main
FLAGS.output_directory, input_shape)
File "C:\tensorflow2\models\research\object_detection\exporter.py", line 453, in export_inference_graph
graph_hook_fn=None)
File "C:\tensorflow2\models\research\object_detection\exporter.py", line 421, in _export_inference_graph
placeholder_tensor, outputs)
File "C:\tensorflow2\models\research\object_detection\exporter.py", line 280, in write_saved_model
builder = tf.saved_model.builder.SavedModelBuilder(saved_model_path)
File "C:\Users\Ali Salar\Anaconda3\envs\tensorflow\lib\sit`enter code here`e-packages\tensorflow\python\saved_model\builder_impl.py", line 90, in init
"directory: %s" % export_dir)
AssertionError: Export directory already exists. Please specify a different export directory: inference_graph\saved_model

A: It's saying the directory already exists. Either change your command in the terminal to point to a new directory or remove everything in this directory that you are currently setting as the output directory.

A: python3 export_inference_graph.py \
--input_type image_tensor \
--pipeline_config_path YOUR_PIPELINE.CONFIG_FILE_PATH \
--trained_checkpoint_prefix YOUR_MODEL_CHECKPOINT_PATH  \
--output_directory exported_graphs/saved_model2

Your try changing output directory.For example exported_graphs/saved_model2 as above.


text:
Q: Google play Games ,automatch How can I disable random auto match from the player-picker UI
In my case I really don't want this feature,so please tell me how to disable it.
Is there any way???
Any help will be appreciated.

A: As stated in this documentation, if the allowAutomatch parameter is set to false, the UI will not display an option for selecting automatch players. Set this to false if your game does not want to support automatching.


text:
Q: Large Shapefiles in R I would like to work with the USGS dataset PADUS in R. However the files are huge and I just want to plot out the main state and national forests, parks and protected areas. Does anyone have any suggestion on how to load and plot these very large files?
USGS DATA DOWNLOAD
Normally I would use readOGR (rgdal) to load in the files but this just seems to crash or fail to load.

A: Use "x <- sf::st_read" it's much faster than rgdal and will happily read much larger data sets.
When you plot it, be sure to use "plot (st_geometry(x))" first, since it will otherwise do a lot of repeated drawing for the default multi panel layout. It defaults to faceting on every column, up to some max.
Indexing with "[" works the same as with sp, so use that to plot just a few rows before trying the entire thing if it's really massive.


text:
Q: Eclipse Project Types Definition/Configuration I am trying to work with a modified version of eclipse that has it's own different project types. For some project types when I Create a project, restart and then delete(with the delete from disc not checked) the project I get the following error:
org.eclipse.core.internal.resources.ResourceException: Resource '/projectName' does not exist.
at org.eclipse.core.internal.resources.Resource.checkExists(Resource.java:341)
at org.eclipse.core.internal.resources.Resource.checkAccessible(Resource.java:215)
at org.eclipse.core.internal.resources.Project.checkAccessible(Project.java:147)
at org.eclipse.core.internal.resources.Resource.checkAccessibleAndLocal(Resource.java:221)
at org.eclipse.core.internal.resources.Resource.touch(Resource.java:1949)
at org.eclipse.core.internal.resources.Project.touch(Project.java:1403)
at org.eclipse.wst.jsdt.internal.core.SetContainerOperation.execute(SetContainerOperation.java:122)
at org.eclipse.wst.jsdt.core.JavaScriptCore.setJsGlobalScopeContainer(JavaScriptCore.java:3901)
at org.eclipse.wst.jsdt.launching.JREContainerInitializer.initialize(JREContainerInitializer.java:48)
at org.eclipse.wst.jsdt.internal.core.JavaModelManager.initializeContainer(JavaModelManager.java:2214)
at org.eclipse.wst.jsdt.internal.core.JavaModelManager$6.run(JavaModelManager.java:2144)
at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:2313)
at org.eclipse.wst.jsdt.internal.core.JavaModelManager.initializeAllContainers(JavaModelManager.java:2160)
at org.eclipse.wst.jsdt.internal.core.JavaModelManager.getJsGlobalScopeContainer(JavaModelManager.java:1536)
at org.eclipse.wst.jsdt.core.JavaScriptCore.getJsGlobalScopeContainer(JavaScriptCore.java:1319)
at org.eclipse.wst.jsdt.internal.core.JavaProject.resolveClasspath(JavaProject.java:2747)
at org.eclipse.wst.jsdt.internal.core.JavaProject.getResolvedClasspath(JavaProject.java:2026)
at org.eclipse.wst.jsdt.core.JavaScriptCore.initializeAfterLoad(JavaScriptCore.java:2655)
at org.eclipse.wst.jsdt.internal.ui.InitializeAfterLoadJob$RealJob.run(InitializeAfterLoadJob.java:32)
at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54)

!SUBENTRY 1 org.eclipse.core.resources 4 368 2015-07-06 13:39:58.865
!MESSAGE Resource '/projectName' does not exist.
My suspicion is that eclipse does not recognize that as a project or something. So the question is the following : Does anybody know how does eclipse defines the acceptable/available project types ?

A: Your stack trace shows that there is no folder projectName in the workspace, so it does not look like the project exists at all.
The contents of the .project file in the project folder defines what 'natures' and 'builders' a project has. For example a Java plug-in project .project file might look like this:
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
    <name>projectName</name>
    <comment></comment>
    <projects>
    </projects>
    <buildSpec>
        <buildCommand>
            <name>org.eclipse.jdt.core.javabuilder</name>
            <arguments>
            </arguments>
        </buildCommand>
        <buildCommand>
            <name>org.eclipse.pde.ManifestBuilder</name>
            <arguments>
            </arguments>
        </buildCommand>
        <buildCommand>
            <name>org.eclipse.pde.SchemaBuilder</name>
            <arguments>
            </arguments>
        </buildCommand>
        <buildCommand>
            <name>org.eclipse.pde.ds.core.builder</name>
            <arguments>
            </arguments>
        </buildCommand>
    </buildSpec>
    <natures>
        <nature>org.eclipse.pde.PluginNature</nature>
        <nature>org.eclipse.jdt.core.javanature</nature>
    </natures>
</projectDescription>

The IProjectDescription interface provides APIs for setting these values.


text:
Q: Public Property Data Binding failing in Xaml My code behind file has its corresponding View Model as a public property for one of my Windows. I tried to data bind my ViewModel with the UI Elements in XAML but I always get error messages for that. However, when I try to create data bind using code, it works without any issues. I am really confused as to why this is happening and would like some guidance on what I am doing wrong.
Scenario 1 - Data binding fails when done in xaml
ProductInfoWindow.xaml:
<Window ...>
    <Grid Name="grdProd" DataContext="{Binding RelativeSource={RelativeSource Self}, Path=ViewModel}">
        <TextBox Name="txtName" Text="{Binding Product.Name}" />
    </Grid>
</Window>

ProductInfoWindow.xaml.cs:
public partial class ProductInfoWindow : Window
{
    public ProductInfoViewModel ViewModel { get; set; }

    public ProductInfo()
    {
        ViewModel = new ProductInfoViewModel(...);
    }
}

Error Messages in Output Window:
System.Windows.Data Error: 40 : BindingExpression path error: 'ViewModel' property not
found on 'object' ''Grid' (Name='grdProd')'. BindingExpression:Path=ViewModel;
DataItem='Grid' (Name='grdProd'); target element is 'Grid' (Name='grdProd'); target
property is 'DataContext' (type 'Object')

Scenario 2 - Data binding works when done in code
ProductInfoWindow.xaml:
<Window ...>
    <Grid Name="grdProd">
        <TextBox Name="txtName" Text="{Binding Product.Name}" />
    </Grid>
</Window>

ProductInfoWindow.xaml.cs:
public partial class ProductInfoWindow : Window
{
    public ProductInfoViewModel ViewModel { get; set; }

    public ProductInfo()
    {
        ViewModel = new ProductInfoViewModel(...);
        grdProd.DataContext = ViewModel;
    }
}

Edit (09/08/2013)
ProductInfoViewModel.cs
public class ProductInfoViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, e);
    }

    private Product m_product;

    public Product Product
    {
        get
        {
            return m_product;
        }

        set
        {
            m_product = value;
            OnPropertyChanged(new PropertyChangedEventArgs("Product"));
        }
    }

    public ProductInfoViewModel(...)
    {
        Product = new Product(...);
    }
}

A: Your error message is telling you that the ViewModel property can't be found on the Grid 'grdProd', which is a fair point, because your Viewmodel is a public property defined on your ProductInfoWindow class.
Try setting the Datacontext at the Window level instead (adapting your example):
<Window DataContext="{Binding RelativeSource={RelativeSource Self}, Path=ViewModel}" ...>
    <Grid Name="grdProd">
        <TextBox Name="txtName" Text="{Binding Product.Name}" />
    </Grid>
</Window>


text:
Q: Get unique properties from array of hashes in ruby Given an array of hashes, I want to create a method that returns a hash where the keys are the unique values of the hashes in the array.
For example, I'd like to take
[
  {foo: 'bar', baz: 'bang'},
  {foo: 'rab', baz: 'bang'},
  {foo: 'bizz', baz: 'buzz'}
]

and return
{
  foo: ['bar', 'rab', 'bizz'],
  baz: ['bang', 'buzz']
}

I am currently accomplishing this using:
def my_fantastic_method(data)
  response_data = { foo: [], baz: []}
  data.each { |data|
    data.attributes.each { |key, value|
      response_data[key.to_sym] << value
    }
  }
  response_data.each { |key, value| response_data[key] = response_data[key].uniq }
  response_data
end

Is there a more elegant way of doing this? Thanks!

A: Your current approach is already pretty good; I don't see much room for improvement. I would write it like this:
def my_fantastic_method(data_list)
  data_list.each_with_object(Hash.new { |h, k| h[k] = Set.new }) do |data, result|
    data.attributes.each do |key, value|
      result[key.to_sym] << value
    end
  end
end

*

*By setting a default value on each hash value, I have eliminated the need to explicitly declare foo: [], bar: [].

*By using each_with_object, I have eliminated the need to declare a local variable and explicitly return it at the end.

*By using Set, there is no need to call uniq on the final result. This requires less code, and is more performant. However, if you really want the final result to be a mapping to Arrays rather than Sets, then you would need to call to_a on each value at the end of the method.

*I have used different variable names for data_list and data. Call these whatever you like, but it's typically considered bad practice to shadow outer variables.

A: Here are a couple of one-liners. (I'm pretty sure @eiko was being facetious, but I'm proving him correct)
This one reads well and is easy to follow (caveat: requires Ruby 2.4+ for transform_values):
array.flat_map(&:entries).group_by(&:first).transform_values{|v| v.map(&:last).uniq}

Here's another, using the block form of merge to specify an alternate merge method, which in this case is combining the values into a uniq array:
array.reduce{|h, el| h.merge(el){|k, old, new| ([old]+[new]).flatten.uniq}}

A: You already have a pretty good answer, but I felt golfy and so here is a shorter one:
def the_combiner(a)
  hash = {}
  a.map(&:to_a).flatten(1).each do |k,v|
    hash[k] ||= []
    hash[k].push(v)
  end
  hash
end

A: Try this:
array.flat_map(&:entries)
  .group_by(&:first)
  .map{|k,v| {k => v.map(&:last)} }

OR
a.inject({}) {|old_h, new_h|
  new_h.each_pair {|k, v|
    old_h.key?(k) ? old_h[k] << v : old_h[k]=[v]};
    old_h}

A: If, as in the example, all hashes have the same keys, you could do as follows.
arr = [{ foo: 'bar', baz: 'bang' },
       { foo: 'rab', baz: 'bang' },
       { foo: 'bizz', baz: 'buzz' }]

keys = arr.first.keys
keys.zip(arr.map { |h| h.values_at(*keys) }.transpose.map(&:uniq)).to_h
  #=> {:foo=>["bar", "rab", "bizz"], :baz=>["bang", "buzz"]}

The steps are as follows.
keys = arr.first.keys
  #=> [:foo, :baz]
a = arr.map { |h| h.values_at(*keys) }
  #=> [["bar", "bang"], ["rab", "bang"], ["bizz", "buzz"]]
b = a.transpose
  #=> [["bar", "rab", "bizz"], ["bang", "bang", "buzz"]]
c = b.map(&:uniq)
  #=> [["bar", "rab", "bizz"], ["bang", "buzz"]]
d = c.to_h
  #=> <array of hashes shown above>


text:
Q: Questions about several Class Descriptions when reading the following OpenFoam class descriptions I am not able to understand all of it:

*

*Time: Class to control time during OpenFOAM simulations that is also
the top-level objectRegistry.

*Clock:Read access to the system clock with formatting.

*CpuTime:Starts timing CPU usage and return elapsed time from start.

*TimePaths: A class for addressing time paths without using the Time
class.

*objectRegistry: Registry of regIOobjects.

*regIOobjects:regIOobject is an abstract class derived
from IOobject to handle automatic object registration with
the objectRegistry.

*IOobject: IOobject defines the attributes of an object for which
implicit objectRegistry management is supported, and provides the
infrastructure for performing stream I/O.

Questions:

*

*What means top-level objectRegistry?

*what means with formatting?

*Does "Starts timing CPU usage" mean the same as "Starts CPU usage"?

*What is meant with "adressing time paths" and what is a "time path"
in this context?

*What is a ObjectRegistry class good for?

*What is meant with "automatic object registration with the
objectRegistry"?

*What is meant with "objectRegistry management" ?

Hopefully some people with more programming knowledge will be able to teach me something here :) .
greetings
streight


text: Q: Exporting image with array band in Google Earth Egnine I am familiar with exporting multiband imagery in Google Earth Engine in TFRecord format. When reading it back in python, I generate a feature dictionary giving it the proper shape (number of features and patch size) and it is easily done. However, I could not do the same for an image containing a simple 1-D array at each pixel and I could not find any example or good documentation anywhere. Can anyone help me?


text:
Q: Map from $\mathbb{C}^2$ to $\mathbb{A}_{\mathbb{Q}}^2$ I was doing Exercise 3.2 I on Ravi Vakil's notes on Algebraic Geometry:
consider the map of sets $\phi: \mathbb{C}^2 \rightarrow \mathbb{A}_{\mathbb{Q}}^2$ defined as follows. $(z_1, z_2)$ is sent to the prime ideal of $\mathbb{Q}[x,y]$ consisting of polynomials vanishing at $(z_1, z_2)$.
I am confused about if the map is well defined or not. Suppose I take
the point $(1,1) \in \mathbb{C}^2$. I feel like I could map it to $(x-1, y-1)$ or $(x-y)$ as they are both
prime ideals in $\mathbb{Q}[x,y]$... I think I am missing something or not interpreting the question right or something. I would appreciate any help with this. Thanks!

A: @you-sir-33433 has given you a good answer. But, if you haven't already, it might be worth noting that we can also consider this map as the morphism of affine schemes induced by the natural inclusion $\mathbb Q[x,y] \hookrightarrow \mathbb C[x,y]$ (which makes it immediate that this map is well-defined). To see this, observe that the morphism $\operatorname{Spec}\mathbb C[x,y] \rightarrow \operatorname{Spec}\mathbb Q[x,y]$ associated to inclusion is given by $\mathfrak p  \mapsto \mathfrak p \cap \mathbb Q[x,y]$. So, the maximal ideal $\mathfrak m$ ideal of a point in $ p \in \mathbb C^2$ is sent to precisely the set of all elements of $\mathbb Q[x,y]$ which vanish at $p$.

A: You would map $(1,1)$ to $(x-1,y-1)$, since this is the prime ideal consisting of all polynomials vanishing at $(1,1)$.  For example, $(x-y) \subset (x-1,y-1)$.


text:
Q: How to pass callback function from Java to Kotlin class I have a Kotlin class as follows (this is a sample for ease, hence it doesn't 'do' anything useful)
class MyKotlinClass (private val handleSomeCallBack: (ByteArray) -> Unit) {
    private val someBuffer = BytesBuilder()

    fun myFunction(bytesList: List<Byte>) {
        handleSomeCallBack(someBuffer.toArray())
    }
}

I want to call this code from a java class, hence, in that class I have the following declared:
public MyJavaClass() {
    messageParser = new MyClass(handleSomeCallback);
}

The callback method being passed is:
private void handleSomeCallback(byte[] dataBytes) {

}

(MyClass is correctly declared within the file)
The issue I'm having is that I can't figure out how to pass the callback to the constructor of MyKotlinClass.
I have tried a variety of things including
messageParser = new MyClass(handleSomeCallback(byte[] dataBytes));
messageParser = new MyClass(this::handleSomeCallback(byte[] dataBytes));
But no matter what I try I receive an error.
I believe the answer is to do with lambdas but I can't quite see what the syntax should be for calling this from Java.

A: You can go with something like this:
MyKotlinClass instance = new MyKotlinClass(byteArray -> {
    // your code
    return Unit.INSTANCE;
});

Or use Unit as return type of your separate method like suggested by @ADM here
You just need to add
compileOptions {
  sourceCompatibility JavaVersion.VERSION_1_8
  targetCompatibility JavaVersion.VERSION_1_8
}

to your android block in app build.gradle


text:
Q: How to make camera movement in a pygame 3d engine from scratch? I am new to matrices and matrix transformations and other things. I am making a 3d engine of my own in pygame using 2d, but I ran into a problem. I can't get my engine to implement camera movement and it only does camera rotation. Here is my code:
window.py: The custom window class
from .general_imports import *

class Py3dWindow:
    def __init__(self, title=None, width=800, height=600,):
        self.title = title
        self.window = None
        self.width = width
        self.height = height
        self.meshes = []
        self.events_assinged = False

        self.projection_matrix = np.matrix([
            [1, 0, 0, 0],
            [0, 1, 0, 0],
            [0, 0, 1, 0],
            [0, 0, 0, 1]
        ])
        print(self.projection_matrix)

        self.camera = [
            [0, 0, 0, 0],
            [0, 0, 0],
            75, # fov
            1, # near
            1000 # far
        ]

    def add_mesh(self, mesh):
        self.meshes.append(mesh)

    def translate_matrix(self):
        angle_x = math.radians(self.camera[1][0])
        angle_y = math.radians(self.camera[1][1])
        angle_z = math.radians(self.camera[1][2])

        pos_x = self.camera[0][0]
        pos_y = self.camera[0][1]
        pos_z = self.camera[0][2]

        rotation_z = np.matrix([
            [int(np.cos(angle_z)), -int(np.sin(angle_z)), 0, 0],
            [int(np.sin(angle_z)), int(np.cos(angle_z)), 0, 0],
            [0, 0, 1, 0],
            [0, 0, 0, 1]
        ],)

        rotation_y = np.matrix([
            [int(np.cos(angle_y)), 0, int(np.sin(angle_y))],
            [0, 1, 0, 0],
            [-int(np.sin(angle_y)), 0, int(np.cos(angle_y))],
            [0, 0, 0, 1]
        ])

        rotation_x = np.matrix([
            [1, 0, 0, 0],
            [0, int(np.cos(angle_x)), -int(np.sin(angle_x)), 0],
            [0, int(np.sin(angle_x)), int(np.cos(angle_x)), 0],
            [0, 0, 0, 1],
        ])

        position_matrix = np.matrix([
            [1, 0, 0, pos_x],
            [0, 1, 0, pos_y],
            [0, 0, 1, pos_z],
            [0, 0, 0, 1],
        ])

        self.projection_matrix = np.dot(rotation_z, np.dot(rotation_y, rotation_x)) * position_matrix

        print(self.projection_matrix)

    def init_window(self):
        pygame.init()
        self.window = pygame.display.set_mode((self.width, self.height), pygame.RESIZABLE)
        pygame.display.set_caption(self.title)
        self.running = False

    def run(self,):
        self.running = True
        while self.running:
            self.draw()
            self.events(pygame.event.get())
            self.update()
            self.translate_matrix()
        pygame.quit()

    def events(self, events):
        for event in events:
            if event.type == pygame.QUIT:
                self.running = False
        if self.events_assinged:
            self._events(events)

    def update(self,):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running = False

    def draw(self,):
        self.window.fill((0, 0, 0))
        for mesh in self.meshes:
            mesh.draw(self.window)
        pygame.display.update()
        time.sleep(0.001)

    def on_events(self, func):
        self._events = func
        self.events_assinged = True

    def on_update(self, func):
        self.update = lambda: func()

    def on_draw(self, func):
        self.draw = lambda: func()

mesh.py: Mesh class
from .general_imports import *

class Mesh:
    def __init__(self, parnet):
        self.points = []
        self.parent = parnet

    def add_point(self, position):
        position = [position[0] * 100, position[1] * 100, position[2] * 100, 1]
        self.points.append(np.matrix(position))

    def draw(self, window):
        for point in self.points:
            p = (point - self.parent.camera[0])
            p = np.reshape(p, (4, 1))
            projection = np.dot(self.parent.projection_matrix, p)
            projection = projection.tolist()
            x = projection[0][0]
            y = projection[1][0]
            pygame.draw.circle(window, (255, 255, 255), (int(x) + window.get_width() / 2 - 100, int(y) + window.get_width() / 2- 100) , 1)

demo.py: The demo
# Py3D demo

from Py3D.__init__ import *
import random

win = Py3dWindow(title="Py3D")
win.init_window()

mesh_ = Mesh(win)

side = 1

for i in range(-side, side):
    for j in range(-side, side):
        for k in range(-side, side):
            mesh_.add_point((i, j, k))

win.add_mesh(mesh_)

def move(events):
    for i in events:
        if i.type == 771:
            if i.text == 'w':
                win.camera[0][2] -= 1
            if i.text == 's':
                win.camera[0][2] += 1
            if i.text == 'a':
                win.camera[0][0] -= 1
            if i.text == 'd':
                win.camera[0][0] += 1

def rotate():
    win.camera[1][0] = 45
    win.camera[1][1] = 45
    win.camera[1][2] = 45

win.on_events(move)
win.on_update(rotate)
win.run()

Errors
ValueError: shapes (4,4) and (1,4) not aligned: 4 (dim 1) != 1 (dim 0)

A: As you pointed out, in the translate_matrix function, your rotation_y variable is declared incorrectly:
rotation_y = np.matrix([
    [int(np.cos(angle_y)), 0, int(np.sin(angle_y))], # <--- missing an item
    [0, 1, 0, 0],
    [-int(np.sin(angle_y)), 0, int(np.cos(angle_y))], # <--- missing an item
    [0, 0, 0, 1]
])

The first and third items are declared with only 3 items, while the 2nd and third items, and all of the items of rotation_x and rotation_z, are made with 4 items. Obviously that can't work, as a matrix is supposed to be rectangular.

A: The solution I found
In the translate_matrix function, I forgot to add four indexes to the whole array in rotation_y. That's it! It worked fine!


text:
Q: Creating an invocable apex class sending email with optional send from I am trying to set up an invocable apex class to send an email to a contact with merge fields from other record ID types with an optional variable to set the sender. I have looked at this question for guidance, however, am having trouble using variable sender.
Can someone have a look over what I have done and offer some suggestions?
global class Invocable_SendEmail {

    global class DataWrapper {

        @InvocableVariable(label='Record ID' required=true)
        public String recordID;
        @InvocableVariable(label='Email Template ID' required=true)
        public String emailTemplateID;
        @InvocableVariable(label='Contact ID' required = true)
        public String contactID;
        @InvocableVariable(label='Sender Email' required=false)
        public String sender;
    }

    @invocableMethod(label='Send Email to Applicant')
    global static void sendMailToLead (List<DataWrapper> passedData) {

        // Send the email:

        for (DataWrapper dw: passedData) {

            // Get the email template
            EmailTemplate selectedTemplate = [SELECT Id FROM EmailTemplate WHERE Id =: dw.emailTemplateId];

            // Get sender details
                // fetch Org Wide Email Address if sender is filled
                if (dw.sender != null) {
                    OrgWideEmailAddress[] owea = [select Id from OrgWideEmailAddress where Address = sender];
                    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                    if ( owea.size() > 0 ) {
                        mailToSend.setOrgWideEmailAddressId(owea.get(0).Id);
                    }
                }

            // Create SingleEmailMessage object and set the target and template.
            Messaging.SingleEmailMessage mailToSend = new Messaging.SingleEmailMessage();
            mailToSend.setTargetObjectId(dw.contactID);
            mailToSend.setWhatId(dw.recordID);
            mailToSend.setTemplateID(selectedTemplate.Id);

            // Send the email and debug results
            List<Messaging.SendEmailResult> sendResults = Messaging.sendEmail(new List<Messaging.Email> { mailToSend });
            System.debug(sendResults[0]);

        }

    }

}

A: Fixed the issues,
global class Invocable_SendEmail {
global class DataWrapper {

    @InvocableVariable(label='Record ID' required=true)
    public String recordID;
    @InvocableVariable(label='Email Template ID' required=true)
    public String emailTemplateID;
    @InvocableVariable(label='Contact ID' required = true)
    public String contactID;
    @InvocableVariable(label='Sender Email' required=false)
    public String sender;
}

@invocableMethod(label='Send Email to Applicant')
global static void sendMailToLead (List<DataWrapper> passedData) {

    // Send the email:

    for (DataWrapper dw: passedData) {

        // Get the relevant template based on the supplied ID.
        EmailTemplate selectedTemplate = [SELECT Id FROM EmailTemplate WHERE Id =: dw.emailTemplateId];

        // Create SingleEmailMessage object and set the target and template.
        Messaging.SingleEmailMessage mailToSend = new Messaging.SingleEmailMessage();
        mailToSend.setTargetObjectId(dw.contactID);
        mailToSend.setWhatId(dw.recordID);
        mailToSend.setTemplateID(selectedTemplate.Id);

        // Get sender details
            // fetch Org Wide Email Address if sender is filled
            if (dw.sender != null) {
                OrgWideEmailAddress[] owea = [select Id from OrgWideEmailAddress where Address =: dw.sender];
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                if ( owea.size() > 0 ) {
                    mailToSend.setOrgWideEmailAddressId(owea.get(0).Id);
                }
            }

        // Send the email and debug results
        List<Messaging.SendEmailResult> sendResults = Messaging.sendEmail(new List<Messaging.Email> { mailToSend });
        System.debug(sendResults[0]);

    }

}

}
Fix includes updating line:
OrgWideEmailAddress[] owea = [select Id from OrgWideEmailAddress where Address = sender];
to:
OrgWideEmailAddress[] owea = [select Id from OrgWideEmailAddress where Address =: dw.sender];
And putting // Get sender details section after creation of SingleEmailMessage object

A: You can bulkify your code so it will work with more than 10 records (e.g. if you use an import wizard or data loader tool).
@invocableMethod(label='Send Email to Applicant')
global static void sendMailToLead (List<DataWrapper> passedData) {
    // Validate email tempaltes and org-wide addresses
    Map<String, Id> emails = new Map<String, Id>();
    Set<Id> emailTemplateIds = new Set<Id>();
    for(DataWrapper wrapper: passedData) {
        emails.put(wrapper.emailTemplateId, null);
        emailTemplateIds.add(wrapper.sender);
    }
    for(OrgWideEmailAddress address: [SELECT Address FROM OrgWideEmailAddress WHERE Address = :emails.keySet()]) {
        emails.put(address.Address, address.Id);
    }
    emailTemplateIds.retainAll(
        new Map<Id, EmailTemplate>([SELECT Id FROM Emailtemplate WHERE Id = :emailTemplateIds]).keySet()
    );
    // Build emails
    Messaging.Email[] mailsToSend = new Messaging.Email[0];
    for (DataWrapper dw: passedData) {
        if(!emailTemplateIds.contains(dw.emailTemplateId)) {
            continue; // Invalid email template?
        }
        Id orgSenderId = emails.get(dw.sender);
        Messaging.SingleEmailMessage mailToSend = new Messaging.SingleEmailMessage();
        // fetch Org Wide Email Address if sender is filled
        if (orgSenderId != null) {
            mailToSend.setOrgWideEmailAddressId(orgSenderId);
        }

        // Create SingleEmailMessage object and set the target and template.
        mailToSend.setTargetObjectId(dw.contactID);
        mailToSend.setWhatId(dw.recordID);
        mailToSend.setTemplateID(selectedTemplate.Id);
        mailsToSend.add(mailToSend);
    }
    // Send the emails
    List<Messaging.SendEmailResult> sendResults = Messaging.sendEmail(mailsToSend);
}


text:
Q: Excel IF, Then Statement I am looking to IF 2 separate columns then count 2 other columns. So I am trying to define information from shift so 1st, 2nd, 3rd & then individual departments, so when you IF let's say 1st Shift for Dept #4100 then count Column P & Q.
I've googled this formula and played, but I feel I'm missing something. Almost like this should be a IF with a Then statement, but that didn't seem to work
=SUMIF("K2:k500,1")&("N2:N500,4100") then (P2:P500+Q2:Q500)

A: There's a far quicker / parsimonious way than 'multiple sumifs' statements which you appear to have adopted based upon commentary above:
sum((p2:q500)*(k2:k500=1)*(n2:n500=4100))

What's nice about this set up is that it's far quicker/easier to extend to encompass multiple adjacent columns - so long as you make sure to have corresponding 'criteria' (e.g. k2:k500=1, n2:n500=4100 etc.) specified as req. (the alternative of attempting to write out 10,20, or even 50 sumifs seems somewhat daunting, let alone tractable from an audit/review viewpoint...


text:
Q: Is there a naming convention for methods in Common Lisp? I found it painful to do object-oriented programming in Common Lisp. The main problem is the naming of methods.Please see the code below.
(defclass foo () ())

(defmethod action ((object foo))
  (write-line "hello"))

(defclass bar () ())

(defmethod action ((object bar) boo)
  t)

(print
 (action (make-instance 'foo)))

(print
 (action (make-instance 'bar) 1))

The two action methods are not different implementations for a same generic function. They have the same name by accident.
But Common Lisp requires all methods with the same name to have the same numbers of parameters.
In order to avoid the name conflicts, I usually prefix the methods' names with the class names, such as foo-action and bar-action. But that causes the code to be quite verbose in real program, e.g. (lengthy-class-name-do-something some-variable).
Other object-oriented programming languages, like C++ and Java, do not have such problems. You can write that like some_variable.do_something() with no name conflicts in them.
So I'd like to know if there exists any better solution to the problem described above?

A: The key difference is indeed that methods are methods on generic functions. They are not methods on classes.
This may sound like words for words' sake. But it should highly influence your naming choices. "Action" is a pretty bland name for a generic function. When foo acts, what does it actually do? When bar acts, what does it actually do?
If action truly is the best name, would having a foo:action and a bar:action make sense (that is, an action in the foo package, and one in the bar package)? They are different GF's. With, of course, the drawback that it is no longer as easy as just calling action on them.
And that hints towards "you don't need a method, you can just use a function", because you don't need a method to do things with classes in CL.

A: Those two methods are methods of the same generic function, and so they absolutely must have compatible lambda lists.  Otherwise, there is no guarantee that the resolution of the effective method combination (which happens at runtime, as this is runtime polymorphism) has an unambiguous  result.
You omitted the defgeneric form, which should give you a warning from the compiler.
This only works in Java as you described because you conventionally put each class into its own namespace.  But here, you are working in one namespace and expect the same name (symbol) to have two entirely different meanings.  This doesn't work.
In Java parlance, every generic function is its own interface.
Aside, to illustrate the advantage: you don't need to attach implementations of this interface to a class, but you can have even multiple classes to dispatch (at runtime) on.  This makes e. g. the notoriously complex Visitor pattern obsolete.
Imagine for a moment such a syntax in Java at toplevel (i. e. as an alternative to class or interface:
method IAction (Foo foo, Bar bar) {
  action (Foo foo, Bar bar) {
    return something(...);
  }
}

This method would be invoked when at runtime a call to IAction#action gets objects of class Foo and Bar.  Of course, this doesn't exist in Java (and seems prohibitively difficult to add).

A: There is no general naming convention for methods likewise there's no naming convention for functions. The situation of name conflict may be resolved differently depending on the context.

*

*The first question is: if there are just two methods that have different functionality and clashing names, why not consider ordinary functions (with different names). If you name some function (ordinary or generic) in a very generic way, it implies that this function is ubiquitous (which is quite a rare case). In such a situation, the set of inputs for this function should be more or less uniform (even if it has different methods for different argument types), but you can use &key (and &allow-other-keys) to deal with the variation of additional arguments. However, in most cases, giving more distinct names to two semantically different actions will be more beneficial for future code maintenance.

*If you still want to retain the same name for two or more different actions, you can place the relevant code in different packages. That may be quite reasonable to do for code that has different functionality. Now, you won't be able to import both functions at once into some other package because it will still result in a name clash. But you'll be able to use package-prefixed names: p1:foo and p2:foo (if both of them will be exported). Packages are a standard Lisp way of resolving unavoidable name conflicts. In this context, we can say that in many other object-oriented languages classes play this role.

A: Here is how you're defining your class
(defclass foo () ())

The trouble is that you're not defining your class with any slots. Like this:
(defclass foo ()
    ((action
        :initarg :action
        :accessor action)))

This adds action which is an accessor (both getter and setter) for class foo,
The :initarg word :action is the word used to give it a value when initializing.
(defvar my-foo-class (make-instance 'foo :action "bar" ))

We can then access the value
(action my-foo-class)
output> "bar"

I suggest checking out this tutorial on CLOS


text:
Q: How run a specific GraphQLTestCase test in graphene-django? import json
from graphene_django.utils.testing import GraphQLTestCase
from swapi.schema import schema
class FirstTestCase(GraphQLTestCase):
fixtures = ['app/fixtures/unittest.json']
GRAPHQL_SCHEMA = schema
def test_people_query(self):
    response = self.query(
        '''
            query{
              allPlanets {
                edges{
                  node{
                    id
                    name
                  }
                }
              }
            }
        ''',
    )

    self.assertResponseNoErrors(response)

    content = json.loads(response.content)
    self.assertEqual(len(content['data']['allPlanets']['edges']), 61)

def test_two(self):
    # Some test logic
    pass

I have the above code, I only need to run the test_two. I already know this command python manage.py test runs all tests. Please help thank you in advance

A: You can run an individual test method using syntax like:
python manage.py test my_app.tests.FirstTestCase.test_two

(Where my_app.tests is the Python dotted path to your file containing FirstTestCase.) More info in the Django documentation for Running tests.


text:
Q: Oracle/SQL - Cursor gives Not Enough Memory for CONNECT BY operation When I create a cursor cur as follows -
CURSOR cur IS SELECT Rownum r FROM dual WHERE mod(rownum,2)=1 CONNECT BY rownum <15;

It gives me an error ORA-30009: Not enough memory for CONNECT BY operation.
I tried reducing the limit to even 3, but it didn't work.
It might be of help to know that I'm running a loop using this cursor as-
FOR cur_inst IN cur
    LOOP
        dbms_output.put_line(cur_inst.r);
    END LOOP;

The loop runs one time and prints 1. However the above error is thrown after the first iteration.
Also, if I remove the WHERE clause, the query is executed correctly as-

A: Apply your filtering logic after connecting the rows! otherwise, it would mess up the connection.
CURSOR cur IS
select r  from
(SELECT Rownum r FROM dual CONNECT BY rownum <15
 )
 where mod(r,2)=1


text:
Q: Display temperature as a color with C#? Someone knows an algorithm that gets temperatue in Kelvin/Celsius and returns RGB?
Like in thermal cameras.
I found some links :
http://www.brucelindbloom.com/index.html?Eqn_XYZ_to_T.html
http://www.fourmilab.ch/documents/specrend/specrend.c

But i cant figure what XYZ color is ?

I only have temperature in Celsius..
i can convert it to any temperature Temperature Conversion Formulas
UPDATE:
Blackbody Color Datafile
I have found this.. but those Kelvin degrees are impossible.. i mean
red suppose to be hot.. so why 8000k is blue and 1000k is red...

A: I realize this is a two-year old thread, but I had the same predicament.
I took the data from the color table and did applied piece-wise 5th order polynomial fitting using Numpy.polyfit in Python. From those coefficients I was able to come up with the C# function below. R-squared values for the fits are close to or exceed 0.999. It has less than .01% error through most of its domain, but it does have a couple of points where it is closer to 3%. Should be good enough for most situations though.
private Color blackBodyColor(double temp)
{
    float x = (float)(temp / 1000.0);
    float x2 = x * x;
    float x3 = x2 * x;
    float x4 = x3 * x;
    float x5 = x4 * x;

    float R, G, B = 0f;

    // red
    if (temp <= 6600)
        R = 1f;
    else
        R = 0.0002889f * x5 - 0.01258f * x4 + 0.2148f * x3 - 1.776f * x2 + 6.907f * x - 8.723f;

    // green
    if (temp <= 6600)
        G = -4.593e-05f * x5 + 0.001424f * x4 - 0.01489f * x3 + 0.0498f * x2 + 0.1669f * x - 0.1653f;
    else
        G = -1.308e-07f * x5 + 1.745e-05f * x4 - 0.0009116f * x3 + 0.02348f * x2 - 0.3048f * x + 2.159f;

    // blue
    if (temp <= 2000f)
        B = 0f;
    else if (temp < 6600f)
        B = 1.764e-05f * x5 + 0.0003575f * x4 - 0.01554f * x3 + 0.1549f * x2 - 0.3682f * x + 0.2386f;
    else
        B = 1f;

    return Color.FromScRgb(1f, R, G, B);
}

A: If get you right you are looking for a theoretical background on XYZ color space

A: Color temperature is based on the actual color of light emitted from something (theoretically, an "ideal black body") that emits light based solely on its temperature.
Some examples of this kind of light source: if you have an electric stove element that is glowing red, it might be around 1000K.  A regular incandescent bulb filament is around 2700K, and the sun is roughly 5700K.  All three are fair approximations of a "black body"; they emit a particular spectrum of light based on their actual temperature.
Many artificial light sources are not actually the "temperature" of the light they emit (and their spectra are generally not black-body spectra, either...).  Instead, their "temperature" rating is the temperature a theoretical black body would have to be in order to emit light of that color.  There are also colors that cannot be generated by a black body:  light which is greenish or purplish compared to a more "natural"-looking black body illumination.
As mentioned in one of the comments, the kind of thermal camera displays you are probably thinking about are all false-color.  In a false-color display, the colors are chosen for convenience only: so, for a thermal camera they might choose a "hot"-looking red for warm, and "cold"-looking blue for cold.  But, they could just as easily choose a range from black to white, or fuschia to green.
Because false-color displays are arbitrary, you really need to check the color key to a particular image or system if you want to estimate the temperature (scientific images should generally have some kind of color key for this purpose).  If you have no color key, and no documentation on how the image was generated, you are out of luck.

A: The best option is to use an image with GetPixel:

private void UpdateTemp()
{
    Bitmap temps = (Bitmap)Properties.Resources.temp;
    if (curTemp >= 0)
    {
        int i = curTemp;
        if (i < 0)
            i = 0;
        if (i > temps.Width-1)
            i = temps.Width-1;
        this.BackColor = temps.GetPixel(i, 10);
    }
}

Or building an array. Source
    private static Color[] colors =
    {
        Color.FromArgb(155, 188, 255), //    40000
        Color.FromArgb(155, 188, 255), //    39500
        Color.FromArgb(155, 188, 255), //    39000
        Color.FromArgb(155, 188, 255), //    38500
        Color.FromArgb(156, 188, 255), //    38000
        Color.FromArgb(156, 188, 255), //    37500
        Color.FromArgb(156, 189, 255), //    37000
        Color.FromArgb(156, 189, 255), //    36500
        Color.FromArgb(156, 189, 255), //    36000
        Color.FromArgb(157, 189, 255), //    35500
        Color.FromArgb(157, 189, 255), //    35000
        Color.FromArgb(157, 189, 255), //    34500
        Color.FromArgb(157, 189, 255), //    34000
        Color.FromArgb(157, 189, 255), //    33500
        Color.FromArgb(158, 190, 255), //    33000
        Color.FromArgb(158, 190, 255), //    32500
        Color.FromArgb(158, 190, 255), //    32000
        Color.FromArgb(158, 190, 255), //    31500
        Color.FromArgb(159, 190, 255), //    31000
        Color.FromArgb(159, 190, 255), //    30500
        Color.FromArgb(159, 191, 255), //    30000
        Color.FromArgb(159, 191, 255), //    29500
        Color.FromArgb(160, 191, 255), //    29000
        Color.FromArgb(160, 191, 255), //    28500
        Color.FromArgb(160, 191, 255), //    28000
        Color.FromArgb(161, 192, 255), //    27500
        Color.FromArgb(161, 192, 255), //    27000
        Color.FromArgb(161, 192, 255), //    26500
        Color.FromArgb(162, 192, 255), //    26000
        Color.FromArgb(162, 193, 255), //    25500
        Color.FromArgb(163, 193, 255), //    25000
        Color.FromArgb(163, 193, 255), //    24500
        Color.FromArgb(163, 194, 255), //    24000
        Color.FromArgb(164, 194, 255), //    23500
        Color.FromArgb(164, 194, 255), //    23000
        Color.FromArgb(165, 195, 255), //    22500
        Color.FromArgb(166, 195, 255), //    22000
        Color.FromArgb(166, 195, 255), //    21500
        Color.FromArgb(167, 196, 255), //    21000
        Color.FromArgb(168, 196, 255), //    20500
        Color.FromArgb(168, 197, 255), //    20000
        Color.FromArgb(169, 197, 255), //    19500
        Color.FromArgb(170, 198, 255), //    19000
        Color.FromArgb(171, 198, 255), //    18500
        Color.FromArgb(172, 199, 255), //    18000
        Color.FromArgb(173, 200, 255), //    17500
        Color.FromArgb(174, 200, 255), //    17000
        Color.FromArgb(175, 201, 255), //    16500
        Color.FromArgb(176, 202, 255), //    16000
        Color.FromArgb(177, 203, 255), //    15500
        Color.FromArgb(179, 204, 255), //    15000
        Color.FromArgb(180, 205, 255), //    14500
        Color.FromArgb(182, 206, 255), //    14000
        Color.FromArgb(184, 207, 255), //    13500
        Color.FromArgb(186, 208, 255), //    13000
        Color.FromArgb(188, 210, 255), //    12500
        Color.FromArgb(191, 211, 255), //    12000
        Color.FromArgb(193, 213, 255), //    11500
        Color.FromArgb(196, 215, 255), //    11000
        Color.FromArgb(200, 217, 255), //    10500
        Color.FromArgb(204, 219, 255), //    10000
        Color.FromArgb(208, 222, 255), //    9500
        Color.FromArgb(214, 225, 255), //    9000
        Color.FromArgb(220, 229, 255), //    8500
        Color.FromArgb(227, 233, 255), //    8000
        Color.FromArgb(235, 238, 255), //    7500
        Color.FromArgb(245, 243, 255), //    7000
        Color.FromArgb(255, 249, 253), //    6500
        Color.FromArgb(255, 243, 239), //    6000
        Color.FromArgb(255, 236, 224), //    5500
        Color.FromArgb(255, 228, 206), //    5000
        Color.FromArgb(255, 219, 186), //    4500
        Color.FromArgb(255, 209, 163), //    4000
        Color.FromArgb(255, 196, 137), //    3500
        Color.FromArgb(255, 180, 107), //    3000
        Color.FromArgb(255, 161,  72), //    2500
        Color.FromArgb(255, 137,  18), //    2000
        Color.FromArgb(255, 109,   0), //    1500
        Color.FromArgb(255,  51,   0), //    1000
    };

A: The above function overestimate red color when temp > 10000 K. Colors turn to purple when temp>14000. I refitted the data with 7th order polynomials. The coefficients of should be:
def temp_to_rgb(temp):
    t = temp/1000.

    # calculate red
    if t < 6.527:
        red = 1.0
    else:
        coeffs = [  4.93596077e+00,  -1.29917429e+00,
                    1.64810386e-01,  -1.16449912e-02,
                    4.86540872e-04,  -1.19453511e-05,
                    1.59255189e-07,  -8.89357601e-10]
        tt = min(t,40)
        red = poly(coeffs,tt)
    red = max(red,0)
    red = min(red,1)

    # calcuate green
    if t < 0.85:
        green = 0.0
    elif t < 6.6:
        coeffs = [ -4.95931720e-01,   1.08442658e+00,
                   -9.17444217e-01,   4.94501179e-01,
                   -1.48487675e-01,   2.49910386e-02,
                   -2.21528530e-03,   8.06118266e-05]
        green = poly(coeffs,t)
    else:
        coeffs = [  3.06119745e+00,  -6.76337896e-01,
                    8.28276286e-02,  -5.72828699e-03,
                    2.35931130e-04,  -5.73391101e-06,
                    7.58711054e-08,  -4.21266737e-10]
        tt = min(t,40)
        green = poly(coeffs,tt)
    green = max(green,0)
    green = min(green,1)

    # calculate blue
    if t < 1.9:
        blue = 0.0
    elif t < 6.6:
        coeffs = [  4.93997706e-01,  -8.59349314e-01,
                    5.45514949e-01,  -1.81694167e-01,
                    4.16704799e-02,  -6.01602324e-03,
                    4.80731598e-04,  -1.61366693e-05]
        blue = poly(coeffs,t)
    else:
        blue = 1.0
    blue = max(blue,0)
    blue = min(blue,1)

    return (red,green,blue)

Here poly(coeffs,x) = coeffs[0] + coeffs[1]*x + coeffs[2]*x**2 + ...
Sorry I am not familiar with C# but you can easily read the codes.
The error is within only 0.5% for most cases and at most 1.2% for red in temp = 6600 K. High order polynomials are adopted here so red and green must keep constant for temp > 40000 K, otherwise strange things will happen.


text:
Q: Using residuals as noise and EWMA to fill in missing values? For some time series data on booking transactions, I am attempting to use EWMA (exponential weighted moving average) + randomized residuals to fill in the missing data. That is, after calculating the EWMA from the datapoints, I calculate the residuals, then resample the residuals and then add them to the ewma to fill in the null totalBookings. TotalBookings are expressed in $ and their distribution is lognormal.
This approach follows the same one used in Chapter 12 of Allen Downey's book, "thinkstats"
I follow his approach for my own dataset:
def FillMissing(daily, span=30):
    """Fill missing values with exponentially weighted moving average"""
    daily = daily.set_index('bookedDate')
    dates = pd.date_range(daily.index.min(), daily.index.max())
    reindexed = daily.reindex(dates)

    ewma = reindexed.totalBookings.ewm(span=span).mean()
    resid = (reindexed.totalBookings - ewma).dropna()

    fake_data = ewma + np.random.choice(resid, len(reindexed), replace=True)
    reindexed.totalBookings.fillna(fake_data, inplace=True)

    reindexed['ewma'] = ewma
    reindexed['resid'] = reindexed.totalBookings - ewma

    return reindexed

The problem I'm encountering is that fake_data can take on negative values because some of the residuals are so large. How should I handle these cases and proceed?


text:
Q: Error while running Angular 7 in Google App Script (Google doc Add-on) I am trying to run Angular cli generated default app, in Google doc add-on (Google App Script) project, As in google app script only .gs and .html files are allowed i have moved all angular's build JS files in script tags and added them as html. But when i run the add-on i am getting this error
userCodeAppPanel:6862 Uncaught Error: Can't resolve all parameters for ApplicationModule: (?).
    at syntaxError (userCodeAppPanel:6862)
    at CompileMetadataResolver.push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver._getDependenciesMetadata (userCodeAppPanel:22346)
    at CompileMetadataResolver.push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver._getTypeMetadata (userCodeAppPanel:22241)
    at CompileMetadataResolver.push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver.getNgModuleMetadata (userCodeAppPanel:22109)
    at CompileMetadataResolver.push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver.getNgModuleSummary (userCodeAppPanel:21920)
    at userCodeAppPanel:22033
    at Array.forEach (<anonymous>)
    at CompileMetadataResolver.push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver.getNgModuleMetadata (userCodeAppPanel:22021)
    at CompileMetadataResolver.push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver.getNgModuleSummary (userCodeAppPanel:21920)
    at userCodeAppPanel:22006

Directory structure in google app script project

my modified index.html for app-script
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>AngularAddOn</title>

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>

  <?!= include('runtime.js');?>
  <?!= include('vendor.js');?>
  <?!= include('styles.js');?>
  <?!= include('main.js');?>
  <?!= include('polyfills.js');?>
  <?!= include('es2015-polyfills.js');?>

  <app-root></app-root>
</body>
</html>

And here is my code.gs file
function myFunction() {

}
function onOpen(e) {
  DocumentApp.getUi().createAddonMenu()
    .addItem('Manage Citations', 'showSidebar')
    // .addItem("test dialog", 'showDialog')
    .addToUi();
}

function showSidebar() {
  var html = HtmlService.createTemplateFromFile('index').evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME).setTitle('wizdom.ai');
  DocumentApp.getUi().showSidebar(html);
}

function include(filename) {
  return HtmlService.createHtmlOutputFromFile(filename).getContent();
}

Is it impossible to run angular in google add-on? or am i missing something?
i already tried adding following to polyfills.ts but no luck
import 'core-js/es7/reflect';

Thanks

A: According to this other question,  How to use AngularJS within Google Apps Script someone suggested to

"move the angular.js include script statement into the head section"

I see yours are in the body section. Change them to the head and it should work.


text:
Q: WIX add new file to shared component I have a shared dll, we'll call it Utility.dll that is installed by multiple products. In my WIX file I install Utility.dll as a separate component. Now version 2.0 of the Utility.dll references an additional dll, UtilityUtility.dll which will need to be installed alongside.
For my first attempt integrating UtilityUtility.dll I created a new WIX component containing the new dll.
This causes problems in the following scenario
1) User installs Product 1 { Utility.dll 1.0 }
  2) User installs Product 2 { Utility.dll 2.0, UtilityUtility.dll 2.0 }
  3) User uninstalls Product 2 { Utility.dll 2.0 }
Now when a user uses the Utility.dll it will fail when it can't find the referenced UtilityUtility.dll
This led me to add UtilityUtility.dll to the original component which prevents UtilityUtility.dll from being removed in the previous scenario but comes with its own issue.
1) User installs Product 1 { Utility.dll 1.0 }
2) User installs Product 2 { Utility.dll 2.0, UtilityUtility.dll 2.0 }
3) User uninstalls Product 2 { Utility.dll 2.0, UtilityUtility.dll 2.0 }
4) User uninstalls Product 1 { UtilityUtility.dll 2.0 }
UtilityUtility.dll is orphaned as it does not get removed by the Product 1 uninstall (it did not exist in the component when it was originally installed).
Do I have any other options here?
Thanks

A: Unless you can update Product 1 (which I presume isn't completely possible), I think you are screwed. IMHO, the Component Rules are the worst thing about the Windows Installer. This link to an old blog post of mine sums up most of it. Your case is a bit different than what is described there but the results are expected.
I think you get to pick the lesser of two evils.

A: I'm not 100% certain... but I think adding the second .DLL to the original component is likely a "violation" of the component rules. Take a look at: http://blogs.msdn.com/robmen/archive/2003/10/18/56497.aspx
From what I gather from the Wix crowd the leading "best practice" is to have each file as an individual component.
What are your plans for upgrades (in msi terms: major, minor, patch)? If I recall correctly minor upgrades are not allowed to muck with component definitions. No idea about patches.
You might also want to worry about repair.

A: Can you reproduce the second issue? In theory after you install Product 2 component version becomes 2.0. After step 3 component version is still 2.0. When user uninstalls product 1 in step 4 Windows Installer knows how to remove both Utility.dll 2.0 and UtilityUtility.dll 2.0.
Update: I was wrong, sorry.

A: I have run into this problem myself. I agree with @rbobby and I further submit that the fact that you can envision this broken user scenario is proof that you are violating the rules. You should only update a shared component if it is fully and completely compatible. If Duck 2.0 doesn't quack or swim, make up a new name for it.
In your case, you have Utility.dll 1.0 and Utility.dll 2.0, but they are only the "same component" in that they do similar things in a different way. Utility.dll 2.0 should really be called UtilityPlus.dll 1.0.
Sorry, I know it's probably not the answer you wanted to hear, but engineering case is clear.

A: This is long back but having the same issue now. Is a possible solution to use the same UpgradeGUID for all related products? The document on MSDN says that

The UpgradeCode property is a GUID representing a related set of
products. The UpgradeCode is used in the Upgrade Table to search for
related versions of the product that are already installed

This sound like multiple products in different MSI files may share the same upgrade code and so avoid conflict situations.


text:
Q: Android Studio : how do 'dependencies' work ? How to update a library? I am a newbie with Android Studio.
I integrated this library https://github.com/2dxgujun/AndroidTagGroup in my project.
All what I had to to is to follow their instructions and thus to add the following line in the 'app gradle file' (in the 'dependencies'):
compile 'me.gujun.android.taggroup:library:1.4@aar'

Then click on "sync" at the top right of the Android Studio window of the app gradle file. It works properly ; great !
Nevertheless, I don't really understand the following things :
1) What does "library:1.4@aar" mean ? Is it a single library file ? Where is it located in the folders ?
2) How does Android Studio know where this library is located on my disk ? I copied/pasted the library folder at the root of the folder where I have all my Android projects on my disk ; is it the default location where Android Studio goes to find libraries ?
3) How should I do if I want to modify something in this library and recompile it ? For example, I modified  13sp (in styles.xml) to  30sp, recompiled the library with "./gradlew assembleDebug" (as mentioned on GitHub) but it has no impact on my project even after a clean/build...why ? By the way what does "./gradlew assembleDebug" mean ?
Thanks for your help !

A:
What does "library:1.4@aar" mean ? Is it a single library file ?

Pulls an AAR file from JCenter or Maven
In the case of a Maven project, this dependency is expressed in a pom.xml format like so
<groupId>me.gujun.android.taggroup</groupId>
<artifactId>library</artifactId>
<version>1.4</version>

As you see, you have the artifact id as "library" and "1.4" is just a version name.

How does Android Studio know where this library is located on my disk ?

In the build.gradle file, you'll have a section like this.
// Top-level build file where you can add configuration options common to all sub-projects/modules.

allprojects {
    repositories {
        jcenter()
        // mavenCentral()
        // mavenLocal()    // Some variant of these. 'jcenter' is the default
    }

Depends on your OS, but there is a .gradle directory or .m2 directory in your home folder where all Gradle & Maven dependencies are downloaded.
For example, Gson, for me is at
~/.m2/repository/com/google/code/gson/gson/2.6.2/gson-2.6.2.jar

if I want to modify something in this library and recompile it ?

Probably too broad for this post, but you would no longer use
compile 'me.gujun.android.taggroup:library:1.4@aar'

Because that will always use the Github sources, not your changes. You would need to clone the repo and use compile project feature of Gradle.

What does "./gradlew assembleDebug" mean ?

Run the assemble task for the debug build type of your project using the Gradle wrapper.


text:
Q: is there any library that assert text is in English? I want to build a form for the user to fill and submit.
There is a free text field.
How can i check the user didn't enter garbage, like:
fhskdjfhjkdshfkjhsd
maybe like checking 3 random words are in English dictionary
or any other language i choose to check (Hebrew for the moment)

A: you could check out this library
https://code.google.com/p/language-detection/
or the ones mentioned in the answer to this question:
How to detect language of user entered text?


text:
Q: Get year from Django DateTimeField with values() What is the correct way to extract the year from a DateTimeField?
Example given:
class Article(models.Model):
    title = models.CharField(_('title'), max_length=250)
    slug = models.SlugField(_('slug'), max_length=250, unique=True, default='', blank=True)
    content = models.TextField(_('content'))
    author = models.ForeignKey(settings.AUTH_USER_MODEL)
    categories = models.ManyToManyField(Category)
    tags = models.ManyToManyField(Tag)
    created = models.DateTimeField(_('created'), default=timezone.now)
    publish_date = models.DateTimeField(_('publish date'), blank=True, null=True)

    STATUS_ARTICLE = (
        ('DRAFT', _('draft')),
        ('PUBLISHED', _('published'))
    )

    status = models.CharField(_('status'), max_length=100, choices=STATUS_ARTICLE, default='DRAFT')

class ExtractMonth(Func):
    template = "EXTRACT(MONTH FROM %(expressions)s)"

    def __init__(self, *expressions, **extra):
        extra['output_field'] = models.SmallIntegerField()
        super().__init__(*expressions, **extra)

Trying to get a list of all the years, and number of articles per year:
result = Article.objects.filter(status='PUBLISHED').annotate(Year=ExtractYear('publish_date')).values('Year').annotate(dcount=Count('Year'))

This results in the following error:
near "FROM": syntax error

The resulting query is:
SELECT EXTRACT(YEAR FROM "articles_article"."publish_date") AS "Year", COUNT(EXTRACT(YEAR FROM "articles_article"."publish_date")) AS "dcount" FROM "articles_article" WHERE "articles_article"."status" = PUBLISHED GROUP BY EXTRACT(YEAR FROM "articles_article"."publish_date"), "articles_article"."created" ORDER BY "articles_article"."created" DESC

A: This is what I've ended up doing. Gocht's solution looks like it should work but I had problems (Django 1.10, SQLite) with Django handling the results. I didn't want to use RawSQL but that's the only thing I've got to work.
try:
    from django.db.models.functions import ExtractYear
except ImportError:
    from django.db.models.expressions import RawSQL

qs = Article.objects.filter(...)

try:
    # Django >= 1.10
    qs = qs.annotate(Year=ExtractYear('publish_date'))
except NameError:
    # Django < 1.10
    qs = qs.annotate(Year=RawSQL(
            "CAST(SUBSTR('table_name'.'publish_date', 1, 4) AS integer)",
            ()
         ))

results = qs.values('Year').annotate(dcount=Count('Year'))

This makes Year an integer, rather than a string; remove the CAST(... AS integer) if you want a string.
You'll need to change the table_name to be whatever your model's database table is.
I'm not sure the except NameError is the best way to handle that, but I couldn't work out how better to handle this.

A: I found this question a lot interesting. So I was playing with console for a while.
I followed the links provided by @Ivan and got this:
from django.db.models import F, Func
from django.db.models.functions import Substr

Article.objects.filter(...).annotate(_date=Func(F('publish_date'), function='LOWER'))
                           .annotate(publish_year=Substr('_date', 1, 4))
                           .values('publish_year')

This should give your the year as an string.
Note: this will work if in _date you get something like this: u'2015-08-24 09:45:16', if you get a different string, you can change the indexes in Substr('_date', 1, 4). You can see what kind of string you get in _date by adding it in .values('_date', 'publish_year').
I hope this helps.
Extra:
This is the result I got:
[{'date': datetime.datetime(2015, 8, 24, 9, 45, 16), 'date3': u'2015', 'date2': u'2015-08-24 09:45:16'}, ...]

In this case, date3 is for me the final result.
EDIT:
Generated SQL:
>>> print MyModel.objects.all().annotate(date2=Func(F('date'), function='LOWER')).annotate(date3=Substr('date2', 1, 4)).query
SELECT `app_model`.`id`, `app_model`.`date`, LOWER(`app_model`.`date`)
AS `date2`, SUBSTRING(LOWER(`app_model`.`date`), 1, 4)
AS `date3` FROM `app_model` ORDER BY `app_model`.`created` ASC

A: Django has a build in function TruncYear
Try this
result = Article.objects.filter(status='PUBLISHED').annotate(Year=TruncYear('publish_date'))

A: This should work:
result = Article.objects.filter(status='PUBLISHED').values('publish_date__year').annotate(dcount=Count('id'))

publish_date__year extract the year value of the field.


text:
Q: Solving a system of quadratic equations. Solve for real $(a, b, c)$ satisfying
$$ab + bc + ca = 1$$
$$a^2 − 2b^2 = 1$$
$$2b^2 − 3c^2 = 1$$
I try isolating $a$, but it leads to a very complicated expression in $a$.

A: If one can show that $c=0$ then $a=\sqrt{2},b=\sqrt{2}/2$ as noted in Tim's answer. I found it a bit involved to actually prove $c=0$ is a consequence of the equations. (I'd be interested in a simpler proof of $c=0$ than the following.) Label the equations:
[1] $ab+bc+ca=1,$
[2] $a^2-2b^2=1,$
[3] $2b^2-3c^2=1.$
From [2] and [3] we can see neither of $a,b$ are zero, since we seek real solutions. From [2] alone we can also see that neither of $a+b,a-b$ are zero, otherwise [2] says $-t^2=1$. We'll need these nonzero properties later.
Now since the right sides are all equal, we have from [1] and [2] that
$$c(a+b)+ab=a^2-2b^2,$$
and moving the $ab$ to the right side and factoring gives
$$c(a+b)=(a+b)(a-2b).$$
As noted we know $a+b$ is nonzero, so we now have $c$ in terms of $a,b$ as
$$c=a-2b.$$
We next use that [2] and [3] have the same right sides, so that on replacing $c$ as above,
$$a^2-2b^2=2b^2-3(a-2b)^2,$$ and the difference factors to obtain:
$$4(a-2b)(a-b)=0.$$
Having noted that we know $a-b$ is not zero we arrive at $a-2b=0$, i.e. $c=0$ as desired.
EDIT: I removed a phrase "luckily the $b^2$ terms cancel" since they didn't.
Also as others have noted, in case $c=0$ the signs on $a,b$ may be changed for another solution, so that the system has actually two triples $(a,b,c)$ for solutions.

A: As one approach try putting the first equation $ab+bc+ca=1$ in terms of $c$ then set $c$ equal to $0$. It will look kind of complicated as you put it with variable terms under radical signs but you will see that the result equals $1$. From there the other two solutions for $a$ and $b$ will be apparent. Real solutions are $$a=\sqrt{2}$$ $$b=\frac{\sqrt{2}}{2}$$ $$c=0$$ to check your work.$$ab=\frac{\sqrt{18c^4 +18c^2+4}}{2}$$
$$bc=\frac{c\sqrt{2+6c^2}}{2}$$
$$ca=\frac{2c\sqrt{2+3c^2}}{2}$$


text:
Q: Function call and user input file name with extentions in Python I am new to Python. After finishing the tutorials I am trying to build small apps to improve myself. I am making little console diary program as you can see.
import os
def greetings():
    name = input("Who is using program : ")
    return "Hello "+name+" welcome to the diary."
def what_todo():
    print("What would you like to do today ?")
    print("Taking notes (1) \nReading notes (2)")
    choice = int(input())
    return choice
def do():
    if what_todo() == 1:
        file_name = input("Please name today's diary :  ")
        f = open(file_name,"w")
        f.write(input())
        f.close()
    elif what_todo() == 2:
        file_name = input("Which diary you want to read : ")
        if os.path.isfile(file_name):
            f = open(file_name,"r")
            for x in f:
                print(x)
        else:
            print("file does not exist")

def main():
    print(greetings())

    do()

if __name__ == "__main__":
    main()

I have three things to ask :

*

*When i call if what_todo() == 1: it runs the what_todo() function
but I only want the return of the what_todo() function and of course print's are repeating itself in the second call for elif statement. Is there a way to do it or I am going all wrong? Like unnecessary functions or anything else.

*I am getting user input for file name it is okay but I want to create
file as a ".txt" or maybe ".data". How do I do that?

*One last thing. As a newbie, if you would like to share I want your
opinion about the code I wrote or advice about it.

Thank you for your answers.
Output :
This is the output :
hilal@crescent:~/Diary$ python diary.py
Who is using program : L
Hello L welcome to the diary.
What would you like to do today ?
Taking notes (1)
Reading notes (2)
1
Please name today's diary :  a
aaa
hilal@crescent:~/Diary$ python diary.py
Who is using program : L
Hello L welcome to the diary.
What would you like to do today ?
Taking notes (1)
Reading notes (2)
2
What would you like to do today ?
Taking notes (1)
Reading notes (2)
2
Which diary you want to read : a
aaa

A: *

*Yes, those prints are redundant as their only purpose seems to show  messages to the user. If you want to show some text to the user upon input-ing input value, you should pass the string as input function's argument e.g.:
input("What would you like to do today ?")

Also, I would check for TypeError when changing type to int from str in choice = int(input()) e.g. when the input is foobar.

*Filenames are strings, so you can append the desired extension to the user inputted file name string e.g.:
final_file_name = '{}.txt'.format(file_name)

will get a .txt extension. Also check if user has not inputted the extension already.

*If you're interested in a thorough review, please ask on CodeReviewSE

A: You are asking for input in what_todo() and you only want to call it once. So you need to call it once and save the value it returns. There are lots of ways to do that but here is one:
def main():
    print(greetings())
    action = what_todo()
    do(action)

def do(action):
    if action == 1:

You can add an extension to the filename like this:
file_name = input("Please name today's diary :  ") + ".txt"

Though in a real program you would also need to verify that the input filename is valid.

A: You could run the what_todo() function and save the returned value in a variable. Then later use the variable in the if conditions.
regarding filename - once you get an input from the user, you can append any extension you want by using the + operator. file_name is just a string. So you can update it as you see fit -
file_name += '.txt'


text:
Q: Click a button on a Browser native Javascript pop up alert window Selenium/C# There is a Delete button on the form, once it gets clicked, a Browser native pop up alert window is asking to confirm the action. How can I click on OK since I can't see any html of that window?

A: To click OK on an alert:
driver.SwitchTo().Alert().Accept();

A:
window.confirm() returns Boolean value.

true if OK is clicked and false if Cancel is clicked.

console.log(window.confirm());


text:
Q: Python Flask Refresh table every 60 seconds I have posted my flask code below. I want to refresh table data every 60 seconds. Setinterval function is included in html . But however its not refreshing. I am not figuring out exact issue in ajax/Javascript. Please somebody can help to figure out the issue.
App.py:
app = Flask(__name__)
app.config['SECRET_KEY'] = 'dsfd'
mysql = MySQL()
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = 'pwd'
app.config['MYSQL_DATABASE_DB'] = 'db'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)
eachcur = ["A","B","C","D"]

@app.route('/', methods= ['GET'])
def display_deals():

    conn = mysql.connect()
    c = conn.cursor()
    data = ((),)
    for curren in eachcur:
      query = "SELECT * from "+curren+" ORDER BY Currid DESC LIMIT 1"
      c.execute(query)
      data = data + c.fetchall()

    conn.close()

    return render_template("dashboard.html", data=data)

if __name__ == '__main__':
    app.run(debug=True)

dashboard.html:
<!doctype html>

{% for row in data %}

    {% for d in row %}
        {{ d }}
    {% endfor %}

{% endfor %}

Console Output:
jquery.min.js:4 XHR finished loading: POST "http://localhost:5000/".
send @ jquery.min.js:4
ajax @ jquery.min.js:4
(anonymous) @ (index):7
setInterval (async)
(anonymous) @ (index):6
17:21:45.516 jquery.min.js:4 [Violation] 'load' handler took 334ms

A: There are a couple of things wrong with your code:

*

*You are using .val() where you should be using .html()
.val() is used to set the value of things like input fields, not overwrite entire DOM objects. You should be using .html() here instead.

*You are assigning non-html data to #table-box
Your for statement generating the table is only going to run on page load. You need to regenerate all of the table rows in the AJAX  .done() handler.
See my example below that fixes both of these issues.
<!doctype html>

{% for row in data %}

    {% for d in row %}
        {{ d }}
    {% endfor %}

{% endfor %}

EDIT: It doesn't look like you have a route/controller set up the handle the AJAX request to POST /. You should try something like this:
@app.route('/json', methods= ['GET'])
def display_deals_json():
  conn = mysql.connect()
  c = conn.cursor()
  data = ((),)
  for curren in eachcur:
    query = "SELECT * from "+curren+" ORDER BY Currid DESC LIMIT 1"
    c.execute(query)
    data = data + c.fetchall()
  conn.close()
  return json.dumps(data)

You will need to update your AJAX command to:
$.ajax({
  type: "GET",
  url: "/json",
})


text:
Q: How to convert cv::Mat type from CV_16UC1 to CV_8UC1 I have a cv::Mat image of type CV_16UC1 and I need it in CV_8UC1, so I can run cv::integral on it. I am not worried about overflow during the conversion - essentially I just want to bulk convert the image from unsigned short to unsigned char.
I asked elsewhere and someone suggested cvtColor, but I don't know what conversion code to use.

A: How about using Mat::convertTo? Documentation
A quick example: (not sure if you need scalefactor though, since I haven't tried)
Your16Image.convertTo(outputImage, CV_8UC1, scalefactor)

A: You can use cv::convertScaleAbs which directly set your output matrix to unsigned char.


text:
Q: Pigeon hole subset problem For a given N numbers labeled from 1-N,
we need to pick M numbers such that there are atleast K pairs of numbers(x,y) which statisfy x+y=N+1?
can anyone help me out with this... please?

A: Hint:
Can you figure it out for $k=1$?  What is the worst case scenario for not having any pair of numbers that add up to $N+1$?  (further hint: think about what happens if you add two numbers smaller than $\frac{N}{2}$?)  What about $k=2$? Can you make a conjecture based on these for larger $k$ as well?
In general and for proof, for $N$ even, try thinking in terms of modulo $\frac{N}{2}$.  Try to generalize this idea to $N$ odd as well.  (If not comfortable with wording things using modular arithmetic, simply note that each number in $1,\dots,N$ is paired with exactly one other number such that they add to $N+1$, and such a pairing is symmetric.)

A: If N is even then minimum numbers required to form k pairs are int(N/2 + K)
if N is odd then  minimum numbers required to form k pairs are int(N/2 + K + 1)


text: Q: How can I view which ports are blocked and why the other ports are activated on a Linux Bridge? This was one of the questions I had on an exam about computer networks (translated from dutch). The answer should be one single command.


text:
Q: How do I plot just the outer edge of a curve in Excel? I have data that looks like this:
Risk    Return
9.2      6.5
7.8      3.4
6.4      5.2
.
.
.
.
10.2     6.4

I created a scatter plot that looks like this:

How can I get just the outer edge of the curve? I'd like it to look like this:

A: Maybe pick off the co-ordinates for points that are nearest to the upper boundary, plot just those co-ordinates as a separate series and add a suitable trend line. Or create the envelope values from the formula shown by plotting the selection with Display Equation on chart. Simplified example:

A: Let say your Risk is in column A rows 2-100, and Return is column B rows 2-100.
Create a column C with this formula (its an array formula so use Ctrl-Shift-Enter):
=MAX(IF($A$2:$A$100<=A2,$B$2:$B$100))=B2
Copy down to all of column C.  This formula is saying get the max return, of all points with the same or lower risk than this point.  If that return is equal to this points return then TRUE.
Now create columns D and E and with formulas like:
=IF(C2,A2,0)
=IF(C2,B2,0)
This will 0 out the points that are not part of the frontier, you can then plot these points.


text:
Q: SQL TRIM VERY SLOW We have millions of records in table. We have a column that has white-spaces after the text. We have tried the following:
update schema.table_name
set column_name = trim(column_name);

It is very slow 20+ hours. We have tried to use the WHERE clause and the RTRIM too however it made no difference. What can be done to speed up this trim?

A: What is making the query slow is probably not the trim() but rather having to update every row.    The trim() would be slow if the column is particularly large.
Assuming that only a few rows need to be updated, then you can filter with a where:
update schema.table_name
    set column_name = trim(column_name)
    where column_name like ' %' or column_name like '% ';

If most rows need to be updated, then reconstructing the table is often the fastest solution:
create table temp_table_name
    select . . ., -- all the other columns
           trim(column_name) as column_name
    from t;

truncate table table_name;  -- BACKUP THE TABLE FIRST!

insert into table_name
    select *
    from temp_table_name;

The exact syntax might vary by database.  Also, this is tricky if you have auto-incrementing columns.  But the idea is the same.


text:
Q: QueryStringOrHeaderApiVersionReader in my dotnet web api is not working I'm trying to use this code to enable API versioning in query string parameter and header. However i get an error saying "The type or namespace name 'QueryStringOrHeaderApiVersionReader' could not be found (are you missing a using directive or an assembly reference?) [Api_Versioning]" and i'm unable to figure out what exactly the issue is.

A: QueryStringOrHeaderApiVersionReader is no longer supported.
If you need it you will have to downgrade your Microsoft.AspNetCore.Mvc.Versioning nugget package to version 1.1.
Refer this wiki: https://github.com/microsoft/aspnet-api-versioning/wiki/API-Version-Reader#query-string-or-header-api-version-reader--110-


text:
Q: CException in Yiistrap .Alias bootstrap.helpers.TbHtml" is invalid In my web application I need to implement yiistrap .But I am getting this error and unable to rectify.Alias "bootstrap.helpers.TbHtml" is invalid. Make sure it points to an existing directory or file.
My config/main.php
    <?php

// uncomment the following to define a path alias
// Yii::setPathOfAlias('local','path/to/local-folder');

// This is the main Web application configuration. Any writable
// CWebApplication properties can be configured here.
return array(
    'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',
    'name'=>'My Web Application',
'aliases' => array(
        'bootstrap' => realpath(__DIR__ . '/protected/config/extensions/bootstrap'), // change this if necessary
    ),
    // preloading 'log' component
    'preload'=>array('log'),

    // autoloading model and component classes
    'import'=>array(
        'application.models.*',
        'application.components.*',
'bootstrap.helpers.TbHtml',
    ),

    'modules'=>array(
        // uncomment the following to enable the Gii tool

        'gii'=>array(
            'class'=>'system.gii.GiiModule',
            'password'=>'xxxx',
            // If removed, Gii defaults to localhost only. Edit carefully to taste.
            'ipFilters'=>array('127.0.0.1','::1'),
'generatorPaths' => array('bootstrap.gii'),
        ),

    ),

    // application components
    'components'=>array(
        'user'=>array(
            // enable cookie-based authentication
            'allowAutoLogin'=>true,
        ),
        // uncomment the following to enable URLs in path-format

            'urlManager'=>array(
                'urlFormat'=>'path',
                 'showScriptName' => false,
                 'rules'=>array(
                       '/'=>'/view',
                            '//'=>'/',
                         '/'=>'/',
                             ),
                                ),

        /*
        'db'=>array(
            'connectionString' => 'sqlite:'.dirname(__FILE__).'/../data/testdrive.db',
        ),
                 */
        // uncomment the following to use a MySQL database

        'db'=>array(
            'connectionString' => 'mysql:host=localhost;dbname=electrical',
            'emulatePrepare' => true,
            'username' => 'root',
            'password' => 'xxxxx',
            'charset' => 'utf8',
        ),

        'errorHandler'=>array(
            // use 'site/error' action to display errors
            'errorAction'=>'site/error',
        ),
        'log'=>array(
            'class'=>'CLogRouter',
            'routes'=>array(
                array(
                    'class'=>'CFileLogRoute',
                    'levels'=>'error, warning',
                ),
                // uncomment the following to show log messages on web pages
                /*
                array(
                    'class'=>'CWebLogRoute',
                ),
                */
            ),
        ),
'bootstrap' => array(
            'class' => 'bootstrap.components.TbApi',
        ),
    ),

    // application-level parameters that can be accessed
    // using Yii::app()->params['paramName']
    'params'=>array(
        // this is used in contact page
        'adminEmail'=>'webmaster@example.com',
    ),
);

Any body kindly help me with this. I am unable to proceed.

A: first of all define this in your /config/main.php and make bootstrap alias
 Yii::setPathOfAlias('bootstrap', dirname(__FILE__) . '/../extensions/bootstrap');

TbHtml is not one of standard bootstrap widgets, maybe you need to get it from somewhere else and put it in directory /extensions/bootstrap/helpers/TbHtml, maybe it's one of YiiStraps helpers


text:
Q: Replace value in dataframe on condition with a different type in python I'm trying to replace values in my dataframe lower than 5.5 with 'insufficient' and higher than 5.5 with 'sufficient' using the following code:
import numpy as np

df['test'] = np.where(df['grade'] > 5.5, 'sufficient', 'insufficient')

This gives me the following error:
TypeError: '>' not supported between instances of 'str' and 'float'
How do I replace my float dataframe values with strings?

A: Check df['grade'] include string type values.
Or, try df['grade'].astype(float) > 5.5


text:
Q: AJAX call not acting as expected I am attempting to use an AJAX call to render a partial view when a radio button is selected. I have searched and have tried what appears to be the best approach via comments on Stack. When I click the radio button, I have no result, in debug, I get a Status Code: 500 Internal Server Error? Any assistance would be great.
Partial View Names:
_BOA.cshtml
_TA.cshtml
_MNB.cshtml

View:
                <td class="radio-inline">
                    @Html.RadioButton("bankSelect", "MNBConvert", false, new { @class = "radioMNB" }) MNB Conversion
                    @Html.RadioButton("bankSelect", "BOAConvert", false, new { @class = "radioBOA" }) BOA Conversion
                    @Html.RadioButton("bankSelect", "TAConvert", false, new { @class = "radioTA" }) TA Conversion
                </td>

Javascript:
<script src="~/Scripts/jquery-1.9.0.js"></script>
   <script type="text/javascript">
        $(function () {
            $("[name=bankSelect]").on('change', function () {
               // var $radio = $(this);
                var checked = $("input[name='bankSelect']:checked").val();

                $.ajax({
                    url: '@Url.Action("GetBankToConvert", "Home")',
                    data: checked,
                    type: 'GET',
                    success: function (data) {
                        $("#renderPartialView").html(data);
                    }
                });
            });
        });
    </script>

Controller:
[HttpGet]
        public ActionResult GetBankToConvert(string bankSelect)
        {
            if (bankSelect == "MNBConvert")
            {
                return PartialView("_MNB");
            }
            else if (bankSelect == "BOAConvert")
            {
                return PartialView("_BOA");
            }
            else
            {
                return PartialView("_TA");
            }
        }

A: You aren't sending a key/value pair as data, only a value.
Try
$.ajax({
    url: '@Url.Action("GetBankToConvert", "Home")',
    data: {bankSelect: checked },
    type: 'GET',
    success: function (data) {
        $("#renderPartialView").html(data);
    }
});

WHen in doubt, inspect the actual request in network tab of browser dev tools to see exactly what is sent and received among all the other components of a request


text:
Q: Why does debian not set the pam module called pam_limits.so in the file /etc/pam.d/su I am using debian version 7.4
The /etc/pam.d/su file there
does not enable pam_limits.so
the snippet is:
# Sets up user limits, please uncomment and read /etc/security/limits.conf
# to enable this functionality.
# (Replaces the use of /etc/limits in old login)
# session    required   pam_limits.so

Why is that ?
googling for it, got articles like
https://my.vertica.com/docs/6.0.x/HTML/index.htm#14567.htm
On some systems the pam module called pam_limits.so is not set in the file /etc/pam.d/su. When it is not set, it prevents the conveying of limits (such as open file descriptors) to any command started with su -

In particular, the HP Vertica init script would fail to start HP Vertica because it calls the Administration Tools to start a database with the su - command. This problem was first noticed on Debian systems, but the configuration could be missing on other Linux distributions.

To resolve this issue, modify the install_vertica script and append this line to the /etc/pam.d/su file:

session required pam_limits.so

A: The default (no limits) work for most people. For most single-purpose, single-user, and small multi-user systems the limits module is not required because you won't be hitting any of them; for that matter, a small system user encountering a ulimit related error would probably not know how to handle it. What's more, /etc/security/limits.conf does not come preconfigured because there's no way of knowing what your needs will be so you would still have to adjust configuration to set limits. Might as well save some (scant) resources for most people and let the few who need it turn the feature on.