text:
Q: Why does my multiprocessing code take so long to complete in python 3.9, but not python 2.7. Code improvements? I have some code that uses multiprocessing to perform some work with apply_async and while it is working, I update the main GUI and allow other activities to be performed.  Everything seems to work just fine in python 2.7, however, I am running into issues running the code in python 3.9.  My overall issue is that it is just not working any more, but in putting together the sample debug code below (which does work) I have noticed a significant increase in the amount of time it takes for my process to complete in 3.9 vs 2.7.
Simplified code is as follows:
import multiprocessing
import time
import datetime

def main():
    start_time = datetime.datetime.now()
    print('Spinning up pool')
    pool = multiprocessing.Pool(processes=10)
    vals = range(100)
    results = []
    print('Adding processes')
    runs = [pool.apply_async(calc, (x, 1), callback=results.append) for x in vals]

    print('Working...')
    while len(vals) != len(results):
        print('Results: {}'.format(results))
        time.sleep(1)

    pool.close()
    pool.join()
    print('Done')
    end_time = datetime.datetime.now()
    duration = end_time - start_time
    print('Program took {} seconds to complete'.format(duration.total_seconds()))

def calc(x, y):
    print(x + y)
    time.sleep(2)
    return(x+y)

if __name__ == "__main__":
    main()

python 2.7:
Program took 48.965 seconds to complete
python 3.9:
Program took 372.522254 seconds to complete
Is there a reason this takes so much longer in 3.9 vs 2.7?  Is there any modifications to my code to speed things up a bit?  Is there a better way to process tasks like this while waiting for a pool to finish up all the work?
Operating system is Windows 10.

A: I could not find a significant difference in running times between Python 3.8 and Python 2.7 on Windows. But the way I would approach solving the problem is by noting that your worker function calc is mostly wait time and a small amount of CPU-required calculations. So one thing you could do is to increase your pool size significantly since your processes will be in a wait state most of the time.
But better would be to use a thread pool of size 100 (since you are submitting 100 tasks) and pass to your worker function a multiprocessing pool (whose size is the number of cores you have) that can be used for performing the calculations that require actual CPU. And since it appears that your results list will contain return values from your worker function in completion order, you might as well use the multiprocessing.pool.ThreadPool.imap_unordered method rather than multiple calls to apply_async:
import multiprocessing
import time
import datetime
from functools import partial

def main():
    start_time = datetime.datetime.now()
    pool = multiprocessing.Pool()
    thread_pool = multiprocessing.pool.ThreadPool(100)
    vals = range(100)
    worker = partial(calc, y=1, pool=pool)
    results = list(thread_pool.imap_unordered(worker, vals))
    end_time = datetime.datetime.now()
    duration = end_time - start_time
    print('Program took {} seconds to complete'.format(duration.total_seconds()))
    print(results)
    pool.close()
    pool.join()
    thread_pool.close()
    thread_pool.join()

def calc(x, y, pool):
    result = pool.apply(do_add, (x, y))
    print(result)
    time.sleep(2)
    return result

def do_add(x, y):
    return x + y

if __name__ == "__main__":
    main()

Prints:
4
10
9
6
...
51
27
96
87
21
Program took 2.276529 seconds to complete
[4, 10, 30, 82, 36, 70, 83, 13, 12, 46, 71, 62, 59, 16, 73, 8, 9, 80, 72, 55, 11, 7, 43, 65, 35, 19, 61, 76, 60, 3, 57, 48, 49, 6, 45, 34, 41, 33, 31, 37, 22, 29, 24, 67, 32, 18, 14, 1, 23, 2, 15, 64, 53, 58, 98, 95, 40, 47, 39, 54, 92, 89, 93, 42, 85, 38, 99, 5, 78, 74, 25, 63, 84, 56, 91, 69, 79, 50, 44, 100, 90, 86, 81, 77, 94, 68, 28, 26, 17, 20, 87, 75, 96, 66, 52, 51, 21, 88, 27, 97]

Discussion
If your worker function, calc, really were as trivial as above, i.e. requiring only a simple addition operation, then I would not bother even using a multiprocessing pool for doing this calculation; I would just use a multithreading pool because it would be less expensive to do the addition in calc compared with submitting a task to the multiprocessing queue. But assuming your actual worker function contains significant CPU requirements, the idea is to break out those CPU calculations into one or more new functions and only retain in your original worker function code that is thread-efficient (e.g. I/O operations, network operations, sleeping, etc., i.e. operations that put the thread into a wait state and therefore allow another thread to execute). The CPU-intensive calculations are then done by using method apply on the multiprocessing queue passing the new CPU-intensive functions you have created (or use method apply_async if you have multiple, unrelated calculations that you can perform in parallel).


text:
Q: Find exactly string "pattern" with awk when two string have similar words I have one file with many lines, I want to get values from columns where this exactly pattern exist: "Enhanced CAR_Red per time", but in the file, there are another string that has similar words: "Wash Enhanced CAR_Red per time". I want to look for the fist string only. I tried to put "^" and "$" but they only works at the begining of the line.
Is there some sugestion?
Thanks
This is one exemplo of the lines that contain the original file:
Cn Operator Index  Operator Name  License Identifier  Description
0                  DODGE          ID20                Enhanced CAR_Red per time
0                  DODGE          ID27                Wash Enhanced CAR_Red per time

I'm looking for "Enhanced CAR_Red per" to get "License Identifier", but I recibe two registers.

A: awk -F'\t' '$NF~/^Enhanced CAR_Red per/{ print $(NF-1) }' file

A: I haven't used AWK before, but in general when using regular expressions here are some good tricks to solve your problem.
You could add some extra specification to what IS acceptable before "Enhanced CAR_Red per time". If the line should begin with that string, the use "^", but if you know want to allow additional spaces or commas (whatever would denote only this specific term you are searching for) then add them as well.
For example, if you're looking through a list delimited with commas, then make make the term "[, ]*Enhanced CAR_Red per time"
If the term "Wash Enhanced CAR_Red per time" is the only occurrence of error you could also specify something along the lines of "Enhanced CAR_Red per time" && !"Wash Enhanced CAR_Red per time" to specify that you don't want Wash in there

A: You can do this to suppress the lines with "Wash Enhanced CAR_Red per time" before starting awk:
grep -v "Wash Enhanced CAR_Red per time" yourfile | awk '/Enhanced CAR_Red per time/{print}'

redpajama_set_name: RedPajamaStackExchange


text:
Q: jQuery UI DatePicker to show month day only jQuery UI DatePicker to show month day only.Where user can only select month and day (mm/dd). And the date picked as mm/dd format

A: The following only shows the month and day part of the date picker and displays the date in the mm/dd format.

