text:
Q: Sending MailChimp email with Rails ((I've found similar questions to mine, but they are specific to a 3rd party mandrill gem, or Heroku. I'm not using any of those, just the mandrill-api itself.))
I'm trying to use email confirmation (we use Devise) for account creation. I've set up confirmable, everything with that works well. Initially, I used the basic Devise emails for everything, and it was fine and sending - but then I tried to switch it to our MailChimp/Mandrill account, and emails won't send. I've tried everything I can think of, and I'm stuck.
Note that it seems to communicate with Mandrill - when I delete the confirmation-instructions template from MailChimp, or don't send it over to Mandrill, I get a template not found error.  But when I create the template, it never actually sends.
The only thing in the logs is:
NotificationMailer#confirmation_instructions: processed outbound mail in 5676.4ms

The mailer:
class NotificationMailer < ActionMailer::Base
    require 'mandrill'
    default from: "XXXXXXXXX <XXXXXX@XXXXXXXXXXXXX.com>"

    def mandrill_client
        @mandrill_client ||= Mandrill::API.new MANDRILL_API_KEY
    end

    def confirmation_instructions(record, token, opts={})
        template_name = "confirmation-instructions"
        template_content = []
        message = {
            to: [{email: record.email}],
            subject: "Confirmation Instructions",
            var_user_email: record.email,
            merge_vars: [
            {rcpt: record.email,
                vars: [
                    {name: "USER_EMAIL", content: record.email},
                    {name: "CONFIRMATION_LINK", content: user_confirmation_url(confirmation_token: token)}
                ]
            }]
        }
        mandrill_client.messages.send_template template_name, template_content, message
    end

end

Development.rb file relative parts:
config.action_mailer.raise_delivery_errors = true
config.action_mailer.perform_deliveries = true

config.action_mailer.delivery_method = :smtp
config.action_mailer.default_url_options = { host: '192.168.33.111' }

config.action_mailer.smtp_settings = {
  address: "smtp.mandrillapp.com",
  port: 587,
  enable_starttls_auto: true,
  user_name: "XXXXXXXXXXXXXXXXX",
  password: "XXXXXXXXXXXXXXXXXX",
  authentication: "login",
}

I also tested it from the console, and it gave no errors there either. There seem to be no errors at all, but the email never sends. Any ideas?

A: So after much pain, I'm still not entirely sure what was wrong with the mailer format originally, but I changed it a little basing it on other websites approaches, to the following, and it worked. I changed nothing else.
class NotificationMailer < ActionMailer::Base
  require 'mandrill'

  default from: "XXXXX <XXXXX@XXXXX>"

  def mandrill_client
    @mandrill_client ||= Mandrill::API.new XXXXXXXXXXXX
  end

  def confirmation_instructions(record, token, opts={})
    template_name = "confirmation-instructions"
    template_content = []
    message = {
      :subject=> "Confirmation Instructions",
      :from_name=> "XXXXXXXXX",
      :text=> "Confirm your email",
      :to=>[
        {
          :email=> record.email,
          :name=> record.first_name + " " + record.last_name
        }
      ],
      :from_email=>"no-reply@XXXXXXXXXXXXX.XXX",
      :merge_vars=>[
        {
          rcpt: record.email,
          vars:
          [
            {name: "USER_EMAIL", content: record.email},
            {name: "USER_NAME", content: record.first_name + " " + record.last_name},
            {name: "CONFIRMATION_LINK", content: user_confirmation_url(confirmation_token: token)}
          ]
        }
      ]
    }
    mandrill_client.messages.send_template template_name, template_content, message
  end
end

Note that the
:text=> "Confirm your email"

field isn't used, I'm still tweaking it - just wanted to post this so others may be spared the pain I was from MailChimp/Mandrill's rediculously tedious formatting and terrible documentation.
And just for info, the only gem i used was the mandrill-api gem:
gem 'mandrill-api', '~> 1.0.51', require: "mandrill"


text:
Q: Send int value to server from iOS device I have to POST int value to server. For what concern String value it's well explained in this article, but with "int" i don't know how to set "setHTTPBody"

A: HTTPBody accepts NSData. You have to convert the int to a NSString or put the integer inside a NSDictionary and convert the NSString/NSDictionary to NSData and set to HTTPBody. This all depends on the web service/URL you are trying to call. So first try to understand in which format your web service accepts the data.

redpajama_set_name: RedPajamaStackExchange


text:
Q: get duplicates from a table using linq to entities In my database i got a column named hashcode. this column stores the hashcodes of pictures. I want to run a query that searches for duplicate hashcodes using linq to entities.
I got stuck with the 'where clause'. How do i compare hashcodes?
var ans = this.pe.TPicture.Where(p => this.pe.TPicture.Count(x => x.Equals(p)) > 1);

A: You can use count also for learning linq query see http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx
in your case
entities.Where(p => entities.Count(x => x.Equals(p)) > 1);

