text:
Q: javascript global variable undefined inside function sometime For some reason a JavaScript global variable becomes undefined inside function when set to local variable sometime.
For example, in below sample the local often become "undefined".
Could anyone of you please advise?
I'm expecting the value of "local" is "global value" in functionB() and functionC() or doStringProcessingA() and doStringProcessingB(). The value of "local" is "undefined". I'm sure there's no other places assign value or set undefined to global in anywhere.
I've checked below links, but it seems not related.
'Hoisted' JavaScript Variables
and
Why a variable defined global is undefined?
functionA() was called by onClick event from HTML.
 var global;

 function functionA(){
    global = "global value";
 }

 function functionB(){
    var local = global;
    doStringProcessingA(local);
 }

 function functionC(){
    var local = global;
    doStringProcessingB(local);
 }

    Submit

A: Can you try this
var global = "text";
function  functA{
     var lol = global;
     dostringprocess(local);
  }

I think in your code it taking local variable from FunctioA,
and also you can check in two ways

*

*open console and see the log what error it showing exactly by putting some log message in every function in function stack

*you can use closure

A: since your global value is defined under a functionA() so when you call a function B() or functionC() directly your global variable does not contain any value.. so for this you have to intialise the value of global variable..
var global="Earth";                      // now it will not give any errror

 function functionA(){
    global = "global value";
 }

 function functionB(){
    var local = global;
    doStringProcessingA(local);
 }

 function functionC(){
    var local = global;
    doStringProcessingB(local);
 }

    Submit


text:
Q: Positioning context on table-cell element in Firefox Usually, we can set a parent element to be the context for a child's absolute positioning, as follows:
#parent {
    position: relative;
}

#child {
    position: absolute;
    top: 0;
    left: 0;
}

This all works fine, but when the parent has its display property set to table-cell, it doesn't work in Firefox. The positioning context for the child element will be the closest positioned ancestor above its parent.
Of note, this works everywhere else. Tested in IE8, IE9, Safari, Chrome & Opera.
See the fiddle here: http://jsfiddle.net/RZ5Vx/
Also, see this fiddle with the parent's display set to inline-block, which does work in Firefox.

So, is this a bug? If so, is there anyway to work around it?

A: A table-cell is meant to be inside a table, so:
See this working Fiddle!
div {
    display: table;      /* this line */
    line-height: 28px;
    padding: 0 20px;
    background: #ddd;
    position: relative;
}

Note:
Since you don't have a table in there, set it.
You can see this quirksmode for the The display declaration.

EDITED
From the W3C recommendation :: Tables it reads

The computed values of properties 'position', 'float', 'margin-*', 'top', 'right', 'bottom', and 'left' on the table element are used on the table wrapper box and not the table box; all other values of non-inheritable properties are used on the table box and not the table wrapper box. (Where the table element's values are not used on the table and table wrapper boxes, the initial values are used instead.)

This is not a bug, is more like a status-bydesign thing! Please see this!

EDITED
To include the work around placed on the comment as requested on the question:

So, is this a bug? If so, is there anyway to work around it?

Possible work around are:
Wrap the element with a div as position:relative; See Fiddle!
#wrapper {
    position: relative;
}

Note: most practical solution!
Wrap the inner elements with a div as position:relative; See Fiddle!
#innerWrapper {
    position: relative;
}

Note: requires some definitions from the original element to be declared on the innerWrapper!

redpajama_set_name: RedPajamaStackExchange


text:
Q: What's the point of splitting related topics into different sites/communities? Similar questions have been asked here before, for example Are we creating too many different Stack Exchange sites?, but my point is slightly different. I have absolutely no issue with the total number of SE sites, on the contrary. However I don't think it makes sense to split topics if there is a high correlation between the users interested in these topics. Here is an example which I personally find a bit annoying:
The Stack Exchange site which I find most helpful and in which I am most active is Stack Overflow. Now as a professional software developer I am not only interested in coding issues but also in topics like project management or requirements engineering which become more and more off-topic in Stack Overflow.
To ask or answer such questions, I need to go to other sites like Project Management or Programmers. Especially the boundary between Stack Overflow and Programmers is far from being obvious.
I would find it much more convenient to have all software development related topics on one site. Of course this is my personal opinion but many questions, answers and comments give me the impression that lots of other users have the same issue.
Am I missing something?

A: Fair enough; you're a programmer, so you might be interested in (for example) project management issues. But what if you're a project manager with little to no interest in programming?
Project management isn't just (or even primarily) a programming discipline. If a professional project management specialist has a question about "Calculating Operations Cost from Man-Hours and Set $/hr" (for example), there is no logical path to seek out something like Stack Overflow: a place for programmers.
So we create a site for this under-served audience explicitly.
Most of the non-Stack Overflow sites were created because the communities showed there was an ecosystem of questions that were not covered on our existing sites. That is how the network was created.
Related: Apparently this is a duplicate


text:
Q: Regex and beautifulsoup returning "'NoneType' object is not callable" error I am trying to implement the regex query at http://regexr.com/3dnut.
This is my code so far:
from bs4 import BeautifulSoup
import urllib
r = urllib.urlopen('http://www.indeed.com/resumes?q=banking&l=london&co=GB&start=0').read()
soup = BeautifulSoup(r, "lxml")
letters = soup.search("\/r\/([^:\/\s]+)\/(\w+)")
print letters

I am expecting an array of matches, but instead I get the following error message:
Traceback (most recent call last):
  File "D:/cv-scraper/main.py", line 5, in <module>
    letters = soup.search("\/r\/([^:\/\s]+)\/(\w+)")
TypeError: 'NoneType' object is not callable

How do I resolve it?

A: There is no search() method in BeautifulSoup. The reason it throws this particular error is that the dot-notation has a special meaning - it is a shortcut to find(). soup.search is basically transformed into soup.find("search") which would try to find a tag search. It fails and returns None which then is being called. What you ended up with is None("\/r\/([^:\/\s]+)\/(\w+)") which fails with None is not callable, of course.


text:
Q: Proof of Lemma preceding Principle of Condensation of Singularities Under the Wikipedia page for the Principle of Uniform Boundedness, we have the Corollaries of the Uniform Boundedness Principle. The third of these relates to the Principle of Condensation of Singularities (a question on which was asked here), however, the following Lemma is given as part of a motivation to achieving that result:

[Let $X,Y$ be Banach Spaces and] Let $L(X, Y)$ denote the continuous operators from $X$ to $Y$, with the operator norm. If the collection $F$ is unbounded in $L(X, Y)$, then by the uniform boundedness principle we have:
      $$R = \{ x ∈ X   :   \sup_{ T ∈ F} ‖ T x ‖_Y = ∞ \} ≠ ∅$$

I'm just wondering how exactly the Principle of Uniform Boundedness is being applied here; I was thinking to try and prove the result by contradiction and invoking PUB, but I don't see a way to do this without needing to make two deliberate incorrect hypotheses - in particular to assume that what we want to show holds for all $x\in X$ and to assume that for these $x$ we have that $\sup_{ T ∈ F} ‖ T x ‖_Y < ∞$. However, that would only tell us that either one of the hypotheses were wrong.
I wonder if instead one should work directly from Baire Category theory to prove the result - and indeed, perhaps, if that is what is meant by saying that UBP ensures this.
Could somebody give me a hint to set me on the right path to proving this result - as to whether I should use PUB directly, or work from Baire?

A: Suppose that $R =\emptyset.$
If $x \in X$, then $x \notin R$, hence there is $c_x \ge 0$ such that
$||Tx||_Y \le c_x$ for all $T \in F.$
The $PUB$ gives that $\{||T||: T \in F\}$ is bounded, a contradiction.


text:
Q: What could be alternative for hashmap as it's consuming more memory I am using hashmap in my application at various places. Especially while executing jobs, it's consuming more memory resulting in server shutdown. what could be the replacement of hashmap in spring-boot application.

A: Hashmap itself is very standard and there isn't a more memory efficient replacement that is equivalent in general. You'll need to change how you are using it. You haven't provided enough information to diagnose the issue but my first guess would be that you might be storing things in maps which make them "reachable" after they are needed, thus preventing the Garbage Collector from freeing up the memory?


text:
Q: textvariables in Tkinter for Python 3 I'm using a tkinter Entry widget in a temporary window to collect information from a user.  I want to be able to use that information for a variety of things: rewrite it in a Label in another window, convert it to an integer for calculations, get its value as a string for writing to a file, and so on.  In this stripped down code, I've got two text variables, and I've used quotation marks to name one and not the other.  As I understand it, using the quotation marks is wrong--the variable without the quotation marks works correctly with get, for example.  The trouble is that the one without the quotation marks doesn't copy correctly when I use it as the textvariable for a Label in a different window.  What am I missing here?
from tkinter import *
from tkinter import ttk

root = Tk()

sheetid = StringVar
sheetname = StringVar

def dosheet():
    sheet = Toplevel(root)
    ttk.Label(sheet, text="Sheet ID:").grid(row=0)
    ttk.Label(sheet, textvariable=sheetid, font=(11)).grid(row=1)
    ttk.Label(sheet, text="Sheet Name:").grid(row=2)
    ttk.Label(sheet, textvariable="sheetname", font=(11)).grid(row=3)
#end dosheet

def new():
    def finish():
        start.destroy()
        dosheet()

    start = Toplevel(root)
    start.title("New sheet dialog")
    ttk.Label(start, text="Sheet ID:").grid(row=1)
    ttk.Entry(start, textvariable=sheetid).grid(row=2)
    ttk.Label(start, text="Sheet name:").grid(row=3)
    ttk.Entry(start, textvariable="sheetname").grid(row=4)
    ttk.Button(start, text="Close", command=finish).grid(row=5)
#end new

main = ttk.Frame(root, padding="16 12 12 12")
main.grid()

ttk.Label(main, text="Start new sheet:").grid()
ttk.Button(main, text="New", command=new).grid()

root.mainloop()

A: What about this:
# with () you call the class to create a new object (instance) of it.
sheetid = StringVar('sheetid')
sheetname = StringVar('sheetname')

def dosheet():
    #                             remove "
    ttk.Label(sheet, textvariable=sheetname, font=(11)).grid(row=3)

What does it do?


text:
Q: Customize app.config when deploying on windows azure I have some issues when I'm trying to deploy my application in windows azure.
I have several services in windows Azure. One of them is called Automaton. It needs to connect to the SQL Azure database. So I've saved the ConnectionString (I'm using Entity Framework) in the app.config and I added some transformation depending on the build configuration.
I've found a plugin that helps to add transformations to any XML file called slow cheetah (http://www.hanselman.com/blog/SlowCheetahWebconfigTransformationSyntaxNowGeneralizedForAnyXMLConfigurationFile.aspx)
When I'm trying to compile the code under different build configuration, I can see that the config file is well transformed (I've checked in the bin folder of my project). But, when I'm deploying the project in windows azure, I can see that my role is cycling due to database connection issue. So, I think the app.config isn't transformed when the solution is compiled for deployment purpose.
Do you have any information that can help me to fix my issue? Thanks

A: You would need to modify the azure project to tell it to update the app.config every time you package , as in the following tutorial step 10 -
http://wely-lau.net/2012/03/14/applying-config-transformation-app-config-in-windows-azure-worker-role/