$(() => {
  $( "#datepicker" ).datepicker({
    minDate: new Date((new Date()).getFullYear(), 0, 1),
    maxDate: new Date((new Date()).getFullYear(), 11, 31),
    hideIfNoPrevNext: true,
    dateFormat: 'mm/dd'
  });
});
.ui-datepicker-year {
  display: none;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.12.4.js"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<input id="datepicker" type="text">

A: You can set properties to datepickr like below.
$('#textBoxID').datepicker({
     changeMonth: true,
     changeDate: true,
     showButtonPanel: true,
     dateFormat: 'mm/dd'
});

A: Are you looking to render the calendar to show only Month and Day?  Or you simply want to the get the month and day from the calendar?
You can use the date format option or use set or get the variable.
// jQuery Date Picker option:
$('.selector').datepicker({
   dateFormat: 'mm/dd'
});

// Getter
var dateFormat = $( ".selector" ).datepicker( "option", "dateFormat" );

// Setter
$( ".selector" ).datepicker( "option", "dateFormat", "mm/dd" );

Documentation here. http://api.jqueryui.com/datepicker/#option-dateFormat
If you want to render only the month and day for the user to select. I would consider using moment.js to create a table or something.


text:
Q: Making rMaps Leaflet Maps Full-screen I'm having some difficulty getting rMaps leaflet to be full-screen in R-shiny. Can anyone point me the right way on this?
ui.R:
library(shiny);library(rCharts)
shinyUI(navbarPage("rMaps Leaflet Sizing",
  tabPanel("Map",
#  tags$style('.leaflet {height: 100%; width: 100%}'), --no change
    mapOutput('mapPlotJSON')
  )
))

server.R:
library(shiny);library(rCharts);library(rMaps)
shinyServer(function(input, output, session) {
  output$mapPlotJSON <- renderMap({
    map1 = Leaflet$new()
    map1$setView(c(45.5236, -122.675), 13)
    map1$tileLayer(provider ='Stamen.Terrain')
#   map1$set(width = "100%", height = "100%") --doesn't show map
    map1
  })
})

A: I have had the same problem. I would suggest using the tips in the following page
http://www.d3noob.org/2014/02/make-your-leafletjs-map-full-screen.html
e.g., in your .css file add:
body {
  height: 100%;
  width: 100%;
}

html {
  height: 100%;
  width: 100%;
}

.leaflet {
  height: 100%;
  width: 100%;
}

A: It should be map1$fullScreen(TRUE)
See example in https://github.com/ramnathv/rCharts/issues/290#issue-21794686


text:
Q: Powershell Join I have an AD query to export all groups membership, that works perfectly.
Get-QADUser -searchRoot $OuDomain -SizeLimit 0
| Select-Object dn, sAMAccountName, @{Name="Groups";Expression={(Get-QADMemberOf $_
| Select-Object -expandProperty Name) -join ";"}}
| export-csv $FilePath | Sort-Object SamAccountName

Result :
DN        SamAccountName    Groups
abc.com   user1             group1;group2;group3

How to export the above results in columns, like :
DN       SamAccountName  Groups
abc.com  user1           group1
         user1           group2
         user1           group3

Please check http://pastebin.com/JMZ863YY

A: Instead of the -join, whose purpose is to keep one (user) to many (group) record, you'll need to do something like this (untested). Give it a try:
$users = Get-QADUser -searchRoot $OuDomain -SizeLimit 0
$users | Sort-Object SamAccountName | % {
    $user = $_ | Select-Object dn, sAMAccountName
    if ($lastDomain -eq $user.dn) {
        $lastDomain = ""
    } else {
        $lastDomain = $user.dn
    }
    $groups = Get-QADMemberOf $_ | Select-Object -expandProperty Name
    $groups | % {
        $user2 = New-Object -TypeName PsObject -Property @{
                "Domain" = $lastDomain
                "sAMAccountName" = $user.sAMAccountName
                "Group" = $_
            }
        $user2
    }
} | export-csv $FilePath


text:
Q: Change Language Hotkeys reset for no reason (Windows 10) Hey I'm using Windows 10. I created some hotkeys to change the keyboard layout to a specific language: Alt+Shift+1 changes the layout to language A, Alt+Shift+2 changes it to language B. The steps I took are also described here Link.
The steps I did are:

*

*Settings

*Devices

*Typing

*Advanced keyboard settings

*Input language hot keys

*Advanced key settings

*Change Key Sequence: to Language A and to Language B

The keyboard shortcuts works fine for a while. I think after I restart or hibernate the system (or maybe just after some time, not sure) the hotkeys reset as if they were never set in the first place.
Edit: This seems to be a bug indeed and is happening after rechanging a dozen times. Users who need a hotkey can use Win + Space to change the language (it's a little bit slower but gets the job done).


text:
Q: Count word based on category in codeigniter and sql I found problem to make a report based on report table, for more detail please check this out :
My SQL Table
+----+-----+------------+--------------+
| No | ID  | Asset      | Link         |
+----+-----+------------+--------------+
| 1  | 203 | Asset A    | Clear        |
| 2  | 204 | Asset B    | Clear        |
| 3  | 205 | Asset A    | Not Clear    |
| 4  | 206 | Asset A    | Not Clear    |
| 5  | 208 | Asset A    | Need Confirm |
| 6  | 210 | Asset B    | Clear        |
| 7  | 212 | Asset B    | Not Clear    |
| 8  | 213 | Asset B    | Clear        |
| 9  | 214 | Asset A    | Clear        |
| 10 | 215 | Asset B    | Need Confirm |
| 11 | 216 | Asset B    | Need Confirm |
+----+-----+------------+--------------+

based on table above, i want to show information like below :
+----+--------------+-------+-----------+--------------+
| No | Count Asset  | Clear | Not Clear | Need Confirm |
+----+--------------+-------+-----------+--------------+
| No | Asset A      |   2   |     2     |       1      |
| No | Asset B      |   3   |     1     |       2      |
+-------------------+-------+-----------+--------------+
|  Total            |   5   |     3     |       3      |
+-------------------+-------+-----------+--------------+

i already read some reference about pivot table in sql, tried this code :
Controller :
$data_get= $this->db->query("SELECT asset,
                        COUNT(CASE WHEN (link='Clear') THEN 1 ELSE 0 END) as clear,
                        COUNT(CASE WHEN (link='Not Clear') THEN 1 ELSE 0 END) as not_clear,
                        COUNT(CASE WHEN (link='Need Confirmation') THEN 1 ELSE 0 END) as need_confirm
                        FROM tbl_master GROUP BY asset");

Views :
<?php
    foreach($data_get->result_array() as $dp)
    {
    ?>

        <?php echo $dp['asset']; ?>
        <?php echo $dp['clear']; ?>
        <?php echo $dp['not_clear']; ?>
        <?php echo $dp['need_confirm']; ?>

     <?php
        }
     ?>

from my code above i got an error, there's undefined variabel..
i'm newbie here, if there correction or any advice, please inform, thanks

A: Controller :
1st : You need to get the result in controller and send the result to view like below.
2nd : And follow  @Tim Biegeleisen  answer too . you need to use sum
$data_get['result'] = $this->db->query("SELECT asset,
                        SUM(CASE WHEN link = 'Clear'             THEN 1 ELSE 0 END) AS clear,
                        SUM(CASE WHEN link = 'Not Clear'         THEN 1 ELSE 0 END) AS not_clear,
                        SUM(CASE WHEN link = 'Need Confirmation' THEN 1 ELSE 0 END) AS need_confirm
                        FROM tbl_master GROUP BY asset")->result_array();

$this->load->view ('home', $data_get);

In view :
foreach($result as $row){

}


text:
Q: Don't want to use Registry in Windows Service I want to remove registry dependency in my Windows service written in C#. and want to maintain Event Logs under Event Viewer under application.
I am using the below code which does not seem correct as I do not want to use Registry.
I am getting Source property was not set before writing to the event log.
Please advice.
public Service()
{
    try
    {
        InitializeComponent();
        if(!System.Diagnostics.EventLog.SourceExists("VWinService"))
            System.Diagnostics.EventLog.CreateEventSource("VWinService","");
        eventLog1.Source = "VWinService";
        eventLog1.Log = "";

    }
    catch (Exception ex)
    {
        eventLog1.WriteEntry("Error in Service Constructor.  Error message = " + ex.Message.ToString(), EventLogEntryType.Error);
    }
}

 private void InitializeComponent()
    {
        this.eventLog1 = new System.Diagnostics.EventLog();
        this.tmrSend = new System.Timers.Timer();
        ((System.ComponentModel.ISupportInitialize)(this.eventLog1)).BeginInit();
        ((System.ComponentModel.ISupportInitialize)(this.tmrSend)).BeginInit();
        this.tmrSend.Elapsed += new System.Timers.ElapsedEventHandler(this.tmrSend_Elapsed);
        this.AutoLog = false;
        this.ServiceName = "VWinService";
        ((System.ComponentModel.ISupportInitialize)(this.eventLog1)).EndInit();
        ((System.ComponentModel.ISupportInitialize)(this.tmrSend)).EndInit();
    }

A: An event source need only be defined once at installation time, an action that generally requires administrative privilege and is performed by your installer.  Once the event source exists, you can write event entries using just the source name.
Writing one error to the event log is:
EventLog eventLog = new EventLog();
eventLog.Source = "VWinService";
eventLog.WriteEntry(ex.Message, EventLogEntryType.Error, 0);

The logic to create the event source
if(!System.Diagnostics.EventLog.SourceExists("VWinService"))
    System.Diagnostics.EventLog.CreateEventSource("VWinService","");

belongs in an installer and need not be repeated in your service application code.  If you have created your service application using a Visual Studio wizard, then this is handled for you in autogenerated ProjectInstaller classes.
If you intend to use event logs and install your service, then there will necessarily be registry entries on Windows.  Creating these required registry entries is the responsibility of your software installer.  For example, see InstallUtil which uses the ProjectInstaller classes to install your service application.  Be assured that your client will understand and agree that registry settings created by an installer to register your application as a service and use the event log are normal and required for your application.
You should be able to entirely avoid using the registry for your application settings.  For simple configuration values, you can add entries in app.config like so:
<configuration>
  <appSettings>
    <add key="myStringSetting" value="My string value"/>
    <add key="myNumericSetting" value="73"/>
  </appSettings>
</configuration>

Your code will use the System.Configuration namespace to read settings:
using System.Configuration;

You read the configuration values in your code like so:
string myString = ConfigurationManager.AppSettings["myStringSetting"];
int myNumber = Convert.ToInt32(ConfigurationManager.AppSettings["myNumericSetting"]);

If the organization of the existing registry settings is much more complex, then you should create a Custom Configuration Section.  Describing in detail how to do this is far beyond the scope of your original question.  Please refer to the documentation or create a new question.

A: You cannot avoid using the registry, either for event logs, or, in fact, for services themselves. You have misinformed your client. Your client should tell you why they think they don't want to use the registry.
If it were even possible, then your client would be the only ones in the world not to use the registry. The registry is an inherent part of Microsoft Windows, and has been for a very long time. Your client is no doubt misinformed about the registry, such that he thinks he wants to avoid it.
You will do your client the greatest favor by learning how Windows Services (and the event logs) use the Registry, then educating your client about that.


text:
Q: I know I can't return a value from an asynchronous function, so how can I restructure this code to get a value back to the caller? I know the title is a bit vague but I don't know how else to ask this and I'm having trouble wrapping my head around async javascript.
I'm writing a nodeJS app and I want to write a function that takes some xml input, converts it to JSON, cleans it up a bit, and returns it. I'm using the xml2js module to achieve this but I'm having some trouble because xml2js is asynchronous. Here's is a simplified version of my code:
function cleanUpData(xmlData) {
    xml2js(xmlData, xml2jsCallback);

    function xml2jsCallback(err, result) {
        // do a bunch of additional cleanup
        return cleanedUpJSON;
    }
}

What I want is to be able to pass the xml to the cleanUpData function and get back the nice JSON, but since xml2js() is async, I can't really do that. I would need to do everything else I want to do inside the xml2jsCallback() function and no value would ever be returned. I'm just trying to write a simple utility function though. Is the answer that I just can't use xml2js for this purpose? I'd really appreciate some insight because I'm pretty sure I must be unfamilair with some js coding pattern that will accomplish what I need.

A: Callback syntax:
function cleanUpData(xmlData, callback) {
    xml2js(xmlData, function(err, result){
        callback(result);
    });
}

cleanUpData(xmlData, function(jsondata){
    // do stuff here with jsondata
});

Promise syntax:
function cleanUpData(xmlData) {
    return new Promise(function(done){
        xml2js(xmlData, function(err, result){
            done(result);
        });
    });
}

cleanUpData(xmlData).then(function(jsondata){
    // do stuff here with jsondata
});


text:
Q: Google Custom Search API returning invalid JSON? I'm calling Google Custom Search w/ Node.js to try.  I'm getting results back just fine, but when I try and parse the JSON using JSON.parse(dataFromGoogle), I get illegal token errors on a number of elements (html titles and snippets; the html titles have unicode escape sequences in them, but I'm not sure what's wrong w/ the snippets).  I can have Google not send me back the html titles, but I really need the snippets!
Is there a good work-around on this, or should I just plan on doing some additional preprocessing to strip out illegal characters manually?
** Edit: added console output from this
searching for "small business" using Google

{
   "kind": "customsearch#search",
   "url": {
    "type": "application/json",
    "template": "https://www.googleapis.com/customsearch/v1?q={searchTerms}&num={count?}&start={startIndex?}&hr={language?}&safe={safe?}&cx={cx?}&cref={cref?}&sort={sort?}&filter={filter?}&gl={gl?}&cr={cr?}&googlehost={googleHost?}&alt=json"
   },
   "queries": {
    "nextPage": [
     {
      "title": "Google Custom Search - small business",
      "totalResults": "42300",
      "searchTerms": "small business",
      "count": 10,
      "startIndex": 11,
      "inputEncoding": "utf8",
      "outputEncoding": "utf8",
      "safe": "off",
      "cx": "my_token"
     }
    ],
    "request": [
     {
      "title": "Google Custom Search - small business",
      "totalResults": "42300",
      "searchTerms": "small business",
      "count": 10,
      "startIndex": 1,
      "inputEncoding": "utf8",
      "outputEncoding": "utf8",
      "safe": "off",
      "cx": "my_token"
     }
    ]
   },
   "context": {
    "title": "IR
  undefined:60
     "htmlTitle": "\u003cb\u003eSmall Business\u003c/b\u003e Health Care Tax Cre
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  SyntaxError: Unexpected token ILLEGAL
      at Object.parse (native)
      at IncomingMessage. (/Users/pvencill/workspace/irslab/lib/searchEngine.js:44:35)
      at IncomingMessage.emit (events.js:64:17)
      at HTTPParser.onBody (http.js:119:42)
      at CleartextStream.ondata (http.js:1213:22)
      at CleartextStream._push (tls.js:291:27)
      at SecurePair._cycle (tls.js:565:20)
      at EncryptedStream.write (tls.js:97:13)
      at Socket.ondata (stream.js:40:26)
      at Socket.emit (events.js:64:17)

A: Wow, so it turns out I totally misunderstood what the error was telling me.  The fact that it was happening on unicode-containing fields was coincidence.  The real issue was that I was calling JSON.parse inside the .on("data", ...) handler, which is handling part of the chunked response; might not be valid JS statement terminator before the chunk completes.  The proper way to handle it is to build the body and then use on("end") to parse it.
        var message = "";
        https.get(options, function(res){
            res.setEncoding('utf8');
            res.on('data', function(data){
                message += data;
            });

            res.on('end', function(){
                if(callback){
                    var data = JSON.parse(message);
                    data.items = data.items || [];
                    callback(data);
                }
            });

            res.on('error', function(error){
                console.log("ERROR" + error.message);
            });


text:
Q: How to prevent access to WordPress blog by ip? I am having problems as some computer from an IP address is trying to access all the files on my server.
How should I change the .htaccess file so that IP address gets NO access at all to any files? And which .htaccess file do I change? It looks like I have one inside each folder.

A: The basic mod_access module should get you what you need
Order allow,deny
Allow from all
Deny from xxx.xxx.xxx.xxx

Something like that. I dont know the exact syntax. Keep in mind that depending on your exact version of Apache (1.3/2.0/2.2) then the module requirements might be different. I think in 2.2 you need the authz_host module, but in 1.3 its mod_access.

A: For simple cases, you can try http://wordpress.org/extend/plugins/wp-ban/, which can keep IP or IP range from visiting your blog.
If that's not enough, you can modify .htaccess as follows

Deny from xx.xx.xx.xx/xx
Allow from ALL

A: Another way, this time using mod_rewrite rules in a .htaccess file.
RewriteEngine on
RewriteCond %{HTTP_HOST} ^123.123.123.123$
RewriteRule ^(.*)$ blocked.html [L,F]

[L,F] means 'stop executing further rules, and return 403 Forbidden as the HTTP status'. blocked.html could contain a message indicating that they've been blocked.


text:
Q: C# Cross thread event not fired I'm developing a telegram bot from scratch, without using libraries that aren't mine. I'm now converting my library to be event based, so i not have to hardcode everything on the library itself and i can work with more libraries together.
So far I have:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using TelegramSharp.Core;
    using TelegramSharp.Core.Objects;
    using System.Threading;
    namespace Bot {
        class Program {
            static void Main(string[] args) {
                BotSetup CFG = ConfigManager.LoadConfig("cfg.json");
                TelegramService TS = new TelegramService(CFG);
                TS.Init();//instantiates all classes that telegramService uses.
                TS.Parser.UpdateReceived += Parser_UpdateReceived;//this stays null. ???
                Thread Telegram = new Thread(TS.Start);
                Telegram.Start();
            }

            private static void Parser_UpdateReceived(object sender, UpdateReceivedEventArgs args) {
                throw new NotImplementedException();
            }
        }
    }

the problem is marked on the comments, when i subscribe to the event, the event stays null. And my NotImplementedException is never raised.
this is how i declared the event on MessageParserClass
    public delegate void UpdateReceivedHandler(object sender, UpdateReceivedEventArgs args);
    public event UpdateReceivedHandler UpdateReceived;
    protected virtual void OnUpdateReceived(Message message, User bot) {
        UpdateReceived?.Invoke(this, new UpdateReceivedEventArgs(message, bot));
    }

and here the event is raised
    public void ParseMessage(Message msg, TelegramService bot) {
        parsedMessagesCount++;
        if (msg.Text != null /*&& msg.Date >= ToUnixTime(DateTime.UtcNow) - 10*/) {
            OnUpdateReceived(msg, bot.BotIdentity);
            OnTextMessageReceived(msg, bot.BotIdentity);
        }
    }

This happens to all the events i declared in this project (all declared and used in the same way). Is this happening because the Program class is static (and the method that subscribes too) or what? How i can fix and succesfully raise the events?

A: I finally solved this issue. It was related to a stupid mistake, here you clearly see why, basicalli i first execute Init(), instantiating all the classes that i need, then i subscribe to the event and later i start my bot, using Start() (that was made in an earlier version of the library), inside start i recreate the classes, so my event would have always been null.
Thanks anyway to everyone tryed to help me.


text:
Q: I'm trying to trigger hover of DOM element by JS, but failed. It seems this is impossible. But why Chrome could do it? How? I'm trying to trigger hover of DOM element by JS, but failed. It seems this is impossible.
I know there is a way to do this is create a class with hover function and do add/remove this class to achieve the same stage.
But why Chrome could do it? How?

A: You can't do it. It's not a trusted event.
You can just simulate it with classes manually.
Browser can do it throw internal API/Methods.
You can check an source code of Chrome devtools for this action.
It's triggers method forcePseudoState for the CSSModel.


text:
Q: How to color labels of dendogram with dendextend and heatmap.2 using pre-defined sample groups heatmap.2 assigns incorrect colors to labels when using "colRow" argument. Is there an alternative way how to assign colors to labels in heatmap.2? Or am I doing something wrong? (examples are based on examples from Label and color leaf dendrogram and How to color the branches and tick labels in the heatmap.2?)
library(dendextend)
library(gplots)

#make dataset
sample = data.frame(matrix(floor(abs(rnorm(20000)*100)),ncol=1000))
groupCodes <- c(rep("Cont",5), rep("Tre1",5), rep("Tre2",5), rep("Tre3",5))
rownames(sample) <- make.unique(groupCodes)
colorCodes <- c(Cont="red", Tre1="green", Tre2="blue", Tre3="yellow")

#calculate distances, cluster
distSamples <- dist(sample)
hc <- hclust(distSamples)
dend <- as.dendrogram(hc)

# Assign the labels of dendrogram object with new colors:
labels_colors(dend) <- colorCodes[groupCodes][order.dendrogram(dend)]
col_labels<-labels_colors(dend)

# plot dendrogram
plot(dend,main ="colors of labels OK")

# plot dendogram and heatmap with heatmap.2
sample.datamatrix<-data.matrix(sample)
heatmap.2(sample.datamatrix, scale="row",
          trace="none",
          dendrogram="row",
          colRow = col_labels, # to add colored labels
          Rowv = dend,
          main="colors of labels mixed-up",
          labCol = FALSE) # hide column names (i.e. gene names)

A: ash, you need to keep col_labels in the original order of the data.
Here is the modified code: (find the "WHAT I CHANGED" comment)
library(dendextend)
library(gplots)

#make dataset
sample = data.frame(matrix(floor(abs(rnorm(20000)*100)),ncol=1000))
groupCodes <- c(rep("Cont",5), rep("Tre1",5), rep("Tre2",5), rep("Tre3",5))
rownames(sample) <- make.unique(groupCodes)
colorCodes <- c(Cont="red", Tre1="green", Tre2="blue", Tre3="yellow")

#calculate distances, cluster
distSamples <- dist(sample)
hc <- hclust(distSamples)
dend <- as.dendrogram(hc)

# Assign the labels of dendrogram object with new colors:
labels_colors(dend) <- colorCodes[groupCodes][order.dendrogram(dend)]
col_labels<-labels_colors(dend)

# plot dendrogram
plot(dend,main ="colors of labels OK")

# <================= WHAT I CHANGED ===================>
# The labels need to be in the order of the original data:
col_labels <- colorCodes[groupCodes]
# </================= WHAT I CHANGED ===================>

# plot dendogram and heatmap with heatmap.2
sample.datamatrix<-data.matrix(sample)
heatmap.2(sample.datamatrix, scale="row",
          trace="none",
          dendrogram="row",
          colRow = col_labels, # to add colored labels
          Rowv = dend,
          main="colors of labels mixed-up",
          labCol = FALSE) # hide column names (i.e. gene names)


text:
Q: UITextView searching for keywords in a database I want to check if the user types specific phrases in a UITextView for a science app. I have this current code that creates a string of the last 20 characters then checks if that string contains a word in the arrayOfWords which gets performed on textViewDidChange:
var arrayOfWords = ["Gold", "Phosphorus"]

func textViewDidChange(_ textField: UITextView) {
    if let selectedRange = textView.selectedTextRange {
        let cursorPosition = textView.offset(from: textView.beginningOfDocument, to: selectedRange.start)
        let startRange = cursorPosition - 20
        let result = textView.text.substring(from: startRange, to: cursorPosition)

        checkIfContains(textViewString: result)
    }}

func checkIfContains(textViewString: String)  {
    if arrayOfWords.contains(where: textViewString.contains) {
        doAction()
    }
}

I know this is a very specific function so any ideas on how I could go about achieving this would be greatly appreciated.

A: Try to look at a regular expression (REGEX).
In your case the regex should look like "([A-Za-z]\w+ [1-9]\.[1-9]*)  " ( note the space at the end )
Then in your textViewDidChange, as soon as the text matches the regex you can trigger your fetching method, and considering there is a space at the end it will only trigger when the user press space as you said.
Here is a link to try your regex : https://regexr.com/
And here is an example of using regex in swift : https://stackoverflow.com/a/27880748/5464805

A: You can separate string and try to cast it to Float:
    let someText = "here will be text from textView 3.5"
    let arrayOfWords = someText.split(separator: " ")

    // more than two words? if not, exit
    guard arrayOfWords.count >= 2 else { return }

    // now you can check if last `word` ca be a Float
    let last = String(arrayOfWords.last ?? "")
    if let number = Float(last), let wordBefore = arrayOfWords[arrayOfWords.count - 2] {
        // here you have number
        print(number)

        // here word before
        print(wordBefore)
    }


text:
Q: Substring function in XSLT behaves strange I'm searching for a keywords element that contains a value "by " and I want to extract the name that follows from it.
For example the keywords element can have a value "by John Doe" and I want to extract "John Doe", so I can use this name in another selection.
The simplified XML looks like this:

    <title>Blog Article</title>
    <keywords>by John Doe</keywords>

    <title>John Doe</title>

An this is the related XSL:
<xsl:template match="article">
    <xsl:for-each select="keywords">
        <xsl:if test="contains(current(), 'by ')">

                <xsl:value-of select="substring(current(), 3)"/>

                <xsl:value-of select="//article[title = 'John Doe']"/>

                <xsl:value-of select="//article[title = (substring(current(), 3))]"/>

        </xsl:if>
    </xsl:for-each>
</xsl:template>

The results for each value-of are:

*

*John Doe

*Selects the article element I need as expected

*PROBLEM: doesn't select anything.
So, since I am getting the expected results in the second hardcoded value-of, perhaps I am missing something fundamental about the substring function or in the given context?
Obs: I also tried setting a variable to substring(current(), 3) and referencing it instead of the hardcoded path ('John Doe') with no luck, I got the same behavior.
Does anyone have any ideea why this might happen?

A: The index into an XPath string starts with 1 so given by John Doe I think you want //article[title = substring(current(), 4)].


text:
Q: Render to texture or offscreen framebuffer I have a problem with rendering to texture and offscreen framebuffer with OpenGLES on iPhone.

(source: imagehost.org)

(source: imagehost.org)
First image shows mahjong tiles rendered to CAEAGLLayer directly and this is correct. Second one shows tiles rendered to offscreen framebuffer, copied to texture using glCopyTexImage2D and the texture rendered to CAEAGLLayer. Both use white opaque quad for background. I also have tried rendering directly to texture but effect was the same as with offscreen framebuffer.
My code for creating framebuffer:
    GLuint framebuffer;
    glGenFramebuffersOES(1, &framebuffer);
    glBindFramebufferOES(GL_FRAMEBUFFER_OES, framebuffer);

    GLuint renderbuffer;
    glGenRenderbuffersOES(1, &renderbuffer);
    glBindRenderbufferOES(GL_RENDERBUFFER_OES, renderbuffer);
    glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_RGB8_OES,
            512, 512);

    glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES,
            GL_RENDERBUFFER_OES, renderbuffer);
I draw all tiles from a texture atlas with one call to glDrawElements using VBO for passing interlaced vertex data (coordinates, texture coordinate, color). I use RGBA8888 texture format, drawing each image on two triangles (quad) with glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) blending function. I do not use depth buffer (in all cases).
Can somebody tell me what could be the problem?

A: It seems that you haven't posted enough of the code but from what is posted it seems that you fused together the roles of the texture and renderbuffer in your FBO. (your post title said render to texture)
Also you forgot to define your draw buffers.
The render buffer attached to an FBO is usually used as a Depth Buffer.
Therefore try the following:
GLuint framebuffer;
glGenFramebuffersOES(1, &framebuffer);
glBindFramebufferOES(GL_FRAMEBUFFER_OES, framebuffer);

//set up the Depth Buffer
GLuint renderbuffer;
glGenRenderbuffersOES(1, &renderbuffer);
glBindRenderbufferOES(GL_RENDERBUFFER_OES, renderbuffer);
glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT24,
        512, 512);

glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT,
        GL_RENDERBUFFER_OES, renderbuffer);
//set up the texture that you will be rendering to
glActiveTexture(GL_TEXTURE0);
GLuint textureID;
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_2D, textureID);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
//add various other texture parameters here
glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGB8_OES, 512,512);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textureID, 0);
// define your draw buffers
GLenum drawBuffers[1] = {GL_COLOR_ATTACHMENT0};
glDrawBuffers(1, drawBuffers);