the order of above query is O(n^2)
but you can do this simply with bellow code in O(n log(n))
            entities.Sort();

            List<x> repeatedItems = new List<x>();

            if (entities.Count > 1)
            {
                if (entities[0].Equals(entities[1]))
                {
                    repeatedItems.Add(entities[0]);
                }
            }

            for (int i=0;i<entities.Count;i++)
            {
                if (i < entities.Count -1)
                {
                    if (entities[i].Equals(entities[i+1]))
                    {
                        repeatedItems.Add(entities[i+1]);
                    }
            }


text:
Q: How can I put my Borland C++ Builder 6 project into Visual Studio Team Services We are putting our existing Embarcadero Borland C++ Builder 6 projects into the new free Microsoft source control called "Visual Studio Team Services" (aka online version of TFS or Team Foundation Server formerly called Team Foundation Service).
http://www.visualstudio.com/products/what-is-visual-studio-online-vs
How can I put my code from my BCB 6 project to use it with this system.
Of course I'd prefer to have IDE integration, but as long as I have some kind of GUI I'm fine with doing source code tasks outside of the BCB IDE.
Are there any BCB files that are binary and therefore might be an issue with comparing changes?
Any ideas are greatly appreciated.

A: C++Builder does not have any native TFS support (not even in the latest version), let alone any VSOnline support.  At least with TFS, there are third-party plugins to let C++Builder access TFS:
SourceConneXion
TFS.us
For TFS, you can also use the standard TFS client GUI.  For Visual Studio Team Services, who knows.
Several files are binary, including RES and TDS, but you usually don't need to do diffs on those.  You should, however, make sure to set your DFM files to Text mode, as they are set to Binary by default.  DFMs are always binary in the final executable's resources, but the DFM source files can be either text or binary, and you will likely do diffs on DFMs from time to time.

A: you could use the visual studio shell (aka 'team explorer everywhere') to do checkins etc
and you could also use the power tools (tfpt) to give you explorer integration.


text:
Q: Powershell output formatting splitting the result The Test-ServiceHealth in powershell for Exchange 2013 provides the following output:
Role                    : Mailbox Server Role
RequiredServicesRunning : True
ServicesRunning         : {IISAdmin, MSExchangeADTopology, MSExchangeDelivery, MSExchangeIS...}
ServicesNotRunning      : {}

Role                    : Client Access Server Role
RequiredServicesRunning : True
ServicesRunning         : {IISAdmin, MSExchangeADTopology, MSExchangeIMAP4, MSExchangeMailboxReplication...}
ServicesNotRunning      : {}

Using the format-table option how can i separate the Services Running removing the braces & commas and display them one below the other?

A: You could join the array values to a multiline-string, and then use the -Wrap switch in Format-Table, like this:
[pscustomobject]@{
Role = "Mailbox Server Role"
RequiredServicesRunning = $True
ServicesRunning = "IISAdmin", "MSExchangeADTopology", "MSExchangeDelivery"
ServicesNotRunning = ""
},[pscustomobject]@{
Role = "Client Access Server Role"
RequiredServicesRunning = $true
ServicesRunning= "IISAdmin", "MSExchangeADTopology", "MSExchangeIMAP4"
ServicesNotRunning = ""
} | Format-Table -AutoSize -Wrap Role, RequiredServicesRunning, @{n="ServicesRunning";e={$_.ServicesRunning -join "`n"}}, @{n="ServicesNotRunning";e={$_.ServicesNotRunning -join "`n"}}

Role                      RequiredServicesRunning ServicesRunning                                  ServicesNotRunning
----                      ----------------------- ---------------                                  ------------------
Mailbox Server Role                          True IISAdmin
                                                  MSExchangeADTopology
                                                  MSExchangeDelivery
Client Access Server Role                    True IISAdmin
                                                  MSExchangeADTopology
                                                  MSExchangeIMAP4


text:
Q: JavaFX FXML 2.2 - Deploy Application with bitmaps I have searched a lot and tried several ways to do this, but am stumped.  I am writing a desktop app (though I suppose it could also run in a browser) that allows an Android programmer to edit all of their dimens.xml files at once.  I have created my own images to use in ImageViews as buttons.  I am using different methods to access these images:

*

*Some are referenced in the FXML file, like <Image url="@Icons/ic_launcher.png" />.  The path is "src/Icons/".  The path of the FXML file is "src/application/xxx,fxml".

*Some are referenced in the css file, like "-fx-image:url("QuestionMark.png");".  The css file and png file are in the same directory "src/MessageBox/"

*Some are changed dynamically at runtime:
ImageView mButtonIcon = new ImageView("/insert_item_above.png");

The path of the image: src/
The path of the class: src/ContextMenuButton/

The above only works in Netbeans 7.4.  None work when I run the app in Eclipse.
If I go to the dist/ directory and run it from any of the 3 methods, I see my images.
If I move the dist/ folder somewhere else, the only way I can get it to work is if I copy the src/ folder to the same directory and delete everything but the png and css files.  So, I end up with:
+ F:/AndroidDimens
    + dist
        xxx.jar
    + src
        insert_item_above.png
        + Icons
             ic_launcher.png
        + MessageBox
             QuestionMark.png

So, the jar file has modified all of the paths to be relative to the src/ folder.  My goal is to make the paths relative to where the jar file is.  I tried to place the images where I would not need project related paths.  But it must have made the paths something like "../src/MessageBox/QuestionMark.png" in the jar (relative to the project's dist/ folder).
Is there any way to fix this?  Ideally, I would like all images to be in one directory.  Then I could zip that directory, and someone else could just unzip it and run the app.
Thanks!
EDIT
Thanks to @jewelsea (in chat), I found that the problem was due to having an older version of JDK 7u13 installed with the latest one needed for JavaFX 2.2.  Deleting the old version, and updating global variables that referenced it, solved the problem.  No changes were needed to the default project settings.

A: Packaging Advice
Package all of your application's runtime class files and resources (fxml, css, png, etc) in the application jar file using the JavaFX packaging tools.
Using the JavaFX packaging tools is what NetBeans 7.4 does automatically during it's build process for JavaFX application projects.
Eclipse and other build environments will not use the JavaFX packaging tools automatically.  I believe, if you use Eclipse with the recommended e(fx)clipse extension toolset for JavaFX development, then that toolset will, through its UI, provide you with the ability to use the JavaFX packaging tools to package your application.
There are 3rd party packaging alternatives for JavaFX such as the JavaFX Maven Plugin or the JavaFX Gradle Plugin which will also package your application correctly.
Whatever packaging tool you choose, test the packaging process by unzipping the files from your resultant jar and checking that all of the resource files (fxml, css, png, properties etc) are where you expect them to be in the jar's internal directory structure.  This unzipping process is just a developer sanity check, you don't need to ask your end users do perform such an extraction.
Your end users can run your application as either an installed native application (JavaFX term self-contained application) or as a click to execute jar file (JavaFX term standalone program) and all of your application's resources will automatically be available from the packaged application, with no additional work required by the user.
Resource Access Advice
I advise not referring to a src path in your code (as you won't have a src path inside your distribution jar), css or fxml files, but instead refer to those paths relative to the root of the distribution jar or your JavaFX application class.  For example, to load a scene style sheet in a JavaFX Application subclass, use a form as recommended by the JavaFX deployment guide - 3.3.4 Loading Resources:
scene.getStylesheets().
    add(this.getClass().getResource("my.css").toExternalForm());


text:
Q: How to store mp3 files in harddisk and maintain performance I'm working on a project which will have millions of small mp3 files that I was thinking to save in harddisk.
I have the following questions:

*

*What is the structure I should use to save the files? one folder or
many folders.

*what is the best way to Searching ?

A: The best approach might be to store the information you are going to search on in a database and use that to search on. You can then use something like Lucene or Solr to do the searching.
The database would store a reference to the file on disk and just use that directly when the search pops out it's results. This means you can organise the files on disk in any order you like.
However, without a lot more information this is effectively just a guess.

A: I had to do a similar thing on a project that involved storing a large number of images. Using some meta data for the file, I generated an MD5 hash which I then used as the file name. The first character of the filename would be the grandparent directory for the file, and the second character the parent. Resulting in a file structure like this:

This has the advantage of keeping the files evenly distributed over the directories. And if you pick the metadata used to generate the hash well, then it also has the advantage of being able to find a file without using a database to store references to it.
I've found this method to work pretty well with 100k or so files, but without more information of what exactly you're trying to do it's hard to know if it's appropriate for your problem...


text:
Q: Wordpress redirecting to localhost instead of virtual host when being proxied by Webpack Dev Server I am trying to do a relatively simple set up with:

*

*An Apache server with a virtual host for the HTML.

*Webpack and the Webpack Dev Server for asset reloading and generation.

To accomplish this, the Webpack Dev Server proxies the other server to pass through requests that it doesn't know how to handle.
Using a basic python server (which works):

*

*Start the python webserver on http://localhost:5000.

*Run npm start.

*Webpack Dev Server starts and proxies the python server using http://localhost:9090.

*Visit http://localhost:9090 and see HTML result of python server plus Webpack assets.

Using Apache server:

*

*Start the Apache server.

*Run npm start.

*Webpack dev server starts and proxies the Apache server using http://localhost:9090.

*Visit localhost:9090 the browser automatically redirects to http://localhost and displays "It works!".

If I separately visit http://vhost.name in the browser I see the correct HTML. My environment is the default Apache Server version: Apache/2.4.16 (Unix) on Mac OSX El Capitan.
package.json
"scripts": {
  "test": "node server.js",
  "start": "npm run start-dev-server",
  "start-dev-server": "webpack-dev-server 'webpack-dev-server/client?/' --host 0.0.0.0 --port 9090 --progress --colors",
  "build": "webpack"
},

webpack.config.js
/*global require module __dirname*/
var webpack = require('webpack');

module.exports = {
    entry: {
        app: [
            'webpack-dev-server/client?http://localhost:9090',
            'webpack/hot/only-dev-server',
            './src/app.js'
        ]
    },
    output: {
        path: __dirname + '/dist',
        filename: '[name]_bundle.js',
        publicPath: 'http://localhost:9090/dist'
    },
    devServer: {
        historyApiFallback: true,
        proxy: {
            // Python server: works as expected at localhost:9090
            // '*': 'http://localhost:5000'

            // Apache virtual host: redirects to localhost instead of
            // serving localhost:9090
            '*': 'http://vhost.name'
        }
    },
    plugins: [
        new webpack.HotModuleReplacementPlugin()
    ]
};

httpd-vhosts.conf
<VirtualHost vhost.name:80>
    DocumentRoot "/Path/To/vhost.name"
    ServerName vhost.name
        <Directory "/Path/To/vhost.name">
            Options FollowSymLinks Indexes MultiViews
            AllowOverride All
            # OSX 10.10 / Apache 2.4
            Require all granted
        </Directory>
</VirtualHost>

hosts
127.0.0.1   localhost

127.0.0.1   vhost.name

A: Wordpress uses canonical URLs to help normalize URLs for content from different sources:

[Y]ou can't control who links to you, and third parties can make errors when typing or copy-pasting your URLs. This canonical URL degeneration has a way of propogating. That is, Site A links to your site using a non-canonical URL. Then Site B see's Site A's link, and copy-pastes it into their blog. If you allow a non-canonical URL to stay in the address bar, people will use it. That usage is detrimental to your search engine ranking, and damages the web of links that makes up the Web. By redirecting to the canonical URL, we can help stop these errors from propagating, and at least generate 301 redirects for the errors that people may make when linking to your blog.

This rewriting is what strips the Webpack-dev-server port number when attempting to proxy. The solution is to add in your theme/functions.php:
remove_filter('template_redirect', 'redirect_canonical');

We obviously don't want this running on the live site, so add a variable to the wp_config.php to set depending on environment:
wp-config.php
// Toggle to disable canonical URLs to allow port numbers.
// Required for Webpack-dev-server proxying.
define('DISABLE_CANONICAL', 'Y', true);

yourtheme/functions.php
// Hack for Webpack dev server
if (DISABLE_CANONICAL == 'Y') {
    remove_filter('template_redirect', 'redirect_canonical');
}

I have experienced issues with the browser "caching" the previous URL redirect, so when you make a change it may not appear immediately. Try opening the URL in incognito mode, using a different browser, or restarting the Webpack and Apache servers.


text:
Q: uncrustify google style c++ config I am using uncrustify and atom-beautify in atom.io to format my C++ code according to google styling guide. I am using CPPlint to verify whether the code is formatted correctly. I am using the config file from https://gist.githubusercontent.com/philectron/1a1e1ccb06d5643cd61d85fc5ecaf429/raw/8813567b8f7dd49003228e19c3d10719b49995a1/uncrustify-preferences.cfg. But after beautifying, cpplint is reporting the following problems.

*

*"At least two spaces is best between code and comments [whitespace/comments]" is not enforced and I am getting this error in multiple places. The answer for this question at Uncrustify - How do I align trailing comments by two-space gap? is not working.

*"protected: should be indented +1 space inside." I am getting the same error for private and public as well.

If this is not the right way, how can I beautify and lint inside atom.io.

A: Well maybe I wasn't clear enough in the last answer or you haven't read it carefully enough. Here is another try.
Uncrustify has spacing and aligning functions. Aligning functions are applied after the spacing functions (at least in the case of the trailing comments).
If you have align_right_cmt_span set to greater than zero the aligning functions will also be applied on trailing comments.
The option align_right_cmt_gap is than enabled, even if it is set to zero, which it is by default even if you do not specify it. It seems that it is now only active if it is not zero. Additionally to that problem you have align_right_cmt_at_col set to 1.
I am not using CPPlint, atom-beautify or the google styling guide. So if you want help, upload some code examples: input code, output code, expected code.


text:
Q: Cryogenics gone wrong - humorous novel A company has been accepting payment from multitudes of people to be cryogenically preserved in 'cans'. But it turns out that it's all a scam and they're dead.
The cans are being shot out into space where, rather than getting to a new planet, they're exploding and oozing out nasty goo.
This is definitely not the main part of the novel; it might just be a scene. The book was humorous, making fun of corrupt bureaucracy - maybe Douglas Adams; but I can't seem to locate it.
any ideas?
Trying to think of more details... the perspective of the scene is from, or involves, an unmotivated, low-level employee at this facility.
There are definitely stinky, nasty piles of these rotting "cans."
Also, there's definitely an overpopulation problem going on.
Probably from the 1980s.

A: Could it be The Marching Morons by Cyril M. Kornbluth? This doesn't include cryogenics, but instead it has the smart elite duping the stupid masses into boarding rockets "to Venus" (but instead they explode in space, killing everyone).


text:
Q: Block access to files in a directory but allow index.html I'm hosting a website on /test/ but files can be accessed by going to the url if user knows filename. Ex:
domain.com/test/readmesample.txt

I have it setup like above but now when i go to domain.com/test the index.html file wont load and I get a 403 forbidden.
How can i set it up so when going to /test it allows the html file to load while still blocking files inside that directory? This includes files, folders and .files other than index.html.
location ~ /test {
             deny all;
}

Here is my config file
server {
listen 80;
listen 443 ssl default_server;

root /config/www;
index index.html index.htm index.php;

server_name www.domain.com;

ssl_certificate /config/keys/letsencrypt/fullchain.pem;
ssl_certificate_key /config/keys/letsencrypt/privkey.pem;
ssl_dhparam /config/nginx/dhparams.pem;
ssl_ciphers 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
ssl_prefer_server_ciphers on;

client_max_body_size 0;

location / {
    try_files $uri $uri/ /index.html /index.php?$args =404;

}

location ~ /new {
    deny all;

}

location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    # With php5-cgi alone:
    fastcgi_pass 127.0.0.1:9000;
    # With php5-fpm:
    #fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_index index.php;
    include /etc/nginx/fastcgi_params;
}

Thank you in advance

A: You can explicitly break out /test/index.html with:
location = /test/index.html {
}
location ^~ /test {
    deny all;
}

The exact match location has highest precedence, and the ^~ modifier places the precedence of the prefix location above regular expression locations at the same level.
See this document for more.

A: I think I figured it out not sure if it's the proper way but it works. Feel free to correct me
location /test {
location ~ \.(txt|gif|jpg|png)$ {
      deny all;
      }
      }

Using that blocks access to all those extensions in /test and inside any sub directory.

A: I prefer return 444; than deny all;
Deny all show server name
Nginx configuration disallow or allow files access

A: Richard Smith's answer is correct.  Here is another correct answer:
location ^~ /test {
    try_files /test/index.html =404
}


text:
Q: Access dynamicalley generated css id from the angular
html (dynamically generated one using jquery)
<div id="undefined-sticky-wrapper" class="sticky-wrapper" style="height: 25px;">

Above html has been generated dynamically using jquery.So could you tell me how can I access above id using angular.B'cos I need to change the height of the above css to 0px when it's loading within the iframe(I know how to handle the iframe part).

A: You can target it with any js after the page has loaded. You can test this with the js console.
Answer :
var obj = angular.element('#undefined-sticky-wrapper');
obj.css('cssText', 'height:0px !important;');


text:
Q: Bootstrap4 on dropdown show change another parent level div property (CSS) Check this fiddle
I have a dropdown and when the dropdown is toggled, I want to change  another div's background-color (div's with classes .main-content and .reqdiv is this case).
I have tried these selectors ~, >, + and I know these won't work in my case. Can anyone please suggest me how to solve this without using JS/JQuery.

.main-content {
  height: 200px;
  width: 100%;
  background: green;
}

.dropdown-menu {
  top: 35px!important;
}

.nav-btn.show~.main-content {
  background: blue;
}

.nav-btn.show>.main-content {
  background: blue;
}

.nav-btn.show+.main-content {
  background: blue;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet" />

    <button class="btn dropdown-toggle " type="button" data-toggle="dropdown">Language

   </button>

HTML

CSS

JavaScript

  //text

A: you want dropdown select then change background color in div
<select id="evt_color">
<option value="#3366CC">Blue</option>
<option value="#E070D6">Fuchsia</option>
<option value="#808080">Gray</option>
<option value="#4bb64f">Green</option>
<option value="#ed9d2b">Orange</option>
<option value="#FF9CB3">Pink</option>
<option value="#EA4A4A">Red</option>
</select>

Colour sample

 **Script**
$("#evt_color").change(function() {
    $("#someDiv").css("background-color", $(this).val());
}).change();

Example

A: U can simply use specified css classes for changing a background.
toggleClass can help on click.

$( "#button" ).on( "click", function() {
    $( ".main-content").toggleClass('blue');
});
.main-content{
    height:200px;
    width:100%;
    background:green;
}
.blue{background: blue}
.dropdown-menu{top:35px!important;}
.nav-btn.show ~ .main-content{background:blue;}
.nav-btn.show > .main-content{background:blue;}
.nav-btn.show + .main-content{background:blue;}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>

   <button class="btn dropdown-toggle " id="button" type="button" data-toggle="dropdown">Language

   </button>

HTML

CSS

JavaScript

   //text

A: If u want to use only css u have to change yours html.
So the background-color changing elements will be siblings to .nav-btn element. e.g:

.main-content{
    height:200px;
    width:100%;
    background:green;
}
.dropdown-menu{top:35px!important;}
.nav-btn.show ~ .main-content{background:blue;}
.nav-btn.show > .main-content{background:blue;}
.nav-btn.show + .main-content{background:blue;}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>

   <button class="btn dropdown-toggle " id="button" type="button" data-toggle="dropdown">Language

   </button>

HTML

CSS

JavaScript

   //text


text:
Q: MySQL 8.0.15 Creating an array We have just upgraded our server and we now have MySQL 8.0.15, previously we had MySQL 5.5.58
We had a procedure to create an array, but on the new server it dont seem to happen. I am just wondering if the procedure is different in a newer version of MySQL?
Thanks
Paul.
$save_path = "C:\\export\\";
if($values['AutoExport']){
    $data =
    array(
    "JobNo"=>$values['JobNo'],
    "ContactEmail"=>$values['ContactEmail'];

    $domtree = new DOMDocument('1.0', 'UTF-8');
    $domtree->xmlStandalone = true;
    $xmlRoot = $domtree->createElement("table");
    $xmlRoot = $domtree->appendChild($xmlRoot);
    $xmlRow = $xmlRoot->appendChild($domtree->createElement("row"));
    foreach ( $data as $data_key => $child_data )
        $xmlRow->appendChild($domtree->createElement(htmlspecialchars($data_key),htmlspecialchars($child_data)));
    $domtree->formatOutput = true;
    $domtree->save($save_path."Job_".$values["JobNo"].".xml");
}


text:
Q: Thumbnail from liveleak Is there any way how I can get thumbnail from liveleak videos using PHP?
It's easy to get thumbnail from youtube, vimeo, dailymotion, metacafe but I didn't find any information about liveleak.
Thank you.

A: If you can scrape the video page then you can look for og:image tag in meta tags.
<meta property="og:image" content="..."/>

Content property will have url for thumbnail.
For example, for:
http://www.liveleak.com/view?i=a5c_1485250453
meta tag will be:
<meta property="og:image" content="https://cdn.liveleak.com/80281E/ll_a_u/thumbs/2017/Jan/24/b124049d23c2_sf_3.jpg"/>


text:
Q: Sending google-analytics pageview is not logged - as active user When I send the request from fiddler or from .net code - I see the counter in Analytics active users
But when it is sent from a cloud machine - I get 200 OK but the counter does not change
Possible problems:

*

*response is from cache

*Results are filtered by region (I couldn't find any active filter)

*Needed header

Request format: https://www.google-analytics.com/collect?t=pageview&v=1&dp={myDp}&tid={myTid}&cid={myCid}
The request was built based on this: https://developers.google.com/analytics/devguides/collection/protocol/v1/reference
Any more ideas?
Dekel

A: This can happen if you are looking at a view where Bot Filtering is enabled:

It happens because your call has few parameters (for example it doesn't have the parameter of screen resolution, host name, etc...) therefore it is interpreted as a bot.
Try to see the data in a View where there is no filter (or disable this option) or to enrich the call with more parameters.


text:
Q: g++ Linker errors after upgrading to gcc-4.8 on Debian, libc6 I have just dist-upgraded a Debian Weezy machine to run gcc-4.8 from gcc-4.7.  Previously the build environment was sane and was compiling normally.  Now it gives the following linker errors, with any program (even a trivial hello world):

/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 0 has invalid symbol index 11
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 1 has invalid symbol index 12
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 2 has invalid symbol index 2
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 3 has invalid symbol index 2
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 4 has invalid symbol index 11
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 5 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 6 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 7 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 8 has invalid symbol index 12
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 9 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 10 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 11 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 12 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 13 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 14 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 15 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 16 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 17 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 18 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 19 has invalid symbol index 20
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_line): relocation 0 has invalid symbol index 2
/usr/lib/gcc/x86_64-linux-gnu/4.8/../../../x86_64-linux-gnu/crt1.o: In function `_start':
(.text+0x12): undefined reference to `__libc_csu_fini'
/usr/lib/gcc/x86_64-linux-gnu/4.8/../../../x86_64-linux-gnu/crt1.o: In function `_start':
(.text+0x19): undefined reference to `__libc_csu_init'
collect2: error: ld returned 1 exit status

I'm sure this is something simple connected with libc6, but I can't see what?  I'm quite surprised to be seeing this error since I'd have assumed dpkg would have taken care of any dependencies, so I'm not sure if it's something wrong with this specific system or an issue with the debian package (which seems unlikely, since nobody else seems to have this problem!)
Any ideas? :)

A: Ah! As soon as I finished typing this, as a last ditch, I tried:
apt-get install libc6-dev --reinstall

(although I was convinced I'd already done it previously), and lo and behold, the issue went away!


text:
Q: Python decode prediction pretrained model error: OpenCV(4.5.4) /tmp/pip-req-build-jpmv6t9_/opencv/modules/highgui/src/window.cpp:1274 I used a pre-trained model vgg19 to train it on my own data and make prediction on my 9 classes by using decode_predictions.
I understood that decode_predictions works only for ImageNet (no. of classes = 1000). So I rewrite my own decode_prediction function.
When I want to predict on my folder of image, I am facing this error:
---------------------------------------------------------------------------
error                                     Traceback (most recent call last)
/tmp/ipykernel_17/3874189441.py in <module>
     53     cv2.putText(original, "Label: {}, {:.2f}%".format(label, prob * 100), (10, 30),
     54                 cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)
---> 55     cv2.imshow('frame',original)
     56     cv2.waitKey(0)

error: OpenCV(4.5.4) /tmp/pip-req-build-jpmv6t9_/opencv/modules/highgui/src/window.cpp:1274: error: (-2:Unspecified error) The function is not implemented. Rebuild the library with Windows, GTK+ 2.x or Cocoa support. If you are on Ubuntu or Debian, install libgtk2.0-dev and pkg-config, then re-run cmake or configure script in function 'cvShowImage'

Here my decode_prediction function:
def decode_prediction(preds, top=9, class_list_path='../input/new_classes.json'):
  if len(preds.shape) != 2 or preds.shape[1] != 9: # your classes number
    raise ValueError('`decode_predictions` expects '
                     'a batch of predictions '
                     '(i.e. a 2D array of shape (samples, 1000)). '
                     'Found array with shape: ' + str(preds.shape))
  index_list = json.load(open(class_list_path))
  results = []
  for pred in preds:
    top_indices = pred.argsort()[-top:][::-1]
    result = [tuple(index_list[str(i)]) + (pred[i],) for i in top_indices]
    result.sort(key=lambda x: x[2], reverse=True)
    results.append(result)
  return results

And here my code to predict on my image folder where I get the error:
import os
import json
import cv2
import argparse
import numpy as np
from keras.applications.vgg19 import VGG19
from keras.preprocessing import image as image_utils
from keras.applications.imagenet_utils import preprocess_input, decode_predictions

# Construct argument parser and parse the arguments
argument_parser = argparse.ArgumentParser()

# First two arguments specifies our only argument "image" with both short-/longhand versions where either
# can be used
# This is a required argument, noted by required=True, the help gives additional info in the terminal
# if needed
argument_parser.add_argument("-i", "--image", required=True, help="path to the input image")

# Set path to files
img_path = "../input/img_val"
files = os.listdir(img_path)
print("[INFO] loading and processing images...")

for filename in files:

    # Passing the entire path of the image file
    file= os.path.join(img_path, filename)

    # Load original via OpenCV, so we can draw on it and display it on our screen
    original = cv2.imread(file)

    image = image_utils.load_img(file, target_size=(224, 224))
    image = image_utils.img_to_array(image)

    image = np.expand_dims(image, axis=0)
    image = preprocess_input(image)

    print("[INFO] loading network...")

    m=load_model('/kaggle/working/model_hemato.h5')
    print("[INFO] classifying image...")
    predictions = m.predict(image)   # Classify the image (NumPy array with 1000 entries)
    P = decode_prediction(predictions)  # Get the ImageNet Unique ID of the label, along with human-readable label
    print(P)

    # Loop over the predictions and display the rank-5 (5 epochs) predictions + probabilities to our terminal
    for (i, (imagenetID, label, prob)) in enumerate(P[0]):
        print("{}. {}: {:.2f}%".format(i + 1, label, prob * 100))

    original = cv2.imread(file)
    (imagenetID, label, prob) = P[0][0]
    cv2.putText(original, "Label: {}, {:.2f}%".format(label, prob * 100), (10, 30),
                cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)
    cv2.imshow('frame',original)
    cv2.waitKey(0)


text:
Q: How can I add a custom python indicator to the unity-greeter login screen? I've installed a custom indicator called PRIME Indicator and it shows up in the top panel (next to date time etc) after I login.
I would like to show the indicator before login on the unity-greeter lightdm login screen, but I can't figure out how to do it.
I have attempted to use the information provided in the following answer:
Is that possible to add icons to the login screen top-panel?
but PRIME Indicator is not installed in either /usr/lib/indicators3/7/ or /usr/share/unity/indicators/, so I don't know what to do.
I can create an override file like this:
$ /usr/share/glib-2.0/schemas/myoverride.gschema.override
[com.canonical.unity-greeter]
indicators=['com.canonical.indicator.keyboard', 'com.canonical.indicator.datetime', 'com.canonical.indicator.power', 'com.canonical.indicator.sound', 'application', 'prime']

NOTE: I added a prime entry.
Also, I created a file here:
$ /usr/share/unity/indicators/prime
[Indicator Service]
Name=indicator-prime
ObjectPath=/com/canonical/indicator/prime
Position=50

[desktop]
ObjectPath=/com/canonical/indicator/prime/desktop

[phone]
ObjectPath=/com/canonical/indicator/prime/phone

[desktop_greeter]
ObjectPath=/com/canonical/indicator/prime/desktop

However, this doesn't work because I don't know what the correct ObjectPath should be.
Q1: Is it possible to make PRIME-indicator show before login?
Q2: How do I do it?


text:
Q: Find the matrix that corresponds to the composite transformation of a rotation followed by a translation. Given an object's vertices, find the matrix that corresponds to the composite transformation of a rotation of $90$ degrees, followed by a translation by adding $(0,3)$ to each point.
I want to call the rotation matrix $A_1$ and the translation matrix $A_2$. Thus my composite transformation will look like $A_2A_1$.
The object's vertices are given as the following:
\begin{align}
A &= (-1,0)\\
B &= (1,0)\\
C &= (0,1)
\end{align}
Here is what I have done so far:
$$\text{For the rotation matrix $A_1$:}\pmatrix{x' \\ y'} = \pmatrix{\cos\theta & -\sin\theta \\ \sin\theta & \cos\theta} \pmatrix{x \\ y}$$
$$\implies \pmatrix{x' \\ y'} = \pmatrix{\cos90 & -\sin90 \\ \sin90 & \cos90} \pmatrix{x \\ y}$$
$$\implies \pmatrix{x' \\ y'} = \pmatrix{0 & -1 \\ 1 & 0} \pmatrix{x \\ y}$$
This would mean that my $A_1 = \pmatrix{0 & -1 \\ 1 & 0}$. However, I think I'm supposed to use homogeneous coordinates for this problem. In other words, I should actually get something like this:
$$\pmatrix{x \\ y \\ 1} \rightarrow A_1 \pmatrix{x \\ y \\ 1} \rightarrow A_2 A_1 \pmatrix{x \\ y \\ 1}$$
This makes sense because I'll need $A_1$ and $A_2$ to be conformable to find my final answer $A = A_2 A_1$.

A: Translation cannot be expressed a matrix acting on a vector. You could contrive the following "translation matrix", that translates by $(0,3)$:
$$
\left(
\begin{array}{ccc}
1 & 0 \\
0 & \frac{y+3}{y}
\end{array}
\right)
\left(\begin{array}{ccc}
x \\ y
\end{array}
\right)
= \left(\begin{array}{ccc}
x \\ y + 3
\end{array}
\right)
$$
But is dependent on the coordinates $(x,y)$ and is as such a nonlinear operator. To see that this is true, try composing the matrix twice and note that it doesn't result in a matrix that translates by $(0,6)$. Translation is a fundamentally different operation from rotation. The transformation you are looking for is a linear operation of the form:
$$
\boldsymbol{x}' = \boldsymbol{x}_0 + A\boldsymbol{x}
$$
where $\boldsymbol{x} = (x,y)$ and $\boldsymbol{x}_0 = (0,3)$ and $A$ is the rotation matrix you derived.


text:
Q: VBA - Changing Copying from a Directory to copying from a server Apreciate any help and excuse me if my terminology is incorrect.
This is a basic macro that opens a file from loacation A and copies the specified content,
It then pastes the content into the current Workbooks, specified worksheet and cell, that has run this macro.
My question is around the "FileName.csv". This is currently scheduled to be dumped in Location A "V:\Dir1\SubDir1\" periodically.
How would I go about Retrieving this file, "FileName.csv", if I started scheduling it to be dumped in loacation B "http://172.1.2.3/Dir1/SubDir1/FileName.csv" a server of some sort?
I would obviusly just like to edit the existing macro to allow for this change.
Sub CopyCSVFile1()

'workbook to copy from
WBToCopy = "FileName.csv"
'workbook path to copy from
WBpthToCopy = "V:\Dir1\SubDir1\"
'workbook to paste to
'WBToPasteTo = "ResourcesV1.xlsm" not needed here as pasting to active workbook
'workbook sheet to paste to
WBSheetToPasteTo = "Raw1"
''workbook path to paste to
'WBPthToPasteTo = "N:\Engineering\Network Performance\Capacity\SG_GG\SGSN Resources\" ' not needed here as pasting to active workbook
'range to select to copy
RangeToSelectToCopy = "A3:B149"
'cell to paste to
CellToPasteTo = "A3" ' need to work this out before assignment

Dim Merged As Object
Dim Data As Object
Set Data = ActiveWorkbook

'debug.print "ActiveWorkbook.Path = " & ActiveWorkbook.Path
Debug.Print "ActiveWorkbook.Path = " & Data.Path

Sheets(WBSheetToPasteTo).Select ' this is the sheet where you want to paste to
Workbooks.Open Filename:=WBpthToCopy & WBToCopy, local:=True

Set Merged = ActiveWorkbook ' this assigns the current active workbook to merged whish is the one I want to copy from

Range(RangeToSelectToCopy).Select ' this value just for this example should be A4 normally
Selection.Copy

Data.Activate ' this activates the Data workbook which happens to be the workbook where this macro resides

Range(CellToPasteTo).Select ' select where I want to past my data

ActiveSheet.Paste ' paste the data
Application.DisplayAlerts = False
Merged.Close 'SaveChanges = False

Application.DisplayAlerts = True

End Sub

A: This worked for me:
Sub CopyCSVFile1()

    Dim wb As WorkBook, WBToCopy As String, WBpthToCopy As String

    'workbook to copy from
    WBToCopy = "test.csv"

    'workbook path to copy from
    WBpthToCopy = "http://127.0.0.1/testpages/"

    'open the source workbook
    Set wb = Workbooks.Open(WBpthToCopy & WBToCopy)

    '...
    'do something with wb...
    '...

    wb.Close False

End Sub


text:
Q: RaphaelJS remove element on click I'd like to remove a shape when I click on it and if the delete radio button is "true". For now I'm only able to delete the whole Raphael paper. Can somebody help me ?
I use RaphaelJS and Jquery.
HTML
<html lang="en" style="height: 100%;">
<head>
    <script src="raphael-min.js" type="text/javascript"></script>
    <script src="jquery-min.js" type="text/javascript"></script>
    <script src="app.js" type="text/javascript"></script>
</head>
<body>
    <input type='radio' id='un' name="action" value="un">draw un</button>
    <input type='radio' id='deux' name="action" value="deux">draw deux</button>
    <input type="radio" id='remove' name="action" value="remove"> remove

  <div id="holder">
  </div>

</body>
</html>

JS
$(document).ready(function() {
      var paper = Raphael('holder', '800', '600');
      var mySet = paper.set();

      var tojsonplease =        [
            {
                category: 'playground',
                type: "rect",
                x: 10,
                y: 10,
                width: 600,
                height: 300,
                fill: "#eee"
            }];
        paper.add(tojsonplease);

        addme = function(cat, myX, myY) {
            switch (cat)
            {
            case '1' :
            specs = {
                category: '1',
                type: 'rect',
                x: myX,
                y: myY,
                width: 20,
                height: 20,
                fill: 'yellow'
            };
            break;
            case '2':
            specs = {
                category: '2',
                type: 'rect',
                x: myX,
                y: myY,
                width: 10,
                height: 20,
                fill: 'red'
            };
            break;
            }
            var newElement = new Array();
                newElement[0] = specs;
            tojsonplease.push(specs);
            paper.add(newElement);
            console.log(tojsonplease);
        };

        $('#holder').click(function () {

            if ($("#remove").is(":checked")) {
                paper.remove();
            };
            if ($("#deux").is(":checked")) {
                SX = event.pageX - $(document).scrollLeft() - $('#holder').offset().left;
                SY = event.pageY - $(document).scrollTop() - $('#holder').offset().top;
                addme('1', SX, SY);
            };
            if ($("#un").is(":checked")) {
                SX = event.pageX - $(document).scrollLeft() - $('#holder').offset().left;
                SY = event.pageY - $(document).scrollTop() - $('#holder').offset().top;
                addme('2', SX, SY);
            };

            });
    });

A: Usually you remove a shape by using element.remove():
var element = paper.rect(100,100,100,100);
element.remove() // this removes the element

Do not do this:
if ($("#remove").is(":checked"))
    paper.remove();

This will remove everything, just remove an element like I showed above.
You should assign ids to your elements, this will help you to use Paper.getById(id) function. You will be able to get the exact element you need to remove.
LOOK AT THE WORKING DEMO
var paper = Raphael("holder",500,500);
var which_one_to_remove = -1;

// use data() to assign ids that correspond to the order
// in which you push() the elements into the array object
var c1 = paper.circle(100, 100, 80).attr({fill:'red'}).data('id', '0');
var c2 = paper.circle(200, 200, 80).attr({fill:'yellow'}).data('id', '1');
var c3 = paper.circle(300, 300, 80).attr({fill:'blue'}).data('id', '2');

var elements = [];
elements.push(c1);
elements.push(c2);
elements.push(c3);

c1.click(function()
{
    which_one_to_remove = this.data('id');
});
c2.click(function()
{
    which_one_to_remove = this.data('id');
});
c3.click(function()
{
    which_one_to_remove = this.data('id');
});

$('#holder').click(function () {
    if ($("#remove").is(":checked"))
    {
        elements[which_one_to_remove].remove();
    };
});


text:
Q: SQL Server - NTEXT columns and string manipulation I have a table with an NTEXT column called comments. I have a second string, let's call it anothercomment (a varchar) that needs placing inside a given comments string after the word UPDATEHERE.
Casting to nvarchar(max) truncates the comments string, so I cannot use the likes of CHARINDEX() (Msg 8152, Level 16, State 10, Line 2
String or binary data would be truncated.). I have used datalength() to check that there are a few thousand columns that are >8000 characters.
An example of what I want to achieve (albeit with much longer strings):

comments - This is a test UPDATEHERE This is the end of the test
anothercomment - . This is inserted.
Resulting string -  This is a test UPDATEHERE. This is inserted.  This is the end of the test

I realize that this is trivial with a normal varchar()/nvarchar(), but ntext is a complete and utter nightmare to work with. I realize it's a deprecated data type, but I did not write the application in question.

A: Converting to nvarchar(max) should work unless you are doing something wrong with your CHARINDEX()
Try this code snippet, it should output what you want.
-- Create the table
CREATE TABLE [dbo].[PhilsTable](
    [comment] [ntext] NULL,
    [anothercomment] [nvarchar](50) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY];

GO

-- insert very long string
INSERT INTO [dbo].[PhilsTable] (comment, anothercomment) VALUES (N'This is a test UPDATEHERE This is the end of the test' + REPLICATE (CAST(N'x' AS nvarchar(max)), 1000000), 'this goes in here');

-- verify data
SELECT DATALENGTH(comment), *  FROM [dbo].[PhilsTable];

-- perform replace
SELECT CAST(REPLACE(CAST(comment AS NVARCHAR(MAX)),'UPDATEHERE','UPDATEHERE' + anothercomment) AS NTEXT) FROM [dbo].[PhilsTable];

DROP TABLE [dbo].[PhilsTable];

Thanks go out to Andriy M for helping out with the REPLICATE statement.

A: Converting to nvarchar(max) and back to ntext does make life simpler from a code point of view, but it does mean converting and rewriting the whole (perhaps very large) value, with all the CPU and logging overhead that implies.
An alternative is to use UPDATETEXT. This is deprecated, just like ntext, but it can reduce the logging overhead significantly. On the downside, it means using text pointers, and it only operates on one row at a time.
The following example code uses a cursor to work around that limitation, and uses PATINDEX instead of CHARINDEX since the former is one of the few functions that work directly with ntext:
Sample data
CREATE TABLE dbo.PhilsTable
(
    comment ntext NULL,
    anothercomment nvarchar(50) NULL
);

INSERT dbo.PhilsTable
    (comment, anothercomment)
VALUES
(
    CONVERT(ntext,
        N'This is a test UPDATEHERE This is the end of the test ' +
            REPLICATE (CONVERT(nvarchar(max), N'x'), 1000000)),
    CONVERT(nvarchar(50), N'. This is inserted.')
),
(
    CONVERT(ntext,
        N'This is a test UPDATEHERE This is the end of the test ' +
            REPLICATE (CONVERT(nvarchar(max), N'x'), 1000000)),
    CONVERT(nvarchar(50), N'. This is inserted.')
),
(
    CONVERT(ntext,
        N'This is a test UPDATEHERE This is the end of the test ' +
            REPLICATE (CONVERT(nvarchar(max), N'x'), 1000000)),
    CONVERT(nvarchar(50), N'. This is inserted.')
);

Cursor declaration
DECLARE c
    CURSOR GLOBAL
    FORWARD_ONLY
    DYNAMIC
    SCROLL_LOCKS
    TYPE_WARNING
FOR
SELECT
    TxtPtr = TEXTPTR(PT.comment),
    Src = PT.anothercomment,
    Offset = PATINDEX(N'%UPDATEHERE%', PT.comment) + LEN(N'UPDATEHERE') - 1
FROM dbo.PhilsTable AS PT
WHERE
    PT.comment LIKE N'%UPDATEHERE%'; -- LIKE works with ntext

OPEN c;

Processing loop
DECLARE
    @Ptr binary(16),
    @Src nvarchar(50),
    @Offset integer;

SET STATISTICS XML OFF; -- No cursor fetch plans

BEGIN TRANSACTION;

    WHILE 1 = 1
    BEGIN
        FETCH c INTO @Ptr, @Src, @Offset;

        IF @@FETCH_STATUS = -2 CONTINUE; -- row missing
        IF @@FETCH_STATUS = -1 BREAK; -- no more rows

        IF 1 = TEXTVALID('dbo.PhilsTable.comment', @Ptr)
        BEGIN
            -- Modify ntext value
            UPDATETEXT dbo.PhilsTable.comment @Ptr @Offset 0 @Src;
        END;
    END;

COMMIT TRANSACTION;

CLOSE c; DEALLOCATE c;


text: Q: Terminal search a file in a non-existent directory on MacOS I changed my Mac profile home directory. Today I needed to use composer in terminal. But the terminal gave this error(Could not open input file: /Users/old_home_directory/composer.phar). The problem only exists in zsh, in bash the composer command is executed. Changing the home directory to the previous version also does not solve the problem.


text:
Q: Get a random point (x,y) that is on a portion of a function's curve? I have a function xy*100*50 = 1000 that plots the following curve:

I would like to be able to get a random pair (x,y), where 0<x<1 and 0.5<y<1. In other words, any pair that will define a point of the curve that is in the red area.

My goal is to be able to generate a random pair that solves the equation xy*100*50 = 1000 with x and y being within some variable borders.
Is it possible at all? I have limited mathematical knowledge so I am not sure if it is even doable.
EDIT: @LuLu already gave a simple solution for that case, but the truth is that I am also looking for something that would work in cases like that one:

Where not all values of x in [2;8] have a matching y between [1;2]. So I can't pick a random x.


text:
Q: How to prevent multiple iframes to slow down loading webpage I have a webpage where a user can click a icon to open a popup.
Since this is in a loop triggered by a db output the can be up 250 icons to open a popup.
The popup is using the iframe tag there can be as many of 250 iframe tags in one page. This is slowing down the webpage. How can I prevent it from slowing down my webpage?

<?php
echo ' ';
?>

JSFiddle


text:
Q: Is the $\alpha$-curve a topological submanifold of $\mathbb{R}^2$ Consider the following subset of $\mathbb{R}^2$ defined by $\mathcal{M}=\{ \ (x,y)\in\mathbb{R}^2\ |\ y^2=x^2(x+1)\ \}$. I'm supposed to decide whether or not $\mathcal{M}$ is a topological submanifold (TS) of $\mathbb{R}^2$. It looks like this:

If it's a TS, then it would have to be 1-dimensional. Here is the definition I am using:
$\mathcal{M}$ is a TS of $\mathbb{R}^2$ if for every point $p \in \mathcal{M}$ there exists an open set $V \subset \mathbb{R}^2$ with $p \in V$, an open set $U\subset \mathbb{R}$ and a homeomorphism $\psi:U \to V$.
I don't think its a manifold. I think that a problem occurs at the origin since the curve crosses over itself there. I believe that a good homeomorphism cannot exist at the origin for this reason. How would I prove this?
I thought about using a proof by contradiction, saying suppose that there does exist a homeomorphism $\psi$ mapping an open ball $V=B_{\epsilon}(0,0)$ to some open interval $U$ of $\mathbb{R}$. Then $\psi(0,0,0)$ would be well-defined, but maybe not $\psi^{-1}(0,0,0)$? I'm not sure.
I am new to differential geometry, can someone give me a hint on how to approach this problem?

A: Let $U$ be a sufficiently small open neighbourhood of the origin in $\mathbb{R}^2$, then $U\cap \mathcal{M}$ is a neighbourhood of $(0, 0)$ in $\mathcal{M}$. It looks something like this
$\hspace{77mm}$
where now I have coloured the axes red to distinguish them from the set $U\cap \mathcal{M}$ (which is still coloured black).
How many connected components does $(U\cap \mathcal{M})\setminus\{(0, 0)\}$ have? If $\mathcal{M}$ were a topological manifold $U\cap \mathcal{M}$ would be homeomorphic to an open interval $I$. How many connected components does $I$ have if a point is removed?


text:
Q: How would nearby charged rods affect two touching, conducting spheres? Disclaimer: This is not a homework question. This came from an online resource that I've been using to tutor a student. After much thought, I found myself going in circles on this one.

*

*Two neutral conducting spheres, A and B, which are initially in
contact, are brought close to a rod (positively charged). Sphere B is
taken away. The investigation is repeated with a negatively charged
rod, same procedure of steps. Which of the following is true?

(It's not clear to me, by the way, if they mean that we bring the rod close, remove sphere B, and then repeat the procedure with sphere B absent. Or just repeat the entire procedure, with sphere B present again.)
A. The rod induces charge separation, so sphere A gains a charge opposite that of the rod.
Removing B, sphere A retains that charge and is therefore attracted to the rod in both
cases.
I understand that the rod should induce a charge separation. But it's not clear to me how that relates to the fact that there are two spheres in contact. The problem makes no distinction regarding where, relative to the spheres, the rod is placed "close" by. So if we factor out relative location, then it seems like, due to lack of contact, all we should expect is a temporary charge separation. After which the sphere, being removed, wouldn't affect anything.
B. Charges from the rod transfer to sphere A, making them the same charge. There is
repulsion between these two objects in both cases since they are like charges.
This answer doesn't make sense to me due to the fact that the rod doesn't come into direct contact with either sphere.
C. Because sphere A remains neutral throughout the experiment, it will attract any nearby
charged object because of induced charge separation. So attraction in both cases
I ruled this out as close to nonsensical for awhile until I started to regard it as the most likely answer due to problems I had with the others. Currently it's my top contender.
D. The gravitational force between objects is always attractive, and at this scale the
gravitational forces are more dominant than electric forces in both cases so attraction wins
Nonsensical answer of course.

A: Because the spheres are made of metal, electrons are free to flow between them. So when the rod containing positive charge is brought close to the spheres, the electrons within the two-sphere system will move toward the rod.
This means there will be a migration of electrons from sphere B to sphere A (assuming sphere A is closest to the rod). This will cause the two spheres to be polarized as they are in contact (but the whole two-sphere system is still electrically neutral). But each individual sphere, will have a net charge. Sphere B will have a net positive charge while sphere A will have a net negative charge. When sphere B is  moved away from sphere A the positive charge will redistribute itself uniformly about sphere B, and therefore there will be net negative charge uniformly distributed around sphere A. Sphere A attracts the rod.

It's not clear to me, by the way, if they mean that we bring the rod close, remove sphere B, and then repeat the procedure with sphere B absent. Or just repeat the entire procedure, with sphere B present again

It means the process is repeated with a negatively charged rod. The same will happen but with opposite net charge on each sphere. That is, there will be net positive charge on sphere A and negative charge on B. Sphere A attracts the rod.

all we should expect is a temporary charge separation. After which the sphere, being removed, wouldn't affect anything.

As written above, since the charged rod polarizes both spheres, removing one sphere results in net opposite signed charge on either sphere.

This answer doesn't make sense to me due to the fact that the rod doesn't come into direct contact with either sphere.

As written above, it makes sense that the rod is brought near to the spheres and not in contact, since charge is free to move on the spheres, all we need is polarization of charge. In fact, if the rod did make contact, there would be charge flow, which will result in equilibrium (equal charge on each sphere).

A. The rod induces charge separation, so sphere A gains a charge opposite that of the rod. Removing B, sphere A retains that charge and is therefore attracted to the rod in both cases.

This is obviously the correct answer, as we have seen in the analysis above.


text:
Q: ionic - how to put ion-select and ion-datetime together in ion-item row I want to put ion-select and ion-datetime together in the same ion-item like below:
<ion-item *ngFor="let column of columns">
            <ion-label floating>{{column.title}}</ion-label>

             <ion-select *ngIf="column.type=='customDate'">
                        <ion-option value="on">on</ion-option>
                        <ion-option value="onorbefore">on or before</ion-option>
                        <ion-option value="onorafter">on or after</ion-option>
                        <ion-option value="bewteen">between</ion-option>
                    </ion-select>

                    <ion-datetime *ngIf="column.type=='customDate'"  displayFormat="YYYY-MM-DD" ></ion-datetime>
                    <ion-datetime *ngIf="column.type=='customDate'"  displayFormat="YYYY-MM-DD" ></ion-datetime>

            <ion-input *ngIf="column.type=='text'" type="text"  [(ngModel)]="filterValues[column.id]"></ion-input>
        </ion-item>

The logic is if the column type is customDate, then show dropdown select and two datetime pickers. Based on the user selected dateType, the second dateTime picker will be hidden.
Now the problem is if I use above code, then I can ONLY see the dateTime component. The dateType dropdown select is no longer there. I looked at the source code in web console, the dropdown dateType select is empty.
Are there any restrictions for using the ion-item component? why can't you display all three together in the same ion-item row?
Thanks

A: you can try this
<ion-list>
 <ion-row>
  <ion-col ion-item col-6>
     <ion-select></ion-select>
  </ion-col>
  <ion-col ion-item col-6>
     <ion-datetime></ion-datetime>
  </ion-col>
 </ion-row>
</ion-list>


text:
Q: Exception caught after BrowserWindow is refactored to a separate file I've had managed to refactor a number of codes to separate files (and classes) all successfully but except for BrowserWindow. Does BrowserWindow handle things differently? I'm on Electron v.14.
My index.js that works before refactoring:
const electron = require('electron');
const { app, BrowserWindow } = electron;

let mainWindow;

app.on('ready', () => {
    mainWindow = new BrowserWindow({
        width: 300,
        height: 500,
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false,
            enableRemoteModule: true
          },
    });
    mainWindow.loadURL(`file://${__dirname}/src/index.html`);
});

And following are the codes that breaks after I refactor BrowserWindow to a separate file (and the error that I get: TypeError: MainWindow is not a constructor):
index.js:
const electron = require('electron');
const MainWindow = require('./app/main_window');
const { app } = electron

let mainWindow;

app.on('ready', () => {
    mainWindow = new MainWindow();
    mainWindow.loadURL(`file://${__dirname}/src/index.html`);
});

main_window.js (./app/main_window.js):
const electron = require('electron');
const { BrowserWindow } = electron;

class MainWindow extends BrowserWindow {
    constructor() {
        super({
            width: 300,
            height: 500,
            webPreferences: {
                nodeIntegration: true,
                contextIsolation: false,
                enableRemoteModule: true,
            }
        });
    }
};

A: You need to export the class to import it in other files.
export class MainWindow extends BrowserWindow ....

You can find more information here.


text:
Q: Changing permissions on all files and folders in a given folder I've recently reinstalled Windows 7, and all the files on the backup hard disk I use are exclusively set to ownership on my previous admin account. How this occurred, I have no idea, but now I can't access my own files. Using my new admin account, I set the ownership to the new account and then set myself to full permissions. But when I changed the settings on a folder, some of the contents recursively updated but others did not- I have to change every one of these files and folders manually, of which there are a great many. I tried setting myself to act as part of the operating system in the Local Security Policy, but again, this has only worked to grant access to some of the files. There are still many more that I can't access.
I need to wipe all trace of the previous administrator account from all files and folders on the hard drive and grant myself all permissions.
Any suggestions as to how I can eliminate this problem?

A: If you mount your drive in Linux, the permissions will be pretty much ignored if the files are not encrypted:

*

*Boot from a live CD

*Copy files to a location that doesn't understand NTFS permissions, e.g., a FAT32 partition or USB stick

*Copy them back to a new location on the original NTFS partition that has its file permission set properly

*Boot back into Windows.

Any live CD that can mount NTFS will do here. Ubuntu works from my experience.
My solution is a bit blunt, I'd be curious to see a batch file or script that repeatedly calls icacls and/or takeown.


text:
Q: ADO.Net Destination connector I'm looking into existing packages in SSIS for my team to streamline some of the ETL, and I came across a symbol which do not correspond to the connectors in the existing library. Has anyone come across the symbol that has the label of ADO destination below?

From what I have seen thus far, ADO.Net Destination has a specific connector with its own symbol like the below

The package is purely extracting source data from oracle DB, and then re-ingest it to another oracle DB using the ADO.Net connectors.

A: I think that the first image is showing a custom component (based on the icon) and the label ADO destination is meaningless since it is wrote by the developer.
To check the component type, click on it and press F4 to show the properties tab, then check the component type on the top of properties.


text:
Q: How to customize AWS Amplify iOS Authentication alerts? As someone new to iOS Swift development, I was wondering if someone could help me understand the proper way to customize client-side alert messages for authentication errors such as incorrect username and password. Below is the default alert message, which has the exception name as the title, which is not good user experience. How would I go about displaying an alert popup with another title and message?

A: I think you are looking for UIAlertController.
Swift sample :
let alert = UIAlertController(title: "Hello!", message: "Message", preferredStyle: UIAlertController.Style.alert)
let alertAction = UIAlertAction(title: "OK!", style: UIAlertAction.Style.default)
        {
            (UIAlertAction) -> Void in
        }
        alert.addAction(alertAction)
        present(alert, animated: true)
        {
            () -> Void in
        }

Hope it helps!

A:
Handle your error response to define custom title & message like
below.

import AWSCognitoIdentityProvider

extension Error {
    var customizedDescription: String {
        let nsError = self as NSError
        if nsError.domain == AWSCognitoIdentityProviderErrorDomain, let code = AWSCognitoIdentityProviderErrorType(rawValue: nsError.code) {
            switch code {
            case .expiredCode: return "Verification code has expired. Please try again"
            case .codeMismatch: return  "Incorrect verification code. Please enter the correct code to continue."
            case .notAuthorized: return "Authentication failed. Please enter the correct credentials to continue."
            case .usernameExists: return "Username already exists."
            case .invalidPassword: return "Invalid password. Please try again."
            case .userNotConfirmed: return "User not confirmed. Please verify your account."
            default: return nsError.userInfo["message"] as? String ?? "AWS cognito failed with error code: \(nsError.code)"
            }
        }
        return localizedDescription
    }
}

https://gist.github.com/Catherine-K-George/11a94271bd0cff282e019cd2613d089b


text:
Q: myFlowPanel has many childFlowPanels, so how to create the same margin for all childFlowPanels without using marginTop on childFlowPanels (GWT)? //myFlowPanel has many childFlowPanels

myFlowPanel.add(childFlowPanel1);
myFlowPanel.add(childFlowPanel2);
//.. more childs here

Then I want each of these childs will have 5px margin gap between them, but I don't want to apply "margin-top" for each child.
Just wondering if there's a way we can just has 1 line of code like this to do all the works like cellspacing in <table>:
myFlowPanel.setFlowPanelSpacing("5px");

Mybe we can do at css level, but I don't know how.

A: You can do it in CSS:
.myPanel div {
    margin-top: 5px;
}


text:
Q: Highchart graph customization not performing well I am using high chart graph to display data in this graph by current month.I want to display four weeks of the month in x-axis and want to show data for the whole month.I am giving my working js fiddle :
**http://jsfiddle.net/Rw69Y/2/**

Everything is working fine except I just want to show four monday of this month. i.e (2014-04-07,2014-04-14,2014-04-21,2014-04-28).Any idea about it?I am stuck on there....

A: just set tickInterval please see this fiddle-**http://jsfiddle.net/Rw69Y/21/**

A: Simply set tickInterval: 7 * 24 * 3600000, see: http://jsfiddle.net/Rw69Y/10/


text:
Q: cross field validation with angular I am trying to create a validator that checks that the beam (width of a boat) is not greater than the length.  In the component:
this.vesselForm = this.fb.group({
  beam: [null, [
    Validators.required,
    BeamValidators.beamCannotBeGreaterThanLength,
  ]],
  length: [null, Validators.required],
});

In the file beam.validators.ts:
import { AbstractControl, ValidationErrors } from '@angular/forms';

export class BeamValidators {

    static beamCannotBeGreaterThanLength(control: AbstractControl): ValidationErrors | null {
      const hullLength = control.parent.controls['length'].value;
      // const hullLength = 48;
      console.log(hullLength);
      if ((control.value >= hullLength)) {
          return { beamCannotBeGreaterThanLength: true };
      } else {
          return null;
      }
  }
}

I cannot figure out how to access the length from the validator.  The code compiles past intellisense but errors out in the browser with the console error:
ERROR TypeError: Cannot read property 'controls' of undefined
    at BeamValidators.beamCannotBeGreaterThanLength (beam.validators.ts:6)

The rest of the program works fine using the test line // const hullLength = 48;

A: To implement cross validation, you must lift the validation to the FormGroup level.
import { Component } from '@angular/core';
import {ValidatorFn, FormGroup, Validators, FormBuilder } from '@angular/forms';

const beamValidator: ValidatorFn = (fg: FormGroup) => {
  const beam = fg.get('beam').value;
  const length = fg.get('length').value;

  return beam < length ? null : { beamError: true };
}

@Component({
  selector: 'my-app',
  template: `
  <form [formGroup]="form">
    <input [formControl]="form.get('beam')" type="number" />
    <input [formControl]="form.get('length')" type="number" />
  </form>

  {{ form.valid }}
  `,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
 form: FormGroup;

  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      beam: [null, [
        Validators.required,
      ]],
      length: [null, Validators.required],
    }, { validator: beamValidator});
  }
}

Live demo
I'm trying to get this type of validation included in the official documentation. If you think it would be a good fit, please consider upvoting this Github issue.


text:
Q: Ubuntu 14.04 On Acer Aspire TImelinex 3830T Microphone Okay so the microphone has been staticy ever since installing ubuntu starting with 12.10 does anyone have a fix for the microphone?

A: Install pavucontrol, go to the recording options, disable "Lock channels together" or something like that. Put one channel (left or right) in half the other channel.
If I understand correctly your problem, it can be because when the 2 channels of the mic are in the same level, they cancel each other. I have a  5830TG and had the same problem, and fixed that way, no need to disable the PulseAudio


text:
Q: Will polling a MySQL Database suffice for a turn based Flash Game? I've wanted to expand my game development into the realm of multiplayer, however I don't have the funds for a proper server that has sockets or the time to develop an understanding of how they work and how to use them properly and securely.
What I am however fully capable of is sending and receiving data between Flash and MySQL via PHP in various formats.
If I were to create a turn based game, would polling a MySQL database in this fashion (via PHP) be suitable? At the moment I am thinking along these lines:

*

*Two players find each other by a means such as global listing of open games (pretty standard approach).

*An encounter or similar row is created in the database.

*The row will store information about who's turn it is and the current state of the game in JSON or XML format. The row will also contain a timestamp from each player representing the last time they had polled the database for game state information. When players complete their turn, the "turn" field will switch over.

*Each player polls the database to see if it is their turn yet. If it is, the game state information will be compared to the game state information before they ended their last turn and actions will take place on-screen to reflect the difference. Their turn then begins and the process repeats.

*While polling the database, if the opponent hasn't polled the database for their turn within 120 (arbitrary) seconds, the player will receive a notice that the other player has left / timed out / whatever.

Will this be far too slow or unreliable? Or are there other issues that can be foreseen such as the result of both players polling the database at the same time (not sure if that matters)?

A: Instead of polling, I'd suggest that you look into a technology allowing to push data from the server to the Flash client. The two most common options are either socket connections, or using the Real Time Messaging Protocol, see this question for more details. That's the default approach to building real time games using Flash.
For PHP, there are a number of open source products or frameworks with support for the RTMP based AMF protocol:

*

*WebORB for PHP

*Zend Framework AMF Adobe Systems has contributed support for their open, binary Action Message Format (AMF) protocol to Zend Framework. Very useful if you use Zend Framework already.

*amfPHP

*sabreamf
I've personally used Zend Framework AMF with good results, heard good things about WebORB as well. I have not used the other AMF libraries.
Regarding your specific questions: I'd not store the information in a database as JSON or XML, since you want to query the data. It's far more efficient to store the data as native SQL data.
Here is a short example showing you how to use Zend Framework AMF to give you an idea how it would work.


text:
Q: change prompt formatting based on cwd I use tcsh. I'd like to have my prompt formatting (coloring/highlighting) change based on the directory I'm in, or other critical aspects of my environment.
I'm not enough of a shell hacker to know how to do this.
Ownership of Current Directory
If I'm in one of "my" directories (i.e., I am owner of the current working directory), then it should have normal appearance. But if I'm in someone else's directory (I do a lot of support and cd to others' working areas), then I want the prompt to look clearly different.
This is to remind me to not type impolite commands in others' directories. (think make clobber or p4 sync, etc.)
Critical Environment Variable Setting
Another important piece of information for my environment is whether a certain environment variable is set, call it SWDEV. If SWDEV is not set, then my scripts and flows come from their default location. But if this variable is set, then it's taken as a new root location for my scripts and flows, with behaviors changing according to the scripts at that location.
It's important to be reminded of the setting of this variable, lest I expect "normal" behavior but instead absentmindedly run code from the new location.

A: I didn't figure out how to do this natively in shell (tcsh), but I did solve the problem using a Perl script.
With a Perl script, you can have logic as sophisticated as you want to check whether you own the $cwd, what environment variables are set, etc. Then, have the script print the prompt string you'd like.
tcsh has a special precmd alias that is executed each time before the prompt is printed. So, having a Perl script "formatPrompt.pl"
#!/home/utils/perl-5.8.8/bin/perl

use strict;
use warnings;

use Cwd;
# "SWDEV" is an env var special to our environment. Want to be reminded in the prompt of its setting.
use Env qw(SWDEV prompt);

my $prompt = '%U{%m}%~%u> ';
my $prefix = '';

if (defined $SWDEV) {
    # set a prompt prefix if special env var is set. use "Boldface" highlighting.
    $prefix = "%Bspecial env var SWDEV=$SWDEV%b\\n";
}
if (! -o getcwd) {
    # change the highlighting of the prompt if not your dir.
    $prompt = '%U{%m}-->%~<--%u> ';
}
$prompt = $prefix . $prompt;
print $prompt;

exit 0;

and an alias defined such
% alias precmd
set prompt="`perl /home/source/perl/formatPrompt.pl`"

can produce
{o-xterm-62}~> setenv SWDEV "/some/special/env/var/value"
special env var SWDEV=/some/special/env/var/value
{o-xterm-62}~> cd /usr
special env var SWDEV=/some/special/env/var/value
{o-xterm-62}-->/usr<--> unsetenv SWDEV
{o-xterm-62}-->/usr<--> cd ~
{o-xterm-62}~>

(Note that if SWDEV is set, its value is printed, and that the cwd is surrounded by -->cwd<-- if the dir is not owned by the user. Try other prompt highlighting such as %S%~%s, also.)

A: Well, if an external script is an acceptable solution, you could do something like this:
#!/usr/bin/env perl
use Cwd;
my $cwd=getcwd();
$cwd =~ /$ENV{HOME}/ ?
             print "$cwd % " :
             print "%{\033[1;31m%}CAREFUL\\\!%{\033[0m%} $cwd % ";

Save that somewhere in your $PATH as make_prompt.pl and make it executable. And then, in your ~/.tcshrc :
alias precmd 'set prompt="`make_prompt.pl`"'

This will result in:

You can also add more conditions to change the prompt in specific ways in different directories:
#!/usr/bin/env perl
use Cwd;
my $cwd=getcwd();

## Here are some colors to choose from
my $red="%{\033[1;31m%}";
my $green="%{\033[0;32m%}";
my $yellow="%{\033[1;33m%}";
my $blue="%{\033[1;34m%}";
my $magenta="%{\033[1;35m%}";
my $cyan="%{\033[1;36m%}";
my $white="%{\033[0;37m%}";
## This resets the color, you need it after each color command
my $end="%{\033[0m%}";

## If you are in $HOME or one of its sub dirs, print a green prompt
if($cwd =~ /$ENV{HOME}/){
   print "$green$cwd$end % ";
}
## If you are in /usr or one of its sub dirs, print a red prompt
elsif($cwd=~ /\/usr/){
   print "$red$cwd$end % ";
}
## If you are in /etc or one of its sub dirs, print a blue prompt
elsif($cwd=~/\/etc/){
    print "$blue$cwd$end % ";
}
## If you're in /root. As you can see, colors can be combined
elsif($cwd=~/\/root/){
    print $red . "OY\\! You're not allowed in here\\!" .
          $end . $magenta . " $cwd$end % ";

}
## For wherever else, just print a plain prompt
else {
    print "$cwd % ";
}

A: For fun I provide another prototype, based on what I've seen the others do here, using simple if statements; make_prompt:
#!/bin/tcsh

set     red="%{\033[1;31m%}"
set   green="%{\033[1;32m%}"
set  yellow="%{\033[1;33m%}"
set    blue="%{\033[1;34m%}"
set magenta="%{\033[1;35m%}"
set    cyan="%{\033[1;36m%}"
set   white="%{\033[0;37m%}"
set     end="%{\033[0m%}"

if ("$dirstack[1]" == "/") then
  echo " ${blue}r${magenta}o${cyan}o${green}t${end} "
else if ("$dirstack[1]" =~ "/home/thisguy*") then
  echo " ${yellow}Watch this guy out\\!${end} "
else if ("$dirstack[1]" =~ "/hom*") then
  echo " ${red}Be mindful of the home dir\\!${end} "
else if ("$dirstack[1]" =~ "/usr*") then
  echo " ${magenta}You're in /usr now\\!${end} "
else if ("$dirstack[1]" =~ "/etc*") then
  echo " ${green}-=etc=-${end} "
endif

With the bit that goes in .tcshrc, opting to use rprompt instead of prompt to automatically align the information to the right:
alias precmd 'set rprompt="`if "$?" == 0 echo "\(ok\)"``if "$?" == 1  echo "\(err\)"``if ("$?" != 0 && "$?" != 1) echo "\($?\)"``make_prompt`"'

Also added is a simple indication of the exit status of the last command (ok = 0, err = 1, $? for anything else).
Limitation is that a specific order is required (from the specific to the general) when making custom messages in the script for directories that are objects within others i.e. /home/thisguy vs. /home here.


text:
Q: Mount disk to /home or /usr in GCP vms I had question regarding mounting disk on GCP vms and creating logical volumes :

*

*Is is possible to use LVM or create logical volumes (lv) for additional disk and mount it to root folders in gcp images as its breaking the whole VMs down when restarted.
In other words, create lv at /home or /usr or /var folders for secondary disk attached /dev/sdb
Is it limitation on GCP Images ?

A: LVM is not supported for predefined images on GCP but will work for custom images. It is recommended to create secondary disk instead or simply resize the current disk for additional resources as a workaround.
Please see this documentation for more information.


text:
Q: How to select and delete a TR element with multiple td's? So what it does it creates a to do list. You add and select a category in the first input field and then in the second you create a TR which contains 4 tds with information such as the number of the list, date, the chosen category and the chosen second user input. With my code I can select and delete categories but I'm having trouble figuring out how to target the TR with multiple TD's in it.
HTML
<!DOCTYPE html>

        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta charset="utf-8">

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

Opravila

                            <input type="text" class="form-control mr-2" id = "dodaj" name="additem">
                            <button id="add" class="btn btn-primary mr-2" onclick="newElement()">Dodaj</button>
                            <button id="remove" class="btn btn-primary" class="remove" >Zbriši</button>

Vaje

Treningi

Projekt

                    <input type="text" id = "opravila" class="form-control mr-2">
                    <button id="add2" onclick="AddTo()" class="btn btn-primary">Dodaj</button>

                #
                Opis
                Kategorija
                Datum vnosa

    <button id="removerino" class="btn btn-danger">Brisi</button>

OSS Vaja 5 - jQuery in Bootstrap

JS
var counter = 0;

$(document).on('click', '.list-group-item', function(){
  $('.list-group-item')
    .css({ "font-weight": 'normal', "text-decoration": 'none'})
    .removeClass("selectedItem");

  $(this)
    .css({"font-weight": 'bold', "text-decoration": 'underline'})
    .addClass("selectedItem");
});

$(function(){
  $("#add").click(function(){
    var addItem = $("#dodaj").val();
    if(addItem.length > 0) {
      $("ul").append($('

)').text(addItem));
      $("#dodaj").val("");
    }
  });

  $("#remove").click(function() {
    $(".selectedItem").remove();
  });
  $("#removerino").click(function() {
    $(".selectedItem").remove();
  });
});

function AddTo(){
  var currentdate = new Date();
    var datetime = currentdate.getDate() + "/"
                + (currentdate.getMonth()+1)  + "/"
                + currentdate.getFullYear() + " @ "
                + currentdate.getHours() + ":"
                + currentdate.getMinutes() + ":"
                + currentdate.getSeconds();

counter++;
var td1 = counter;
var td2 = document.getElementById('opravila').value;
var td3 = document.getElementsByClassName("selectedItem")[0].innerText;
var td4 = datetime;

$("tbody").append("
" + "
");
  $("tr").last().append("" +td1+  "</td");
    $("td").last().append("" +td2+"</td");
      $("td").last().append("" +td3+"</td");
        $("td").last().append("" +td4+"</td");
          $("tr").last().attr("" +td1+  "</td");

}

A: Based on the code you have given I found.remove(), so if that is the intended 'TD' you are trying to remove and you want relevant TR you can try "parent().remove()" which will remove 'TR' completely.
sample Js:
  $("#remove").click(function() {
  $(".selectedItem").parent().remove();
  });
  $("#removerino").click(function() {
   $(".selectedItem").parent().remove();
    });


text:
Q: Using AlertDialog inside Button.onClick messes up value of getView(int position) in ArrayAdapter I've been trying to figure this out for about 2 weeks but no luck at all. I'm trying to add a confirmation message in my onClickListener by using AlertDialog, and the setPositiveButton of AlertDialog will be the one to do the things that I want to happen, but it messes up the int position value in getView . Instead of getting the position of the item I clicked on, it gets the position of the last item. I tried doing Toast message inside the onClick(NOT inside the AlertDialog) and it returns the proper position, but when I try to Toast message inside the AlertDialog it changes the position value. I stuck and don't how to make this work.
Here is my Adapter.Class
public class myOrderAdapter extends ArrayAdapter<myOrder> {

    AlertDialog.Builder builder;
    AlertDialog ad;

    public class ViewHolder{
        TextView tableNum;
        TextView itemName;
        TextView itemQuantity;
        TextView custName;
        Button btnStatus;
    }

    public myOrderAdapter(Context context, ArrayList<myOrder> orderList) {
        super(context, 0,orderList);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        final myOrder orderList = getItem(position);

        ViewHolder viewHolder;
        viewHolder = new ViewHolder();

        if(convertView == null){

            convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_layout,parent,false);

            viewHolder.tableNum = (TextView)convertView.findViewById(R.id.tableNum);
            viewHolder.itemName = (TextView)convertView.findViewById(R.id.itemName);
            viewHolder.custName = (TextView)convertView.findViewById(R.id.custName);
            viewHolder.itemQuantity = (TextView)convertView.findViewById(R.id.itemQuantity);
            viewHolder.btnStatus = (Button)convertView.findViewById(R.id.statusButton);

            convertView.setTag(viewHolder);

        }

        else {
            viewHolder = (ViewHolder)convertView.getTag();
        }

        viewHolder.tableNum.setText("Order for Table: "+orderList.getTable_id());
        viewHolder.itemName.setText(orderList.getItem_name());
        viewHolder.custName.setText("Customer Name: " + orderList.getCust_name());
        viewHolder.itemQuantity.setText("QTY: " + orderList.getQuantity());

        builder = new AlertDialog.Builder(Order.context);
        builder.setTitle("Confirmation");
        builder.setIcon(R.drawable.ic_confirm);
        builder.setMessage("Is this Ready to Serve?");

        builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Toast.makeText(getContext(),orderList.getOrder_id()+ "+" + orderList.getItem_name() + "+" + position,Toast.LENGTH_SHORT).show();
            }
        });

        builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        });

        ad = builder.create();

        viewHolder.btnStatus.setText("Ready");
        viewHolder.btnStatus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getContext(),orderList.getOrder_id()+ "+" + orderList.getItem_name() + "+" + position,Toast.LENGTH_SHORT).show();
                ad.show();
            }
        });

        return convertView;
    }

}

