text:
Q: Swift: create module (namespace) Hy guys,
Do you know how can I create a module(namespace) in swift ? For example in C# we have namespace keyword, but in Objective-C there is no such thing, there we named our classes with the prefix of the folder they were located in. Shall I use the same approach in swift or do you know some other way to achieve namespacing in swift.
Thank you!

A: You can achieve it by using Frameworks which is newly introduced in iOS 8 for namespace-ing, if I am not mistaken.

A: I think I will either rename my classes to have a prefix of two capital letters like NSString, UIView and other classes from Objective-C do or I will wrap them in structs.
Thank you for your comments.


text:
Q: Error: connect ETIMEDOUT, how to solve it? using Node.js and MySQL2 I used Node.js and MySQL2. Working on MySQL workbench. Created virtual DB using Railway workbench. Schemas and tables are created. But showing `ETIMEDOUT error in the VS code's terminal when i try to run node index.js. What can i do?
db.js:
import mysql2 from 'mysql2';

export const db = mysql2.createConnection({
    host: 'containers-us-west-174.railway.app',
    user: 'user',
    password: 'password',
    database: 'railway'
})

index.js:
import express from 'express';
import authRoutes from './routes/auth.js';
import userRoutes from './routes/users.js';
import postRoutes from './routes/posts.js';
import dotenv from 'dotenv';
import cookieParser from 'cookie-parser';
import multer from 'multer';

dotenv.config();

const app = express();

app.use(express.json());
app.use(cookieParser());

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, '../client/public/upload');
    },
    filename: function (req, file, cb) {
        cb(null, Date.now() + '-' + file.originalname);
    }
})

const upload = multer({ storage: storage })

app.post('/api/upload', upload.single('file'), function (req, res) {
    const file = req.file;
    res.status(200).json(file?.filename)
});

app.use('/api/auth', authRoutes);
app.use('/api/users', userRoutes);
app.use('/api/posts', postRoutes);

app.listen(8800, () => {
    console.log('Connected wih backend!');
})

In my VS Code Terminal it is showing this error:
Connected wih backend!
node:events:505
      throw er; // Unhandled 'error' event
      ^

Error: connect ETIMEDOUT
    at Connection._handleTimeoutError (I:\EMON\Web-Development\FINALE\timeless-blog-f\api\node_modules\mysql2\lib\connection.js:189:17)
    at listOnTimeout (node:internal/timers:559:17)
    at processTimers (node:internal/timers:502:7)
Emitted 'error' event on Connection instance at:
    at Connection._notifyError (I:\EMON\Web-Development\FINALE\timeless-blog-f\api\node_modules\mysql2\lib\connection.js:236:12)
    at Connection._handleFatalError (I:\EMON\Web-Development\FINALE\timeless-blog-f\api\node_modules\mysql2\lib\connection.js:167:10)
    at Connection._handleNetworkError (I:\EMON\Web-Development\FINALE\timeless-blog-f\api\node_modules\mysql2\lib\connection.js:180:10)
    at Connection._handleTimeoutError (I:\EMON\Web-Development\FINALE\timeless-blog-f\api\node_modules\mysql2\lib\connection.js:193:10)
    at listOnTimeout (node:internal/timers:559:17)
    at processTimers (node:internal/timers:502:7) {
  errorno: 'ETIMEDOUT',
  code: 'ETIMEDOUT',
  syscall: 'connect',
  fatal: true
}

I was trying to deploting in railway. I'm using MySQL workbench.
In Railway deployment logs this error shows:
> api@1.0.0 start
> node index.js
node:internal/modules/cjs/loader:1239
return process.dlopen(module, path.toNamespacedPath(filename));
^
Error: /app/node_modules/bcrypt/lib/binding/napi-v3/bcrypt_lib.node: invalid ELF header
at Object.Module._extensions..node (node:internal/modules/cjs/loader:1239:18)
at Module.load (node:internal/modules/cjs/loader:1033:32)
at Function.Module._load (node:internal/modules/cjs/loader:868:12)
at Module.require (node:internal/modules/cjs/loader:1057:19)
at require (node:internal/modules/cjs/helpers:103:18)
at Object.<anonymous> (/app/node_modules/bcrypt/bcrypt.js:6:16)
at Module._compile (node:internal/modules/cjs/loader:1155:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1209:10)
at Module.load (node:internal/modules/cjs/loader:1033:32)
at Function.Module._load (node:internal/modules/cjs/loader:868:12) {
code: 'ERR_DLOPEN_FAILED'
}
npm WARN config production Use `--omit=dev` instead.

And deployment crashed!
Any solution?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Amazon EC2 Ubuntu Instance Maximum File Upload Size I was given an Amazon EC2 Ubuntu Instance. We are task to create a web application that includes uploading a client video. I have created a file upload application in my localhost and it is working fine. When I migrated the code to the virtual host server, I cannot upload any video and even any file that exceeds 2Mb. I tried editing the php.ini setting upload_max_filesize to 50M and post_max_size to 1000M.
After restarting Apache so many times, the update is not reflected in my phpinfo() information but changes were saved in my php.ini file.

I was suspecting that the Amazon EC2 instance given to me has a file upload restrictions but Im not sure if Im right. If I was wrong, how can I override the configuration below? Any help would be very much appreciated.
UPDATE:
I even made sure that I was editing the correct configuration file. Below are the screen shots:

UPDATE:
I tried following what is said in the link with no luck. I have a lot of questions in mind about the link like:

*

*What does tomcatchesides mean about S3 bucket? I uploaded the config file in /var/www/html/.ebextensions . Am I doing the right thing?

My zzz.ini contains the code below and I place it in /etc/php.d/zzz.ini:
[php]
post_max_size = 1000M
upload_max_filesize = 50M

My myconfigfile.config was located in /var/www/html/.ebextensions/myconfigfile.config and contains the code below:
files:
  "/etc/php.ini":
    mode: "000644"
    owner: root
    group: root
    source: http://mybucketname.s3.amazonaws.com/php.ini

  "/etc/php.d/zzz.ini":
    mode: "000644"
    owner: root
    group: root
    source: http://mybucketname.s3.amazonaws.com/zzz.ini

How to know the bucket name of my instance?
I also copied my php.ini from /etc/php/7.0/apache2/php.ini to /etc/php.ini and restarted apache. Still no changes. Am I doing the right thing?
UPDATE:
I ask for the bucket name to the person who gave me the EC2 instance and her reply was.

Yes, you were given access to an EC2 instance. S3 is a different
  service provided by Amazon and that's not automatically available to
  EC2 instances. We can create a bucket in S3 for you but it may no
  longer be needed.
The EC2 instance has around 8GB storage space. You should be able to
  store multiple videos greater than 2MB in the EC2 file system and
  access them directly.
Using S3 for file uploads is a good idea especially when your software
  goes to production. However, to simplify the setup, please use the
  file system instead to store the videos.

UPDATE :
Running the following commands:
php -i | grep -i max_size

yields: post_max_size => 1000M => 1000M
grep -ir "max_size" /etc/php/7.0/apache2/conf.d/

yieds nothing.
grep -ir "max_size" /etc/php/7.0/

yields
/etc/php/7.0/fpm/php.ini:post_max_size = 1000M
/etc/php/7.0/apache2/php.ini:post_max_size = 1000M
/etc/php/7.0/cli/php.ini:post_max_size = 1000M

My phpinfo() can be access through this link

A: After changin the php.ini file I also had to restart FPM:
sudo systemctl restart php-fpm.service
before restarting apache:
sudo systemctl restart httpd

A: Check also for:
/etc/php.ini
or
/etc/php-[version].ini
and modify the value also in this file. If this is not sufficient, search for:
/etc/php.d/aws.ini

infact it is possible that AWS is overriding your value. If this is the case, the solution is to create a file named /etc/php.d/99uploadsize.ini containing only:
[php]
upload_max_filesize = 100M
post_max_size = 100M

The name 99uploadsize.ini is not mandatory, but remember that the name should be in alphabetical order after aws.ini and in the same directory, because this is the order these ini files are read.
Even if the example is not about generical Ubuntu with Apache, this kind of solution is given by Amazon for a similar issue with WP here:
https://aws.amazon.com/it/premiumsupport/knowledge-center/wordpress-themes-2mb/

A: Sorry guys, for bothering all of you, my bad. I was banging my head for this for almost 4 days and it turns out that I have only made a syntax error in my php.ini. I updated my server php.ini with my newly installed php in my localhost and phpinfo() was updated after apache restart.


text:
Q: Auto reload configuration changes without restarting pod/container using Kubernetes ConfigMap for application with large number of configuration files Our team is planning the migration of legacy enterprise application developed in ASP.net web-Forms, to .Net Core 6 as use the containerized approach. For this, mostly we will target the Kubernetes container orchestration platform.
The application is highly configurable and can be integrated with related apps up to certain extent. It has large number of XML based configuration files (more than 100). Current mode of deployment is IIS (on-premise).
The major technical challenge that we are facing is to manage our application configuration.
So ConfigMap is one the option available in Kubernetes can be used for configuration management. ConfigMap APIs allows to generate ConfigMap from environment, yaml file, existing configuration file or directory. Directory based approach seems more suitable. However, considering the maximum size limit of ConfigMap we may end up creating multiple ConfigMap.
We need to make sure:

*

*Migrated app should be able to use configuration however application image should be separate and configuration can be injected from outside.

*The configuration changes should be reflected in application without POD.

Since the ConfigMap is kind of read-only resource when container starts, I am currently looking for mechanism to use with configuration reload without the need of  restarting POD/container.
Initial focus is to achieve this. (The impact of changed configuration on active users who might be referring to application feature based on previous configuration is a different topic altogether).

A: You can do it without restarting the POD using configmap only, however still it more depends on your application end.
You can inject your configmap and mount it to POD Kubernetes auto-reload the config map if mounted to the directory. To note it does not work if you are using the subpath.
Auto reload config map into Kubernetes without restarting the POD, you can more here: https://medium.com/@harsh.manvar111/update-configmap-without-restarting-pod-56801dce3388
YAML example
apiVersion: v1
kind: ConfigMap
metadata:
  name: test-config
data:
  hello: world
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: test
spec:
  selector:
    matchLabels:
      app: test
  replicas: 1
  template:
    metadata:
      labels:
        app: test
    spec:
      containers:
      - name: configmaptestapp
        image: <Image>
        volumeMounts:
        - mountPath: /config
          name: data-volume
        ports:
        - containerPort: 80
      volumes:
        - name: data-volume
          configMap:
            name: test-config

Official documentation : https://kubernetes.io/docs/concepts/configuration/configmap/#mounted-configmaps-are-updated-automatically

Mounted ConfigMaps are updated automatically When a ConfigMap
currently consumed in a volume is updated, projected keys are
eventually updated as well. The kubelet checks whether the mounted
ConfigMap is fresh on every periodic sync. However, the kubelet uses
its local cache for getting the current value of the ConfigMap. The
type of the cache is configurable using the
ConfigMapAndSecretChangeDetectionStrategy field in the
KubeletConfiguration struct. A ConfigMap can be either propagated by
watch (default), ttl-based, or by redirecting all requests directly to
the API server. As a result, the total delay from the moment when the
ConfigMap is updated to the moment when new keys are projected to the
Pod can be as long as the kubelet sync period + cache propagation
delay, where the cache propagation delay depends on the chosen cache
type (it equals to watch propagation delay, ttl of cache, or zero
correspondingly).
ConfigMaps consumed as environment variables are not updated
automatically and require a pod restart.

Note:

A container using a ConfigMap as a subPath volume mount will not
receive ConfigMap updates.

In this case your application need to be handling the content properly with change detection etc.


text:
Q: HTML file creation with image I created an HTML file programmatically with images sources. The images are stored in the documents directory. The problem is that when I give the image source path as document directory path the images are not shown in Windows.
So, I choose the second option is to give only the image's name instead of whole path. Then it work well on Mac & Windows, but now images are not shown on the device's UIWebView.
Then I selected to open the HTML file in Safari insted of UIWebView, but the safari could not be opened because URL becomes NULL.
My code to open Safari is as follow:

NSLog(@"%@",documentsDirectory);
NSString *urlStr = [NSString stringWithFormat:@"%@/AccReport1.html",documentsDirectory];
NSLog(@"urlStr :: %@",urlStr);
NSURL *url1=[[NSURL alloc]init ];
url1 = [NSURL fileURLWithPath:urlStr];
NSLog(@"url :: %@",url1);
[[UIApplication sharedApplication]openURL:url1];

I want to mail the HTML file that contains images. And these HTML file and images are stored in document directory. I want to show this HTML file with images in windows browser, mac browser and iphone's safari.
How to do this?

A: One of the simple way to solve your problem is to keep Images and HTML file in same directory and refer those images in HTML files just by name and if you put them in a folder then give the complete path.

A: The images are not showing because the image path specified within the HTML code is not the documents directory path.
I suggest you might have to construct an html string and then subject the uiwebview to load that string
    NSString *htmlString = [NSString stringWithFormat:@"",documentsDirectoryPath];

[webView loadHTMLString:htmlString baseURL:nil];


text:
Q: Convert opencv::Mat to std::string gives std::bad_alloc I have a cv::Mat of size 2064x1544 and I want to save it as a std::string. My code is simple:
std::string image_string(image.begin<unsigned char>(), image.end<unsigned char>());
json["image"] = image_string;

As I wrote in the title of the question I hit this error:
std::bad_alloc

What's the problem?

A: I'd recommend using OpenCV's cv::imencode function over your attempt as it is more flexible and safer.
You can use this function to convert a cv::Mat to a std::string.
Note that you need to specify the image format. You might want to change ".png" to ".jpg" or whatever is supported by cv::imencode(...).
std::string get_mat_as_string(const cv::Mat& cv_buffer_orig) {
    std::stringstream ss;
    if (!cv_buffer_orig.empty()) {
        try {
            std::vector<uint8_t> buffer;
            cv::imencode(".png", cv_buffer_orig, buffer);
            for (auto c : buffer) ss << c;
        } catch (std::exception& e) { std::cerr << e.what() << std::endl; }
    }
    return ss.str();
}

To retrieve the encoded cv::Mat inside the std::string you'd use
   std::string buffer; // must contain encoded image from above function
   std::vector<byte> pic_data(buffer.begin(), buffer.end());
   cv::Mat mat(pic_data, true);
   mat = cv::imdecode(mat, cv::IMREAD_COLOR);

Now mat contains the original cv::Mat.

I originally wrote this (slightly edited) to transfer cv::Mats over network, you can use it at your own discretion.

*

*(Source, Original Encoder)

*(Source, Original Decoder)


text:
Q: AS3 Class Error I am trying to make a game in flash using AS3. I am making a class file that set the parameters for creating a new planet, but when I then add the actions to the first frame of the timeline, it immediately gives me an error. I am new to action script and would love any help. My code should work as far as I know. Here it is:
The actions menu contains this code on the first frame -
var zuun:MovieClip = new Planet();

The class "Planet" looks like this, and is saved in a file name "Planet.as" and is targeted at my main file.
package  {

    import flash.display.MovieClip;

    public class Planet extends MovieClip {

        private var planetname:String;

        public function Planet() {
            // constructor code
        }

        public function setName(a:String):void {
            planetname = a;
        }

        public function getName():String {
            return planetname;
        }
    }

}

EDIT
The error i'm getting is this  -
Error: Error #2136: The SWF file file:///Users/mike/Desktop/jonah/bindings.swf contains     invalid data.
at Planet/frame1()[Planet::frame1:1]

Thanks


text:
Q: How to obtain the ImageSize? I want to obtain the ImageSize of an output in printer's points,
which is the standard unit of measurement of ImagePadding, ImageMargins etc.
For example I have a Plot
plot = ListPlot[{}, ImageSize -> 500, AspectRatio -> 2]

This plot will have an ImageSize of 500. If I use
N[ImageDimensions[plot]]

It gives {834., 1665.}, which is the "pixel dimension". I could now define a factor (in this case 1/333.6) to get the ImageSize in printers points, but this is not reliable, since the "pixel dimension" does not go linear with the ImageSize. Is there a better way to obtain the ImageSize in printers points for both x and y directions?

A: This is not the best answer, but perhaps a good starting point.
There exists a resource function developed by @Carl Woll that is called GraphicsInformation
You can do
"ImageSize" /. ResourceFunction["GraphicsInformation"]@plot

and you will get a result with a mismatch.
However, I claim that the missing factor between the first number and the value of ImageSize is always $\tfrac{4}{5}$
I have checked the following examples
plot1 = ListPlot[{}, ImageSize -> 300, AspectRatio -> 1];
plot2 = ListPlot[{}, ImageSize -> 300, AspectRatio -> 2];
plot3 = ListPlot[{}, ImageSize -> 300, AspectRatio -> 3];
plot4 = ListPlot[{}, ImageSize -> 300, AspectRatio -> GoldenRatio];
plot5 = ListPlot[{}, ImageSize -> 300, AspectRatio -> 1/GoldenRatio];
"ImageSize" /. ResourceFunction["GraphicsInformation"]@plot1
"ImageSize" /. ResourceFunction["GraphicsInformation"]@plot2
"ImageSize" /. ResourceFunction["GraphicsInformation"]@plot3
"ImageSize" /. ResourceFunction["GraphicsInformation"]@plot4
"ImageSize" /. ResourceFunction["GraphicsInformation"]@plot5

Then
plot1 = ListPlot[{}, ImageSize -> 400, AspectRatio -> 1];
plot2 = ListPlot[{}, ImageSize -> 400, AspectRatio -> 2];
plot3 = ListPlot[{}, ImageSize -> 400, AspectRatio -> 3];
plot4 = ListPlot[{}, ImageSize -> 400, AspectRatio -> GoldenRatio];
plot5 = ListPlot[{}, ImageSize -> 400, AspectRatio -> 1/GoldenRatio];
"ImageSize" /. ResourceFunction["GraphicsInformation"]@plot1
"ImageSize" /. ResourceFunction["GraphicsInformation"]@plot2
"ImageSize" /. ResourceFunction["GraphicsInformation"]@plot3
"ImageSize" /. ResourceFunction["GraphicsInformation"]@plot4
"ImageSize" /. ResourceFunction["GraphicsInformation"]@plot5

And finally,
plot1 = ListPlot[{}, ImageSize -> 55, AspectRatio -> 1];
plot2 = ListPlot[{}, ImageSize -> 55, AspectRatio -> 2];
plot3 = ListPlot[{}, ImageSize -> 55, AspectRatio -> 3];
plot4 = ListPlot[{}, ImageSize -> 55, AspectRatio -> GoldenRatio];
plot5 = ListPlot[{}, ImageSize -> 55, AspectRatio -> 1/GoldenRatio];
"ImageSize" /. ResourceFunction["GraphicsInformation"]@plot1
"ImageSize" /. ResourceFunction["GraphicsInformation"]@plot2
"ImageSize" /. ResourceFunction["GraphicsInformation"]@plot3
"ImageSize" /. ResourceFunction["GraphicsInformation"]@plot4
"ImageSize" /. ResourceFunction["GraphicsInformation"]@plot5

The above is not rigorous, but perhaps is pointing towards the right direction. Of course, more checks are needed. A robust explanation would be fantastic really. Finally, to the author of the O.P, if you are unhappy with the answer let me know and I will delete it.


text:
Q: d3.js realtime updating svg line with python websocket data I'm new to d3.js/javascript and web oriented  programming.
My goal is update the existing chart with new values through a websocket.
Note: In this example I alredy have a javascript array "var" and I need to add new values obtained with a websocket, but is not mandatory the array "var" could be also empty. My goal is draw data received through websocket ws.
I received correctly the values from a python websocket server (code1) but I still don't understand how to draw new elements on d3.js graph.
I read several doc about update pattern example  like https://bl.ocks.org/mbostock/3808218
but still doesn't get a working solution using d3.js enter()/update(). Code2 is a working example plus the javascript code for the websocket. I correctly get new data and store in var "close" "when". Could anyone help to modified the html code to plot new data? Thanks for help, regards.
Code1: working python server websocket
#!/usr/bin/env python
import asyncio
import datetime
import random
import websockets
import numpy as np
import json

IP = '192.168.10.224'
PORT = 5678

def format_time():
    t = datetime.datetime.now().time()
    s = t.strftime('%H:%M:%S.%f')
    return s[:-3]

async def time(websocket, path):
    while True:
        #now = datetime.datetime.utcnow().isoformat() + 'Z'
        data = {'datetime': str(format_time()),
                'ticker': 'ticker',
                'value': str(random.randint(100,1000)),
                'volume': str(random.randint(1,10))}
        await websocket.send(json.dumps(data))
        await asyncio.sleep(random.random() * 3)

start_server = websockets.serve(time, IP, PORT)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

Code2: html page d3.js
<!DOCTYPE html>
 <meta charset="utf-8">
 <style> /* set the CSS */

 .line {
   fill: none;
   stroke: steelblue;
   stroke-width: 2px;
 }

 </style>
 <body>

    <!-- load the d3.js library -->
     <script src="d3/d3.min.js"></script>
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

     <script>

     //working websocket get new data and print for debug purpose on javascript console
     var ws = new WebSocket("ws://192.168.10.224:5678/")
     ws.onmessage = function (event) {
     var messages = document.getElementsByTagName('ul')[0],
         message = document.createElement('li'),
         content = document.createTextNode(event.data);
     //console.log(typeof(event.data));
     var obj = jQuery.parseJSON(event.data);
     var close = obj.volume
     var when = obj.datetime;
     console.log(close,when);
     };

     // set the dimensions and margins of the graph
     var margin = {top: 20, right: 20, bottom: 30, left: 50},
         width = 960 - margin.left - margin.right,
         height = 500 - margin.top - margin.bottom;

     // parse the date / time
     var parseTime = d3.timeParse("%H:%M:%S.%L");

     // set the ranges
     var x = d3.scaleTime().range([0, width]);
     var y = d3.scaleLinear().range([height, 0]);

     // define the line
     var valueline = d3.line()
         .x(function(d) { return x(d.date); })
         .y(function(d) { return y(d.close); });

     // append the svg obgect to the body of the page
     // appends a 'group' element to 'svg'
     // moves the 'group' element to the top left margin
     var svg = d3.select("body").append("svg")
         .attr("width", width + margin.left + margin.right)
         .attr("height", height + margin.top + margin.bottom)
       .append("g")
         .attr("transform",
               "translate(" + margin.left + "," + margin.top + ")");

     var data = [
       {"date":"9:22:43.111","close":1.98},
       {"date":"10:22:43.222","close":5.98},
       {"date":"11:32:43.333","close":7.00},
       {"date":"11:52:43.444","close":8.70},
       {"date":"14:52:43.444","close":10.28},
       {"date":"15:52:43.444","close":16.70},
       {"date":"16:12:43.222","close":10.98},
       {"date":"16:12:43.222","close":3.44},
       {"date":"17:32:43.111","close":4.34},
     ];

     //per ogni elemento converto la data
     data.forEach(function(d) {
       d.date = parseTime(d.date);
       d.close = +d.close;
     }
     );

       // Scale the range of the data
       x.domain(d3.extent(data, function(d) { return d.date; }));
       y.domain([0, d3.max(data, function(d) { return d.close; })]);

       // Add the valueline path.
       svg.append("path")
           .data([data])
           .attr("class", "line")
           .attr("d", valueline);

       // Add the X Axis
       svg.append("g")
           .attr("transform", "translate(0," + height + ")")
           .call(d3.axisBottom(x)
             .ticks(d3.timeMinute.every(30))
     );

       // Add the Y Axis
       svg.append("g")
           .call(d3.axisLeft(y));

     </script>
     </body>

A: a friend of mine solved the problem! A chunk of data already inside array data drawline() other data coming across the websocket and function updateLine() is called! Remember to change the local ip address in html code. Enjoy :)
<!DOCTYPE html>
<meta charset="utf-8">
<style> /* set the CSS */

.line {
  fill: none;
  stroke: steelblue;
  stroke-width: 2px;
}

</style>
<body>

<!-- load the d3.js library -->
<script src="d3/d3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<script>

//websocket get new data on close and when
var ws = new WebSocket("ws://192.168.1.118:5678/")
ws.onmessage = function (event) {
var messages = document.getElementsByTagName('ul')[0],
    message = document.createElement('li'),
    content = document.createTextNode(event.data);
//console.log(typeof(event.data));
    var obj = jQuery.parseJSON(event.data);
    var close = obj.volume
    var when = obj.datetime;
//  console.log(close,when);
    var a = {"date":parseTime(when),"close":close};
    data.push(a);
    console.log(data);
    updateLine(data);
};

// Preparo la prima sequenza di dati

var data = [
  {"date":"9:22:43.111","close":1.98},
  {"date":"9:23:43.111","close":2},
/*
  {"date":"10:22:43.222","close":5.98},
  {"date":"11:32:43.333","close":7.00},
  {"date":"11:52:43.444","close":8.70},
  {"date":"14:52:43.444","close":10.28},
  {"date":"15:52:43.444","close":16.70},
  {"date":"16:12:43.222","close":10.98},
  {"date":"16:12:43.222","close":3.44},
  {"date":"17:32:43.111","close":4.34},
*/
];

// parse the date / time
var parseTime = d3.timeParse("%H:%M:%S.%L");

//per ogni elemento converto la data
data.forEach(function(d) {
  d.date = parseTime(d.date);
  d.close = +d.close;
});

// Esempio di riferimento per il funzionamento
//http://bl.ocks.org/d3noob/6bd13f974d6516f3e491

// d3js
// Set the dimensions and margins of the graph
var margin = {top: 20, right: 20, bottom: 30, left: 50},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

// Set the ranges
var x = d3.scaleTime().range([0, width]);
var y = d3.scaleLinear().range([height, 0]);

// Define the axes
var xAxis = d3.axisBottom(x)
    .ticks(d3.timeMinute.every(30));

var yAxis = d3.axisLeft(y);

// Define the line
var valueline = d3.line()
    .x(function(d) { return x(d.date); })
    .y(function(d) { return y(d.close); });

// append the svg object to the body of the page
// appends a 'group' element to 'svg'
// moves the 'group' element to the top left margin
var svg = d3.select("body")
    .append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
    .append("g")
        .attr("transform",
            "translate(" + margin.left + "," + margin.top + ")");

// funzione per prmo draw
function drawLine(line_data)
{
    // Scale the range of the data
    x.domain(d3.extent(line_data, function(d) { return d.date; }));
    y.domain([0, d3.max(line_data, function(d) { return d.close; })]);

    // Add the valueline path.
    svg.append("path")
        .attr("class", "line")
        .attr("d", valueline(line_data));

    // Add the X Axis
    svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis);

    // Add the Y Axis
    svg.append("g")
        .attr("class", "y axis")
        .call(yAxis);
}

// funzione per aggiornamento
function updateLine(line_data)
{
    // Scale the range of the data
    x.domain(d3.extent(line_data, function(d) { return d.date; }));
    y.domain([0, d3.max(line_data, function(d) { return d.close; })]);

    // Select the section we want to apply our changes to
    var svg = d3.select("body").transition();

    // Make the changes
    svg.select(".line")   // change the line
            .duration(250)
            .attr("d", valueline(line_data));
    svg.select(".x.axis") // change the x axis
            .duration(250)
            .call(xAxis);
    svg.select(".y.axis") // change the y axis
            .duration(250)
            .call(yAxis);
}

// Disegno i primi dati
drawLine(data);

// Preparo la prima sequenza di dati
/*
var data = [
  {"date":"9:22:43.111","close":2.98},
  {"date":"10:22:43.222","close":3.98},
  {"date":"11:32:43.333","close":4.00},
  {"date":"11:52:43.444","close":7.70},
  {"date":"14:52:43.444","close":11.28},
  {"date":"15:52:43.444","close":15.70},
  {"date":"16:12:43.222","close":12.98},
  {"date":"16:12:43.222","close":2.44},
  {"date":"17:32:43.111","close":1.34},
];

// parse the date / time
var parseTime = d3.timeParse("%H:%M:%S.%L");

//per ogni elemento converto la data
data.forEach(function(d) {
  d.date = parseTime(d.date);
  d.close = +d.close;
});

// Aggiorno i dati
updateLine(data);
*/
</script>
</body>


text:
Q: Material Design in Android SDK 6.0 This is my first time using Android Studio as my IDE in developing Android apps.
I see that my Android Studio's SDK is already version 6.0 (Marshmallow). My question is, by using SDK 6.0, does it already promote Material Design? As in through the SDK, it already has Material Design concepts that were introduced back in 5.0 (Lollipop). I'm planning to design my app using Material Design.
Thank you very much!

A: Kind of. When you create a new project in Android Studio then you will get the Material Theme by default in which your status bar will have the PrimaryColorDark and Toolbar will have the PrimaryColorLight. You can choose and modify your own themes and colors in styles.xml and colors.xml
Also if you crate a new Activity, you will have 2 options in Android Studio - Blank Activity or Empty Activity. If you choose a Blank Activity then you will get the Material design Floating Button already incorporated in your Activity's layout.
So Android Studio does try to help the developer by introducing little Material Design stuff beforehand. But as you go further you'll have to put things yourself. You might have to import the design library like this in your gradle to use some other widgets -
 compile 'com.android.support:design:22.2.0'

See this link to see how to use other Material Design elements in your app.


text:
Q: How can I create a switch statement generator with an arbitrary number of cases using C++ templates? Switch statements can be lengthy, so I wrote the following class (with example usage in main()):
#include <iostream>
using namespace std;

template <typename In, typename Out, In In1, Out Out1, In In2, Out Out2, Out DefaultOut>
struct SwitchMap
{
    Out operator[](const In& input) const
    {
        switch (input) {
        case In1: return Out1;
        case In2: return Out2;
        default: return DefaultOut;
        }
    }
};

int main(int, char **)
{
    SwitchMap<unsigned int, unsigned int, 3, 1, 4, 2, 3> myMap;

    cout << myMap[3] << endl; // prints 1
    cout << myMap[4] << endl; // prints 2
    cout << myMap[5] << endl; // prints 3

    return 0;
}

There are two goals I'd like to achieve:
1. I'd like to make SwitchMap accept an arbitrary number of cases (where the number of Outs is one greater than the number of Ins to provide a default return value). My example only works for two Ins, two Outs, and one default Out.
2. Is it possible to make the declaration for map look like this: SwitchMap<3, 1, 4, 2, 3> myMap;? It would be great if the types could be automatically deduced (although I realize this might result in the compiler choosing int instead of unsigned int, which I'm willing to deal with).
Can I achieve either or both of these goals?

A: Here is an example using if-statements. Note that a good compiler will produce code that is just as efficient as a switch. The result is also constexpr.
#include <iostream>

template <typename T, T DEF>
inline constexpr T SwitchMap_helper(T) {
    return DEF;
}

template <typename T, T IN, T OUT, T... REST>
inline constexpr T SwitchMap_helper(T v) {
    return v == IN ? OUT : SwitchMap_helper<T, REST...>(v);
}

template <typename T, T... CASES>
struct SwitchMap {
    constexpr T operator[](T v) {
        return SwitchMap_helper<T, CASES...>(v);
    }
};

int
main() {

    SwitchMap<int, 1, 2, 3, 4, 5> sm1;
    std::cout << sm1[1] << std::endl;
    std::cout << sm1[3] << std::endl;
    std::cout << sm1[10] << std::endl;
}

A: Here is a little workaround which uses an indirection over a function template:
#include<tuple>
#include<iostream>

template<typename ... Args>
struct SwitchMap
{
    static const size_t ArgsSize = sizeof ... (Args);
    using ArgsTuple = std::tuple<Args ...>;
    using InType = typename std::tuple_element<0,ArgsTuple>::type;
    using OutType = typename std::tuple_element<1,ArgsTuple>::type;

    std::tuple<Args ...> t;
    SwitchMap(Args const& ... args) : t(std::make_tuple(args ...))
    {
        static_assert((ArgsSize & 1) &&  (ArgsSize > 2), " ");
        //here possibly add another check for the consistency of the input types
    }

    template<int> struct int2type{};

    template<int N>
    OutType get(InType const& in, int2type<N>) const
    {
        return in == std::get<N>(t) ? std::get<N+1>(t) : get(in,int2type<N+2>());
    }

    OutType get(InType const& in, int2type<ArgsSize-1>) const
    {
        return std::get<ArgsSize-1>(t);
    }

    OutType operator[](InType const& in) const
    {
        return get(in,int2type<0>());
    }

};

template<typename ... Args>
auto makeSwitchMap(Args const& ... args)
{
    return SwitchMap<Args ...>(args ...);
}

Call it via
int main()
{
    auto switchMap = makeSwitchMap(1,std::string("Say Hi"),2,std::string("Say Goodbye"),std::string("Say nothing"));
    std::cout<<switchMap[1]<<std::endl;
    std::cout<<switchMap[2]<<std::endl;
    std::cout<<switchMap[4]<<std::endl;
}

which produces
Say Hi
Say Goodbye
Say nothing

DEMO


text:
Q: Is it possible to count the number of items in a Haskell list? I am trying to count the number of items in a list in Haskell, but all i can find online is that you can do this only if you are using a value to satisfy the condition.
I was wondering if you can use a generic count :: List -> Int function which will give the number of elements in the list

A: length :: [a] -> Int is a function that returns the length of any list.
For example, length [1, 1, 2, 42, 7] evaluates to 5.


text:
Q: Why $http response data are not shown in angular js? I make a example of directive in  angular js .I am using this directive
https://github.com/ONE-LOGIC/ngFlowchart
when I take static data ..it show the output please check my plunker
http://plnkr.co/edit/d2hAhkFG0oN3HPBRS9UU?p=preview
but when I use $http request and make same json object .it not display the chart see my plunker using $http request .I have same data object as in static
http://plnkr.co/edit/Vts6GdT0NNudZr2SJgVY?p=preview
$http.get('data.json').success(function(data) {
        console.log(data)
        var arr = data
        var model={};

        var new_array = []
        for (var i = 0; i < arr.length; i++) {
            var obj = {};
            obj.name = arr[i].name;
            obj.id = arr[i].id;
            obj.x = arr[i].x;
            obj.y = arr[i].y;
            obj.color = '#000';
            obj.borderColor = '#000';
            var p = {};
            p.type = 'flowchartConstants.bottomConnectorType';
            p.id = arr[i].con_id
            obj.connectors = [];
            obj.connectors.push(p);
            new_array.push(obj);

        }
        console.log('new array')
        console.log(new_array)
          model.nodes=new_array;

        var edge = [];
        for (var i = 0; i < arr.length; i++) {
            if (arr[i].children.length > 0) {

                for (var j = 0; j < arr[i].children.length; j++) {
                    var obj = {};
                    obj.source = arr[i].con_id;
                    obj.destination = arr[i].children[j].con_id;
                    edge.push(obj);
                }

            }

        }
          model.edges=edge;
        console.log(edge)
        console.log("model")
          console.log(JSON.stringify(model))
          $scope.flowchartselected = [];
      var modelservice = Modelfactory(model, $scope.flowchartselected);

    $scope.model = model;
    $scope.modelservice = modelservice;

    })

any update ?

A: Working Example
It is now working.
The issue was when we load the directive first time it has no parameter value to it. So, when the chart directive try to initialize your chart with no parameter it gets an error. So, it will not work anymore.
How solve the issue?
Just give a dummy parameter upon the page load. I have given the dummy model as,
 $scope.model = model;
 $scope.modelservice = modelservice;

So, first your chart will display a chart based on the dummy values. After that it populates chart with the data from the server ($http.get())


text:
Q: Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= I am trying to fetch the data in three tables by using their version columns.
HERE IS MY CODE:
INSERT INTO [dbo].tblCALPLA(ACCOUNT,DATASRC,VERSION)

SELECT ACCOUNT,DATASRC,VERSION FROM [dbo].TBLFACT
WHERE VERSION=(SELECT ID FROM [dbo].VERSION)

UNION

SELECT ACCOUNT,DATASRC,VERSION FROM [dbo].TBLFACT1
WHERE VERSION=(SELECT ID FROM [dbo].VERSION)

UNION

SELECT ACCOUNT,DATASRC,VERSION FROM [dbo].TBLFACT2
WHERE VERSION=(SELECT ID FROM [dbo].VERSION)

A: In all your WHERE conditions, instead of
WHERE Version = (SELECT ID ...)

make use of
WHERE Version IN (SELECT ID...)


text:
Q: Set the actual priority tag? There are questions tagged multiple languages, and there are many of them. Occasionally, I come across some where it's an issue. Not a huge issue, but an issue nevertheless. There are two instances of this issue:

*

*The question applies to multiple languages, but the code sample is in a particular language. This currently requires manual re-highlighting with <!-- language: lang-therightlanguage -->as far as I know. I'd like to be able to just move the right language to the front.

*The question involves two components but is really about one particular tag. Take this question for example. It's tagged both php and javascript but php takes priority. It shouldn't. It can be solved using PHP, but it's not about PHP, it's about JavaScript. And "php" appears in the title, which I can't fix with a comment unless I'm missing something. It's possible that the php tag should be removed entirely, but that's not the question right now :)
So, can there be a way to prioritize or rearrange tags? Maybe by appending a ! to the end of the tag name, for example? Or is there a better way to go about this?

A:
The question applies to multiple languages, but the code sample is in a particular language. This currently requires manual re-highlighting

That's usually not true: when two different language tags occur on a question, the syntax highlighter switches back to autodetecting the language. So you should only have trouble when the language actually being used can't be auto-detected (for instance: VB).
The title thing is a can of worms, but as Jeff notes in a comment it's easy to avoid if you exclude tags that aren't actually relevant. And if all the code is in JavaScript, it's pretty hard to argue that the question is about PHP... Still, if all else fails, just edit the title: instead of a stupid prefix, work both tags in organically. Example:

How to avoid writing $(document).ready() in each JavaScript file in my PHP app?

If you do this, the system won't prefix the title with either tag.


text:
Q: Smooth Sobolev extension from $W^{1,p}(U)$ to $W^{1,p} (\mathbb{R}^n) $  The question I would be asking is roughly : do the smooth Sobolev functions defined on an open bounded domain extend to smooth Sobolev functions on the Euclidean space ?
For detail :
Fix $p \geq 1.  $  By the word 'smooth', I will always mean $C^{\infty}$ .Let $U, V$ be two bounded, connected open domains in $ \mathbb{R}^n $ with smooth boundary, so that $\bar{U}\subset V $. Let $u \in W^{1,p}(U)   \cap C^0(\bar{U})  $. In many PDE books ( for example , L.C. Evans'        "Partial Differential Equations", P. 254 )
there are standard methods described to produce an extension $Eu$ of $u$ such that :
$Eu \in W^{1,p}(\mathbb{R}^n), support (Eu) \subset V, Eu = u  $ a.e.on $U$ . The method is first to treat the case where $u \in W^{1,p}(U)   \cap C^0(\bar{U}) \cap C^{\infty}(\bar{U}) $ ,locally flatten the boundary $ \partial{U} $, extend $u$ by higher order reflection across the boundary, using partition of unity and then approach arbitrary $u \in W^{1,p}(U) $ by $C^{\infty}(\bar{U})$ functions in $W^{1,p}(U)$ -norm. We do not even need $ u \in C^0(\bar{U}) $ in this proof .
I understand that if $u \in C^{\infty}(\bar{U}) $as well. , then $Eu \in C^\infty(\mathbb{R}^n)$, but is the same true if $u \in C^{\infty}(U) \cap C^0(\bar{U}) $ only, not $C^{\infty}(\bar{U})$ ? This is my main question.

A: To my taste, the cleanest approach to the extension problem is contained in Stein's 1970 book "Singular integrals and differentiability properties of functions". For a bounded open set with Lipschitz boundary, he constructs a 'universal' extension operator which, when applied to a $W^{k,p}$ function on the open set, produces a $W^{k,p}$ function on the whole space, with support in a fixed neighbourhood, and suitable bounds on the norm. The method also works if the set is unbounded, provided some uniform bounds at infinity are assumed on the coordinate patches at the boundary. It is not necessary at any step to assume continuity or smoothness up to the boundary.
As Pietro mentions in his answer, the extension property is blatantly false if the boundary contains inward cusps, but I understand from your question that your boundary is smooth hence at least Lipschitz.

A: Extension is a well studied topic in the theory of Sobolev spaces, included in any treatise on the topic. Have a look e.g. to Adams' Sobolev spaces, Chapter 4 (Interpolation and Extension theorems). For positive results, you need geometric properties of domains.


text:
Q: SSRS Complex Dataset Filtering I have couple of complex conditions in my stored procedure, e.g.
if @Acr != '' and @Acr != '<Select All>'
begin
delete from #temp where O_client != @Acr and O_originreason != 'RTE'
end

if @Acr = '<Select All>'
begin
delete from #temp where LEFT(O_client, 5) = 'WS80_'
                    AND O_client IS NULL
                    AND O_originreason != 'RTE'
end

if @Chnl != '' and @Chnl != '<Select All>'
begin
delete from #temp where C_Channel != @Chnl
end

and I want to get rid of it, and reimplement it in DataSet filter in reports. But I can't understand how to build such complex conditions.

A: Okay I did it.
I've made an expression that returns bool and compare it with true


text:
Q: AngularJS - Creating Ad Hoc Web Form from Metadata I've been struggling with a problem that involves building a web form to input answers to questions provided in a JSON resource.
Here's the plunk: http://plnkr.co/edit/HX11iHdA5kM2yJzDcSTb
This plunk is a prototype for generating a web form based on structured meta data. A sample of the question meta-data is in-lined in the controller. I've assigned it to a questions variable of the model, and provided a second model object called "answers" where I want to bind the data input into the rendered form.
My goal is to add each question to the answers object as a new property. But I'm stuck on getting the data input into the rendered form bound to the model.
The problem is that I am unable to successfully bind the particular question to the ng-model. The problematic area of the code is in the Link function of the fsQuestionnaireQuestion directive:
var modelLinkId = scope.question.linkId;
var modelAccessor = scope.ngModel + $parse(modelLinkId);

function updateModel() {
  var val = element.value;
  scope.$apply(function(scope) {
    modelAccessor.assign(scope, val);
  });
}

scope.$watch(modelLinkId, function(val) {
  element.value = val;
  });

element.bind('change', updateModel);

The form renders fine, but when I input data into any of the form elements, I get back an "undefined is not a function" error.

A: The second line of your snipped:
var modelAccessor = scope.ngModel + $parse(modelLinkId);

is concatenating 2 objects, so the result (modelAccessor) will be a string, not the "Model" object that I guess that you were expecting.
I think that you wanted that line to be like this:
var modelAccessor = $parse(modelLinkId);


text:
Q: Move email after being categorized I want to move emails, once they are categorized, into a folder with the same name as the category.
What I found so far:
Private WithEvents Explorer As Outlook.Explorer
Private WithEvents Mail As Outlook.MailItem
Private MoveToThisFolder As Outlook.MAPIFolder

Friend Sub Application_Startup()
  On Error Resume Next
  Set Explorer = Application.ActiveExplorer
End Sub

Private Sub Explorer_SelectionChange()
  Dim obj As Object
  Dim Sel As Outlook.Selection

  Set Mail = Nothing
  Set Sel = Explorer.Selection

  If Sel.Count > 0 Then
    Set obj = Sel(1)
    If TypeOf obj Is Outlook.MailItem Then
      Set Mail = obj
    End If
  End If
End Sub

Private Sub Mail_PropertyChange(ByVal Name As String)
  Dim Ns As Outlook.NameSpace
  Dim Inbox As Outlook.MAPIFolder
  Dim Subfolder As Outlook.MAPIFolder
  Dim SubfolderName As String

  If Name = "Categories" Then
    Set Ns = Application.GetNamespace("MAPI")
    Set Inbox = Ns.GetDefaultFolder(olFolderInbox)
    SubfolderName = Mail.Categories
    If Len(SubfolderName) = 0 Then Exit Sub
    Set Subfolder = Inbox.Folders(SubfolderName)
    If Subfolder.EntryID <> Mail.Parent.EntryID Then
      Set MoveToThisFolder = Subfolder
      EnableTimer 500, Me
    End If
  End If
End Sub

Friend Sub TimerEvent()
  DisableTimer
  If Mail Is Nothing Then Exit Sub
  If MoveToThisFolder Is Nothing Then Exit Sub
  Mail.Move MoveToThisFolder
  Set Mail = Nothing
  Set MoveToThisFolder = Nothing
End Sub

I have some problems with respect to Friend Sub TimerEvent () because it gives me

Sub or Function not compiled correctly

A: At the end i figured out in this way:
    Private WithEvents xInboxFld As Outlook.Folder
Private WithEvents xInboxItems As Outlook.Items

Private Sub Application_Startup()
    Set xInboxFld = Outlook.Application.Session.GetDefaultFolder(olFolderInbox)
    Set xInboxItems = xInboxFld.Items
End Sub

Private Sub xInboxItems_ItemChange(ByVal Item As Object)
Dim xMailItem As Outlook.MailItem
Dim xFlds As Outlook.Folders
Dim xFld As Outlook.Folder
Dim xTargetFld As Outlook.Folder
Dim xFlag As Boolean
On Error Resume Next
If Item.Class = olMail Then
    Set xMailItem = Item
    xFlag = False
    If xMailItem.Categories <> "" Then
        Set xFlds = Application.Session.GetDefaultFolder(olFolderInbox).Folders
        If xFlds.Count <> 0 Then
            For Each xFld In xFlds
                If xFld.Name = xMailItem.Categories Then
                    xFlag = True
                End If
            Next
        End If
        If xFlag = False Then
            Application.Session.GetDefaultFolder(olFolderInbox).Folders.Add xMailItem.Categories, olFolderInbox
        End If
        Set xTargetFld = Application.Session.GetDefaultFolder(olFolderInbox).Folders(xMailItem.Categories)
        xMailItem.Move xTargetFld
    End If
End If
End Sub

Hope it could help!!!

A: The error is due to missing code for DisableTimer and EnableTimer.
The category has not yet updated when the code is triggered.
EnableTimer delays the move until after the category updates.
Without a delay, there would be an error when attempting to update, due to the item having been moved.
Attribution: http://www.vboffice.net/en/developers/trigger-actions-with-categories/


text:
Q: Passing new selected value as parameter to 'onchange' method on rich:autocomplete I want to use <rich:autocomplete> to select an item from a list and call an action method when a new value is selected (using this new value in the method).
I have something like this:
<rich:autocomplete mode="cachedAjax" minChars="2"
    autocompleteMethod="#{bean.autocompleteMethod}"
    fetchValue="#{var.name}"
    var="var">
    <rich:column>
        <h:outputText value="#{var.name}" />
    </rich:column>
</rich:autocomplete>

The autocomplete method returns a MyObject list:
public List<MyObject> autocompleteMethod(String prefix){
    //...
    return results;
}

I want to make a method which is called when a new list value is selected but all I have tryed didn't work because I don't know how can I pass the new selected value to the bean.
I have tryed using onchange="changeMethod('#{var.id}')" and making a function like:
<a4j:jsFunction name="changeMethod"
    action="#{bean.changeMethod}">
    <a4j:param name="param1" assignTo="#{bean.idParam}" />
</a4j:jsFunction>

It doesn't work with onselectitem too, the 'idParam' is always null.
How can I have this new selected value in the method?
Thx

A: There's a simpler way.
<rich:autocomplete autocompleteMethod="#{bean.autocompleteMethod}" value="#{bean.value}">
    <a4j:ajax event="selectitem" />
</rich:autocomplete>

The ajax makes sure the value updates when it is selected. If you're working with something else than a String you can use a converter:
@FacesConverter("someConverter")
public class SomeConverter implements Converter {

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        // find/create object by name;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value {
        return ((MyObject) value).getName();
    }

}


text:
Q: Date filter on One Drive Graph API not working I have following date filter query on one drive with greater than operator.
lastModifiedDateTime gt 2020-08-29T10:48:41.000Z

https://graph.microsoft.com/v1.0/me/drive/root/search(q='test')?filter=lastModifiedDateTime%20gt%202020-08-29T10%3A48%3A41.000Z

But it always returns empty result. I have following file detail displaying on one drive.
Type: SRT File
Modified: 8/29/2020 04:40 PM
Added: by me
Date created: 8/29/2020 04:39 PM
Path: My file > stest
Size: 101 KB

Just additional info. I am able to access all files using following url.
https://graph.microsoft.com/v1.0/me/drive/root/children


text:
Q: Laravel 4 on MAMP won't work without index.php in URL Since updating my virtual host so I can view my app at dev.mysite.com instead of the previous localhost/mysite/public, I cannot get the app to have 'pretty urls'.
It will only work if I use dev.mysite.com/index.php/register
How can I revise my settings so I can view at dev.mysite.com/register
HTACCESS
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes...
    RewriteRule ^(.*)/$ /$1 [L,R=301]
    RewriteEngine On

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

ROUTES.PHP
Route::get('register', array('uses' => 'UserController@create'));

HTTPD-VHOSTS.CONF
NameVirtualHost *
<VirtualHost *>
    DocumentRoot "/Applications/MAMP/htdocs"
    ServerName localhost
</VirtualHost>
<VirtualHost *>
    DocumentRoot "/Applications/MAMP/htdocs/mysite/public"
    ServerName dev.mysite.com
</VirtualHost>


text:
Q: Подключить Wordpress API к скрипту PHP Есть Wordpress и файл api.php
Требуется подключить функции wordpress к файлу api.php, чтобы оттуда можно было вызывать функции типа
$field = get_post_field( 324 );
echo $field;

и тд.
Собственно, как это сделать?
Погуглил и нашел этот вариант.
Но при вызове функции Wordpress выдает ошибку HTTP 500 ERROR:
<?php

include_once 'wordpress/wp_load.php';

$field = get_post_field( 372 );
echo $field;

A: Укажите полный путь к файлу:
require($_SERVER['DOCUMENT_ROOT'].'/wp-load.php');

A: Всем спасибо за помощь все получилось.
Скидываем скрипт в папку темы, и пишем туда вот это.
Вот код :
<?php

$path = preg_replace('/wp-content(?!.*wp-content).*/','',__DIR__);
include($path.'wp-load.php');
$post = get_post( 393 );
echo $post->post_title;

?>


text:
Q: C++: how to print all elements in a vector of vectors I read from a file some number and put them in a graph (called grafo) with this code:
struct node{
    vector<int> vic;
    bool visitato = false;
};

int main (){
    vector<node> grafo;
    ifstream in("input.txt");
    int n, m, s, from, to;
    in >> n >> m >> s;
    grafo.resize(n);
    for (int i = 0; i < m; i++){
        in >> from >> to;
        grafo[from].vic.push_back(to);
    }
}

How can I print all those elements?
Here's the input txt file:
0 2
0 4
1 4
3 2
2 4
4 3

I think I have to print all (sub) vectors for each vector, so I tried with something like this:
for (int i = 0; grafo.size() < n; i++)
        for(int j = 0; j < grafo[i].vic.size(); j++)
            cout << "From node " << i << " to node " << grafo[i].vic[j] << endl;

Any advice?
EDIT: ot, it works but I'm not sure I really got what I did and why is it working.

A: The condition, i.e. grafo.size() < n, in the for-loop will always be false, which is not what you want.
Change
for (int i = 0; grafo.size() < n; i++)
                ^^^^^^^^^^^^^^^^

to
for (int i = 0; i < grafo.size(); i++)

A: You'd better use vector iterator.
 using namespace std;
  struct node{
      vector<int> vec;
      bool visitato = false;
  };
  int main()
  {
      vector<node> grafo;
      int n,m,s,from,to;
      ifstream in("input.txt");
      in>>n>>m>>s;
      grafo.resize(n);
      for (int i = 0; i < m; i++){
          in >> from >> to;
          grafo[from].vec.push_back(to);
      }
      int i=0,j=0;
      for ( auto it = grafo.begin(); it != grafo.end(); ++it, ++i){
          for ( auto it2 = it->vec.begin(); it2 != it->vec.end(); ++it2, ++j){
              cout << "From node " << i << " to node " << *it2 << endl;
          }
      }
      return 0;
  }

A: You may want to use https://github.com/gileli121/VectorEx
In this library you have display function that display vector of vectors.
It works under windows (tested on windows 7) and developed under in visual studio 2015.
This example shows you how to use it:
// includes.functions
#include <windows.h>

// Include CU3 Library
// Get the files from https://github.com/gileli121/CU3-Library/
#include "CU3_Library\EasyCoding\easy_macros.h"

// Include VectorEx https://github.com/gileli121/VectorEx
#include "VectorEx\VectorEx.h"
#include "VectorEx\VectorDisplay.h"
using namespace vectorex;
using namespace vectordisplay;

/*

Example 1 - Manually make vector of vectors and then show it with vectordisplay::DisplayVector_OfVector

    This example shows how to use display std::vector of std::vector(s) array datatype
    with vectordisplay::DisplayVector_OfVector
*/

int main()
{

    std::vector<std::vector<std::string>> stringVecofvec; // Create Vector of std::string vectors

    DisplayVector_OfVectors(&stringVecofvec); // Display it
    /*
        As you can see, you get list view that is completely gray with nothing in it.
        This is because that the vector (that intended to contains other vectors)
        have 0 size.

        So we resize this main vector to 10 in the next step.
    */

    stringVecofvec.reserve(20); // Allocate space for 20 vectors
    stringVecofvec.resize(10); // Resize the main vector to 10. so will be space for 10 vector in it.

    DisplayVector_OfVectors(&stringVecofvec); // Display it
    /*
        As you can see, now the list view is not completely empty. you will see vector 0 - vector 9 (10 vectors)
        It shows the room for the 10 vectors.

        Also, you will see that after vector 9, there is unamed columns and the last one named with the number 19.
        This is visualize the stringVecofvec.capacity() - the reserved space.
        Remember that we was call "stringVecofvec.reserve(20);" ? this is why you see 19. (0-19 is 20)

        However, the list view is still completely gray. because all the 10 vector inside the main vector
        is 0 size.

        So we resize some few vector (few vectors of 0-9 ) to random sizes.
    */

    stringVecofvec[0].reserve(30); // Reserve space for 30 rows in vector 0
    stringVecofvec[0].resize(5); // Resize vector 0 to 5.

    stringVecofvec[1].reserve(20); // Reserve space for 20 rows in vector 1
    stringVecofvec[2].reserve(13); // Reserve space for 13 rows in vector 2

    stringVecofvec[3].resize(10); // And resize vector 3 to 10

    stringVecofvec[5].reserve(15); // Reserve space for 15 rows in vector 5

    stringVecofvec[6].resize(15); // And resize vector 6 to 15

    stringVecofvec[7].reserve(27); // Reserve space for 27 rows in vector 7

    stringVecofvec[9].reserve(24);// Reserve space for 10 rows in vector 9

    stringVecofvec[9].resize(6); // And resize vector 9 to 6

    DisplayVector_OfVectors(&stringVecofvec); // Display it
    /*
        As you can see, now not everything is gray. you will see some vectors that colored in white color,
        some with Grey-Blue color and some that completely gray.

        The vectors that are completely gray are those that with size 0. others have size that is bigger
        then 0.

        The size of each vector is visualized by the number of the white columns.
        For example, in this case - vector 0 will have 5 white columns, and vector 6 will have 15 white columns.

        The reserved size / .capacity() is visualized by the Grey-Blue color.

        Vector with 0 size have no white columns. only gray.
        Vector with 0 size but it's .capacity() bigger then 0 have only Grey-Blue color.

        The .size() of the vector can never be bigger then the .capacity(). so if the .capacity() is 0,
        the vector will have only gray color.

                                    .size() visualized by white color
                                    .capacity() visualized by Grey-Blue color

                                        out of this range is unallocated memory zone
                                        unallocated memory zone start where the .capacity() ends.

                                    unallocated memory zone is visualized by Gray color.

                                    reserved space for vector is visualized by on row and col of green color

        In the next step will fill some vectors with data. You can fill data only on areas with white color.
    */

/*
    Liked this example? Did that helped you? If so, you can also thanks by giving a small contribution
    https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=S2KFGDTQZG4XQ
*/

    // Fill data in vector 0
    stringVecofvec[0].at(0) = "HELLO"; //       Fill data in vector 0 -> row 0
    stringVecofvec[0].at(4) = "VECTORS!"; //    Fill data in vector 0 -> row 4
        /*
            Try to add stringVecofvec[0].at(5) = "TEST";
            It will not work because you try to fill data in no-space
            you can fill data only in space.

        */

    // Fill data in vector 3 ()
    stringVecofvec[3].at(4) = "OF";  //         Fill data in vector 3 -> row 4
    stringVecofvec[3].at(0) = "WORLD"; //       Fill data in vector 3 -> row 0
    stringVecofvec[3].at(8) = "VERY"; //        Fill data in vector 3 -> row 8

    /*
            you can't fill data in vector 2. it have 0 size.
            But you can try different thing that will work.

            Try to add here:
            stringVecofvec[2].push_back("TEST");

            What will happen here is that it will use the reserved space that
            is visualized by Grey-Blue color and write in the text in the next available
            *unused* reserved space

    */

    // Fill data in vector 6
    stringVecofvec[6].at(4) = "VECTORS"; //     Fill data in vector 6 -> row 4
    stringVecofvec[6].at(0) = "OF MANY"; //     Fill data in vector 6 -> row 0
    stringVecofvec[6].at(14) = "EASY :)"; //    Fill data in vector 6 -> row 14

    // Fill data in vector 9
    stringVecofvec[9].at(4) = "EXAMPLE !"; //   Fill data in vector 9 -> row 4
    stringVecofvec[9].at(0) = "VECTORS !"; //   Fill data in vector 9 -> row 0

    /*
        Try to add here
        stringVecofvec[9].push_back("TEST");

        If you do not know how vectors works, you may expect that it will add
        "TEST" in row 5.

        This is not true. It will add it in row 6.
        .push_back looks for the next *unused* reserved space.
        the next *unused* reserved space is available in row 6 that colored in Grey-Blue color.

        After that, unused become used so it colored in white with the text in it.

    */

    DisplayVector_OfVectors(&stringVecofvec); // Display it
    /*
        Is it looks much more beautiful than this ugly black console?

        Enjoy.
    */
    return 0;
}

Here is an image of the final output:


text:
Q: Vertically aligned table in plainTeX / LaTeX / Context etc My last answer about vertically aligned table inspired me to write my first
question at this site. How to create the following table in various TeX
approaches: plainTeX, LaTeX, Context, eplain, OPmac etc.? The comparison
would be welcome.
The table has given column widths, each data item is vertically centered,
some data items can be vertically spanned and vertically centered in its
space. Data items are one of the two types: single centered line in the column or the paragraph. There are single lines between columns and between lines. The table looks like:

It would be fine to separate the code to two parts: first part will be signed as
% macro code created by the macro programmer and/or typo designer.
The second part is signed as % document and the author of the text is
supposed to write it.
I'll give the answer for plainTeX (this is my domain). I am looking forward to another approaches.
As a bonus you can try to create the table from my book
TeXbook inside out
(full text is available here) from the page 142.
The vertical aligning is here too: the last but one line is vertically
centered and the the last line is aligned to the top.
Edit I am still waiting for LaTeX solution. One user mentioned in comments that this is worse aspect from typographical point of view. But I am not evaluating the typographical quality of many examples presented at tex.stackexchange. Why do it with this special case? For example, my customer asked me for creating the following excel-like table:

This is not used for printing in book but only as a tool printed on paper sheets to do data more transparent. This is typical example for \valign usage.

Is there a LaTeX approach to do this? LaTeX is mentioned here in 98 % of threads. Can we found somebody to explain this from LaTeX point of view? Or LaTeX isn't able to do it (without absorbing the plain TeX solution)?

Note: the vertical-alignment tag includes 1030 threads. What can be more natural than \valign primitive for such request...
Today, there is very similar question Different vertical alignment with multirow.

A: The plainTeX approach is here.
This is my answer from here slightly improved. Two new features are here:

*

*The code is divided to the macro part (done by macro programator) and
document part (done by author).

*The author can set the width of each column used in the table.

The code
% Macro code (by programator and designer)
\newcount\tmpnum
\def\setcolumnsA #1,{\if,#1,\else \advance\tmpnum by1 \dimen\tmpnum=#1
   \expandafter \setcolumnsA \fi
}
\def\vtable #1#2{\vbox{\hbox{%
   \tmpnum=180 \setcolumnsA #1,,\tmpnum=180
   \everycr={\noalign{\vrule \global\advance\tmpnum by1}}%
   \valign{&\hrule\vfil\vbox{\setrowparams\topstrut##\unskip\botstrut}\vfil\crcr
   #2\crcr}}\hrule}%
}
\def\multirow#1#2{\multispan{#1}\hrule\vfil\vbox{\setrowparams\topstrut#2\botstrut}\vfil}
\def\topstrut{\vbox to3ex{}} \def\botstrut{\vtop to2ex{}}
\def\setrowparams{\hsize=\dimen\tmpnum \leftskip=.5em \rightskip=\leftskip
   \ifdim\hsize=0pt \hsize=100pt \message{WARNING: the columnwidth is not set.}\fi
   \emergencystretch=2em \noindent\hfil}
\let\dopar=\hfilneg  % the items of paragraph format are prefixed by \dopar

% document (by author):
\def\blah{blah blah blah blah blah blah blah blah}
\def\blahh{\blah\ \blah\ \blah\  blah blah blah}

\vtable{25mm,25mm,40mm}{
   Type   & & \multirow3{Spring} \cr
   Specs  & Model 1 & Model 2 & Model 3 & Model 4 \cr
   Uses   & \dopar\blah & \dopar\blahh & \dopar\blah & \dopar blah blah \blah\ blah \cr
}

\end

You can process it by tex document or pdftex document. The result is the
same as the table given in the question.

A: Here's a LaTeX solution:
\documentclass{article}
\usepackage{array,multirow}

\newcommand*\blah{blah blah blah blah }

\newcolumntype{z}[1]{>{\centering\arraybackslash}m{#1}}% a centered m-type column
\renewcommand*\multirowsetup{\centering}% default is \raggedright

\begin{document}

\begin{tabular}{|z{2cm}|z{2cm}|m{.3\linewidth}|}
  \firsthline
    \bfseries Type &
    \multicolumn{1}{c|}{\bfseries Specs} &
    \multicolumn{1}{c|}{\bfseries Uses} \\
  \hline
    & Model 1 & \blah\blah \\
  \hline
    \multirow{3}*[-2\baselineskip]{Spring}
    & Model 2 & \blah\blah\blah\blah\blah blah blah blah \\
  \cline{2-3}
    & Model 3 & \blah\blah \\
  \cline{2-3}
    & Model 4 & \blah\blah blah blah blah \\
  \lasthline
\end{tabular}

\end{document}

The »Spring« in the \multirow needed some vertical shift (the optional argument [-2\baselineskip]). If this is necessary depends on the actual use case and is explained in the manual.
Even easier and without the need for manual interference is using nested tabulars. We just need to suppress the space to the left and right of the inner tabular by inserting @{} to the column specs:
\documentclass{article}
\usepackage{array}

\newcommand*\blah{blah blah blah blah }

\newcolumntype{z}[1]{>{\centering\arraybackslash}m{#1}}

\begin{document}

\begin{tabular}{|z{2cm}|z{2cm}|m{.3\linewidth}|}
  \firsthline
    \bfseries Type &
    \bfseries Specs &
    \multicolumn{1}{c|}{\bfseries Uses} \\
  \hline
    & Model 1 & \blah\blah \\
  \hline
    Spring &
    \multicolumn{2}{@{}c@{}|}{%
      \begin{tabular}{z{2cm}|m{.3\linewidth}}
          Model 2 & \blah\blah\blah\blah\blah blah blah blah \\
        \hline
          Model 3 & \blah\blah \\
        \hline
          Model 4 & \blah\blah blah blah blah \\
      \end{tabular}%
    } \\
  \lasthline
\end{tabular}

\end{document}

The output is the same.

A: With ConTeXt:
\def\blah{blah blah blah blah }
\switchtobodyfont[10pt]
\starttext
\bTABLE
  \setupTABLE[offset=1em]
  \setupTABLE[column][each][align={middle, lohi}]
  \setupTABLE[column][3][align=right, width=.3\textwidth]
  \bTABLEhead
    \bTR\bTH Type\eTH         \bTH Specs\eTH   \bTH[align=middle] Uses\eTH\eTR
  \eTABLEhead
  \bTABLEbody
    \bTR\bTD\eTD              \bTD Model 1\eTD \bTD \blah\blah \eTD\eTR
    \bTR\bTD[nr=3] Spring\eTD \bTD Model 2\eTD \bTD \blah\blah\blah\blah\blah\blah blah blah blah \eTD\eTR
    \bTR                      \bTD Model 3\eTD \bTD \blah\blah \eTD\eTR
    \bTR                      \bTD Model 4\eTD \bTD \blah\blah blah blah blah \eTD\eTR
  \eTABLEbody
\eTABLE
\stoptext

which looks like

A: I would show the solution based on OPmac. This macro package provides the
\table command to create tables. Of course it uses \halign primitive.
The following solution defines the \vtable alternative for \table based
on \valign primitive. It redefines locally a few internal macros from
OPmac. This is done in the \vtabledefs macro. A \vrule <-> \hrule,
\vfil <-> \hfil etc. changes are performed here.
The user (in % document part) of the code can enjoy the OPmac table features,
for example the non-intersected double lines.
% macros:
\input opmac

\def\vtable{\hbox\bgroup \catcode`\|=12 \vtabledefs \tableB}
\def\tableB#1#2{\offinterlineskip \def\tmpa{}\tabdata={}\scantabdata#1\relax
   \valign\expandafter{\the\tabdata\tabstrutA\cr#2\crcr}\egroup}
\def\vtabledefs{%
   \let\dopar=\hfilneg  % the items of paragraph format are prefixed by \dopar
   \def\setrowparams{\hsize=\dimen\tmpnum \leftskip=.5em \rightskip=\leftskip
      \normalbaselines \hsize=\tmpdim
      \emergencystretch=2em \noindent\hfil}%
   \def\topstrut{\vbox to3ex{}}\def\botstrut{\vtop to2ex{}}%
   \def\tabstrut{}%
   \def\multirow##1##2{\multispan{##1}\vfil\vbox{\setrowparams\topstrut##2\botstrut}\vfil\hrule}%
   \def\crl{\crcr\noalign{\vrule}}%
   \def\colw=##1 {\noalign{\global\tmpdim=##1}}%
   \def\addtabvrule{\ifx\tmpa\vrule \addtabdata{\kern\hhkern}%
      \ifnum\colnum=0\def\vvleft{\vvitem}\else\addto\ddlinedata{\vvitem}\fi\fi
      \let\tmpa=\vrule \addtabdata{\hrule}}%
   \def\crli{\crcr \omit \gdef\dditem{\omit\tablinefil}\gdef\vvitem{\tabvvline}%
      \vvleft\tablinefil\ddlinedata\cr}%
   \def\tablinefil{\leaders\vrule\vfil}%
   \def\tabvvline{\hrule\kern\hhkern\hrule}%
   \def\crlli{\crli\noalign{\kern\vvkern}\crli}%
   \tmpdim=100pt
   \def\tabdeclarec{\medskip\vfil\vbox{\setrowparams\topstrut####\unskip\botstrut}\vfil\medskip}%
}
\def\vvkern{2pt} \def\hhkern{2pt}

% document:

\def\blah{blah blah blah blah blah blah blah blah}
\def\blahh{\blah\ \blah\ \blah\  blah blah blah}

\frame{\vtable{|c||c||c|c|c|}{\crli
   \colw=20mm Type  & & \multirow3{Spring} \crlli
   \colw=20mm Specs & Model 1 & Model 2 & Model 3 & Model 4 \crlli
   \colw=40mm Uses  & \dopar\blah & \dopar\blahh & \dopar\blah & \dopar\blah\ blah \crli
}}
\bye

OPmac provides colors too. Then the second example uses this feature. The
\vtabledefs is similar as above but new macros for colorization
backgrounds of the items are added. Use pdftex to process it.
% macros:
\input opmac

\def\vtable{\hbox\bgroup \catcode`\|=12 \vtabledefs \tableB}
\def\tableB#1#2{\offinterlineskip \def\tmpa{}\tabdata={}\scantabdata#1\relax
   \valign\expandafter{\the\tabdata\tabstrutA\cr#2\crcr}\egroup}
\def\vtabledefs{%
   \let\dopar=\hfilneg  % the items of paragraph format are prefixed by \dopar
   \def\setrowparams{\hsize=\dimen\tmpnum \leftskip=.5em \rightskip=\leftskip
      \normalbaselines \hsize=\tmpdim
      \emergencystretch=2em \noindent\hfil}%
   \def\topstrut{\vbox to3ex{}}\def\botstrut{\vtop to2ex{}}%
   \def\tabstrut{}%
   \def\crl{\crcr\noalign{\vrule}}%
   \def\colw=##1 {\noalign{\global\tmpdim=##1}}%
   \def\addtabvrule{\ifx\tmpa\vrule \addtabdata{\kern\hhkern}%
      \ifnum\colnum=0\def\vvleft{\vvitem}\else\addto\ddlinedata{\vvitem}\fi\fi
      \let\tmpa=\vrule \addtabdata{\hrule}}%
   \def\crli{\crcr \omit \gdef\dditem{\omit\tablinefil}\gdef\vvitem{\tabvvline}%
      \vvleft\tablinefil\ddlinedata\cr}%
   \def\tablinefil{\leaders\vrule\vfil}%
   \def\tabvvline{\hrule\kern\hhkern\hrule}%
   \def\crlli{\crli\noalign{\kern\vvkern}\crli}%
   \tmpdim=100pt
   \def\tabdeclarec{\medskip\vfil\vbox{\setrowparams\topstrut####\unskip\botstrut}\vfil\medskip}%
}
\def\vvkern{2pt} \def\hhkern{4pt}

\def\spancolor#1#2{\multispan{#1}{\localcolor#2\kern\vvkern\leaders\hrule width\tmpdim \vfil\kern\vvkern}}
\def\multirow#1#2{\multispan{#1}\vfil\vbox{\setrowparams\topstrut#2\botstrut}\vfil}%

\def\colitem#1{\omit{\localcolor#1\kern\vvkern\leaders\hrule width\tmpdim \vfil\kern\vvkern}}
\def\crc{\crcr\noalign{\global\advance\tmpdim by-\hhkern \hskip-\tmpdim \global\advance\tmpdim by-\hhkern}}
\def\crx{\crcr\noalign{\hskip\hhkern\hskip\hhkern}}

% document:

\def\blah{blah blah blah blah blah blah blah blah}
\def\blahh{\blah\ \blah\ \blah\  blah blah blah}

\def\itemcolors#1#2#3#4#5{\colitem#1&\colitem#2&\colitem#3&\colitem#4&\colitem#5\crc}

\def\liRed{\setcmykcolor{0 .5 .5 0}}
\def\liBlue{\setcmykcolor{.3 .3 0 0}}
\def\liGreen{\setcmykcolor{.5 0 .5 0}}
\def\liOrange{\setcmykcolor{0 0.2 0.5 0}}
\def\liCyan{\setcmykcolor{.3 0 0 0}}

\vtable{ccccc}{
   \colw=20mm \colitem\liGreen & \colitem\liGreen & \spancolor3\liOrange \crc
   Type  & & \multirow3{Spring} \crx
   \colw=20mm \itemcolors\liRed\liBlue\liRed\liBlue\liRed
   Specs & Model 1 & Model 2 & Model 3 & Model 4 \crx
   \colw=40mm \itemcolors\liCyan\Yellow\liCyan\Yellow\liCyan
   Uses  & \dopar\blah & \dopar\blahh & \dopar\blah & \dopar\blah\ blah \crx
}
\bye

A: An easy solution with tblr environment of the new LaTeX package tabularray:
\documentclass{article}

\usepackage{tabularray}

\newcommand*\blah{blah blah blah blah }

\NewColumnType{z}[1]{Q[m,c,#1]}% a centered m-type column

\begin{document}

\begin{tblr}{
  colspec ={|z{2cm}|z{2cm}|m{0.3\linewidth}|},
  row{1} = {c,font=\bfseries},
  cell{3}{1} = {r=3}{m,c}, % multirow
  hlines,
}
  Type   & Specs   & Uses \\
         & Model 1 & \blah\blah \\
  Spring & Model 2 & \blah\blah\blah\blah\blah blah blah blah \\
         & Model 3 & \blah\blah \\
         & Model 4 & \blah\blah blah blah blah \\
\end{tblr}

\end{document}

A: I always like the simplest way (little cheating), but this will work:
    \begin{table}
\begin{tabular}{|m{1cm}|m{3cm}|m{3 cm}|}
  \toprule
 Type & Specs & Uses \\
  \midrule
 & Model 1 & blah blah blah blah blah \\ \cline{1-3}
  & Model 2 & blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah \\ \cline{2-3}
Spring & Model 3 & blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah \\ \cline{2-3}
& Model 4 & blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah \\
\bottomrule
\end{tabular}
\end{table}


text:
Q: Function pointers in Inno Setup Are function pointers supported in Inno Setup?  I can't find anything in the documentation.  I know Delphi/Pascal supports them and as the Inno Setup scripting engine is based on it, I'm hoping it is supported.

A: I just did a little test and function pointers do work indeed. The following [Code] section compiles and works just fine:
type
  TStrProc =  procedure (const AStr: String);

procedure Call(const AProc: TStrProc; const AStr: String);
begin
  AProc(AStr);
end;

procedure ShowStr(const AStr: String);
begin
  MsgBox(AStr, mbInformation, MB_OK);
end;

function InitializeSetup(): Boolean;
begin
  Call(@ShowStr, 'Hello World!');
end;

BTW: Inno Setup uses the Pascal Script engine from RemObjects. Maybe you can find some more information there.


text:
Q: Python Creating SSL connection using ssl.PROTOCOL_TLSv1_1 and ciphers "RC4-SHA" failing with error: sslv3 alert handshake failure (_ssl.c:1108) I am trying to connect to one of my server in Python.
On my Windows 10 system when I issue a :
openssl s_client -connect host_ip:443

The result is :
---
SSL handshake has read 858 bytes and written 494 bytes
---
New, TLSv1/SSLv3, Cipher is RC4-SHA
Server public key is 1024 bit
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1.1
    Cipher    : RC4-SHA

Coming to python, I tried to set the SSL context and cipher:
ssl_context = ssl.create_default_context()

### The Following Changes Worked setting up the cipher ####

ciphers = ssl._DEFAULT_CIPHERS
# print (ciphers)
ciphers = re.sub(r":!RC4", "", ciphers)
# print(ciphers)
ciphers = ciphers + ":RC4-SHA"
ssl_context.set_ciphers(ciphers)

######################################################
ssl_context.options &= ~ssl.OP_NO_SSLv3  # I need to connect to a old server.
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
.
.
.

But I am getting error while making the connection:
[SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:1108)

System Version:
> openssl version
WARNING: can't open config file: /z/extlib/_openssl__/ssl/openssl.cnf
OpenSSL 1.0.2o  27 Mar 2018

> python --version
Python 3.8.3

> pip show pyOpenSSL
Name: pyOpenSSL
Version: 19.1.0


text:
Q: Reading in a JPEG image and calculate image coordinates I want to read in a JPEG image with a uniform gray background with several colored balls on it of the same size. I want a program which can take this image and record the coordinates of each ball. What's the best way to do this?

A: I agree with James. I used the following program once to find red boxes in an image (before most of the red boxes were recolored by the community):
/**
 * @author karnokd, 2008.11.07.
 * @version $Revision 1.0$
 */
public class RedLocator {
    public static class Rect {
        int x;
        int y;
        int x2;
        int y2;
    }
    static List<Rect> rects = new LinkedList<Rect>();
    static boolean checkRect(int x, int y) {
        for (Rect r : rects) {
            if (x >= r.x && x <= r.x2 && y >= r.y && y <= r.y2) {
                return true;
            }
        }
        return false;
    }
    public static void main(String[] args) throws Exception {
        BufferedImage image = ImageIO.read(new File("fallout3worldmapfull.png"));
        for (int y = 0; y < image.getHeight(); y++) {
            for (int x = 0; x < image.getWidth(); x++) {
                int c = image.getRGB(x,y);
                int  red = (c & 0x00ff0000) >> 16;
                int  green = (c & 0x0000ff00) >> 8;
                int  blue = c & 0x000000ff;
                // check red-ness
                if (red > 180 && green < 30 && blue < 30) {
                    if (!checkRect(x, y)) {
                        int tmpx = x;
                        int tmpy = y;
                        while (red > 180 && green < 30 && blue < 30) {
                            c = image.getRGB(tmpx++,tmpy);
                            red = (c & 0x00ff0000) >> 16;
                            green = (c & 0x0000ff00) >> 8;
                            blue = c & 0x000000ff;
                        }
                        tmpx -= 2;
                        c = image.getRGB(tmpx,tmpy);
                        red = (c & 0x00ff0000) >> 16;
                        green = (c & 0x0000ff00) >> 8;
                        blue = c & 0x000000ff;
                        while (red > 180 && green < 30 && blue < 30) {
                            c = image.getRGB(tmpx,tmpy++);
                            red = (c & 0x00ff0000) >> 16;
                            green = (c & 0x0000ff00) >> 8;
                            blue = c & 0x000000ff;
                        }
                        Rect r = new Rect();
                        r.x = x;
                        r.y = y;
                        r.x2 = tmpx;
                        r.y2 = tmpy - 2;
                        rects.add(r);
                    }
                }
            }
        }
    }
}

Might give you some hints. The image originates from here.

A: You can use the ImageIO library to read in an image by using one of the read() methods.  This produces a BufferedImage which you can analyze for the separate colors.  getRGB() is probably the best way to do this.  You can compare this to the getRGB() of a Color object if you need to.  That should be enough to get you started.


text:
Q: How to pass argparse argument to a sanic route? I wish to pass an argparse argument to a function with decorators. What is the strategy here? How can I achieve this without global variables?
#!/usr/bin/env python3
from sanic import Sanic, views, response
import os
import argparse

app = Sanic(__name__)

@app.route('/<var:var>')
async def get(self, request, var):
    print(path)
    return response.text(var)

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("-p", "--path",
                        help="Set the server root path",
                        action="store")
    args = parser.parse_args()

    app.run(host='0.0.0.0', port=8000)

I also tried using the view HTTPMethodView but without success

A: Okay so you could dynamically change the function for that route based on the parse arguments... Like this (sorry I'm on my phone)
#!/usr/bin/env python3
from sanic import Sanic, views, response
import os
import argparse

app = Sanic(__name__)

@app.route('/<var:var>')
async def get(self, request, var):
    print(path)
    return response.text(var)

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("-p", "--path", help="Set the server root path", action="store")
    args = parser.parse_args()

    def get(var):
        # use args.p in your route function!!

    app.view_functions["/<var:var>"] = get
    app.run(host='0.0.0.0', port=8000)

Might be some mistakes but you should get the gist of it


text:
Q: Flipping Card Issue I am trying to create a flipping card metro style menu, however when I tried to declare the front and back styles when you are hovering your mouse on the front div it does not look good when it shows the back div.
Here's the CSS code:
ul{
    -webkit-perspective: 1000;
    width: 50%;
    margin: 120px auto;
}
li{
    width: 200px;
    height: 200px;
    margin-right: 10px;
    margin-bottom: 10px;
    float: left;
    list-style: none;
    position: relative;
    cursor: pointer;
    font-family: 'Open Sans';
    font-weight: 300;
    background: #34495e;
}
div{
    color: yellow;
    width: 100%;
    height: 100%;
    position: absolute;
    -webkit-transition: all 0.5s ease;
    -webkit-backface-visibility: hidden;
}
.front{
    z-index: 3;
    color: #fff;
    text-align: center;
    line-height: 210px;
    font-size: 20px;
    background: #e3e3e3;
}
.front:hover {
    z-index: 0;
    -webkit-transform: rotateY(180deg);
}
.back:hover {
    -webkit-transform: rotateY(0deg);
}
.back{
    color: #fff;
    text-align: center;
    line-height: 200px;
    font-size: 22px;
}
#box1{ background: #1abc9c;}
#box2{ background: #2ecc71;}
#box3{ background: #3498db;}
#box4{ background: #f1c40f;}
#box5{ background: #e67e22;}
#box6{ background: #e74c3c;}

I am just wondering if there is a fix that we can do to make it look like the back is a part of the card cause right now it seems that it was a static face and won't move and I am just flipping front one to show the other static.
Check out the JSFiddle: http://jsfiddle.net/p6NQ2/2/

A: Method explanation: Initially the back face is rotated by 180 deg and when the li is hovered on, its child div.back) is rotated back into view (0 deg) while the div.front is rotated by 180 deg and thus gives it a front and back flipping effect.
You can achieve the card flip effect by doing the following changes to your CSS.
.back{
  color: #fff;
  text-align: center;
  line-height: 200px;
  font-size: 22px;
  -webkit-transform: rotateY(180deg); /* initially it would be rotated by 180 deg */
  -moz-transform: rotateY(180deg);
  transform: rotateY(180deg);
  background: #34495e; /* moved the background color from the li to the back element */
}

li:hover > .front {
  -webkit-transform: rotateY(180deg);
  -moz-transform: rotateY(180deg);
  transform: rotateY(180deg);
}
li:hover > .back {
  -webkit-transform: rotateY(0deg);
  -moz-transform: rotateY(0deg);
  transform: rotateY(0deg);
}

Tested in Internet Explorer 10 & 11, Chrome v24, Firefox v19 and Safari v5.1.7 (on Windows).
Notes:

*

*Set the -webkit-perspective: 1000; (and other browser prefixed versions) on the li rather than on the ul. When the perspective is set on the ul, it is common for all child elements of the ul and the perspective is from the view point of the parent ul. When it is applied on the li it is from the view point of each individual li and hence produces the same effect on each li. Refer to this thread for more details on the difference.

*We are adding the flip effect on the hover of the container li instead of the .front element because since the .front element is also being rotated, it would cause a very jittery effect.

Demo with hover on LI

body {
  background: #ecf0f1;
}
ul {
  width: 50%;
  margin: 120px auto;
}
li {
  width: 200px;
  height: 200px;
  margin-right: 10px;
  margin-bottom: 10px;
  float: left;
  list-style: none;
  position: relative;
  cursor: pointer;
  font-family: 'Open Sans';
  font-weight: 300;
  -webkit-perspective: 1000;
  -moz-perspective: 1000;
  perspective: 1000;
}
div {
  color: yellow;
  width: 100%;
  height: 100%;
  position: absolute;
  -webkit-transition: all 0.5s ease;
  -moz-transition: all 0.5s ease;
  transition: all 0.5s ease;
  -webkit-backface-visibility: hidden;
  -moz-backface-visibility: hidden;
  backface-visibility: hidden;
}
.front {
  z-index: 3;
  color: #fff;
  text-align: center;
  line-height: 210px;
  font-size: 20px;
  background: #e3e3e3;
}
li:hover > .front {
  -webkit-transform: rotateY(180deg);
  -moz-transform: rotateY(180deg);
  transform: rotateY(180deg);
}
li:hover > .back {
  -webkit-transform: rotateY(0deg);
  -moz-transform: rotateY(0deg);
  transform: rotateY(0deg);
}
.back {
  color: #fff;
  text-align: center;
  line-height: 200px;
  font-size: 22px;
  -webkit-transform: rotateY(180deg);
  -moz-transform: rotateY(180deg);
  transform: rotateY(180deg);
  background: #34495e;
}
#box1 {
  background: #1abc9c;
}
#box2 {
  background: #2ecc71;
}
#box3 {
  background: #3498db;
}
#box4 {
  background: #f1c40f;
}
#box5 {
  background: #e67e22;
}
#box6 {
  background: #e74c3c;
}
<link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet"/>

Home

About

Portfolio

Services

Products

Contact

Jittery demo with hover on front div

body {
    background: #ecf0f1;
}
ul {
    width: 50%;
    margin: 120px auto;
}
li {
    width: 200px;
    height: 200px;
    margin-right: 10px;
    margin-bottom: 10px;
    float: left;
    list-style: none;
    position: relative;
    cursor: pointer;
    font-family:'Open Sans';
    font-weight: 300;
    -webkit-perspective: 1000;
}
div {
    color: yellow;
    width: 100%;
    height: 100%;
    position: absolute;
    -webkit-transition: all 0.5s ease;
    -webkit-backface-visibility: hidden;
}
.front {
    z-index: 3;
    color: #fff;
    text-align: center;
    line-height: 210px;
    font-size: 20px;
    background: #e3e3e3;
}
.front:hover {
    z-index: 0;
    -webkit-transform: rotateY(180deg);
}
.front:hover + .back {
    -webkit-transform: rotateY(0deg);
}
.back {
    color: #fff;
    text-align: center;
    line-height: 200px;
    font-size: 22px;
    -webkit-transform: rotateY(180deg);
    background: #34495e;
}
#box1 {
    background: #1abc9c;
}
#box2 {
    background: #2ecc71;
}
#box3 {
    background: #3498db;
}
#box4 {
    background: #f1c40f;
}
#box5 {
    background: #e67e22;
}
#box6 {
    background: #e74c3c;
}
<link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet"/>

Home

About

Portfolio

Services

Products

Contact

A: Maybe something like this:
CSS Flip: DEMO
I added two new classes: Flipper , Flip Container.
.flip-container {
    perspective: 1000;
}
    /* flip when hovered */
    .flip-container:hover .flipper, .flip-container.hover .flipper {
        transform: rotateY(180deg);
    }
.flipper {
    transition: 0.6s;
    transform-style: preserve-3d;
    position: relative;
}
.front, .back {
    backface-visibility: hidden;
    position: absolute;
    top: 0;
    left: 0;
}

Additional Info:
I've embedded Aerotwist's | Paul Lewis's Graphical CSS FLIP including jQuery.
It's really cool and you might find it more helpful:
there is a CSS code inside, which divides to two parts, first, is the "Movement" of the "Card", the second is the main style.css. I'd suggest you separate one from another.
CSS: 3D Flip: JSFIDDLE
Good Luck!


text:
Q: is it possible to create a database-wide alias for a table in MySQL? I have a table named "meetings" for historic reasons, and a lot of code that references that table name.
I want to rename it to "jobs" to match what we've been calling it for the last 8 years.
renaming the table will break the code.
Is there a way to create a database-wide alias so I can rename the table to "jobs", but code that references "meetings" will still work?
the code is for inserts and reads.


text:
Q: Tomcat: uploaded image can only be obtained after restarting server
Possible Duplicate:
Uploaded image only available after refreshing the page

I'm uploading an image to a folder 'images' inside my web context. Everything is working ok and I can see the image was correcly uploaded into that folder.
However, after the upload I can't access that image using the url 'http://mywebapp/images/uploadedimage.png' (404)... Aparently, only after a server restart that resource is available, which of course is not suitable.
How can I fix this, is this a Tomcat cache issue?
Thanks in advance


text:
Q: Lambda function to start EC2 instance based on tag I have created a python Lambda Function in AWS to start some EC2 instances based on a TAG that's being deployed to them. It checks if the instance is stopped and only run on them.
import boto3
import logging
ec2 = boto3.resource('ec2')
def lambda_handler(event, context):
    filters = [{
        'Name': 'tag:STARTUP',
        'Values': ['YES']
    },
    {
        'Name': 'instance-state-name',
        'Values': ['stopped']
    }]
instances = instances.filter(Filters=filters)
stoppedInstances = [instance.id for instance in instances]
if len(stoppedInstances) > 0:
    startingUp = instances.filter(instances).start()

When I try to run it, I get the following error:
START RequestId: XXX Version: $LATEST
filter() takes 1 positional argument but 2 were given: TypeError
Traceback (most recent call last):
  File "/var/task/lambda_function.py", line 17, in lambda_handler
    startingUp = ec2.instances.filter(instances).start()
TypeError: filter() takes 1 positional argument but 2 were given

Although everywhere I look the FILTER variable is able to handle more than one argument but somehow I am only able to use one?
I'm using Python 3.6 runtime and I am using the same role as other function that works correctly to start servers (based only on time).
Can you please advise? Thank you!

A: This did the trick @ last line! Thank you for your comments that pointed me to the right direction :)
startingUp = ec2.instances.filter(InstanceIds=stoppedInstances).start()


text:
Q: DeviceIoControl fails with error 395 to set a reparse point Recently I posted this question and now I am trying to set a reparse point after a file modification with WordPad app. Currently I checked that the reparse point is a Microsoft tag and I can save the reparse point data in a REPARSE_DATA_BUFFER pointer before the file lose the reparse point. But when I try to set the reparse point to the file, after a file modification, I always get the 395 error with the GetLastError function after call to DeviceIoControl function using the control code FSCTL_SET_REPARSE_POINT. The error 395 doesn't appear in this System Error Codes although I found this error here that has sense. I also removed the discretionary access control list (DACL) from the file, to grants full access to the file by everyone, before try to set the reparse point but I got the same error. Here I put two fragments of my code to get and set the reparse point. I will appreciate any help.
Code to get the reparse point
            HANDLE hDevice = CreateFile(
                filePath.c_str(), // File path in the computer
                0,
                FILE_SHARE_READ,
                NULL,
                OPEN_EXISTING,
                FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
                NULL);

            if (hDevice != INVALID_HANDLE_VALUE)
            {
                size_t maxReparse = MAXIMUM_REPARSE_DATA_BUFFER_SIZE;
                rdb = (REPARSE_DATA_BUFFER*)malloc(maxReparse); // rdb was declared as: REPARSE_DATA_BUFFER* rdb;
                DWORD outBufferSize = maxReparse;
                DWORD bytesReturned = 0;

                if (DeviceIoControl(hDevice, FSCTL_GET_REPARSE_POINT, NULL, 0, rdb, outBufferSize, &bytesReturned, NULL))
                {
                    if (rdb != NULL)
                    {
                        if (IsReparseTagMicrosoft(rdb->ReparseTag))
                        {
                            wprintf(L"Is a Microsoft tag.\n");
                        }

Code to set the reparse point
            LPTSTR pszObjName = const_cast<wchar_t*>(filePath.c_str()); // File path in the computer
            PACL newDACL = NULL; // NULL discretionary access control list to grant full access to everyone
            DWORD secInfo = SetNamedSecurityInfo(pszObjName, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, newDACL, NULL);

            if (secInfo == ERROR_SUCCESS)
            {
                HANDLE hDevice = CreateFile(filePath.c_str(),
                    GENERIC_ALL, //GENERIC_READ | GENERIC_WRITE,
                    FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
                    FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, NULL);

                if (hDevice != INVALID_HANDLE_VALUE)
                {
                    size_t maxReparse = MAXIMUM_REPARSE_DATA_BUFFER_SIZE;
                    DWORD inBufferSize = maxReparse;

                    if (rdb != NULL)
                    {
                        DWORD bytesReturned = 0;

                        if (!DeviceIoControl(hDevice, FSCTL_SET_REPARSE_POINT, rdb, inBufferSize, NULL, 0, &bytesReturned, NULL))
                        {
                            DWORD error = GetLastError(); // Error 395
                            unsigned long errorUL = error;
                            wprintf(L"Error %lu in DeviceIoControl method.\n", errorUL);
                        }


text:
Q: Toggling Less/More button in jQuery I have a code that partially load and display two comments. Another button, More comments is attached and it loads the remaining comments via AJAX.
The More comments is then replaced with Less comments button. Now what I want is whenver the less comment button is clicked, the comments should be hidden and
the Less comments button should be replaced with More comments button which can be clicked to display the hidden comments.
It actaully does replace the Less comments button with expected one but it hides it together with the comments.

 slideToggle!

 classToggle!

    <button class='morecomments ' value='7 ' name = 'more ' type='submit '>
     More comments</button>

The jQuery code to fetch more comments via AJAX. This is working fine.
$(".morecomments").click(function () {
    var $this = $(this);
    var post_id = $(this).val();
    var user_id = $(".user_id").text();
    var request = $.ajax({
        url: "comments.php",
        type: "POST",
        data: {
            post: post_id,
            user: user_id
        },
        dataType: "html"
    });
    request.done(function (msg) {
        $this.prev('.per_comment').html(msg);
        $this.replaceWith("<button class='lesscomments' value='7' name = 'more' type='submit'>Less comments</button>");
    });
});

The jQuery code to hide the comments. Clicking this will hide the comments but the replaceWith button also disappear:
$('.comment_data').on('click', ".lesscomments", function () {
    var $this = $(this);
    $this.closest('.comment_data').slideToggle();
    $this.replaceWith("<button class='morecomments' value='7' name = 'more' type='submit'>More comments</button>");
});

Any workable solution will be immensely appreciated...

A: Try
//use event delegation here also as the button is created dynamically
$(".comment_data").on('click', '.morecomments', function () {
    var $this = $(this),
        $pc = $this.prev('.per_comment');
    //if the comments are already loaded then don't load it again just display it
    if ($pc.data('loaded')) {
        $this.replaceWith("<button class='lesscomments' value='7' name = 'more' type='submit'>Less comments</button>");
        $pc.slideDown();
    } else {
        var post_id = $(this).val();
        var user_id = $(".user_id").text();
        var request = $.ajax({
            url: "comments.php",
            type: "POST",
            data: {
                post: post_id,
                user: user_id
            },
            dataType: "html"
        });
        request.done(function (msg) {
            $pc.html(msg).data('loaded', true);
            $this.replaceWith("<button class='lesscomments' value='7' name = 'more' type='submit'>Less comments</button>");
        });
    }
});
$('.comment_data').on('click', ".lesscomments", function () {
    var $this = $(this);
    $this.prev('.per_comment').slideUp();
    $this.replaceWith("<button class='morecomments' value='7' name = 'more'>More comments</button>");
});

A: Your button is inside the
 that you are hiding.  If you move the button outside this div, it should work.

A: try this:
Working Fiddle
HTML:

slideToggle!

classToggle!

slideToggle!

slideToggle!

slideToggle!

            <button class="morecomments showMoreLess" value="7" name="more" type="submit">More comments</button>

Jquery:
$(document).on("click", ".showMoreLess", function () {
    if ($(this).hasClass("morecomments")) {
        $(this).html("Less Comment");
        $(this).removeClass("morecomments").addClass("lesscomments");
    } else {
        $(this).html("More Comment");
        $(this).removeClass("lesscomments").addClass("morecomments");
    }
    $('.comment').slideToggle();
});