hope that helps


text:
Q: Exception error while compiling game code I am a complete beginner at Java, and I tried running the following code:
package Happily.Insane.Rain;

import java.awt.Canvas;
import java.awt.Dimension;

import javax.swing.JFrame;

public class Game extends Canvas implements Runnable {
        private static final long serialVersionUID = 1L;

        public static int width = 300;
        public static height = width / 16 * 9;
        public static int scale = 3;

        private Thread thread;
        private JFrame frame;
        private boolean running = false;

        public Game() {
                Dimension size = new Dimension (width*scale, height*scale);
                setPreferredSize(size);

                frame = new JFrame();
        }

        public synchronized void start() {
                running = true;
                thread = new Thread (this, "Display");
                thread.start();
        }

        public synchronized void stop() {
                running = false;
                try {
                        thread.join();
                } catch (InterruptedException e) {
                        e.printStackTrace();
                }
        }

        public void run() {
                while (running) {
                        System.out.println("Running...");
                }
        }

        public static void main(String[] args) {

                Game game = new Game();
                game.frame.setResizable(false);
                game.frame.setTitle("Rain");
                game.frame.add(game);
                game.frame.pack();
                game.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                game.frame.setLocationRelativeTo(null);
                game.frame.setVisible(true);

                game.start();
        }

}