NOTE :
I set the Toast message the same way as Button.onClickListener in the builder.setPositiveButton to check if the value changes, and yes it does change. Need some help and guidance, thank you.

A: The problem here is that you are creating the AlertDialog for every view created even to the last view(for the last item) which is the reason why you are getting the position to be the last index of your item list. Try something like below, this will only create the dialog when you click on the button from one of the view.
public class myOrderAdapter extends ArrayAdapter<myOrder> {

public class ViewHolder{
    TextView tableNum;
    TextView itemName;
    TextView itemQuantity;
    TextView custName;
    Button btnStatus;
}

public myOrderAdapter(Context context, ArrayList<myOrder> orderList) {
    super(context, 0,orderList);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    final myOrder orderList = getItem(position);

    ViewHolder viewHolder;
    viewHolder = new ViewHolder();

    if(convertView == null){

        convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_layout,parent,false);

        viewHolder.tableNum = (TextView)convertView.findViewById(R.id.tableNum);
        viewHolder.itemName = (TextView)convertView.findViewById(R.id.itemName);
        viewHolder.custName = (TextView)convertView.findViewById(R.id.custName);
        viewHolder.itemQuantity = (TextView)convertView.findViewById(R.id.itemQuantity);
        viewHolder.btnStatus = (Button)convertView.findViewById(R.id.statusButton);

        convertView.setTag(viewHolder);

    }