A: Have you thought about using Service Configuration instead?
You can read the connection string during startup of the worker role, you can defined separate configuration for Cloud and Local, and you can also change the configuration values via the Management Portal.
See RoleEnvironment Class on MSDN.


text:
Q: BinaryFormatter.Deserialize "unable to find assembly" after ILMerge I have a C# solution with a referenced dll (also C# with the same .Net version).  When I build the solution and run the resulting exe, without merging the exe and the referenced dll, everything works fine.
Now I want to merge these into one exe.  I run ILMerge and everything appears to work ok.  I try to execute the exe and it seems to run just fine until it tries to deserialize an object defined in the referenced dll.
using (Stream fstream = new FileStream(file_path, FileMode.Open))
{
    BinaryFormatter bf = new BinaryFormatter();
    return bf.Deserialize(fstream) as ControlledRuleCollection;
    // throws unable to find assembly exception
}

Is there maybe some ILMerge option I'm missing here?

A: It sounds like you've serialized an object inside a DLL, then merged all of the assemblies with ILMerge and are now trying to deserialize that object.  This simply won't work.  The deserialization process for binary serialization will attempt to load the object's type from the original DLL.  This DLL doesn't exist post ILMerge and hence the deserialization will fail.
The serialization and deserialization process need to both operate pre or post merge.  It can't be mixed

A: SerializationBinder was also my solution. But I have the class in a DLL which is referenced. So i have to search in all load assemblies. I have modified the answers bevor with the parameter if the binder should search in dlls.
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace ibKastl.Helper
{
   public static class BinaryFormatterHelper
   {
      public static T Read<T>(string filename, Assembly currentAssembly)
      {
         T retunValue;
         FileStream fileStream = new FileStream(filename, FileMode.Open);

         try
         {
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            binaryFormatter.Binder = new SearchAssembliesBinder(currentAssembly,true);
            retunValue = (T)binaryFormatter.Deserialize(fileStream);
         }
         finally
         {
            fileStream.Close();
         }

         return retunValue;
      }

      public static void Write<T>(T obj, string filename)
      {
         FileStream fileStream = new FileStream(filename, FileMode.Create);
         BinaryFormatter formatter = new BinaryFormatter();
         try
         {
            formatter.Serialize(fileStream, obj);
         }
         finally
         {
            fileStream.Close();
         }
      }
   }

   sealed class SearchAssembliesBinder : SerializationBinder
   {
      private readonly bool _searchInDlls;
      private readonly Assembly _currentAssembly;

      public SearchAssembliesBinder(Assembly currentAssembly, bool searchInDlls)
      {
         _currentAssembly = currentAssembly;
         _searchInDlls = searchInDlls;
      }

      public override Type BindToType(string assemblyName, string typeName)
      {
         List<AssemblyName> assemblyNames = new List<AssemblyName>();
         assemblyNames.Add(_currentAssembly.GetName()); // EXE

         if (_searchInDlls)
         {
            assemblyNames.AddRange(_currentAssembly.GetReferencedAssemblies()); // DLLs
         }

         foreach (AssemblyName an in assemblyNames)
         {
            var typeToDeserialize = GetTypeToDeserialize(typeName, an);
            if (typeToDeserialize != null)
            {
               return typeToDeserialize; // found
            }
         }

         return null; // not found
      }

      private static Type GetTypeToDeserialize(string typeName, AssemblyName an)
      {
         string fullTypeName = string.Format("{0}, {1}", typeName, an.FullName);
         var typeToDeserialize = Type.GetType(fullTypeName);
         return typeToDeserialize;
      }
   }

}

Usage:
const string FILENAME = @"MyObject.dat";

// Serialize
BinaryFormatterHelper.Write(myObject1,FILENAME);

// Deserialize
MyObject myObject2 = BinaryFormatterHelper.Read<MyObject>(FILENAME, Assembly.GetExecutingAssembly()); // Current Assembly where the dll is referenced

A: You can do this by creating and adding a SerializationBinder sub class that will change the assembly name before the deserialization happens.
sealed class PreMergeToMergedDeserializationBinder : SerializationBinder
{
    public override Type BindToType(string assemblyName, string typeName)
    {
        Type typeToDeserialize = null;

        // For each assemblyName/typeName that you want to deserialize to
        // a different type, set typeToDeserialize to the desired type.
        String exeAssembly = Assembly.GetExecutingAssembly().FullName;

        // The following line of code returns the type.
        typeToDeserialize = Type.GetType(String.Format("{0}, {1}",
            typeName, exeAssembly));

        return typeToDeserialize;
    }
}

Then when deserializating add this to the BinaryFormatter:
BinaryFormatter bf = new BinaryFormatter();
bf.Binder = new PreMergeToMergedDeserializationBinder();
object obj = bf.Deserialize(ms);

A: You may have serialized that from the separate assembly and then tried to deserialize it with another assembly (or a newer version of the same assembly).
Some discussion here

A: For anyone having this issue, trying to deserialize from a different assembly, I found this solution which seems to great for me using a small "BindChanger" class with a shared namespace for the Object type in question.
https://www.daniweb.com/programming/software-development/threads/339638/deserializing-in-a-different-assembly

A: I found another solution for this problem. Mine problem was maybe a little different...
I was trying to deserialize from the same library that serialized, but it could not locate the correct assembly to do so. I tried all the solutions above, and none worked.
I found a solution on another website (Here)
In short, override the ResolveEventHandler of AppDomain.CurrentDomain.AssemblyResolve in the +tor
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);

Then implement the method for "CurrentDomain_AssemblyResolve" as follows:
System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
  System.Reflection.Assembly ayResult = null;
  string sShortAssemblyName = args.Name.Split(',')[0];
  System.Reflection.Assembly[] ayAssemblies = AppDomain.CurrentDomain.GetAssemblies();
  foreach (System.Reflection.Assembly ayAssembly in ayAssemblies)
  {
      if (sShortAssemblyName == ayAssembly.FullName.Split(',')[0])
      {
          ayResult = ayAssembly;
          break;
      }
  }
  return ayResult;
}

This fixed the error for me which allowed me to deserialize.

A: In case you merge assemblies into a existing one (for-example all DLLs to the EXE) you can use the solution proposed in this answer:
// AssemblyInfo.cs for My.exe
[assembly: TypeForwardedTo(typeof(SomeTypeFromMergedDLL))]

This at least works for deserializing pre-merge. IL-Merge also still passes; even if you can't compile with a type-forward to a type of the same assembly...
I have not tried, if serializing works post-merge yet. But I'll keep my answer updated.

A: I had a situation where serialized data was being stored in SQL server by an old .NET service that had been in place for years. I needed to get the data out of SQL and ran into this also. I was able to refer to the .exe and make it work until I used the solution mentioned above. However my assembly names were different.
sealed class Version1ToVersion2DeserializationBinder : SerializationBinder
    {
        public override Type BindToType(string assemblyName, string typeName)
        {
            Type typeToDeserialize = null;

            // For each assemblyName/typeName that you want to deserialize to a different type, set typeToDeserialize to the desired type.
            String assemVer1 = assemblyName;
            String typeVer1 = typeName;

            if (assemblyName == assemVer1 && typeName == typeVer1)
            {
                // To use a type from a different assembly version, change the version number.
                assemblyName = Assembly.GetExecutingAssembly().FullName;
                // To use a different type from the same assembly, change the type name.
                typeName = "projectname.typename";
            }

            // The following line of code returns the type.
            typeToDeserialize = Type.GetType(String.Format("{0}, {1}", typeName, assemblyName));
            return typeToDeserialize;
        }
    }

A: i got the solution
   sealed class VersionDeserializationBinder : SerializationBinder
  {
     public override Type BindToType(string assemblyName, string typeName)
    {
    Type typeToDeserialize = null;
    string currentAssemblyInfo = Assembly.GetExecutingAssembly().FullName;

    //my modification
    string currentAssemblyName = currentAssemblyInfo.Split(',')[0];
    if (assemblyName.StartsWith(currentAssemblyName))assemblyName = currentAssemblyInfo;

    typeToDeserialize = Type.GetType(string.Format("{0}, {1}", typeName, assemblyName));
    return typeToDeserialize;
}

}
Deserialization problem: Error when deserializing from a different program version

A:     public sealed class DeserializationBinder : SerializationBinder
{
    private readonly string _typeName;
    private readonly Assembly _assembly;
    public DeserializationBinder(Assembly assembly, string typeName)
    {
        _typeName = typeName;
        _assembly = assembly;
    }

    public override Type BindToType(string assemblyName, string typeName)
    {
        Type typeToDeserialize = null;
        if (!assemblyName.Contains("System") && !assemblyName.Contains("mscorlib"))
        {
            String currentAssembly = _assembly.FullName;
            assemblyName = currentAssembly;
            typeName = _typeName;
        }
        typeToDeserialize = Type.GetType(String.Format("{0}, {1}",
            typeName, assemblyName));
        return typeToDeserialize;
    }
}


text:
Q: How to get user access token? I'm trying to access scores through the Facebook API to get a list of scores of my friends. When I try to access /[facebook id]/scores, I get the following error even with my app access token:

FacebookApiException [ 0 ]: A user access token is required to request this resource. ~ APPPATH/classes/basefacebook.php [ 1039 ]

How do I get a user access token?
Updated: After reading http://developers.facebook.com/docs/reference/api/permissions/, I've confirmed that the app access token and user access token are two different access tokens. The question still remains, how do I get a user access token?