Had the error :
Exception in thread "main" java.lang.Error: Unresolved compilation problem:

        at Happily.Insane.Rain.Game.main(Game.java:47)

How do I fix this?

A: You did not specify the type of the static variable height:
public static height = width / 16 * 9;
// ----------^

It should be an integer:
public static int height = width / 16 * 9;

In future posts, please highlight the affected line. Additionally, we are not a give-us-problems-we-will-solve-them-all system. Invest some own effort, do some researches and then come to us and ask a question.


text:
Q: R CMD BATCH - output in terminal Just learning R and I thought it would be great to use it in batch mode in the unix terminal instead of writing in the R terminal.
So I decided to write test.r
    x <- 2
    print(x)

then in terminal I did
    R CMD BATCH test.r

it runs, But outputs a test.r.Rout file. I can get it to output to say a text file by running R CMD BATCH test.r out.txt.
Question is, is it possible to print the output to the terminal?

A: Sebastian-C posted:
    Rscript test.r

This worked in the terminal and produced the desired output
Thanks Sebastian-C

A: A somewhat late reaction, but the other day I was looking for the answer to exactly the question Blakedallen posted. Here's my solution:
mkfifo fifo   # create a named pipe
cat fifo &    # show everything to the terminal
              # (or do 'cat fifo' in another terminal)
R CMD BATCH input # 'input' contains your R commands

Works like a charm :-)
The 'fifo' named pipe can be used again for any future R CMD BATCH commands
you may want to execute. After the 'R CMD BATCH' command the 'cat' command also ends.


text:
Q: System bootloader not found I recently installed UbuntuDDE 20.04 LTS to be able to dual boot with Windows 10. After following the instructions online, I was able to get it up and running. However, after shutting down my PC and trying to boot into Windows 10, I get the message "System bootloader not found. Initializing Defaults." and then it would send me back to the startup menu.
I tried to boot back into UbuntuDDE, but it also failed and sent me back to the startup menu. I also don't seem to have a GRUB menu either. It would be my UEFI prompting for my boot device options.
EDIT: This is what I got after typing the commands after booting Ubuntu setup through my USB:

Is there any sort of way I can get this fixed?

EDIT3: sudofdisk -l


text:
Q: How to login with another user when using Google for login? I am using Google login to authenticate user before they login to my website.
Here is what I am doing.

*

*User comes to my website

*Click on login button

*Login with Google account

*if user pass google authentication, session is set

*when user click on logout, session is destroyed

Basic stuff!
Problem I am facing, happens when two users using same device tries to use the website.

*

*UserA logs in to the website using his Google account.

*UserA do his stuff and log out.

*UserB then comes and try to login to website. Because userA is already logged into Google, Google authentication process does not ask userB for his credentials and carry on logging in with UserA account.

My question is how can I make user log out from Google when user log out from my website.

A: setPrompt to 'select_account'. Google will ask to select account each time authentication request is made .
I do not think your users are happy with being logged out after logging out your page... They can change their account within the Google page.
This is the url for logging out:
accounts.google.com/logout

You can pass a redirect parameter there:
accounts.google.com/logout?continue=http://www.google.com/

But this parameter just work with links to Google services. There is no way to link your own page (not even with Google search redirect links). I think there is a very good reason for this. You should not log out your users from another foreign service for any reason.


text:
Q: Youtube iframe video restarts after modal box is closed I am using colorbox to pop up a video when a webpage loads. I am using the inline html option with the colorbox modal and I have an iframe youtube video in the modal box. When I close out of the video the audio stops but then it loads again and starts playing. When I close the modal box I would like for the audio to not start playing again.
Here is my script that opens the modal when the page is loaded:

Here is the actual inline content:

    <button></button>

A: If you want to display iframe content (embedded youtube), remove the html code and try this:
jQuery(document).ready(function() {
     jQuery.colorbox({innerWidth:602, innerHeight:460, iframe:true, href:"http://www.youtube.com/embed/6A8W77m-ZTw?&autoplay=1&controls=0"})
  });

