text:
Q: operator >> in C#
Possible Duplicate:
What does the ">>" operator in C# do?

Also related: Doubling a number - shift left vs. multiplication

This is code in C#.
I just need to know if I'm right.
I'm not sure with using operator >>.
this code:
winHalfWidth = this.ClientSize.Width >> 1; // both is int

make the same as:
winHalfWidth = this.ClientSize.Width / 2;

and if I'm right so, this code should do:
quaterWidht = this.ClientSize.Width >> 2;

should do same as:
quaterWidth = this.ClientSize.Width / 4;

So 2 questions:

*

*Is it right?

*Is any difference between using >> and /?

*

*When we speak about int values?

*When we speak abou float values? (I thing there could be.. but I'am not sure.)

Answers like yes/no would be nice :)
Thanks.

A: It does in fact do what you intend with int values, but you should be careful about edge cases such as negative numbers or very big numbers.
As for floating-point numbers, their memory representation is not that simple, so a simple shift-right won't do the trick of dividing by 2.

A: This is shift operator not divide , we know that shift left will multiply a number by 2 , For exmaple
2 in base 2 is : 0010 , if we shift it one times to left it will turn to 4 or 0100.
So as MSDN said :
If the first operand is an int or uint (32-bit quantity), the shift count is given by the low-order five bits of the second operand (second operand & 0x1f).
If the first operand is a long or ulong (64-bit quantity), the shift count is given by the low-order six bits of the second operand (second operand & 0x3f).
If the first operand is an int or long, the right-shift is an arithmetic shift (high-order empty bits are set to the sign bit). If the first operand is of type uint or ulong, the right-shift is a logical shift (high-order bits are zero-filled).


text:
Q: Add custom shortcut to the GNOME Terminal I want to add my own shortcuts to the terminal.
So you know like Ctrl+Shift+C copies text, Ctrl+Shift+L clears the terminal.
I would like to be able to execute the command in the current terminal using shortcut. So for example, I press Ctrl+Shift+Q and ls -l executes, etc.
Is that possible?

A: As a workaround I could achieve this by the mix of

*

*Is it possible to achieve autocomplete to predifined text in gnome-terminal?

*Custom Keyboard Shortcut

*xdotool
Steps

*

*Created a alias for ls -l as ls in ~/.bashrc file:

*To type ls and a key press of Enter, used xdotool sleep 1 key l s Return as a command for custom keyboard shortcut:

*Result, when I press the shortcut key combo:

redpajama_set_name: RedPajamaStackExchange


text:
Q: Store values in realm I am creating a fitness journal app, and I store workout values in realm this this:

I am sorting the workouts using date. I want to accomplish something new, where I can have different weight and reps each set on the same exercise. It is based on this design:

I think the database has to bee something like this, but not sure:

*

*23.11.2019

*

*Barbell Bench Press

*

*Set 1

*

*KG: 90

*Reps: 5

*Set 2

*

*KG: 87,5

*Reps: 6

*Triceps Pushdown

*

*Set 1

*

*KG: 110

*Reps: 6

*Set 2

*

*KG: 110

*Reps: 6

*Set 3

*

*KG: 112,5

*Reps: 5

Any tips on how I can do this?
Edit;
This is my current Workout.swift class (not sure how to edit it to get what I want):
import Foundation
import RealmSwift

class Workout: Object {

    @objc dynamic var date: Date?
    @objc dynamic var name: String?
    @objc dynamic var exercise: String?
    @objc dynamic var sets = 0
    @objc dynamic var reps = 0
    @objc dynamic var kg: Double = 0.0
    @objc dynamic var notes: String?

}

A: You would need to have three objects (Workout, Exercise, and Set) and have 2 many-to-many relationship as outlined in the documentation: https://realm.io/docs/swift/latest/#many-to-many
class Workout: Object {

    @objc dynamic var date: Date?
    // List of exercises (to-many relationship)
    var exercises = List<Exercise>()

}

.
class Exercise: Object {

    @objc dynamic var name: String?
    // List of sets (to-many relationship)
    var sets = List<Set>()
    var parentWorkout = LinkingObjects(fromType: Workout.self, property: "exercises")
}

.
class Set: Object {

    @objc dynamic var reps: Int = 0
    @objc dynamic var kg: Double = 0.0
    @objc dynamic var notes: String?
    // Define an inverse relationship to be able to access your parent workout for a particular set (if needed)
    var parentExercise = LinkingObjects(fromType: Exercise.self, property: "sets")

    convenience init(numReps: Int, weight: Double, aNote: String) {
       self.init()
       self.reps = numReps
       self.kg = weight
       self.notes = aNote
    }

}

EDIT
adding example code
let aSet0 = Set(numReps: 10, weight: 5.0, aNote: "light workout")
let aSet1 = Set(numReps: 10, weight: 20.0, aNote: "medium workout")
let aSet2 = Set(numReps: 10, weight: 30.0, aNote: "heavy workout")

let aWorkout = Workout()
aWorkout.name = example
aWorkout.sets.append(objectsIn: [aSet0, aSet1, aSet2] )

Another example code to display the sets for the "Bench Press" workout:
// Find the Workout instance "Bench Press"
let benchPressWorkout = realm.objects(Workout.self).filter("name = 'Bench Press'")
// Access the sets for that instance
let sets = benchPressWorkout.sets
// Access set[0]
let set0 = sets[0]
// Access reps and kg for set 0
let reps0 = set0.reps
let kg0 = set0.kg
// and so on ...

A: Create a WorkOut this way
let realm = try! Realm()
var wo = WorkOut()//Do initialization for properties such as name,reps,...
try! realm.write{
   realm.add(wo)
}

One record of WorkOut is written to your database


text:
Q: How can I best run a MySQL SELECT query between two tables in Node JS? I have a pretty long SELECT query I have attempted to save to a variable (queryString) in my app.js file. It's throwing a SQL syntax error and I'm just not getting it. It appears I am not escaping my double quote on the string "February" because the error message shows a transient single quote at the end like "February"'. How am I getting that additional single quote at the end? Or is that really what's causing the error?
Also, is there a more appropriate method for passing a query like this? Like, can you store it in an .sql file and import that into the app.js file?
I know the query works because I can run it from the terminal with expected results.
This is the original query:
SELECT CASE WHEN m.item_trx_qty > 0 THEN m.item_trx_qty * (s.old_cost - m.liuom_unit_price_amt) ELSE 0 END as `Savings`,
        s.coid as `COID`,
        s.fee_id as `Fee ID`,
        s.sw_idea_num as `SW Idea Num`,
        s.description as `Item Description`
    FROM
        monthly_usage m, smart_items s
    WHERE
        m.coid = s.coid
        AND m.fin = s.fin
        AND m.u_year = 2019
        AND m.u_month = "February"
    GROUP BY s.sw_idea_num
    ORDER BY s.sw_idea_num
    ;

This is the snippet from my app.js file:
// For savings data from the saving query
const queryString = "SELECT CASE WHEN m.item_trx_qty > 0 THEN m.item_trx_qty * (s.old_cost - m.liuom_unit_price_amt) ELSE 0 END as `Savings`, " +
                    "s.coid as `COID`, s.fee_id as `Fee ID`, s.sw_idea_num as `SW Idea Num`, s.description as `Item Description`" +
                    "FROM monthly_usage m, smart_items s" +
                    "WHERE m.coid = s.coid " +
                    "AND m.fin = s.fin " +
                    "AND m.u_year = 2019 " +
                    "AND m.u_month = \"February\"" +
                    "GROUP BY s.sw_idea_num " +
                    "ORDER BY s.sw_idea_num;"

const savings = connection.query(queryString, (err, rows, fields) => {
    console.log('Fetched savings successfully!')
        })

Here is the error I am getting:
Failed to query for savings Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'm.coid = s.coid AND m.fin = s.fin AND m.u_year
= 2019 AND m.u_month = "February"' at line 1


text:
Q: How to find Complexity? How to find the time complexity {Big-Oh} of the following function?
function(int n) {
  for (int i = 0; i < n; i++){
    for (int j = i; j < i*i; j++){
       if (j%i == 0){
         for(int k = 0; k < j; k++){
            printf(" * ");
         }
       }
    }
  }
}

Answer for this is O(n^5) but I don't know how to find that.

A: I think that complexity is O(n^5).
function(int n) {
  for (int i = 0; i < n; i++){           // N, max value of i is n
    for (int j = i; j < i*i; j++){       // N^2, max value of j is n*n
       if (j%i == 0){
         for(int k = 0; k < j; k++){     // N^2, max value of k is n*n
            printf(" * ");
         }
       }
    }
  }
}

The first loop is N. Second loop the max value of j is i*i => n*n so it is n^2. Third loop, the max value of k is j, which is n*n so n^2. So n * n^2 * n^2 is n^5


text:
Q: paste input name between words for save it using write.table im super newbie on R and i have been learning for myself for a few weeks already due my work degree.
Im almost done with the statistical analysis that i need, but it is through an ugly and messy code, that is, repeating lot of codes for several data frames, to apply different statistical tests, save results, etc.
Well now, for personal interest, want to write this better, but im totally trapped in my ignorance and really need a push to get the idea, please.
For example, i want to create a function that measure the correlation on all the data tables im using and save those results as a tables using the input name as part of the output name.
I mean, if we had the iris data but measured on different seasons, e.g. iris_fall, iris_winter, iris_spring and iris_summer, after apply cor(X) method to each one, i want to save those results as tables called like "mCoriris_fall.txt", "mCoriris_winter.txt", "mCoriris_spring.txt" and "mCoriris_summer.txt" respectively.
My useless code for now say:
cor_PQ<-function(X) {
  cor_PQ<-cor(X, use="pairwise.complete.obs")
  return(cor_PQ)
}
savecor<-function(t) {
  outputname<-(paste0("mCor",t)) #HOW DO I CALL THE NAME OF THE INPUT? t is cor_PQ result matrix.
  savecor<-write.table(t, file=paste0(outputname,".txt"))
  return(savecor)
}
cor_PQ(Iris_fall)

I expect to get cor result and save it as a table in my workspace, using the input name as part of the output name.
Im aware this are 2 separates functions and the one to write table should be inside the function for cor(x), but i cant understand how.
I have been reading a lot but i just cant fit all in my head.
Thanks to anyone who can help me.
Regards.
UNTIL HERE IT HAS BEEN SOLVED...
But after making a list with my 14 data frames to apply cor and other methods, the write.table function overwrite the 14 cor results on 1 single doc. This is my code.
PQ_files<-list.files(path="C:/Users/Sol/Documents/ProyectoTítulo/CalidadAgua/Matrices/Regs",pattern="\\_PQ.txt")

PQ_data<-lapply(PQ_files, read.table)

names(PQ_data)<-gsub("\\_PQ.txt","", PQ_files)

PQ_data

cor_PQ<-function(X) {
  cor_PQ<-cor(X, use="pairwise.complete.obs")
  outputname.txt<-paste0("mCor",deparse(substitute(X)),".txt")
  write.table(cor_PQ, file=outputname.txt)
  outputname.pdf<-paste0("Cor",deparse(substitute(X)),".pdf")
  pdf(outputname.pdf)
  plot(X)
  dev.off()
  return(cor_PQ)
}

