Q: Laravel - Running Horizon in Google Cloud Run (via Docker) I'm trying to set up laravel horizon to run on my google cloud (run) containers. I have gotten installed successfully, however when I navigate to the dashboard, it always indicates to be inactive. Jobs are getting scheduled but are not being executed.

For clarification:
The laravel application also houses an application on which actual end-users end up. I want to add Horizon to manage the jobs that are generated by that platform. It's a serverless application (housed on Cloud Run as mentioned), however there are atleast 3 containers running at all times and the Redis instance which powers the queue is also housed seperately.
Dockerfile:
FROM composer:2.1.3 as build
WORKDIR /app
COPY . /app

RUN apk update
RUN apk add libpng libpng-dev libjpeg-turbo-dev supervisor libwebp-dev zlib-dev libxpm-dev gd && docker-php-ext-install gd && docker-php-ext-install pdo pdo_mysql

RUN docker-php-ext-install pdo pdo_mysql pcntl
RUN composer install

FROM php:8.1-apache-buster
RUN docker-php-ext-install pdo pdo_mysql pcntl
RUN pecl install redis && docker-php-ext-enable redis

EXPOSE 8080
COPY --from=build /app /var/www/
COPY docker/000-default.conf /etc/apache2/sites-available/000-default.conf
COPY docker/supervisord.conf /etc/supervisord.conf
COPY .env.example /var/www/.env
RUN echo 'max_execution_time = 1200' >> /usr/local/etc/php/conf.d/docker-php-maxexectime.ini;
RUN echo 'memory_limit = 1G' >> /usr/local/etc/php/conf.d/docker-php-memlimit.ini;
RUN echo 'php artisan horizon'

RUN chmod 777 -R /var/www/storage/ && \
    echo "Listen 8080" >> /etc/apache2/ports.conf && \
    chown -R www-data:www-data /var/www/ && \
    a2enmod rewrite