If you want to display iframe content in inline format (for some reason):
The inline element would be appended to original parent element after user close the modal box.
So iframe will be loaded again and the video will play even though it's invisible. (because you set the youtube embedded url para autoplay=1). To solve this problem I register a handler for cleanUp event which will be fired at the start of the close process. I change the iframe src url param "autoplay" to 0 before modal window start to close. The audio will not play after modal window closed.
Try this:
jQuery(document).ready(function() {
     jQuery.colorbox({
        width:"602px",
        height:"460px",
        inline:true,
        href:"#video_popup",
        onCleanup: function(){
            $("iframe").attr("src","http://www.youtube.com/embed/6A8W77m-ZTw?&autoplay=0&controls=0");
        }

});


text:
Q: Auto-Stop a Console Service after the work is finished I have a console app that is built using IServices, like this:
class Program
{
    static void Main(string[] args)
    // ...
    var serviceToUse = args[0];

    var host = Host.CreateDefaultBuilder()
        .ConfigureServices((context, services) => {
            switch (serviceToUse) {
                case "first": { services.AddTransient<IService, AlphaService>(); break; }
                case "second": { services.AddTransient<IService, BetaService>(); break; }
            }
        })
        .UseSerilog()
        .Build();

    IService svc;

    if (serviceToUse == "alpha") {
        svc = ActivatorUtilities.CreateInstance<AlphaService>(host.Services);
    }
    else {
        svc = ActivatorUtilities.CreateInstance<BetaService>(host.Services);
    }

    List<Entity> entities = Common.GetEntities();

    svc.Run(modeToUse, entities);
}

my service is like this:
public class AlphaService : IHostedService {
    public AlphaService(ILogger<AlphaService> log, IConfiguration config) {
        _log = log;
        _config = config;
    }

    public async Task StartAsync(CancellationToken cancellationToken) {
        // update entities
        AlphaRepository.ProcessEntities(_config, alphaEntities);
    }
}

with
public interface IService {
    public void Run(string arg, IEnumerable<Entity> alphaEntities);
}

The problem is that the application never ends, even if the services ended its works. Is there a way to "kill" the application after the work is finished?

A: You need to close the service when it is done, and you need to use a service controller to check for the service status and close the app when the service stat is closed.
ServiceController Class
This answer may help
Start and stop a service using c# [duplicate]
Note that in an application that have several threads or running services you must call
Environment.Exit(0);

to end the application to end the application or it will stuck in the background waiting for events from the services or threads.


text:
Q: Azure Vnet Peering Can someone let me know when Microsoft Azure introduced Vnet Peering? I'm working with a company that has introduced a number of Vnets (8 Vnets) for security. I'm trying to suggest that creating that number of Vnets is unnecessary.
I just would like to know if there are any other benefits to Vnet peering and when it was first introduced by Azure?
Cheers
Carlton

A:
I just would like to know if there are any other benefits to Vnet
peering and when it was first introduced by Azure?

Virtual network peering enables you to connect two virtual networks in the same region through the Azure backbone network. Once peered, the two virtual networks appear as one, for connectivity purposes. The two virtual networks are still managed as separate resources, but virtual machines in the peered virtual networks can communicate with each other directly, by using private IP addresses. More information about this please refer to this link.

I'm trying to suggest that creating that number of Vnets is
unnecessary.

It depends on your company's need. If you want to connect two Vnets, you must create a peering tunnel.
VNet peering is between two virtual networks, and there is no derived transitive relationship.
In others words, if you want 3 VNets to be both interconnected, you need create 3  peering tunnels. Please refer to the similar question.

A: We announced peering in September 2016. See our service update for reference: https://azure.microsoft.com/en-us/updates/vnet-peering-ga/
VNet peering has many benefits: low latency, high bandwidth, direct VM to VM connectivity among others. You can see a comprehensive list here: https://learn.microsoft.com/en-us/azure/virtual-network/virtual-network-peering-overview
You can also suggest using subnets in the same virtual network: https://learn.microsoft.com/en-us/azure/virtual-network/virtual-networks-create-vnet-arm-pportal
-- Anavi N [MSFT]


text:
Q: Two Dimensional Array - arr[i][0] Gives Wrong Result - JavaScript ASP.NET C# I have an Array of Arrays populated from C# Model:
var AllObjectsArray = [];
        @foreach(var Cobject in Model.ObjectList)
        {
            @:AllObjectsArray.push(new Array("@Cobject.Name", "@Cobject.Value", "@Cobject.Keyword"));
        }

var SelectedObjects = [];
        uniqueobj.forEach(function (element) {

            SelectedObjects.push(new Array(AllObjectsArray.filter(elem => elem[0] === element))); //makes array of selected objects with their values(name,value,keyword)
        });

I am trying to get second parameter of each and every inner Array and add it to new array containing those elements like this:
var ValuesArray = [];
        for (i = 0; i < SelectedObjects.length; i++) {
            ValuesArray.push(SelectedObjects[i][0]) //problem here i think
        };

Unfortunately, on:
alert(ValuesArray + " : " + SelectedObjects);

I get nothing for ValuesArray. The other data for SelectedObjects loads properly with all three parameters correctly returned for each and every inner Array,so it is not empty. I must be iterating wrongly.
EDIT:
SOme more info as I am not getting understood what I need.
Lets say SelectedObjects[] contains two records like this:
{ name1, number1, keyword1}
{ name2, number2, keyword2}

Now, what I need is to populate ValuesArray with nane1 and name2.
That is why I was guessing I should iterate over SelectedObjects and get SelectedObject[i][0] where in my guessing i stands for inner array index and 1 stands for number part of that inner array. Please correct me and put me in the right direction as I am guesing from C# way of coding how to wrap my head around js.
However SelectedObject[i][0] gives me all SelectedObject with all three properties(name, value and keyword) and I should get only name's part of the inner Array.
What is happening here?
Hope I explained myself better this time.
EDIT:
I think I know why it happens, since SelectedObjects[i][0] returns whole inner Array and SelectedObjects[i][1] gives null, it must mean that SelectedObjects is not Array of Arrays but Array of strings concatenated with commas.
Is there a way to workaround this? SHould I create array of arrays ddifferently or maybe split inner object on commas and iteratee through returned strings?

A: First things first, SelectedObjects[i][1] should rather be SelectedObjects[i][0].
But as far as I understand you want something like
var ValuesArray = [];
for (let i = 0; i < SelectedObjects.length; i++) {
    for(let j = 0; j <SelectedObjects[i].length; j++) {
         ValuesArray.push(SelectedObjects[i][j]);
    }
};

A: In this snippet
var ValuesArray = [];
for (i = 0; i < SelectedObjects.length; i++) {
   ValuesArray.push(SelectedObjects[i][1]) //problem here i think
};

You're pointing directly at the second item in SelectedObjects[i]
Maybe you want the first index, 0


text:
Q: Converting iPhone/iPad apps onto Android I have started to build my own apps on iPhone and iPad using the iPhone SDK. The next question that is always asked by the client is, "Can we have it on Android?"
So my question to you, 'the internet', is: what are my options?
I don't have the time to learn another language (learning iOS has been enough!), so are there companies who specialize in this, or are there any online services that do a conversion?
Any help on this welcome, just need to know which way to turn...

A: Converting a native application from one mobile platform to the other is not a straight-forward process unless the initial application was built with a framework with cross-platform capabilities from the start.
Your options at this point are learn the other platform and develop it yourself, or contract with another development company which specializes in the platform you need to target.

A: No, there is no way to convert an existing iOS app to an Android app.
However, there are cross-platform frameworks that allow you to code once and deploy your app in more than one platform. The most popular are based on HTML/CSS/JavaScript and one of them is PhoneGap.
You can also develop for iOS and Android with Adobe technologies such as Adobe AIR (this was forbidden by Apple until recently).
And there are online services (such as Mobile Roadie) that allow you to generate cross-platform apps using a content management system.
That said, I strongly recommend to:

*

*Learn Android and Java development if you want to specialize in mobile development.

*Take advantage of the strengths of each platform when working on an iOS/Android project, instead of creating something that uses only what's common to both.

A: Due to the massive differences between the 2 platforms, you are looking at a complete rewrite of your application.  You either do it yourself or pay someone else to do it.  I don't see any shortcuts you can take.

A: Even if there was a way to easily port an Objective-C application to Java, I wouldn't highly encourage it. iPhone users and Android users are two different families of users. The typical iPhone interface just wouldn't sit well with Android users who aren't familiar with how the iPhone works. Yes, I understand that the UIs of both iPhone and Android seem pretty trivial to learn to most people, but when you break a novice's comfort zone, it puts your applications (or websites) on a higher learning curve.
You should take the time to learn Android's language and UI and develop your application in a fashion that is consistent with how applications on Android work. As said in other answers, if your taught yourself Objective-C, you should find that Java will come pretty easily to you. In addition, in never hurts to know more than one programming language.

A: You may be interested in reading my book, HTML5 for iOS and Android, which enables you to take web apps created in HTML, JavaScript & CSS, and turn them into standalone apps that you can upload to the app stores (for free or to sell). See http://html5formobile.com - the wrappers to do this for the iOS and Android SDKs are freely available on the website, and you don't need any knowledge of either programming language if you follow the instructions in the book.

A: You can try the following https://bitbucket.org/zabirauf/icona.
Its open source iOS to Android Application Conversion Tool.

A: You can't just convert iOS apps into Android. iOS is Objective-C and Android is Java.
I highly doubt there are 'converters' on the internet, even if there are that's not the way you should program an app because every SDK has his own special capabilities and you should use them for maximum user-experience.
I'm sure there are some companies who specialize in porting apps from iOS to Android. Look it up on Google I'd say..

A: If you want an easy place to look for android development you can try appMaker which I hear is a GUI based Android development tool or I believe Google has released its own GUI based android application development tool. If you are not a java programmer than you might be better off with the gui. Otherwise I would say android is not too different from traditional java. As a java programmer who went from Android to iOS, I will tell you Android is a walk in the park compared to learning iOS. Two completely different beasts in my opinion.

A: Selecting a mobile development environment which will enable you write once and deploy/distribute it on many devices would be a better solution in the future. If your application is HTML-based, go with HTML5/CSS alternative (ex: PhoneGap, ). If you prefer native, then chances are you may want to learn Lua, a scripting language (ex: Gideros Studio) or C++ (ex: Mosync).
Other than that, the application you created on iOS with Objective-C is very, very hard to port to Android and other devices.


text:
Q: Detecting collision with arrays in C++ So I have a 2d map array printed out. I have 0's set as a space and 1 set as a wall. I have variables such as traps and health as well as the player. However, I am having trouble implementing a score as the two collide. I was wondering how I can detect when a player and life collide which would increment the health variable by 1. Right now it increments every time I move.
Thank you!
These are my variable functions
void putplayer()
{
    setcolor(9);
    gotoxy( player.x +mazex,    player.y  +mazey);
    cout<<playersymbol;
    setcolor(7);

}

void puttreasure()
{
    setcolor(14);
    gotoxy(treasure.x +mazex, treasure.y +mazey);
    cout<<treasuresymbol;
    setcolor(7);

}

void puttraps()
{
    setcolor(14);
    gotoxy( traps.x +mazex,    traps.y  +mazey);
    cout<<trapssymbol;
    setcolor(7);

}

void putlives()
{
    setcolor(14);
    gotoxy( lives.x +mazex,    lives.y  +mazey);
    cout<<livessymbol;
    setcolor(7);

}

void moveleft()
{
    gotoxy(31,7);
    cout<<"left key   move player left    \n\n";
     if (maze[player.y][player.x-1]==0)   player.x = player.x -1;
}

Then my Main, however some code I took out as it might not be relevant
int main()
{
    DWORD        mode;          /* Preserved console mode */
    INPUT_RECORD event;         /* Input event */
    BOOL         EXITGAME = FALSE;  /* Program termination flag */
  //  unsigned int counter = 0;   /* The number of times 'Esc' is pressed */

    /* Get the console input handle */
    HANDLE hstdin = GetStdHandle( STD_INPUT_HANDLE );

    /* Preserve the original console mode */
    GetConsoleMode( hstdin, &mode );

    /* Set to no line-buffering, no echo, no special-key-processing */
    SetConsoleMode( hstdin, 0 );

   srand ( time(NULL) ); //initialize the random seed

    // Variables
    int health = 0;

   // Declare variable positions
    player.x=1;
    player.y=1;
    treasure.x = 1;
    treasure.y = 3;
    traps.x =  1;
    traps.y = 7;
    lives.x = 1;
    lives.y = 9;

    clrscr();
    setcolor(15);

    while (!EXITGAME)
    {
        if (WaitForSingleObject( hstdin, 0 ) == WAIT_OBJECT_0)  /* if kbhit */
        {
            DWORD count;  /* ignored */

            /* Get the input event */
            ReadConsoleInput( hstdin, &event, 1, &count );

            /* Only respond to key release events */
            if ((event.EventType == KEY_EVENT)
            &&  !event.Event.KeyEvent.bKeyDown)

            clrscr();
            putmenu();
            gotoxy(6,20);
            cout<<"Lives: " << health;
            Sleep(100);

                switch (event.Event.KeyEvent.wVirtualKeyCode)
                {
                    case VK_ESCAPE:
                       EXITGAME = TRUE;
                     break;

                    case VK_LEFT:
                        // left key   move player left
                         moveleft();
                     break;

                    case VK_RIGHT:
                        // right key   move player right
                        moveright();

                     break;

                    case VK_UP:
                        // up key   move player up
                        moveup();

                     break;

                    case VK_DOWN:
                        // down key   move player down
                         movedown();

                     break;

                    case VK_A:
                        // left key   move player left
                        moveleft();

                     break;

                    case VK_D:
                        // right key   move player right

                        moveright();
                     break;

                    case VK_W:
                        // up key   move player up

                        moveup();
                     break;

                    case VK_S:
                        // down key   move player down
                        movedown();
                     break;

                }//switch

                putplayer();
                puttreasure();
                puttraps();
                putlives();

        }
                if(maze[player.x][player.y] = maze[lives.x][lives.y]){
                health++;
                }

                else if(maze[player.x][player.y] = maze[traps.x][traps.y]){
                health--;
                }
    }

    gotoxy(1,23);cout<<"  ";
    SetConsoleMode( hstdin, mode );
    return 0;
}

A: You have the code
if(maze[player.x][player.y] = maze[lives.x][lives.y])

which sets the maze[player.x][player.y] to the value at maze[lives.x][lives.y], and then evaluates it (it will evaluate to true if 1 (wall), false if 0 (space)). I think you meant to have something like
if((player.x == lives.x) && (player.y == lives.y))

which will (as far as I can tell) evaluate if the player and the lives are at the same location.


text:
Q: HTML multiple select box I am just wondering what's the name of the below form? I was Googling from morning for the list of HTML forms but I couldn't find this kind of form anywhere. Can anyone tell me the exact name of this form and is this available in HTML forms?

I just want to add this kind of form in my website. Is that available for HTML or should I use JavaScript or its only limited for Windows applications?

A: Here's a little sample to get you started: http://jsfiddle.net/eUDRV/3/
This example will move items (one or multiple) from the left to the right and back again. Whatever item(s) are selected in the right side will update the textbox on the right side.
We are using the elements:

*

*select

*input type="button"

*input type="text"
Framed by:

*

*div

*section
Styled with simple CSS. Functionality is provided with JavaScript.
I'm using the jQuery library to make things a little easier. This could also be done with pure JavaScript.

$("#btnLeft").click(function () {
    var selectedItem = $("#rightValues option:selected");
    $("#leftValues").append(selectedItem);
});

$("#btnRight").click(function () {
    var selectedItem = $("#leftValues option:selected");
    $("#rightValues").append(selectedItem);
});

$("#rightValues").change(function () {
    var selectedItem = $("#rightValues option:selected");
    $("#txtRight").val(selectedItem.text());
});
SELECT, INPUT[type="text"] {
    width: 160px;
    box-sizing: border-box;
}
SECTION {
    padding: 8px;
    background-color: #f0f0f0;
    overflow: auto;
}
SECTION > DIV {
    float: left;
    padding: 4px;
}
SECTION > DIV + DIV {
    width: 40px;
    text-align: center;
}

        <select id="leftValues" size="5" multiple></select>

        <input type="button" id="btnLeft" value="<<" />
        <input type="button" id="btnRight" value=">>" />

        <select id="rightValues" size="4" multiple>
            <option>1</option>
            <option>2</option>
            <option>3</option>
        </select>

            <input type="text" id="txtRight" />

A: It's most commonly referred to as a listbox multiselect. Here's a lightweight jQuery multiselect library at loudev.com:


text:
Q: Feasibility of MMO 3D game on HTML5/WebGL I don't know if anyone thought about this but are games like World of Warcraft, Lineage II, or Aion, feasible with a browser front-end through WebGL? What are the things I would have to consider if I want to make a full fledged game with these new technologies? Also, what would be a good place to start?

A: This may be too open-ended, but I will take a stab.
First, there is no modeling programs that will output what you expect, as far as I know, since you will need javascript outputted.
Some browsers will use the hardware to accelerate the graphics, but that isn't a guarantee, and your only getting a bit of the cpu, sharing with the other tabs, so it may not be as smooth as you like.
If you have to download a large amount of data to run your program that will be a problem for the user.
I think the modeling program is the real challenge though, as you will have to basically do everything by hand, and the fact that it won't be very smooth will be an issue, unless you design for this.
But, for some game designs WebGL should be a fantastic choice.

A: I don't believe it's possible if your game must go beyond some cubes on heigtmaps.

*

*Large amounts of coding in JS multiplied by browsers quirks. (Yes, I'm aware of JQuery, but it's not panacea)

*Large resources hanging on tiny thread of browser cache

*Ready-to-be-hacked client code exposed to a lot of browser tools like Firebug

Such game is much more realistic on Flash, especially with upcoming 11 version of player with hardware 3D.

A: In fact it is fully possible, and we will se such games.
We can expect libraries like O3D to take care of the browser quirks. We already have these problems on desktop platforms and libraries takes care of multi-platform portability there.
Browser cache can be a slight problem, but not a big one. It is possible to assign more cache to games, and we also have proxy servers like squid that can cache very large resources. If a group of players on a LAN share a proxy server they will also share large resource objects, if the game are well designed (ie the resource cannot have multiple generated names, but be have a common URL for all players.)
Also there are discussions about adding local storage possibilities for web applications.
And "ready to be hacked" is not a mayor issue. There are nothing to stop hackers from manipulating Flash or C++ applications, anti-cheating tools are already rendered useless. Blizzard is already relying on spotting "bot-like behavour" rather then try more anti-hacking measures.
However, I do not think that WoW will be the first flash-based games. In fact it will be Quake (http://playwebgl.com/games/quake-2-webgl/) as there is already a Quake-port for WebGL... There will be web games that makes use of WebGL, but do not count on Blizzard supporting it in the near future.
IE is the only browser that does not support WebGL and to be honest that does not matter. All other browsers do, and users will not mind running Chrome or Firefox. Or running both and choose the one that is faster for their game.
Who cares of marginalized browsers like IE and Opera. They are equally unimportant. Unless you count IE6 which will never support any of the stuff we are discussing, as it is discontinued and unsupported.

A: For caching local files, you should look into the File System APIs that are now in Chrome.  This gives you programmatic access to a virtual file system, letting you control what resources you store locally.
The Application Cache can help you with static resources like the HTML, CSS, and JavaScript required for the game.  However, you need to run as an "installed web app" (via the Chrome Web Store, for example) to get unlimited storage.  Browsers are building quota management systems to help make this easier.
WebGL is great, and the libraries are emerging to help make it easier.  There's no clear "winner" but lots of options.
JavaScript is pretty fast these days, thanks to improvements like CrankShaft.  For even better performance, you can use Native Client to run your C/C++ code and post messages back and forth to JavaScript.
There are two big issues that I can see.  One is helping the middleware companies port their work to JavaScript or Native Client.  The second is improving the speed with which we can move data from JavaScript into WebGL.

A: Runescape one of the most played browser games for many years is rewriting their engine in with WebGL... (They currently use Java applets)

A: "If you can find a way to minimize the cost of transporting massive amounts (possibly gigs) of resources"
Actually http already has the minimal cost of transporting gigs of static resources. With its native resource allocation scheme, the URL, it has the ultimate caching abilities. Not only does browsers know how to cache static resources by URL, but fast and efficient proxy servers exists that can handle terrabyte of data.
The main secret to this is the HTTP HEAD requeset, where the browser of proxy server efficiently can check if it has the latest version of the resource and re-syncronize it. Also it is possible trough HTTP headers to mark a resource as eternal or very long-living (immutable). re-syncronization will then be impossible, instead updates will be done by creating a new resource with a new name.
There is a myth that HTTP is somehow inefficient as a resource transport system, when in fact it have been designed to be very efficient.
WoW and other clients that use proprietary protocol are notoriously inefficient compared to HTTP-based clients. These client cannot be accelerated using proxy servers. Windows update, Apt and Yum all have in common that they update OS resources with HTTP and have been able to leverage Akamai:s vast global networks of proxy servers among other similar resources in order to efficiently transfer URL resources in the scale of many gigabytes per client.


text:
Q: Hide/unhide shapes in Excel using VBA
I have 3 shapes named oval 1, oval 2 and oval 3 and I need to hide/unhide that shapes according to a value calculated from "A1" where the resulted values are 10, 20 and 30 and when oval 1 = 10, oval 2 = 20 and oval 3 = 30. The image show an error box. How I do this?
Private sub worksheet_change(byval target as range)

     If target.row = 1 and target.column = 1 then
          Me.shapes("Oval 1").Visible = (Cells(1, 1).Value = 10)

     If target.row = 1 and target.column = 1 then
          Me.shapes("Oval 2").Visible = (Cells(1, 1).Value = 20)

     If target.row = 1 and target.column = 1 then
          Me.shapes("Oval 3").Visible = (Cells(1, 1).Value = 30)
End sub

A: Something like this:
Private sub worksheet_calculate()
     Dim v
     v = Me.Cells(1, 1).Value
     Me.shapes("Oval 1").Visible = (v = 10)
     Me.shapes("Oval 2").Visible = (v = 20)
     Me.shapes("Oval 3").Visible = (v = 30)
End sub


text:
Q: Open Password Protected Workbook with VBA I have wb1 and wb2. wb1 is used for data entry and wb2 is used to record that data. wb2 is password protected (let's say with "password").
The VBA below is in wb1 and is run on a button click. As it is now, a box pops up requesting the password for wb2 before the VBA is done running. Is there a way to use VBA to enter "password" in that box?
I'm fairly new to VBA, so I'm open to other suggestions as well. Thanks!
Sub OpenClose()

Application.ScreenUpdating = False

Dim wb1 As Workbook
Dim wb2 As Workbook

Set wb1 = ThisWorkbook
Set wb2 = Workbooks.Open("C:\Users...")  'I have taken out the rest of the file path

wb1.Activate
    Sheets("Entry").Activate
        Range("A1:A5").Select
            Selection.Copy

wb2.Activate
    Sheets("Log").Activate
        Range("A1").PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, _
            SkipBlanks:=False, Transpose:=True

wb2.Save
wb2.Close

Set wb1 = Nothing
Set wb2 = Nothing

MsgBox "Logged and saved."

Application.ScreenUpdating = True

End Sub

A: When opening wb2 pass your "password" argument as the Password parameter:
Set wb2 = Workbooks.Open(Filename:="C:\Users...", Password:="password")

See Workbooks.Open Method (Excel) for more details.

A: This works for a file that requires a password to open it. When opening wb2 pass your "password" argument as the Password parameter:
Set wb2 = Workbooks.Open(Filename:="C:\Users...", Password:="password")
If the file is set to open in Read Only but requires a password to Modify it use this:
Set wb2 = Workbooks.Open(Filename:="C:\Users...", writeresPassword:="password")

A: Checkout this code might be resolved your issue for which you looking for
ThisWorkbook.Password = "1"
ThisWorkbook.Save
ThisWorkbook.Close


text:
Q: Creating a function to be called again and again I want to create a simple text game of choices of sorts where you always have two choices and depending on your choice, something is displayed and the current content disappears. My problem is each of the choices are different so i can't figure out a way to not repeat myself again and again in the javascript code.
HTML :
<!Doctype html>

    <link rel="stylesheet" href="style.css" type="text/css"/>

    <title>Game</title>

Some stuff.

getup

sleep

Something happened

do this

do that

something else happened

do something

do something else

CSS :
body {
    margin: 0 auto;
    align-content: center;
    font-family: 'Open Sans', sans-serif;
    font-weight: 400;
}
#console {
    width: 100%;
}

.storyCard {
    min-width: 100px;
    max-width: 600px;
    background-color: rgba(0, 0, 0, 0.51);
    box-shadow: 1px 1px 7px;
    padding: 50px;
    color: white;
    margin: 0 auto;
    border-radius: 4px;
    display: none;
}
#start {
    display: block;
}
.storyCard .a {
    background-color: dodgerblue;
    border-bottom-color: dodgerblue;
    border-top-color: white;
    border-left-color: white;
    border-right-color: dodgerblue;
    padding: 10px;
    text-align: center;
    color: white;
    width: 30%;
    display: inline;
    margin: 0 auto;
    box-shadow: 1px 1px 7px black;
    float: right;
    cursor: pointer;
}
.storyCard .a:hover {
    background-color: white;
    color: black;
}
}

Javascript :
document.querySelector('#console').addEventListener('click', function (e) {
    var answer = e.target.textContent;
    switch (answer) {
        case 'getup':
            e.target.parentNode.style.display = 'none';
            document.querySelector('#getup').style.display = 'block';
            break;
        case 'sleep':
            e.target.parentNode.style.display = 'none';
            document.querySelector('#sleep').style.display = 'block';
            break;
        case 'do this':
            e.target.parentNode.style.display = 'none';
            /*display another content like above*/
        case 'do that':
            /*hide the current content again and display another content and add more cases*/

}, false);

A: You can try something like performAction(e, '#getup'); - a generalized method with parameters, in this link.
Please refer below for the code:
HTML:

Some stuff.

getup

sleep

Something happened

do this

do that

something else happened

do something

do something else

CSS:
body {
  margin: 0 auto;
  align-content: center;
  font-family: 'Open Sans', sans-serif;
  font-weight: 400;
}

#console {
  width: 100%;
}

.storyCard {
  min-width: 100px;
  max-width: 600px;
  background-color: rgba(0, 0, 0, 0.51);
  box-shadow: 1px 1px 7px;
  padding: 50px;
  color: white;
  margin: 0 auto;
  border-radius: 4px;
  display: none;
}

#start {
  display: block;
}