A: I see that you are using the php-sdk. So you need your friend to access your app with a script something like the example:
<?php
/**
 * Copyright 2011 Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may obtain
 * a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

require '../src/facebook.php';

// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
  'appId'  => '191149314281714',
  'secret' => '73b67bf1c825fa47efae70a46c18906b',
));

// Get User ID
$user = $facebook->getUser();

// We may or may not have this data based on whether the user is logged in.
//
// If we have a $user id here, it means we know the user is logged into
// Facebook, but we don't know if the access token is valid. An access
// token is invalid if the user logged out of Facebook.

if ($user) {
  try {
    // Proceed knowing you have a logged in user who's authenticated.
    $user_profile = $facebook->api('/me');
  } catch (FacebookApiException $e) {
    error_log($e);
    $user = null;
  }
}

// Login or logout url will be needed depending on current user state.
if ($user) {
  $logoutUrl = $facebook->getLogoutUrl();
} else {
  $loginUrl = $facebook->getLoginUrl(array('scope'=>'offline_access'));
}

// This call will always work since we are fetching public data.
$naitik = $facebook->api('/naitik');

?>
<!doctype html>

    <title>php-sdk</title>

php-sdk

    <?php if ($user): ?>
      <a href="<?php echo $logoutUrl; ?>">Logout
    <?php else: ?>

        Login using OAuth 2.0 handled by the PHP SDK:
        <a href="<?php echo $loginUrl; ?>">Login with Facebook

    <?php endif ?>

PHP Session

<?php print_r($_SESSION); ?>

    <?php if ($user): ?>

You

      <img src="https://graph.facebook.com/<?php echo $user; ?>/picture">

Your User Object (/me)

<?php print_r($user_profile); ?>

    <?php else: ?>
      You are not Connected.
    <?php endif ?>

Public profile of Naitik

    <?php echo $naitik['name']; ?>

Then you need to:

*

*Grant the offline_access permission

*Store the returned access_token

*Use that token whenever you query your friend's scores $facebook->api('friend_id/scores?access_token=$stored_access_token');

A: Please refer to the documentations showing the authentication flows for Facebook.
http://developers.facebook.com/docs/authentication/
This is the best place to start to understand how it works.

*

*You get the user's permission and access_token

*You can use this access_token as a "key" to get and post Facebook information

The access_token is not to be mistaken for your application secret code, which is used to authorised to make a connection on behalf of your registered application.

A: In Flex you can use:
FacebookDesktop.getSession().accessToken;

A: I call this function:
FB.getLoginStatus(onFacebookInitialLoginStatus);

Which calls the function below and gets the accesss_token from the response.
function onFacebookInitialLoginStatus(response) {
            if (response.status == "connected" && response.session) {
                var access_token = response.session.access_token;
                var url = 'https://graph.facebook.com/me/likes?access_token=' + access_token;
            }
            else {
                facebookLogin();
            }
        }

A: Suscribe to this event:
FB.Event.subscribe('auth.authResponseChange', function(response) {

then check response.status


text:
Q: GridView search button How to place search button in DataGridView cell in Windows Application like font selecting in control property window in Visual Studio 2010

A: This may not be a direct answer to your question but you might want to look at Object List View
http://objectlistview.sourceforge.net/cs/index.html
It actually wraps a ListView but has a lot of capabilities including reading data from a database as I recall.  This provides for in-cell editors.  For standard things like colors it has a built in cell editor.  If that does not work then you can roll your own.


text:
Q: Why Kendo ComboBoxFor show 0 instead of property binded model which was passed from another view? I am ASP MVC newbie.
I have problem with Kendo ComboBoxFor. I tried dozens of examples from Stack but with no success.
I want to pass two ids from one view to another and use them in two ComboboxFor. In both views I use this same model.
Beneath, there are my two target ids.
Model
public class Wymiarowanie_PorownajModel
{
    public int Target1 { get; set; }
    public int Target2 { get; set; }
}

This is my two approaches to binding this ids in target view. Both not work.
ComboBoxFor display 0 instead of property binded model which was passed from another view. Binded list to ComboboxFor works correctly.
View
@model WebApp.Models.Wymiarowanie_PorownajModel

            @(Html.Kendo().ComboBoxFor(model => model.Target1)
            .DataTextField("Opis")
            .DataValueField("Id")
            .Suggest(true)
            .Name("Target1")
            .Filter("contains")
            .BindTo((System.Collections.IEnumerable)ViewData["opis"])
            .Placeholder("Wybierz tłoka bazowego...")
            .HtmlAttributes(new { style = "width:225px;" })
            )

            @(Html.Kendo().ComboBoxFor(model => model.Target2)
            .DataTextField("Nazwa").DataValueField("Id")
            .Suggest(true)
            .Filter("contains")
            .Placeholder("Wybierz opcję 1...")
            .HtmlAttributes(new { style = "width:225px;" })
            .DataSource(source =>
            {
                source.Read(read =>
                {
                    read.Action("PodajRysunek", "Wymiarowanie_PorownajWymiaryTlokow");
                })
                                 .ServerFiltering(true);
            })
            )

Controller
public class Wymiarowanie_PorownajWymiaryTlokowController : Controller
{
  private MainDb db = new MainDb();
  Wymiarowanie_PorownajModel wym = new Wymiarowanie_PorownajModel();

  public ActionResult Index(Wymiarowanie_PorownajModel wymMain)
  {
     wymMain = wym;
     UzupelnijNrRysunku();
     return View(wym);
  }

  private void UzupelnijNrRysunku()
  {
     var typ = db.Specyfikacja_V_TlokiZwymiarowaneDoPorownaniaNrRysunku_list
     .Select(c => new
     {
       Id = c.Id,
       Opis = c.Rysunek_Nr_Zmiana
     })
     .OrderBy(e => e.Opis);
     ViewData["opis"] = typ.OrderBy(e => e.Opis);
     ViewData["defaultopis"] = typ.First().Opis;
  }

  public JsonResult PodajRysunek(string text)
  {
      var rysunki =
      db.Specyfikacja_V_TlokiZwymiarowaneDoPorownaniaNrRysunku_list
      .Select(tlok => new {
         Id = tlok.Id,
         Nazwa = tlok.Rysunek_Nr_Zmiana
      });

      if (!string.IsNullOrEmpty(text))
      {
         rysunki = rysunki.Where(p => p.Nazwa.Contains(text));
      }
      return Json(rysunki, JsonRequestBehavior.AllowGet);
  }
}

I don't have any clue what is wrong.
Would you like to help me find solution for this error?
I hope that my code is clear to you Sorry for my English.
Kind Regards

A: Here you have example how bind data
   public ActionResult Products_Read([DataSourceRequest]DataSourceRequest request)
{
    using (var northwind = new NorthwindEntities())
    {
        IQueryable<Product> products = northwind.Products;
        DataSourceResult result = products.ToDataSourceResult(request);
        return Json(result);
    }
}

More information u can find here

A: Solution an explanation: I commited rookie's mistake. I messed up instances in my controllers. I wanted to use two separate views with two separate controllers.
I cleaned a reduced my code and put it to one controller.
I have this same model class. Finally, my ComboBoxFor look like example beneath:
@(Html.Kendo().ComboBoxFor(model => model.Target)
    .DataTextField("Nazwa").DataValueField("Id")
    .Suggest(true)
    .Filter("contains")
    .Placeholder("Wybierz opcję 1...")
    .HtmlAttributes(new { style = "width:225px;" })
    .DataSource(source =>
        {
            source.Read(read =>
            {
                read.Action("PodajRysunek", "Wymiarowanie_Porownaj");
            })
                             .ServerFiltering(true);
        })
            )

Now I using only JsonResult PodajRysunek method to binding list to combobox.
I changed a little bit method for second view which appearence is invoked by button.
public ActionResult WymiaryTlokow(Wymiarowanie_PorownajModel wymiarowaniePorownajModel)
    {
        this.wym = wymiarowaniePorownajModel;
        return View(wym);
    }

It is never late to learn. :)


text:
Q: Detecting when a windows form has been initialised and has completely painted I'm looking to implement a quick and dirty way of measuring the UI performance of a set of winforms. My idea is to put in System.Diagnostic timing calls into the code base and detect when the time from when the page is requested to when it is completely drawn and available to the user. Is this even possible? Is there an initial event I can hook into and an event I can hook into when the form has completely? painted. I know there is a Paint event but this is when the form starts to draw but this isn't going to help me.
I'm a web developer dealing with some windows forms hence the obvious question.

A: You can start the Stopwatch exactly before executing the constructor of your Form or in the first line of your constructor.
It is a good idea to start the Stopwatch before the constructor, because when you start it inside the constructor, already base class constructor will have finished running, so you'll be excluding those timings if you decide to start it in the first line of the constructor.
Then stop the Stopwatch in Form.Shown event. It will be raised when the form is fully shown to the user.
Then use Stopwatch.Elapsed to read the time taken for the form to load.
As @HansPassant noted in comments, you may need to add this.Update(); in the Shown event handler so that we can make sure all children are painted fully.


text:
Q: stuck with WordNet relations in nested list in prolog I would like to do an approximate match using wordNet relations,
So there are two items approximately match if
  (i) the head of one subsumes the head of the other according to wordnet
  (ii) (a) the first dtr of each approximately match
       (b) we skip over the first dtr of the second tree and try again
To do this neatly, you want approxmatch and approxmatchdtrs.
[love, [peter], [susan], [in, [january]] |- [like, [peter], [susan]]

I tried to solve it this way but it is not working:
subsynset([] ,_).

subsynset([H0 | ARGS0], [H1 | ARGS1]) :-
    wordnetsubsumes(H0, H1),
    subsynset(ARGS0,ARGS1).

subsynset(L, [_ | ARGS]):-
    subsynset(L, ARGS).

wordnetsubsumes(H0, H0).

wordnetsubsumes(H0, H1):-
    \+list(
    s(I,_,H0,_,_,_),
    (hyp(I, J) ->
    s(J,_,Hyp,_,_,_),
    Hyp = H1 ;
    subsynset(Hyp, H1))).

I found that my wordnetsubsumes just check the first word and I am not sure if it check for the list or not in my code.
BY THE WAY, I am using sicstus prolog if there is some different between it and SWI in this code.


text:
Q: How can I make a tkinter program go to a previous frame? I'm building a small program where different parts of the code will call on one object different times. I'd like to try and make it call the previous frame back instead of duplicating the actual code multiple times. Here is part of my code if you need an example:
    #Console Menu
    class consoleMenu(tk.Frame):

        #Initialize
        def __init__(self, parent, controller):
            tk.Frame.__init__(self, parent)

            #Setups
            consoleGuideLabel = ttk.Label(self, text = "Console Guide", font = LARGE_FONT)

            consoleItemInfoButton = ttk.Button(self, text = "Console Item Info", command = lambda: controller.show_frame(consoleItemInfo))
            consoleVersionButton = ttk.Button(self, text = "Console Version History", command = lambda: popupmsg ("Not supported just yet!"))
            consoleMainMenuButton = ttk.Button(self, text = "Main Menu", command = lambda: controller.show_frame(StartPage))

            #Placement
            consoleGuideLabel.pack(pady = 10, padx = 10)

            consoleItemInfoButton.pack()
            consoleVersionButton.pack()
            consoleMainMenuButton.pack()

Now this is the part that gets called on multiple times by different frames.
    #Air - MCPE, PC, Xbox
    class mc_air(tk.Frame):

        #Initialize
        def __init__(self, parent, controller):
            tk.Frame.__init__(self, parent)

            #Item Info
            text_file = open("minecraft_air.txt", "r")
            file = text_file.read()
            text_file.close()

            #Setups
            airLabel = ttk.Label(self, text = "Minecraft - Air - 1", font = LARGE_FONT)
            airInfo = ttk.Label(self, text = file, font = NORMAL_FONT)
            exitButton = ttk.Button(self, text = "Return to Menu", command = lambda: controller.show_frame(StartPage))

            #Placement
            airLabel.pack(pady = 10, padx = 10)
            airInfo.pack()
            exitButton.pack()

Where it says:
exitButton = ttk.Button(self, text = "Return to Menu", command = lambda:      controller.show_frame(StartPage))

I'd like to be able to replace StartPage with a command to go to the previous window.

A: Here is one possible implementation, based on my implementation of frame switching here:
import Tkinter as tk

class BaseFrame(tk.Frame):
    """An abstract base class for the frames that sit inside PythonGUI.

    Args:
      master (tk.Frame): The parent widget.
      controller (PythonGUI): The controlling Tk object.

    Attributes:
      controller (PythonGUI): The controlling Tk object.

    """

    def __init__(self, master, controller):
        tk.Frame.__init__(self, master)
        self.controller = controller
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        """Create the widgets for the frame."""
        raise NotImplementedError

    def goto_three(self):
        self.controller.frames[FrameThree].return_to(self.__class__)
        self.controller.show_frame(FrameThree)

class FrameOne(BaseFrame):
    """First page."""

    def create_widgets(self):
        """Create the base widgets for the frame."""
        self.button_two = tk.Button(self,
                                    anchor=tk.W,
                                    command=lambda: self.controller.show_frame(FrameTwo),
                                    padx=5,
                                    pady=5,
                                    text="Two")
        self.button_two.grid(padx=5, pady=5, sticky=tk.W+tk.E)
        self.button_three = tk.Button(self,
                                      anchor=tk.W,
                                      command=self.goto_three,
                                      padx=5,
                                      pady=5,
                                      text="Three")
        self.button_three.grid(padx=5, pady=5, sticky=tk.W+tk.E)

class FrameTwo(BaseFrame):
    """Second page."""

    def create_widgets(self):
        """Create the base widgets for the frame."""
        self.button_one = tk.Button(self,
                                    anchor=tk.W,
                                    command=lambda: self.controller.show_frame(FrameOne),
                                    padx=5,
                                    pady=5,
                                    text="One")
        self.button_one.grid(padx=5, pady=5, sticky=tk.W+tk.E)
        self.button_three = tk.Button(self,
                                      anchor=tk.W,
                                      command=self.goto_three,
                                      padx=5,
                                      pady=5,
                                      text="Three")
        self.button_three.grid(padx=5, pady=5, sticky=tk.W+tk.E)

class FrameThree(BaseFrame):
    """Third page."""

    def create_widgets(self):
        """Create the base widgets for the frame."""
        self.button_two = tk.Button(self,
                                    anchor=tk.W,
                                    command=lambda: self.controller.show_frame(FrameTwo),
                                    padx=5,
                                    pady=5,
                                    text="Two")
        self.button_two.grid(padx=5, pady=5, sticky=tk.W+tk.E)
        self.button_one = tk.Button(self,
                                    anchor=tk.W,
                                    command=lambda: self.controller.show_frame(FrameOne),
                                    padx=5,
                                    pady=5,
                                    text="One")
        self.button_one.grid(padx=5, pady=5, sticky=tk.W+tk.E)
        self.button_back = tk.Button(self,
                                     anchor=tk.W,
                                     padx=5,
                                     pady=5,
                                     text="Back")
        self.button_back.grid(padx=5, pady=5, sticky=tk.W+tk.E)

    def return_to(self, frame):
        self.button_back.config(command=lambda: self.controller.show_frame(frame))

class PythonGUI(tk.Tk):
    """The main window of the GUI.

    Attributes:
      container (tk.Frame): The frame container for the sub-frames.
      frames (dict of tk.Frame): The available sub-frames.

    """

    def __init__(self):
        tk.Tk.__init__(self)
        self.title("Python GUI")
        self.create_widgets()
        self.resizable(0, 0)

    def create_widgets(self):
        """Create the widgets for the frame."""
        #   Frame Container
        self.container = tk.Frame(self)
        self.container.grid(row=0, column=0, sticky=tk.W+tk.E)

        #   Frames
        self.frames = {}
        for f in (FrameOne, FrameTwo, FrameThree): # defined subclasses of BaseFrame
            frame = f(self.container, self)
            frame.grid(row=2, column=2, sticky=tk.NW+tk.SE)
            self.frames[f] = frame
        self.show_frame(FrameOne)

    def show_frame(self, cls):
        """Show the specified frame.

        Args:
          cls (tk.Frame): The class of the frame to show.

        """
        self.frames[cls].tkraise()

if __name__ == "__main__":
    app = PythonGUI()
    app.mainloop()
    exit()

It's a bit hacky as it stands, but basically the idea is that goto_three calls the FrameThree instance's return_to, which alters the command on its button_back to return to whichever frame it was called from.


text:
Q: swiper carousel + animation + mask image I am building a Swiper carousel (triggered by mouse scrolling) that has a frame on the top of it. this is the design

the red color is the frame that should cover the carousel. the middle hole is transparent

I have tried to make the red image as a mask-image so that I can control the swiper carousel by mouse scrolling, but the center hole goes white and the red color is transparent! and what I want is exactly the opposite I want the hole transplant and the outside the hole the red color.
Is there any way to add the image frame on the top of the swiper carousel and still can trigger and control the carousel positioned under the frame?
Code:
codePen

// https://swiperjs.com/
// ===================== -->

var mySwiper = new Swiper('.swiper-container', {
  // Optional parameters
  direction: 'horizontal',
  loop: true,
  speed: 1200,
  grabCursor: true,
  mousewheel: true,

  // If we need pagination
  pagination: {
    el: '.swiper-pagination',
    type: 'bullets',
    clickable: true,
  },

  // Navigation arrows
  navigation: {
    nextEl: '.swiper-button-next',
    prevEl: '.swiper-button-prev',
  },

  on: {
    slideChangeTransitionStart: function() {
      // Slide captions
      var swiper = this;
      setTimeout(function() {
        var currentTitle = $(swiper.slides[swiper.activeIndex]).attr("data-title");
        var currentSubtitle = $(swiper.slides[swiper.activeIndex]).attr("data-subtitle");
      }, 500);
      gsap.to($(".current-title"), 0.4, {
        autoAlpha: 0,
        y: -40,
        ease: Power1.easeIn
      });
      gsap.to($(".current-subtitle"), 0.4, {
        autoAlpha: 0,
        y: -40,
        delay: 0.15,
        ease: Power1.easeIn
      });
    },
    slideChangeTransitionEnd: function() {
      // Slide captions
      var swiper = this;
      var currentTitle = $(swiper.slides[swiper.activeIndex]).attr("data-title");
      var currentSubtitle = $(swiper.slides[swiper.activeIndex]).attr("data-subtitle");
      $(".slide-captions").html(function() {
        return "
" + currentTitle + "
" + "
" + currentSubtitle + "
";
      });
      gsap.from($(".current-title"), 0.4, {
        autoAlpha: 0,
        y: 40,
        ease: Power1.easeOut
      });
      gsap.from($(".current-subtitle"), 0.4, {
        autoAlpha: 0,
        y: 40,
        delay: 0.15,
        ease: Power1.easeOut
      });
    }
  }
});

// Slide captions
var currentTitle = $(mySwiper.slides[mySwiper.activeIndex]).attr("data-title");
var currentSubtitle = $(mySwiper.slides[mySwiper.activeIndex]).attr("data-subtitle");
$(".slide-captions").html(function() {
  return "
" + currentTitle + "
" + "
" + currentSubtitle + "
";
});
body {
  margin: 0;
}

/* Swiper */

