text:
Q: Implementing both controltemplate and datatriggers for a textbox control I have tried implementing controltemplate and datatriggers both for textbox.. the Xaml code is as follows:
<TextBox x:Uid="txtagevals" x:Name="txtAge" Height="25" Width="80" Background="Wheat"  BorderThickness="1" BorderBrush="Black">
                                                        <TextBox.Template>
                                                            <ControlTemplate x:Uid ="txtagevals" TargetType="{x:Type TextBox}">
                                                                <Border Background="{TemplateBinding Background}"
                                            BorderBrush="Black" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="5">
                                                                    <ScrollViewer x:Name="PART_ContentHost"/>
                                                                </Border>
                                                                <ControlTemplate.Triggers>
                                                                    <DataTrigger Binding="{Binding Age}" Value="18">
                                                                        <Setter **TargetName=""** Property="Text" Value="Green" />
                                                                    </DataTrigger>
                                                                </ControlTemplate.Triggers>
                                                            </ControlTemplate>
                                                        </TextBox.Template>
                                                    </TextBox>

could you please help me... with..what should be my Target Name="" in the above code..Thank you..

A: You can just leave out the target name, that should work.
See here for more examples.


text:
Q: How to Webstorm search references acquired by jquery selectors? when you use ctrl+g on a reference, it finds you that within the same file
is there a more global search (all files in project) that finds direct references as well as as those places where jquery is invoked to get a reference to the object?

A: You can check the event that is occurring on any button or any html element when clicked.
All you need to do is instead of searching it right in the webstorm you can trace it accurately in the firebug.
Please make sure that firebug is installed or open the default developer's tool in your firefox or chrome browser.
To see the event that is occurring on an element :

right  on the element and inspect it.
firebug will open up at the bottom of the browser and in the right-bottom corner you will find a box in which there are different tabs.
click on the events tab
you will see events such as click,mousehover....etc.
check the function that is getting called by clicking on that function name and it will show you the line of code that is being executed when you click that particular element with the js file name and the line number.

Hope that helps you out.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Further simplifying and shortening a simple grouping algorithm This is the input list
input_list = ['string','string','1','string','2','string','string','3','string','5']

This is the output required
    [['string', 'string', '1'], ['string', '2'], ['string', 'string', '3'],
     ['string', '5']]

Basically you're grouping the list data string and (numeric data) into a list of lists, each list containing the first numeric data and previous string data encountered
A simple algorithm which can accomplish this
output_list = []
inner_list = []
for data in input_list:
    inner_list.append(data)
    if data.isdigit():
        output_list.append(inner_list)
        inner_list = []

print output_list

I was wondering if this could be made even simpler (accomplished in lesser number of lines)?

A: One liner with reduce. Do not use.
reduce(lambda n, e: n[:-1]+[n[-1]+[e]] + ([[]] if e.isdigit() else []), input_list, [[]])[:-1]

A: You can first find the index of digit elements then use zip to create the desire slice indices and slice you list :
>>> ind=[0]+[i for i,j in enumerate(input_list,1) if j.isdigit()]
>>> [input_list[i:j] for i,j in zip(ind,ind[1:])]
[['string', 'string', '1'], ['string', '2'], ['string', 'string', '3'], ['string', '5']]

A: Even though this is a single line solution, it is not simpler, it's more complex:
input_list = ['string','string','1','string','2','string','string','3','string','5']
result = [s.split() for s in ' '.join([s+'\n' if s.isdigit() else s for s in input_list]).splitlines()]
print result

Output:

[['string', 'string', '1'], ['string', '2'], ['string', 'string', '3'], ['string', '5']]