.storyCard .a {
  background-color: dodgerblue;
  border-bottom-color: dodgerblue;
  border-top-color: white;
  border-left-color: white;
  border-right-color: dodgerblue;
  padding: 10px;
  text-align: center;
  color: white;
  width: 30%;
  display: inline;
  margin: 0 auto;
  box-shadow: 1px 1px 7px black;
  float: right;
  cursor: pointer;
}

.storyCard .a:hover {
  background-color: white;
  color: black;
}

JS:
document.querySelector('#console').addEventListener('click', function(e) {
  var answer = e.target.textContent;
  switch (answer) {
    case 'getup':
      performAction(e, '#getup');
      break;
    case 'sleep':
      performAction(e, '#sleep');
      break;
    case 'do this':
      performAction(e, '#getup'); /**Use any 'id' or target of your choice.*/
      /*display another content like above*/
      break;
    case 'do that':
      performAction(e, '#getup'); /*Use any 'id' or target of your choice.*/
      /*hide the current content again and display another content and add more cases*/
      break;
  }
}, false);

function performAction(event, target) {
  event.target.parentNode.style.display = 'none';
  document.querySelector(target).style.display = 'block';
}

A: I assume that the question must defined in html like your sample. There are many others way to do this better.
You can use class name to specify next question.

document.addEventListener('click', function (e) {
  var target = e.target;
  if (target.className.match('answer')) {
    var nextQuestionId = target.className.replace('answer ', '');
    hideAllStoryCards();
    showStoryCard(nextQuestionId);
  }
});