.swiper-container {
  position: absolute;
  width: 100%;
  height: 100vh;
  mask-image: url(https://i.ibb.co/kmBv430/Frame.png);
  mask-size: contain;
}

/* .above{
  position:absolute;
  left:25%;
  background-color: #fff;
   width: 200%;
   height: 100vh;
  z-index:2;
   mask-image: radial-gradient(circle  at center, transparent 49%, white 50%);
  mask-size: contain;
  mask-repeat: no-repeat;
} */

/* Swiper slides */

.swiper-slide {
  position: relative;
  z-index: 1;
}

.slide-1 {
  background-color: #e67204;
}

.slide-2 {
  background-color: #e67204;
}

.slide-3 {
  background-color: #e67204;
}

.rounded-circle {
  width: 400px;
  height: 300px;
  border-radius: 50%;
  position: absolute;
  top: 30%;
  left: 35%
}

.htu {
  position: absolute;
  color: #fff;
  font-size: 50px;
  top: 39%;
  left: 10%;
  z-index: 2;
}

/* Slide captions */

.slide-captions {
  position: absolute;
  top: 50%;
  left: 75%;
  color: #FFF;
  z-index: 999;
  transform: translateY(-50%);
}

.slide-captions .current-title {
  position: absolute;
  left: 60%;
  margin: 0;
  font-size: 48px;
}

.slide-captions .current-subtitle {
  margin: 10px 0 0 0;
  font-size: 28px;
}

/* Swiper arrows */

.swiper-pagination-bullet-active {
  background-color: #fff;
}

/* Swiper pagination */

.swiper-container-horizontal>.swiper-pagination-bullets {
  bottom: 50px;
}

.swiper-button-prev,
.swiper-button-next {
  color: #fff;
}

HOW TO USE

A: I have solved my problem by using GSAP scroll Trigger to trigger the movement of each layer and it works for me.
let tl2 = gsap.timeline({

scrollTrigger :{
trigger : "#sec-4",
pin: true,
scrub: true,
  start : "center center",
  end: "+=" + (window.innerHeight * 8),
}
  });
  tl2.from('.step-1', 1, {y: 100, opacity:0 })
  tl2.to('.step-1', 1, {opacity:0 })
  tl2.to('.flwres-frame', 0.5 , {x: -300}, 'frist')
  tl2.to('.girl-frame', 1 , {x: -300}, 'frist')
  tl2.from('.step-2', 1, {y: 100, opacity:0 }, 'frist')
  tl2.to('.step-2', 1, {opacity:0 })
  tl2.to('.flwres-frame', 0.5 , {x: -600}, 'second')
  tl2.to('.girl-frame', 1 , {x: -670}, 'second')
  tl2.from('.step-3', 1, {y: 100, opacity:0 }, 'second')
  tl2.to('.step-3', 1, {opacity:0 })
  tl2.to('.flwres-frame', 0.5 , {x: -900}, '3rd')
  tl2.to('.girl-frame', 1 , {x: -1050}, '3rd')
  tl2.from('.step-4', 2, {y: 100, opacity:0 }, '3rd')


text:
Q: Increase display time of exception message in magento 2 I am using Magento 2.1.3 and I need to display an error message in the shipping information page. Currently I'm using this code:
throw new StateException(__('Shipping is not available on the provided zipcode'));

but the issue is that the error message is just showing 2 or 3 seconds. I need to show this message up to refresh the page.
<?php

namespace Sem\Shipment\Plugin\Checkout\Model;
use Magento\Framework\Exception\StateException;
use Magento\Checkout\Model\Session;
use Magento\Framework\View\Element\Messages;
use Magento\Framework\Message\ManagerInterface;
use Magento\Framework\UrlInterface $urlInterface;

class ShippingInformationManagement
{

    protected $_messageManager;
    protected $jsonResultFactory;
    protected $_checkout;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\Controller\Result\JsonFactory $jsonResultFactory,
        \Magento\Framework\Message\ManagerInterface $messageManager,
        \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
        \Magento\Checkout\Model\Session $session,
        \Magento\Framework\UrlInterface $urlInterface

    ) {
        $this->_messageManager = $messageManager;
        $this->jsonResultFactory = $jsonResultFactory;
        $this->_session = $session;
        $this->_urlInterface = $urlInterface;
    }

    public function beforeSaveAddressInformation(
        \Magento\Checkout\Model\ShippingInformationManagement $subject,
        $cartId,
        \Magento\Checkout\Api\Data\ShippingInformationInterface $addressInformation

    )
    {
        $objectManager =   \Magento\Framework\App\ObjectManager::getInstance();
        $resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
        $connection = $resource->getConnection();
        $items = $this->_session->getQuote()->getAllVisibleItems();
        $address = $addressInformation->getShippingAddress();
        $postcode = $address->getData('postcode');
        $result = $this->jsonResultFactory->create();
        $pid='';
        if (count($items) > 0){
            foreach ($items as $item)
            {
                $pname= $item->getName();
                $pid=$item['product_id'];
                $carttotal=$item['grand_total'];
                $weight=$item['weight'];
                $sql ="SELECT ca.postcode FROM
                       mgcb_marketplace_product mp
                       JOIN mgcb_marketplace_userdata mu ON mp.seller_id = mu.seller_id
                       JOIN mgcb_customer_entity ce ON mu.seller_id = ce.entity_id
                       JOIN mgcb_customer_address_entity ca ON ce.entity_id = ca.parent_id
                       WHERE(mp.mageproduct_id = '$pid')";
                $qryresult = $connection->fetchAll($sql);
                foreach ($qryresult as $qryresult)
                {
                    $pikup=$qryresult['postcode'];
                }

                foreach($result as $object) {
                    $stat = "NO SERVICE AVAILABLE";
                }
                //print_r($object);
                if($stat=="NO SERVICE AVAILABLE")
                {

                    $msg = "Shipping is not available on the provided zipcode For the following product: <em>" . $item->getName() . "</em>
                            Currently Added Product : " . $linkUrl;
                    $this->_messageManager->addError(__("errorr"));
                    throw new StateException(__($msg));
                }

            }
        }
    }
}