    else {
        viewHolder = (ViewHolder)convertView.getTag();
    }

    viewHolder.tableNum.setText("Order for Table: "+orderList.getTable_id());
    viewHolder.itemName.setText(orderList.getItem_name());
    viewHolder.custName.setText("Customer Name: " + orderList.getCust_name());
    viewHolder.itemQuantity.setText("QTY: " + orderList.getQuantity());

    viewHolder.btnStatus.setText("Ready");
    viewHolder.btnStatus.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(getContext(),orderList.getOrder_id()+ "+" + orderList.getItem_name() + "+" + position,Toast.LENGTH_SHORT).show();
            createDialog(position);
        }
    });

    return convertView;
}

private void createDialog(final int position) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
    builder.setTitle("Confirmation " + position);
    builder.setIcon(R.drawable.pencil);
    builder.setMessage("Is this Ready to Serve? " + position);

    builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            Toast.makeText(getContext(),orderList.getOrder_id()+ "+" + orderList.getItem_name() + "+" + position, Toast.LENGTH_SHORT).show();
        }
    });

    builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            dialogInterface.dismiss();
        }
    });

     builder.create().show();
}
}


text:
Q: Safely Execute Stored Procedure Via DMZ Server I'd like to execute a stored procedure via web application that connects to SQL Server. The procedure is to be activated by clicking a link in an email. The link will have to be accessible from a mobile 3g connection, so the link will exist on a DMZ server.
How can I go about protecting and securely setting up this link, without potentially compromising the SQL server?
Is there a safer way to accomplish the same goal?