function hideAllStoryCards () {
  var i, elm, elms = document.getElementsByClassName('storyCard');
  for (i = 0; i < elms.length; i++) {
    elm = elms[i];
    elm.style.display = 'none';
  }
}

function showStoryCard (id) {
  var storyCard = document.getElementById(id);
  storyCard.style.display = 'block';
}

hideAllStoryCards();
showStoryCard('first-question');

Are you hungry?

yes

no

Some stuff.

a pie

a buger

Some stuff.

bye

bye again

A: You need to separate your data from your UI.
Your data could be something simple like this:
var stories;

function StoryCard(q, option1, option2) {
    this.q = q
    this.option1 = option1;
    this.option2 = option2;
}

function displayStory(storyCard) {
    document.getElementById('q').innerHTML = storyCard.q;
    document.getElementById('option1').innerHTML = storyCard.option1;
    document.getElementById('option2').innerHTML = storyCard.option2;
}

Your "console" UI could change to something more like this:

Your click function may be more like this:
document.querySelector('#console').addEventListener('click', function (e) {
    var answer = e.target.id;
    switch (answer) {
        default: // for when they click within the div, but not on an option
            break;
        case 'option1':
        case 'option2':
            var story = stories[e.target.innerHTML];
            if (null != story) {
                displayStory(story);
            }
            break;
    }
}, false);

You would set up your stories perhaps in an onload:
function init() {
    stories = { "start": new StoryCard("Some stuff", "getup", "sleep")
              , "getup": new StoryCard("Something happened", "do this", "do that")
              , "sleep": new StoryCard("something else happened", "do something", "do something else")
              };

    displayStory(stories["start"]);
}


text:
Q: Terminal Services Buttons Stuck (mstsc) After connecting to a remote server via mstsc, the window opens fine and everything in full-screen mode, but the close/minimize/restore buttons get stuck. I.e they do not respond to any action (they don't change when you mouseover them or do anything when you click on them). However, I am running an extended desktop, so when I click on the desktop on the other monitor the buttons start working. It's a perplexing problem, any ideas?

A: Unpin the menu bar at the top of the screen.


text:
Q: Building a single drop-down menu from 2 arrays I'm trying to build a drop-down from 2 arrays, and I've got the options working but the nested foreach loop is not working, so each option in the drop down has the same title (first item of array $linkText). What is the correct way of doing this? Thanks.
$content.='<select onChange="window.location.href=this.value">';
      $content.='  <option selected="selected">Choose one</option>';

 foreach($dateLinks as $item1){
               $content.='<option value="'.$item1.'">';

               foreach($linkText as $item2){
                 $content.='   '.$item2.'  </option>';
}
}

$content.='</select> ';

The arrays look like this:
$dateLinks = array(
    '/latest/potm/previousmonths/Oct2003',
    '/latest/potm/previousmonths/Nov2003',
    '/latest/potm/previousmonths/Dec2003',
    '/latest/potm/previousmonths/Jan2004'
);

$linkText = array('Oct2003', 'Nov2003', 'Dec2003', 'Jan2004');

A: Ok nevermind sorry. I managed to do it with a little more research, by combining the arrays:
 $c = array_combine($linkText, $dateLinks);

      foreach($c as $key => $value){
               $content.='<option value="'.$value.'"> '.$key.' </option> ';
               }

     $content.='</select> ';


text:
Q: how to match more range sliders style to store in a single element by id Hi I'm working on a project where I have four range sliders
every slider change a single css property of the html element (in particular a single webkit filter to everything)
I have:
hue
blur
grayscale
invert
now:
when I use a single slider it's all ok
but when i leave the slider and I use another one it set only one parameter to the style, writing over the previous
here an example of the code
HTML: this is one of the sliders

      <input type="range" data-default="0" value="0" min="0" max="360" step="1" id="hue-rotate" oninput="hueFunction(this.value)">

JS: these are the functions
//filters
//hue
function hueFunction(hueVal) {
  var setAs = hueVal + "deg";
  document.getElementById("html").setAttribute("style", "-webkit-filter:hue-rotate(" + setAs + ")");
}
//blur
function blurFunction(blurVal) {
  var setAs = blurVal + "px";
  document.getElementById("html").setAttribute("style", "-webkit-filter:blur(" + setAs + ")");
}
//grayscale
function grayscaleFunction(grayscaleVal) {
  var setAs = grayscaleVal + "%";
  document.getElementById("html").setAttribute("style", "-webkit-filter:grayscale(" + setAs + ")");
}
//invert
function invertFunction(invertVal) {
  var setAs = invertVal + "%";
  document.getElementById("html").setAttribute("style", "-webkit-filter:invert(" + setAs + ")");
}

I would like to use every sliders together

A: Check this.

//filters
//hue
function hueFunction(hueVal) {
    apply_filter('hue-rotate', hueVal + 'deg');
}
//blur
function blurFunction(blurVal) {
    apply_filter('blur', blurVal + 'px');
}
//grayscale
function grayscaleFunction(grayscaleVal) {
    apply_filter('grayscale', grayscaleVal + '%');
}
//invert
function invertFunction(invertVal) {
    apply_filter('invert', invertVal + '%');
}
var apply_filter = function (fil, val) {
    var filter = document.getElementById('html').style.filter.trim().split(' ').filter(function (a) { return a.trim(); });
    var f = false;
    filter.forEach(function (v, i) {
        if (v.indexOf(fil) === 0) {
            filter[i] = fil + '(' + val + ')';
            f = true;
        }
    });
    if (f === false) filter.push(fil + '(' + val + ')');
    document.getElementById('html').style.filter = filter.join(' ');
};
#filters > input {
  display: block;
}
#html {
  height: 80px;
  width: 80px;
  border: 1px solid #000;
  background-color: #F00;
}

      Hue
      <input type="range" data-default="0" value="0" min="0" max="360" step="1" id="hue-rotate" oninput="hueFunction(this.value)">
      Blur
      <input type="range" data-default="0" value="0" min="0" max="360" step="1" id="blur-rotate" oninput="blurFunction(this.value)">
      Grayscale
      <input type="range" data-default="0" value="0" min="0" max="360" step="1" id="gray-rotate" oninput="grayscaleFunction(this.value)">
      Invert
      <input type="range" data-default="0" value="0" min="0" max="360" step="1" id="invert-rotate" oninput="invertFunction(this.value)">


text:
Q: Using Interop with C#, Excel Save changing original. How to negate this? The problem: Loading an excel spreadsheet template.  Using the Save command with a different filename and then quitting the interop object.  This ends up saving the original template file. Not the result that is liked.
public void saveAndExit(string filename)
{
    excelApplication.Save(filename);
    excelApplication.Quit();
}

Original file opened is c:\testing\template.xls
The file name that is passed in is c:\testing\7777 (date).xls
Does anyone have an answer?
(The answer I chose was the most correct and thorough though the wbk.Close() requires parameters passed to it.  Thanks.)

A: Excel interop is pretty painful.  I dug up an old project I had, did a little fiddling, and I think this is what you're looking for.  The other commenters are right, but, at least in my experience, there's a lot more to calling SaveAs() than you'd expect if you've used the same objects (without the interop wrapper) in VBA.
Microsoft.Office.Interop.Excel.Workbook wbk = excelApplication.Workbooks[0];  //or some other way of obtaining this workbook reference, as Jason Z mentioned
wbk.SaveAs(filename, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing);
wbk.Close();
excelApplication.Quit();

Gotta love all those Type.Missings.  But I think they're necessary.