A: I know it's three months down the line, but am sure this will help someone.
You can do this by adjusting the timeout period on the file.

vendor/magento/module-ui/view/frontend/web/js/view/messages.js

It is around lines 70/71. you can set the time out to be a figure of your choice (in milliseconds)

A: As Moses has detailed above, the timeout is set in:
vendor/magento/module-ui/view/frontend/web/js/view/messages.js
This can simply be applied as a Mixin inside your theme. Mixin's are a way of changing/extending functions within JS files without over-riding the entire file. If you aren't family with mixins, I'd suggest checking out Magento's documentation: https://devdocs.magento.com/guides/v2.4/javascript-dev-guide/javascript/js_mixins.html
Create the file:
app/design/frontend/Vendor/ThemeName/Magento_Ui/web/js/view/messages-mixin.js
define([
    'ko',
    'jquery',
    'uiComponent',
    '../model/messageList',
    'jquery-ui-modules/effect-blind'
], function (ko, $, Component, globalMessages) {
    'use strict';
    var mixin = {
        /**
         * @param {Boolean} isHidden
         */
        onHiddenChange: function (isHidden) {
            // Hide message block if needed
            if (isHidden) {
                setTimeout(function () {
                    $(this.selector).hide('blind', {}, this.hideSpeed);
                }.bind(this), 30000);
            }
        }
    };
    return function (target) {
        return target.extend(mixin);
    };
});

Create the file:
app/design/frontend/Vendor/ThemeName/Magento_Ui/requirejs-config.js
var config = {
    config: {
        mixins: {
            'Magento_Ui/js/view/messages': {
                'Magento_Ui/js/view/messages-mixin': true
            }
        }
    }
};

Modify the vendor/theme name, and timeout accordingly.
If the above doesn't work, it's likely that the theme, or a 3rd party module is already doing something with Message timeouts. Best thing to do in this case is to search for keywords related to the functionality, e.g. globalMessages or DOM element '.page.messages' . I found that a popular 3rd party extension (UB Theme Mega Nav) was modifying the behaviour of messages in a PHTML file within a script tag.


text:
Q: Plotting the explained variance ratio from PCA I'm having trouble plotting my explained variance ratio in PCA. I'm building PCA from scratch and the plotting results is difference than using PCA from sklearn. My code is below :
class PCA:
def __init__ (self, n_components):
    self.n_components = n_components

def fit(self, X):
    self.x_mean = np.mean(X , axis = 0)
    X_meaned = X - self.x_mean
    cov_mat = np.cov(X_meaned.T)
    eigen_values , eigen_vectors = np.linalg.eigh(cov_mat)
    sorted_index = np.argsort(eigen_values)[::-1]
    self.eigen_values = eigen_values[sorted_index].real
    self.eigen_vectors = eigen_vectors[:,sorted_index].real

def transform(self, x):
    x_new = x - self.x_mean
    return np.matmul(x_new, self.eigen_vectors[:,:self.n_components])

def fit_transform (self,X):
    self.fit(X)
    return self.transform(X)

def plot(self):
    exp_var = self.eigen_values/sum(self.eigen_values)
    cum_var = np.cumsum(exp_var)
    plt.figure(1, figsize=(6,4))
    plt.clf()
    plt.plot(cum_var, linewidth= 3)
    plt.axis('tight')
    plt.grid()
    plt.xlabel("No of Components")
    plt.ylabel("Cumulative Variance")
    plt.show()

The result for the plot is
this
Meanwhile the plot generated using PCA from sklearn is like this
I know that explained_variance stands for the eigen_values/sum(eigen_values), but why does the plot did not getting the same result?


text:
Q: Apollo Android Client and JetPack Support I'm new to GraphQL and Apollo clients. My situation is that I'm making an Android app, I want to use JetPack libraries and components, and the web service for the app is using GraphQL. I'm trying to decide whether to use the apollo-android client, or just use okhttp3 to make my queries directly to the server, and implement the usual MVVM stuff, making my own classes and caching them with Room. Are these approaches meant to be combined? Or are they simply different ways of doing things? I ask because all of the tutorials and examples of apollo-android I've seen are really simple and don't involve view-models with LiveData objects observing data.

A: There's a pull request open to integrate apollo-android with LiveData: https://github.com/apollographql/apollo-android/pull/1320
You also have the option to use GraphQL just like you would use REST and map the apollo generated models to your own App models. GraphQL is then an api just like REST but with added type safety and all the tooling GraphQL brings.


text:
Q: Send ERC-20 token from another contract I am trying to send ERC-20 token that was deposited to my contract address to another address. Here is the ERC-20 contract code -
pragma solidity ^0.4.11;

/**
 * Math operations with safety checks
 */
library SafeMath {
  function mul(uint a, uint b) internal returns (uint) {
    uint c = a * b;
    assert(a == 0 || c / a == b);
    return c;
  }

  function div(uint a, uint b) internal returns (uint) {
    // assert(b > 0); // Solidity automatically throws when dividing by 0
    uint c = a / b;
    // assert(a == b * c + a % b); // There is no case in which this doesn't hold
    return c;
  }

  function sub(uint a, uint b) internal returns (uint) {
    assert(b <= a);
    return a - b;
  }

  function add(uint a, uint b) internal returns (uint) {
    uint c = a + b;
    assert(c >= a);
    return c;
  }

  function max64(uint64 a, uint64 b) internal constant returns (uint64) {
    return a >= b ? a : b;
  }

  function min64(uint64 a, uint64 b) internal constant returns (uint64) {
    return a < b ? a : b;
  }

  function max256(uint256 a, uint256 b) internal constant returns (uint256) {
    return a >= b ? a : b;
  }

  function min256(uint256 a, uint256 b) internal constant returns (uint256) {
    return a < b ? a : b;
  }

  function assert(bool assertion) internal {
    if (!assertion) {
      throw;
    }
  }
}

/**
 * @title ERC20Basic
 * @dev Simpler version of ERC20 interface
 * @dev see https://github.com/ethereum/EIPs/issues/20
 */
contract ERC20Basic {
  uint public totalSupply;
  function balanceOf(address who) constant returns (uint);
  function transfer(address to, uint value);
  event Transfer(address indexed from, address indexed to, uint value);
}

/**
 * @title Basic token
 * @dev Basic version of StandardToken, with no allowances.
 */
contract BasicToken is ERC20Basic {
  using SafeMath for uint;

  mapping(address => uint) balances;

  /**
   * @dev Fix for the ERC20 short address attack.
   */
  modifier onlyPayloadSize(uint size) {
     if(msg.data.length < size + 4) {
       throw;
     }
     _;
  }

  /**
  * @dev transfer token for a specified address
  * @param _to The address to transfer to.
  * @param _value The amount to be transferred.
  */
  function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) {
    balances[msg.sender] = balances[msg.sender].sub(_value);
    balances[_to] = balances[_to].add(_value);
    Transfer(msg.sender, _to, _value);
  }

  /**
  * @dev Gets the balance of the specified address.
  * @param _owner The address to query the the balance of.
  * @return An uint representing the amount owned by the passed address.
  */
  function balanceOf(address _owner) constant returns (uint balance) {
    return balances[_owner];
  }

}

/**
 * @title ERC20 interface
 * @dev see https://github.com/ethereum/EIPs/issues/20
 */
contract ERC20 is ERC20Basic {
  function allowance(address owner, address spender) constant returns (uint);
  function transferFrom(address from, address to, uint value);
  function approve(address spender, uint value);
  event Approval(address indexed owner, address indexed spender, uint value);
}

/**
 * @title Standard ERC20 token
 *
 * @dev Implementation of the basic standard token.
 * @dev https://github.com/ethereum/EIPs/issues/20
 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
 */
contract StandardToken is BasicToken, ERC20 {

  mapping (address => mapping (address => uint)) allowed;

  /**
   * @dev Transfer tokens from one address to another
   * @param _from address The address which you want to send tokens from
   * @param _to address The address which you want to transfer to
   * @param _value uint the amout of tokens to be transfered
   */
  function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) {
    var _allowance = allowed[_from][msg.sender];

    // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
    // if (_value > _allowance) throw;

    balances[_to] = balances[_to].add(_value);
    balances[_from] = balances[_from].sub(_value);
    allowed[_from][msg.sender] = _allowance.sub(_value);
    Transfer(_from, _to, _value);
  }

  /**
   * @dev Aprove the passed address to spend the specified amount of tokens on beahlf of msg.sender.
   * @param _spender The address which will spend the funds.
   * @param _value The amount of tokens to be spent.
   */
  function approve(address _spender, uint _value) {

    // To change the approve amount you first have to reduce the addresses`
    //  allowance to zero by calling `approve(_spender, 0)` if it is not
    //  already 0 to mitigate the race condition described here:
    //  https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
    if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw;

    allowed[msg.sender][_spender] = _value;
    Approval(msg.sender, _spender, _value);
  }

  /**
   * @dev Function to check the amount of tokens than an owner allowed to a spender.
   * @param _owner address The address which owns the funds.
   * @param _spender address The address which will spend the funds.
   * @return A uint specifing the amount of tokens still avaible for the spender.
   */
  function allowance(address _owner, address _spender) constant returns (uint remaining) {
    return allowed[_owner][_spender];
  }

}

/**
 * @title Ownable
 * @dev The Ownable contract has an owner address, and provides basic authorization control
 * functions, this simplifies the implementation of "user permissions".
 */
contract Ownable {
  address public owner;

  /**
   * @dev The Ownable constructor sets the original `owner` of the contract to the sender
   * account.
   */
  function Ownable() {
    owner = msg.sender;
  }

  /**
   * @dev Throws if called by any account other than the owner.
   */
  modifier onlyOwner() {
    if (msg.sender != owner) {
      throw;
    }
    _;
  }

  /**
   * @dev Allows the current owner to transfer control of the contract to a newOwner.
   * @param newOwner The address to transfer ownership to.
   */
  function transferOwnership(address newOwner) onlyOwner {
    if (newOwner != address(0)) {
      owner = newOwner;
    }
  }

}