Horizon configuration file:
return [

    /*
    |--------------------------------------------------------------------------
    | Horizon Domain
    |--------------------------------------------------------------------------
    |
    | This is the subdomain where Horizon will be accessible from. If this
    | setting is null, Horizon will reside under the same domain as the
    | application. Otherwise, this value will serve as the subdomain.
    |
    */

    'domain' => env('HORIZON_DOMAIN', null),

    /*
    |--------------------------------------------------------------------------
    | Horizon Path
    |--------------------------------------------------------------------------
    |
    | This is the URI path where Horizon will be accessible from. Feel free
    | to change this path to anything you like. Note that the URI will not
    | affect the paths of its internal API that aren't exposed to users.
    |
    */

    'path' => env('HORIZON_PATH', 'horizon'),

    /*
    |--------------------------------------------------------------------------
    | Horizon Redis Connection
    |--------------------------------------------------------------------------
    |
    | This is the name of the Redis connection where Horizon will store the
    | meta information required for it to function. It includes the list
    | of supervisors, failed jobs, job metrics, and other information.
    |
    */

    'use' => 'default',

    /*
    |--------------------------------------------------------------------------
    | Horizon Redis Prefix
    |--------------------------------------------------------------------------
    |
    | This prefix will be used when storing all Horizon data in Redis. You
    | may modify the prefix when you are running multiple installations
    | of Horizon on the same server so that they don't have problems.
    |
    */

    'prefix' => env(
        'HORIZON_PREFIX',
        Str::slug(env('APP_NAME', 'laravel'), '_').'_horizon:'
    ),

    /*
    |--------------------------------------------------------------------------
    | Horizon Route Middleware
    |--------------------------------------------------------------------------
    |
    | These middleware will get attached onto each Horizon route, giving you
    | the chance to add your own middleware to this list or change any of
    | the existing middleware. Or, you can simply stick with this list.
    |
    */

    'middleware' => ['web', 'sessionvalidation'],

    /*
    |--------------------------------------------------------------------------
    | Queue Wait Time Thresholds
    |--------------------------------------------------------------------------
    |
    | This option allows you to configure when the LongWaitDetected event
    | will be fired. Every connection / queue combination may have its
    | own, unique threshold (in seconds) before this event is fired.
    |
    */

    'waits' => [
        'redis:default' => 60,
    ],

    /*
    |--------------------------------------------------------------------------
    | Job Trimming Times
    |--------------------------------------------------------------------------
    |
    | Here you can configure for how long (in minutes) you desire Horizon to
    | persist the recent and failed jobs. Typically, recent jobs are kept
    | for one hour while all failed jobs are stored for an entire week.
    |
    */

    'trim' => [
        'recent' => 60,
        'pending' => 60,
        'completed' => 60,
        'recent_failed' => 10080,
        'failed' => 10080,
        'monitored' => 10080,
    ],

    /*
    |--------------------------------------------------------------------------
    | Metrics
    |--------------------------------------------------------------------------
    |
    | Here you can configure how many snapshots should be kept to display in
    | the metrics graph. This will get used in combination with Horizon's
    | `horizon:snapshot` schedule to define how long to retain metrics.
    |
    */

    'metrics' => [
        'trim_snapshots' => [
            'job' => 24,
            'queue' => 24,
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Fast Termination
    |--------------------------------------------------------------------------
    |
    | When this option is enabled, Horizon's "terminate" command will not
    | wait on all of the workers to terminate unless the --wait option
    | is provided. Fast termination can shorten deployment delay by
    | allowing a new instance of Horizon to start while the last
    | instance will continue to terminate each of its workers.
    |
    */

    'fast_termination' => false,

    /*
    |--------------------------------------------------------------------------
    | Memory Limit (MB)
    |--------------------------------------------------------------------------
    |
    | This value describes the maximum amount of memory the Horizon master
    | supervisor may consume before it is terminated and restarted. For
    | configuring these limits on your workers, see the next section.
    |
    */

    'memory_limit' => 128,

    /*
    |--------------------------------------------------------------------------
    | Queue Worker Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may define the queue worker settings used by your application
    | in all environments. These supervisors and settings handle all your
    | queued jobs and will be provisioned by Horizon during deployment.
    |
    */

    'defaults' => [
        'supervisor-1' => [
            'connection' => 'redis',
            'queue' => ['default'],
            'balance' => 'auto',
            'maxProcesses' => 1,
            'maxTime' => 0,
            'maxJobs' => 0,
            'memory' => 128,
            'tries' => 1,
            'timeout' => 60,
            'nice' => 0,
        ],
    ],

    'environments' => [
        'production' => [
            'supervisor-1' => [
                'maxProcesses' => 10,
                'balanceMaxShift' => 1,
                'balanceCooldown' => 3,
                'queue'=> ['low', 'medium', 'high', 'vip'],
            ],
        ],

        'local' => [
            'supervisor-1' => [
                'maxProcesses' => 3,
                'queue'=> ['low', 'medium', 'high', 'vip'],
            ],
        ],
    ],
];

Supervisord.conf
[supervisord]
nodaemon=true
[program:laravel-worker]
process_name=%(exampleprocessname)s_%(process_num)02d
command=php /var/www/artisan horizon
autostart=true
autorestart=true
numprocs=1
redirect_stderr=true

Would anyone be able to give me some clues as to where it might go wrong?
Thank you
Ps. The environment variables are exactly the same between the .env and the horizon configuration file.

A: Is it possible to run background tasks in Cloud Run ? i thought it operates only on request, and therefore after a request is handled it stops working, until the next requests comes in.

A: The trick is to pass a custom container command in Cloud Run with the value /usr/bin/supervisord to actually start the supervisor/Horizon.
But there's another trick you need, as Cloud Run expects the service to respond to a health check request. You should not only start Horizon from supervisor (which by default would override the container command and not start Apache), but also start Apache, so the service can be considered healthy.
You can also pick a more lightweight solution, that will return HTTP 200 on request to the root of your service, as Apache feels a bit overkill for this purpose.
Disclosure: I believe I happen to be currently working for ilovecookies


Q: Spring boot request X509 certificate on login page I am writing a Spring Boot application where on login page, user should be prompted to provide his X509 certificate (generated with my self-signed CA).
If user fails to provide certificate he is then shown another page with error. If user provides correct certificate, I want to show him a login page with his email pre-filled (read from certificate) and waiting for password input.
The only affected path should be /admin/login which requires certificate, all the other paths should be left completely unsecured.
What I have found so far is this procedure:

*

*generate proper certificates

*generate jks file

*configure tomcat to ask for certificate

*configure spring boot security

*before loading login page, ask for certificate, parse it, check validity of data in it (common name,...)

*show login page

*check login data and if it is ok, do my stuff

I am having problem with points 3-5, as all the tutorials I found are not really the solution I am looking for.
Also, later on, this Spring Boot project will run behind Apache's virtual host, so I guess I will need Apache to request certificate and then forward it to Spring Boot server.
I would need some starting points how to learn things I need to implement this.

Some context:
I am building an Angular 6 (Spring Boot for backend) application, where I have two types of roles: users and admins.
Users will login through normal (Angular) page with only username and password. Admin will have to login by providing certificate and then logging in with username written in certificate and password - this will be done on separate page served by Spring Boot with Thymeleaf template engine.
What I envisioned to implement is that when user is authenticated I generate JWT token and save it to cookie, which will be used for all future request (for the duration of JWT's validity). The only problem is I don't know how to connect all of these things


Q: 3 divs in row with auto width adjust I got 3 divs that:

*

*need to to be side by side ( in a row)

*all have a background imgage

*the center div need to adjust the width automatic, center div's width dependance on the content that have been inserted into the div( longer text = longer width

*center div needs to be at the center of the page too.

*the divs on sides have diffrent backgrounds img.

HTML Code:

Headline

note that the divs in sides are empty.
something like this:
http://jsfiddle.net/fsnuh/134/
Is this possible to do with css or css3? If not how can I do it with jquery or raw javascript?

A: Tables for the win! fiddle
<!DOCTYPE html>

blah

A: Give the header a fixed width if you can. Then use jQuery to calculate the widths and set them accordingly.
Here is a working demo: http://jsfiddle.net/rniestroj/fsnuh/135/
html:

Kontakt 11111111111 22222

css:
*{
    padding: 0;
    margin: 0;
}

h3{
    width: 600px;
    overflow: auto;
}

.spanr, .spanl {
    background: url("../img/headline2.png") no-repeat scroll right center gold;
    float: left;
    height: 33px;
    position: relative;
    width: 33%;
}
.center {
    background: none repeat scroll 0 0 #E6B043;
    float: left;
    height: 33px;
    line-height: 33px;
    padding: 0 10px;
    position: relative;
    text-transform: uppercase;
    width: auto;
}

js:
var h3Width = $("h3").width();
var centerWidth = $(".center").width();
var asideWidth = 0;
asideWidth = ((h3Width - centerWidth) / 2) - 12;

$(".spanl").width(asideWidth );
$(".spanr").width(asideWidth );

A: Try this CSS only solution:
jsFiddle Example.
HTML:

        Kontakt

CSS:
#headlines {
    background-image: url('../img/headline2.png'), url('../img/headline2.png');
    background-repeat: no-repeat;
    background-position: left center, right center
}
.headline2, .headline2 > span {
    height: 33px;
    text-align: center;
    text-transform: uppercase;
    line-height: 33px
}
.headline2 > span {
    background-color: #E6B043;
    display: inline-block;
    padding: 0 10px
}


Q: Template Error on Form_for in Rails I have an nested model student that belongs to a high_school.  The problem is that when I go to create a new student (/high_schools/1/students/new) I get this error:
No route matches {:action=>"destroy", :controller=>"students", :high_school_id=> # <HighSchool id: 1, name: "cool place", ... }

<%= form_for @student, :url => high_school_student_path(@high_school, @student), :html => { :multipart => true } do |f| %>

I think I'm just doing something really simple and stupid that I can't think of.
My environment: Rails3 and Ruby1.9.2dev
Thank you!

A: Try passing an array as the first arg to form_for, and remove the :url hash.
<%= form_for [@high_school, @student], :html => { :multipart => true } %>

And be sure that @student is a new record.

A: Maybe add
delete 'student' => :destroy

in routes.rb
controller :students do
     delete 'student' => :destroy

end


Q: Best way to store content? First of all I want to thank you for even reading this. I'm a complete noob and I'm trying to learn Android Java. I've made many little "Learn Apps" in which I just try to learn things. Today I want to make another one.
I want to have ListView in the MainActivity which contains names of Food like:

*

*Pizza

*Ice Cream

*Spaghetti

*Apple

*Orange

*...

When the user clicks on one of those a SecondActivity gets called and this SecondActivity contains a two TextViews. One with the name on which the user clicked and one with a description. Example:
User clicks on Pizza.
SecondActivity looks like this:
Pizza
Pizza is blah blah blah
and if the user clicks Orange:
Orange
Oranges are fruits blah blah blah
I hope you undestand me.
My question is now. Which is the easiest way to store this descriptions? An SQLDatabse? Or should I just write them like Strings and say. If user clicks this parse this String to TextView1 and this String to TextView2? I hope you understand me and can help me! Thank you very much!!

A: If they are static Strings (that you may or may not want to translate later on) you would probably be best saving them as a String array in a resource.xml file:
(The filename can be anything_you_like.xml)
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="food_names">
        <item>apple</item>
        <item>orange</item>
        <item>pizza</item>
        <item>blah</item>
        <item>blah</item>
    </string-array>
    <string-array name="food_descriptions">
        <item>green, doctor friendly</item>
        <item>round, hurts eyes</item>
        <item>flat, cheezy, liked by turtles</item>
        <item>blah</item>
        <item>blah</item>
    </string-array>
</resources>

You need to locate the file inside your values folder and you then get the option to do all the fancy folder variations like values-v14, values-v16 and values-en, values-es, values-fr and so on, and so on...
You can later access this String[] from your code to grab the appropriate version for the user's API and language with:
String[] foodNames = context.getResources().getStringArray(R.array.food_names);
String[] foodDescriptions = context.getResources().getStringArray(R.array.food_descriptions);

static final String FOOD_FORMAT = "%s :: $s";
for (int i=0; i<foodNames.length; i++) {
    System.out.println(
            String.format(FOOD_FORMAT,
                          foodNames[i],
                          foodDescriptions[i]
            )
    );
}

A: indivisible's answer is acceptable to your case. But considering that your content may change and may be more detailed, you should stick to an SQLite database. You only will need a simple table insert your data. Having an if else chain is not the cleanest way and definitely is not friendly when you think about scalability. But if you really want to use the second approach, use a switch, instead of an if else chain.
If in the future, you want to add other elements to your data, just change your database as you like and that is it.


Q: using valuewhen in pine script I can understand how valuewhen works in pine script by its docs at https://www.tradingview.com/pine-script-reference/v5/#fun_ta{dot}valuewhen
The example given there is simple:
// Get value of `close` on second most recent cross
plot(ta.valuewhen(ta.cross(slow, fast), close, 1))

But I'm not able to understand how the following code works in a production open source script that finds highs in a divergence where Dinput1 is the series D for stochastic calculated earlier in the script.
depth = input(2, 'Fractal Depth')
_src = Dinput1
_high = high
_low = low
top_fractal = ta.highest(_src, depth * 2 + 1) == _src[depth]
prev_top_fractal = ta.valuewhen(top_fractal, _src[depth], 0)[depth]
prev_high = ta.valuewhen(top_fractal, _high[depth], 0)[depth]

Specifically, the line:
prev_top_fractal = ta.valuewhen(top_fractal, _src[depth], 0)[depth]
As I understand it, if the depth = default 2 then 5 candles are examined each time starting from index 0 (rightnost) and if the middle value is highest then top_fractal condition will give a true result. But what will be returned by valuewhen? From docs, it should return that highest value found. But then why is it indexing it again by [depth]? That suggest that what is returned is a series. Is it a value or series?
Update after some research: It seems valuewhen returns the highest value in the most recent (0th) occurence of last 5 candles only if the highest is also the middle value in those 5 candles. But what I'm not able to understand is the [depth] suffix to get the prev_top_fractal (previous high). That suggests that valuewhen returns the series beginning with 5 candles so that [depth] suffix is needed to get the highest value.

A: Figured it out. Coming from a regular programming background, I had a confusion on how the historic referencing works and the way the pine script runs on each bar.
valuewhen returns the first occurrence of the 5-bar D fractal with the TOP value in the middle. The actual top value prev_top_fractal is obtained by historic referencing [2] on the returned result.
In the next line, prev_high in price is found by a similar logic.


Q: ReferenceError: myData is not defined I am learnig angular js service.Try to execute following code which reads JSON from a json file.
data.json
 {
   "name": "ishmam",
   "age": "23"
 }

Body of html:
<body ng-app="myAppp" ng-controller="customersCtrl">

<div>
     {{myData.name}}
</div>

    <script>
         var app = angular.module('myAppp', []);
         app.controller('customersCtrl', function($scope, $http) {
             $http.get('data.json').then(function (response) {
                 $scope.myData = response.data.records;
                 console.log("sadas"); //this is ok
                 console.log(myData.name); //this is showing error
             });
         });
    </script>

 </body>

Getting the following error:

ReferenceError: myData is not defined
  at MyAJ.html:30
  at processQueue (angular.js:15552)
  at angular.js:15568
  at Scope.$eval (angular.js:16820)
  at Scope.$digest (angular.js:16636)
  at Scope.$apply (angular.js:16928)
  at done (angular.js:11266)
  at completeRequest (angular.js:11464)
  at XMLHttpRequest.requestLoaded (angular.js:11405)

Why?

A: You are trying to log myData which doesn't exist.
try this
$http.get(url).then(function(response){
    // Will have proper data only if your response has the key 'records'.
    // Otherwise your $scope.myData will have undefined value
    console.log(response.data) //Check if Key 'records' is present.

    $scope.myData = response.data.records;
    console.log($scope.myData.name);
});

A: myData is not defined..
Use $scope.myData to get output.

A: The error is you are referencing response.data.records in the success callback of then. Your json will be available on response.data directly. So what you need to do is just access that like
$http.get('data.json')
        .then(function (response) {
            $scope.myData = response.data; // just access data, not data.response
            console.log("sadas"); //this is ok
            console.log($scope.myData.name); //you need to access $scope.myData, rather than just myData
        }, function(error){
            console.log(error);
        });

A: var app = angular.module('myAppp', []);
app.controller('customersCtrl', function($scope, $http) {
angular.element(document).ready(function(){
$scope.myData={};
});
$http.get('data.json').then(function (response) {
$scope.myData = response.data.records;
console.log($scope.myData ); //make sure this is not null/undefined
console.log($scope.myData.name); //if not null this will work
});
});

A: Try this i think that's may be work for you
myData[0].name


Q: Missing Assembly Reference Trying to Compile .cs File With Mono I am trying to make a simple Console Application using Visual Studio for Mac (version 17.4). Current target framework is .NET 7.0 but I've toggled back and forth between .NET 6.0 with no luck. My goal is to set up something that can automatically run my application per a schedule I set. To that end I've come across using 'Mono' as a way to compile .cs files into .exe files and then run them from the Terminal. I can compile and run my application with no issues when I'm using Visual Studio for Mac. However when using (what I understand to be) the way to compile my .cs file into an executable using a bash script, I can't figure out how to resolve the series of Are you missing an assembly reference? errors I get. The script I'm using to compile my code is:
mcs /out:AmazonProductCheck.cs *.cs

Below is an image of the results I get after running the script above.
And here is an image of my using Directives in the .cs file I'm targeting in my bash script from above.

Any help is appreciated! I've scoured Stack Overflow for days now and while I've found the language 'Are you missing an assembly reference?' in quite a few posts I haven't been able to use the information in those posts to figure out my problem.
Things I've tried:
(1) Scouring Stack Overflow for searches like "Visual studio for mac mono Are you missing an assembly reference"
(2) Adding more 'using Directives' to the top of the code that is my entry point for this console app
(3) Copying some .dll files into the working directly where my .cs file lives
(4) Switching my target framework from 7.0 back to 6.0 within Visual Studio for Mac.
Expectation is that I can compile my .cs file into an executable and then run that executable with a bash script.


Q: Symfony 1.4.4 - Doctrine migration and Plugin installation I make my first steps in the symfony plugin world, and I'm a bit
lost...
I have a live app with a database. Usually, when I need a new table or
field I do a migration, by updating my schema.yml, calling the
generate-migration-diff and build --all-classes --and-migrate symfony
commands.
Today, I need to install a plugin (i.e, sfCombinePlugin) in order to
minify my js and css scripts. I installed it via the symfony
plugin:install command, it's ok I've got all my files in the plugins
folder. I follow the read-me, it says to build the model, so I run the
command doctrine:build-model, and a folder sfCombinePlugin appears in
my lib/model/doctrine folder.
But now I'm stuck, I need to add the table in my database. In the read-
me it says, to generate the sql via doctrine:build-sql, and run the
generated sql in my database. But I see some issues coming...
Will it erase my data by running the sql file? I pretty sure it will,
because it create the database from scratch...
So, I would like to use a migration, as I do usually. But when I run
the generate-migration-diff, it doesn't take in account the schema.yml
from the plugin folder. Is it normal or is it a bug?
I've thought of copying the content of the schema.yml plugin inside
the schema.yml app file, but I'm not sure this is a good idea, because
the model classes will not be in the sfCombinePlugin folder but in the
general model folder. And it sounds not good.

A: build-sql will just create the SQL files; insert-sql would overwrite the database. When I do table adding like this, I have just looked in the generated SQL in data/sql and added the tables by hand. s2 has migrations built in, IIRC. For s1.4 check out http://www.symfony-project.org/plugins/sfPropelMigrationsLightPlugin - just found via google, I've never used it.


Q: I have error when I run docker in daemon mode I try to run docker in daemon mode but get an error
#docker -d -b br0
flag provided but not defined: -d
See 'docker --help'.

#service docker status
docker stop/waiting

I need this because I use own bridge for docker instance.
Two weeks ago I did not got any problems  like this, but now I can't understand what happen
docker -v
Docker version 1.10.0, build 590d5108
uname -a
3.16.0-60-generic #80~14.04.1-Ubuntu SMP Wed Jan 20 13:37:48 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux

A: I would suggest not starting the docker daemon by hand, because not least - the flags and options change.
My running 1.9 docker daemon has flags:
/usr/bin/docker daemon -H fd://

I would suggest what has happened here, is that the docker invocation has changed - it's no longer docker -d - it changed between my two installs (1.7.1 and 1.9.1).
If you look at the docker daemon manpage you'll see the -d flag is gone.
But actually, I'd suggest not running it by hand at all, and look at altering the service invocation. On my Centos6 box, that's /etc/sysconfig/docker (You can see where this is by reading /etc/init.d/docker which is what service invokes)


Q: UI-Router redirecting to a child not working Hi I am trying to have a parent state redirect to a child state.
export const states = [
 { name: 'top', url: '/top', redirectTo: 'top.bottom' },
 { name: 'top.bottom', url: '/bottom', component: GenericComponent },
];

The transition is successful but the child view is not showing up. What am I doing wrong?
https://stackblitz.com/edit/ui-router-angular-redirecto-child
In above example you'll see a redirect with a successful transition but it just says "Loading.."

A: All that's needed is a component for the parent that has a template <ui-view></ui-view>. Otherwise child has no place to render it's view.


Q: How to plot vertical base line to show current time using react-google-charts for chart type Timeline chart //https://www.react-google-charts.com/examples/timeline
import { Chart } from "react-google-charts";
export function GoogleTimeLineChart(props){

const data source=[[{"type":"string","id":"Plan"},{"type":"string","id":"Job"},{"type":"date","id":"Start"},{"type":"date","id":"End"}],["Base Line","1","2022-08-05T04:30:00.000Z","2022-08-05T04:35:00.000Z"],["Base Line","2","2022-08-05T05:00:00.000Z","2022-08-05T05:05:00.000Z"],["Base Line","3","2022-08-05T05:30:00.000Z","2022-08-05T05:35:00.000Z"],["Base Line","4","2022-08-05T06:00:00.000Z","2022-08-05T06:05:00.000Z"],["Base Line","5","2022-08-05T06:40:00.000Z","2022-08-05T06:45:00.000Z"],["Base Line","6","2022-08-05T07:05:00.000Z","2022-08-05T07:10:00.000Z"],["Base Line","7","2022-08-05T07:40:00.000Z","2022-08-05T07:45:00.000Z"],["Actual",".1","2022-08-05T04:47:00.000Z","2022-08-05T04:52:00.000Z"],["Actual",".2","2022-08-05T05:10:00.000Z","2022-08-05T05:15:00.000Z"],["Actual",".3","2022-08-05T05:50:00.000Z","2022-08-05T05:55:00.000Z"],["Actual",".4","2022-08-05T06:20:00.000Z","2022-08-05T06:25:00.000Z"],["Actual",".5","2022-08-05T06:30:00.000Z","2022-08-05T06:35:00.000Z"],["Actual",".6","2022-08-05T06:50:00.000Z","2022-08-05T06:55:00.000Z"],["Revised","7.","2022-08-05T07:35:00.000Z","2022-08-05T07:40:00.000Z"]]
const colors=["#062373","#062373","#062373","#062373","#062373","#062373","#062373","green","red","red","red","red","green","green"]

return (
 <Chart
      chartType="Timeline"
      data={dataSource}
      width="100%"
      height="500px"
      options={{
        colors: [...colors],
      }}
    />
)
}

How can to draw vertical line in this react google timeline chart here i have uploaded my code output


Q: How to fix string too long exception in java I have a algorithm to analysis string but it take only about 10000 characters more than that it will throw following exception
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - constant string too long

this is the code I'm using
public static void printRepeatingStrings(String inputString, int sequenceLength) {
    if (inputString.isEmpty() || sequenceLength <= 0 || sequenceLength >= inputString.length()) {
        System.out.println("Invalid input");
    } else {
        int i = 0;
        int j = i + sequenceLength;
        Set<String> tempSet = new HashSet<>();
        Set<String> repeatingSequences = new TreeSet<>();
        while (j <= inputString.length()) {
            if (!tempSet.add(inputString.substring(i, j))) {
                repeatingSequences.add(inputString.substring(i, j));
            }
            i++;
            j = i + sequenceLength;
        }
        for (String str : repeatingSequences) {
            System.out.println(str);
        }
    }
}

If you can help me to fix this that will be very helpful

A: See Java "constant string too long" compile error. Only happens using Ant, not when using Eclipse
there ist stated that the length of a string constant in a class file is limited to 2^16 bytes in UTF-8 encoding.
If you don't use such a long constant, maybe the otpimizing compiler makes some concatenation with static expressions in the main function.

A: You should be able to get a String of length Integer.MAX_VALUE (always 2147483647 (231 - 1) by the Java specification, the maximum size of an array, which the String class uses for internal storage) or half your maximum heap size (since each character is two bytes), whichever is smaller.


Q: CSS3 - Fade between 'background-position' of a sprite image I want to fade between 'background-position' of a sprite image only with CSS. I found a lot o tutorials but I didn't found something simple like this:
<!doctype html>

<meta charset="utf-8">
<title>CSS3 - Fade between 'background-position' of a sprite image</title>

Thank you.

A: I found the answer, thanks anyway.
<!doctype html>

<meta charset="utf-8">
<title>CSS3 - Fade between 'background-position' of a sprite image</title>

A: so basically, you need to perform two things upon :hover

*

*background-position change

*fadein effect

CSS3 transition won't be useful in this case.
You can use CSS3 animation property.
animation property accepts name of the animation and duration. Multiple animation names can be provided separated by comma.
you need to define these animation names.They can be any string of your choice,  but you need to define them.
so consider this css:
div:hover{
   animation: fadein 10s, bp 0.5s;
   -moz-animation: fadein 10s, bp 0.5s; /* Firefox */
   -webkit-animation: fadein 10s, bp 0.5s; /* Safari and Chrome */
   -o-animation: fadein 10s, bp 0.5s;
    background-position:0 0;
}
@-webkit-keyframes fadein { /* Safari and Chrome */
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}
@-webkit-keyframes bp { /* Safari and Chrome */
    from {
        background-position:-200px 0;
    }
    to {
        background-position:0 0;
    }
}

see this fiddle, for complete browser supported animation
NOTE: it won't work in IE<9 for sure! and it might in IE9(not sure).

A: You can use CSS3 Animation with @keyframes
div:hover{
  animation: logo 2s 0 linear;
}
@keyframes logo{
  0%   { opacity: 1; }
  5%   { opacity: 0; }
  50%  { background-position: 0 -60px; opacity: 0; }
  100% { background-position: 0 -60px; opacity: 1; }
}

Example: http://jsfiddle.net/Y8W9S/
Of course, now you have to adjust the times and effect you want to implement.
Hope it's helps or point you in right direction.
Good luck.

A: Use like this:
div{
    width:  120px;
    height: 60px;

    background-image: url('sprite.jpg');
    background-repeat: no-repeat;
    background-position: 0   0;
    transition: background-position 1s ease;

}

And don't forget the optional vendor prefixes
Edit:
I've noticed you need fade. You try to similar solution like this:
div{
    background: url(foo.jpg) no-repeat 0 0 transparent;
    transition: background: 1s ease;
}

div:hover{
    background: rgba(0, 0, 0, 1);
}

I can't try this, coz' im from mobile.


Q: How to add and access a yaml file as a resource in Ballerina? I have a YAML file that I want to keep as part of my jar resources and consume inside my .bal program.
I have created a resources folder under my project and placed the file there.
The file is being added to the JAR and I can confirm it.
But how do I now access it within my code:
string requestedFile = "./resources/service_openapi.yaml"; // <--- here
res.setFileAsPayload(requestedFile, contentType = mime:APPLICATION_OCTET_STREAM);

The above throws a runtime error: no such file or directory


Q: How to tell which JSON object is being used (Crockford's or another)? I'm using Crockford's json2.js. When I want to stringify, I do JSON.stringify()...works great.
However, those who've taken a look at the code know that it defers to existing JSON objects and properties. I suspect a certain problem I'm having may be due to this deference.
Is there a property of the JSON object I can check to see if the browser is using Crockford's object, or some other? It would be nice to be able to do something like alert(JSON.version());

A: You can decide one to use like this:
<script>window.JSON || document.write('<script src="js/json2.js"><\/script>')</script>

This checks for window.JSON (supported by browser) first if it exists, use that else imports json2.js of Crockford.
update
var whichJSON = null;

if (! window.JSON) {
  document.write('<script src="js/json2.js"><\/script>');
  whichJSON = 'Crockford Version';
}
else {
  whichJSON = 'Browser Native Version';
}

alert(whichJSON);

A: Before you load Crockford's script, you can check for the global JSON object exactly like he does:
<script>
    var JSON,
        nativeJSON = true;

    if (!JSON) {
        var nativeJSON = false;
        document.write('<script src="js/json2.js"><\/script>');
    }

    if (!nativeJSON) {
        // All JSON objects are using Crockford's implementation
    } else {
        // All JSON objects from here on out are NOT using Crockford's implementation
    }
</script>


Q: Android studio is unable to recognize ndk.dir and ANDROID_NDK in Mac I'm running into a strange Android studio problem. My gradle sync fails every time with the following message:
Error:NDK is not configured. Define location with ndk.dir in local.properties or with an ANDROID_NDK environment variable.
local.properties has been updated through Android studio (I have added the right path to the downloaded NDK in File -> Project structure -> SDK location -> NDK location)
I have also updated my .bash_profile with the ANDROID_NDK environment var and appended it to the PATH.
ANDROID_NDK and ndk.dir point to the same location.
On gradle sync, I still see the same error.
Any ideas?

A: I would try wiping the caches. I think the issue could be in either the Android Studio cache or in the Gradle cache, so I would wipe them both.
To clear the Gradle cache:
Locate the folder .gradle in your home directory, and delete it.
To clear the Android Studio cache:
In Android Studio, choose File->Invalidate Caches/Restart. Then choose Invalidate and Restart from the pop-up.

A: Fixed the problem. The problem was that Android Studio was auto-generating local.properties in the parent folder as well while importing my project. The local.properties in the parent folder had only the sdk.dir and not the ndk.dir. On adding ndk.dir to that file, I was able to gradle sync successfully.


Q: Create childband Delphi (QR) at runtime I have the following code
procedure Tar_ardemo.qr_ardemoBeforePrint(Sender: TCustomQuickRep;
  var PrintReport: Boolean);
var
    QR: TquickRep;
    QB2: TQRBand;
    QB3: TQRChildBand;
    QL: TQRLabel;
begin
  with artikste do
  begin
    close;
    sql.Clear;
    sql.add('SELECT * FROM Artikels');
    open;
    first;
  end;

  QR := qr_ardemo;
  QB2 := QRBAND2;
  QB3 := TQRchildband.Create(QR);
  QB3.ParentBand := QB2;
  QB3.Height := 40;

  QL := TQRLabel.Create(QR);
  QL.Parent := QB3;
  QL.Left := 300;
  QL.Top := 1;
  QL.Width := 81;
  QL.Height := 23;
  QL.Caption := 'QRLabeZZ';
end;

I want to create a Childband (QB3) and a QRLabel (QL) at runtime. I just can't see it in my output, when I run the script in Delphi. When I change QL.Parent := QB3 to QB2, I see the output in QRBand2, but I want to see it in the just created Childband QB3. What do I wrong? I can not figure it out.
Thanks

A: This could be a solution:
procedure Tar_ardemo.qr_ardemoBeforePrint(Sender: TCustomQuickRep;
  var PrintReport: Boolean);
var
    QR: TquickRep;
    QB2: TQRBand;
    QB3: TQRChildBand;
    QL: TQRLabel;
    QS : string;
begin
  with artikste do
  begin
    close;
    sql.Clear;
    sql.add('SELECT * FROM Artikels');
    open;
    first;
  end;

  QR := QR_ARDEMO;
  QB2 := QRBAND2;

  QB2.HasChild := true;
  QB2.ChildBand.Height := 23;
  QL := TQRLabel.Create(QR);
  QL.Parent := QB2.ChildBand;
  QL.Left := 100;
  QL.Top := 1;
  QL.Width := 81;
  QL.Height := 23;
  QL.Caption := 'QRLabeXX';

  QB2.ChildBand.HasChild := true;
  QB2.ChildBand.ChildBand.Height := 23;
  QL := TQRLabel.Create(QR);
  QL.Parent := QB2.ChildBand.ChildBand;
  QL.Left := 100;
  QL.Top := 1;
  QL.Width := 81;
  QL.Height := 23;
  QL.Caption := 'QRLabeYY';

  QB2.ChildBand.ChildBand.HasChild := true;
  QB2.ChildBand.ChildBand.ChildBand.Height := 23;
  QL := TQRLabel.Create(QR);
  QL.Parent := QB2.ChildBand.ChildBand.ChildBand;
  QL.Left := 100;
  QL.Top := 1;
  QL.Width := 81;
  QL.Height := 23;
  QL.Caption := 'QRLabeZZ';
end;

end.

This works (huray). But now the problem is: How do I get an array of childband.chhildband......childband. There is no Childband array like Childband[x]. Or is there one?? As I wrote there could be many Childbands [n]. It has to be dynamic, and... after printing the first childbands, they must be destroyed, before printing the next childbands for the next record (Artikel).


Q: Incrementing a field in JSON from angular controller I have a schema that includes a field like so: flagCount  : Number.
I am trying to increment the count by 1 when the user clicks a button (the reportListing button). The button is inside a HTML page and looks like:
  <img class="flagIcon" id="flag" src="../../../images/red_flag_icon.jpg" background-color=transparent ng-hide="hide" ng-click="reportListing()"/>

Relevant part of the controller:
app.controller('ListingController', function ($scope, $location, $http) {

    $scope.hide = false;
    $scope.reportListing = function() {
        $http.get("/api/listing/:street/:buildingNumber/:apartmentNumber").success(function (apartment){
            //var count = apartment.flagCount;
            sweetAlert("Thank you!", "This listing has been reported", "success");
            $scope.hide = true;
        });
    };

I have tried several ways but failed as I can't access the flagCount to update it (is it only possible through the back-end (Node)) ?

A: node will have to send a response object with the flagCount property if you want to use it in the frontend. If the flagCount is just getting saved in a database you do not need to use a get request for it.
You could use a post request instead. A post request is useful to change database info.
Node can respond with the flagCount if you need it on the frontend.
If you do need the flagCount then check the node response object to see if it is sending it. If the flagCount is used in the browser than you could also save it and retrieve it in an angular service.


Q: org.eclipse.core dependency to org.eclipse.runtime suddenly changed We compile an Adobe CQ project (services, taglib, view, content, etc.) with maven. At some point in time, we introduced the following dependencies:
        <dependency>
            <groupId>org.eclipse.core</groupId>
            <artifactId>resources</artifactId>
            <version>3.3.0-v20070604</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.equinox</groupId>
            <artifactId>registry</artifactId>
            <version>3.3.0-v20070522</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.core</groupId>
            <artifactId>jobs</artifactId>
            <version>3.3.0-v20070423</version>
        </dependency>

This resulted in the following dependencies e.g. for org.eclipse.resources (extracted with mvn dependency:tree -Dverbose ):
[INFO] +- org.eclipse.core:resources:jar:3.3.0-v20070604:compile
[INFO] |  +- org.eclipse.core:expressions:jar:3.3.0-v20070606-0010:compile
[INFO] |  |  \- (org.eclipse.core:runtime:jar:3.3.100-v20070530:compile - omitted for duplicate)
[INFO] |  +- org.eclipse.core:filesystem:jar:1.1.0-v20070606:compile
[INFO] |  |  +- (org.eclipse.equinox:common:jar:3.3.0-v20070426:compile - omitted for duplicate)
[INFO] |  |  +- (org.eclipse.equinox:registry:jar:3.3.0-v20070522:compile - omitted for duplicate)
[INFO] |  |  \- (org.eclipse:osgi:jar:3.3.0-v20070530:compile - omitted for duplicate)
[INFO] |  \- org.eclipse.core:runtime:jar:3.3.100-v20070530:compile
[INFO] |     +- (org.eclipse:osgi:jar:3.8.2.v20130124-134944:compile - omitted for duplicate)
[INFO] |     +- (org.eclipse.equinox:common:jar:3.3.0-v20070426:compile - omitted for duplicate)
[INFO] |     +- (org.eclipse.core:jobs:jar:3.3.0-v20070423:compile - omitted for duplicate)
[INFO] |     +- (org.eclipse.equinox:registry:jar:3.3.1:compile - omitted for duplicate)
[INFO] |     +- org.eclipse.equinox:preferences:jar:3.2.100-v20070522:compile
[INFO] |     |  \- (org.eclipse.equinox:common:jar:3.3.0-v20070426:compile - omitted for duplicate)
[INFO] |     +- org.eclipse.core:contenttype:jar:3.2.100-v20070319:compile
[INFO] |     |  +- (org.eclipse.equinox:preferences:jar:3.2.100-v20070522:compile - omitted for duplicate)
[INFO] |     |  +- (org.eclipse.equinox:registry:jar:3.3.1:compile - omitted for duplicate)
[INFO] |     |  \- (org.eclipse.equinox:common:jar:3.3.0-v20070426:compile - omitted for duplicate)
[INFO] |     \- org.eclipse.equinox:app:jar:1.0.0-v20070606:compile
[INFO] |        +- (org.eclipse.equinox:registry:jar:3.3.1:compile - omitted for duplicate)
[INFO] |        \- (org.eclipse.equinox:common:jar:3.3.0-v20070426:compile - omitted for duplicate)

Then, from Monday 19th of August 2013 to the 20th of August, the org.eclipse:osgi dependency suddenly changed from 3.3.0-something to 3.8.2-something without any apparent reason (This broke our build quite nastily):
[INFO] +- org.eclipse.core:resources:jar:3.3.0-v20070604:compile
[INFO] |  +- org.eclipse.core:expressions:jar:3.3.0-v20070606-0010:compile
[INFO] |  |  \- (org.eclipse.core:runtime:jar:3.3.100-v20070530:compile - omitted for duplicate)
[INFO] |  +- org.eclipse.core:filesystem:jar:1.1.0-v20070606:compile
[INFO] |  |  +- (org.eclipse.equinox:common:jar:3.3.0-v20070426:compile - omitted for duplicate)
[INFO] |  |  +- (org.eclipse.equinox:registry:jar:3.3.0-v20070522:compile - omitted for duplicate)
[INFO] |  |  \- org.eclipse:osgi:jar:3.8.2.v20130124-134944:compile
[INFO] |  \- org.eclipse.core:runtime:jar:3.3.100-v20070530:compile
[INFO] |     +- (org.eclipse:osgi:jar:3.8.2.v20130124-134944:compile - omitted for duplicate)
[INFO] |     +- (org.eclipse.equinox:common:jar:3.3.0-v20070426:compile - omitted for duplicate)
[INFO] |     +- (org.eclipse.core:jobs:jar:3.3.0-v20070423:compile - omitted for duplicate)
[INFO] |     +- (org.eclipse.equinox:registry:jar:3.3.1:compile - omitted for duplicate)
[INFO] |     +- org.eclipse.equinox:preferences:jar:3.2.100-v20070522:compile
[INFO] |     |  \- (org.eclipse.equinox:common:jar:3.3.0-v20070426:compile - omitted for duplicate)
[INFO] |     +- org.eclipse.core:contenttype:jar:3.2.100-v20070319:compile
[INFO] |     |  +- (org.eclipse.equinox:preferences:jar:3.2.100-v20070522:compile - omitted for duplicate)
[INFO] |     |  +- (org.eclipse.equinox:registry:jar:3.3.1:compile - omitted for duplicate)
[INFO] |     |  \- (org.eclipse.equinox:common:jar:3.3.0-v20070426:compile - omitted for duplicate)
[INFO] |     \- org.eclipse.equinox:app:jar:1.0.0-v20070606:compile
[INFO] |        +- (org.eclipse.equinox:registry:jar:3.3.1:compile - omitted for duplicate)
[INFO] |        \- (org.eclipse.equinox:common:jar:3.3.0-v20070426:compile - omitted for duplicate)

We were able to resolve this by adding the dependency explicitely:
    <dependency>
        <groupId>org.eclipse</groupId>
        <artifactId>osgi</artifactId>
        <version>3.3.0-v20070530</version>
    </dependency>

But still, we do not have any clue, why the dependency changed. Does anybody know the reason or experienced the same issue?

A: After digging through pom files, .m2/repository/repository.xml and several maven-metadata.xml files, I found the root cause.
The maven-metadata.xml file in Maven repository http://repo.adobe.com for org.eclipse.osgi seems to have been changed on 20th August. For some reason the date of this file was reset now to 11th of July, but the change remains:
The metadata file changed from
<metadata>
<groupId>org.eclipse</groupId>
<artifactId>osgi</artifactId>
<version>3.3.0-v20070530</version>
<versioning>
<versions>
...
</versions>
<lastUpdated>20071127073207</lastUpdated>
</versioning>
</metadata>

to
<metadata modelVersion="1.1.0">
<groupId>org.eclipse</groupId>
<artifactId>osgi</artifactId>
<version>3.3.0-v20070530</version>
<versioning>
<latest>3.8.2.v20130124-134944</latest>
<release>3.8.2.v20130124-134944</release>
<versions>
...
</versions>
<lastUpdated>20130711152942</lastUpdated>
</versioning>
</metadata>

Obviously, the latest version was provided after the change, which is now 3.8.2 and not 3.3.0 anymore.

A: The problem is likely caused by version ranges. These ranges do not even have to be used for the Eclipse artifacts.
Assume you depend on [1,2) and 1.1, and 1.2 are available. At a moment in time, 1.3 is added that has different dependencies. If it finds multiple groupId:artifactId with a different version then it picks the first it finds. Maven follows a breadth first strategy to find dependencies so that you can override it in your top level pom. This is of course very obscure and error prone. A better way is to specify all your app dependencies in one pom so you can ensure valid versions.


Q: Generate a column with random digit with mean = 20, maximum = 25 and minimum = 5 as quickly as possible in pandas I have a df as shown below
        df = pd.DataFrame({'Session': ['s1', 's1', 's1', 's1', 's1', 's1', 's1',
                                       's1', 's1', 's1', 's1', 's1', 's1', 's1', 's1'],
                          'slot_num': [1, 2, 3, 3, 4, 4, 5, 5, 6, 7, 7, 8, 8, 9, 9]})

df:
Session         slot_num
s1              1
s1              2
s1              3
s1              3
s1              4
s1              4
s1              5
s1              5
s1              6
s1              7
s1              7
s1              8
s1              8
s1              9
s1              9

From the above I would like to create a column called service_time randomly with mean exactly 20, maximum is 25 and minimum 2 as quickly as possible.
I tried below code but it is not giving the mean exactly 20.
Note: Service time should contain whole numbers only
# generate service time with mean = 20, min = 2 and max = 25
def gen_avg(n, expected_avg=20, a=2, b=25):
    l = np.random.randint(a, b, size=n)
    while True:
        if np.mean(l) == expected_avg:
            break
        while np.mean(l) > expected_avg:
            c = np.random.choice(np.where(l>expected_avg)[0])
            l[c] = np.random.randint(a, expected_avg+1)
        while np.mean(l) < expected_avg:
            c = np.random.choice(np.where(l<expected_avg)[0])
            l[c] = np.random.randint(expected_avg, b)
        return l

df['service_time'] = df.groupby('Session')['Session'].transform(lambda x: gen_avg(len(x)))

I tried below one as well but it is taking very long time
#https://stackoverflow.com/a/39435600/2901002
def gen_avg(n, expected_avg=20, a=5, b=25):
    while True:
        l = np.random.randint(a, b, size=n)
        avg = np.mean(l)

        if avg == expected_avg:
            return l

df['service_time'] = df.groupby('Session')['Session'].transform(lambda x: gen_avg(len(x)))

A: It is probably taking a long time because you are expecting the mean to be exactly equal to the expected_avg. Because it is a random variable in which one out of n observations can change the average, this is a problem, especially as n grows. If this is allowed, you could use a method such that the mean is sufficiently close, e.g. at most 5% away. Suppose that we call this tolerance. Try something like the following:
while abs((avg-expected_avg)/expected_avg) > tolerance:
  l = np.random.randint(a, b, size=n)
  avg = np.mean(l)


Q: Laravel 4 : model assocation (belongsTo) I have a very simple tables association with laravel 4 :
foods table
  id
  name
  food_category_id

food_categories table
  id
  name

Here are my two models:
//models/Food.php
class Food extends Eloquent {
    public function food_category()
    {
        return $this->belongsTo('FoodCategory');
    }
}

//models/FoodCategory.php
class FoodCategory extends Eloquent {

}

When trying to extract category information form the Food model :
in controller:
class FoodController extends \BaseController {
    public function index()
    {
        $foods = Food::all();
        return View::make('admin/food/index',compact('foods'));
    }
}

In view:
@foreach($foods as $food)

            {{ $food->id }}
            {{ $food->name }}
            {{ $food->description}}
            {{ $food->price}}
            {{ $food->food_category->name }}

@endforeach

I get the below error message :
Trying to get property of non-object (View:
/Library/WebServer/Documents/xxx/test/app/views/admin/food/index.blade.php)
Based on the dynamic properties, data should be available from ->food>category

*

*I've followed the naming convention for laravel.

*Data exists in the database

Debugging with dd(DB::getQueryLog()) :
array(2) { [0]=> array(3) { ["query"]=> string(44) "select * from `users` where `id` = ? limit 1" ["bindings"]=> array(1) { [0]=> int(6) } ["time"]=> float(0.79) } [1]=> array(3) { ["query"]=> string(21) "select * from `foods`" ["bindings"]=> array(0) { } ["time"]=> float(0.32) } }

======= UPDADED
When adding eager loading :
$foods = Food::with('food_category')->get();

I got  :
array(3) { [0]=> array(3) { ["query"]=> string(44) "select * from `users` where `id` = ? limit 1" ["bindings"]=> array(1) { [0]=> int(6) } ["time"]=> float(0.52) } [1]=> array(3) { ["query"]=> string(21) "select * from `foods`" ["bindings"]=> array(0) { } ["time"]=> float(0.42) } [2]=> array(3) { ["query"]=> string(67) "select * from `food_categories` where `food_categories`.`id` in (?)" ["bindings"]=> array(1) { [0]=> string(1) "1" } ["time"]=> float(3.23) } }

A: It seems like your relations are inverted. You are asking for food_category through food. So food has a food_category and food_category belongs to food if this should be hasOne or hasMany I can't see from your example.
Database
foods table
  id
  name

food_categories table
  id
  name
  food_id

models/Food.php
class Food extends Eloquent {
    public function food_category()
    {
        return $this->hasOne('FoodCategory');
    }
}

models/FoodCategory.php
class FoodCategory extends Eloquent {

}

A: Try with eager loading:
$foods = Food::with('FoodCategory')->get();

A: I think to resolve this question, you have two choice:
Fisrt:
public function category()
{
    return $this->belongsTo('FoodCategory');
}

Then do {{ $food->category->name }} which is more elegant
Second:   just add 'id'
public function food_category()
{
    return $this->belongsTo('FoodCategory','food_category_id');
}


Q: Procedure or function expects parameter which was not supplied Driving me mad on a personal project; I know I've done this before but elsewhere and don't have the code.  As far as I can see, I'm setting the parameter, I'm setting its value, the connection is open, yet when I try to fill the dataset I get the error 'Procedure or function expects parameter "@test" which was not supplied'.
(This is obviously a simplified test! Same error on this or the real, rather longer code though.)
C#:
SqlCommand l_oCmd;
DataSet l_oPage = new DataSet();

l_oCmd = new SqlCommand("usp_test", g_oConn);
l_oCmd.Parameters.Add(new SqlParameter("@test", SqlDbType.NVarChar));
l_oCmd.Parameters[0].Value = "hello world";

SqlDataAdapter da = new SqlDataAdapter(l_oCmd);
da.Fill(l_oPage);

SQL:
create procedure usp_test
(
    @test nvarchar(1000)
)
as
select @test

What have I missed?

A: Change the command type to Procedure


Q: create a simple ImageSlider using any of react-native libraries I am new to React-Native and I am currently struggling out for creating a simple Image-slider in react-native. I went through some of the links like: https://reactnativeexample.com/tag/carousel/
But not able to figure out if react-native provides a library which I can import directly in my code to implement an Image-slider.
Is there a native library which I can use or is there some other procedure to create an image-slider?
I want a slider as presented in this website: https://www.jssor.com/

A: For example, when you want to use react-native-snap-carousel, you can follow the instructions in the usage part of that link
https://github.com/archriss/react-native-snap-carousel#usage
And also, If you want to use so simple carousel, you can use
<FlatList horizontal={true}/>


Q: Create custom Regressor in sklearn I would like to use a custom Regressor with sklearn GridSearchCV. The spirit of it is analogous to creating a custom Classifier - as shown in this blog:
http://danielhnyk.cz/creating-your-own-estimator-scikit-learn/
Here is a condensed/edited portion of the code from the blog - showing some of the required methods to override.
from sklearn.base import BaseEstimator, RegressorMixin

class MyCustomClassifier(BaseEstimator, RegressorMixin):
    """An example of classifier"""

    def __init__(self, intValue=0, stringParam="defaultValue", otherParam=None):
        """
        Called when initializing the classifier
        """
        self.intValue = intValue
        self.stringParam = stringParam

    def fit(self, X, y=None):
        self.treshold_ = (sum(X)/len(X)) + self.intValue  # mean + intValue

        return self

    def _meaning(self, x):
        # returns True/False according to fitted classifier
        # notice underscore on the beginning
        return( True if x >= self.treshold_ else False )

    def predict(self, X, y=None):
         ..

The things that would be same between Regressor and Classifier would likely be the __init__, fit, predict methods: I can probably piece that much together. But what about equivalents to __meaning ? Or other subtle considerations for a Regressor that might not be obvious/clear?
Here is a skeleton I am starting with:
from sklearn.base import BaseEstimator, RegressorMixin
class MyCustomRegressor(BaseEstimator, RegressorMixin):
    def __init__(self, regressorMethod):
      self.regressorMethod = regressorMethod

    def fit(self, X, y=None):
      self.regressorMethod(X,y)
      return self

It is my understanding that the score method will be used by GridSearchCv ..?


Q: Simple way to check for membership in a list? For use in a closure (though I suppose it will be useful elsewhere as well), what is the cleanest way to check to see whether or not a given element is a member of a list (or any character is a member of a string)?
For example, to check whether or not the string "abcde" contains any of the characters in "aeiou", or whether the list ["bill", "sam" , "suzy"] contains any of the names in ["abe", "bill", "charlie"]?

A: Swift arrays have built in functions for this exact functionality.
I recommend checking out the official documentation for Collection Types from Apple for a starting point.
Here is an example that follows your question:
// With [Character]
let vowels: [Character] = ["a", "e", "i", "o", "u"]
let chars: [Character] = ["a", "b", "c", "d", "e"]
let resultVowels = vowels.filter { chars.contains($0) }
resultVowels.count // == 2
resultVowels.description // == "[a, e]"

// With [String]
let people = ["Bill", "Sam", "Suzy"]
let peeps = ["Abe", "Bill", "Charlie"]
let resultPeople = people.filter { peeps.contains($0) }
resultPeople.count // == 1
resultPeople.description // == "[Bill]"

The result will be the names (or numbers, characters, etc.) that are matching up. So you can not only get the count, but also the contents of the comparison in this procedure. So long as the types follow Equatable, this will work for you.
If you want to return a Boolean, just simply:
return filteredArray.count != 0

Now, if you want to compare say, a [Character] to a String then:
let vowels: [Character] = ["a", "e", "i", "o", "u"]
let someString = "abcde"
let result = vowels.filter { someString.characters.contains($0) }
result.count // == 2
result.description // == "[a, e]"

The String.characters property is a new feature brought in to Swift 2.
I hope I was able to assist you.

A: 1 ) Common chars in 2 words
You easily check the intersection of the common chars in 2 strings using the Set struct:
let set0 = Set("abcde".characters)
let set1 = Set("aeiou".characters)

let intersection = set0.intersect(set1) // {"e", "a"}

2) Common words in 2 lists
Similarly you can find the intersection of 2 arrays of strings:
let set0 : Set = ["bill", "sam", "suzy"]
let set1 : Set = ["abe", "bill", "charlie"]

let intersection = set0.intersect(set1) // {"bill"}

3) Back to Array
Please note that in both examples, the intersection constant is a Set. You can transform it into an Array writing:
let list = Array(intersection)

Hope this helps.
P.S. This code is for Swift 2.0
Update
More specifically if you want to find out whether an intersection exists you can simply write:
 !intersection.isEmpty


Q: How to extract two rgb values/strings from the another string using regex or another method The following string has been retrieved from an element's style attribute, the attribute is a variable and can contain different colors in a particular vertical gradient background:
string = "background: linear-gradient(0deg, rgb(100, 106, 237) 0%, rgb(101, 222, 108) 100%) repeat scroll 0% 0% transparent; display: list-item; cursor: pointer;"
Using the following code, the linear-gradient contents is extracted from the string:
string = string.substring(string.indexOf('linear-gradient('), 1+string.lastIndexOf(')')); // string = "linear-gradient(0deg, rgb(100, 106, 237) 0%, rgb(101, 222, 108) 100%)"
Now using a regular expression -or any other method- I need to extract both the first rgb -rgb(100, 106, 237)- value as-well as the second -rgb(101, 222, 108). Can anyone please recommend/suggest a simple method to achieve this. Thanks in advance.

A: You can use this regular expression to extract all rgb codes:
var regex = /rgb\(([^\)]+)\)/g;

A: You can use this:
string.replace(/^.*?linear-gradient *\((.+)/, function($1, $2) {
                         return $1.match(/rgb *\([^)]+\)/g); } );
//=> rgb(100, 106, 237),rgb(101, 222, 108)

Assuming there is no other rgb segment outside closing bracket of linear-gradient

A: There is no need for your first extracting. Try the following:
var re = /rgb\(\d{1,3}, ?\d{1,3}, ?\d{1,3}\)/g;

// and then get array of matches

var rgbs = string.match(re);

//It will be equal to null if there is no matches.


Q: How to choose python 3.5.1 executable for project on Xcode 7? I want to set up a python 3 project in Xcode, but I fail in the step where I'm asked to choose an executable for the scheme. See step 16 in the answer to Python in Xcode 4+?.
I use "which python3" to locate the executable:
$ which python3
/usr/local/bin/python3

but Xcode does not let me choose python3 from "/usr/local/bin" by clicking on it:

If I try following the suggestion of trojanfoe below to uncover the symbolic link through:
    ls -l /usr/local/bin/python3
I get to "../Cellar/python3/3.5.1/bin/python3" which in turn is a symbolic link pointing to "../Frameworks/Python.framework/Versions/3.5/bin/python3" which finally points at "Python3.5" in that directory. However, my Xcode also is not willing to let me select this file:

I'm running Xcode 7.3.1 in OS X 10.11.4. I've installed python 3.5.1 with home-brew.

A: I just finished wrestling with this for about three hours.
    Okay, short answer (which marken, above, deserves credit for): Just right-click the dimmed out python3 executable, then click "Quick Look", then hit the space bar to exit the quick-look, and notice the executable is now selected, and just hit enter, or click "Choose".
    I have the following explanation to offer. The reason for our ability to see--but not to select--the python3 executable is that Homebrew uses a file alias, /usr/local/bin/python3, which brew's installation is given restricted permissions that Xcode is unable to pre-select, for reasons I am unsure of. (You might notice you can tediously select the executable at each and every runtime.) The alias points, in my case, to the Homebrew "Cellar"; for your reference, using the Terminal app to execute,ls -al /usr/local/bin/python3 reveals that my it's aliased to the true Homebrew python3 executable located at /usr/local/Cellar/python3/3.5.2_3/bin/(python3).

A: In the file selection window right-click on python3.5 and select quick look. Close the quick look window and python3.5 will become selectable.
(images attached show workflow referencing the newer python3.6 - it is the same for all python releases).
Right click on python executable
Pop up window will be shown
Select quicklook
Python executable has been selectable and "choose" button is clickable

A: Just right click and Quick Look option works. File becomes selectable, and then you can choose to specify it as an executable in your Xcode project.

A: If you are using Anaconda, you can install the python.app package:
conda install python.app

Then, in Xcode, select </path/to/anaconda-environment>/python.app/Contents/MacOS/python.
(Note: Do not select the python.app in the bin directory (</path/to/anaconda-environment>/bin/python.app), which will result in some error regarding the Mach-O header.)


Q: unable to use await while doing multiple fetch requests I am fetching data from an API. The first fetch URL i pass the data it returns success and the other fetch URL then using second fetch URL i fetch the data and print it. I was unable to use await as after doing a fetch request of the first URL its takes time for the second fetch URL to gets the data before calling it for the data so i was thinking to use await. The input is CC(C)(C)Br. Here is the code link
import React, { useState } from "react";
import TextField from "@mui/material/TextField";
import Button from "@mui/material/Button";

async function App() {
  const [solutestate, setSolutestate] = useState("");
  const [fetchData, setFetchData] = useState("");
  const [jsondata, setjsonData] = useState("");
  console.log(solutestate);
  console.log(fetchData);

  let params = new URLSearchParams({
    solute: solutestate
  });

  const onSubmit = (e) => {
    e.preventDefault();
    let [res1, res2] = await Promise.all([
      fetch(
        `https://fastapi-ihub-n7b7u.ondigitalocean.app/predict_two?${params}`,
        {
          method: "GET"
        }
      ),
      fetch(
        `https://fastapi-ihub-n7b7u.ondigitalocean.app/predict_solubility_json`,
        {
          method: "GET"
        }
      )
    ]);
    setFetchData(res1);
    setjsonData(res2);
  };

  return (

      <>
        <form noValidate onSubmit={onSubmit}>

            Input: CC(C)(C)Br
            <TextField
              label="Solute"
              variant="outlined"
              onChange={(e) => setSolutestate(e.target.value)}
            />
            <Button type="submit" variant="contained">
              Submit
            </Button>
            <TextField label="Result" variant="outlined" value={fetchData} />
            {jsondata}

        </form>
      </>

  );
}
export default App;

A: The await keyword is only valid on places where asynchronous code is accepted.
The easiest here is to make the onSubmit funcion async.
const onSubmit = async (e) => {
    let [res1, res2] = await Promise.all([
        fetch(
            `https://fastapi-ihub-n7b7u.ondigitalocean.app/predict_two?${params}`,
            {
                method: "GET"
            }
        ),
        fetch(
            `https://fastapi-ihub-n7b7u.ondigitalocean.app/predict_solubility_json`,
            {
                method: "GET"
            }
        )
    ]);

// etc
}

A: React components cannot be made async like this. What you probably want is to execute an async callback once the button is clicked.
const onSubmit = async (e) => {
    e.preventDefault();
    let [res1, res2] = await Promise.all([ /* ... */ ]);
    setFetchData(res1);
    setjsonData(res2);
}

If you don't want your handler function itself to be async, you can also just call a new async function:
const onSubmit = (e) => {
    e.preventDefault();
    const fetchData = async () => {
        let [res1, res2] = await Promise.all([ /* ... */ ]);
        setFetchData(res1);
        setjsonData(res2);
    }
    fetchData();
}


Q: MySQL query help I have two tables with the following structure:
Table_1
No  Name
1   Test1
2   Test2
2   Test3

Table_2
t_no  t_name  no
1     tname1  1
2     tname2  2

How can I write a query to get the result below
t_no  t_name  Name
1     tname1  Test1
2     tname2  Test3

In Table1 two records have the same id but different values (i.e the difficulty).

A: Assuming your tables are named table_1 and table_2
SELECT
  table_2.t_no,
  table_2.t_name,
  table_1.Name
FROM table_1 JOIN table_2 ON table_1.no = table_2.t_no

Or another method:
SELECT
  table_2.t_no,
  table_2.t_name,
  table_1.Name
FROM table_1, table_2
WHERE table_1.no = table_2.t_no

A: SELECT
  grpt1.t_no,
  grpt1.t_name,
  table_2.Name
FROM table_2
  JOIN
    ( SELECT t_no
           , MAX(t_name)
      FROM table_1
      GROUP BY t_no
    ) AS grpt1
    ON table_2.no = grpt1.t_no


Q: Material-UI Select doesn't update after onChange I've seen this problem about all around the web but nothing could come short of giving me a valid explanation.
I'm using Material-UI Select and the good ol' setState(...) from React (not hooks though)
My component is composed essentially of those lines :
class MyComponent extends Component {

exportOptions = ['CSV','SDF']

  constructor(props) {
    super(props);
    this.state = {
[...]
      formatToExportTo : this.exportOptions[0]
    };

[...]

<Select value={this.state.formatToExportTo}
        style={{width : "10em"}}
        onChange={event=> {
            this.setState({formatToExportTo : event.target.value})
        }}>{
            this.exportOptions.map(f=><MenuItem key={f} value={f}>{f}</MenuItem>)
        }</Select>,

And my problem is that my Select component dosen't update its value after selecting another option.
So far I've tried :

*

*setState({...this.state, formatToExport : event.target.value}) in the onChange= of the Select and in the Select tag : value = {this.state.formatToExport}

*setState({...this.state, formatToExport : event.target.value}) in the onClick= of each options and in the Select tag : value = {this.state.formatToExport}. But that was only to see the update, because the event.target.value isn't right anyway

*and the current version of my lines written above also onClick OR onChange (without tthe cloning of state which is supposed to be done by setState alone).

It's like in the official example so I truly don't see where this lack of update could come from. No matter what I try, the currently displayed value of the Select component doesn't change is display, even though the state was properly updated
Thank you for the time you took to read me !

A: After searching for 3 hours total :
normally value={this.state.formatToExportTo} should work ( I tried it alone without the rest of my app surrounding it)
But since I made some quircky things with my this and the order of update, I just had to replace :
value={this.state.formatToExportTo} by defaultValue={this.state.formatToExportTo}
That's all ! I hope it helps someone who'll come by this question


Q: Outbound Email bounce processing - is it possible to set requires SSL? I'm configuring Outbound Email Bounce processing using Tridion 2011, but am getting the following error:
errCannotAccessPOP3Account

StackTrace Information Details:
   at Tridion.OutboundEmail.Services.BounceProcessor.BounceInbox.ProcessPop3Mailbox(XmlDocument analyzedMessages)
   at Tridion.OutboundEmail.Services.BounceProcessor.BounceInbox.ProcessMessages()
   at Tridion.OutboundEmail.Services.BounceProcessor.BounceProcessorService.ProcessItem(UserContext userContext, BounceInbox inbox)
   at Tridion.AudienceManagement.DomainModel.Utilities.OutboundEmailServiceBase`1.Process(UserContext userContext)

In OutboundEmail.xml there is a section to configure Bounce Processing:
<BounceProcessing>
    <PollingInterval>300</PollingInterval>
    <Mailbox name="MailBounce">
      <Protocol>POP3</Protocol>
      <Server>pop.gmail.com</Server>
      <Port>995</Port>
      <User></User>
      <Password></Password>
      <ImapFolder></ImapFolder>
      <Forwarding>
        <Server>localhost</Server>
        <Port>25</Port>
        <SenderName>Forwarder</SenderName>
        <SenderAddress>forwarder@localhost</SenderAddress>
        <SuccessSubject></SuccessSubject>
        <SuccessAddress>bounced@localhost</SuccessAddress>
        <SuccessMessage></SuccessMessage>
        <FailedSubject></FailedSubject>
        <FailedAddress>replies@localhost</FailedAddress>
        <FailedMessage></FailedMessage>
      </Forwarding>
    </Mailbox>
  </BounceProcessing>

However, there is not a section to enable SSL, which might be the cause of my error?
Is it possible to enable SSL for Tridion Outbound Email Bounce processing?

A: Outbound E-mail doesn't specifically handle SSL, an enhancement request has been created to remedy this. However, Outbound E-mail uses Chilkat software, whose documentation seems to indicate that SSL should be chosen automatically when using port 995 (though I've not tried this). The above shown configuration doesn't actually contain a user / password, I imagine you've actually tried it with credentials?


Q: ui:param - passing method arguments I have two xhtml files, one includes another. I already know how to pass the controller and method to be called to the dialog, what I am not sure is possible, is to actually pass arguments/objects to the method that will be called. I tried something like this, but Eclipse tells me there is syntax error in this part

actionListener="#{bean[confMethod(param1, param2)]}"

but it does not have any problem with just

actionListener="#{bean[confMethod]}"

file1.xhtml:
<ui:composition>
.....
    <ui:include src="/jsf/include/dg_confirm.xhtml">
        <ui:param name="bean" value="#{myController}" />
        <ui:param name="question" value="Are you sure?" />
        <ui:param name="confMethod" value="myMethod" />
        <ui:param name="param1" value="#{otherController.param1}" />
        <ui:param name="param2" value="#{urlToFollow}" />
    </ui:include>

</ui:composition>

and the dialog
dg_confirm.xhtml
....
<p:commandButton value="Yes" oncomplete="PF('dlg_conf').hide();" actionListener="#{bean[confMethod(param1, param2)]}" ajax="false"/>
.....

Question: Is it possible to pass argument for the method somehow in JSF?

A: actionListener="#{bean[confMethod(param1, param2)]}"

This syntax is indeed invalid. You're basically expecting that the confMethod is a static function which returns the name of the dynamic method based on the given two arguments.
The correct syntax is as below:
actionListener="#{bean[confMethod](param1, param2)}"


Q: repeating macro I am looking for a marcro that can copy and paste cells.
The value of cell X must be copied to a cell X + 6.
So A1 text "Xteam" has to be copied to cell A7, this up to cell A380.
The same applies to cell B2 + 6.
It has to be dynamic, so the cell and sequence are dynamic..
I want to be able to indicate for myself which cell it is and the sequence ..
How can I do this,
I have this but doesnot work like i want:
Sub sequence()
Const Nxt As Long = 7
Dim A As Variant, B As Variant, V As Variant, N As Long
A = Range("A1").Value
B = Range("B2").Value
ReDim V(Nxt To 380, 1 To 2)
For N = Nxt To 380
    If N Mod 6 = 1 Then
        V(N, 1) = A
        V(N + 1, 2) = B
    End If
Next N
Application.ScreenUpdating = False
Range("A" & Nxt, "B380").Value = V
Application.ScreenUpdating = True
End Sub

thank you in advance
elmalle

A: Ok well, this is under the assumption that you want to specify how many times you want to copy A1 and B2 down the sheet. So your loop is fairly confusing, instead of using MOD, since you know you want it every 6 spaces and you're not doing anything to the other cells, it's easier just to have the number multiplied by 6 for your indexing. This also helps you figure out the dimensions of your transfer arrays more easily since you want to specify how many times you want to copy.
It's also worth noting that you're Application.screenupdating = False is in the wrong place. The real place you would want to speed up is during the loop. So if you were to include it, I would put it near the top of the code, but this isn't very resource intensive so I've just left it out.
Normally it's good to dim Constants if it helps with the legibility of the code, but in this case it doesn't seem to add any clarity. An example where it could help is where you're changing the colour of cells and are using colour indices. Constant Red as long = 3 makes it a lot more understandable, whereas constant Nxt as long = 7 doesn't add much.
Instead of working with a 2-D array dealing with both A and B at once, I chose to use two column vectors because it makes the pasting easier since they are staggered and it simplifies the math since you don't need to have items on staggered rows.
Lastly, I can't advocate this enough, but please, please, please use names that make sense at a glance. Although it may not have made a huge difference in this case, if you get to a more complicated project people might look at it and have to wonder what V is even used for. It also just makes it easier for people to help you since they won't have to sit for a bit wondering what each variable means.
I've also specified the worksheet it looks at, so currently it'll only look at the first sheet as indicated by the index 1. Make sure you change that so it changes the correct sheet.
Hope this helped and welcome to Stack Overflow.
Option Explicit

Sub sequence()

    Dim A As Variant
    Dim B As Variant
    Dim N As Long
    Dim ArrA() As Variant
    Dim ArrB() As Variant
    Dim NumCopies As Long

    A = Range("A1").Value
    B = Range("B2").Value
    NumCopies = 100

    ReDim Preserve ArrA(1 To NumCopies * 6, 1 To 1)
    ReDim Preserve ArrB(1 To NumCopies * 6, 1 To 1)

    For N = 1 To NumCopies
        ArrA(N * 6, 1) = A
        ArrB(N * 6, 1) = B
    Next N

    Worksheets(1).Range("A2:A" & 1 + NumCopies * 6).Value = ArrA
    Worksheets(1).Range("B3:B" & 2 + NumCopies * 6).Value = ArrB

End Sub


Q: Validate null object In order to validate if model comes null or not I use something like this:
  if (model is null || !model.Any()) return this;

But in latest Microsoft conference I saw guys use something like:
    if(model is { })

I try to use it but always return true (if object comes null or not)
So my question is. Is there a new way to check if a model comes null?
What is the correct usage of brackets { }
Note: I googled about that brackets but I found anything. Regards

A: You can do a generic extension method to check if your object is null or not.
Try:
public static bool IsNullOrEmpty<T>(this IEnumerable<T> source) {
   return source?.Any() != true;
}

A: Another way to check for NullOrEmpty is to coerce Count() to an int?. Then we can compare the result of GetValueOrDefault to 0:
if((model?.Count).GetValueOrDefault() == 0) return this;

How it works:

*

*Because the ?. operator will return null if the left side is null, and Count returns an int, the result of (model?.Count) is a Nullable<int>.

*The GetValueOrDefault method returns the value of Count if model is not null, otherwise it returns default(int) (which is 0).

*This way if model is null, the condition returns 0


Q: Ninject Array Bind I'm trying to use Ninject with WPF
I have same interface for all my views
interface IView
{
  string ViewName { get; }
  object Content{ get; private set; }
}

public partial class FirstView : IView
{
    ......
}
public partial class SecundView : IView
{
  ......
}

etc..
At start of App I Bind them using
Kernel.Bind<IView>().To<FirstView>();
Kernel.Bind<IView>().To<SecundView>();
........
........

I'm interested is there a way to register them by convention?
Something like:
.Kernel.Bind(
            x => x.FromThisAssembly()
                  .SelectAllClasses().InNamespaceOf<FirstView>()
                  .BindToInterface<IView>);

A: You can use the BindDefaultInterfaces() method, which will bind every class which has the View word in their names to your IView interface:
.Kernel.Bind(
    x => x.FromThisAssembly()
          .SelectAllClasses().InNamespaceOf<FirstView>()
          .BindDefaultInterfaces());

You can also check the available "BindSomething" options in the documentation.


Q: Scroll table and store data in the list using Selenium web driver I'm working on a project where wanted to
1. Scroll the web page.
2. links are stored in the table
3. Click on the link present in the row
((JavascriptExecutor) driver).executeScript("window.scrollTo(0, document.body.scrollHeight)");
List<WebElement> req = driver
              .findElements(By.xpath("//table[@class='forceRecordLayout uiVirtualDataGrid--default uiVirtualDataGrid forceVirtualGrid resizable-cols']//tr"));

int total_req = req.size();
System.out.println(total_req);

for (int i = 0; i < total_req; i++) {
  String reqToClick = req.get(i).getText();
  if (reqToClick.equalsIgnoreCase("UPC_ 762016_Product Test- 06-07-2016 0")) {
      Thread.sleep(3000);
      req.get(i).click();
      Thread.sleep(3000);
      break;
  }
}

Above is the code where I'm storing data into the list, but the page is not scrolling down. List says showing count without scroll. Please help me out.

A: This seem to work for me:
            WebElement table = wait.until(presenceOfElementLocated(By.tagName("tbody")));
        int len = table.findElements(By.tagName("tr")).size();
        for (int index = 0; index < len; index++) {
            WebElement tr = table.findElements(By.tagName("tr")).get(index);
            //save information in row
            if (index == len - 1) {
                JavascriptExecutor jse = (JavascriptExecutor) driver;
                jse.executeScript("window.scrollBy(0,250)");
                len = table.findElements(By.tagName("tr")).size();

            }

        }

the length of the loop changes when you scroll down so it gets all the rows in the table

A: This will not scroll down the page but take all the links in the web table into the list and click on the link which you need.

A: public void ClickLink(string link)
{
    //scroll to table.

    Actions action = new Actions(driver);
    action.MoveToElement(driver.FindElement(By.Id("tableID"));

    //get elements in list
    List<WebElement> req = driver.findElements(By
        .xpath("//table[@class='forceRecordLayout uiVirtualDataGrid--defaultuiVirtualDataGrid forceVirtualGrid resizable-cols']//tr"));

    List<string> linkNamesList = new List<string>();

    //Click the required link.
    foreach(IWebElement element in req)
    {
      string linkName = element.text;
      if(linkName == link)
      {
        element.click();
        break;
      }
   }
}

This should work.
Thanks,
Rakesh Raut


Q: Get updated time of a particular row values in java I have a csv file. I want to add a column of Last updated in csv file i.e.
Name Last Updated
A        2:30
B        3:30
C        5:00
I'm not able to figure out how can i get the time when a row was last updated.
Any kind of help regarding this would be much appreciated.
Thanks


Q: why method "equals" skips the necessary chars although they are written in unicode? I splitted csv-file by "," but some numbers were written with using of this symbol so some numbers were splitted on some parts. The beginning and the end of the every splitted number are signed by """ so i tried to paste parts of the number focusing on quotation marks...
string[] inputData = File.ReadAllLines("file.csv");
        string[,] allData = new string[inputData.GetLength(0) - 1, 8];
        for (int i = 1; i < inputData.GetLength(0); i++)
        {
            string[] arrayHelpStupied = inputData[i].Split(",");
            string[] arrayHelpSmart = new string[8];
            int m = 0;
            int flagMistake = 0;
            string compoundingOfSplittedNumber = "";
            Console.WriteLine("\u0022");
            for (int j = 0; j < arrayHelpStupied.Length; j++)
            {
                string prov = arrayHelpStupied[j];
                if ((prov[0].Equals("\"")) || (flagMistake == 1))
                {
                    flagMistake = 1;
                    compoundingOfSplittedNumber += arrayHelpStupied[j];
                    if (arrayHelpStupied[j][^1].Equals("\u0022"))
                    {
                        flagMistake = 0;
                        arrayHelpSmart[m++] = compoundingOfSplittedNumber;
                        continue;
                    }
                    continue;
                }
                arrayHelpSmart[m++] = arrayHelpStupied[j];
            }

but numbers that start with quotation mark is ignored :(
please could you explain me the reason of such behaviour and how can i cope this difficulty please

A: If I'm reading the question correctly, you have a CSV file you're splitting on , and some of the "values" you're looking for also have a , in them and you don't want it to split on the , in the value...
Sorry, but it's not going to work.  String.Split does not have any overrides, or regex matching.  Your best bet is to sanitize your data first by removing the , from the values, or ensuring the , separating your values matches differently than the , in the values.
For example...
12,345 , 23,1566 , 111 , 1
you can split the above on " , " instead of just "," and since the pattern of " , " is consistent, then it will work
Alternately, you could open your csv in Excel and save it as a Tab delimited text file and then split on the tab "/t" character


Q: ImageMagick Command Line Photo Editing I have the following lightroom presets that I am trying to get as close to with CLI for ImageMagick7.
Highlights -20
Temp 7500
Tint +10
Sharpening 25
NoiseReduction 5
Color Noise Reduction 5


Q: In Android, how can i allow the user to choose a color between 4? I'm making an Android App, and i need to put a control that let user choose between 4 different colors. I want to do this with something like radio buttons: the problem is that radiobuttons are round...
is there a way to set them looks like square/rect buttons, and assign a color to their inside rect area ?
If not, how can i achieve that choose for the user ?
I need this because i'm making a Todo/Task android application, and i need the user to choose the priority of a task, between for priority level that are rapresented with a color. So i think to do that by showing 4 buttons, each with a different color associated, and a text inside ("0", "1", "2", "3")
Thanks!

A:
is there a way to set them looks like
  square/rect buttons, and assign a
  color to their inside rect area ?

Step #1: Copy $ANDROID_HOME/platforms/$API/data/res/drawable/btn_radio.xml to your project, where $ANDROID_HOME is where you have installed the Android SDK and $API is some Android platform (e.g., android-2.1)
Step #2: Copy $ANDROID_HOME/platforms/$API/data/res/drawable-hdpi/btn_radio* to your project
Step #3: Copy $ANDROID_HOME/platforms/$API/data/res/drawable-mdpi/btn_radio* to your project
Step #4: Modify those PNG files from steps #2 and #3 to suit your needs


Q: How to stop 2 digit numbers going to 00? Making a cookie clicker I encountered some problems including the title. Here is my code:

#imports

from getkey import getkey

#variables/strings/int whatever they're called

money = 0

cookies = 0

#loop

while True:

    print(f"{cookies}\n${money}\n\n[1]offer1: {offer1}")

    click = getkey()

    if click == "\n":

        cookies += 1

    if click == "1":

        for cookies in range(cookies):

            money += offer1

If cookies are sold to offer1 and it has 2 or more digits, it will show 2 numbers that may or may not be 00 or 0 (random num)
Does anyone have any idea to fix this?


Q: Why am Igetting the error "Could not load type 'CADE.main.index'." on a new server when I'm using the same code on all other instances, how fix it? I just checked out my "mixed" (asp classic and .Net) web site source from SVN on a new Windows 2019 Server.  When I go to the logon page (.asp classic), it's fine but when you logon and call the main page (.aspx) it throws the error: "Could not load type 'CADE.main.index'" and displays:
Line 1:  <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="index.aspx.cs" Inherits="CADE.main.index" %>

This SVN code is running on 15+ servers, including one 2019 Server. The code behind looks like:
namespace CADE.main
{
    public partial class index : BasePage  // Override with BasePage
    {

IIS and everything under Application Development is installed. IIS serves .asp, .txt, .gif, .png, even .Net handlers (.ashx) and web services (.asmx), just not the aspx pages.
So, I rebuilt the solution with VS2019 and published it, gave administrator permissions on the app pool, gave "Everyone" full permissions on the entire web, deleted the bin directories in both the source and web locations, ensured output path was bin/, cleaned the project, don't think I should change CodeBehind to CodeFile, and tried about every other thing that people have suggested on this web site but nothing has eliminated the error.
Question: How do I fix this error so the .aspx pages loads?
EDIT #1: 15 hours after post
I'm not sure but with this information maybe this should be a new post.
This error ONLY happens on the second web site. IIS is serving two web sites, separating them by host name (web1.com vs. web2.com) in bindings.  They both point at the same file structure.  Web1's subdirectories are natural while Web2's subdirectories are virtual directories that point to Web1's.
Web1: Normal IIS web
wwwroot

*

*LMW (subweb, LMW/Main/index.aspx is page in question, but works here)

Web2: Second web in IIS, based on host name, uses Web1's folders as virtual directories.
wwwroot

*

*WEB2 (folder under wwwroot)

*LMW (virtual directory points to Web1/wwwroot/LMW.  LMW/Main/index.aspx gives the error here)

Question: Why doesn't the .aspx work when it's a virtual directory?... it's the same file as is in Web 1?
EDIT #2
It is working but I don't know what I did to fix it.  I'm sure I changed something but I don't know what it was.  So, I created another web like web #2, New web folder under wwwroot with LMW a virtual directory pointing to Web1/wwwroot/LMW!  I'm seriously missing something, Any ideas?

A: These errors occur if the .aspx page or the Global.asax page contains a reference to a code-behind module and if the application has not been built.
You could try the below method to build the application:
Use the C# command-line compiler (CSC.exe) to run the following command:
csc /t:library /r:System.web.dll /out:mydll.dll myfile.cs

OR
In Microsoft Visual Studio .NET, click Build on the Build menu.
Also try changing CodeBehind="index.aspx.cs" to CodeFile="index.aspx.cs". This change is required when you change project type from website to webapplication or vice versa.
make sure you install the .ne framework feature of iis.

A: I actually created a brand new web that used a Virtual Directory for it's codebase that is the same code as the other webs.
Index.aspx resides in the /lmw/main directory.  I had created an Application on that folder when I was creating the other applications in the web.  So, I removed the "Application" from /lmw/main and it worked.


Q: regexp to check if input is only whole numbers (int) , and to check if another is only numbers with 2 decimal places I want to know what a regex would look like for:

*

*only whole numbers

*only numbers with less than or equal to two decimal places (23, 23.3, 23.43)

A: I. [1-9][0-9]* if the number should be greater than zero (any series of digits starting with a nonzero digit). if it should be zero or more: (0|[1-9][0-9]*) (zero or a nonzero number). If it can be negative: (0|-?[1-9][0-9]*) (zero or a nonzero number that can have a minus before it.)
II. a regex like I. followed by: (\.[0-9]{1,2})? that means, optionally a dot followed by one or two digits.

A: Only whole numbers:
/^\d+$/
         # explanation
\d       match a digit
 +       one or more times

Numbers with at most 2 decimal places:
/^\d+(?:\.\d{1,2})?$/

         # explanation
 \d       match a digit...
 +        one or more times
  (        begin group...
   ?:      but do not capture anything
   \.      match literal dot
   \d      match a digit...
   {1,2}   one or two times
  )        end group
 ?        make the entire group optional

Notes:

*

*The slashes denote start and end of pattern

*^ and $ are start and end of string anchors. Without these, it will look for matches anywhere in the string. So /\d+/ matches '398501', but it also matches 'abc123'. The anchors ensures the entire string matches the given pattern.

*If you want to allow negative numbers, add a -? before the first \d. Again, ? denotes "zero or one time."

Usage example:
var rx = new RegExp(/^\d+(?:\.\d{1,2})?$/);
console.log(rx.test('abc'));      // false
console.log(rx.test('309'));      // true
console.log(rx.test('30.9'));     // true
console.log(rx.test('30.85'));    // true
console.log(rx.test('30.8573'));  // false

A: Whole numbers only
/\d+/

One or two decimal places:
/\d(\.\d{1,2})?/


Q: WSO2 XML declaration in double quotes For WSO2ei 6.3.0, by default respond mediator is including XML declaration in single quotes
<? xml version=’1.0’ encoding=’UTF-8’?>
were as we need the XML declaration as;
<? xml version="1.0" encoding="UTF-8"?>


Q: AB Testing Framework Creation In one of my app, home page layout is loaded from storefront application written in java in back-end. This application produce layout in form of JSON having widgets and app consumes and render the layout.
I am assigned to write some AB testing framework. If there any opensource tool which i can use to intercept my JSON for AB test or should I have to write out some out of the box solution for this.

A: Most AB testing you hear about is referring to client-side tests powered by injecting JS in the browser. Testing in a Java app requires a different approach.
You can use a free, open-source tool such as Planout. This serves as a basic traffic splitter and uses a deterministic hashing algorithm so that you get consistent variations as long as you keep using the same user ID.
If you need more robust functionality, you may need to go for a commercial package. For in-app testing (mobile, web, backend), these usually take 1 of 2 forms:

*

*API approach: your app can send a request to the vendor-managed server asking for a variation for the current user. The downside here is the performance hit of waiting for a response every time you need the user's variation.

*SDK: vendor-provided SDK you implement in your Java code base that uses a deterministic hash to determine the variation for the user. The SDK will need retrieve some kind of data file with experiment status, traffic allocation, etc from a server prior to running the experiment (and on some update frequency), but then lets you determine variations in memory (no blocking network calls). Tracking calls can be sent async.

A commercial package will give you a few benefits over a free solution, like a user-friendly web portal to manage experiments, a statistical calculator, QA tools, feature flags, user permissions, ongoing updates and support, etc.
Disclaimer: I work for Optimizely who develop an SDK-driven platform for AB testing & feature flags.


Q: Ordering of sed command breaks for unknown reason Input
File.txt
Start
1
2
3
4
Start
5
6
7
8

Problem
I was messing around with sed to work out different ways to get data from between the Starts.
One script i made was
sed ':2;h;$!N;$b1;/\n.*Start[^\n]*$/{:1;$!x;/5/p;x;s/.*\n//};$!b2;d'

Explanation of script
:2 #A label for the break point

;h #Hold all the lines currently in the pattern buffer, i use this before getting the next line so that it doesn't have the next start.

 ;$!N # Gets the next line for every line except the last

 ;$b1 # Breaks to label 1 on the last line. This is to bypass having to see start to enter the block

 ;/\n.*Start[^\n]*$/ # If start is on the last line of pattern buffer then execute the next block

  { #Start of block

  :1 #Label to jump to if end of file

  ;$!x # If not the last line switch in the hold buffer we got which doesn't include the next `Start`.

  ;/5/p # Print if this Start section contains `5`

  ;x #Switch back hold buffer and pattern to get `Start` back

  ;s/.*\n// #Delete everything up to last line of pattern buffer(leaving just `Start`.

  } # End block

  ;$!b2 # If not end of file go back to label at the start

  ;d #Deletes anything left in pattern buffer when we reach the end of the file

Outputs
Start
5
6
7
8

Which is correct
But changing the order of $!N;$b1; to $b1;$!N makes the script output nothing.
sed ':2;h;$b1;$!N;/\n.*Start[^\n]*$/{:1;$!x;/5/p;x;s/.*\n//};$!b2;d'

I don't know if I'm missing something obvious, or don't really understand the meaning of $ but it seems to me as though this should make no difference as one command only executes on the last line($) and the other on all other lines, so the ordering shouldn't matter should it?
Any explanations are welcome and if any more info is needed let me know.
Also I DO NOT want a better way of doing this, I just want an explanation of why it is happening.

More Info

*

*GNU sed version 4.1.5

A: $!N;$b1 at the line before last first appends, then branches (as it is now the final line), wheras $b1;$!N doesn't branch, appends, doesn't enter the block. following is $!b2 which isn't taken, followed by d deleting the pattern. (and ending the script, as there is no more input) – Hasturkun


Q: How to get size of column in mysql table I'm trying to find out the exact size of one column within a table. PHPMyAdmin doesn't show size of columns, only the tables.
Any way I can get the size of the column?
Thankyou

A: If you are doing this from a script, you can run this after you have established a connection (and hence the database is already selected):
SELECT  character_maximum_length
FROM information_schema.columns
WHERE table_name = ? AND column_name = ?

Replace the ?'s with the name of your table and the name of your column, respectively.

A: If you want to find out the size of column=COLUMN_NAME from table=TABLE_NAME, you can always run a query like this:
SELECT sum(char_length(COLUMN_NAME))
FROM TABLE_NAME;

Size returned is in bytes. If you want it in kb, you could just divide it by 1024, like so:
SELECT sum(char_length(COLUMN_NAME))/1024
FROM TABLE_NAME;

A: SELECT column_name,
       character_maximum_length
FROM   information_schema.columns
WHERE  table_schema = Database()
       AND -- name of your database
       table_name = 'turno'
       AND -- name of your table
       column_name = 'nombreTurno' -- name of the column

*

*SQLFiddle Demo
INFORMATION_SCHEMA.COLUMNS
If you wanna Whole Table size then use this
SELECT table_name                                                 AS "Tables",
       Round(( ( data_length + index_length ) / 1024 / 1024 ), 2) "Size in MB"
FROM   information_schema.tables
WHERE  table_schema = "$db_name"
ORDER  BY ( data_length + index_length ) DESC;

Edit
SELECT column_name,
       character_maximum_length
FROM   information_schema.columns
WHERE  table_schema = 'websi_db1'
       AND table_name = 'thread'
       AND column_name = 'title'

Source


Q: For a 2 core machine, will it help to set 4 processes with pm2? Using pm2 with node.js app, 2 core machine.
pm2 start app.js -i 4

Will it help the performance, or won't help at all ?
Thanks !

A: It won't help performance, in fact it will be harmful. It's recommended to spawn N-1 workers, N being the amount of CPU cores.
You can issue: pm2 start app.js -i -1 for that. Given that you only have 2 cores, this will only use one, so you won't take advantage of clustering.
If you want to try using 2 cores in your case, you should run your own benchmarks, but make sure that your machine is not doing much work outside of Node.js, otherwise it will be better to just use 1 core.
If you use more workers than CPU cores, the processes will start competing for resources, which will downgrade the performance of the application.