A: Rather than using an ExcelApplication, you can use the Workbook object and call the SaveAs() method.  You can pass the updated file name in there.

A: Have you tried the SaveAs from the Worksheet?

A: *

*Ditto on the SaveAs

*Whenever I have to do Interop I create a separate VB.NET class library and write the logic in VB. It is just not worth the hassle doing it in C#


text:
Q: How to generate a list of antonyms for adjectives in WordNet using Python I want to do the following in Python (I have the NLTK library, but I'm not great with Python, so I've written the following in a weird pseudocode):
from nltk.corpus import wordnet as wn  #Import the WordNet library
for each adjective as adj in wn        #Get all adjectives from the wordnet dictionary
    print adj & antonym                #List all antonyms for each adjective
once list is complete then export to txt file

This is so I can generate a complete dictionary of antonyms for adjectives. I think it should be doable, but I don't know how to create the Python script. I'd like to do it in Python as that's the NLTK's native language.

A: from nltk.corpus import wordnet as wn

for i in wn.all_synsets():
    if i.pos() in ['a', 's']: # If synset is adj or satelite-adj.
        for j in i.lemmas(): # Iterating through lemmas for each synset.
            if j.antonyms(): # If adj has antonym.
                # Prints the adj-antonym pair.
                print j.name(), j.antonyms()[0].name()

Note that there will be reverse duplicates.
[out]:
able unable
unable able
abaxial adaxial
adaxial abaxial
acroscopic basiscopic
basiscopic acroscopic
abducent adducent
adducent abducent
nascent dying
dying nascent
abridged unabridged
unabridged abridged
absolute relative
relative absolute
absorbent nonabsorbent
nonabsorbent absorbent
adsorbent nonadsorbent
nonadsorbent adsorbent
absorbable adsorbable
adsorbable absorbable
abstemious gluttonous
gluttonous abstemious
abstract concrete
...

A: The following function uses WordNet to return a set of adjective-only antonyms for a given word:
from nltk.corpus import wordnet as wn

def antonyms_for(word):
    antonyms = set()
    for ss in wn.synsets(word):
        for lemma in ss.lemmas():
            any_pos_antonyms = [ antonym.name() for antonym in lemma.antonyms() ]
            for antonym in any_pos_antonyms:
                antonym_synsets = wn.synsets(antonym)
                if wn.ADJ not in [ ss.pos() for ss in antonym_synsets ]:
                    continue
                antonyms.add(antonym)
    return antonyms

Usage:
print(antonyms_for("good"))


text:
Q: Chrome is accessing links in webpages that were not clicked I spent the day debugging my website, because I seem to be getting randomly logged out, but just on Chrome on Android.
After reviewing the server logs, I see requests from my Android tablets IP hitting my server for links that I never clicked on. After some experimentation I see every couple of links I click, Chrome will fetch another link at random in the page that was not clicked.
The issue is that there is an a link in the page with an href="logout" which will sign in, and Chrome calls this all on its own, disconnecting the session. I suppose if I changed the link to call a POST operation Google would not fetch it, but I can't see why Google would be fetching links that were not clicked.
This is very odd, and does not occur on Firefox, or Chrome on Windows.
Not sure if this is some sort of virus on the tablet, or some thing Google is doing to check the content of pages that it would not have access to without the session.
I have seen Google do this before, but only when there were Google ads in the page, then Google would fetch the links twice so that it could get the page content to choose the ad. This seems a huge privacy issue, as Chrome is fetching private data from the session.

A: So the issue is that Chrome is using a new feature "prefetching".
This is a "feature" that will have Chrome randomly fetch any linked URL from the page.
This seems like a very error prone "feature" for Chrome to enable by default. Seems like it could give the user cached or stale data, or change the server's state causing obscure difficult to debug issues. This will also use double the amount of the user's data (and server's CPU), which you would think would not be desirable to most users that pay for their data.
I confirmed this by disabling the feature in Chrome.
My solution was to switch the logout call to use a POST through a  element.
See, https://www.technipages.com/google-chrome-prefetch


text:
Q: Search function for a Heap I have made a generic Binary Heap (MaxHeap) in which I have to search for a particular node based upon the value present in the node. I have made it such that the search function using Pre-OrderTraversal and it should give a run time of Order n where n is the number of nodes in the Heap. My code doesn't seem to work. It never goes into the second 'else if' present in the preOrderT function. Could you suggest what changes can be made in it?
My node class has been defined to contain an integer key (according to which the heap is arranged), a generic object value, and the references to the parent, leftChild and rightChild.
public Node<E> search(E p){
    Node<E> N;

    N= preOrderT(root, p);
    return N;
}

public Node<E> preOrderT(Node<E> N, E p){
    Node<E> M=null;

    if (N.value==p) M=N;
    else if (M==null && N.leftChild!=null){ M=preOrderT(N.leftChild, p);}
    else if (M==null && N.rightChild!=null){ M=preOrderT(N.rightChild, p);}
    return M;
}

A: The issue is if there is a leftChild, then you never give it a chance to check the rightChild. Instead, once you've completed checking the leftChild, check the rightChild if the value hasn't been found yet.

A: You need to update your function as:
public Node<E> preOrderT(Node<E> N, E p){
Node<E> M=null;

if (N.value==p) M=N;
else
{
  if (N.leftChild!=null){ M=preOrderT(N.leftChild, p);}
  if (N.rightChild!=null){ M=preOrderT(N.rightChild, p);}
}
return M;

}

A: change as below.
if (N.value==p) M=N;
    else {
      if (M==null && N.leftChild!=null){ M=preOrderT(N.leftChild, p);}
      if (M==null && N.rightChild!=null){ M=preOrderT(N.rightChild, p);}
}


text:
Q: what is 'this' refers to in jquery's $.ajax success? Sorry if I have made some mistakes of js terms in my question.
I'm trying to call a method in $.ajax success event which is within the same namespace, here is the demo:
"use strict";

var example = window.example || {};

example.Demo = {
    doSomething: function(data) {
        console.log(data);
    },
    main: function() {
        $(document).ready(function() {
            $.ajax({
                url: 'url/to/some/place',
                type: 'GET',
                async: true,
                dataType: "json",
                success: function (data) {
                    this.doSomething(data);
                }
            });
        });
    },
};

example.Demo.main()

but it will fail with the following error:
Object # has no method 'doSomething',
seems this can works:
...
main: function() {
    var that = this;
    ...
    ...
        success: function (data) {
            that.doSomething(data);
...

but I want to know whether there is any best practice for such case, or this is exactly the proper solution.

A: it refers the ajax settings by default, you can use the context to pass a custom object
context

This object will be made the context of all Ajax-related callbacks. By
  default, the context is an object that represents the ajax settings
  used in the call ($.ajaxSettings merged with the settings passed to
  $.ajax).

example.Demo = {
    doSomething: function (data) {
        console.log(data);
    },
    main: function () {
        //don't use dom ready handler here
        $.ajax({
            url: 'url/to/some/place',
            type: 'GET',
            //see the use of context
            context: this,
            async: true,
            dataType: "json",
            success: function (data) {
                this.doSomething(data);
            }
        });
    },
};

A: In JavaScript this always refers to the "owner" of the function we're executing, or rather, to the object that a function is a method of. When we define our faithful function doSomething() in a page, its owner is the page, or rather, the window object (or global object) of JavaScript. An onclick property, though, is owned by the HTML element it belongs to.
This "ownership" is the result of JavaScript's object oriented approach. See the Objects as associative arrays page for some more information.

A: Remove $(document).ready(function(){... inside the main , that will solve the problem


text:
Q: How define variables in a macro, so that they available for the caller of the macro I want to have a macro dbtest that can be used like this:
(dbtest
  (prn test-object1)
  (prn test-object2))

test-object1 and test-object2 should be variables which are defined by dbtest (because I need them everytime I use the dbtest macro). "prn" is just an example; I want to use arbitrary code inside the macro.
I tried this:
(defmacro dbtest [& body]
  `(sql/with-connection db
     (delete-all-tables)
     (let [~'test-object1 (insert-object "foo")]
       ~@body)))

where insert-object is a function that insert something into the DB and returns a the corresponding data structure.
But it doesn't work: I get a "no such var" error

A: It works for me:
user=> (defmacro let-test [& body]
         `(let [~'test-object1 123] ~@body))
#'user/let-test
user=> (let-test (+ test-object1 321))
444

Are you sure the problem isn't with the SQL-related calls?


text:
Q: Compare strings in two different workbooks I have to compare the username from 2 workbooks in Excel using VBA. How does one do this?
For example :

*

*In workbook 1 : column A contains 10 names

*In workbook 2 : column A contains 10 names

I need to have the cell of column B in each workbook be colored Green or Red based on the match.

A: I "think" that you mean something like this, but I know I always need to be prudent.
The code below should work, but probably you will want to set the ranges more dynamically.
Option Explicit
Sub Compare_Names()

Dim oBook_1             As Excel.Workbook
Dim oBook_2             As Excel.Workbook
Dim oRange_1            As Range
Dim iRange_1_Rows       As Integer
Dim oRange_2            As Range
Dim iRange_2_Rows       As Integer

Dim vArray              As Variant
Dim vArray_Found        As Variant
Dim iCnt                As Integer
Dim iCnt_B              As Integer

Application.ScreenUpdating = False
Application.DisplayAlerts = False

Set oBook_1 = Workbooks.Open("U:/Names_1.xls")
    Set oRange_1 = oBook_1.Sheets(1).Range("A1:A5") 'Can be dynamically set when needed
    iRange_1_Rows = oRange_1.Rows.Count
    ReDim vArray(1 To iRange_1_Rows, 1 To 1)
    vArray = oRange_1
    Set oRange_1 = Nothing
oBook_1.Close
Set oBook_1 = Nothing

Set oBook_2 = Workbooks.Open("U:/Names_2.xls")
    Set oRange_2 = oBook_2.Sheets(1).Range("A1:A5")
    iRange_2_Rows = oRange_2.Rows.Count
    For iCnt = 1 To iRange_1_Rows
        For iCnt_B = 1 To iRange_2_Rows

            ReDim vArray_Found(1 To iRange_2_Rows, 1 To 1)

            If Trim(vArray(iCnt, 1)) = Trim(oRange_2(iCnt_B)) Then
                oRange_2(iCnt_B).Interior.Color = vbGreen
                vArray(iCnt_B, 1) = True
            End If
        Next iCnt_B
    Next iCnt

    For iCnt = 1 To iRange_2_Rows
        If vArray(iCnt, 1) <> True Then
            oRange_2(iCnt).Interior.Color = vbRed
        End If
    Next iCnt

    Set oRange_2 = Nothing
oBook_2.Save
oBook_2.Close
Set oBook_2 = Nothing

End Sub

If you want a non-case sensitive comparison you can use:
if UCase(Trim(vArray(iCnt, 1))) = UCase(Trim(oRange_2(iCnt_B))) Then