A: There's nothing inherently risky about what you're trying to do, given that you follow a couple of standard security rules:

*

*Never expose variables used in the SQL query (ie GET or POST Variables) without ensuring they are clean before executing the query.

*Ensure the script can't do anything beyond what you expect

*If it is something the public shouldn't access make sure you password protect it

*Run the script as a user with the minimum privileges required to do the job. NOT Administrator!

A: If you have the resources you would have a SQL server separate from your web interface which sits in the DMZ. This is standard practice to isolate the SQL engine. Mobility interfaces get hammered by all kinds of traffic.


text:
Q: Failed to resolve: com.google.android.gms:play-services-location:9.6.1 Having updated to AS v2.2.2 I can no longer resolve the Google Play Services maps and location facets. The message I receive is;

Error:(54, 27) Failed to resolve:
  com.google.android.gms:play-services-maps:9.6.1 Install Repository and sync project/Documents/workspace//Polaris/build.gradle">Show
  in FileShow in
  Project Structure dialog

The install link does not work and I have uninstalled AS and reinstalled as well as having uninstalled Play Services and reinstalled the latest (v37 at the time of writing).
All out of ideas. I do not have the classpath 'com.google.gms:google-services:3.0.0' and apply plugin: 'com.google.gms.google-services' bits and pieces that related questions suggest. I don't know what they are for so avoiding... plus, it worked on Android Studio v2.2 (at the same version 9.6.1).
Any help in getting my Google flavour to build again much appreciated.