/**
 * @title Mintable token
 * @dev Simple ERC20 Token example, with mintable token creation
 * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
 */

contract MintableToken is StandardToken, Ownable {
  event Mint(address indexed to, uint value);
  event MintFinished();

  bool public mintingFinished = false;
  uint public totalSupply = 0;

  modifier canMint() {
    if(mintingFinished) throw;
    _;
  }

  /**
   * @dev Function to mint tokens
   * @param _to The address that will recieve the minted tokens.
   * @param _amount The amount of tokens to mint.
   * @return A boolean that indicates if the operation was successful.
   */
  function mint(address _to, uint _amount) onlyOwner canMint returns (bool) {
    totalSupply = totalSupply.add(_amount);
    balances[_to] = balances[_to].add(_amount);
    Mint(_to, _amount);
    return true;
  }

  /**
   * @dev Function to stop minting new tokens.
   * @return True if the operation was successful.
   */
  function finishMinting() onlyOwner returns (bool) {
    mintingFinished = true;
    MintFinished();
    return true;
  }
}

/**
 * @title Pausable
 * @dev Base contract which allows children to implement an emergency stop mechanism.
 */
contract Pausable is Ownable {
  event Pause();
  event Unpause();

  bool public paused = false;

  /**
   * @dev modifier to allow actions only when the contract IS paused
   */
  modifier whenNotPaused() {
    if (paused) throw;
    _;
  }

  /**
   * @dev modifier to allow actions only when the contract IS NOT paused
   */
  modifier whenPaused {
    if (!paused) throw;
    _;
  }

  /**
   * @dev called by the owner to pause, triggers stopped state
   */
  function pause() onlyOwner whenNotPaused returns (bool) {
    paused = true;
    Pause();
    return true;
  }

  /**
   * @dev called by the owner to unpause, returns to normal state
   */
  function unpause() onlyOwner whenPaused returns (bool) {
    paused = false;
    Unpause();
    return true;
  }
}

/**
 * Pausable token
 *
 * Simple ERC20 Token example, with pausable token creation
 **/

contract PausableToken is StandardToken, Pausable {

  function transfer(address _to, uint _value) whenNotPaused {
    super.transfer(_to, _value);
  }

  function transferFrom(address _from, address _to, uint _value) whenNotPaused {
    super.transferFrom(_from, _to, _value);
  }
}

/**
 * @title TokenTimelock
 * @dev TokenTimelock is a token holder contract that will allow a
 * beneficiary to extract the tokens after a time has passed
 */
contract TokenTimelock {

  // ERC20 basic token contract being held
  ERC20Basic token;

  // beneficiary of tokens after they are released
  address beneficiary;

  // timestamp where token release is enabled
  uint releaseTime;

  function TokenTimelock(ERC20Basic _token, address _beneficiary, uint _releaseTime) {
    require(_releaseTime > now);
    token = _token;
    beneficiary = _beneficiary;
    releaseTime = _releaseTime;
  }

  /**
   * @dev beneficiary claims tokens held by time lock
   */
  function claim() {
    require(msg.sender == beneficiary);
    require(now >= releaseTime);

    uint amount = token.balanceOf(this);
    require(amount > 0);

    token.transfer(beneficiary, amount);
  }
}

contract TestToken is PausableToken, MintableToken {
  using SafeMath for uint256;

  string public name = "TestToken";
  string public symbol = "TT";
  uint public decimals = 18;

  /**
   * @dev mint timelocked tokens
   */
  function mintTimelocked(address _to, uint256 _amount, uint256 _releaseTime)
    onlyOwner canMint returns (TokenTimelock) {

    TokenTimelock timelock = new TokenTimelock(this, _to, _releaseTime);
    mint(timelock, _amount);

    return timelock;
  }

}

And the following is the contract from which I'm trying to send the deposited tokens -
pragma solidity ^0.4.18;

contract ERC20Interface {
  // Send _value amount of tokens to address _to
  function transfer(address _to, uint256 _value) public returns (bool success);
  // Get the account balance of another account with address _owner
  function balanceOf(address _owner) public constant returns (uint256 balance);
}

/**
 * Contract that will forward any incoming Ether to the creator of the contract
 */
contract Forwarder {
  // Address to which any funds sent to this contract will be forwarded
  address public parentAddress;
  event ForwarderDeposited(address from, uint value, bytes data);

  /**
   * Create the contract, and sets the destination address to that of the creator
   */
  function Forwarder() public {
    parentAddress = msg.sender;
  }

  /**
   * Modifier that will execute internal code block only if the sender is the parent address
   */
  modifier onlyParent {
    if (msg.sender != parentAddress) {
      revert();
    }
    _;
  }

  /**
   * Default function; Gets called when Ether is deposited, and forwards it to the parent address
   */
  function() public payable {
    // throws on failure
    parentAddress.transfer(msg.value);
    // Fire off the deposited event if we can forward it
    ForwarderDeposited(msg.sender, msg.value, msg.data);
  }

  /**
   * Execute a token transfer of the full balance from the forwarder token to the parent address
   * @param tokenContractAddress the address of the erc20 token contract
   */
  function flushTokens(address tokenContractAddress) public onlyParent {
    ERC20Interface instance = ERC20Interface(tokenContractAddress);
    var forwarderAddress = address(this);
    var forwarderBalance = instance.balanceOf(forwarderAddress);
    if (forwarderBalance == 0) {
      return;
    }
    if (!instance.transfer(parentAddress, forwarderBalance)) {
      revert();
    }
  }

}

When I call the flushToken function I get an error - Error: gas required exceeds allowance or always failing transaction.

A: In order to transfer tokens from one address to another you need first to approve the transaction.
function approve(address spender, uint tokens) public returns (bool success);

In that was you approve that the second contract can transfer the money from the first contract.
You can check  the allowance wit this function
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);


text:
Q: Adding plug in to datatables (ColReorder) Hy there,
I have problem, I am trying to add ColReored plugin to Datatables, but i cannot make it to work properly. I've read documentation and there it is said that you have to put to in extension folder but i don't have one. I even try to add one but nothing happened. But when i call jquery file directly it is not working properly.
Thanks

A: You can put the plugin wherever you like. Just include the colreorder.css and colreorder.js after datables.js
Init you table with this:
$(function() {
  $("#datatable").dataTable({
         "sDom": 'Rlfrtip'
    })
})

Find a working Plunker here


text:
Q: How do I access a dynamic element with selenium that returns None I'm trying to find an attribute 'src' via selenium to get an image but instead of returning the element. it returns a None type. I think its doing it because it is JavaScript. I want to know is there a way to still get the attribute instead of a None type? please help
script
from lib2to3.pgen2 import driver
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.common.exceptions import *
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.alert import Alert
from webdriver_manager.opera import OperaDriverManager
from PIL import Image
import urllib.request

driver = webdriver.Opera(executable_path=OperaDriverManager().install())

video_list = []

url = "https://www.tiktok.com/@nkosazana_daughter"

driver.get(url)

try:
    driver.implicitly_wait(30)
    popup = driver.find_element(By.XPATH,'.//*[@id="tiktok-verify-ele"]/div')

    if popup is False:
        driver.quit()
    elif popup is not None:
        popup_pic = driver.find_element(By.XPATH, './/*[@id="captcha-verify-image"]')

except Exception as e:
    print(e)

finally:
    pic = popup_pic.get_attribute('src')
    urllib.request.urlretrieve(pic, 'pic.png')
    img = Image.open('pic.png')
    print(img.getpixel(xy=(0,5)))
    print(img.getbbox())
    print(img.getbands())
    print(img.getdata(0))

    pic2 = popup.get_attribute('src')
    print(pic2)

output
(88, 102, 49)
(0, 0, 552, 344)
('R', 'G', 'B')
<ImagingCore object at 0x0000025C45276AF0>
None

A: alt and src are two different HTML attributes.
To print the value of the src attribute you can use the following line of code:
print(popup.get_attribute('src'))