Is this blob of complex code what you want?
(Note the bug: if one of the strings should already contain a \n. You could choose another character if you know for sure that it won't be in one of the strings).

A: If you want a (slightly evil) reduce()-based version:
def reduce_string_prefix(cur, item):
    cur[-1].append(item)
    if item.isdigit():
        cur.append([])
    return cur

input_list = ['string', 'string', '1', 'string', '2', 'string', 'string', '3', 'string', '5']
output_list = reduce(reduce_string_prefix, input_list, [[]])[:-2]

I'm not so sure if this is actually easier to read, though ;-).


text:
Q: ContentEditable onChange function not working within html tag?
const checkQs = 'Hi everyone, I live in +++America+++.';

let newStr = checkQs.replace(
  /\++(.*)\++/g,
  '
$&
',
);

In here I have replaced America with contentEditable, where I can update,
But onChange function is not working


text:
Q: How to serialize? using System;
using System.Collections.Generic;
using System.IO;

class Program
{
    static void Main()
    {
        // Get all files in Documents
        List<string> dirs = FileHelper.GetFilesRecursive("S:\\bob.smith\\");
        foreach (string p in dirs)
        {
            Console.WriteLine(p);
        }
        // Write count
        Console.WriteLine("Count: {0}", dirs.Count);
        Console.Read();
    }
}

static class FileHelper
{
    public static List<string> GetFilesRecursive(string b)
    {
        // 1.
        // Store results in the file results list.
        List<string> result = new List<string>();

        // 2.
        // Store a stack of our directories.
        Stack<string> stack = new Stack<string>();

        // 3.
        // Add initial directory.
        stack.Push(b);

        // 4.
        // Continue while there are directories to process
        while (stack.Count > 0)
        {
            // A.
            // Get top directory
            string dir = stack.Pop();

            try
            {
                // B
                // Add all files at this directory to the result List.
                result.AddRange(Directory.GetFiles(dir, "*.*"));

                // C
                // Add all directories at this directory.
                foreach (string dn in Directory.GetDirectories(dir))
                {
                    stack.Push(dn);
                }
            }
            catch
            {
                // D
                // Could not open the directory
            }
        }
        return result;
        var k = "";
        result = k;
    }
}

This is my code.  I am trying to serialize the result to an XML file (i thought by passing it to a var, i could use that variable to serialize).  I'm at wits' end.  Please someone help.
weirdly for some reason i can't add comments--in response, yes i have gone over endless tutorials about serialization.  i'm a complete newbie at this stuff and frankly put, these tutorials have been unhelpful for the large part b/c i'm not able to put this function and serializaton together.  at this point, i'm looking for a solution as i'm about to seriously break something out of frustration.

A: You can use the XmlSerializer:
using System.Xml.Serialization;

static void Main()
    {
        // Get all files in Documents
        List<string> dirs = FileHelper.GetFilesRecursive(@"S:\\bob.smith\\");

        XmlSerializer x = new XmlSerializer(dirs.GetType());
        x.Serialize(Console.Out, dirs);

        Console.Read();
    }

A: If you simply want to output the contents of the dirs list, it's probably easiest using an XmlWriter:
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
using (XmlWriter writer = XmlWriter.Create(@"c:\path\filename.xml", settings))
{
    writer.WriteStartElement("dirs");
    dirs.ForEach(d => writer.WriteElementString("dir", d));
    writer.WriteEndElement(); // dirs
}

The result will look like this:
<?xml version="1.0" encoding="utf-16"?>
<dirs>
  <dir>c:\</dir>
  <dir>c:\Program Files</dir>
  ...
</dirs>

Note that this might not be what is generally meant when talking about serialization in .NET, since it amongst other things does not contain information about what type of object that contained the data, so you can not use this to deserialize the xml data into a List using the available serialization mechanisms in the framework.
Update
If you instead want to do it more "framework-style", you can use the BinaryFormatter:
// serialize the object to disk
BinaryFormatter formatter = new BinaryFormatter();
using (Stream stream = File.OpenWrite(@"c:\temp\dirlist.data"))
{
    formatter.Serialize(stream, dirs);
}

// at some other point, when you want to deserialize
BinaryFormatter formatter = new BinaryFormatter();
List<string> dirList;
using (Stream stream = File.OpenRead(@"c:\temp\dirlist.data"))
{
    dirList = (List<string>)formatter.Deserialize(stream);
}

In this case you will get a binary file on disk that makes little sense in a text editor (but it looks something like this; I have introduced some line breaks to make it more "readable"):
ÿÿÿÿ          System.Collections.Generic.List`1[[System.String, mscorlib,
Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
_items_size_version                       c:\   c:\Program Files

A: I do not wish to sound mean, but it seems from your question that you're missing some very important and fundamental concepts to do with serialisation.
This tutorial might be a good place to start with serialisation. Try this out, and if you've questions then feel free to post them here on SO.
Hope this helps,

A: On a side note, you could've got all the files across all sub folders using
Directory.GetFiles(@"S:\\bob.smith\\", "*.*", SearchOption.AllDirectories)


text:
Q: Can my weather station cause interference with my wireless network? I know my weather station is on 433 MHz and my home Wi-Fi network is on 2.4 GHz  and 5 GHz. It's ok so far and everything seems to be fine.
But I found many cases on the Internet that cheap stations like mine may cause Wi-Fi interference: can it be harmful for my wireless network?

A: Just because your device operates at 433 MHz doesn't mean that it's the only frequency in use in the device.
I take it you mean 'cheap' as in 'made overseas and not subjected to communication regulatory testing'. Unapproved transmitters may work well, or may not. If it causes interference with other communications, the local communications commission may get upset with you.
An approved transmitter should have this statement (or some equivalent legal boilerplate) somewhere in the manual:
"THIS DEVICE COMPLIES WITH PART 15 OF THE FCC RULES. OPERATION IS SUBJECT TO THE FOLLOWING TWO CONDITIONS:

*

*THIS DEVICE MAY NOT CAUSE HARMFUL INTERFERENCE, AND

*THIS DEVICE MUST ACCEPT INTERFERENCE RECEIVED, INCLUDING INTERFERENCE THAT MAY CAUSE UNDESIRED OPERATION."


text:
Q: downloading a pdf into app i am stuck with an issue,in my app i am creating to download a pdf file from a url and it has to save in my app.can any one give me suggestion how to download the file and store it in the app.
thank you all.

A: Use NSData to retrieve files from the Internet (synchronously):
NSURL *downloadUrl = [NSURL URLWithString:@"mydomain.tld/myfile.pdf"];
NSData *data = [NSData dataWithContentsOfURL:downloadUrl];
[data writeToURL:filePath atomically:YES];

To download data without blocking the main thread (asynchronously), view the answer to this post:
iPhone SDK: How do you download video files to the Document Directory and then play them?
You cannot save any files to your application bundle, but you can save them to an application-specific Documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"myfile.pdf"];

NSURL *filePath = [NSURL fileURLWithPath:path];


text:
Q: How can I sort X-Axis and Legend Entries? I have a dashboard where I am measuring a metric value for different items during the day and then displaying it on Google Data Studio.
On the X-axis, I am displaying time of day in hhmm format (internally this is a number) and on the Y-axis I have the metric value with different lines for different items.
I want to display X-Axis in chronological order and the legend entries for different items in descending order of cumulative metric value. This should be more clear from the image here:

There is a sort option available in Google Data Studio but its not very clear on demarcation between X-Axis and the legend.

*

*Data Set (Google Sheets)

*Google Data Studio Report

A: Display the time is chronological order by setting the X-axis Sort in the line chart to:

*

*Field: TIME

*Order: Ascending
To sort the ITEM values in legend by cumulative METRIC, change the Secondary Sort to:

*

*Field: Metric

*Aggregation: SUM

*Order: Descending
Additionally, to ensure that all 11 items are displayed change the Number of Series (in the Style Tab) from the default, 10, to the required number, with 20, currently being the maximum number of unique series (lines) that can be displayed simultaneously.
Editable Google Data Studio Report (Embedded Google Sheets Data Source) and a GIF to elaborate:


text:
Q: Azure DevOps install .Net Core 3.1 on CI Agents I am trying to update my agents on an Azure DevOps build pipeline and I need to update to Azure 3.1.
I've found instructions (though vague) to do so using YAML, but I am using the classic view and do not have access (that I know of) to YAML instruction sets.
Does anyone know how I can accomplish this?
I know I need to include a Task before the Restore portion, but there is not step that I see that will allow me to install the SDK on the agents.  Any assistance is greatly appreciated.

A: You can use the Use .NET Core task and specify there the version you need (3.1.x for 3.1):

The task results:


text:
Q: nginx using OR set at regex for the map I'm trying to write a map for my website and it's working great:
map $request_uri $redirect_uri {
  /en/oldname    /en/newname;
  /de/oldname    /de/newname;
  /fr/oldname    /fr/newname;
}

until I try to implement some regex, something like this:
map $request_uri $redirect_uri {
  /(?<lang>(en|de|fr))/oldname    /$lang/newname;
}

The map above is not working, and due to the lack of debugging knowledge - I'm unable to know why. Even the basic regex (without using named captures) is not working for me:
map $request_uri $redirect_uri {
  /(en|de|fr)/oldname    /en/newname;
}

nginx 1.10.3
Please help me to figure out what am I doing wrong?

A: Mike, you should use "~" symbol to indicate a regular expression.
Look at here Module ngx_http_map_module

A regular expression should either start from the "~" symbol for a case-sensitive matching, or from the "~*" symbols (1.0.4) for case-insensitive matching. A regular expression can contain named and positional captures that can later be used in other directives along with the resulting variable.

The right configuration should be:
map $request_uri $redirect_uri {
  ~/(?<lang>(en|de|fr))/oldname    /$lang/newname;
}

Good luck!

2017.07.13 edited
Here is the full configuration based on the default configuration(echo directive is provided by nginx-echo-module)
#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;
    map $request_uri $redirect_uri {
      ~/(?<lang>(en|de|fr))/oldname    /$lang/newname;
    }

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            echo $redirect_uri;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }

    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

And this is my test case:
yxr nginx # curl localhost/en/oldname
/en/newname
yxr nginx # curl localhost/de/oldname
/de/newname
yxr nginx # curl localhost/fr/oldname
/fr/newname
yxr nginx # curl localhost/cn/oldname

yxr nginx #

2017.07.14 edited
As @Mike pointed out, this requires at least nginx/1.11.0.

A: In regards to mononoke's answer. You don't need the extra set of parentheses in the pattern matching, and that could give some unexpected results for certain pcre engines as you are technically adding another group within the lang group.
~/(?<lang>en|de|fr)/oldname    /$lang/newname;

A: map $http_user_agent $loggable {
    "~kube-probe"   0;
    default         1;
}


text:
Q: How to develope prolog parser for mySMPL program? I am new in prolog i have a code that i want to read from file then parse this is the code here
    var x;
    x <- (5 * 2);
   return (x + 1).

now in prolog i want to tokenize this like this first
 ['var', 'x', ';', 'x','<-', '(', 5, '*', 2, ')', ';', 'return', '(', 'x', '+', 1, ')', '.']

the i want to implement predicate
 parse(+TokenList, -AST)

then again
evaluate(+AST, -Number)

using SWIProlog
The parser should not allow the keywords of the language (e.g., the arithmetic operators, <-,
var, return) as variable identifiers

A: You can try tokenize_atom, to see if it fits your requirements.
Otherwise, bite the bullet and try to write your own DCG...


text:
Q: Permanent category order How can I make the order of magento categories permanent so it doesn't change every time I import with magmi?
I was thinking of reassigning each category with the position value but I can't seem to find it.
Another way might be to write a script that moves the first category to the desired category to put it first and so on until it's done, but how do I move categories in a script?
Is there a way to fix this with magmi?


text:
Q: ASP.Net core HTTP requests never reach my API, and wont redirect to HTTPS When I call my asp.net core API using an HTTP URL, the request never reaches my app, I've added a middleware to test this, and the request never hits the context. Though I've configured https redirection as I will show below, no Http request redirect to https.
But when I use an HTTPS URL, the request now hits my app.
I want to be able to call my API from Http URL then it redirects to https.
I've tried everything I saw on the internet.
I tried enabling HTTPS redirection, but nothing worked.
Here is what the https redirection looks like:
public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
    if (env.IsDevelopment()) {
        app.UseDeveloperExceptionPage();
    }
    else {
        app.ConfigureExceptionMiddleware();
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseCookiePolicy();
    app.UseMvc();
}

IN the configureServices method:
services.AddHttpsRedirection(options => {
    options.RedirectStatusCode = StatusCodes.Status308PermanentRedirect;
    options.HttpsPort = 44382;
});

launchSettings.json
 "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:53471",
      "sslPort": 44382
    }
  },

The code doesn't work and does not enable redirection. It only permits me to access my app via HTTPS, but redirection is not done.
Can anyone tell me how I can make a call to Http redirect to https?

A: What caused this problem was that I had two profiles in my Launch settings.json and I was chosing the wrong profile to launch the app.
Selecting the profile (in project settings) with the attribute: "commandName": "Project" resolved this issue. The guys in the comments on my answer lead me on the right track to solve this issue.

A: I think you are missing HTTPS port, so your app should have logged error message "Failed to determine the https port for redirect."
You can configure the port using one of the following methods.

*

*Set HttpsRedirectionOptions.HttpsPort

*Set ASPNETCORE_HTTPS_PORT environment variable (Restart the computer to reflect changes)

*You can configure https_port port in appsettings.json file
e.g:
  {
     "https_port": 443
  }

*Set an HTTPS URL in launchsettings.json

I hope one of these methods will resolve your issue!


text:
Q: Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON I am deploying a report in SSRS 2008.
I created the report on the same server as where it should be deployed on.
I am getting this error message when I try to deploy my solution:
Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'.

why does it use this user? is it logging into the database with this?
thanks so much for you guidance and ttime. and please let me know what information you need in order to point me into the right direction.

A: *

*SSRS Server uses data sources to connect to databases.

*When you setup a datasource in the SSRS server, under credentials: set the user and
password.

*When you deploy the report to the SSRS server. In the server you need
to assign the correct datasource per report

If this is a login problem with the SSRS Web Site, then check the setup. Link


text:
Q: Paypal click button is not working on safari I am troublinig with the paypal button click is not working specially in safari browser, and rest all browsers its working fine for me,
The issues is i am getting while i am clicking paypal button:
An SSL error has occurred and a secure connection to the server cannot be made.
ERROR:

ppxo_button_pre_template_click

Object{
country: "US"
env: "production"
host: "localhost:4200"
lang: "en"
pageID: "27fc589f4a"
path: "/"
referer: "localhost:4200"
timestamp: 1507207991057
uid: "0b1089af2f"
ver: "4.0.131"
windowID: "5cf026dfb9"}

A: This might be an issue since you are working locally. Try to do the following:
In your address bar type: https://localhost:4200 I added and "s" to the http://. This will be a quick hack. When you deploy this to your actual domain, some of this errors go away if not you can purchase an SSL certificate for your website. Also you might want to take a look to Paypal's documentation on security
https://developer.paypal.com/docs/classic/lifecycle/info-security-guidelines/


text:
Q: .vimrc does not appear when I 'ls', but I can open it when it type 'vim .vimrc' in same directory. why? I was searching for my vimrc so I could change my settings in vim, but was struggling to find it. I followed this which gave me the directory of the vimrc (user/home/.vimrc) that my vim is currently using, but when I went into home and hit ls to find the file, there was nothing that said .vimrc or vimrc. However, when I typed vim .vimrc in that same directory, I was able to open the file.
I am very new to everything Linux, so I don't know what exactly I am getting wrong; does ls not list all the files in a directory, or is .vimrc an exceptional file type?

A: Any file that is preceded by . is a hidden file.
ls will not show hidden files by default.
You can use the -a(all flag) to display ALL files.
$ ls -a
.
..
00001ea3_medium.jpeg
video.mp4

Using the  -l (long listing flag) will display more information regarding the files:
$ ls -al
-rw-rw-r--   1 za   za             7275 Apr  7 00:59  .xboardrc
-rwxr-xr-x   1 za   za              131 Apr 20  2017  .xinputrc
-rwxr-xr-x   1 za   za             8099 Apr 19  2017  .xscreensaver
-rw-------   1 za   za             3569 Jun 13 03:51  .xsession-errors
-rw-------   1 za   za             3569 Jun 12 22:28  .xsession-errors.old

You can read more about the ls command by reading the manpage online or from terminal:
man ls

To filter the results you can use grep in combination with ls.
$ ls -al | grep vim
drwxr-xr-x   2 za   za             4096 May 15 02:53 .vim
-rwxr-xr-x   1 za   za            15049 May 25 21:51 .viminfo


text:
Q: How can I make a modal window(url) refresh to another modal window(url) via facebox This is ultimately what I want to achieve.
User clicks on Page1
Modal window opens.
User clicks on Page2
Modal window refreshes to that page.
/////
But this is what happens
User clicks on Page1
Modal window opens.
User clicks on Page2
Page changes to index2.html.

A: User clicks on "Page1" and page1 opens.
In page1 the user clicks on "refresh parent" button. The button then activates the following javascript command:
window.opener.location.reload(true);

window.opener referes to the parent page and location.reload(true) refreshes the page.


text:
Q: why Ransomware malware payment message not encrypted also? it is an awkward question but just want to know why the payment message not encrypted or corrupted or any error seems to happen when pop-up?
and what type of this message is it an excutable extension or something else?

A: As @Tetsujin said, the user needs to:

*

*Know that he must pay to recover his files;

*Know how to pay.

An encrypted message would be useless for both the hackers and the user.
How does a (basic) ransomware work?
You may not understand how a ransomware really works. A basic1 ransomwares will encrypt most of your files and create a READ_THIS_TO_GET_YOUR_FILES_BACK.txt on your desktop. However, it won't encrypt the files needed by your OS as your computer must be able to boot for you to see what is happening.
Imagine you have this file structure:
C:\Documents and Settings\Victim

.
├── Desktop
│   ├── photo.png
│   └── stuff.txt
├── Documents
│   └── Work
│       ├── contract.pdf
│       ├── another_document.pdf
...

Our basic ransomware can decide to only encrypt the files that are in the C:\Documents and Settings\Victim directory. To be sure you know what's going on, it will create the file READ_THIS_TO_GET_YOUR_FILES_BACK.txt on your desktop.
You will be stuck with a file structure like this:
C:\Documents and Settings\Victim

.
├── Desktop
│   ├── photo.png [encrypted]
│   ├── stuff.txt [encrypted]
│   └── READ_THIS_TO_GET_YOUR_FILES_BACK.txt [not encrypted]
├── Documents
│   └── Work
│       ├── contract.pdf [encrypted]
│       ├── another_document.pdf [encrypted]
...

To be even more scary, it could rename all your file too to some strange random_str.bin names.
As you can see, the creation of that last .txt file is totally independent of the encryption used. Nothing about the key used is leaked. It's just a regular file. Encrypting it would be counter-productive. They need you to know that you have to pay, and they need you to know how to pay.
Think about it like a kidnapping: will you stick your ransom note on your victim, locked in your basement?

1 This is a really basic explanation of how ransomware may work. Some of them will encrypt your whole hard drive; others won't encrypt anything but will still kick you out of your computer. What is certain is that they will all figure out a way to tell you how to pay. They need you to pay.
They also have a great customer service.


text:
Q: read a file and sort marks I am trying to write a code to read a file of names, emails and marks in order to sort data from the lower mark to higher
The structure of file is  name;email;mark
                          name;email;mark
                          ...
The problem is that I get error with this line 'note.get(j+1)=note.get(j)'
"unexpected type required variable found value"
here is my code is it correct ?? help please
   try {
 BufferedReader lineReader = new BufferedReader(new
 FileReader("C://wamp/www/text.txt"));
 String lineText = null;
 ArrayList<String> nom = new ArrayList<String>();
 ArrayList<String> email= new ArrayList<String>();
 ArrayList<Double> note = new ArrayList<Double>();
 while ((lineText = lineReader.readLine()) != null) {
 String[] split = lineText.split(";");
 nom.add(split[0]);
 email.add(split[1]);
 note.add(Double.parseDouble(split[2]));
}
double temp;
String temps;
 for(int i=0;i<note.size();i++){
for(int j=0;j<note.size()-1-i;j++){
  if(note.get(j)> note.get(j+1)){
    temp=note.get(j);
    note.get(j+1)=note.get(i);
    note.get(i)=temp;
      temps=nom.get(j);
    nom.get(j+1)=nom.get(i);
    nom.get(i)=temps;
            temps=email.get(j);
    email.get(j+1)=email.get(i);
    email.get(i)=temps;
  }
  }

   }

  lineReader.close();
  } catch (IOException ex) {
  System.err.println(ex);
  }
  }

A: There's an easy way to sort your list.  First off, create a new class so you can link nom, email, and note all together:
public class Entry implements Comparable {

    String nom;
    String email;
    double note;

    public Entry(String nom, String email, Double note) {
        this.nom = nom;
        this.email = email;
        this.note = note;
    }

    @Override
    public int compareTo(Object o) {
        if(!(o instanceof Entry)) throw new IllegalArgumentException("Wrong type!");

        Entry other = ((Entry) o);

        if(this.note > other.note) return 1;
        if(this.note == other.note) return 0;
        return -1;
    }
}

You can implement the Comparable interface so you can easily sort using built-in java methods however you want.  Read more about this here.
Do this before you read the file:
ArrayList<Entry> entries = new ArrayList<>();

And each line/entry you read (probably want to add input validation):
Entry next = new Entry(split[0], split[1], Double.parseDouble(split[3]));
entries.add(next);

Then, when you're done reading/creating your list of entries, simply do this to sort it:
Collections.sort(entries);

Your list will now be sorted from highest->lowest. Reverse it:
Collections.sort(entries, Collections.<Entry>reverseOrder());


text:
Q: Can you subclass UITabBarItem and to set it with a xib file? I want to create a custom UITabBarItem and to set its UI with a xib file like a regular UIView.
I've tried to create a subclass on UITabBarItem but the option of createing a xib file was unavailable.
Please take a look:

Is it possible to subclass UITabBarItem with a xib file?
Thanks!

A: UITabBarItem inherits from UIBarItem, and UIBarItem inherits from NSObject.
So UITabBarItem is not a view object, you can't use xib file with it.
If you want to make some customize appearances, please read the documents of UITabBarItem and UIBarItem, in "Customizing Appearance" sections.


text:
Q: If $A_n$ is an event, $X_n = \mathbb{1}_{A_n}$, and $X = 0$, why does $X_n \to X$ in probability imply $P(A_n) \to 0$? If $A_n$ is an event, $X_n = \mathbb{1}_{A_n}$, and $X = 0$, why does $X_n \to X$ in probability imply $P(A_n) \to 0$? I know that this means that $\forall \epsilon >0$, $P(|\mathbb{1}_{A_n}| \geq \epsilon) \to 0$, but don't know where to proceed.

A: Take $\varepsilon=1/2$, and note that
$$\{|1_{A_n}|\geq \varepsilon\}=\{1_{A_n}\geq 1/2\}=A_n,$$
such that if $1_{A_n}\stackrel{P}{\rightarrow}0$, then even
$$P(A_n)=P(|1_{A_n}|\geq \varepsilon)\rightarrow 0,$$
as $n\rightarrow\infty$.

A: Indicators only take the values 0 and 1. So if the absolute value of the indicator is at least some positive number, it must be 1.


text:
Q: Dispatch C function pointer with Swift type system I'd like to dispatch C function pointer with Swift type in my framework.
The C function will be provided in future by the framework user.
I think Protocol system is a way to realize that in that case.
How should I write?
The functions will be defined in C.
void someIntFunction(int32_t*const x, int32_t count);
void someFloatFunction(float32_t*const x, int32_t count);

Suppose that the import of C functions is done without any problems.
The goal is dispatch these c functions depending on the type.
I try with Swift protocol system.
public protocol CFunctionPointerProvider {
  static var someFunctionPointer: @convention(c) (UnsafeMutablePointer<Self>, Int32) -> Void { get }
}
extension Int32 : CFunctionPointerProvider {
  public static var someFunctionPointer: @convention(c) (UnsafeMutablePointer<Self>, Int32) -> Void { someIntFunction } // imported from C
}
extension Float32 : CFunctionPointerProvider {
  public static var someFunctionPointer: @convention(c) (UnsafeMutablePointer<Self>, Int32) -> Void { someFloatFunction } // imported from C
}
public func applyTwice<T: CFunctionPointerProvider>(source: UnsafeMutablePointer<T>, count: Int) {
    T.someFunctionPointer(source, Int32(count))
    T.someFunctionPointer(source, Int32(count))
}

These extensions will be defined by the framework user.
But I expect a work as
var intArray: [Int32] = [0, 0, 0, 0]
var floatArray: [Float32] = [0, 0, 0, 0]
applyTwice(source: &intArray, count: intArray.count) // call user-defined someIntFunction
applyTwice(source: &floatArray, count: floatArray.count) // call user-defined someFloatFunction

However, the above code cannot be built with the error '(UnsafeMutablePointer, Int32) -> Void' is not representable in Objective-C, so it cannot be used with '@convention(c)'.
I think the protocol-self should have a constraint which can be applied to ONLY C-compatible value types to realize the above code.
How should I write the constraint?
Also, is there any other way to dispatch C function pointers at compile time with type system.


text:
Q: How to configure ng-semantic in latest angular2 release candidate? I'm trying to configure ng-semantic with angular2 release candidate 4 but so far haven't been successful. Been following the instructions on the main npm page here

A: After tinkering around for awhile I finally got it to work. Note that I'm using ng-semantic 1.0.32 and angular 2 rc4.
Step 1:
You need to add ng-semantic to the vendorNPMFiles array in angular-cli-build.js
When you run ng build, ng serve or ng start the angular cli builds your project and outputs to the dist folder which has a vendor directory. This vendor directory contains the packages listed in vendorNPMFiles. Any package added in vendorNPMFiles has to already exist in the node_modules directory. So you should add ng-semantic like this:
[
  .....,
  'ng-semantic/**/*'
]

Step 2:
You need to configure ng-semantic in src/system-config.ts. So first you'll need to add it to the map object like this:
const map: any = {
  'ng-semantic': 'vendor/ng-semantic',
}

Then you'll also need to add it in the packages object like this:
const packages: any = {
  'ng-semantic': {main:'ng-semantic.js', defaultExtension:'js'}
}

Finally
After that you should be able to use it in any component like this:
    import {Component} from '@angular/core';
    import { SEMANTIC_COMPONENTS, SEMANTIC_DIRECTIVES } from "ng-semantic";

    @Component({
      selector: 'demo-cmp',
      directives: [SEMANTIC_COMPONENTS, SEMANTIC_DIRECTIVES],
      template: `
        <sm-segment class="raised">
         Hello
        </sm-segment>
      `
    })
    export class DemoComponent {}


text:
Q: Why Would This C++ Code Deadlock or Freeze? I have what I think is a simple background worker thread setup that has been working for millions of executions over many days. Recently I got a hang at this point in my code and am wondering if I've missed something in my setup that led to a deadlock.
Code snippet (will not compile):
cout << "Starting." << endl;
atomic<bool> keepThreadRunning;
mutex coutMutex;
keepThreadRunning = true;
auto doBackgroundTask1 = [&keepThreadRunning, &backgroundData1, &coutMutex] () {
    size_t numSteps = 0;
    while (keepThreadRunning && backgroundData1->doOneTask()) {
        ++numSteps;
    }
    coutMutex.lock();
        cout << " Did " << numSteps << " background 1 tasks." << endl;
    coutMutex.unlock();
};
auto doBackgroundTask2 = [&keepThreadRunning, &backgroundData2, &coutMutex] () {
    size_t numSteps = 0;
    while (keepThreadRunning && backgroundData2->doOneTask()) {
        ++numSteps;
    }
    coutMutex.lock();
        cout << " Did " << numSteps << " background 2 tasks." << endl;
    coutMutex.unlock();
};
thread backgroundThread1(doBackgroundTask1);
thread backgroundThread2(doBackgroundTask2);
doForegroundWork();
keepThreadRunning = false;
backgroundThread1.join();
backgroundThread2.join();
cout << "Finished." << endl;

I suspect I'm doing something wrong with the atomic or the mutex. I have no way of proving this to you, but the two sets of background data and the foreground work are completely isolated, so the threads have no buried locks or conflicts over that data. I'm showing two threads just in case I've missed something with the mutex around cout.


text:
Q: Jquery uniform wont design input type=text elements This picture shows that the input type=text wont be designed by the uniform lib.

here is the code:

    <meta charset="utf-8" />
    <title>Log On</title>

    <link href="/Content/JqueryUniform/Aristo/css/uniform.aristo.css" rel="stylesheet" type="text/css" />

<form action="/Affiliates/LogOn" method="post">

                User Name

                <input  style="width:90%" type="text" name="UserName" id="UserName" />

                Password

                <input style="width:90%" type="password" name="Password" id="Password" />

                Remember Me
                <input type="checkbox" name="RememberMe" id="RememberMe" />

</form>

A: Uniform doesn't do text inputs, or text areas at version 1.5. Time of writing this. Uniform styles: Selects (Drop downs), Checkboxes, Radio buttons, File Upload inputs.

A: Use this, it might work:
input[type=password]
$("input, input[type=password], textarea, select, button").uniform();

A: maybe the script is not loaded, try to rewrite the path to the library:


text:
Q: Update Boolean Within UseState Hook Is there a way to initiate state to true, then change to false after x amount of time within useState?
Currently looks like this:
const [scrollDown, setScrollDown] = useState(true)

setTimeout(() => {
    setScrollDown(false)
  }, 2000)

Looking to do something like this, but syntax doesn't appear to be correct:
const [scrollDown, setScrollDown] = useState(() => {
   setScrollDown(true)
   setTimeout(() => {
    setScrollDown(false)
  }, 2000)
})

Trying this as well:
const [scrollDown, setScrollDown] = useState(true, () => {
    setTimeout(() => {
      setScrollDown(false)
    }, 1000)
  })

A: Like others have mentioned, using useEffect works best so I went with this solution. My issue initially was passing that second empty array arg:
const [scrollDown, setScrollDown] = useState(true)

  useEffect(() => {
    setTimeout(() => {
      setScrollDown(false)
    }, 1000)
  }, [])

A: I'm afraid both of the code snippets you mentioned are not correct. useStates expects the value but we're returning nothing. Also, we can't pass second argument to useState. Your best bet would be to utilize useEffect that runs on first render only. There you can place your timeout.


text:
Q: Change JavaScript NaN Message to Something Else I've got an input[type="text"] that throws up a NaN error until another box is filled. I know why the message is appearing, that's not a problem, it's correct. I'm just wondering if I can change 'NaN' to something more descriptive for the user.

A: if(isNaN(input.value)) {
    input2.value = '';//or a message of your choice
}

A: Test the value with isNaN(value) and if true then handle it however you want.


text:
Q: Order By Descending using String and Int in SQL I Have try to display my testing column data is descending order using sql query but I accept data in following format
21
17
4
AB
0
AB
0
AB

but I Want below format
21
17
4
0
0
AB
AB
AB

I Want All AB value last of column

A: SELECT *
FROM test
ORDER BY col+0 DESC, col

A: You may try:
ORDER BY
    col REGEXP '^[0-9]+$' DESC,
    CASE WHEN col REGEXP '^[0-9]+$' THEN LPAD(col, 6, '0') ELSE col END DESC;

The first level of sorting places number strings before anything containing non digits.  The second level sorts descending by the column.  Note that we left pad with zeroes in the case the value be a number string.  This ensures that a lexicographical sort will agree with a numeric sort.

A: WIth Union:
SELECT * FROM documentsets WHERE tabla REGEXP '^[0-9]+$'
UNION
SELECT * FROM documentsets WHERE NOT tabla REGEXP '^[0-9]+$'


text:
Q: UDP Packet drops I understand that the receive flow for a UDP packet is

*

*Check udp header for errors

*Match destination to socket

*Send an error message back if no such socket

*Put packet into appropriate socket receive queue

*Wake up process waiting for data for that socket

But in the above stages what would /proc/net/udp count as a drop? Does the failure of any step above constitute as a drop? Or is it only when the receive queue/buffer is full?

A: In Linux 5.4.66, the pseudo-file /proc/net/udp is generated by a function in net/ipv4/udp.c:
int udp4_seq_show(struct seq_file *seq, void *v)
{
        seq_setwidth(seq, 127);
        if (v == SEQ_START_TOKEN)
                seq_puts(seq, "  sl  local_address rem_address   st tx_queue "
                           "rx_queue tr tm->when retrnsmt   uid  timeout "
                           "inode ref pointer drops");
        else {
                struct udp_iter_state *state = seq->private;

                udp4_format_sock(v, seq, state->bucket);
        }
        seq_pad(seq, '\n');
        return 0;
}

That calls udp4_format_sock() in the same file:
static void udp4_format_sock(struct sock *sp, struct seq_file *f,
                int bucket)
{
        struct inet_sock *inet = inet_sk(sp);
        __be32 dest = inet->inet_daddr;
        __be32 src  = inet->inet_rcv_saddr;
        __u16 destp       = ntohs(inet->inet_dport);
        __u16 srcp        = ntohs(inet->inet_sport);

        seq_printf(f, "%5d: %08X:%04X %08X:%04X"
                " %02X %08X:%08X %02X:%08lX %08X %5u %8d %lu %d %pK %u",
                bucket, src, srcp, dest, destp, sp->sk_state,
                sk_wmem_alloc_get(sp),
                udp_rqueue_get(sp),
                0, 0L, 0,
                from_kuid_munged(seq_user_ns(f), sock_i_uid(sp)),
                0, sock_i_ino(sp),
                refcount_read(&sp->sk_refcnt), sp,
                atomic_read(&sp->sk_drops));
}

Note that the value of the drops field comes from atomic_read(&sp->sk_drops).  That value is incremented using atomic_inc(&sk->sk_drops) in a couple of places.

*

*The receive queue is full
int __udp_enqueue_schedule_skb(struct sock *sk, struct sk_buff *skb)
{
         ...
        /* try to avoid the costly atomic add/sub pair when the receive
         * queue is full; always allow at least a packet
         */
        rmem = atomic_read(&sk->sk_rmem_alloc);
        if (rmem > sk->sk_rcvbuf)
                 goto drop;
       ...
drop:
        atomic_inc(&sk->sk_drops);

*Bad checksum frames
static struct sk_buff *__first_packet_length(struct sock *sk,
                                             struct sk_buff_head *rcvq,
                                             int *total)
{
        struct sk_buff *skb;

        while ((skb = skb_peek(rcvq)) != NULL) {
                if (udp_lib_checksum_complete(skb)) {
                        ...
                        atomic_inc(&sk->sk_drops);

*Failure to read
int udp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int noblock,
                int flags, int *addr_len)
{
        ...
        if (checksum_valid || udp_skb_csum_unnecessary(skb)) {
                if (udp_skb_is_linear(skb))
                        err = copy_linear_skb(skb, copied, off, &msg->msg_iter);
                else
                        err = skb_copy_datagram_msg(skb, off, msg, copied);
        } else {
                err = skb_copy_and_csum_datagram_msg(skb, off, msg);

                if (err == -EINVAL)
                        goto csum_copy_err;
        }

        if (unlikely(err)) {
                if (!peeking) {
                        atomic_inc(&sk->sk_drops);

*Failures during receive
static int udp_queue_rcv_one_skb(struct sock *sk, struct sk_buff *skb)
{
        ...
drop:
        ...
        atomic_inc(&sk->sk_drops);

*Failures during multicast processing when trying to clone the message
static int __udp4_lib_mcast_deliver(struct net *net, struct sk_buff *skb,
                                    struct udphdr  *uh,
                                    __be32 saddr, __be32 daddr,
                                    struct udp_table *udptable,
                                    int proto)
{
        ...
        sk_for_each_entry_offset_rcu(sk, node, &hslot->head, offset) {
                ...
                nskb = skb_clone(skb, GFP_ATOMIC);

                if (unlikely(!nskb)) {
                        atomic_inc(&sk->sk_drops);


text:
Q: How to detect brightness in live webcam using javascript I would like to detect the brightness of my room using the webcam and save them into a database.
I thought it would be possible with javascript, 'cause there are many jQuery plugins for webcam using. I googled lot but didn't get any good idea to complete this. So any one know about this? how to do this.
best,
brigi

A: I don't think you can achieve that in pure javascript, but if you can grab an image then just send that to the server and use a server side script to analyse the brightness of the image and store that in the database.
On the server side you will find a lot more script to do such things, in javascript I don't know of any work done over analysing images to that extend.
This might help Quickly get brightness / lumanacity of images


text:
Q: Process the image for good OCR recognition I'm trying to proccess a picture. Initially, there is a lot of noise, but I'm trying to make some improvements. Unfortunately, this does not give much result. It may be possible to realize such a thing that somehow select the center of each black line of letters in the word and do something like their skeleton. I have no idea how to do this, so please help here.
The code i'm using now:
word = cv2.resize(word, (word.shape[1]*2, word.shape[0]*2))
kernel = np.array([[-1,-1,-1], [-1,9,-1], [-1,-1,-1]])
word = cv2.filter2D(word, -1, kernel)
word[np.where((word >= [180,180,180]).all(axis=2))] = [255,255,255]
word[np.where((word <= [179,179,179]).all(axis=2))] = [0,0,0]
cv2.imshow(str(i), word)

it gives this result: from this:

A: Try cv2.erode().
cv2.bitwise_not(img,img)
kernel = np.ones((3,3),np.uint8)
erosion = cv2.erode(img,kernel,iterations = 1)


text:
Q: Trying to renew a cert made with my own CA fails with "There is already a certificate for... " I've set up my own CA following the directions from Jamie and issued my first certs a year ago happily.  They have now expired, but I'm having a devils own time trying to renew them.
I have tried the code I used to create the certs in the first place, giving it a different output name, but I'm getting an error.
openssl ca -config intermediate/openssl.cnf -extensions usr_cert -days 375 -notext -md sha256 -in intermediate/csr/blahapi2.csr.pem -out intermediate/certs/blahapi2.cert.pem
Using configuration from intermediate/openssl.cnf
Enter pass phrase for /root/ca/intermediate/private/intermediate.key.pem:
Check that the request matches the signature
Signature ok
ERROR:There is already a certificate for /C=AU/ST=Victoria/O=MD/CN=blahapi.there.com.au/emailAddress=pnunn@example.com
The matching entry has the following details
Type          :Valid
Expires on    :220501022116Z
Serial Number :1000
File name     :unknown
Subject Name  :/C=AU/ST=Victoria/O=MD/CN=blahapi.there.com.au/emailAddress=pnunn@example.com

I guess there is another way to renew a certificate with the same credentials, but I can't find it anywhere.
Clues?


text:
Q: Add a row to a TableView from a Detail view So I have a tableView and a detail view.  I have an extra row in my tableView to "Add" a record.  When I click on the new button I send a nil object to my detail view which is the same that I use for editing an existing row.  I use the following code for that:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    new = NO;
    NSUInteger row = [indexPath row];
    SavedCarDetailController *detailController = [[SavedCarDetailController alloc] initWithNibName:@"SavedCarDetailController" bundle:nil];
    if(indexPath.row >= [listOfCars count]){
         NSLog(@"New Car");
         detailController.car = nil;
        new = YES;
    } else {
        new = NO;
        detailController.car = [listOfCars objectAtIndex:row];
    }
    detailController.managedObjectContext = self.managedObjectContext;
    [self.navigationController pushViewController:detailController animated:YES];
    [detailController release];
}

When I save my core data stuff I execute this in my detailController
 - (void)viewWillDisappear:(BOOL)animated {
    NSError * e = nil;
    if(self.New){
        NSLog(@"New Car Saving");
        NSManagedObject * obj = [NSEntityDescription insertNewObjectForEntityForName:@"Cars" inManagedObjectContext: managedObjectContext];
        [obj setValue:Name.text forKey:@"name"];
        [obj setValue:Year.text forKey:@"Year"];
        [obj setValue:Notes.text forKey:@"Notes"];

    } else {
        NSLog(@"Updating exiting car");
        car.Name = Name.text;
        car.Year = Year.text;
        car.Notes = Notes.text;
}
    [managedObjectContext save:&e];
    if(e){
        NSLog(@"Error occurred, %@", e);
    }
    if(self.New){

    } else {
    //  [self.parentViewController.tableView reloadData];

    }
 }

Then I update my tableView with reloadData but it only updates the modified feild
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    if(new){
        NSInteger row = [listOfCars count];
        NSLog(@" row  %i", row);
        NSArray *paths = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:row inSection:0]];
        //NSArray * foo = [NSArray arrayWithArray:<#(NSArray *)array#>
        [self.tableView beginUpdates];
        [self.tableView insertRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationFade];
        [self.tableView endUpdates];
        new = NO;
    }
    //This only works with "changed data" not new rows.
    [self.tableView reloadData];

}

This saves new rows to my database but the new row never appears.  The InsertRows actually coreDumps on me.  I am pretty sure I need to use the insertRowsAtIndexPaths but I have no clue where to put it so it will be executed once I have added the object to CoreData.  Any ideas?

A: You forget to insert the newly created car to the listOfCars array.


text:
Q: Chart Control Multiple ChartArea's, Same Table I've got a table with three columns, the latter two with values in them.  I'm trying to output two pie charts displaying the data for each one.  For some reason, the second pie chart isn't displaying, instead it's coming up as a gray square.  Additionally the legend is appearing twice consecutively, but it's only a single legend which makes no sense to me.
Here's the markup:
<asp:Chart Height="500" Width="500" ID="ClientModelChart" runat="server">
    <Series>
       <asp:Series ChartType="Pie" IsValueShownAsLabel="true" Name="PortfolioActual"></asp:Series>
       <asp:Series ChartType="Pie" IsValueShownAsLabel="true" Name="ModelActual"></asp:Series>
    </Series>
    <Legends>
       <asp:Legend Name="PortfolioActual"></asp:Legend>
       <asp:Legend Name="ModelActual"></asp:Legend>
    </Legends>
    <ChartAreas>
       <asp:ChartArea Area3DStyle-Enable3D="true" Area3DStyle-LightStyle="Realistic" Name="PortfolioActual"></asp:ChartArea>
       <asp:ChartArea Area3DStyle-Enable3D="true" Name="ModelActual"></asp:ChartArea>
    </ChartAreas>
</asp:Chart>

Then I've got a SqlDataAdapter used to fill a DataSet, I then turn the DataTableCollection into an IEnumerable list type so I can use it when data binding the chart series.  It seems a bit hairy, but the reason I do this is because the DataSet is used for some XSLT output later on, so there's no point re-querying the database when I've already got the data I need/want.
Dim sectorList As IList = CType(ds.Tables(1), IListSource).GetList()

ClientModelChart.Series("PortfolioActual").Points.DataBind(sectorList, "Sector", "Model", Nothing)
ClientModelChart.Series("ModelActual").Points.DataBind(sectorList, "Sector", "Client", Nothing)

So the second pie chart (ModelActual) isn't displaying at all, it's just a gray square.  I've been fiddling for hours with no avail. (EDIT: Also, I've already done something similar so I don't know why this one isn't working.  The difference with my other one is that it came from two separate sets of data initially, but that shouldn't be the reason it doesn't work)
Thanks.

A: Okay, I spent the morning on it stupidly, but I solved all the problems.  The issue with the legend was solved because you need to specify the legend against the series like so:
      <asp:Chart Height="500" Width="500" ID="ClientModelChart" runat="server">
        <Legends>
          <asp:Legend Name="PortfolioActual"></asp:Legend>
          <asp:Legend Enabled="false" Name="ModelActual"></asp:Legend>
        </Legends>
        <Series>
          <asp:Series ChartType="Pie" Legend="PortfolioActual" ChartArea="PortfolioActual" IsValueShownAsLabel="true" Name="PortfolioActual"></asp:Series>
          <asp:Series ChartType="Pie" Legend="ModelActual" ChartArea="ModelActual" IsValueShownAsLabel="true" Name="ModelActual"></asp:Series>
        </Series>
        <ChartAreas>
          <asp:ChartArea Area3DStyle-Enable3D="true" Area3DStyle-LightStyle="Realistic" Name="PortfolioActual"></asp:ChartArea>
          <asp:ChartArea Area3DStyle-Enable3D="true" Area3DStyle-LightStyle="Realistic" Name="ModelActual"></asp:ChartArea>
        </ChartAreas>
      </asp:Chart>

and binding the data should be done like this instead:
Dim sectorList As IList = CType(ds.Tables(1), IListSource).GetList()

ClientModelChart.Series("PortfolioActual").Points.DataBindXY(sectorList, "Sector", sectorList, "Model")
ClientModelChart.Series("ModelActual").Points.DataBindXY(sectorList, "Sector", sectorList, "Client")
ClientModelChart.Series("PortfolioActual")("PieLabelStyle") = "Outside"
ClientModelChart.Series("ModelActual")("PieLabelStyle") = "Outside"

Got there in the end.


text:
Q: Instantiate object when Tomcat starts I have a Tomcat server deployed that receives observations transmitted from sensors in JSON format. I also have a sensor describing ontology that I want to make use of.
However, I'd like to load the ontology before any sensor observations are received by the server. How can I instantiate an object as soon as Tomcat is loaded?

A: To execute actions when your application starts or stops you should use a ServletContextListener: http://download.oracle.com/javaee/6/api/javax/servlet/ServletContextListener.html
In web.xml:
<web-app>
    ...
    <listener>
        <listener-class>com.example.Listener</listener-class>
    </listener>
    ...
</web-app>

In contrast to Peter Knego's proposal this solution is portable to any servlet container and not confined to Tomcat.

A: I presume that strictly speaking, what you want to do is instantiate an object as soon as your servlet is loaded by Tomcat.  (It wouldn't really make any sense to modify Tomcat itself for an application-specific functionality).
In this case, your Servlet class can override/implement the init(ServletConfig config) method.  This is called by the servlet container (Tomcat in this case) when the servlet is initialised, and is exactly the right place to perform static startup logic, such as the kind you are referring to here.
In fact, the servlet will not even be able to receive connections until its init method has returned, so you can guarantee that the ontology will be fully loaded before the sensor observations arrive.

A: You could use event listeners which are invoked when the web app (contex) is loaded. There you initialize your objects and save them to ServletContext where they'll be available to all servlets in your app.
Implement ServletContextListener and in it's contextInitialized() put:
contextInitialized(ServletContextEvent sce){

    // Create your objects
    Object myObject = ...

    sce.getServletContext().setAttribute("myObjectKey", myObject);
}

Then register the listener in Tomcat context.xml:
<Context path="/examples" ...>
    ...
    <Listener className="com.mycompany.mypackage.MyListener" ... >
    ...
</Context>


text:
Q: Complete Class Python I am doing an assignment and it is not going very well. It is my code which is not working super good:
from dataclasses import dataclass

@dataclass
class Node:
    value: int = None
    nxt: Node = None

@dataclass
class Deque:
    head: Node = None      # First node in queue
    tail: Node = None      # Last node in queue
    size: int = 0

    def add_first(self, n):
        new = Node(n, None)
        if self.head is None:
            self.head = new
            self.tail = new
        self.size += 1

        s = "{ "
        node = self.head
        while node is not None:
            s += str(node.value) + " "
            node = node.nxt
        s += "}"
        return s

    def add_last(self, n):
        new = Node(n, None)
        if self.head is None:
            self.head = new
            self.tail = new
        else:
            self.tail.nxt = new
            self.tail = new
        self.size += 1

    def get_last(self):
        if self.tail is None:
            print("Get can't be applied on an empty list")
            return None
        else:
            return self.tail.value

    def get_first(self):
        if self.head is None:
            print("Get can't be applied on an empty list")
            return None
        else:
            #node = self.head
            return self.head.value

    def remove_first(self):
        if self.head is None:
            print("Remove can't be applied on an empty list")
        elif self.head == self.tail:
            s = self.head.value
            self.head = None
            self.tail = None
            self.size -= 1
            return s
        elif self.size == 1:
            node = self.head
            self.head = self.head.nxt
            self.size -= 1
            return node.value

Output:
{ 1 2 3 4 5 6 7 8 9 10 }
Size: 10
{ 20 19 18 17 16 15 14 13 12 11 1 2 3 4 5 6 7 8 9 10 }
Size: 20
Update:
I found an answer to my question. It was issues regarding def add_first and def remove last as well as def remove first.

A: Because this is homework I'm not going to give away the fixed code, but I will point out what needs fixing. I believe I figured out all the required fixes, but I could be wrong since you didn't share the code used to test your Deque:

*

*Your add_first method is unnecessarily stepping through all the
Nodes, then setting the last Node (the tail)'s nxt value to the
new Node, meaning the new Node will appear at the end of the Deque.
Instead, all you need to do is set the nxt of the new Node to the
current head, and set head to the new Node.

*Your remove_first doesn't account for any case except if there's
one Node in the Deque. You have to set the Deque's head to its old
head's nxt Node in all other cases.

*Your remove_last also doesn't account for any case except if
there's one Node in the Deque. In all other cases, you have to loop
through the Deque's Nodes, starting with head, until you find a
Node whose nxt value is the Deque's tail, then set its nxt to
None, and set the Deque's tail to that Node.
Example of finding the Node before the tail Node:
node = self.head
while node.nxt != self.tail:
    node = node.nxt
node.nxt = None
self.tail = node


text:
Q: Redirecting as proxy one subfolder of apache server to azure web app I have a website on apache web server, and I would like one of subfolders to transparently redirect to azure web app.

*

*mydomain.org -> regular apache page

*mydomain.org/something -> regular apache page

*mydomain.org/azure  -> redirect to azure

However, I would need the url to stay on mydomain.org, so I would like - for example mydomain.com/azure/x/y to actually show result of azuredomain.org/x/y
I believe I can do it using .htaccess with rule: RewriteRule ^(.*)$ azuredomain.org/$1 [P]
However, this results in azure 404 error with suggestion that maybe "Custom domain has not been configured inside Azure", which is in fact correct.
Is it possible to configure 'mydomain.org ' as custom domain in azure, but only for one subfolder (mydomain.org /azure/) while allowing all other urls to map to apache server?

A: I managed to make it work:

*

*Create subdomain 'azure' pointing to folder 'azure'

*Add .htaccess to 'azure' folder with rule RewriteRule ^(.*)$ azuredomain.org/$1 [P]

*Add records to domain:

*

*TXT / asuid.azure / [verificationID]

*CNAME / azure / azuredomain.org

*In Web App settings add custom domain with subdomain: azure.mydomain.org


text:
Q: onActivityResult in my BaseAdapter is not firing In my getView i have the following
holder.ivDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {

                switch (v.getId()) {
                    case R.id.ivDelete:

                        PopupMenu popup = new PopupMenu(mContext, v);
                        popup.getMenuInflater().inflate(R.menu.transaction_list_menu,
                                popup.getMenu());
                        popup.show();
                        popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                            @Override
                            public boolean onMenuItemClick(MenuItem item) {

                                switch (item.getItemId()) {
                                    case R.id.edit:

                                        Intent i = new Intent(v.getContext(), EditAmountDialogActivity.class);
                                        i.putExtra("table", table);
                                        i.putExtra("id", listItemId);
                                        ((Activity) mContext).startActivityForResult(i, Activity.RESULT_OK);

                                        break;
                                    case R.id.delete:

                                        AlertDialog.Builder alertDialog = new AlertDialog.Builder(v.getContext());
                                        alertDialog.setMessage("Are you sure you want to delete?")
                                                .setCancelable(false)
                                                .setPositiveButton("Yes", new DialogInterface.OnClickListener(){
                                                    public void onClick(DialogInterface dialog, int id){
                                                        db.deleteTransaction(table, listItemId);
                                                        notifyDataSetChanged();
                                                    }
                                                })
                                                .setNegativeButton("No", new DialogInterface.OnClickListener(){
                                                    public void onClick(DialogInterface dialog, int id){
                                                        dialog.cancel();
                                                    }
                                                });
                                        AlertDialog alert = alertDialog.create();
                                        alert.show();

                                        break;

                                    case R.id.refresh:
                                        cursor = db.getTransactions(table);
                                        ((TransactionActivity)mContext).setBalances();
                                        notifyDataSetChanged();
                                        break;

                                    default:
                                        break;
                                }

                                return true;
                            }
                        });

in the R.id.edit i am starting activity for result
in the EditAmountActivityDialog.class i have the following
dialogButtonOK.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                memo = etMemo.getText().toString().replace("'", "\'\'");
                timestamp = etDate.getText().toString();

                try {
                    amountDouble = Double.parseDouble(etAmount.getText().toString().replace(",", ""));
                } catch (NumberFormatException e) {

                }

                if (amountDouble == 0.0) {
                    Toast.makeText(getApplicationContext(), "You must enter an amount!",
                            Toast.LENGTH_SHORT).show();
                } else {

                    hideSoftKeyboard();
                    db.updateTransaction(id, table, type, amountDouble, memo, dbTimestamp);
                    db.close();
                    Intent i = new Intent();
                    setResult(RESULT_OK, i);
                    finish();
                }

Any idea why it is not activating the onActivityResult?
Thanks!

A: Don't startActivityForResult() with RESULT_OK as the requestCode. RESULT_OK value is -1 and onActivityResult() won't be called if the requestCode is below 0.

A: You are using the startActivityForResult and the setResult methods wrong.
You should specify a request code for your startActivityForResult so it can be later used in onActivityResult to determine which request has a result available.
Define a static and final variable on the top of your class:
private static final int REQ_EDIT = 100;

It can be anything. We are just saving it for later reference.
Then start your activity for result:
 case R.id.edit:
     Intent i = new Intent(v.getContext(), EditAmountDialogActivity.class);
     i.putExtra("table", table);
     i.putExtra("id", listItemId);
     startActivityForResult(i, REQ_EDIT);
     break;

So you now have started an activity for the result.
To finish the activity with a result use the following code:
...
hideSoftKeyboard();
db.updateTransaction(id, table, type, amountDouble, memo, dbTimestamp);
db.close();
setResult(RESULT_OK);
finish();
...

This will return a OK result to your fragment.
In your fragment, override the onActivityResult method like below:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case REQ_EDIT:
            if(resultCode == Activity.RESULT_OK) {
                // Do something
            }
            break;
    }
}


text:
Q: How do I hide a React Native BottomTabNavigator (from React Navigation) on orientation change? I have a React Native app using React Navigation 2.2.5 and a BottomTabNavigator created with createBottomTabNavigator, which has a child StackNavigator. I need the Bottom Navigator to be hidden in landscape orientation globally or in at least one of the screens of the child StackNavigator. Can this even be achieved? Through the style property of the createBottomTabNavigator tabBarOptions?
  const RoomStack = createStackNavigator(
{
 Home: {screen: RoomsScreen},
 Room: {screen: RoomsRender},
},
{headerMode: 'none',
  initialRouteName: 'Home',
});

const HomeStack = createBottomTabNavigator(
{
  Home: RoomStack,
  'Create a Space': SpaceScreen,
  Settings: SettingsStack,
},
{
  /* Other configuration remains unchanged */
});

export default HomeStack

A: You can use custom tabBarComponent and render null when orientation changed. For receiving event of orientation changed, you can use React Native Orientation package (i did not use it myself but i don't think there is problem in using it). Your code will change like this:
import myTabBarComponent ...
const HomeStack = createBottomTabNavigator(
{
  Home: RoomStack,
  'Create a Space': SpaceScreen,
  Settings: SettingsStack,
},
{
  tabBarComponent: myTabBarComponent,
});

And your custom myTabBarComponent is:
import React from 'react'
import { BottomTabBar } from 'react-navigation-tabs';
import Orientation from 'react-native-orientation';

export default class myTabBarComponent extends React.PureComponent {

  constructor(props: TProps, context: any) {
    super(props)
    this.state = {
      lanscape: true,
    }
    Orientation.addOrientationListener(this._orientationDidChange);
  }

  componentWillUnmount() {
    Orientation.removeOrientationListener(this._orientationDidChange);
  }

  _orientationDidChange = (orientation) => {
    if (orientation === 'LANDSCAPE') {
      this.setState({lanscape : true})
    } else {
      this.setState({lanscape : false})
    }
  }

  render() {
    return !this.state.lanscape ?
      <BottomTabBar {...this.props} />
      :
      <View/>
  }
}

Maybe this code is not accurate but the solution is correct because i use it for keyboard show/hide. I hope this will help you.


text:
Q: Which topological manifolds do not correspond to strongly Hausdorff locales? I'm toying with the idea of using locales as a way to define topological manifolds without beginning with points, largely for philosophical reasons.
In this context I think I want to redefine a topological manifold as a locale that is paracompact and strongly Hausdorff in the sense of Johnstone Stone Spaces p.82.
My understanding is that this may make my version of the theory strictly smaller than the traditional one. That might be OK for my purposes, depending on what kinds of objects are "missing".
My question: is there any way to characterise those paracompact topological spaces that are Hausdorff but whose corresponding locales are not strongly Hausdorff?
I'm just beginning to learn about locales so would also appreciate answers that explain why my question (or whole project) is completely misconceived...

A: Let me expand a bit my comment as this is a rather subtle property.
As I said any locally compact Hausdorff topological space is a strongly hausdroff locally compact locales. (and under the axiom of choice the two notion are completely equivalent) So this does not exaclty answer the precise question you ask, but as it applies to all topological manifold, it should be sufficient for your purpose.
The result you need for this is lemma C4.1.8 of sketches of an elephant which says that:
Lemma :  (C4.1.8 in Sketches) The product of a locally compact spatial locale with a spatial locale is spatial.
The reason that it gives you what you want is because the only reason why Hausdroff and strongly Hausdorff are differents is because in general the product $X \times X$ in the category of locales can be non-spatial even if $X$ is spatial, hence asking that the diagonal map $X \rightarrow X \times^{top} X$ in the category of topological space is closed only say that the map from $X$ to the largest spatial sublocale of $X \times X$ is closed. But this largest spatial sublocale can be itself not closed and so it does not implies that the locale is strongly Hausdorff. But because of the lemma above, if $X$ is locally compact then $X \times X$ is spatial and so the product in the category of topological space and the product in the category of locales are the same.
This is enough for the treatment of manifolds.
I wouldn't be surprise if results of this kind also holds under only paracompactness assumption. But having only studied the constructive theory of locales I know very little of paracompactness in this framework so I leave to someone else to comment or answer about this.
Side note : I would like to add a last remark regarding your project: classically (i.e. assuming the axiom of choice and the law of excluded middle) there is a complete equivalence between locally compact strongly Hausdorff locales and locally compact Hausdorff topological spaces, so you will have no problem formulating differential geometry in this framework and it will not say anything new.
In constructive settings this is no longer true. In fact if you look at section D4.7 of Sketches of an elephant you will see a very interesting feature:
In constructive mathematics one can define a ``locale of real numbers'' which is always locally compact and Hausdorff but which is in general not spatial, i.e. not the same as the topological spaces of real numbers. And constructively The topological space of real numbers can even fail to be locally compact ! In fact it will be isomorphic to the locale of real number if and only if it is locally compact.
So clearly, if one wants to do differential geometry in constructive mathematics one HAS to use locales instead of topological space (or we need to say goodbye to local compactness... which would basically the end of everything in differential geometry) and I have never seen anyone develop that point of view.
(Also note that this is not related to AC, but really to LEM: the law of excluded middle alone is already enough to prove that the topological space of real number is locally compact/the locale of real number is spatial)


text:
Q: Sort Vimeo API Showcase by custom order I am using a call
$response = $client->request("/users/$client_id/albums/$showcase_id/videos", array(), 'GET');

so I can add the sorting parameters for instance ?sort=alphabetical&direction=desc but what I need is what Vimeo in the Showcase editor describe as 'custom' but ?sort=custom&direction=desc is not a valid call.
How do I obtain the sorting order from the drag and drop?

A: The various sort options are defined in the API docs, but I think the keyword you're looking for is manual. From the docs:

manual - Sort the results by their manual order.


text:
Q: extract substring in vb.net I have following string, and would need to extract the X and Y values cut to a single digit after the point.
A234X78.027Y141.864D1234.2
There are a few variables that can change here:

*

*the string can have any length and contain any number of values

*I know that X and Y are Always present, but they do not have to be in a specific order in the string

*Each value for X or Y can have any lenght.. for example x can be 1.1 or 1234.1

*it is not imperative that X or Y do have a point. it can also be a round number, for example X78Y141.34561 (note that X has no point) If there is no point I am ok with the value, but if there is a point then I would need the first digit after the point. (rounded)

As a Result of the above string I would need two string variables containing the values 78.0 and 141.9
EDIT: Updated the last sentence, the variables should contain JUST the value, no X and Y. Sorry for the mistake
Update, code as requested

        Dim objReader As New System.IO.StreamReader(FILE_NAME)

        Do While objReader.Peek() <> -1
            Dim curline As String = objReader.ReadLine()  'curline = G1X39.594Y234.826F1800.0
            If curline.Contains("X") Then
                Dim t As String = ExtractPoint(curline, "X"c) 't = "39.594"
                Dim d As Double = Math.Round(Convert.ToDouble(t), 1) 'd= 39594.0
                destx = d * 10 'destx = 395940

            End If
         Loop

Function ExtractPoint(dataString As String, character As Char) As String
    Dim substring As String = String.Empty

    Dim xIndex As Integer = dataString.IndexOf(character) + 1
    substring += dataString(xIndex)
    xIndex = xIndex + 1
    While (xIndex < dataString.Length AndAlso Char.IsLetter(dataString(xIndex)) = False)
        substring += dataString(xIndex)
        xIndex = xIndex + 1
    End While

    Return substring
End Function

A: Have you looked into Regular Expressions?
    Dim x As System.Text.RegularExpressions.Match = System.Text.RegularExpressions.Regex.Match(TextBox1.Text, "X\d+([.]\d{1})?")
    Dim y As System.Text.RegularExpressions.Match = System.Text.RegularExpressions.Regex.Match(TextBox1.Text, "Y\d+([.]\d{1})?")

    MsgBox(x.ToString & " -- " & y.ToString)

I believe this will do what you are looking for if I understood correctly.
EDIT For Only getting the numbers after X and Y
Based off my original code, you could do something like this.
This also rounds the numbers to the nearest one decimal place.
    Dim x As System.Text.RegularExpressions.Match = System.Text.RegularExpressions.Regex.Match(TextBox1.Text, "X(\d+([.]\d{2})?)")
    Dim y As System.Text.RegularExpressions.Match = System.Text.RegularExpressions.Regex.Match(TextBox1.Text, "Y(\d+([.]\d{2})?)")

    MsgBox(Math.Round(CDbl(x.Groups(1).Value), 1) & " -- " & Math.Round(CDbl(y.Groups(1).Value), 1))

Updated code for added code
    Dim s As String = "A234X78.027Y141.864D1234.2"
    Dim dX As Double = Extract(s, "X")
    Dim dY As Double = Extract(s, "Y")
    MsgBox(dX * 10 & "-" & dY * 10)

    Private Function Extract(ByRef a As String, ByRef l As String) As Double
        Dim x As System.Text.RegularExpressions.Match = System.Text.RegularExpressions.Regex.Match(a, l & "(\d+([.]\d{2})?)")
        Return Math.Round(CDbl(x.Groups(1).Value), 1)
    End Function

A: Your sample data indicates that fields are separated by letters, and the last letter ends with the string.  Knowing that you can parse your desired letters out manually and round to 1 decimal point.
This also takes into account when there is no decimal point, but it will display a .0 at the end of the number.
EDIT
Moved common code to a function
Update
Doesn't include the letter as part of the output
Sub Main()
    Dim dataString As String = "G1X39.594Y234.826F1800.0"

    Dim xString As String = ExtractPoint(dataString, "X"c)
    Dim yString As String = ExtractPoint(dataString, "Y"c)

    Dim xDouble As Double = Math.Round(Convert.ToDouble(xString), 1)
    Dim yDouble As Double = Math.Round(Convert.ToDouble(yString), 1)

    Console.WriteLine(xDouble.ToString("F1"))
    Console.WriteLine(yDouble.ToString("F1"))

    Console.WriteLine((xDouble * 10).ToString("F1"))
    Console.WriteLine((yDouble * 10).ToString("F1"))

    Console.ReadLine()
End Sub

Function ExtractPoint(dataString As String, character As Char) As String
    Dim substring As String = String.Empty

    Dim xIndex As Integer = dataString.IndexOf(character) + 1
    substring += dataString(xIndex)
    xIndex = xIndex + 1
    While (xIndex < dataString.Length AndAlso Char.IsLetter(dataString(xIndex)) = False)
        substring += dataString(xIndex)
        xIndex = xIndex + 1
    End While

    Return substring
End Function

Results:

A: Here is a simple LINQ function that should do it for you (no regex, no long code):
Private Function ExtractX(s As String, symbol As Char) As String
    Dim XPos = s.IndexOf(symbol)
    Dim s1 = s.Substring(XPos + 1).TakeWhile(Function(c) Char.IsDigit(c)).ToArray()
    If (XPos + 1 + s1.Length < s.Length) AndAlso s.Substring(XPos + 1 + s1.Length)(0) = "."c AndAlso Char.IsDigit(s.Substring(XPos + 1 + s1.Length)(1)) Then
      Return String.Join("", s1, s.Substring(XPos + 1 + s1.Length, 2))
    Else
      Return s1
    End If
End Function

Call it like this:
Dim s = "A234X78.027Y141.864D1234.2"
Dim x = ExtractX(s, "X"c)
Dim y = ExtractX(s, "Y"c)


text:
Q: Is Hibernate Criteria API Deprecated and if so what API should we use? Just as the title says. Is it deprecated? It says in the dev manual that it is and we should user JPA Criteria, but in the user manual there is no mention of this.

A: AFAIK and off looking at the Javadocs, the Hibernate Criteria API is not deprecated.  However, there is a very good argument for using JPA over hibernate, as it means you can switch between persistence providers without having to modify your code.  Where as if you go with the Hibernate Criteria API, then your code is completely tied in to Hibernate.
Update 06/07/16
From the Hibernate 5.2 documentation.
"This appendix covers the legacy Hibernate org.hibernate.Criteria API, which should be considered deprecated.
New development should focus on the JPA javax.persistence.criteria.CriteriaQuery API. Eventually, Hibernate-specific criteria features will be ported as extensions to the JPA javax.persistence.criteria.CriteriaQuery. For details on the JPA APIs, see Criteria.".
This means, the Hibernate criteria is usable as it isn't officially @Deprecated, but you should be using JPA instead!


text:
Q: Cron job that outputs "hello world" every minute to the terminal This is my first time playing with cron jobs and I can't figure out what's wrong. I've read the three most upvoted questions on this but it still won't work.
sayhello.sh, which has been made executable with chmod -x and is located at /home/user
#!/bin/sh
echo "HELLO WORLD"

in crontab -e
* * * * * DISPLAY=0.0 /home/user/sayhello.sh

A: A shell on its own has no way to interact with the user's desktop  - it needs to be attached to a terminal device of some kind. For example:
* * * * * DISPLAY=:0 gnome-terminal -- /home/user/sayhello.sh

or
* * * * * DISPLAY=:0 xterm -e /home/user/sayhello.sh

You may need to arrange for the terminal to stay open after the command exits - either through its preferences, or by adding a command such as read a to the bottom of your script (so that the shell blocks waiting for user input).

A: Did you try sudo chmod +x sayhello.sh?
I noticed you said -x, perhaps that is the issue. -x removes permissions to execute whilst +x adds it.

A: Setting all asterisks * * * * * tells crontab to run the command every minute of every day of every week of every month. You have to specify the times when you want to run the script:
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/


text:
Q: SendKeys is messing with NumLock when running macro from VBA editor Sorry to ask again this NumLock/SendKeys question, but I couldn't find a relevant answer in Stack Overflow.
My question is about the VBA class module NumLockClass proposed in this answer.
I created the below normal module in my MS Word Office 365 version.
To reproduce the issue:

*

*Create the VBA class module NumLockClass as proposed in the answer, and create a normal module with the code below.

*Make sure that your keyboard has the NumLock key light off (pressing the 1 of the numeric pad is then like pressing the End key)

*Run the macro test of the normal module below, directly from the VBA editor (position the cursor in the macro test and press F5)

*The input popup indicates "NumLock is deactivated", as expected

*Type 1 in the input field via the numeric pad, nothing is shown as expected, because pressing 1 when the NumLock key is off is like pressing the End key

*Now type a and press Enter, to activate programatically the NumLock key

*The input popup indicates "NumLock is activated", and on your keyboard you can see that the NumLock key light is on, as expected

*Type 1 in the input field via the numeric pad, and 1 is shown as expected

*Now replace 1 with e and press Enter, which executes programatically SendKeys "^{END}" (simulates Ctrl+End)

The input popup indicates "NumLock is activated", but on your keyboard you can see the NumLock key light is off and if I type 1 via the numeric pad, nothing happens i.e the NumLock has really been deactivated.
As we know, the reason is that SendKeys "^{END}" is messing with the NumLock key and it's buggy.
My question is not about why SendKeys "^{END}" is messing with the NumLock key, it's why does the class module given in the other Stack Overflow answer is unable to detect the right status of the NumLock key, and how to solve?
Thank you.
Dim numLock As New NumLockClass

Sub test()
    Do
        If numLock.value = False Then
            k = InputBox("NumLock is deactivated, pressing digit keys in the Numeric Pad does nothing." & vbCrLf & "- Type 'a' to activate NumLock" & vbCrLf & "- Type 'e' to type Ctrl+End")
        Else
            k = InputBox("NumLock is activated, press digit keys in the Numeric Pad to type a number." & vbCrLf & "- Type 'd' to deactivate NumLock" & vbCrLf & "- Type 'e' to type Ctrl+End")
        End If
        If k = "a" Then
            numLock.value = True
        ElseIf k = "d" Then
            numLock.value = False
        ElseIf k = "e" Then
            SendKeys "^{END}"
        Else
            Exit Sub
        End If
    Loop
End Sub


text:
Q: Why does coffeescript require parentheses here? Look at the following snippets:
if a
  return

if a b
  return

if (a b)
  return

if a(b)
  return

if a((b) -> c)
  return

if (a (b) -> c)
  return

if a (b) -> c
  return

The last one won't compile and it will produce a misleading error message, unexpected if.
I would expect it to produce the same output as the previous two.
Why is it not allowed?

A: In the last example there is an ambiguity whether the return is part of the function, or of the if statement. If it's interpreted as part of the function, then it would be a syntax error as there is no body for the if statement.
if a (b) -> c
  return

Could be interpreted as you expected:
if (a (b) -> c)
  return

Or the indentation of the return is understood to be a continuation of the anonymous function:
if (a (b) -> c
  return)

In this case it gives an error as there is no body to go with the if statement.
I'm not certain, but I assume it chooses to place the return inside the function as this is the closest context, and it hasn't been explicitly closed (eg. with parenthesis).
As an alternative, It's safe enough to use the parenthesis as you have, as it will fail with a compile error rather than giving you unexpected behaviour that would be dificult to debug.
If all you are doing is returning inside the if statement, you can use a trailing if:
return if a (b) -> c

Or execute the function first, then use the result in the if statement to make it more
verbose:
isValid = a (b) -> c
return if isValid


text:
Q: Usefulness of asymptotic (e.g., Big O) notation embedded in expressions Recently I've been working through The Probabilistic Method by Alon and Spencer, and I've noticed that almost everywhere results (specifically bounds) are given using asymptotic notation. Here are some examples:
On page 10 (Theorem 1.3.2), we bound a function $m(n)$ as follows:
$$m(n) < (1 + o(1)) \frac{e \ln 2}{4} n^2 2^n$$
On page 26 (Theorem 2.5.1), we bound a function $R(n)$:
$$R(n) \ge \left(  \sqrt{\frac{2}{\pi}} + o(1) \right)n^{3/2}$$
To my understanding the embedded $o(1)$'s mean that, take the second example, $R(n)$ is greater than the expression on the right when you replace the $o(1)$ with a function of $n$, call it $g(n)$, where $g(n) = o(1)$. (I.e., $\lim_{n \rightarrow \infty} g(n) = 0$.) My question is: how is a bound such as this actually useful? To me, it seems like the $o(1)$ is a hole in our bound that prevents it from being useful. For example, if I want to find a lower bound for $R(5)$ using the expression, I'm not sure how I would actually do that since I can't just plug in $n = 5$.
My intuition goes even more haywire when you have something other than 1 in there, like in
$$f(n) = n^2 + n + o(\ln n)$$
Or in one example in the book (Theorem 2.2.3), it says there exists a set of size $$m = \Theta((\ln n)^{1/(k-1)}$$
I don't see how this could possibly be helpful since, say $m =a \cdot   \Theta((\ln n)^{1/(k-1)}$ for some $a$, the constant $a$ could be arbitrarily large! It is just that bounds such as these are useful for deriving other important (perhaps more advanced) results? Or can I actually plug in numbers somehow? I'm used to thinking in terms of strict equalities and "plug things in," so any intuition would be much appreciated!

A: Think about the harmonic series, which can be approximated by
$$H_n \approx \ln(n) + \gamma$$
Where $\gamma$ is the Euler Mascheroni constant. However,
$$H_n > \ln(n) + \gamma$$
For all $n$. So if we want something that is always true we might say
$$H_n = \ln(n) + \gamma + O\left(\frac{1}{2n}\right)$$
Which means we have turned our inequality into an equivalency by adding an error term that is at worst $\dfrac{1}{2n}$ which tells us more about the function we are analyzing since
$$\lim_{n \rightarrow \infty} \frac{1}{2n} = 0$$
so we can say,
$$\lim_{n \rightarrow \infty} H_n = \lim_{n \rightarrow \infty} \left(\ln(n) + \gamma\right).$$


text:
Q: WebStorm, React & JSX curly braces autocomplete I have an issue with WebStorm and React.
Within the render function I type my HTML (JSX) and when I type an attribute for an element, WebStorm will autocomplete it with curly braces instead of speech marks.
Anyone any ideas?

A: You can control this behavior:
File | Settings | Editor | Code Style | HTML | Add for JSX attributes

The "Add for JSX attributes" setting is under the "Other" tab:

A:
Yes, Attila's answer is correct. It's a bit confusing though. This screenshot will complement Attila's answer.


text:
Q: DAX Filter Table To Replace Relationship I have two tables that I'm looking to create a DAX measure from.
DimProject
ProjectID EmployeeID StartDate
5         2          2017-08-01
6         2          2017-07-01

DimEmployee
EmployeeID Name
2          Nick

I need to return the MAX StartDate where the StartDate is on or before today. The kicker is, I cannot have a relationship between these two tables in SSAS directly, because there's already a relationship between these tables through a fact table. Here's what I have so far, but, it errors on the last EmployeeID reference.
When Placed Into Work:= CALCULATE(MAX(DimProject[ProjectStartDateKey]), FILTER(DimProject, DimProject[ProjectStartDateKey] < TODAY()), FILTER(DimProject, DimProject[EmployeeID] = DimEmployee[EmployeeID]))

EDIT:
I've tried an alternate method of creating the join between the two tables. However, while this formula compiles, it can't be used because it states that multiple values are being returned.
MAXX(DimProject, CALCULATE(VALUES(DimProject[ProjectStartDateKey]), FILTER(DimProject, DimProject[EmployeeID] = DimEmployee[EmployeeID]), FILTER(DimProject, DimProject[ProjectStartDateKey] < TODAY())))

A: 1) may I suggest you to flatten the 2 dimensions? means that you merge the dim tables like this:
ProjectID EmployeeID StartDate  EmployeeName
5         2          2017-08-01 Nick
6         2          2017-07-01 Nick

then returning the highest date becomes trivial.
2) you can make a non active relation between the two table and in your DAX formula you can force to use the non active relationship with USERELATIONSHIP
Hope that helps!


text:
Q: IntelliJ IDEA: "Indexed Maven Repositories" list - how to REMOVE a remote maven repository in this list? I really wanted this to be a comment to the answer posted in the thread IntelliJ IDEA: "Indexed Maven Repositories" list - how to add remote maven repository in this list? but my reputation does not allow for it. So please excuse this being posted as a new Question.
Is there any way to remove a repository from the "Indexed Maven Repositories" list? I moved projects and still see my old repositories in there, some of which have actually been taken offline.
I have tried re-importing my settings.xml file, restarting IntelliJ multiple times(invalidating the cache too), but cannot get those repositories to go away from this list.

A: In my case the "indexed maven repository" I wanted to remove wasn't defined in Maven's settings.xml, but was defined inside one of my many sub-project's pom.xml file. I had to delete the following section from a pom.xml file. After deleting that from the pom.xml file the "indexed maven repository" was removed from Maven's settings in IntelliJ
<repositories>
    <repository>
        <id>foo</id>
        <name>foo</name>
        <url>file://${project.basedir}/maven/repository</url>
    </repository>
</repositories>

A: All my repositories got removed from this list, probably because I've moved the project to another directory on my device.
My solution was to delete the jarRepositories.xml file, which is located inside the .idea folder.

A: Possible solution: Just delete the file ".idea" in your program's root file, and open the pom.xml as a new program, then you will find the "indexed maven repositories" is modified automatically.


text:
Q: Word or concept for "credit system" in context of "topping up" an account The word or concept I'm after is the system where a user of a service can transfer real money to their account (top-up), receive "credits", use those credits somehow inside the system, and then exchange the credits back to real currency (check-out). These "credits" wouldn't officially be recognized as a currency.
The concepts that I think are closest to what I'm looking for are complementary currency and scrip, but neither seems to be correct in my opinion.
Update:
No matter how I try to read credit's wiki definition, the 'provides resources to another party and arranges to repay those resources at a later date' doesn't seem to fit. As told, the purpose of these "credits" for which I try to find a better word for are, to be used as a form of currency inside the service.
This made me think of casino chips, which led me to another interesting contender: exonumia, which unfortunately appears to only be used in the context of physical items.

A: *

*credit

" The trust which allows one party to provide resources to another party where that second party does not reimburse the first party immediately (thereby generating a debt), but instead arranges either to repay or return those resources (or other materials of equal value) at a later date.
  - Wikipedia, Credit (as of June 26, 2014 09:30, UTC)

While the word doesn't appear to be correct by definition, it apparently is understood by many so as to justify it's usage when referring to virtual currency in a service.

*virtual currency

" A type of unregulated, digital money, which is issued and usually controlled by its developers, and used and accepted among the members of a specific virtual community.
  - Wikipedia, Credit (as of June 26, 2014 09:30, UTC)

Most unambiguous, but may be hard to use in writing due to not being succinct.

A: I think you're talking about their account balance, though you haven't provided enough context to be sure.

A: Try something like the phrase "currency exchange"
They are exchanging real currency for credits in your system. and then exchanging credits in your system for real currency.
'currency exchange' is also used when converting between differnet types of real money:  exchange Rupees for Yen, or Dollars for Pounds.
you can also try "credit transfer"


text:
Q: Create a new index in elasticsearch for each log file by date Currently
I have completed the above task by using one log file and passes data with logstash to one index in elasticsearch :
yellow open   logstash-2016.10.19   5   1    1000807            0    364.8mb        364.8mb
What I actually want to do
If i have the following logs files which are named according to Year,Month and Date
MyLog-2016-10-16.log
MyLog-2016-10-17.log
MyLog-2016-10-18.log
MyLog-2016-11-05.log
MyLog-2016-11-02.log
MyLog-2016-11-03.log

I would like to tell logstash to read by Year,Month and Date and create the following indexes :
yellow open   MyLog-2016-10-16.log
yellow open   MyLog-2016-10-17.log
yellow open   MyLog-2016-10-18.log
yellow open   MyLog-2016-11-05.log
yellow open   MyLog-2016-11-02.log
yellow open   MyLog-2016-11-03.log
Please could I have some guidance  as to how do i need to go about doing this ?
Thanks You

A: It is also simple as that :
 output {
   elasticsearch {
      hosts => ["localhost:9200"]
      index => "MyLog-%{+YYYY-MM-DD}.log"
   }
 }

A: If the lines in the file contain datetime info, you should be using the date{} filter to set @timestamp from that value.  If you do this, you can use the output format that @Renaud provided, "MyLog-%{+YYYY.MM.dd}".
If the lines don't contain the datetime info, you can use the input's path for your index name, e.g. "%{path}".  To get just the basename of the path:
mutate {
    gsub => [ "path", ".*/", "" ]
}

A: wont this configuration in output section be sufficient for your purpose ??
output {
    elasticsearch {
        embedded => false
        host => localhost
        port => 9200
        protocol => http
        cluster => 'elasticsearch'
        index => "syslog-%{+YYYY.MM.dd}"
    }
}