A: Fixed by manually downloading Play Services as described here and moving into position under the SDK.
:S
#hacking4life


text:
Q: How many real numbers satisfy the following How many real numbers satisfy:
$$\sin x=\frac{x}{100}$$
I don't know where to start it how to do this at all. Can someone please help me?

A: Hint:
The following graph shows the $\sin{x}$ curve and $\frac {x}{100}$ straight line:

Solution:
The RHS takes on the values $-1 \le \sin{x} \le 1$.
The LHS is within these values when $-1 \le \frac {x}{100} \le 1\quad \Rightarrow -100 \le x \le 100$.
Within this range of $x$, we note that $\frac {x}{100} $ straight line cuts the $\sin {x}$ curve at $2$ points (roots) in the positive half-cycle of the sine curve when $x>0$ or negative half cycle when $x<0$.
Within $ -100 \le x \le 0$ and $0 \le x \le 100$, each has $\frac {100}{2\pi} \approx 15.9$ full cycles and $16$ positive or negative cycles.
Therefore the $\frac {x}{100} $ straight line cuts through $16\times 2 -1 = 31$ negative points and $31$ positive points and share $1$ point when $x=0$.
Therefore the number of points cut and hence the number or real roots is $31+31+1 = 63$.


text:
Q: ¿Porqué los links del archivo svg dejan de funcionar si se utiliza un tag img? Problema
Tengo un archivo svg que cuenta con un link  en su interior, la función de este link es repetir la animación del svg cada vez que se clica en él. Funciona correctamente si abro el archivo svg en un navegador, pero al importar el archivo en html usando un tag  la animación funciona pero el link no parece ser reconocido ya que al posicionarse sobre el svg el cursor no cambia su default por el pointer y al hacer click no se repite la animación.
Navegadores en los que se verifica esta situación: Firefox, Chrome, Edge.