text:
Q: slideshow on extra monitor? I'm looking for a slideshow style application for windows that I can apply to one monitor on a multi-monitor system.  I want to simulate it being a photo frame, in rotating pictures etc.  I also need the other monitors to be unaffected, except maybe a tray icon allowing some options.
I'd like it to keep working even when the PC is locked, which might make this the hardest part, and might not even be possible.
I found some shareware called AutoWallpaper, which seems like it might work out well for just rotating pictures every so often, but A) I'm cheap an it costs money, and B) would love to have transitions between images as well.
It seems that most slideshow screen savers have a nice look to them (google's screen saver that works by pulling in images from picasa etc is pretty cool) but I can't use it at the same time I'm actually using the PC.
Any ideas?

A: I use FoxSaver, a Firefox plugin that turns your browser into screensaver. It pulls pictures from their website and/or your computer. The main reason I use this is when I teach class. Before class and on breaks I just Maximize that instance of Firefox with Foxsaver running, When I want my presentation back up I just minimize it and start teaching.
You can use the Picasa screensaver for when the computer is locked, it puts different pictures on each monitor a feature I really like, and if you point Foxsaver to the same directory you put your Picasa screensaver pictures in it's practically the same thing.
You could even add pictures of delicious waffles and ponies.

A: IrfanView can do this! Transitions and all!
Don't think it's possible for it to happen when the PC is locked, however, sorry. You may wish to look into alternative methods of locking - perhaps just input using Autohotkey?

A: This might be CPU overkill, but what about open office impress /or msoffice powerpoint? If you make the sideshow and set it to run on a particular screen with auto next slide it should work except for the "when locked part".
I think you can even convert powerpoints to self executing files. If powerpoint doesn't allow this, there are certainly third party utilities.


text:
Q: If $x, y \in \mathbb{R}$, there exists a rational $r$ with *finite decimal expansion* s.t. $x < r < y$ There are many proofs (such as those described here), proving that between any two reals exists a rational: If $x, y \in \mathbb{R}$, there exists a rational $r$ s.t. $x < r < y$. I wish to know how these proofs can be adapted so that one can prove, in particular, that between any two reals exists a rational with finite decimal expansion. I have tried to adapt these proofs, using the Archemedean Principle, to end up with an expression of the form $x < n/10^k < y$, where $n \in \mathbb{N}$, as  $n/10^k$ would certainly have a finite decimal expansion, but have been unsuccessful in obtaining such an inequality. How should one then adapt these proofs to show that, between any two reals exists a rational with finite decimal expansion?

A: By Archimedean principle, there exists a natural number $k$ so that $\frac{1}{10^k}<b-a$ and it implies that $1<b10^k -a10^k$. This assures the existence of an integer $n$ between $a10^k$ and $b10^k$ as the gap is greater than $1$. We can mimic the proof for $\mathbb{Q}$ is dense in $\mathbb{R}$.
So we have $a10^k <n < b10^k$ which implies $a< n/10^k < b$.

A: Take $k\in\Bbb Z^+$ such that $10^k>\frac {1}{y-x},\,$ so $\,0<10^{-k}<y-x.$
Take $A\in\Bbb Z$ such that $A\cdot 10^{-k}<x.$
There exists $j\in\Bbb Z^+$ such that $(j+A)\cdot 10^{-k}\ge y .$  Let $B=\min\{j+A:j\in\Bbb Z^+\land (j+A)\cdot 10^{-k}\ge y\} .$
We have $(B-1)\cdot 10^{-k}<y.$
And we also have $$(B-1)\cdot 10^{-k}-x=$$ $$=B\cdot 10^{-k}-10^{-k}-x\ge$$ $$\ge y-10^{-k}-x=$$ $$=(y-x)-10^{-k}>0,$$ so we have
$(B-1)\cdot 10^{-k}>x.$


text:
Q: How to search for header files in usr/include/linux I am writing a C++ program with cmake in Ubuntu, which uses the header file joystick.h in /usr/include/linux. By default, it does not seem that make can find joystick.h in the default directories if I use #include <joystick.h>. Therefore, I add the line include_directories (/usr/include/linux) to CMakeLists.txt to enable this header to be found.
The problem is, I now get all sorts of errors such as error: redefinition of 'struct timeval' and error: redefinition of 'struct timezone'. This seems to be because there is a header time.h in both /user/include and /usr/include/linux. The header guards in these files are #ifndef _TIME_H and #ifndef _LINUX_TIME_H respectively. Therefore, the only solution I can think of is to hardcode the path to joystick.h in my source code.
Because of this, it seems to me that /usr/include/linux should never be added to the search path due to these redefinition issues. Is this correct? And is my solution of hardcoding the path the best one?

A: Unless there is a reason not to (and there might be I suppose) it would seem that just using #include <linux/joystick.h> in the source file would be the simplest solution here.


text:
Q: Windows .bat file to schedule git add, commit and push to Github I need to schedule a task in Windows Server 2008 R2 to automatically push files from a folder to Github Enterprise (I don't think the "Enterprise" part will make it different than regular Github, except that ssh authentication is required).
Here's what I've done:

*

*Set up a public/private key pair and added them to Github and .ssh, respectively

*Created a Github repo and cloned it to a local folder

*Manually ran through the add, commit, and push steps to make sure it works that way

*Tried to write a .bat file for automatically doing step #3

*Scheduled the task to run as my user, with highest privileges, in the target folder

Unfortunately, the task fails because I am not writing the .bat file correctly.
This was my attempt at the .bat file:
echo git add . | "C:\Program Files\Git\bin\git.exe"
echo git commit -m 'scheduled commit' | "C:\Program Files\Git\bin\git.exe"
echo git push | "C:\Program Files\Git\bin\git.exe"

I found a good resource on how to do this, but it is unfortunately very Linux-specific.

A: Just do:
git add .
git commit -m 'scheduled commit'
git push

Or, if git is not in your path:
"C:\Program Files\Git\bin\git.exe" add .
"C:\Program Files\Git\bin\git.exe" commit -m 'scheduled commit'
"C:\Program Files\Git\bin\git.exe" push

And depending on what you want to achieve,
git commit -a -m 'scheduled commit'

to commit only tracked file that changed, or :
git add -A
git commit -m 'scheduled commit'

to commit new file or delete is even better...

A: The above answer from Philippe works. However, it does not work if it is run somewhere the errorlevel is checked after the execution of commit (like in Jenkins). A small modification solves that:
git add -A
git diff-index --quiet HEAD || git commit -m "scheduled commit"

This is explained further in the original answer on https://devops.stackexchange.com/a/5443

A: Maybe you should call git directly.
Because git does not read from the standard input,  the output of echo means nothing to git through the pipe | .
The solution has been posted by Philippe while I'm editing this answer :)


text:
Q: Is there a similar function to C# Select() in JavaScript? I am new to Javascript and I was wondering is there a similar function in Javascript like C# Select(). My task is from array of people to sort the age of them and select only age of each person and print it. And this is what i come up with:
ageArraySorted = args.sort(function(person1, person2) {
    return person1.age - person2.age;
});

I sorted them and now I need only the values of age property to be printed.

A: Without a library like linq.js the closest analog is the map method on Array;
ageArraySorted = args.sort(function(person1, person2) {
  return person1.age - person2.age;
}).map(function(item) {
  return item.age;
});

A: be careful with Map as a new to javascript
map does not mutate the array on which it is called (although callback, if invoked, may do so).
var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt);
// roots is now [1, 2, 3]
// numbers is still [1, 4, 9]

and map was added to the ECMA-262 standard in the 5th edition;
Feature     Chrome  Firefox (Gecko)     Internet Explorer   Opera   Safari
Basic support   (Yes)   1.5 (1.8)   9   (Yes)   (Yes)
from ...https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map


text:
Q: Need assistance making a batch file for renaming files in separate folders Ok, here's one for you.  I'm trying to use a batch file to rename a bunch of files, but none of them are in the same folder as the batch file itself.  The command prompt keeps telling me that the directory can't be found.  I suppose I could just rename all the files in all the folders that match the filename, but I don't want to do that either; I only want to change certain ones.
My batch file as it stands is:
@echo off
ren "engine/info.txt" "disabled.txt"
ren "gravplating/info.txt" "disabled.txt"
ren "HAWX content/info.txt" "disabled.txt"
ren "laserz/info.txt" "disabled.txt"
ren "NeuroNaval/info.txt" "disabled.txt"
ren "NeuroPlanes/info.txt" "disabled.txt"
ren "NeuroTanks/info.txt" "disabled.txt"
ren "NeuroWeapons/info.txt" "disabled.txt"
ren "WAC Base/info.txt" "disabled.txt"
ren "WAC DamageSystem/info.txt" "disabled.txt"
ren "WAC GravityController/info.txt" "disabled.txt"
ren "WAC Helicopters/info.txt" "disabled.txt"
ren "WAC Sweps/info.txt" "disabled.txt"
ren "weapons/info.txt" "disabled.txt"
ren "AFF_ships/info.txt" "disabled.txt"
ren "AntiTakeRifle/info.txt" "disabled.txt"
ren "Catmull-Rom Cameras/info.txt" "disabled.txt"
ren "Displacer Cannon/info.txt" "disabled.txt"
ren "Drumdevil's Trains/info.txt" "disabled.txt"
ren "EVEOnline/info.txt" "disabled.txt"
ren "gm_botmap_v3/info.txt" "disabled.txt"
ren "gm_construct_flatgrass_v5-2/info.txt" "disabled.txt"
ren "gm_mobenix_v3_final/info.txt" "disabled.txt"
ren "gm_mobenix_v3_highquality_Water/info.txt" "disabled.txt"
ren "gm_snabbansairfield_b1/info.txt" "disabled.txt"
ren "gm_XhS_construct/info.txt" "disabled.txt"
ren "linedraw/info.txt" "disabled.txt"
ren "ModelManipulator/info.txt" "disabled.txt"
ren "NeuroCars/info.txt" "disabled.txt"
ren "Propeller Engine/info.txt" "disabled.txt"
ren "VanDookie and Predaaator's pack/info.txt" "disabled.txt"
ren "WAC ECM/info.txt" "disabled.txt"
ren "WAC Extra Helicopters/info.txt" "disabled.txt"
echo Done!
pause

A: Two things you need to consider:

*

*You should use backslash () to separate between path parts parts, not forward slash (/).

*It is assumed that all the directories you specified are located in the same directory as your script, and that your run your script from the same location as the directories.
So, I recommend correcting it as follows:
rem CD to the directory in which this script is located:
CD "%~dp0"

rem 'Use' '/', not '\'
ren "gravplating\info.txt" "disabled.txt"
ren "HAWX content\info.txt" "disabled.txt"
ren "laserz\info.txt" "disabled.txt"

rem [...]


text:
Q: iOS/UI Automation: UIAActionSheet does not have possibilities to manipulate with buttons My question is related to UI Automation template from XCode's Instruments tool. How does UI Automation support UIActionSheet testing? I know that there is a UIAActionSheet element and I was able to obtain it in my application. But I do not know how to get and manipulate with buttons from the action sheet. UI Automation does not provide any elements for these buttons. The UI Automation documentation does not have any info on the matter either. See the link below. It looks like this control does not use UIButton class for the buttons and renders them in some specific way. Could you give me some clue how to reach the buttons from UIAActionSheet? Thank you.
http://developer.apple.com/library/ios/#documentation/ToolsLanguages/Reference/UIAActionSheetClassReference/UIAActionSheet/UIAActionSheet.html#//apple_ref/doc/uid/TP40009895

A: I have found a solution for the problem using direct tapping simulation. It is not an excellent solution but at least it works. I have asked the same question in the Apple Developer Forum but did not get any response.
So, the function below is my solution. I have tested it and it performs well. I will still continue to search for better approach.
function tapActionSheetButton(target, actionSheet, buttonIndex)
{
    var headerHeight = 28;
    var buttonHeight = 50;

    if (buttonIndex >= 0)
    {
        var actionSheetRect = actionSheet.rect();
        UIALogger.logMessage("actionSheet:{rect:{origin:{x:" + actionSheetRect.origin.x.toString()
                             + ", y:" + actionSheetRect.origin.y.toString()
                             + "}, size:{width:" + actionSheetRect.size.width.toString()
                             + ", height:" + actionSheetRect.size.height.toString()
                             + "}}}");
        var xOffset = actionSheetRect.size.width / 2;
        var yOffset = headerHeight + buttonIndex * buttonHeight + buttonHeight / 2;
        if (yOffset < actionSheetRect.size.height) {
            var tap_x = actionSheetRect.origin.x + xOffset;
            var tap_y = actionSheetRect.origin.y + yOffset;
            target.tap({x:tap_x, y:tap_y});
        }
    }
    else
    {
        var message = "Cannot tap button " + buttonIndex.toString() + ". It does not exist";
        throw message;
    }
}

A: As you can see there is method to return default button for each action sheet, which is Cancel button. As there is no other 'default' buttons for action sheet you need to implement those on your own.
One thing to notice woorth apple reference is that it skips methods for given class which are inherited from parent. UIAActionSheet (like most UIA elements) inherits all methods from UIAElement class. Check this reference. You should be able to get array of all buttons from actionsheet by calling
var arrButtons = objActionSheet.buttons();

Then you can check by name property which one you need (again method from UIAElement name() ).
Alliteratively, if you check which element in array you are interested in you could call  that button directly (assuming, that you won't change ActionSheet) by using UIAElement method elements().
For example if you want to tap second button in ActionSheet tree, you just call
UIATarget.localTarget().frontMostApp().actionSheet().elements()[1].tap();

Maybe you can skip localTarget(), not sure, but code above should work.

A: Since my action sheet was in a popover this returns a nil element:
UIATarget.localTarget().frontMostApp().actionSheet();

This does return the action sheet:
UIATarget.localTarget().frontMostApp().mainWindow().popover().actionSheet();

But it has nil elements() and buttons().
So I used MikhailV's function to tap the buttons.
var target = UIATarget.localTarget();
var actionSheet = UIATarget.localTarget().frontMostApp().mainWindow().popover().actionSheet();
var buttonIndex = 1;

tapActionSheetButton(target, actionSheet, buttonIndex);

A: If you like to keep it organized like me:
function getTarget() {
    return UIATarget.localTarget();
}

function getApp() {
    return getTarget().frontMostApp();
}

function getWindow() {
    return getApp().mainWindow();
}

function tapActionSheetButtonInIndex(index) {
    var actionSheet = getApp().actionSheet() || getWindow().popover().actionSheet();
    actionSheet.buttons()[index].tap();
}


text:
Q: Java save xls file as PDF I have a simple java program that creates .xls file (open office excel file), and I want to save it as pdf. I saw some answers here but none of them worked for me. Is there a simple and free way to do so?
The file contains only 1 page of .xls
Thanks

A: Not sure, please provide more details , share code so that the answer can be more precise, but for code perspective it can  be achieved via Apache POI.something like below ....
 //Instantiate a new workbook with excel file path
Workbook workbook = new Workbook("F:\\FileTemp\\Book1.xls");

//Save the document in Pdf format
workbook.save("F:\\FileTemp\\MyPdfFile.pdf", FileFormatType.PDF);

A: I have published a library that saves files, and handles everything with one line of code only, you can find it here along with its documentation
Github repository
and the answer to your question is so easy
String path = FileSaver
        .get()
        .save(fileXls,"file.pdf");


text:
Q: How to properly extract generic parameters of function in Typescript Usually I use Typescript's Parameters to receive all parameters required by a function of a class:
get = (...params: Parameters<Controller["get"]>) => {}

It works just fine with predefined types in function signature like this: get(id: number).
I'm currently trying to get parameters of function that has the following signature:
functionName<T>(callback: () => Promise<T>)

But with the Parameters it supposes that the T is never and I can't pass my own T into the parameters of such arrow function to get something like Parameters<Controller["get"]<T>> to get proper generic when I call my function like in the beginning.
Edit 1: Minimal Reproducible Example
class Test {
    genericFunction<T>(obj: T): T {return obj;}
    genericFunctionPromise<T>(c: () => Promise<T>): Promise<T> {return c();}

    example(params: Parameters<Test["genericFunction"]>) {};
    examplePromise(params: Parameters<Test["genericFunctionPromise"]>) {params};
}

A: TypeScript 4.7 introduced instantiation expressions as implemented in microsoft/TypeScript#47606, so if you have a value f of a generic function type, you can specify the type parameters of that function without  calling it.  Let's say your function declaration is
declare function f<T, U>(x: T, y: U): [T, U];

Then you can instantiate T and U with, say, number and string, to get a new expression:
const g = f<number, string>; // instantiation expression
// const g: (x: number, y: string) => [number, string]

You can even use the typeof type operator to get the type of such a expression without actually creating one:
type G = typeof f<number, string>;
// type G = (x: number, y: string) => [number, string]

Unfortunately, you can't do this purely at the type level (see this comment on ms/TS#47606).  You need that variable f, or a property of a variable.  If you only have the type of f, then you can't instantiate its type parameters
type F = typeof f;
// type F = <T, U>(x: T, y: U) => [T, U]

type Nope = F<number, string>; // error, F is not generic!

Luckily, inside of Test, you do have a value of the generic function type you care about.  It's this.genericFunction or this.genericFunctionPromise:
class Test {
  genericFunction<T>(obj: T): T { return obj; }
  genericFunctionPromise<T>(c: () => Promise<T>): Promise<T> { return c(); }

  example<T>(
     ...params: Parameters<typeof this.genericFunction<T>>) {
     // error ------------------> ^^^^
  }
  examplePromise<T>(
    ...params: Parameters<typeof this.genericFunctionPromise<T>>
    // error ------------------> ^^^^
  ) { params }
}

new Test().examplePromise(() => Promise.resolve(100));
// (method) Test.examplePromise<number>(c: () => Promise<number>): void

And that actually works... except that there are errors on this in TypeScript 4.7.  Ugh.  This turns out to be a bug in TypeScript, see microsoft/TypeScript#49451.  This bug has been fixed at microsoft/TypeScript#49521, so typescript@next nightly build will work, and it will be released with TypeScript 4.8.
If you need to get this working in TS4.7, you could declare a fake variable of type Test and use it instead, since we just care about types:
declare const __test: Test; // fake

class Test {
  genericFunction<T>(obj: T): T { return obj; }
  genericFunctionPromise<T>(c: () => Promise<T>): Promise<T> { return c(); }

  example<T>(
    ...params: Parameters<typeof __test.genericFunction<T>>) {
  }
  examplePromise<T>(
    ...params: Parameters<typeof __test.genericFunctionPromise<T>>) {
    params
  }
}

Playground link to code


text:
Q: $\text{div} (\mathcal{L},s) = 0$ I am reading a proposition in Prof. Vakil's notes where he shows that if $X$ is a normal and Noetherian scheme, then $\text{div}$ is injective. He opens by saying that if $\text{div} (\mathcal{L},s) = 0$, then $s$ has no poles.
That is fine. What about zeros though? It seems to me that if $s$ has zeros, then the divisor corresponding to it cannot be $0$. Thanks.


text:
Q: Make jquery autocomplete not to fill the input value with the label of selected item Is there any way to make jquery autocomplete plugin only respond to the "select" callback, not to fill the target input with the label value of the selected item after user selection?
I am trying but still no success, waiting for help...
Regards.
Larry

A: I know that this is an old question but, for people that doesn't want to use the setTimeout function, the solution is to change the property ui.item.value to ""
Code:
$('#ac').autocomplete({
    source : ["hello", "how", "do", "you", "do"],
    select: function(event, ui){
        if (ui.item && ui.item.value){
            ui.item.value="";
        }
    }
})

A: Try code below ;)
$('#ac').autocomplete({
    source : ["hello", "how", "do", "you", "do"],
    close: function(event, ui){
          $('#ac').val('');
    }
});

A: Here is an even simpler way (using experimentX's code):
$('#ac').autocomplete({
    source : ["hello", "how", "do", "you", "do"],
    select: function(event, ui){
        $('#ac').css('color','white');
    }
})

A: If your source array is an array of objects with "label" and "value" properties, the plugin handles this for you.
SeejQuery api for autocomplete:

$('#autocomplete').autocomplete({
    source: [
      {
        label: 'This is a descriptive label'
        , value: 'Just the value'
      }
      ,{
        label: '2 is better than one'
        , value: '2'}
      ,{
        label: 'third times the charm'
        , value:'Three'
      }
    ]
  })
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.js"></script>
<input type='text' id='autocomplete'>

SO's code snippet doesn't like it but it works

A: DEMO ON JS FIDDLE
$('#ac').autocomplete({
    source : ["hello", "how", "do", "you", "do"],
    select: function(event, ui){
        setTimeout(function (){
          $('#ac').val('');
        }, 1000)
    }
})


text:
Q: Regular Expression for Removing (nested) Parentheses I am using DOM to get a Wikipedia article as a NSString and then using NSString stringByReplacingOccurrencesOfString:withString:options:range: to remove unneeded things. I'm using regular expressions, which I don't have much experience with. From reading Apple's documentation and just trying things I was able to make this
"\\[[\\w]+\\]"

regular expression which removes the brackets from the Wikipedia article. This works perfectly fine because brackets aren't nested.
Now I am trying to remove parentheses (including everything inside them (and nested ones)) from the NSString. I'm having problems with the nesting part. With this
\\s+\\([^\\)]*+\\)

regular expression I was able to remove a set of parentheses including the space before it (so I don't end up with duplicate spaces after is removed). What regular expression could I use to do this same thing but also remove nested parentheses instead?
My current implementation will change this

The quick brown (slightly reddish) fox jumped over the lazy (he was old (26 years) and exhausted) dog.

into this

The quick brown fox jumped over the lazy and exhausted) dog.

while the desired result is this

The quick brown fox jumped over the lazy dog.

A: I figured it out. This method will return the string without nested parentheses.
-(NSString*)stringWithoutParentheses:(NSString*)input{
     NSString *expression = @"\\s+\\([^()]*\\)";
     while ([input rangeOfString:expression options:NSRegularExpressionSearch|NSCaseInsensitiveSearch].location!=NSNotFound)
     {
          input = [input stringByReplacingOccurrencesOfString:expression withString:@"" options:NSRegularExpressionSearch|NSCaseInsensitiveSearch range:NSMakeRange(0, [input length])];
     }
     return input;
}

With this method, passing

The quick brown (slightly reddish) fox jumped over the lazy (he was old (26) and exhausted) dog.

will return

The quick brown fox jumped over the lazy dog.


text:
Q: bootstrap modal does not show,only showing backdrop I have posted this before but no one has reply me on my problem. However, after trying for few days. I encountered something funny.
My View Code
<% provide(:title, "Log in") %>

 Kaching

    <%= form_for(:session, url: login_path) do |f| %>

    <%= f.label :logID, "Log ID" %>
    <%= f.text_field :logID %>

    <%= f.label :password %>
    <%= f.password_field :password, class: 'form-control' %>

    <%= f.submit "Log In", class:"btn btn-primary" %>
    <% end %>

<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

        <button type="button" class="close" data-dismiss="modal">×</button>

Modal Header

Some text in the modal.

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

When i include the  code, the modal box will appear when i load the page. However, my modal still will not appear when i press the button. I do not understand why. It will only work when i include bootstrap.js in my /assets/javascripts folder. However, this affects my tab that i implement on my other page. I try loading just the bootstrap-modal.js file, but it did not work also. Please guide me on this.
Thanks


text:
Q: How to recursively(as in math) add a count of items from a list inside a for in range block? If I am to count the number of times vowels are used in a given text, how do I make a code skim through the text to identify all the vowels as items from a list and yet add the counts of each vowel to get a total vowel count, where the given text might incluse repeated vowels? (said recursive because I need to add new nth y to (n-1)th y.)
I'm a beginner as is obvious from the below code, I do not have any knowledge of a library of functions but the purpose of the exercise(a challenge in a mobile app), I believe, is to  come up with an answer just with a basic knowledge of lists, strings, loops etc.
vowels=["a","A","e","E","i","I","o","O","u","U"]
exprs=input("Please type an expression to get a count of the vowels it has: ")

Ind= len(vowels)
eL=list(exprs)

for i in range(Ind):
    x=vowels[i]
    if x in exprs:
        y=eL.count(x)
        print("\n\nThe number of times that vowel",x,"occurs in", exprs, "is",y)
        print("The vowel",x,"occurs in the given expression at index",str(eL.index(x)) + ".")

I cannot find a way to recursively add y values (tried y=0 outside the loop and then y=y+eL.count(x) and some other ideas to no avail.)
Then I searched about it and bumped into apparently a rule of thumb that "dynamic naming" is never good for languages, HLL, I guess?
I had some other ideas but I think I bump into this same problem everytime. I am not even sure these have to do with the same thing. Seems like I created my own paradox by this code. Any help would be appreciated.

A: If you just want to count how many times every letter in the vowels list appear in a string txt:
vowels = ["a","A","e","E","i","I","o","O","u","U"]
txt = 'hello world abcdef'

frequency = {}
total = 0
for i in txt:
    if i in vowels:
        frequency[i] = frequency.get(i, 0) + 1
        total += 1

print(frequency)
print('total:', total)

This will print the following:
{'e': 2, 'o': 2, 'a': 1}
total: 5

Meaning 'e' appears twice and so on, and the total number of vowels present