for (i in seq_along(PQ_data)){
  Correlaciones<-lapply(PQ_data,cor_PQ)
  }

Correlaciones

On SUM: seems to work almost good, until the write.table and plot(x) overwrite the outputs from the 14 dataframes on my PQ_data withe the name mCor[[i]] and CorX[[i]], respectively.
Should i define [i] somehow to have each results with the right name?
Also, when i run Correlaciones at the end, i can see the cor result for the 14 dataframes in one single dataframe, but i dont know how to split them correctly.
I guess almost there.
THANKS AGAIN!

A: You can combine the two functions and use deparse substitute to get input names as string
cor_PQ <- function(X) {
   cor_PQ<-cor(X, use="pairwise.complete.obs")
   outputname<- paste0("mCor",deparse(substitute(X)), ".txt")
   write.table(t, file=outputname)
   return(cor_PQ)
}

and then call
cor_PQ(Iris_fall)


text:
Q: How to iterate a Map() object? I have a Map() object that I need to iterate, so I can get the day of the week and a selected hour. The code below doesn't work, because Object.keys(newFieldReservationPrice).forEach is trying to loop a Map() object, which seems to make no sense. So, is there a better solution for this?
Here is the code below:
handlePriceInput = (e, hour, day) => {
let value = e.target.value

const newFieldReservationPrice = this.state.newFieldReservationPrice
console.log('newFieldReservationPrice', newFieldReservationPrice) // A Map();
let map;

if (!newFieldReservationPrice instanceof Map) {
  console.log('!== Map')
  console.log('newFieldReservationPrice is a Map()? inside if ()', newFieldReservationPrice)
  if (newFieldReservationPrice[day] && newFieldReservationPrice[day][hour]) {
      newFieldReservationPrice[day][hour] = Number(value)
  }
} else {
  map = new Map();
  console.log('map object', Object.keys(newFieldReservationPrice)) // logs map object []

  Object.keys(newFieldReservationPrice).forEach(key => {
    console.log('key', key)
      map.set(key, new Map(Object.entries(newFieldReservationPrice[key])));
  }); // This doesn't work
  console.log('Am I a Map()? map', map)

  const aux = map.get(day)
  console.log('aux day', aux) // A Map()
  aux.set(hour, Number(value)) // Comes as undefined || Cannot read property 'set' of undefined
  console.log('aux set', aux) // A Map()

  map.set(day, aux);
  console.log('what do I have?', map)

}
const isReservationPrice = !newFieldReservationPrice instanceof Map ? newFieldReservationPrice : map
console.log('isReservationPrice', isReservationPrice)

this.setState({
  newFieldReservationPrice: isReservationPrice
})
}

Thank you! :)

A: You could use Map#forEach and iterate the Map directly.

A: Maps provide three ways to get iterators for their contents:

*

*keys - Iterates the keys in the map

*values - Iterates the values

*entries - Iterates the key and values, giving you [key, value] arrays (this is the default)

As Nina notes, Maps also provide forEach, which loops through their contents giving the callback the value, key, and map as arguments.
Use the one appropriate for your use case. For instance, if you're trying to replace Object.keys, use keys. Similarly, if you want the entries in the map (I notice you use Object.entries at one point), use entries or the default iterator.
Note that in a few places in your code, you seem to be trying to index into the map using []. That doesn't work for maps, you need to use get.
Here's a simple example of using the default iterator (which is also the one you get from entries):

const map = new Map();
map.set(1, "one");   // Could also include these when calling
map.set(2, "two");   // the constructor but I wanted to
map.set(3, "three"); // avoid any confusion

for (const [key, value] of map) { // Using the default iterator (could be `map.entries()` instead)
    console.log(`The value for key ${key} is ${value}`);
}

Also note that you're breaking one of React's rules by setting new state based on existing state, but not using the callback version of setState. If you need to use existing state when setting new state, you must use the callback version:
this.setState(prevState => {
    // ...use `prevState` values (*not* `this.state`!) to create an object with
    // the updates, then return the object...
});

A: You can iterate a Map object using for of:
for (const [key, value] of myMap) {
  console.log(key, value);
}

which is the same as iterating over the entries:
for (const [key, value] of myMap.entries()) {
  console.log(key, value);
}