Ejemplo mínimo verificable
Página html

Archivo svg

<svg xmlns="http://www.w3.org/2000/svg" width="680" height="370" viewBox="0 0 180 98">

    <rect x="1.5" y="1.5" width="102.6" height="54.3" rx="2.8" fill="#85bb65"/>
    <g>
      <set attributeName="opacity" to="0" dur="2s"/>
      <animateTransform attributeName="transform" attributeType="XML" type="translate" from="40 40" to="0 0" id="A" begin="2s;A.begin" dur="0.5s"/>
      <circle cx="54" cy="29" r="20" fill="#dcdcdc"/>
    </g>

</svg>

Enlaces útiles

*

*Archivo svg completo que se repite al clicar en él.

*Sitio web en el que el archivo es importado con el tag img.

A: Solución
Puede deberse a la compatibilidad de navegadores, en Firefox parece ir bien, sin embargo, en Microsoft Edge y Chrome no va usando la etiqueta , puedes añadir un  para reemplazar a la etiqueta

Es más eficiente debido a que el  carga la página vinculada en su totalidad

Prueba con la etiqueta img
Varía dependiendo del navegador, aquí está la misma imagen vinculada con


text:
Q: libgdx app doesn't run on android device, works fine on desktop I'm learning to work with libgdx and I tried to run a very simple app
on my android device but it doesn't open. The screen of my phone turns horizontally and then immediately turns back. It runs fine when I run it on desktop. My phone is a oneplus 3t. The only thing I did was show an image on screen. I haven't touched the android launcher and usb debugging is enabled on my phone. I know there a other questions like this but I haven't found a solution there. This is what android studio tells me:
04/06 19:37:42: Launching AndroidLauncher
$ adb install-multiple -r -p com.mygdx.game
D:\JavaGameDev\Game3\android\build\intermediates\split-
apk\debug\slices\slice_4.apk
Split APKs installed
$ adb shell am start -n "com.mygdx.game/com.mygdx.game.AndroidLauncher" -a
android.intent.action.MAIN -c android.intent.category.LAUNCHER
Client not ready yet..Connected to process 9593 on device oneplus-
oneplus_a3003-ba73d782
Application terminated.