As @Nina Scholz said, you can use forEach on the Map prototype (doc MDN):
myMap.forEach((value, key, map) => {
  console.log(key, value);
}


text:
Q: Setting cookie in Wordpress I've been tinkering on this and can't seem to spot the problem. I'm able to get the state right but it's not saving in the cookie.
functions.php
add_action( 'wp_ajax_setBgSoundCookie', 'so_wp_ajax_function' );
add_action( 'wp_ajax_nopriv_setBgSoundCookie', 'so_wp_ajax_function' );
function so_wp_ajax_function(){
    $state  =  $_POST['state'];
    setcookie("bg_sound", $state ,time()+60*60*24); //expires in 24 hours
    wp_die();
}

myscript.js
function setSoundCookie(state){

    $.ajax({
        url: vision_globals.ajaxurl,
        type: 'POST',
        data: {
            action :'setBgSoundCookie',
            state : state
            },
        success: function (data) {

            },
        error: function (er) {
            console.log(er);
            }
        });
    }

A: Make sure to set the cookie path:
setcookie('visionare_sound', $state, time()+60*60*24, '/');

The cookie is being set...but likely not to your intended path.


text:
Q: Build error when building hono from source code - on project hono-adapter-amqp-vertx: Cannot create docker access object I was following the documentation here to build hono from source code - [1]: https://www.eclipse.org/hono/docs/dev-guide/building_hono/
But the build fails with this error -

[ERROR] Failed to execute goal io.fabric8:docker-maven-plugin:0.33.0:build (build_images) on project hono-adapter-amqp-vertx: Cannot create docker access object : extension (5) should not be presented in certificate_request -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal io.fabric8:docker-maven-plugin:0.33.0:build (build_images) on project hono-adapter-amqp-vertx: Cannot create docker access object

The docker client version  installed in my machine is 19.03.1 and server version is 19.03.02
java version is 11.0.7
The detailed dump with X option is here - [2]: https://docdro.id/AMRsFem
Please let know how to fix this.
Updated with more info

$ docker info
Client:
Debug Mode: false

Server:
Containers: 0
Running: 0
Paused: 0
Stopped: 0
Images: 0
Server Version: 19.03.12
Storage Driver: overlay2
Backing Filesystem: extfs
Supports d_type: true
Native Overlay Diff: true
Logging Driver: json-file
Cgroup Driver: cgroupfs
Plugins:
Volume: local
Network: bridge host ipvlan macvlan null overlay
Log: awslogs fluentd gcplogs gelf journald json-file local logentries splunk >syslog
Swarm: inactive
Runtimes: runc
Default Runtime: runc
Init Binary: docker-init
containerd version: 7ad184331fa3e55e52b890ea95e65ba581ae3429
runc version: dc9208a3303feef5b3839f4323d9beb36df0a9dd
init version: fec3683
Security Options:
seccomp
Profile: default
Kernel Version: 4.19.130-boot2docker
Operating System: Boot2Docker 19.03.12 (TCL 10.1)
OSType: linux
Architecture: x86_64
CPUs: 1
Total Memory: 985.4MiB
Name: default
ID: JGCF:FKDA:TRZS:L3E3:U5FP:PUTI:VTXZ:M2TN:PITL:P74X:AMJJ:YRPO
Docker Root Dir: /mnt/sda1/var/lib/docker
Debug Mode: false
No Proxy: 192.168.99.100
Registry: https://index.docker.io/v1/
Labels:
provider=virtualbox
Experimental: false
Insecure Registries:
127.0.0.0/8
Live Restore Enabled: false
Product License: Community Engine

$ echo $DOCKER_HOST                                                                                >tcp://192.168.99.108:2376

Command used to build -

mvn clean install -Ddocker.host=tcp://192.168.99.108:2376 -Pbuild-docker-image,metrics-prometheus

A: You might be running into this issue with Java 11.0.7 and TLS 1.3.
Can you try to use
mvn clean install -Djdk.tls.client.protocols=TLSv1.2 -Ddocker.host=tcp://192.168.99.108:2376 -Pbuild-docker-image,metrics-prometheus

to build Hono as described in the issue?


text:
Q: Button to return changes made to a property? I am trying to the value of properties during run time. First I am trying to do it with the name property for a person but I am not sure how to complete the if statement down below. I would like it to reopen my Form2 which takes in the student as a parameter and it will display all the details for them. Any help or advice would be much appreciated. If I have done this completely wrong, please let me know give me some guidance or advice on how to edit a property data in runtime.
public class Student :IPerson
{
    //Method that changes the original name
    public string ChangeName(string newForename)
    {
        _forename = newForename;
        return _forename;
    }
}

public partial class Edit_Details : Form
{
    public Edit_Details(Student student)
    {
        InitializeComponent();
        nameLabel.Text = student.Forename;
        student.ChangeName(editNameTextBox.Text);
        //if(savebutton.Click) //how can I get this to replace the old name with the new one when the button is pressed??
    }
}

A: in
 public Edit_Details(Student student)
    {
        InitializeComponent();
        nameLabel.Text = student.Forename;
        savebutton.Click+=(sender,e)=>
          {
             savebutton.Text=student.ChangeName(editNameTextBox.Text);
          };
    }


text:
Q: Ambiguous column error using orange3 - POSTGRES When executing the query inside Orange 3, I got an ambiguous column error
QUERY
SELECT CAST(REPLACE(memoria_em_uso, 'G','') AS FLOAT),
       CAST(REPLACE(memoria_total, 'G','') as FLOAT),
       CAST(REPLACE(memoria_livre, 'M','') as FLOAT)
FROM tbl_memoria_hosts

OUTPUT
Error encountered in widget SQL Table:

Traceback (most recent call last):
  File "/home/luis/anaconda3/lib/python3.7/site-packages/Orange/data/sql/backend/postgres.py", line 81, in execute_sql_query
    cur.execute(query, params)
psycopg2.errors.AmbiguousColumn: column reference "replace" is ambiguous
LINHA 1: SELECT (("replace")::double precision) AS "replace", (("repl...

Note:
All columns in the table are VARCHAR, where the information is written as follows 7.7G


text:
Q: How to log successful starting and finishing of a function execution? I am debugging a code. I have a code with many lines in python 2. And some functions are executed long. To check a function completed successfully I am doing the following ugly stuff:
print("creating an object... "), # a comma here to print a subsequent print in one line
obj = TimeDemandingFunction()
print("end")

Is there a best method for logging?
P.S.
the function TimeDemandingFunction() is from an external library.

A: Well, if all you need is a decorator to, say, log function's execution time you could use something like this:
import functools
import time

def my_custom_timer(func):
    @functools.wraps(func)
    def wrapper_timer(*args, **kwargs):
        start_time = time.perf_counter()
        value = func(*args, **kwargs)
        end_time = time.perf_counter()
        run_time = end_time - start_time
        print(f"Finished {func.__name__!r} in {run_time:.4f} seconds.")
        return value
    return wrapper_timer

@my_custom_timer
def waste_some_time(num_times):
    for _ in range(num_times):
        sum([i**2 for i in range(10000)])

waste_some_time(2)

Output:
Finished 'waste_some_time' in 0.0050 seconds.

EDIT:
Here's how you would decorate a function from another module. First, you have to import it and then put it in a function block.
@my_custom_timer
def find_evens(n):
    return itertools.filterfalse(lambda x: x % 2, range(n))

evens = find_evens(20)
print(list(evens))

Output:
Finished 'find_evens' in 0.0000 seconds.
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

Note that by definition, a decorator is a function that takes another function and extends the behavior of the latter function without explicitly modifying it.
And if you want to use the decorator in another module of yours, just import it as if you would import any other function.
from othermodule import your_decorator

@your_decorator
def some_function():
    pass

A: Baduker's answer prompted me to give a modified version of his answer. I will summarize and give several examples.
Construction of a decorator is similar as Baduker, but several modifications: (1) there is a notification that a function has been started with the information where it was called (number of line and which keys are used), (2) it writes info about time only at the end. Below I give examples how to use it for external functions:
import functools
import timeit
import sys

def my_custom_timer(func):
@functools.wraps(func)
def wrapper_timer(*args, **kwargs):
    start_time = timeit.default_timer()
    s = ''
    for arg_name in kwargs:
            s += arg_name + '; line=' + str(sys._getframe().f_back.f_lineno)
    print("Started {!r}({!r}) ".format(func.__name__, s)),
    value = func(*args, **kwargs)
    end_time = timeit.default_timer()
    run_time = end_time - start_time
    print("Finished in {:.4f} seconds.".format(run_time))
    return value
return wrapper_timer

Then goes an interesting part. First, you need to find out the whole path to the function. Use the idea here. Briefly, functions have a module attribute:
>>> from math import sqrt
>>> sqrt.__module__
'math'

First, let's redefine the sqrt function from some module:
import math
@my_custom_timer
def sqrt(*args, **kwargs):
    return math.sqrt(*args, **kwargs)

What if a function from a built-in module?! No problem. The answer is __builtin__ module:
>>> print(divmod.__module__)
'__builtin__'


text:
Q: Percentage Validation in Cakephp I have tax percentage field .In that i want to validate for numeric ,tax percentage not greater than 100% , decimal places only 2.
 my demo code is
$result = $this->validate['TaxPercent'] = array(
            'numeric' => array(
                'rule'    => 'numeric',
                'allowEmpty' => true,
                'message' => __("err__numberfield", array(__('lbl_TaxPercent', true))),
            ),
            'range' => array(
                'rule' => array('range', 0, 101),
                'allowEmpty' => true,
                'message' => __("err__percentage", array(__('lbl_TaxPercent', true))),
            ),
            'decimal' => array(
                'rule' => array('decimal', 2),
                'allowEmpty' => true,
                'message' => __("err__decimal", array(__('lbl_TaxPercent', true))),
            )
        );

please suggest appropriate solution.


text:
Q: how to get the difference between 2 dates with Dql How can I get the difference between 2 dates with Dql?
I have tried the following code, but that didn't work.
$query =$this->_em->createQuery('select a,DATEDIFF(d,\'now\',a.date) from ABundle:Abonment a where d==1');

How can I solve this?

A: From this source http://docs.doctrine-project.org/en/2.1/reference/dql-doctrine-query-language.html#dql-functions:
DATE_DIFF(date1, date2) - Calculate the difference in days between date1-date2, and in your query your function is taken 3 parameters.
In Doctrine2 you have to use one of the following functions that fits better on you instead of now() function:
CURRENT_DATE() - Return the current date
CURRENT_TIME() - Returns the current time
CURRENT_TIMESTAMP() - Returns a timestamp of the current date and time.

On conclusion your query should by something like:
$query =$this->_em->createQuery('select a, DATE_DIFF(CURRENT_DATE(), a.date) as days from ABundle:Abonment a where days = 1');


text:
Q: Will Fakes be made available on versions of Visual Studio other than 'Ultimate' as Moles is? Does anyone know if there are any intentions to make Fakes available on releases of Visual Studio lower than Ultimate?
Fakes seems to be billed as replacing Moles but if it will only work in Ultimate, most Moles users won't have access to it.

A: No. Fakes are in Visual Studio 2012 Ultimate only, as of posting this answer. This may change in future versions and updates.


text:
Q: Is it "is buried" or "was buried" in the following sentence? Below is an example sentence from Collins English Dictionary. I wonder if there is a mistake in this sentence and if we should replace "is buried" with "was buried," as the first part of the sentence is past tense.

He died a pauper and is buried in an unmarked grave.

A: "Buried" is both the past participle of the verb to bury and an adjective to describe the state of being under the ground.

*

*You would say "he was buried" (verb) if you were referring to the event of his burial.

*You would say "he is buried" (adjective) if you wanted to refer to his current state or location under the ground.


text:
Q: Is there any sentiment forum dataset for unsupervised training available? I recently finished a machine learning course and would like to make a forum sentiment analysis tool, to apply it in stock-related forums.
The idea is to:

*

*Capture (text mining) users with their comments, and evaluate their comment's sentiment (positive, negative, neutral).

*Capture what happens (stock market) after those comments, and assign a weight to the user accordingly (bigger weight if the user's sentiments is spot-on and the market follows the same direction)

*Use the comments as a tool to predict market direction.

Actually, I do this myself (pay attention on forums) plus my own technical analysis and the obligatory due diligence, and it has been working very well for me. I just wanted to try to automate it a little bit and maybe even allow a program to play with some of my accounts (paper trading first, and if it performs decently assign some money in a real account)
This would be my first machine learning project (just as a proof-of-concept) so any comments would be very kindly appreciated.
The biggest problem that I find is that I would like to make an unsupervised training, and I need a sample dataset to do the training.
Question: Is there any known forum-sentiment dataset available to be used for unsupervised training?
I've found several sentiment datasets (twitter, imbd, amazon reviews) but they are very specific to their niche (short messages, movies, products...) but I'm looking for something more general.

A: Since you are looking for an unsupervised approach you can use any set of data that matches your "real case scenario". Text mining and sentiment analysis are are often tailored to the problem at hand so it is easy to start directly with the real data. The best approach is to built a scraper that grabs directly the forum posts that you want to analyze. You can build the scraper easily enough with Python (beautifulsoup/selenium). Online is full of nice tutorial eg: https://www.dataquest.io/blog/web-scraping-tutorial-python/


text:
Q: Picking properties of a map from a list in Elixir Is there a way to pick properties of a map from a list in elixir?
map = %{
  a: 1, b: 2, c: 3
}

do_something(map, [:a, :b]) = %{a: 1, b: 2}

A: You want Map.take/2:
iex> Map.take(%{a: 1, b: 2, c: 3}, [:a, :b])
%{a: 1, b: 2}


text:
Q: Webmin port 25 is blocked I have set up webmin on my CentOS server with a few domains. I have also added a test email account but cannot send any emails from my Outlook after configuring the settings for IMAP/STMP server. If I try and telnet to port 25, i get an error. Iptables isn't blocking port 25, postfix server is running and ISP isn't blocking any ports. I have also tried turning off iptables which made no difference.
Any ideas?


text:
Q: Laravel - how to launch emails dynamically by tenant I'm making an api in Laravel, where my registered users are segmented by tenant, but when I send the welcome email, each tenent has their own domain. That is, when a user registers with tenant1, I want to welcome them to no-reply@tenat1.com.
But in laravel I put the email information in the .env:
MAIL_DRIVER=smtp
MAIL_Host=mail.propnex.sg
MAIL_PORT=587
MAIL_USERNAME=no-reply@tenant1.com
MAIL_PASSWORD=xxxxxxxx
MAIL_ENCRYPTION=ssl

how do I pass this information that I'm passing in .env, dynamically?


text:
Q: Laravel 5.7 SendEmail is not working properly I am sending email using laravel 5.7 but i found following error " (1/1) FatalErrorException
Class 'App\Mail\UserRequest' not found" Need help
 <?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
//use \App\Mail\SendMail;
use App\Mail\UserRequest;
class ContactusController extends Controller
{
    public function index()
    {
        return view('contactus');
    }

     public function sendmail(Request $req)
    {

        $msgdata = array('subject'=>$req->subject,'email'=>$req->email,
        'name'=>$req->name,'body'=>$req->message);
         Mail::to('dddddddd@dddsdsf.com')->send(new UserRequest($msgdata));
        return view('contactus');
    }

}


text:
Q: Error displaying Records in my table: It shows one record less I'm showing records in a table from my database.
BUT If I have 6 records, my .php file shows me 5... It shows me one record less:
I've looking in pages like this, but I still have the error...
Any idea?
This is my code:
    <?php
    include 'conexion.php';
    $contabla=conexion();
    $sqltabla="select * from precotizacion p, producto pro where p.idproducto=pro.id";
    $resutadotabla=mysql_query($sqltabla,$contabla);
    $dato=mysql_fetch_array($resutadotabla);

$contador=0;
while ($dato=mysql_fetch_array($resutadotabla))
{
    $contador++;
    echo "".$contador."	";
    echo "".$dato['id']."	";
    echo "".$dato['parte']."	";
    echo "".$dato['descripcion']."	";
    echo "<input size='3' name='pcanitdad' id='idcantidad' value ='1' onchange='editarproducto(this.value)'> 	";
    echo "".$dato['pfinal']."	";
    echo "subtotal	";
    echo "Descuento aplicado	";
    echo "total";
    echo "<select name='desc' id='desc' onchange='descuento(this.value)'>
    <option >Aplicar</option>
    <option >1</option>
    <option >2</option>
    <option >3</option>
    <option >4</option>
    <option >5</option>
    </select>	";
    echo ' Eliminar producto 	';
    echo "
";
}
?>

A: Before going into while, please delete this line:
$dato=mysql_fetch_array($resutadotabla);

That line will get the first records and then it will go into the while loop, and starting with the second one.

A: I found the mistake!!
I had to remove this line:
$dato=mysql_fetch_array($resutadotabla);


text:
Q: How to protect named mutex from opening by another process WinApi? I have created named Mutex and named Event in my service process for synchronizing access to data shared between my processes but I worry about some malware users will open named event and start to signal on it. How I can protect my mutex and allow open it only applications from the list?

A: You secure a Mutex or an Event object the same way you secure any other securable kernel object: By applying an access control list.
The topic is broad. See the following resources:

*

*Access Control Model.

*DACLs and ACEs.


text:
Q: How can I put a format specifier in Elasticsearch query using Go? In the following code, I want to put a variable id, like some format specifier %d. How do I do this for the following elasticsearch query with Golang?
str := `{
        "query": {
          "match": {
            "id": 123
          }
        }
      }`

s := []byte(str)
url := "http://localhost:9200/student/_delete_by_query"

_, err = helper.GoDelete(url, s)
if err != nil {
    return err
}
return nil

A: Using fmt.Sprintf may be the simplest way to do that, not the fastest. but simplest.
d := 123
id := fmt.Sprintf(`{"query": {"match": {"id": %d}}}`, d)

A: fmt.Sprintf could work, but is also prone to errors. I would create the appropriate structures, then use json.Marshal to do it:
type (
    Match struct {
        ID int `json:"id"`
    }
    Query struct {
        Match Match `json:"match"`
    }
    MyStruct struct {
        Query Query `json:"query"`
    }
)

func main() {
    s := MyStruct{
        Query: Query{
            Match: Match{
                ID: 123,
            },
        },
    }
    bytes, err := json.Marshal(s)
}


text:
Q: Implementing member swap() in terms of non-member swap() I'm implementing a class with a similar interface to std::array, which has both the member swap() and the non-member swap().
Since I want my class to mimic the standard containers, I would like to implement both kinds of swap() (the non-member swap() is implemented via ADL, since specializing std::swap() isn't permitted):
class A {
    public:
        friend void swap(A& a, A& b) { /* swap the stuff */ }
        void swap(A& other) { swap(*this, other); }
};

However, it seems like I can't call the non-member swap() from inside the class, because it prefers the member swap() even though it only has a single parameter.  Changing it to ::swap(*this, other) doesn't work as well, because the in-class friend function is only findable via ADL.  How might I call the non-member swap() from inside the class?

A: The problem is that the name of the member function swap hides the namespace-scope swap in the body of A::swap. Unqualified name lookup for swap in A::swap will never find namespace-scope swap and, thus, namespace-scope swap will not be part of the overload set. One way to get around this would be to simply add a declaration for namespace-scope swap in the body of A::swap:
class A
{
public:
    friend void swap(A& a, A& b) { /* swap the stuff */ }

    void swap(A& other)
    {
        void swap(A& a, A& b);
        swap(*this, other);
    }
};

That being said, I'm not sure what this really does for you. The obvious solution is to just implement namespace-scope swap in terms of A::swap rather than the other way around. Personally, I would just not have a swap member function to begin with. The typical way of swapping aand b is to just swap(a, b)…

A: The following works for me (it prints blah twice)
#include <utility>
#include <iostream>

class A {
    public:
        friend void swap(A& a, A& b) { std::cout << "blah\n";/* swap the stuff */ }
        void swap(A& other) {  using std::swap; swap(*this, other); }
};

int main() {
    A a, b;
    swap(a,b);
    a.swap(b);
}

A: You can declare your class and your swap function first, then use the global namespace specifier within your member function.
Now you are free to define your swap function outside the class.
#include <algorithm>
#include <iostream>

class A;
void swap(A& a, A& b);

class A {
    int the_stuff;

  public:
    A(int a): the_stuff(a) {}
    friend void swap(A& a, A& b);
    void print_stuff(){std::cout << "A's stuff is " << the_stuff << std::endl;}
    void swap(A& other){
      ::swap(*this, other);
      std::cout << "Member swap" << std::endl;}
};

void swap(A& a, A& b)
{
  std::swap(a.the_stuff, b.the_stuff);
  std::cout << "Friend swap" << std::endl;
}

int main()
{
  A a = 1, b = 2;
  a.print_stuff();
  swap(a, b);
  a.print_stuff();
  return 0;
}

Outputs:
//> A's stuff is 1
//> Friend swap
//> A's stuff is 2


text:
Q: Unable to view user input when debugging CQL input in Cassandra SO having some issues with trying to debug a program that I'm using, and wondered if anyone could help me out.
The current environment is I'm running Cassandra (v2), using cqlsh (v3) that comes with it. I'm making changes to some of it's functionality, and then using cqlsh to test commands to see if my changes are working as intended, or if not what the input looks like as I step through the program.
I start up a debugging session (either in eclipse of IntelJ, doesn't really matter), firing up the server code to accept connections/input.
I then load up cqlsh, and specify the keyspace that I want to use. This seems to work fine.
I then execute a line of cql to test my changes via command line. What I expect to see is the command line entry being caught by the debugger in my IDE, where I can see how the input is handled by my code changes. What I'm seeing is nothing happening at all, as if no command was submitted.
So my questions would be the following:
1) Should I see anything in my debugging IDE when executing commands as described above?
2) If not, how would you debug a server based application that has this configuration, especially in the realm of handling user input?
3) If so, what settings should I check to see if I have set correctly, or what processes should be followed to view and debug said submissions?
I figure there has to be a better way then having 50,000 System.out.println() all over the place (assuming they'd even work), or at least, I hope there is.
Thanks for anyone that reads this. Any questions (which I'm sure there may be since I'm probably not using the right descriptors) please ask away.

A: I've had success with the following approach.

*

*Make sure to compile with -g (use like: javac -g) to enable generation of all debugging information.

*When starting your application use appropriate debug flags (like so java -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=1414, the number is the port you connect to) to start a debugging server.  Note that you can debug from a remote host (debugger will connect using hostname:port syntax).  You don't need to type this all up for Cassandra; you can simply uncomment a relevant line in cassandra-env.sh (in Windows, look in bin/Cassandra.bat or if running Datastax distro, under registry key HKLM\SOFTWARE\[optionally Wow6432Node\]Apache Software Foundation\[Procrun node]\[Cassandra node]\Parameters\Java:Options).

*Connect to your server from your IDE (I used Eclipse, IntelJ is similar, I'm sure).

*Open the source code in the IDE and put some breakpoints that would be in play in your use case.

*Run your scenario.  Your breakpoints should hit.  For definite confirmation that the setup works, put a breakpoint on something that is guaranteed to be executed during your scenario, rather than on something you believe should.

In your case, because you can successfully specify the keyspace, I believe everything is working, and then there is a silent failure when you try to do other steps, possibly introduced by your modifications.  To confirm, I would recommend rolling back all your changes and first testing the debugger setup on a clean build.
Lastly, and this may be superfluous, CQLSH is a program written in Python, and runs separate from Cassandra in a different process.  Therefore you cannot see the actual "command line entry" from a Java debugger.  The closest you can get to your raw input is by putting breakpoints somewhere in cql3 package to see CQL statements get passed in (hopefully).  Of course you can use a Python debugger to debug CQLSH if this is what you want.


text:
Q: InfoPath error while publishing the form to SharePoint list in Office 365 I'm getting the below error when i publish the InfoPath form to SharePoint list in Office 365.
Error:
The soap error indicates that an error occurred on the server:
Server was unable to process request. ---> Unsupported expression
It didn't give any clear description of the error, so i'm getting confused and unable to resolve this issue. Due to this issue we are not able to make updates on the InfoPath form, it is really impacting our main solution. i have searched a lot about this, but i didn't get the resolution. Can anyone help me to resolve this issue. Any help will be appreciated.
Thanks in advance.

A: There is a service which is being called from your Infopath form. Open in Infopath designer and check the .svc service which is being called. There can be several reason why the service is down. It can be due to lost connectivity of server or any change in account through which service is running.


text:
Q: django - Using one form to create two model instances This seems like something that should be rather simple, and something that should be a common thing to need, but the more I try and find an answer, the more confused I get.
I have an event model that is linked to multiple other models that need events, so I created a separate event model for it.  Now, I want to create an event when I create a job model, but I am having trouble figuring out how to do it.
In my job field, I have a OneToOneField relationship to an event, and the only thing I need to decide at the time I make the event is the duration.
A simplified Job model might look like this:
class Job(models.Model):
    customer = models.ForeignKey(Customer)
    address = models.CharField(max_length=100, verbose_name="Job Address", null=False, blank=False)
    city = models.CharField(max_length=100, verbose_name="City", null=True, blank=True)
    state = models.CharField(max_length=2, verbose_name="State", null=True, blank=True)
    zip = models.CharField(max_length=5, verbose_name="Zip Code", null=True, blank=True)
    # Simply need to set duration
    event = models.OneToOneField(Event, on_delete=models.CASCADE, null=False, blank=False)

And a simplified Event model might look like this:
class Event(models.Model):

    TIME_LIST = (
        (1, "0:30"),
        (2, "1:00"),
        (3, "1:30"),
        (4, "2:00"),
        (5, "2:30"),
        (6, "3:00"),
        (7, "3:30"),
        (8, "4:00"),
        (9, "4:30"),
        (10, "5:00"),
        (11, "5:30"),
        (12, "6:00"),
        (13, "6:30"),
        (14, "7:00"),
        (15, "7:30"),
        (16, "8:00"),
    )

    title = models.CharField(max_length=255)
    employee = models.ForeignKey(Employee, null=True, blank=True)
    start_time = models.DateTimeField(null=True, blank=True)
    end_time = models.DateTimeField(null=True, blank=True)
    range = RecurrenceField(null=True, blank=True)
    duration = models.IntegerField(choices=TIME_LIST, null=True, blank=True)
    is_all_day = models.BooleanField(default=False, null=False, blank=False)

I'm using generic CBVs, so simply:
class JobCreate(CreateView):
    template_name = 'jobs/create.html'
    success_url = '/schedule/add/'
    form_class = JobCreateForm

    def get_success_url(self):
        return self.success_url + str(self.object.id)

And my form can simply be:
class JobCreateForm(forms.ModelForm):
    class Meta:
        model = Job
        fields = [
            'customer',
            'address',
            'city',
            'state',
            'zip',
        ]

What I need is a way where I can make a select box for the duration within my job form, then create a new instance of Event, plug the event_id into the event field of my Job model, and submit it all in one go.
I looked at inlineformset_factory, which seems like it should be what I need, and I keep getting errors with it, so it is either the wrong idea, or I am using it wrong.  I tried a couple mixins that others have suggested, and they seem like overkill, and didn't work for me anyway.

A: You could create a second form for Event and rendering it in your template as well. Then in your view you can save it first, creating an event, then save your Job form and set it's related event to the one just created.
Alternatively (the way I'd probably do it), if you'd prefer a single form, you could add the duration field to your jobs form and override the form's save function. An overridden save could look something like this
def save(self, commit=True):
    e = Event.objects.create(duration=self.cleaned_data.get('duration'))

    job = super().save(commit=False)
    job.event = e
    job.save()
    return job

Formsets are really for making multiple forms, so in your case as you are using a OneToOneField (thereby only creating requiring a single form to create a single related object) it wouldn't make sense to use them.

A: I just realized that the answer I accepted was not exactly correct.  For some reason (django magic), save is called more than once, one for getting data, and once to save, so it was making two event instances every time a job was created.  Another problem was that the event must also be saved prior to saving the job, or trying to run job.save() throws an error.  I solved that by using the following code.
def save(self, commit=True):
    job = super(JobCreateForm, self).save(commit=False)
    if commit:
        event = Event(duration=self.cleaned_data.get('duration'), title=self.cleaned_data.get('customer'))
        event.save()
        job.event = event
        job.save()
    return job


text:
Q: Is there a built and minified AureliaJS? I don't want to get into the why / why nots of Node, jspm, Gulp etc. (they have my full buy-in) but to cut a long (boring) story short, I absolutely cannot use those lovely tools at the location i am currently at.
I want to use Aurelia. I just want to drop the built minified javascript library into my web application and start using it.
Where is such a package?
Many thanks,
R.

A: We don't have an official one yet, but we are looking into it. There may be something unofficial floating around. Aurelia does require a module loader. Even though you can't use node-related tools, can we assume that you can use either system.js or require.js as a loader? (preferably system.js)

A: Not possible for this time because aureliajs is only starting period and not complete for development.


text:
Q: QGIS, labels offset for a line layer I am working with rule based labels on a line layer and need to move the labels along different axes along the line. I want to move the label 2 along the line a few millimeters.
For the label 2, the placement is a curve, and the position is above the line. The labels 1 and 2 will repeat after 15 millimeters, and I need the label 2 to be offset from the label 1 along the line by a few millimeters. There is a distance parameter, but it is responsible for the offset not along the line, but across.

Сurrent setting for the first label
Current setting for the second label


text:
Q: AccessViolationException [ArcEngine] I am currently developing using ArcObects 10.2.1 and I've encountered this tricky exception:
AccessViolationException was encountered
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
Source=System.Windows.Forms
StackTrace:
   System.Windows.Forms.UnsafeNativeMethods.CallWindowProc(IntPtr wndProc, IntPtr hWnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   System.Windows.Forms.NativeWindow.DefWndProc(Message& m)
   System.Windows.Forms.Control.DefWndProc(Message& m)
   System.Windows.Forms.Control.WndProc(Message& m)
   System.Windows.Forms.AxHost.WndProc(Message& m)
   System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

InnerException:
I tried to annotate the code and find out where it was wrong,I found it's in the last line.but I still don't know how to solve it.
    public void SetSimpleLabel(IFeatureLayer featLayer, string field, string where = "")
    {
        IGeoFeatureLayer geoFeatureLayer = featLayer as IGeoFeatureLayer;
        IAnnotateLayerPropertiesCollection annoProperties = geoFeatureLayer.AnnotationProperties;
        annoProperties.Clear();

        ILineLabelPosition position = new LineLabelPosition();
        position.Parallel = true;
        position.Perpendicular = false;

        ILineLabelPlacementPriorities placement = new LineLabelPlacementPriorities();
        IBasicOverposterLayerProperties basic = new BasicOverposterLayerProperties();
        basic.FeatureType = esriBasicOverposterFeatureType.esriOverposterPoint;
        basic.LineLabelPlacementPriorities = placement;
        basic.LineLabelPosition = position;

        ILabelEngineLayerProperties labelProperties = new LabelEngineLayerProperties() as ILabelEngineLayerProperties;
        labelProperties.Symbol = sf.CreateTextSymbol(null, 12, null, null, esriTextHorizontalAlignment.esriTHACenter);
        labelProperties.BasicOverposterLayerProperties = basic;
        labelProperties.Expression = "[" + field + "]";
        IAnnotateLayerProperties annoLayerProperties = labelProperties as IAnnotateLayerProperties;
        if (where != "")
            annoLayerProperties.WhereClause = where;
        annoProperties.Add(annoLayerProperties);

        geoFeatureLayer.DisplayAnnotation = true; //it cause
    }

why does it cause the exception?Does anybody have any ideas?


text:
Q: Laptop doesn't boot I have couple years old Packard bell easynote ts11-hr-777nc. Recently I had serious overheating problems so I opened the laptop and removed the dust (there wasn't alot).
Now when I press the power button, fans and lights go up, but after a second laptop shuts down. So no bios, nor windows. Did I do some damage to motherboard when I removed the dust? Is there a way to check what's wrong with my laptop?
Thanks

A: .Not Booting to Windows but you were getting light/s and fan on..
.You can try the Motherboard self-test first. Remove all the RAMs, if you hear a beep sound, it means that the motherboard is still functional. If there's no sound, that means that the motherboard is defective. You need to bench it and replace it, or just replace the whole unit, it will be cheaper than exchanging the board.


text:
Q: Trim / Truncating / Limit Chars of Title  Tag Only in Wordpress using Functions.php Our website, many of the titles in meta name="title" content="HUGE MOTHER TITLES HERE..." Have titles exceeding the 50-55 norm. How to trim the meta title result only?  I do not want to trim anything in the front end, only the rendered  shown in the view src.
Saw this example below, but can dig up the needed action, the attached action with the below example may have been too old. Likewise this trims the 'chars' to 5 words, however, we would prefer to set the total string amount to max50, and then add ellipsis (...) to keep it more realistic.
<meta name="title" content="<?php echo wp_trim_words( get_the_title(), 5 ); ?>" />

Been digging thru the ancient posts of yesteryear (2015) online... nothing but voodoo...
Thanks guys.

A: The below code trims the <meta name="title" content="it works here, booyakka..." /> to 50 characters and adds ... after the 50. Set the number to what you prefer.
However this solution does not trim the <title>Still monster titles in here...<title/>
I will start a new question for that.
    /**
 * Fix Title Meta - add to functions.php
 */
function create_meta_title() {
$title = mb_strimwidth(get_the_title(), 0, 50, '...');
echo "<meta name=\"title\" content=\"$title\" />\n";
}
add_action('wp_head', 'create_meta_title');


text:
Q: Android studio gradle build error 'after' connecting it to firebase database after connecting to firebase realtime database , I am getting build gradle error as :-
(https://i.stack.imgur.com/cPuqb.png)(https://i.stack.imgur.com/evv5S.png)
I tried changing gradle plugin versions but errror is not getting solved


text:
Q: ffmpeg - add multiple videos in panes, give offset start times how? In these days of COVID, our choir director is recording a video which is the accompaniment, and then each choir member (at home) is listening to the accompaniment in headphones, singing along, and recording their voice and lovely face as a video.  I now want to take all these disparate videos and combine them into one video with all the members in small panes, Brady Bunch style.  And of course, each choir member has different hardware so the audio levels are all different and need to be normalized.  And of course, one person took the video sideways (portrait instead of landscape) so their video has to be cropped before adding it in.
I've got it mostly working, my command line looks like this (simplified):
ffmpeg -y -i "Director.MOV"
   -i "Member1.MOV"
   -i "Member2.mp4"
   -filter_complex "
      nullsrc=size=1920x1080 [base];
      [0:v] scale=960x540 [clip0];
      [0:a]volume=1[aud0];
      [1:v] crop=1080:1000:0:920,scale=583x540 [clip1];
      [1:a]volume=2[aud1];
      [2:v] scale=960x540 [clip2];
      [2:a]volume=1.1[aud2];
      [base][clip0] overlay=shortest=1:x=0:y=0 [tmp0];
      [tmp0][clip1] overlay=shortest=1:x=1148:y=0 [tmp1];
      [tmp1][clip2] overlay=shortest=1:x=0:y=540 [tmp2];
      [aud0][aud1][aud2]amix=inputs=3[a]
   " -map "[tmp2]" -map "[a]" -c:v libx264 output.mkv"

That's working beautifully.
Now for the (hopefully final) issue.  Everybody hit the "record" button at different times, so the videos have to be time-shifted before being combined.
I tried adding -itsoffet as mentioned here, but of course that offsets the video and not the audio.  I tried adding the offset after the STARTPTS as mentioned here, and again that offsets only the video.  I tried offsetting the audio using the asetpts method as mentioned here but that didn't seem to do anything.
EDIT
[0:v] setpts=PTS-STARTPTS-0.2/TB,scale=960x540 [clip0];
[0:a]volume=1.7066118239302597,asetpts=PTS-STARTPTS-0.2/TB[aud0];
[1:v] setpts=PTS-STARTPTS-3.2/TB,crop=1080:1000:0:920,scale=583x540 [clip1];
[1:a]volume=2.384951956074125,asetpts=PTS-STARTPTS-3.2/TB[aud1];
[2:v] setpts=PTS-STARTPTS,scale=960x540 [clip2];
[2:a]volume=1.1[aud2];

How do I shift videos forward or backward in time, while keeping their audio in sync?
I tried going the other direction (adding a positive offset to the videos that started later, instead of a negative offset to the videos that started sooner), just to see what would happen (see if PTS-STARTPTS doesn't like negative numbers), and it was no better -
[0:v] setpts=PTS-STARTPTS+3/TB,scale=960x540 [clip0];
[0:a]volume=1.7066118239302597,asetpts=PTS-STARTPTS+3/TB[aud0];
[1:v] setpts=PTS-STARTPTS,crop=1080:1000:0:920,scale=583x540 [clip1];
[1:a]volume=2.384951956074125[aud1];
[2:v] setpts=PTS-STARTPTS+3.2/TB,scale=960x540 [clip2];
[2:a]volume=1.1,asetpts=PTS-STARTPTS+3.2/TB[aud2];
[base][clip0] overlay=shortest=1:x=0:y=0 [tmp0];
[tmp0][clip1] overlay=shortest=1:x=1148:y=0 [tmp1];
[tmp1][clip2] overlay=shortest=1:x=0:y=540 [tmp2];
[aud0][aud1][aud2]amix=inputs=3[a]

EDIT: ffmpeg -version reports
ffmpeg version git-2020-08-07-fab00b0 Copyright (c) 2000-2020 the FFmpeg developers
built with gcc 10.2.1 (GCC) 20200805

which seems reasonably up-to-date.

A: itsoffset works on audio as well; it's just that amix doesn't respect absolute timestamps. Use aresample to pad the start with silence.
I'd also suggest you alter offsets with respect to the earliest starting video, so all offsets are positive. overlay has to be altered to avoid showing a frozen first frame till playback starts, for delayed streams.
ffmpeg -y -i "Director.MOV"
   -itsoffset 5 -i "Member1.MOV"
   -itsoffset 10 -i "Member2.mp4"
   -filter_complex "
      nullsrc=size=1920x1080 [base];
      [0:v] scale=960x540 [clip0];
      [0:a]volume=1[aud0];
      [1:v] crop=1080:1000:0:920,scale=583x540 [clip1];
      [1:a]volume=2,aresample=async=1:first_pts=0[aud1];
      [2:v] scale=960x540 [clip2];
      [2:a]volume=1.1,aresample=async=1:first_pts=0[aud2];
      [base][clip0] overlay=shortest=1:x=0:y=0 [tmp0];
      [tmp0][clip1] overlay=shortest=1:x=1148:y=0:enable='gt(t\,5)' [tmp1];
      [tmp1][clip2] overlay=shortest=1:x=0:y=540:enable='gt(t\,10) [tmp2];
      [aud0][aud1][aud2]amix=inputs=3[a]
   " -map "[tmp2]" -map "[a]" -c:v libx264 output.mkv"

Use ffmpeg 4.1 or later.


text:
Q: Redirect with querystring I have a certain situation where the ActionResult method in a controller needs to do a Redirect if a Returnurl is provided.
However, how can I append a querystring to that and still use:
return Redirect(url) ?
everytime I do this, I always get a security exception that the request had a potentially dangerous value (the ampersand or even the question mark).

A: Try this,filling in the name of the action and controller as appropriate:
System.Web.Routing.RouteValueDictionary rvd = new System.Web.Routing.RouteValueDictionary();
foreach(string key in HttpContext.Request.QueryString.AllKeys)
{
    rvd.Add(key, HttpContext.Request.QueryString[key]);
}

return RedirectToAction("MyAction", "MyController", rvd);

A: forgot - I used Url.Content and now it works just fine.
return Redirect(Url.Content(model.ReturnUrl + otherPotentialQueryStringHere)


text:
Q: IQueryable doesn't implement IDbAsyncEnumerable The question was originally asked at http://entityframework.codeplex.com/discussions/399499#post928179 .
Good day! Please tell me if it is wrong place to post this question.
I have a query as follows:
IQueryable<Card> cardsQuery =
  dataContext.Cards
  .Where(predicate)
  .OrderByDescending(kc => kc.SendDate)
  .AsQueryable();

Then I try:

Task<Card[]> result = cardsQuery.ToArrayAsync();

And then exception rises:
The source IQueryable doesn't implement IDbAsyncEnumerable<Models.Card>
I use modified version of 'EF 5.x DbCotext generator'.
How to avoid it?
UPDATE
Important remark is that I have method to produce IQuerayble<Card> as follows:
class Repository {
  public IQueryable<Card> GetKudosCards(Func<Card, bool> predicate) {
    IEnumerable<KudosCard> kudosCards = kudosCardsQuery.Where(predicate);
     return kudosCards
            .OrderByDescending(kc => kc.SendDate)
            .AsQueryable();
  }
}

A: What is the point of calling AsQueryable? If you compose a query with the extension methods starting from an IQueryable source collection (e.g. DbSet, ObjectSet), the query will be IQueryable too.
The purpose of AsQueryable is to wrap an IEnumerable collection with an IQueryable proxy/adapter that uses a Linq provider that is capable of compiling IQueryable queries into a Linq to Object queries. This can be useful in scenarios when you would like to use inmemory data queries.
Why is the AsQueryable call necessary? What if you just simply remove it?
Update
Okey, now it seems I understand your problem. After a quick look on the ODataQueryOptions.ApplyTo I realized that it just extends the underlying expression tree of the query. You can still use it to run the query in the way you want, however you need a little trick to transform the query back to generic.
IQueryable<Card> cardsQuery =
   dataContext.Cards
    .Where(predicate)
    .OrderByDescending(kc => kc.SendDate);

IQueryable odataQuery = queryOptions.ApplyTo(cardsQuery);

// The OData query option applier creates a non generic query, transform it back to generic
cardsQuery = cardsQuery.Provider.CreateQuery<Card>(odataQuery.Expression);

Task<Card[]> result = cardsQuery.ToArrayAsync();

A: The problem is as follows.
I have a method:
class Repository {
  public IQueryable<Card> GetKudosCards(Func<Card, bool> predicate) {
    IEnumerable<KudosCard> kudosCards = kudosCardsQuery.Where(predicate);
    return kudosCards
            .OrderByDescending(kc => kc.SendDate)
            .AsQueryable();
  }
}

The problem is that kudosCards has type IEnumerable<KudosCard>. That throws exception. If I change predicate type to Expression<Func<Card, bool> predicate then everything works just fine.

A: I had the same problem when I was using the LinqKit library expression builder, which in the end, was producing AsQueryable(), and very surprisingly it was happening for me from the XUnit Integration Tests call.
I was going wild about why the same problem wasn't happening when calling the same API endpoint via Swagger.
It turned out I had to do an elementary change.
I had to replace:
using System.Data.Entity;

with:
using Microsoft.EntityFrameworkCore;

A: I had the same problem when I was using the LinqKit library expression builder, which in the end, was producing AsQueryable().
And very surprisingly, it was happening for me from the XUnit Integration Tests call.
I was going wild about why the same problem wasn't happening when calling the same API endpoint via Swagger.

It turned out I had to do an elementary change.
I had to replace the:
using System.Data.Entity;

with:
using Microsoft.EntityFrameworkCore;

In the place where I was calling the LinqKit expression method.

A: If you want to use the List<T> for Linq query, Avoid chaining it with ToListAsync(). It uses the class IDbAsyncEnumerable that is not available to a normal List<T> object


text:
Q: setImage forState method sets the image for all the states on a button I have this small problem that i cannot figure out. I have about 16 buttons and they are connected as an outlet collection to my controller.And also they have an action method which makes the buttons change their state from default to selected. Im trying to change all the buttons' images for only default state. So i run a loop through the array and set their image for the default state using setImage: forState: method. However the method changes the images for all states( Default and selected states ).
This is the setter method for my outlet collection
- (void) setCardsButton:(NSArray *)cardsButton
{
    _cardsButton = cardsButton;

    for (UIButton *button in cardsButton) {

         [button setImage:[UIImage imageNamed:@"card.png"] forState:UIControlStateNormal];

    }
     [self updateView];

}

A: If you don't specify an image for another state, the image for the 'normal' (UIControlStateNormal) state will be used instead. So, explicitly set the image you want to be used for state UIControlStateSelected.
If the 'normal' state isn't set then the system default is used.

A: Any properties you set for the "Normal" state are used for all other states not explicitly set otherwise. This is stated in the docs for UIButton setImage:forState:. If you want a different image for other states, you need to call setImage:forState: for the other states as well.


text:
Q: How to send google maps location info through SMS as a link In an application that I'm building,
I am trying to send my location info(Lat,Long/ Geocoded) to my emergency contact list.
I am assuming that all my recipients are using smartphones(Android/iOS)
Until now, the application sends my location info as a string through SMS:
"I am at: " + Some Geocoded Location

However, I thought that this is not an optimal way of sending the exact location info.
So, I was thinking if it was possible to generate a map through Google Maps API with a
pinpoint/dot on it, and send a link to that map.
Can this be done in Device level(Without contacting any servers)
Or, can this be done by making my own map website?
Or, is this not possible at all?
I'd appreciate better approaches and suggestions as well.
Thank you in advance

A: The simple and smarter way is to use q= parameter, so that it displays the map with the point marked.

Example -:
http://maps.google.com/?q=<lat>,<lng>

where lat- latitude,
lng- longitude

If the device that receives the sms with the above link is one of following :

*

*Smartphone(say android) , then it will show maps application in launching intent list on device when clicked on the above shared url.

*If not (simple phone) the link will redirect to browser with the maps.google.com showing the location with pin point.


text:
Q: How to change multiple  tag into ?

<?php

$content_description = '
They have added their own unique spin to marketing technology and convinced us that their refreshing understanding of the whys and wherefores of this rapidly growing industry is just one of the several ways to look at business. In this feature, we bring you the views of key executives who discuss how their 'being' pours into their professional personas

How does being a woman as a part of an exponentially explosive marketing tech space help you to be better equipped to understand this constantly evolving sector through your unique perspective?

Nikki Nixon, Director #FlipMyFunnel at Terminus

"Being a woman in marketing tech, coupled with being an introvert, has given me tremendous advantages. I've had the opportunity to grow two software companies in the space and be uniquely empathetic along the way. My introversion allows me to think critically about the pros and cons of a given tool beyond the surface sales pitch. It allows me to dig deeper and ask questions to determine if the tool will really solve my needs."

Jen Spencer, Vice President of Sales and Marketing at Allbound

"Since I'm a woman, and I've always been a woman, I don't know any other way of being. I can't begin to assume I know what makes me as a woman better suited to lead a sales and marketing team at a SaaS company than a man – except maybe that having had twins, I know I have more stamina than most. Getting by on 4 hours of sleep a night? No problem! Getting those 4 hours of sleep in 1 hour increments over a 12-hour period? I. Will. Win.

?>

I need to Replace all the Img tag into <amp-img> Format of all images should look like.<amp-img src="/img/amp.jpg" width="1080" height="610" layout="responsive" alt="AMP"></amp-img>

A: Use .replaceWith() API to replace the content :
$('p').find('img').replaceWith(function () {
   return '<amp-img src="'+this.src+'" width="1080" height="610" layout="responsive" alt="'+this.alt+'"></amp-img>'
 });

Using PHP Code:
$html = preg_replace('//', '<amp-img$1></amp-img>',$content_description);

Hope this works for you.

A: You can achieve your goal by using following approach

*

*Remove inline css for content, because amp does not support inline css

*Convert the  tag into <amp-img> tag, also add the height, width and layout (amp requirement)

Here is working Url : Click Here
Code :
<?php
$content_description = '
They have added their own unique spin to marketing technology and convinced us that their refreshing understanding of the whys and wherefores of this rapidly growing industry is just one of the several ways to look at business. In this feature, we bring you the views of key executives who discuss how their 'being' pours into their professional personas

How does being a woman as a part of an exponentially explosive marketing tech space help you to be better equipped to understand this constantly evolving sector through your unique perspective?

Nikki Nixon, Director #FlipMyFunnel at Terminus

"Being a woman in marketing tech, coupled with being an introvert, has given me tremendous advantages. I've had the opportunity to grow two software companies in the space and be uniquely empathetic along the way. My introversion allows me to think critically about the pros and cons of a given tool beyond the surface sales pitch. It allows me to dig deeper and ask questions to determine if the tool will really solve my needs."

Jen Spencer, Vice President of Sales and Marketing at Allbound

"Since I'm a woman, and I've always been a woman, I don't know any other way of being. I can't begin to assume I know what makes me as a woman better suited to lead a sales and marketing team at a SaaS company than a man – except maybe that having had twins, I know I have more stamina than most. Getting by on 4 hours of sleep a night? No problem! Getting those 4 hours of sleep in 1 hour increments over a 12-hour period? I. Will. Win.
';
$content = preg_replace('/style=[^>]*/', '', $content_description);
$html = preg_replace('//', '<amp-img$1 width="1080" height="610" layout="responsive" alt="AMP"></amp-img>',$content);
echo $html;
?>


text:
Q: How to set the initial weights to Xavier? I would like to set the initial weights in Pytorch to Xavier.
class Model(nn.Module):
    def __init__(self):
        super(Model, self).__init__()
        # self.linear1 = nn.Linear(1, 516*4*4)
        self.linear1 = nn.Linear(2, 512*8)
        self.linear2 = nn.Linear(256*16, 256*8)
        self.linear3 = nn.Linear(256*8, 1)

    def forward(self, x):
        x = self.linear1(x)
        x = torch.sigmoid(x)
        x = self.linear2(x)
        x = torch.sigmoid(x)
        x = self.linear3(x)

A: You can loop over each layer using the children generator and initialize the layer weights using the built-in xavier_uniform_ initializer provided by nn.init module.
For example, you could put this in your __init__ definition:
for m in self.children():
    if isinstance(m, nn.Linear):
        nn.init.xavier_uniform_(m.weight)
        m.bias.data.fill_(0.01)


text:
Q: OpenAs_RunDLL in Vista This isn't strictly a programming question, but hopefully someone here has the knowledge to help me.
Running Vista x64, the "Open File With" dialog takes forever to appear when trying to open a file with unknown type.
To be specific, the prompt giving the choice between "Use the web service to find the correct program" and "Select a program from a list of installed programs" appears immediately, but there is about a 10 second delay between pressing OK here and the next window (with a list of installed programs) appearing.
The same delay is present when I run "rundll32 shell32.dll,OpenAs_RunDLL" from a command line.
I'm guessing that this is not common behaviour, because I find it incredibly annoying, and I couldn't find any mention of it anywhere.
So..does anyone have any ideas what it might be?  Or what I could do to try and find out?

A: VonC could be correct.
Read this article:
http://blogs.technet.com/markrussinovich/archive/2005/08/28/the-case-of-the-intermittent-and-annoying-explorer-hangs.aspx
You should use process explorer to watch the stack when you initiate the action. You should be able to tell what sort of operation is timing out.
Download process explorer here:
http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx

A: You could check if you do not have have network connection declared (net use), or more generally any network paths which may be used by your list of program listed to "Open File With".
If a network path is unavailable, a 'timeout' delay can affect the GUI responsiveness, especially if that GUI must explore/list those paths.


text:
Q: Number of random walks in which the maximum distance from the origin is reached only at the end Consider a random walk in which each step is either $\binom{-1}{-1}$ or $\binom{1}{-1}$.
Define "Furthest-at-Finish path" (abbreviated as FF) as a path in which the maximum horizontal distance from the origin is reached only at the end.
So for example,
The path $\binom{1}{-1}, \binom{-1}{-1}, \binom{1}{-1}, \binom{1}{-1}$ is an FF because the maximum horizontal distance from the origin, $2$, is reached only at the end.
The path $\binom{1}{-1}, \binom{1}{-1}, \binom{-1}{-1}$ is not an FF because the maximum horizontal distance from the origin, $2$, is reached before the end.

Prove that the number of FF with $2k$ steps is $\binom{2k}{k}$.

I have a proof, shown below. I am looking for a simpler, more intuitive proof.

A: There does exist a bijective proof, using something called the Catalan factorization of a random walk. This proof is given in Random walks and Catalan factorizations, by Ömer Eğecioğlu and Alastair King. The authors show how to give a bijection from  $FF$ paths, to the set of paths from $A$ to $A'$ of length $2k$, where $A'$ is the point $2k$ units south of $A$. Obviously, the number of paths $A\to A'$ is $\binom{2k}k$. However, their bijection is not something I would call intuitive.
To equate your setup to  the one used in the paper, you need to rotate your picture $90^\circ$ clockwise. That is, instead of counting walks from $A$ to $C$ whose steps are $\binom{-1}{-1}$ and $\binom{-1}1$, you consider walks from $C$ to $A$ when the picture is rotated $90^\circ$ anti-clockwise, using steps $\binom{1}{1}$ and $\binom{1}{-1}$. Now, the condition $FF$ in the original setup translates to saying that the walk never dips below the horizontal line passing through $C$ (which is the green line in your picture, rotated $90^\circ$). In the language of the paper, these are nonnegative walks of length $2k$. By proposition $2$ in that paper, they are in bijection with balanced walks of length $2k$, which are obviously enumerated by $\binom{2k}k$.


text:
Q: Customize spring:form to render different value and tag content I have the following jsp:
<form:select path="terminalStatus">
     <form:options items="${allStatuses}"/>
</form:select>

it renders like this:
<select id="terminalStatus" name="terminalStatus">
     <option value="ACTIVE" selected="selected">ACTIVE</option>
     <option value="INACTIVE">INACTIVE</option>
</select>

I want that it renders a bit different. like this:
<select id="terminalStatus" name="terminalStatus">
     <option value="ACTIVE" selected="selected">label_1</option>
     <option value="INACTIVE">label_2</option>
</select>

Actually allstatuses is the set of enum values of TerminalStatus:
public enum TerminalStatus {
    ACTIVE("label_1"), INACTIVE("label_2");
    String label;

    public String getLabel() {
        return label;
    }

    private TerminalStatus(String label) {
        this.label = label;

    }
}

Does spring form allow to customize my jsp to get desired result ?

A: form:options tag have special attribute for this (itemLabel):
<form:select path="terminalStatus">
    <form:options items="${allStatuses}" itemLabel="label"/>
</form:select>


text:
Q: how to display marker title for multiple markers without tapping on it in iOS swift like places in photo gallery in iOS Im able to display info window of markers but can we display the info when the map loads without even tapping on marker?

A: Okay, since google maps currently don't provide this functionality by default here is a work around. When you create your marker manipulate it as follows:

*

*First you create a view and add your label and image to it.
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 20)];
        // Set label properties as required including marker Name

UIImageView *markerIconImageView = [[UIImageView alloc]initWithFrame:CGRectMake(35, 10, 30, 50)];
        // Set image properties as required including image which will be displayed as marker

UIView *markerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
[markerView addSubview:label];
[markerView addSubview:markerIconImageView];

*Then you create a marker and assign it the image of above view:
GMSMarker *marker = [[GMSMarker alloc] init];
marker.icon  = [self imageWithView:markerView];
marker.position = coordinates for marker;
marker.appearAnimation = kGMSMarkerAnimationPop;
marker.map = your map;

*For reference here is my function for converting view to image:
-(UIImage *) imageWithView:(UIView *)view
{
    UIGraphicsBeginImageContext(view.bounds.size);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
 }

We have converted the view to image because. It takes up lesser space in memory.
Hope this helps. And gives you an idea for the approach.


text:
Q: Run Blustacks or Android to play clash of clans on ubuntu 13.4+ I am trying to get rid of the need to dual boot Ubuntu and windows and one thing I can do with windows I can not do with Linux is to run Bluestacks to play android games my favourite one ow is clash of clans. I have tried different VM's to run android emulators and virtual box but nothing works for clash of clans I can download the game to the VM from Google Play Store but it fails to open
If Ubuntu can fix this by making a way to successfully install Bluestacks on Ubuntu or Android with Virtual box with out loading errors of all apps/games it would help the Linux community to become less dependant of Windows.
Thanks in advance! go Ubuntu!

A: Install VirtualBox Install virtualbox from the Ubuntu Software Center.
download android sdk to run AVD
Create a new Virtual Machine with the steps mentioned here.
http://androvm.org/blog/blog/2012/11/14/androvm-configuration-tutorial/
download ur app and run
------------------OR--------------
(BEST=>)Try Genymotion runs with VBox/ Linux
Its not really bluestacks but something similar which will emulate android apps
http://forum.xda-developers.com/showthread.php?t=2333452

A: Use Wine Application to run it on Ubuntu. It can run any app of windows in Ubuntu. You can Download it from Software center.
USe he virtual box. For more information check outenter link description here


text:
Q: Append input field with click in select menu I have a select options menu. I want that jQuery/ javascript appends an input field in a specific "div content" under the menu when clicking a certain option value in it.
At the moment nothing gets triggered with the click event.
If you click in the select menu on the option value "Search Field" an input field should be created in the
 area.
My code:

$('.inputicon').click(function() {
  $(".content").append('<input id="test">')
});

<select name="category6" id="category6" class="form-control">
  <option value="">Delete</option>
  <optgroup label="Search" value="iconsearch">
    <option class="inputicon " value="16">Search Field</option>
  </optgroup>
</select>

A: Options don't get click events. Use the change event of the <select> and check if the value is 16.

$('#category6').change(function() {
  if (this.value == '16') {
    $("#content").append('<input id="test">')
  } else {
    $("#test").remove();
  }
});

<select name="category6" id="category6" class="form-control">
  <option value="">Delete</option>
  <optgroup label="Search" value="iconsearch">
    <option class="inputicon " value="16">Search Field</option>
  </optgroup>
</select>


text:
Q: ReCaptcha JSP 'Cannot load URL' on processing Following instructions in this url: https://developers.google.com/recaptcha/docs/java
I'm trying to use reCaptcha with the JSP plugin using the code they provide on the page.
My initial page works fine - the captcha is displayed and I can enter the text and submit.
The problem is with my processing page which is returning an error:
net.tanesha.recaptcha.ReCaptchaException: Cannot load URL: Connection timed out: connect at net.tanesha.recaptcha.http.SimpleHttpLoader.httpPost(SimpleHttpLoader.java:89) at net.tanesha.recaptcha.ReCaptchaImpl.checkAnswer(ReCaptchaImpl.java:61) at org.apache.jsp.Captchas.processServer_jsp._jspService(processServer_jsp.java:7...
So it says it 'Cannot load URL' - is this a problem with the company's firewall?

A: Yes it is the problem with your network connectivity . You can conclude it by checking your connection with google.com.
If you are able to connect with google in your browser amidst of the firewall , you can  successfully run the captacha code


text:
Q: How to search only 'not-installed' packages in Arch Linux? What flags can one use with pacman -S to show only those packages, that aren't yet installed?
Will accept shell script if it can't be done by design. Thx.

A: After first try was the inverse answer, thanks Jeff Schaller. Here's a little script that filters out installed packages and only displays not installed packages.
#!/bin/sh

installed=$(pacman -Q | cut -d ' ' -f 1 | tr '\n' '|')
pacman -Ssq | egrep -v \'${installed}\'

A: here is a script with 3 different methods, all keeping the one line description. also it lets you do search terms with command line arguments
#!/bin/bash
#pacman -Ss "$@" | pcregrep -Mv '.*\[installed.*\n'
#pacman -Ss "$@" | sed -n -e '/\[installed/!p;: m' -e '//{' -e '$!{' -e 'n;b m' -e '}' -e'}'
pacman -Ss "$@" | awk '/\[installed/ { getline; next } 1'

example:
pacman-search-exclude-installed.sh search terms

my research:
How to grep -v and also exclude the next line after the match?
How to `grep -v` and also exclude 'n' lines after the match?

A: expanding on @thomas answer here are some ready to go functions you can source and use to achieve OPs question
pmig () {
  pacman -Q | grep $1 | cut -d ' ' -f 1
}

pmrg () {
pacman -Ssq | grep $1
}

pmnig () {
local installed="|$(pmig $1 | tr '\n' '|')"
pmrg $1 | grep -E -v \'${installed}\'
}

pmnigv () {
  pacman -Ss $1 | grep -v "$(pacman -Ss $1 | grep "\[installed\]" -A1 )" | grep -v "\[installed\]"
}

then trying out.
echo "==installed =="; pmig disk; echo "==in repos=="; pmrg disk; echo "===in repos but not installed==="; pmnig disk
results in
==installed ==
gnome-disk-utility
gptfdisk
udiskie
udisks2
==in repos==
gnome-disk-utility
gptfdisk
plasma-disks
testdisk
udisks2
xfce4-diskperf-plugin
deepin-diskmanager
diskonaut
diskus
haskell-disk-free-space
kdiskmark
udiskie
udisks2-qt5
xdiskusage
yubikey-full-disk-encryption
===in repos but not installed===
plasma-disks
testdisk
xfce4-diskperf-plugin
deepin-diskmanager
diskonaut
diskus
haskell-disk-free-space
kdiskmark
xdiskusage
yubikey-full-disk-encryption

an pmnigv is a verbose version
pmigv disk
extra/cdrdao 1.2.5-1
    Records audio/data CD-Rs in disk-at-once (DAO) mode
extra/filelight 22.12.2-1 (kde-applications kde-utilities)
    View disk usage information
extra/kdf 22.12.2-1 (kde-applications kde-utilities)
    View Disk Usage
extra/libisofs 1.5.4-1
    Library to pack up hard disk files and directories into a ISO 9660 disk image
extra/mtools 1:4.0.42-1
    A collection of utilities to access MS-DOS disks
extra/partitionmanager 22.12.2-1 (kde-applications kde-system)
    A KDE utility that allows you to manage disks, partitions, and file systems
extra/plasma-disks 5.26.5-1 (plasma)
    Monitors S.M.A.R.T. capable devices for imminent failure
extra/qemu-img 7.2.0-3
    QEMU tooling for manipulating disk images
....


text:
Q: Which jquery frunction [bind, on, live, delegate] is safe to use for event binding to guarantee compatibility with future releases? I came accross a few posts on stackoverflow that says bind will be removed from future releases of jquery and only on will be used for event binding. As in the following post:
jquery .bind() vs. .on()
Is it true that bind will be removed? If so which event binding function should I use?


text:
Q: NGINX try_files across multiple drives on Windows I am moving nginx out of a Linux VM to the Windows host for performance reasons and I'm having trouble with this part.
On Linux the configuration is:
root /;

try_files /mnt/m$uri /mnt/d$uri /mnt/l$uri =404;

Where /mnt/m, /mnt/d and /mnt/l are the mount points of the M:, D: and L: drives respectively.
On Windows I tried
root /;

try_files M:$uri D:$uri L:$uri =404;

but it throws this error
*1 GetFileAttributesEx() "C:L:/[...]" failed (123: The filename, directory name, or volume label syntax is incorrect)

It seems / is interpreted as the C: drive, it's the drive that nginx runs from. I also tried root ; and leaving the root directive out altogether but nothing worked.

A: I managed to do it by nesting(?) named locations. Though be careful as any headers/options you set in the main location block won't apply in the named locations, at least in my experience. @IvanShatsky's solution with NTFS mount points seems to be a lot better.
location /  {
    root "M:\\";
    try_files $uri $uri/ @ddrive;

}

location @ddrive {
    root "D:\\";
    try_files $uri $uri/ @ldrive;
}

location @ldrive {
    root "L:\\";
    try_files $uri $uri/ =404;
}

A: I think mklink on Windows may be a solution.
https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/mklink
You can link your mounted disk to, for example, C:\mnt\M, C:\mnt\D, C:\mnt\L with command like:
mklink /D C:\mnt\M M:
mklink /D C:\mnt\D D:
mklink /D C:\mnt\L L:

and then in nginx.conf
...
root C:/mnt/;

try_files /M/$uri /D/$uri /L/$uri =404;
...


text:
Q: Trying to set up virtual hosts to block access by IP, for three domains and when using SSL on one domain So I want all this on one server:
- 3 domains / websites
- SSL on one of them
- nothing to be accessed by an IP address (e.g. 'domain.com' is okay, but not by just typing '123.55.44.123' into the browser)

I am using:
- Ubuntu 12.04 LTS
- Apache

I have set these virtual hosts up and everything works perfectly for non-SSL
<VirtualHost *:80>
ServerName 123.55.33.123
DocumentRoot /var/www/random-empty-folder
<Directory />
Options FollowSymLinks
Deny from all                    # notice the deny here
</Directory>
</VirtualHost>

<VirtualHost *:80>
ServerName www.domain-one.com
ServerAlias domain-one.com *.domain-one.com
DocumentRoot /var/www/domain-one
<Directory />
Options FollowSymLinks
AllowOverride All
</Directory>
</VirtualHost>

<VirtualHost *:80>
ServerName www.domain-two.com
ServerAlias domain-two.com *.domain-two.com
DocumentRoot /var/www/domain-two
<Directory />
Options FollowSymLinks
AllowOverride All
</Directory>
</VirtualHost>

...etc. for 'domain-three'

The problem is that I can't get this configured for SSL. My standard SSL setup is this, but that allows access using the IP address. I just need to stop that:
<VirtualHost *:443>
ServerName www.domain-two.com:443
ServerAlias domain-two.com *.domain-two.com
DocumentRoot /var/www/domain-two
SSLEngine on
SSLCertificateFile /etc/apache2/ssl/apache.crt
SSLCertificateKeyFile /etc/apache2/ssl/apache.key
<Directory />
Options FollowSymLinks
AllowOverride All
</Directory>
</VirtualHost>

There's also a 'default-ssl' site/file which is disabled, so not sure if I should be doing something with that. I've tried enabling it and making changes, but mostly I run into a 'default duplicate' error.
So, based on the above setup, I just need to block access to [https]://123.55.44.123. Thanks in advance.
I do always run 'service apache2 reload' after making changes, just in case anyone is wondering.

A: A possible alternative, rather than blocking access, what if you forwarded any requests that come to the ip address over to your hostname?  This could be done with htaccess or mod_rewrite.
RewriteEngine On
RewriteCond %{HTTP_HOST} ^123\.55\.33\.123
RewriteRule (.*) http://domain-one.com/$1 [R=301,L]

I believe because the way SSL works (ip address-dependent) that you won't be able to block requests at the apache level.  If you're working w PHP or such, you could have an include file that checks the $_SERVER['HTTP_HOST'] and dies if it's your ip address.

A: Since the domain requested is in the http headers (and thus still encrypted when apache has to decide which vhost config to use) apache uses the IP and port to chose which SSL vhost config to use, not the domain name.
Edit:
I should have mentioned SNI and a couple other factors in my answer. SNI is an addition to TLS that allows servers to use multiple named virtual host configs on one IP/port combination. But since you only have one *:443 VirtualHost configuration block apache will always choose it.
What you want to do is possible, and the easiest way would be to activate default-ssl as a catchall for requests not targeted at a specific domain. I'm not quite sure what you mean by a 'default duplicate' error when activating default-ssl, the full error message might be more helpful. I could suggest naming the symlink 000-default-ssl so that any options you have in it are set first.


text:
Q: New Google Sites Announcements and Recent Post Methods I am currently working on a project that involves upgrading an intranet running Classic Google Sites to new Google Sites. It appears that when upgrading we will lose the announcements and recent post functionality if we upgrade. I am having difficulty locating an example of this functionality being used within new Google Sites on the web. How are developers working around this issue in new Google Sites? Are they working around this issue?
Specific problems:

*

*New Google Sites does not support the gadgets that classic Sites used, so these will be lost.

*This includes content you added via an iframe because the iframe was a gadget.

*You can add content in iframes and make your own gadgets

As per the last list item, can anyone chime in on a preferred gadget for this purpose or point to gadget development source examples that achieves the old announcements functionality seen in classic sites?
Edit: Looking at this deeper, it appears we can achieve similar functionality by adding announcements as a blog post or some other block content. It looks like we can embed HTML. However, linked content need to come from a secure url. I suppose what we are looking for were people to weigh in on their experience using these sort of workarounds.


text:
Q: Do I need a relay or can I wire this circuit with diodes? Background
I'm doing some automotive wiring to add a light to a cargo area with the following requirements:

*

*The light turns on/off when the cargo door is opened/closed

*The cargo light can be turned off with a switch on the dash

*If the vehicle is off but the cargo light is on, an audible buzzer should sound

I don't know much about electronics, but from what I understand after some research I've developed two options. The first option uses a relay, and the second option uses diodes.
My Question
Can I use either of the two options below?  My preference is the diode circuit because it saves space by not needing a second relay.

A: Option 1:

*

*The cargo light will not turn on with the relay coil wired in series with it.

*Even without the series relay coil, the light will turn on only when the door is opened and the dash switch is actuated.
Option 2:

*

*the cargo light will turn on only when the door is opened and the dash switch is actuated.

*When the door is opened without the dash switch being actuated, the buzzer will come on without the cargo light.
Here's my schematic.

Here's my revised schematic considering the dash switch as an override to turn the light off.


text:
Q: docker pull under corporate network - windows Now questions surrounding this topic might be found in abundance here; but when I was facing this issue I surfed throughout the internet, pulling out my hairs, but wasn't able to find a proper solution.
Now, the situation -
I am working on creating docker containers by pulling images from the docker registry. I am working on Windows. I am under the corporate network where Cyberroam is used. When pulling any image I was getting error of

TLS Handshake timeout

When getting out of the corporate network, this issue is getting resolved and I am not getting any errors - all image pulls are working properly.
Not sure if it's a proxy issue or not. But I need it to work under corporate network as the other option for internet is limited.

A: I surfed through the internet many times but with failure all the time.
I tried multiple things, like -

*

*Applying HTTP_PROXY, HTTPS_PROXY and NO_PROXY environment variables at multiple locations (seperate options) like in the docker-machine config file, in the command prompt when the virtual machine is up, in the docker daemon settings under option Proxies.

But my error wasn't getting solved.
So, with less hope I started from beginning and did this -
Firstly I created a new Virtual Switch in Hyper-V Manager. I selected internal option from the given.
Then, going to Network Settings > Change Adapter Settings I opened the properties of the wireless adapter that I used (corporate network).
Under Sharing tab I selected the first option - Allow other network users to connect through this computer's internet connection.
From the dropdown select the virtualswitch that you created in the first step.
Restart docker and in cmd restart the virtual machine - docker-machine restart [machinename]. You might be asked to regenerate the certificates for the virtual machine. Run the commands shown in cmd and you will be good to go.
Now try to pull any image and the error would be solved.

Now I know there would be multiple links in the internet for this solution with most of them suggesting to set environment variables (which, btw, might be the solution for many. Unfortunately wasn't for me).
According to my understanding -
The docker tries to connect to the outer world for pulling an image. Now, previously it wasn't able to pull because, if you think in a way, the docker is inside an environment, which needs to communicate with my laptop in order to access the outer net.
Now, without making any connection between the docker and the laptop internet, it would be able to access the internet. Consider it as a broken link, if you may. Previously I had created a bridge between the virtual switch and the wireless adapter but it wasn't helping. On following the above steps, I was able to do successfully.
Below is an image showing what I understood.

Now this was the solution that I got, able sooo many days; that I had to write this QA with the hope of someone else getting stuck at this point might get some help.
Hope it helps.


text:
Q: Hashmap implemented as a family tree with linked list Java I have a question regarding a Hashmap that is implemented as a Family tree which looks like this. The key value of the Hashmap is the first name of the person and the value is from the class Person, which contains again the first name, the sex and an Arraylist with the children. The children are again from type person.
I want to find a way to make a function, which should return an float array with two fields, in the first field the maximum of children a person has from all persons and the mean of children of all persons. Should look like this:
float[] describe(Map<String, Person> m) {
}

This is the Hashmap: (already filled with keys and values and there is also a link between them and the children)
Map<String, Person> allPersons = new HashMap<String, Person>();

This is the class Person:
class Person {
    String name;
    String sex;
    List<Person> children;

    public Person(String name, String sex) {
        this.name = name;
        this.sex = sex;
        this.children = new ArrayList<Person>();
    }
}

My question is how can u iterate through the Hashmap and also get the amount of children every person has.

A: It may be convenient to use Stream API and its Collectors::summarizingInt with regard to the size of children list per Person:
float[] describe(Map<String, Person> m) {
    IntSummaryStatistics stats = m.values()
        .stream() // Stream<Person>
        .collect(Collectors.summarizingInt(p -> p.getChildren().size()));

    return new float[]{ stats.getMax(), (float) stats.getAverage()};
}

If Stream API cannot be used, the stats may be computed in a simple loop:
float[] describe(Map<String, Person> m) {
    float[] stats = {0.0f, 0.0f};
    for (Person p : m.values()) {
        int kids = p.getChildren().size();
        stats[0] = Math.max(stats[0], kids);
        stats[1] += kids;
    }
    stats[1] /= Math.max(1, m.values().size());
    return stats;
}

A: If you don't care about the size of the grandchildren, you can use stream with summaryStatistics
Map<String, Person> m = Map.of(...);
IntSummaryStatistics stats = m.values().stream()
        .mapToInt(person -> person.children.size())
        .summaryStatistics();
float[] s = {stats.getMax(), (float) stats.getAverage()};

Iterative solution:
float max = 0, sum = 0;
for (Person person : m.values()) {
    max = Math.max(person.children.size(), max);
    sum += person.children.size();
}

float[] s = {max, sum / m.values().size()};