text:
Q: how to redirect laravel website using .htaccess or bootstrap file change how to redirect laravel website using .htaccess or bootstrap file change
I have a domain www.mydm.com/folder/public but maximum url says my.mydm.com how can i tell my domain  my.mydm.com to hit is equal to www.mydm.com/folder/public laravel
Wrote this
     RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_URI} (.+)/$
        RewriteRule ^ %1 [L,R=301]
    RewriteRule /assets www.mydm.com/folder/public [R=301,L]

does not help me
Any idea please guide thanks in advance
Please guide

A: Can you try with this
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteEngine On
    RewriteRule ^$ public/index.php [L]
    RewriteRule ^((?!public/).*)$ public/$1 [L,NC]

A: step 1:
Rename File server.php INTO index.php
step 2:
Update .htaccess
Options -MultiViews -Indexes
RewriteEngine On

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_URI} !(\.css|\.js|\.png|\.jpg|\.gif|robots\.txt)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !^/public/
RewriteRule ^(css|js|images)/(.*)$ public/$1/$2 [L,NC]


text:
Q: How does a hdmi monitor affect video playback? I have the following setup:

*

*quad core mini pc (rikomagic v5)

*custom android app using an android webview to show a website

*rather old non working dell monitor supporting hdmi

*working tv monitor surely supporting newer hdmi standards

The story:
The mini pc is connected to a monitor via HDMI. The weird thing is that my Dell PC monitor causes a youtube video loaded in the webview to playback as either complete unviewable with only green artefacts on the whole screen or red and blue colors exchanged depending on the user agent i choose for the webview.
Whereas a colleague of mine told me that he tried the mini pc at home on his tv monitor and the video worked like a charm (without toying around with user agent - its working out of the box).
So i have a setup which is working depending on the hdmi monitor connected. I never thought much about hdmi, but my impression was, that the youtube website reads the encoded video from the server (e.g. some mp4 with h264 codec or such) and uses html5 (a software component) to view the video. So in the end i thought the video goes to maybe some hardware decoder on the mini pc or is done by plain software decoder.
At this point i thought the decoded video is merged into the mini pc graphics card buffer or such, and the result is streamed via hdmi to the monitor. Which means i thought that hdmi just receives by specification (which i dont know anything about) some video stream in a hdmi specific encoded format.
The question:
So my question is if its possible to send e.g. h264 directly via hdmi to a monitor and it just works, depending on the monitor surely. But is this possible? Or to ask it differently, how can it be that, the software side doesnt seem to work on an rather old Dell monitor but hdmi supported, but suddenly works on a new tv monitor also just connected via hdmi without touching the software at all? I thought that the devices connected to some kind of hdmi monitor need to be able to understand the needed video codecs and not the monitor itself which i thought is just stupid to playback some specification based stream.

A: If you are playing something as a h264, it will go as a h264 via HDMI. HDMI is the currently only standardized lossless video file format.
The problem youre describing sounds like a RGB-format issue or YCbCr-format issue. These settings should be adjusted in the mini-pc side, from the GPU settings or from the browser (or other video/image software) settings. Your monitor might be old, so it might not support all the formats mentioned above - hence the color issues.
Id suggest heavily to check out the YCbCr and RGB -settings and try to adjust those for the better image quality on your current monitor.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Kafka and Topic with Multiple Messages Types (Avro) : Consumer(spring cloud spring fails due to the lack of class on classpath Topic contains two types of messages: PaymentStarted and PaymentCompleted.
There are 2 separated microservices with consumers.
So :Microservice_1, has consumer1 which should grab the PaymentStarted type;
Microservice_2, has consumer2 which should grab the PaymentCompleted type.
Additionally Microservice_1 contains only PaymentStarted on its jvm classpath and
Microservice_2 contains only PaymentCompleted on its jvm classpath.
Each service for handling different types of messages.
I am using spring-cloud-stream, so in my Microservice_1 the Consumer 1 has:
@StreamListener(target = PayBindings.EVENTS, condition = "headers['eventType']=='com.company.domain.PaymentStarted'")
    void onPaymentEvents(Message<PaymentStarted> message){
    }

analogically Microservice_2 the Consumer 2 has:
@StreamListener(target = PayBindings.EVENTS, condition = "headers['eventType']=='com.company.domain.PaymentCompleted'")
    void onPaymentEvents(Message<PaymentCompleted> message){
    }

Documentations says(https://cloud.spring.io/spring-cloud-static/spring-cloud-stream/3.0.0.M1/spring-cloud-stream.html#_using_streamlistener_annotation) that filtering goes before the serialization.
But in my case before condition filters them out, the default deserialiser(in my case io.confluent.kafka.serializers.KafkaAvroDeserializer) fails due to lack of PaymentCompleted on the classpath at microservice_1. Analogically with microservice_2 and PaymentStarted.
I don't want to mix the domains and keep PaymentStarted and PaymentCompleted pojos in Microservice_1 and Microservice_2.
I tried to solve that with my custom deserializer and it looks that it is doable with handling exception, but it is really tricky.
I am also confused that the doc I mentioned here above says that the filtering out goes before deserializing.
I appreciate your thoughts/comments.

A: You should really use a different topic for each type.
However, see Spring for Apache Kafka's ErrorHandlingDeserializer2.
Which will catch the exception and the listener container will route the error directly to the container's error handler.

I am also confused that the doc I mentioned here above says that the filtering out goes before deserializing.

That does not apply when you are using native deserialization, which is much lower down in the stack.

A: You should consume all messages and inside the function onPaymentEvents filter messages needed be each consumer. I suppose you have a single microservice that producer both type of messages.Also I replace the Avro with JSON.


text:
Q: Is there a decision procedure for analytic continuation? Let an analytic element be a power series associated with an open disc of the complex plane over which the series is convergent. W.l.o.g. assume the series is a Taylor expansion about the center of the disc. It is easy to show that analytic continuation is an equivalence relationship between analytic elements.
Given two analytic elements $(U, f)$ and $(V, g)$, how can we tell whether they are in the same class? Obviously if $f$ and $g$ are both polynomials of degrees at most $n$ we could see if the two are in the same class by evaluating at $n + 1$ points. On the other extreme: even comparing coefficients of two general series may take infinite steps. So let me bifurcate the question:

*

*Without concern for computability, what can we say in general on how to decide if two analytic elements are in the same class?

*What restrictions do we need to restore computability to this question?

A: !!Without regard for computability!!
One classic criterion is this.  $(U,f)$ analytically continues to $(V,g)$ iff there is a finite sequence $(U_k,f_k), k=0,\dots,n$ of analytic elements,
with $(U_0,f_0) = (U,f)$ and $(U_n,g_n) = (V,g)$ where, for $k=1,\dots,n$, we have $U_{k-1}\cap U_k \ne \varnothing$ and $f_{k-1}(z) = f_k(z)$ for all $z \in U_{k-1}\cap U_k$.

A simple example.
Take $(U,f)$ where $f(z) = \log z$ where $f(1) = 0$ and $U$ is the disk $|z-1|<1$.
Take $(V,g)$ where $g(z) = \log(-z)+C$ where $g(-1) = C$, $C$ a fixed constant, and $V$ is the disk $|z+1|<1$.
Question: Is $(U,f)$ continuable to $(V,g)$?
Answer: If and only if $C$ is an odd integer multiple of $i\pi$.


text:
Q: How do I manually inject a dependency in service through its constructor? I am trying to inject a service dependency in the constructor for another service.(see example code below). However, a NoSuchBeanDefinitionException is throws when I try to assign the api variable, even if the bean variable is set correctly.
It could also be worth to mention that this occur when I extend this service and initializing the child service.
My question is then, how could I proper inject the dependency service into my class dependent on the setting in my Config.groovy?
class MyService {
def api

public MyService() {
def beanString = ConfigurationHolder.config.api
def bean =  ApplicationHolder.application.getMainContext().getBean(GrailsNameUtils.getPropertyName(beanString))
this.api = bean
}
}

EDIT: To clarify my idea. I have two API:s, one XML and one JSON that serves the same data, but with different representations. However, I want to be able to set the api to use in the configuration file, eg a string with the api-name.
My idea is to have a common interface for the available apis (ApiInterface) and then when my service that uses the api is initialized, set an instance variable to the configured api.
In addition to this, I want to be able to have service specific settings i.e. a setting for each service that injects the api in the configuration file that sets which api to use.
e.g.
Config.groovy

firstService {
api = "xml"
}
secondService {
api = "json"
}

A: There isn't much info to go on. Is the bean defined in the config.api property definitely created by the time MyService is created? How are you guaranteeing that?
I think you could do some lazy initialization to get around it perhaps:
class MyService {
   static class ApiBeanHolder {
      static api = ApplicationHolder.application.getMainContext().getBean(GrailsNameUtils.getPropertyName(ConfigurationHolder.config.api))
   }

   def doSomeWork = {
      def bean = ApiBeanHolder.api
      bean.callBeanMethod
   }
}

Not tested, and don't know if it solves your particular problem.

A: I doubt you can get this to work without a lot of trouble since the instance is created by Spring when building the beans, so the other bean probably isn't available yet. You could look it up lazily on first request though:
class MyService {

   def grailsApplication

   private apiBean // use different name so 'api' resolves as property to getApi()

   def someMethod() {
      def foo = api.someMethodCall()
      ...
   }

   def someOtherMethod() {
      def bar = api.someOtherMethodCall()
      ...
   }

   private getApi() {
      if (apiBean == null) {
         String beanString = grailsApplication.configuration.api
         apiBean =  grailsApplication.mainContext.getBean(
               GrailsNameUtils.getPropertyName(beanString))
      }
      apiBean
   }
}


text:
Q: Как упростить конструкцию вывода из БД PHP? Есть конструкция вида:
     If($y['kabala'] == "Легкая")                     echo 'Хорошая.жпег';
     elseif ($y['kabala'] == "Тяжелая")               echo 'Плохая.жпег';
     elseif ($y['kabala'] == "Страшная")              echo 'Злая.жпег';

     elseif ($y['kabala'] == "ЛегкаяТяжелая")         echo 'Хорошая.жпег Плохая.жпег';

     elseif ($y['kabala'] == "ЛегкаяТяжелаяСтрашная") echo 'Злая.жпег Плохая.жпег Злая.жпег';

То есть, при совпадении: выводит вариант картинок ( одну, или несколько).
Данные в базе записаны в виде различных комбинаций(без пробела).
Таких комбинаций более 20.
Будет ли лучше, если в БД будет не одно поле "Kabala" а например отдельно: Kabala1, Kabala2 и т.д,  и Просто выводить при совпадении, иначе НИЧЕГО?
Какие еще более простые варианты можете предложить?
Спасибо!

A: Примерно так
Таблица справочник
CREATE TABLE kabalaDict(
    kabalaId BYTE,
    kabala VARCHAR,
    jpegName VARCHAR
)

Таблица связи какой-то вашей сущности с разными kabala'ми
CREATE TABLE kabala(
    entityId INT,
    kabalaId BYTE
)

В коде вычитываете справочник
$kabalaDictRaw = $dbLink
     ->query('SELECT kabalaId, jpegName FROM kabalaDict')
     ->fetchAll(\PDO::FETCH_ASSOC);
$kabalaDict = [];
foreach($kabalaDictRaw as $kabala){
    $kabalaDict[$kabala['kabalaId']] = $kabala['jpegName'];
}

Получаем данные по своей сущности и печатаем html
$currentKabala = $dbLink
    ->query('SELECT kabalaId FROM kabala')
    ->fetchAll(\PDO::FETCH_COLUMN, 1);
foreach($currentKabala as $kabala){
    echo ''.$kabalaDick[$kabala].'';
}


text:
Q: Plot bars in MATLAB I have a matrix(4,100) in MATLAB. Each one of its column are in such way that the 1st element
matrix(1,i) is the smaller and the 4th element matrix(4,i) is the bigger. Something like
    matrix(:,1) = - 0.3; 0,4; 0,4; 0,9

How can I do a bar graph were I can plot as a bar the distance between the two edges?
each column has to be represented by on bar in order to make 100 bars at the end.
Thanks

A: I'm not sure if this is what you want, but you can plot all bars in different colors, from the largest (last row of matrix) to the smallest (first row of matrix), so that the smaller ones get stacked over but let the larger ones to be seen:
matrix = [.1 .2 .3 .4 .5
          .2 .3 .5 .6 .7
          .4 .4 .8 .7 .8
          .5 .6 .9 .8 .9]; %// example data
hold on
colors = {'r','g','b','c'}; %// define colors
for n = size(matrix,1):-1:1 %// iterate over rows, from last to first
    bar(matrix(n,:), colors{n})
end

A: I assume by edges you mean the first and fourth element.
You can use:
diff = abs(matrix(1,:) - matrix(4,:)); // distance
bar(diff); // bar plot


text:
Q: Is it offensive to say "utilize workers"? Is it offensive to say "utilize someone"?

Automated factories perform better than those that utilize human
workers.

If it is, could you please give me a polite and positive alternative?

A: Workplaces treat people as resources, so utilize is appropriate here.
There is no actual, real polite way to directly say "machines are better than people", so the least offensive way to express this will be to not mention people at all.

For factories, a strong correlation exists between high performance and process automation utilization rate.


text: Q: Cylinder Set and It's Importance I am trying to learn the Cylinder set. From Wikipedia, I have learned its definition. But still, confused about how a set could create a Cylinder Shape? Why this set is called a Cylinder set. Most of the Books have given the definition. But they didn't mention why it has this kind of name and why we study this? Maybe this is trivial to everyone but I am new here and not understanding. Any kind of help would be appreciated.


text:
Q: Failing Media Check on Fedora Installation I am trying to install Fedora 23 and continually getting a media check fail at 85.7%.
I am using a 32gb ADATA USB stick and making the bootable with dd.
sudo dd if=/Users/me/Downloads/Fedora-Workstation-netinst-x86_64-23.iso of=/dev/disk3 bs=1m

Here is the result of that command:
413+0 records in
413+0 records out
433061888 bytes transferred in 22.151491 secs (19550011 bytes/sec)

I have also checked the SHA-256 hash and it is identical to the one on getfedora.com (where I downloaded the iso from).
I have also tried reformatting the USB drive as well (it is formatted as FAT).
Any ideas? Can I safely go ahead with the installation anyways?

A: It is not clear to me what this would be, but I would proceed with caution as ignoring a "bad read" might result in corrupted code on disk (it doesn't have to it as the check could be faulty).
First thing to do is trying a different USB port, especially downgrading to USB2 if you used a USB3 port before.
The other thing you can do if you have a machine with VirtualBox or other VM,  is to install from that USB to a VM and see what happens.
If you have the time to buy another stick, do so and weigh the cost of spending against potential future trouble. You can of course re-use the stick for other things if it turns out that gives the same error (indicating it is something in the target machine) ¹.
If another stick gives the same error, it might be some USB problem or a memory problem. In that case test the memory extensively (memcheck) even if you tested the USB on the target machine (from an older installation e.g.) as it could be that the installer media check hits some other memory with a bad spot that the "manual" check doesn't hit.
If memcheck doesn't show anything, I would try a more minimal network installation if available. It might just be that the USB interface goes bad after reading a certain amount of bytes.
If you decide to proceed, it might be that you get more errors (if the USB hardware has some errors), but AFAIK the checksums of the individual packages will still be checked during the installation as well independent of the "global" media check.

¹ Reusability is the primary reason I use a SD cards for installation, as I can also use those in my camera, phone and ebook readers. I did find however that my laptop did not boot from my multi-card USB3 reader (with hub, from which my desktop PC and servers boot fine). My laptop would only boot from my single card USB2 SD card reader


text:
Q: How to dump one database to another database using mysql? i have tried the following query but i gate with an error.
mysql> mysqldump test |mysql test1;
ERROR 1064 (42000): 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 'mysqldump test |mysql test1' at line 1
mysql> mysqldump test |mysql test1
-> ;
ERROR 1064 (42000): 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 'mysqldump test |mysql test1' at line 1
mysql>

A: You have to use these commands on command prompt.
Syntax :
mysqldump --opt -u [uname] -p[pass] [dbname] > [backupfile.sql]

i.e.
C:\>mysqldump --all-databases > dump.sql

If you want to create dump for any specific database then you have to mention that database name in the command.
C:\>mysqldump --databases yourdb > dump.sql

To import the database you have to use following command,
C:\>mysql -p -u[user] [database] < dump.sql


text:
Q: How to find a particular resource in Dwarf Fortress Is there any way to know where one should try digging to find a particular type of stone?
For example, I would sorely like some coal, but I'm just digging around more or less at random at the moment. Is there a smarter way to find coal seams and other similar things?

A: The wiki has a great guide to exploratory mining.
Otherwise, the map is generated at random, so the only way is to try.

A: Expanding on Arda's answer a little bit. It depends on what material you are looking for. Different materials appear in different forms. Assuming your are running 0.31.x coal will appear mostly in the form of veins, with large ovals of it every now and then. Your best shot is going to be looking laterally across a single Z level. Veins can be between 50-100 squares wide. so I'd advise digging single wide paths every 30 squares or so.
More or less it is random searching. But you can rule certain things out. stuff like coal will never be above an aquifer. it will never be found in sand of any kind, or most soils. you only should look in rocks. that might help narrow your search a little.
Good luck! Have Dwarven fun! xD

A: Or you could cheat and use Reveal. Spoils the fun, obviously.


text:
Q: how to open multiple windows I'd like to open a new Window whenever a button is clicked. As shown in the picture, I would like to open a new Popup Window when the Button is pressed.

However, I can currently open ONLY ONE window whenever I click the button.
Any idea?

class ViewController: NSViewController {

    lazy var myNewWindowController: newWindowController? =
    {
        let storyboard = NSStoryboard(name: "Main", bundle: nil)
        var newWC = storyboard.instantiateControllerWithIdentifier("new")  as? newWindowController
        return newWC
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    @IBAction func showWindow(sender: NSButton) {
        myNewWindowController?.showWindow(self)
    }
}

Just like Notes. Whenever I select an object, it will pop up another window for editing.


text:
Q: Having a separate project for satellite assembly for globalization for a solution with a Silverlight and ASP.NET application I'm trying to figure out a way to have a separate project for my two applications that are in the same solution. Can this be done? I can't find any examples and even tutorials for globalization with satellite assemblies are pretty bad. I want both applications to share a common base of resources. Does anyone know how I would go about this? Silverlight can't reference non silverlight projects so that is a hurdle already.

A: You can add separate project as Silverlight class library project and reference it from both Silverlight and ASP.NET project.
Visual Studio may throw warnings in this case, but this works fine.


text:
Q: Flyway ignoring sql files I'm using flyway plugin inside jenkins.
I have 3 sql files

*

*V1.0__1_C_OWNER.sql

*V1.1__C_USER_APLICACAO.SQL

*V1.2__C_DDL_DCL.SQL

Only the first is running by flyway
Jenkins output
11:34:23 Flyway Community Edition 5.1.4 by Boxfuse
11:34:23
11:34:24 Database: jdbc:oracle:thin:@(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = db1.domain)(PORT = 1523))(CONNECT_DATA = (SERVICE_NAME = develop))) (Oracle 12.1)
11:34:24 Successfully validated 1 migration (execution time 00:00.022s)
11:34:24 Current version of schema "U_FLYWAY": 1.0
11:34:24 Schema "U_FLYWAY" is up to date. No migration necessary.
11:34:24 Result is already [Sucess], not changing

Plugin config.

A: The default setting for sqlMigrationSuffixes is lowercase .sql..
The suffixes of files 2 & 3 are both uppercase: .SQL.
Either rename the files to use a lowercase suffix, or override the default by adding:
-sqlMigrationSuffixes=.sql,.SQL

to the Other command line arguments section in Jenkins.

A: *

*Never edit existing file. Always add a new file and Make sure newly added SQL file Version number is greater than the existing ones.

*If its a stored procedure make sure you include DROP PROCEDURE IF EXISTS [Procedure_name]; so this enables to delete the old procedure and update with new one.


text:
Q: Time series (xts) strptime; ONLY month and day I've been trying to do a time series on my dataframe, and I need to strip times from my csv. This is what I've got:
campbell <-read.csv("campbell.csv")

campbell$date = strptime(campbell$date, "%m/%d")
campbell.ts <- xts(campbell[,-1],order.by=campbell[,1])

First, what I'm trying to do is just get xts to strip the dates as "xx/xx" meaning just the month and day. I have no year for my data. When I try that second line of code and call upon the date column, it converts it to "2013-xx-xx." These months and days have no year associated with them, and I can't figure out how to get rid of the 2013. (The csv file I'm calling on has the dates in the format "9/30,10/1...etc.)
Secondly, once I try and make a time series (the third line), I am unsure what the "order.by" command is calling on. What am I indexing?
Any help??
Thanks!

A: For strptime, you need to provide the full date, i.e. day, month and year. In case, any of these is not provided, current ones are assumed from the system's time and appended to the incomplete date. So, if you want to retain your date format as you have read it, first make a copy of that and store in a temporary variable and then use strptime over campbell$date to convert into R readable date format. Since, year is not a concern to you, you need not bother about it even though it is automatically appended by strptime.
campbell <-read.csv("campbell.csv")
date <- campbell$date
campbell$date <- strptime(campbell$date, "%m/%d")

Secondly, what you are doing by 'the third line' (xts(campbell[,-1],order.by=campbell[,1])) command is that, your are telling to order all the data of campbell except the first column (campbell[,-1]) according to the index provided by the time data in the first column of campbell (campbell[,1]). So, it would only work given the date is in the first column.
After ordering the data according to time-series, you can replace back the campbell$date column with date to get back the date format you wanted (although here, first you have to order date also like shown below)
date <- xts(date, order.by=campbell[,1])  # assuming campbell$date is campbell[,1]
campbell.ts <- xts(campbell[,-1], order.by=campbell[,1])
campbell.ts <- cbind(date, campbell.ts)

A: format(as.Date(campbell$dat, "%m/%d/%Y"), "%m/%d")


text:
Q: Reading equations & formula from Word (Docx) to html I have a word/docx file which has equations as under formulas  ,
but my display is not normal, as follows:
(2×-1+3i2)3[(1+i)2]3
In the process of implementation, reference is Reading equations & formula from Word (Docx) to html and save database using java


text:
Q: How to print attributes in python. it is printing location. but i need to print ''25" It should print a number, not location.
a=25
class me:
    def it(a):
        print(a)
m=me()
m.it()

I should get 25, but I am getting - <__main__.me object at 0x7f98cb648b70>

A: This should be theclass, a have to be inside class, I def set/get methods
class me:

    def __init__(self, a):
        self.a = a

    def set_a(self, v):
        self.a = v

    def get_a(self):
        return self.a

m = me(5)

m.get_a()
m.set_a(12)
m.get_a()

Output
5
12

A: In your case it method is considered as instance method and for instance method 1st parameter is always an instance(self). So when you do print(a) it's printing location of an instance instead of printing value of variable a.
You can declare it method as static like below
a=25
class me:
    @staticmethod
    def it():
        print(a)
m=me()
m.it()

Or you can do
a=25
class me:
    def it(self):
        print(a)
m=me()
m.it()


text:
Q: Sum all the values in an array of factorials and print the result I want to write a java program which will calculate the first 20 factorial and store them in an array. Then go through the array and sum all of the items and print the result on the screen.
Here is my code but I think I did something wrong:
public class ArrayQuestion4 {

    public static void main(String[] args) {
        long array[]= new long[20];
        long temp=1;

        for ( int i=1; i<20; i++){
            temp = i*(i+1);
            temp = temp*(temp+1);
            array[i]=temp;
            System.out.println(array[i]);
        }

        for ( int i=1; i<20; i++){
            temp = array[i];
            temp = array[i]+(array[i+1]);
            temp = temp+(temp+1);
            System.out.println(temp);
        }
    }
}

The answer that comes out is not correct by the way.
I figure it out the correct code is this:
public class ArrayQuestion4 {

public static void main(String[] args) {
    long array[]= new long[20];
    array[0]=1;
    long temp=0;
    for ( int i=1; i<20; i++){
        array[i]=array[i-1]*(i+1);
        System.out.println(array[i-1]+"*"+(i+1)+" = "+array[i]);
    }

    for ( int i=1; i<20; i++){
       temp = temp + array[i-1] + array[i];
    }
    System.out.println(" ");
    System.out.println("Sum = "+temp);
}
}

A: As an illustration of where the code is probably not doing what you want it to be doing, look at what you get for (2)!
temp = i*(i+1);       //temp = 1*(1+1); which is 2
temp = temp*(temp+1); //temp = 2*(2+1); which is 6
array[i] = temp;      //array[1] = 6; - also note we skip ever assigning array[0]

You get 6 as an answer, which is incorrect.

A: The way you define factorial of n is
fact(n) = n * fact(n-1)
In the solution, factorial[n] represents factorial(n).
and temp is the current factorial being calculated.
public static void main(String[] args) {

    long factorial[] = new long[20];
    //Because Fact(1) = 1 * Fact(0), and fact(0) = 1.
    factorial[0] = 1;

    for (int n = 1; n < 20; n++) {
        // Loop needs to be <20 because i have defined the array size = 20.
        // <= would get an array out of bound exception. You can change the limits as you want.

        //calculating  the factorial based on formula:
        // Factorial(N) = n * Facorial(N-1);
        long factorialOfN = n*factorial[n-1];

        //storing back the value in the array for future use.
        factorial[n] = factorialOfN;

       //Printing it.
        System.out.println(factorialOfN);
    }
}

A: Long could not hold sum of all 20! results. There is a limit for 'long' in Java and it is
 public static final long MAX_VALUE = 0x7fffffffffffffffL;

 which is 9223372036854775807

Use 'BigInteger' to get correct answer. And also refer 'How (not) to write Factorial in Java'


text:
Q: How do I get count of a row in SQL I am a beginner regarding SQL queries so I hope that someone can help me with this.
I have a table that has 2 columns that are called MID and jachtID.
What I need is the count of how many of the same jachtIDS there are with different MIDS attached to them like this:
MID   jachtID
89    10
95    10
83    11

The result should look something like this:
MID   jachtID  count
89    10       2
95    10       2
83    11       1

And I need this for all of the rows
I have tried using
  SELECT count(DISTINCT jachtID) FROM table

But this just gives me 1 big number and not the result that I need.
Any help would be appreciated.

A: You can try the following query:
SELECT
    T.MID,
    T.jachtID,
    jT.total
FROM table T INNER JOIN
(
    SELECT
    jachtID,
    COUNT(*) total
    FROM table
    GROUP BY jachtID
)AS jT

ON T.jachtID = jT.jachtID

First get count of each jachtID by the following query:
 SELECT
   jachtID,
   COUNT(*) total
 FROM table
 GROUP BY jachtID

Then make an INNER JOIN between the main table and the above query and get the corresponding jatchtID count thereby.

A: You might be able to do this with some GROUP BY magic, but I'm not sure, since you want all the rows. Using a sub query will work, though.
SELECT
    a.MID,
    a.jachtID,
    (SELECT count(b.jachtID) FROM table AS b WHERE b.jachtID= a.jachtID) AS `count`
FROM table AS a


text:
Q: Laravel distinct not doing its job I have a simple query like this:
    if (Cache::has('films')) {
        $films = Cache::get('films', function () {
            return $films = Film::distinct('date')
                ->select('date')
                ->with('entities')
                ->groupBy('date')
                ->get();
        });
        $film = Cache::get('films', function () {
            return Film::select('date')->first();
        });
        dd($films);

I am using redis cache, however it looks like, distinct doesn't work for it. As if I do a query without the cache it seems to work fine. Anyone else had that issue? I get everything in the cache, while I should be getting every different date, so 7 results

A: As your code are working without cache closure. It means that you forgot to configure database info (Database username, password etc) in Redis server.


text:
Q: friend selector when using Feed Dialog I know I can use the Feed Dialog to post to a friend's wall by sending/using the "to" parameter... as well documented in http://developers.facebook.com/docs/reference/dialogs/feed/
I wonder if is it possible to say the Feed Dialog to show a friend selector widget/type ahead combo (as the Send Dialog does) or some thing to select the user whose he is looking... ?
Any idea.
Thanks in advance


text:
Q: What is different between compile and provided When I set <scope> to provided, my application didn't work. When It was compile, however, It works. Can you explain what different between both them.
This is tileConfig class for setting path.
@Configuration
public class TilesConfig {

    @Bean
    public ViewResolver viewResolver() {
        UrlBasedViewResolver viewResolver = new UrlBasedViewResolver();
        viewResolver.setViewClass(TilesView.class);
        return viewResolver;
    }

    @Bean
    public TilesConfigurer tilesConfigurer() {
        TilesConfigurer tilesConfigurer = new TilesConfigurer();
        tilesConfigurer.setDefinitions("/WEB-INF/tiles.xml");

        return tilesConfigurer;
}

and I added dependencies for Apache Tiles 3 and JSP. Because embedded server (tomcat) in Spring Boot do not support JPS.
Following pom.xml is working but when I add <scope> as provided in tomcat-embed-jasper. It does not work:
    <!-- Apache Tiles 3 -->
    <dependency>
        <groupId>org.apache.tiles</groupId>
        <artifactId>tiles-jsp</artifactId>
        <version>3.0.8</version>
    </dependency>

    <!-- JSP -->
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
    </dependency>

A: If you specify the scope as provided, you are saying that you expect JDK or the container to provide the dependency at runtime. This dependency is not present there so it cannot find it.

*

*compile is the default scope - these dependencies are available in all project classpaths

*provided - these dependencies are expected to be present int your environment

*runtime - not necessary for compilation but needs to be present for runtime

*test - required for tests

*system - like provided but you need to provide the jar file

A: provided means that you expect the container (Tomcat) to provide the dependency. Provided dependencies are used for compilation but are not packaged into your application.
compile dependencies are packaged into your applícation.


text:
Q: Disable GitLab Letsencrypt as option when installing for first time When I install GitLab Omnibus on Ubuntu-18.04 I am hitting a LetsEncrypt problem. The certs won't be issued.
This results in GitLab using a self-singed cert. I want to install my own certs so don't need Let's Encrypt at all.
I can disable it once GitLab is installed by adding this to /etc/gitlab/gitlab.rb
letsencrypt['enable'] = false

and then adding my certs in the correct place and then reconfigure.
Is it possible to pass a gitlab.rb file into the initial installation process with the above line so it doesn't even bother with LetsEncrypt on installation?
I am installing by:
sudo EXTERNAL_URL=<my url> apt-get install gitlab-ee

so I am looking for something like:
sudo EXTERNAL_URL=<my url> CONFIG=<path to local gitlab.rb> apt-get install gitlab-ee

EDIT: I believe the initial Lets Encrypt error issue is this one:
https://gitlab.com/gitlab-org/omnibus-gitlab/issues/4900

A: I took a cue from the docker installation instructions and passed the GITLAB_OMNIBUS_CONFIG variable like this:
sudo GITLAB_OMNIBUS_CONFIG="letsencrypt['enable'] = false" apt-get install gitlab-ce

Hope it helps.

A: Using the GITLAB_OMNIBUS_CONFIG did not work for me, at least not with yum on rhel 7.  For a workaround, I specified an http instead of https url:
sudo EXTERNAL_URL=http://<my-url> yum install -y gitlab-ee  #or apt-get

Then change to https, disable letsencrypt, and add the certs in the configuration after the installation and reconfigure.


text:
Q: How authenticate Google wave gadget viewer on Appengine? Imagine I want to create game "Rock-paper-scissors" for Google Waves.
I am thinking to implement it as a Wave Gadget.
The idea is simple: all participants send their decisions to my cloud
app (it is an Appengine Java Application), my server part collects
this data and does not share to anybody until all participants
complete their selection. After this the selection is shared to all
participants and the winner is determined.
I can use wave.getViewer().getId() to identify user on the server
during gadgets.io.makeRequest. I works perfectly.
But how can I, on the server side, make sure that the incoming request is
really from this specific wave user? (How can I approve that wave's
participant id is not hacked on the client side? Any wave container
signature allowing determine wave participant id is available?)
What are the best practices for google wave participant authentication
on my appengine side? Please provide examples if possible.
My actual gadget is more complicated but the problem is as described
above.

A: I would code against an imagined future solution that is baked directly into the Wave protocol or API and hope that nobody spoofs participant IDs. You could also contact the Wave team to make your need for the feature known and see if anyone else is looking for the same.
It looks like there is some OpenAuth integration already built-in for robots:
http://wave-robot-java-client.googlecode.com/svn/trunk/doc/index.html
Would you be able to implement a robot instead of a gadget? Or maybe use a robot for auth and have the gadget interface with your own auth tokens server-side?

A: As far as I can tell there is no "easy" way of doing this because all the communication with gadgets is directly between the client and the gadget, without Google interference for anything but the gadget's XML description.
The only way I can think off the top of my head is to have your users "log in" to the gadget's iframe with the accounts feature of Google App Engine. This would ensure they are indeed whoever they log in as.

A:
How can I approve that wave's participant id is not hacked on the client side?

How can a user hack his wave patricipant id?
I think there's no problem, wave.getViewer().getId() should be right.

A: I think you'd want to look into making a wave ROBOT instead of a GADGET. There is a difference.
Robots are wave-aware, gadgets are not.
Wave Robot API: http://code.google.com/apis/wave/extensions/robots/


text:
Q: log4cplus file cannot create directory administrative privileges I am trying to install Log4Cplus using Cmake.
First I downloaded log4cplus into a directory called 3rdparty
git clone https://github.com/log4cplus/log4cplus.git --recursive

Later in the common CMakeLists.txt I did the following
cmake_minimum_required (VERSION 3.4)
enable_testing()
include(USR_macros_and_functions.cmake)

project (unixpackages)
USR_init_project(unixpackages)
#other packages ...
add_subdirectory(3rdParty/log4cplus)
 #other packages ...
USR_add_build_repo_targets()

The problem is that when I try build I get the following error:
-- Installing: /home/compilation/UnixPackagesFareShopping/Output_API/Lib/libvalidator.so
-- Removed runtime path from "/home/compilation/UnixPackagesFareShopping/Output_API/Lib/libvalidator.so"
CMake Error at 3rdParty/log4cplus/src/cmake_install.cmake:36 (file):
  file cannot create directory: /usr/local/lib64/cmake/log4cplus.  Maybe need
  administrative privileges.
Call Stack (most recent call first):
  3rdParty/log4cplus/cmake_install.cmake:37 (include)
  cmake_install.cmake:48 (include)

I understand that I don't have the right to install it into /usr/local/lib64/cmake/ but the problem is that i don't know where I should change the path to point it to a directory where I have the rights to install it into.
I tried looking to see if i can find lib64 in all the configue and cmake files I only found this
./configure:  # 'ldconfig -N -X -v | grep ^/' on 64bit Fedora does not report /usr/lib64,
./configure:  # 'ldconfig -N -X -v | grep ^/' on 64bit Fedora does not report /usr/lib64,
./m4/libtool.m4:  # 'ldconfig -N -X -v | grep ^/' on 64bit Fedora does not report /usr/lib64,

I am new to cmake so sorry for the question

A: As commented, you can adjust the installation location using CMake, just use the CMAKE_INSTALL_PREFIX variable (see answers to this question). You can set this variable to somewhere you have access to, so the software is eventually installed in that location instead.
You can set the CMAKE_INSTALL_PREFIX variable on the command line when calling cmake, or in the CMake file itself before any calls to project, as you have done:
set(CMAKE_INSTALL_PREFIX ${PROJECT_SOURCE_DIR}/3rdParty/log4cplusclea)


text:
Q: grep: How to find Closing Bracket? One part of /usr/share/X11/xkb/symbols/us starts with xkb_symbols "dvorak" { and ends with the closing curly bracket }; which line-number I want to find.
partial alphanumeric_keys
xkb_symbols "dvorak" {

    name[Group1]= "English (Dvorak)";

    key <TLDE> { [       grave, asciitilde, dead_grave, dead_tilde      ] };

    key <AE01> { [          1,  exclam          ]       };
    key <AE02> { [          2,  at              ]       };
    key <AE03> { [          3,  numbersign      ]       };
    key <AE04> { [          4,  dollar          ]       };
    key <AE05> { [          5,  percent         ]       };
    key <AE06> { [          6,  asciicircum, dead_circumflex, dead_circumflex ] };
    key <AE07> { [          7,  ampersand       ]       };
    key <AE08> { [          8,  asterisk        ]       };
    key <AE09> { [          9,  parenleft,  dead_grave] };
    key <AE10> { [          0,  parenright      ]       };
    key <AE11> { [ bracketleft, braceleft       ]       };
    key <AE12> { [ bracketright, braceright,  dead_tilde] };

    key <AD01> { [  apostrophe, quotedbl, dead_acute, dead_diaeresis    ] };
    key <AD02> { [      comma,  less,   dead_cedilla, dead_caron        ] };
    key <AD03> { [      period, greater, dead_abovedot, periodcentered  ] };
    key <AD04> { [          p,  P               ]       };
    key <AD05> { [          y,  Y               ]       };
    key <AD06> { [          f,  F               ]       };
    key <AD07> { [          g,  G               ]       };
    key <AD08> { [          c,  C               ]       };
    key <AD09> { [          r,  R               ]       };
    key <AD10> { [          l,  L               ]       };
    key <AD11> { [      slash,  question        ]       };
    key <AD12> { [      equal,  plus            ]       };

    key <AC01> { [          a,  A, adiaeresis, Adiaeresis ]     };
    key <AC02> { [          o,  O               ]       };
    key <AC03> { [          e,  E               ]       };
    key <AC04> { [          u,  U               ]       };
    key <AC05> { [          i,  I               ]       };
    key <AC06> { [          d,  D               ]       };
    key <AC07> { [          h,  H               ]       };
    key <AC08> { [          t,  T               ]       };
    key <AC09> { [          n,  N               ]       };
    key <AC10> { [          s,  S               ]       };
    key <AC11> { [      minus,  underscore      ]       };

    key <AB01> { [   semicolon, colon, dead_ogonek, dead_doubleacute ] };
    key <AB02> { [          q,  Q               ]       };
    key <AB03> { [          j,  J               ]       };
    key <AB04> { [          k,  K               ]       };
    key <AB05> { [          x,  X               ]       };
    key <AB06> { [          b,  B               ]       };
    key <AB07> { [          m,  M               ]       };
    key <AB08> { [          w,  W               ]       };
    key <AB09> { [          v,  V               ]       };
    key <AB10> { [          z,  Z               ]       };

    key <BKSL> { [  backslash,  bar             ]       };
};

I can find the start of the environment which returns 192
grep -n 'xkb_symbols "dvorak"' /usr/share/X11/xkb/symbols/us | cut -d ":" -f1 > /tmp/lineNumberStartEnvironment

I do but blank output
# http://unix.stackexchange.com/a/147664/16920
grep -zPo 'pin\(ABC\) (\{([^{}]++|(?1))*\})' /usr/share/X11/xkb/symbols/us

Pseudocode

*

*Go first to the linenumber given by file /tmp/lineNumberStartEnvironment.

*Find the closing bracket of the thing located at the line of /tmp/lineNumberStartEnvironment.

*

*do this with the data content in the body but also with the complete file /usr/share/X11/xkb/symbols/us
Attempt for heredoc until next line [cas, Kusalananda]
I do where I do not know what I should put to the deliminator; -n returns blank too
sed -n -f - /usr/share/X11/xkb/symbols/us <<END_SED | cut -f1
/xkb_symbols "dvorak" {/,/^};/{
        /xkb_symbols "dvorak" {/=
        /^};/=
}
END_SED

but blank output.
Systems: Ubuntu 16.04
Grep: 2.25

A: This sed script prints the line number of the line matching /^};/ in the range of lines from /xkb_symbols "dvorak" {/ to the next /^};/ (which will be the same }; as the one we get the line number for):
/xkb_symbols "dvorak" {/,/^};/{
        /^};/=
}

If you need both start and end line numbers:
/xkb_symbols "dvorak" {/,/^};/{
        /xkb_symbols "dvorak" {/=
        /^};/=
}

$ sed -n -f tiny_script.sed /usr/share/X11/xkb/symbols/us
192
248

Alternatively:
$ sed -n -f - /usr/share/X11/xkb/symbols/us <<END_SED
/xkb_symbols "dvorak" {/,/^};/{
        /xkb_symbols "dvorak" {/=
        /^};/=
}
END_SED

EDIT: To get these two numbers in a variable, assuming you're using Bash:
pos=( $( sed -n -f - /usr/share/X11/xkb/symbols/us <<END_SED
        /xkb_symbols "dvorak" {/,/^};/{
                /xkb_symbols "dvorak" {/=
                /^};/=
        }
END_SED
) )

echo "start = " ${pos[0]}
echo "end   = " ${pos[1]}

Also, hi! Another Dvorak user!

A: #! /usr/bin/awk -f

/"dvorak"/ {dvorak++};

/{/ && dvorak {b++} ;

/}/ && dvorak {b--} ;

dvorak && b == 0 && NR > 1 {
    print NR;
    exit
}

$ ./find-dvorak.awk /usr/share/X11/xkb/symbols/us
248

This uses a counter (b) which gets incremented every time it sees an open-curly-bracket { and decremented whenever it sees a close-curly-bracket }.  It also uses a flag variable (dvorak) to know if it is inside the "dvorak" stanza or not.
When b == 0 and the line number is greater than one, print the line number.
BUGS: This does not account for commented-out brackets or those embedded in strings.
If you want the line numbers of the opening AND closing brackets:
#! /usr/bin/awk -f

/"dvorak"/ {dvorak++};

/{/ && dvorak {
    b++;
    if (!first++) {
        print NR
    }
} ;

/}/ && dvorak {b--} ;

dvorak && b == 0 && NR > 1 {
    print NR;
    exit
}

$ ./find-dvorak2.awk /usr/share/X11/xkb/symbols/us
192
248

Here's a version that allows you to search for any xkb_symbols stanza:
#! /usr/bin/awk -f

match($0,"xkb_symbols.*\""search"\"")  {found++};

/{/ && found {
    b++;
    if (!first++) {
        print NR
    }
} ;

/}/ && found {b--} ;

found && b == 0 && NR > 1 {
    print NR;
    exit
}

$ ./find-xkb_symbols.awk -v search=dvorak-intl /usr/share/X11/xkb/symbols/us
255
314


text:
Q: Jmeter: change default body data request filed with new value from json response I call a REST web service with post method with this request:
{
    "id":null,
    "scrollType":0,
}

In JMeter after creating Thread Group and add 10 to Loop Count, I added Http Request.I set protocol and other stuff and body data.
I added JSR223 PostProcessor and i'm using this groovy code to get last id from my response:
vars.put("id_BSH", new groovy.json.JsonSlurper().parse(prev.getResponseData()).get(9).id as String)

Now i want to add id_BSH into next request instead of "id":null, !
How can i do this?
For first request I want to be id = null and in other request i want to be id = ${id_BSH}?

A: Use id_BSH variable in your request:
"id":${id_BSH},

You just need to initialize value with null, you can defined it in Test Plan or in a User Defined Variables

User Defined Variables element lets you define an initial set of variables, just as in the Test Plan


text:
Q: How to inject property into Aspect logging class? I am having trouble injecting a property into LoggingAspect class. Imaging I have an AspectJ class:
@Aspect
public class LoggingAspect {
   private IBoc theBo;

   /** getter and setter **/
}

This is the BOC:
public interface IBoc {
}

public class BocImpl implements IBoc {
}

and the Spring configuration for BOC:
<beans ...>
   <aop:aspectj-autoproxy/>

   <bean id="theBoc" class="org.huahsin.BocImpl"/>
</beans>

In applicationContext.xml file, I configure the AspectJ in this way:
<beans...>
   <bean id="theLog" class="org.huahsin.LoggingAspect">
      <property name="theBo" ref="theBoc"/>
   </bean>
</beans>

How could I inject theBo in LoggingAspect class?

Update on 17 Oct 2012
I found some clue here. If I remove the <aop:aspectj-autoproxy>, the member variable theBo in class LoggingAspect will not be null. If I have that code, theBo will be null.

A: Normally Spring is responsible for both creating and configuring beans. AspectJ aspects, however, are created by the AspectJ runtime. You need Spring to configure the aspect that AspectJ has created. For the most common case of singleton aspects such as yours LoggingAspect aspect above, AspectJ defines an aspectOf() method that returns the aspect instance. You can tell Spring to use the aspectOf() method as a factory method for obtaining the aspect instance.
For e.g.:
  <beans>
      <bean name="loggingAspect"
        class="org.huahsin.LoggingAspect"
        factory-method="aspectOf">
        <property name="theBo" ref="theBoc"/>
      </bean>

      <bean id="theBoc" class="org.huahsin.BocImpl"/>
  </beans>

UPDATE:
Define factory method in your class:
@Aspect
public class LoggingAspect {

    private IBoc iBoc;

    private static LoggingAspect instance = new LoggingAspect();

    public static LoggingAspect aspectOf() {
        return instance;
    }

    public void setiBoc(IBoc iBoc) {
        this.iBoc = iBoc;
    }
}


text:
Q: convert APNs auth key to use with PyJWT Context
I am using pyjwt to generate a jwt to send push notifications from a python backend to APNs (Apple Push Notification service). My backend is running on a standard GAE (Google App Engine) instance, so I must use the legacy packages pycrypto and ecdsa instead of cryptography within pyjwt (docs).
Problem
My auth_key.p8 (which I downloaded from Apple Developer) is formatted -----BEGIN PRIVATE KEY-----, but the ecdsa package expects it to be formatted -----BEGIN EC PRIVATE KEY-----. Hence I get the following traceback:
  File "app/venv/lib/python3.7/site-packages/jwt/api_jwt.py", line 65, in encode
    json_payload, key, algorithm, headers, json_encoder
  File "app/venv/lib/python3.7/site-packages/jwt/api_jws.py", line 113, in encode
    key = alg_obj.prepare_key(key)
  File "app/venv/lib/python3.7/site-packages/jwt/contrib/algorithms/py_ecdsa.py", line 44, in prepare_key
    key = ecdsa.SigningKey.from_pem(key)
  File "app/venv/lib/python3.7/site-packages/ecdsa/keys.py", line 189, in from_pem
    privkey_pem = string[string.index(b("-----BEGIN EC PRIVATE KEY-----")):]
ValueError: subsection not found

It seems that my auth_key is in a format that ecdsa does not accept, but I don't know what to do to fix this. Am I supposed to convert this auth_key into a different format?
Thank you for your help.

A: For me this was caused by having a newline at the end of the key. After removing the newline the error went away.


text:
Q: Multiple xcode projects found, please specify one When I try to run the pod init command at mac terminal. It says

[!] Multiple Xcode projects found, please specify one

A: Sometimes, even when you are in the project folder that contains only one Xcode project, it will still raise that same error. However strange, it can be quickly remedied by denoting the intended Xcode project as so:
pod init <fullname of Xcode project here>

e.g.:
pod init myApp.xcodeproj

A: You need to create your pod file in the same directory in which your project
please follow below steps like
/Users/directory/Desktop/projectFolder/.

In project directory, you have to create your pod file by pod init command
 then use pod install to install pods
then open project.xcworkspace.
Please refer this link also, if my answer not helpful to you
Issues with adding a pod file to my Xcode project


text:
Q: What is the difference between UDP hole punching and UPnP? So Skype and other p2p type applications often work by what is called hole punching (see simple guide here) to get two clients connected to each other that are both behind firewalls which block incoming connections.
uPnP is also used to get around the user manually having to forward ports. How exactly is it different to the kind of hole punching described above? I assume it must operate differently as most routers have the setting to turn it on/off, whereas I see no way one could stop the above type of UDP hole punching (aside blocking outgoing connections and incoming established/related).
Second, if say Skype/bittorrent can set up and direct connection between A-B with hole punching, does that mean it doesn't need upnp enable on the router?

A: For UPnP to work, the router in question must support it.  A device with UPnP basically asks the UPnP enabled router to open a port and forward traffic to it.  No party external to the LAN should be able to do this unless the LAN's router is horribly misconfigured or wide open to the world at large.
Hole punching takes advantage of UDP's connectionless nature:

*

*A sends UDP packet on a port+IP to B

*A's NAT remembers this, and since A originated the packet, considers A to have started a conversation (even though technically with UDP there is no way to know that for sure) and then allows incoming traffic on that port+IP

*An intermediate party (in the article you provided, that's the Skype "switching" server) is still needed since B's firewall will block the incoming traffic, but now the switching server can MITM and send a response through A's port+IP, which should reach A because NAT is forwarding due to A originating traffic.

Hole punching basically lets a party external to the LAN reach something listening behind a NAT with the help of an intermediary.


text:
Q: G is a finite group, show that $a=b^{-1}$ Let $(G,\cdot)$ be a finite group with $ord(G)=n,\;$ $n\ge3\,$ and $a, b \in G\; \backslash \{e\}$ so that $a^k\neq \; b^p\;\; \forall k, p \in \{1, 2,\ldots,\left[\frac{n}{2}\right]\}$. Show that $a=b^{-1}$.
If $a \in G$ it follows that $\exists \;k=ord(a)$ so that $k\,|\,n$ . Since $k$ is a divisor of $n$, we have $k \in \{2,\ldots,\left[\frac{n}{2}\right],n\}$. Now if we pick $p=\left[\frac{n}{2}\right]$, with $k \in \{2,\ldots,\left[\frac{n}{2}\right]\}$, we have $e=a^k\neq b^{\left[\frac{n}{2}\right]}$ which follows that $ord(b)=n$. It seems like I'm stuck here. Is my approach correct, or do you have another idea?

A: Let $r=ord(a)$ and $s=ord(b)$.
If $r<n$, then $r\le [n/2]$, and the hypothesis implies that $s > [n/2]$. But this means that $s=n$ and $G$ is cyclic generated by $b$.
Write $a=b^k$ with $k>[n/2]$. Let $u=n-k$. Then $a=b^{n-u}$, $a^2=b^{n-2u}$, $a^i = b^{n-iu}$.
Take $i\ge [n/(2u)]$ and $j=n-iu$.
If $u \ge 2$, then $a^i=b^j$, with $i,j \in \{1, 2,\ldots,\left[\frac{n}{2}\right]\}$, which cannot happen.
Therefore, $u=1$ and $a=b^{n-1}=b^{-1}$.


text:
Q: Cannot find ActionMappings or ActionFormBeans collection? hello guy's
i am new in struts while running a program in struss i got an error like this....
org.apache.jasper.JasperException: javax.servlet.ServletException: javax.servlet.jsp.JspException: Cannot find ActionMappings or ActionFormBeans collection
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:531)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:439)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:389)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:332)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

root cause

javax.servlet.ServletException: javax.servlet.jsp.JspException: Cannot find ActionMappings or ActionFormBeans collection
    org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:901)
    org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:830)
    org.apache.jsp.insert_jsp._jspService(insert_jsp.java:83)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:68)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:416)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:389)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:332)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

root cause

javax.servlet.jsp.JspException: Cannot find ActionMappings or ActionFormBeans collection
    org.apache.struts.taglib.html.FormTag.lookup(FormTag.java:798)
    org.apache.struts.taglib.html.FormTag.doStartTag(FormTag.java:506)
    org.apache.jsp.insert_jsp._jspx_meth_html_005fform_005f0(insert_jsp.java:136)
    org.apache.jsp.insert_jsp._jspx_meth_html_005fhtml_005f0(insert_jsp.java:106)
    org.apache.jsp.insert_jsp._jspService(insert_jsp.java:73)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:68)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:416)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:389)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:332)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

mycode are like this......
InsertModel.java
package com.cac.struts;
import java.sql.*;
public class InsertModel
{
    public boolean insert(String name,String branch,int regd)
    {
        boolean b=false;
        try
        {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            Connection con=DriverManager.getConnection("jdbc:odbc:mohit","system","rock");
            PreparedStatement ps=con.prepareStatement("insert into emp values(?,?,?)");
            ps.setString(1,name);
            ps.setString(2,branch);
            ps.setInt(3,regd);
            int k=ps.executeUpdate();
            if(k>0)
                b=true;
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return b;
    }
}

InsertForm.java
package com.cac.struts;
import org.apache.struts.action.ActionForm;
public class InsertForm extends ActionForm
{
    private int regd;
    private String name;
    private String branch;
    public void setRegd(int r)
    {
        regd=r;
    }
    public int getRegd()
    {
        return regd;
    }
    public void setName(String name)
    {
        this.name=name;
    }
    public String getName()
    {
        return name;
    }
    public void setBranch(String branch)
    {
        this.branch=branch;
    }
    public String getBranch()
    {
        return branch;
    }
}

InsertAction.java
package com.cac.struts;
import org.apache.struts.action.*;
import javax.servlet.http.*;
public class InsertAction extends Action
{
    public ActionForward execute(ActionMapping am,ActionForm af,HttpServletRequest hreq,HttpServletResponse hres) throws Exception
    {
        String key="failure";
        InsertForm iif=(InsertForm)af;
        int regd=iif.getRegd();
        String name=iif.getName();
        String branch=iif.getBranch();
        InsertModel im=new InsertModel();
        boolean b=im.insert(name,branch,regd);
        if(b)
        {
            key="success";
        }
        ActionForward af1=am.findForward(key);
        return af1;
    }
}

web.xml
<web-app>
    <servlet>
        <servlet-name>one</servlet-name>
        <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>one</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
</web-app>

struts-config.html
<struts-config>
    <form-beans>
        <form-bean name="insertForm" type="com.cac.struts.InsertForm">
    </form-beans>
    <action-mappings>
        <action path="/insert" type="com.cac.struts.InsertAction" name="insertForm">
            <forward name="success" path="/success.jsp">
            <forward name="failure" path="/failure.jsp">
        </action>
    </action-mappings>
</struts-config>

insert.jsp
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>

Student Application

            regd

            name

            branch

        insert

in addition i am also using all the jar files in lib and a struts-html.tld.
Please...Please help me...!!

A: < action path="/insert" type="com.cac.struts.InsertAction" name="insertForm" scope="request" validate="false" input="/insert.jsp">

A: You are probably missing one of these jars:
commons-digester.jar
commons-beanutils.jar
struts.jar
Add them to the project should solve your problem


text:
Q: Can't connect to MySQL database - PHP Quick question here, I'm new to web hosting and I'm just having a muck around to see what's what. I've created the following PHP document and hosted it on my free 000webhost domain:
<?php

$mysql_host = "mysqlXX.000webhost.com";
$mysql_database = "***********_people";
$mysql_user = "*************_admin";
$mysql_password = "******************";

// Create connection
$con=mysqli_connect($mysql_host,$mysql_database,$mysql_user,$mysql_password);

// Check connection
if (mysqli_connect_errno($con))
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
?>

I have set up (hopefully correctly) a small table in my database with 3 fields:

*

*ID - No Null, auto-increment, integer, primary

*First Name - VarChar, Length 20

*Last Name - VarChar, Length 20

And entered data for each one.
When I open the file from my control panel, I get the following error:

Warning: mysqli_connect() [function.mysqli-connect]: (28000/1045):
  Access denied for user 'a4935911_people'@'10.1.1.45' (using password:
  YES) in /home/a4935911/public_html/MySQL+PHP.php on line 9

AND

Failed to connect to MySQL: Access denied for user
  'a4935911_people'@'10.1.1.45' (using password: YES)

Any ideas, anyone?

A: Wrong argument sequence here:
$con=mysqli_connect($mysql_host,$mysql_database,$mysql_user,$mysql_password);

Look at the message: Access denied for user 'a4935911_people'@'10.1.1.45' (using password: YES) where a4935911_people is not a user, it is your database's name as set above $mysql_database = "***********_people";.
Use: Host, user, password, dbname as described in the Documentation.
Solution:
$con=mysqli_connect($mysql_host, $mysql_user, $mysql_password, $mysql_database);

A: argument sequence is following order.
$host ="localhost" // change to your host
$username ="root"     // change to your mysql user name by default root
$pass =" "       //add password if any
mysql_connect($host,$username,$pass) //don't change the sequence
mysql_select("test") // create the test database in mysql

A: Two possible reasons:

*

*Wrong username/password - check it carefully.

*You can't connect remotely, connections are allowed only via localhost. Check your hosting website for such information. If it's not allowed, you can do nothing.

A: In Addition to the possible conclusions that @ElonThan provides...
it's also possible that your username lacks the proper privileges to the database you are connecting to.

A: You need to set up mysql to allow remote connection for a particular user in the MySQL database server i.e. mysqlXX.000webhost.com here . The default syntax is:
grant <permission> on <database> to <user>@<location> identified by <password>
So here you have to use(as you have specified the parameters)-
grant all on ***********_people.* to '*************_admin'@'10.1.1.45' identified by '******************'
So for your case run the following command-
grant all on database_name.* to 'username'@'your_ipaddress' identified by 'password'
Run this command in MySQL command prompt.
This will allow username to connect from your IP using that password and give all permissions on all tables in the specified database.

*

*To allow any user to connect from any IP address and use all the tables in any database use the following syntax-

grant all on *.* to '%'@'%' identified by 'password'
And finally you have to use the following command-
FLUSH PRIVILEGES;
To reload all privileges.

A: For 000webhost.com (Free Hosting Service ) you should Test your code online by uploading it to 000webhost.com server.
That will solve your problem for sure.


text:
Q: How does react handle - in css selector I have a css block
.button-set {
/* css styles */
}

How do I use this on an JSX element using the className attribute

A: If you are using an external css file like app.css then just import it in the component (App.js) and try this.
for example -
App.css -
.button-set{

background-color:black;
 color:white;
}

App.js
import './App.css';
function App() {
return (

 return (

    <button className="button-set">CLick me</button>

 );
}
export default App;

A: You can try this
const YourFunction = () =>{
    return(

            Your content here

    )
}

A: What I didn't knew was that when importing a CSS module element like this returns a key value pair
import styles from "../styles/Home.module.css";

So I could very easily do this

...


text:
Q: How do I check if an email field is 1) empty and 2) contains a specific email address with jquery? Not sure why my alerts aren't firing, but what I eventually would like to do is enable the submit button when this field is not empty and contains a specific email address, such as "@something.com"
First things first, I'm simply trying to check if the field is empty on the change event.
HTML
<input type="email" id="email" placeholder="lauren@something.com">

JS
$("#email").change(function(){
    if (this.is(':empty')) {
        alert('empty');
    } else {
        alert('not empty');
    }
});

A: $("#email").change(function(){
    var domain = this.value.indexOf('@') != -1? this.value.split('@').pop() : '';

    if (this.value.trim() == '') {
        alert('empty');
    }else if (this.value.trim() == 'bill@gates.com') {
        alert('Holy crap, it\'s Bill Gates');
    }else if (domain == 'gates.com') {
        alert('It\'s a radiator hose salesman ?');
    }else{
        alert('someone else');
    }
});


text:
Q: reCaptcha v2 & Invisible Captcha on Cordova-based apps Has anyone ever tried to integrate reCaptcha v2 or the invisible captcha on a Cordova-based app?
I have configured everything correctly. Once I launch my page as a Web Site, everything works great and I see the reCaptcha v2 working. However, when I run the page as an app on Android or iOS I see the error which says:

ERROR for site owner:
  Invalid domain for site key

I've also unchecked the option in Google Console to prevent the domain check, but it only affected the web site and not the app.
Does anyone have any experience integrating reCaptcha v2 or invisilbe Captcha in a cordova-based app?

A: After deep investigation seems that the issue is related to the fact that the Cordova-based apps run over the file:/// protocol which seems to cause the issue.
Actually we've faced the issue only on Android devices, ios devices seem to work fine.
We've finally fixed the issue creating a web page on our web site and putting there the invisible recaptcha library then we've linked the page inside an iFrame in the app.
This tricks let us to run the recaptcha library over the http protocol which has fixed the issue.

A: Try to install cordova-plugin-ionic-webview@latest using the below command
cordova plugin add cordova-plugin-ionic-webview@latest


text:
Q: How do I filter a ManyToMany field? I have a model Called Parent. In the model I have a ManyToManyfield called partner_types. which is based on the model Partner_type. What I want to do is filter the model to check if someone is a parent or not.
I tried filter sets but the problem is my partner_type is defined in the admin so I am not able to filter it.
class PartnerType(models.Model):

    name = models.CharField(blank=False,
                        help_text="Name of the role or function", max_length=64,
                        verbose_name="Partner Type", )

class Partner(TimeStampedModel, StatusModel):
    name = models.CharField(blank=True, max_length=100, verbose_name='Account Name', )
    partner_types = models.ManyToManyField(PartnerType)

so my current partner types created in the admin are :
Broker,
Service,
Distributor,
Customer,
Parent
Here is what I have tried.
a = Partner.objects.filter(partner_types= Partner)

but it does not work.
I have also tried.
a = Partner.objects.filter(partner_types = 4) for the numerical value of the many to many field object.

A: There are multiple ways to do this, depending on how exactly your view's information that "parent" is the PartnerType you're interested in is represented.
One way is to filter on the related CharField:
a = Partner.objects.filter(parter_types__name="parent")

If you have actually loaded the PartnerType instance, you can provide that directly:
parent = ParterTypes.objects.get(name="parent") # or whatever
...
a = Partner.objects.filter(parter_types=parent)

Your id-based query Partner.objects.filter(partner_types=4) is also valid, so if that didn't get the results you expect you might need do some data checking. But it's generally a bad idea to rely on hardcoded PKs as opposed to content-based filters.

A: This should work.
a=Partner.objects.filter(partnertype__name="Parent")


text:
Q: Dual ISPs - Load balancing We currently have 1 ISP and are adding a second. I need to load balance this into our current network so it shares the bandwidth between our 2 ISPs. We have a total of about 10 external IP addresses that will need to be able to route to the correct servers on our network.
Our network structure is an ASA5505 (and identical failover system) with unlimited users/security+ licenses.
From here it just routes to the switches/patch panel and network.
I know there are hardware solutions that you can plug in. Like sonic wall does this.
But there's also an exterior BGP/Multi homing option that can be used.
We are a company with 40+ employees and reliability to the internet is key for us as we are a software company.

A: For using multiple outgoing connections, all you need is something to route the traffic appropriately. There are a number of free linux/BSD router distros that will work fine, such as m0n0wall.
However, to share the same set of public IPs on multiple incoming connections, ISP participation is required.
This is indeed referred to as multi-homing, and requires the use of BGP, an assigned AS number, and ownership of an IP space.
This is not often feasible for such small IP spaces; you may be able to get a redundant link from one ISP, in which case they will take care of the multi-homing, but that doesn't protect you against that ISP going down...
An alternative is to host your critical services in a datacenter, which will be redundant in all respects (power, cooling, hardware, connectivity) - but you will have to compare costs.


text:
Q: Generating PDF, error with IE and HTTPS I am streaming a PDF to the browser in ASP.NET 2.0. This works in all browsers over HTTP and all browsers except IE over HTTPS. As far as I know, this used to work (over the past 5 years or so) in all versions of IE, but our clients have only recently started to report issues. I suspect the Do not save encrypted pages to disk security option used to be disabled by default and at some point became enabled by default (Internet Options -> Advanced -> Security). Turning this option off helps, as a work-around, but is not viable as a long term solution.
The error message I am receiving is:

Internet Explorer cannot download OutputReport.aspx from www.sitename.com.
Internet Explorer was not able to open this Internet site. The requested site is either unavailable or cannot be found. Please try again later.

The tool used to create the PDF is ActiveReports from DataDynamics. Once the PDF is created, here is the code to send it down:
Response.ClearContent()
Response.ClearHeaders()
Response.AddHeader("cache-control", "max-age=1")
Response.ContentType = "application/pdf"
Response.AddHeader("content-disposition", "attachment; filename=statement.pdf")
Response.AddHeader("content-length", mem_stream.Length.ToString)
Response.BinaryWrite(mem_stream.ToArray())
Response.Flush()
Response.End()

Note: If I don't explicitly specify cache-control then .NET sends no-cache on my behalf, so I have tried setting cache-control to: private or public or maxage=#, but none of those seem to work.
Here is the twist: when I run Fiddler to inspect the response headers, everything works fine. The headers that I receive are:

HTTP/1.1 200 OK
  Cache-Control: max-age=1
  Date: Wed, 29 Jul 2009 17:57:58 GMT
  Content-Type: application/pdf
  Server: Microsoft-IIS/6.0
  MicrosoftOfficeWebServer: 5.0_Pub
  X-Powered-By: ASP.NET
  X-AspNet-Version: 2.0.50727
  content-disposition: attachment; filename=statement.pdf
  Content-Encoding: gzip
  Vary: Accept-Encoding
  Transfer-Encoding: chunked

As soon as I turn Fiddler off and try again, it fails again. One other thing that I noticed is that when Fiddler is running I get a There is a problem with this website's security certificate warning message, and I have to click Continue to this website (not recommended) to get through. When Fiddler is off, I do not encounter this security warning and it fails right away.
I am curious what is happening between Fiddler and the browser so that it works when Fiddler is running but breaks when it's not, but more importantly, does anyone have any ideas how I could change my code so streaming PDFs to IE will work without making changes to the client machine?
Update: The Fiddler issues are resolved, thank you very much EricLaw, so now it behaves consistently (broken, with or without Fiddler running).
Based on Google searching, there seem to be plenty of reports of this same issue all over the web, each with it's own specific combination of response headers that seem to fix the problem for their individual cases. I've tried many of these suggestions, including adding an ETag, LastModified date, removing the Vary header (using Fiddler) and dozens of combinations of the Cache-Control and/or Pragma headers. I tried "Content-Transfer-Encoding: binary" as well as "application/force-download" for the ContentType. Nothing has helped so far. There are a few Microsoft KB articles, all of which indicate that Cache-Control: no-cache is the culprit. Any other ideas?
Update: By the way, for completeness, this same issue occurs with Excel and Word outputs as well.
Update: No progress has been made. I emailed the .SAZ file from Fiddler to EricLaw and he was able to reproduce the problem when debugging IE, but there are no solutions yet. Bounty is going to expire...

A: Your Cache-Control header is incorrect. It should be Cache-Control: max-age=1 with the dash in the middle. Try fixing that first to see if it makes a difference.
Typically, I would say that the most likely culprit is your Vary header, as such headers often cause problems with caching in IE: http://blogs.msdn.com/ieinternals/archive/2009/06/17/9769915.aspx.  You might want to try adding a ETAG to the response headers.
Fiddler should have no impact on cacheability (unless you've written rules), and it sounds like you're saying that it does, which suggests that perhaps there's a timing problem of some sort.
>Do not save encrypted pages to disk security option used to be disabled by default
This option is still disabled by default (in IE6, 7, and 8), although IT Administrators can turn it on via Group Policy, and some major companies do so.
Incidentally, the reason you see the certificate error while running Fiddler is that you haven't elected to trust the Fiddler root certificate; see http://www.fiddler2.com/fiddler/help/httpsdecryption.asp for more on this topic.

A: After two weeks on a wild goose chase, I have not been able to find any combination of code changes that will allow this method of streaming PDF, Excel or Word documents when the 'Do not save encrypted pages to disk' option is turned on.
Microsoft has said this behavior is by design in a number of KB articles and private emails. It appears that when the 'Do not save encrypted pages to disk' option is turned on that IE is behaving correctly and doing what it is told to do.  This post is the best resource I have found so far that explains why this setting would be enabled and the Pros and Cons of enabling it:

"The 'Do not save encrypted pages to disk' comes into play when dealing with SSL (HTTPS) connections. Just like a web server can send done information about how to cache a file one can basically set Internet Explorer up to not save files to the cache during an SSL (HTTPS) connection regardless if the web server advises you can.
What is the upside for turning this feature on, security is the number one reason why the feature is turned on. Pages are not stored in the Temporary Internet Files cache.
What is the downside? Slow performance, since nothing is saved to the cache even that 1 byte gif image used a dozen times on the page must be fetched from the webserver each time. To make matters worse some user actions may fail such as downloaded files will be deleted and an error presented or opening PDF documents will fail to name a few scenarios."

The best solution we can find at this point is to communicate to our clients and users that alternatives exist to using this setting:

"Use 'Empty Temporary Internet Files folder when browser is closed'. Each time the browser closes all files will be purged from the cache assuming there is not a lock on a file from another instance of the browser or some external application.
A lot of consideration needs to be given before utilizing 'Do not save encrypted pages to disk'. Sounds like a great security feature and it is but the results of using this feature may cause your help desk calls to go up for download failures or slow performance."

A: I found that this seemed to work for me:
Dim browser As System.Web.HttpBrowserCapabilities = Request.Browser
If (browser.Browser = "IE") Then
  Response.AppendHeader("cache-control", "private") ' ie only
Else
  Response.AppendHeader("cache-control", "no-cache") ' all others (FF/Chrome tested)
End If

A: I had a similar problem with PDF files I wanted to stream.  Even with Response.ClearHeaders() I saw Pragma and Cache-Control headers added at runtime. The solution was to clear the headers in IIS (Right-click -> Properties on the page loading the PDF, then "Http headers" tab).

A: We have faced a similar problem long time back - what we did was we (this is Java EE). In the web application config we add
<mime-mapping>
    <extension>PDF</extension>
    <mime-type>application/octet-stream</mime-type>
</mime-mapping>

This will make any pdf coming from your web application to be downloaded instead of the browser trying to render.
EDIT: looks like you are streaming it. In that case you will use a mime-type as application/octet-stream in your code and not in the config. So here instead of
Response.ContentType = "application/pdf"

you will use
Response.ContentType = "application/octet-stream"

A: SOLVED:  This is an IE problem, not from aplication...
fix it with this:   http://support.microsoft.com/kb/323308
It work perfect for me, after try for a long time.
ATT: Mr.Dark

A: What version of IE? I recall that Microsoft released a Hotfix for IE6 for this issue. Hope that is of some use?

A: I read of your Cache-control goose chase, but I'll share mine, that met my needs, in case it helps.

A: try to disable gzip compression.

A: Adding it here hoping that someone might find this useful instead going through the links.
Here is my code
    byte[] bytes = // get byte array from DB

    Response.Clear();
    Response.ClearContent();
    Response.ClearHeaders();
    Response.Buffer = true;

    // Prevent this page from being cached.
    //  NOTE: we cannot use the CacheControl property, or set the PRAGMA header value due to a flaw re: PDF/SSL/IE
    Response.Expires = -1;

    Response.ContentType = "application/pdf";
    // Specify the number of bytes to be sent
    Response.AppendHeader("content-length", bytes.Length.ToString());

    Response.BinaryWrite(bytes);

            // Wrap Up
    Response.Flush();
    Response.Close();
    Response.End();

A: Like the OP I was scratching my head for days trying to get this to work, but I did it in the end so I thought I'd share my 'combination' of headers:
            if (System.Web.HttpContext.Current.Request.Browser.Browser == "InternetExplorer"
                && System.Web.HttpContext.Current.Request.Browser.Version == "8.0")
            {
                System.Web.HttpContext.Current.Response.Clear();
                System.Web.HttpContext.Current.Response.ClearContent();
                System.Web.HttpContext.Current.Response.ClearHeaders();
                System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream";

                System.Web.HttpContext.Current.Response.AppendHeader("Pragma", "public");
                System.Web.HttpContext.Current.Response.AppendHeader("Cache-Control", "private, max-age=60");
                System.Web.HttpContext.Current.Response.AppendHeader("Content-Transfer-Encoding", "binary");

                System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + document.Filename);
                System.Web.HttpContext.Current.Response.AddHeader("content-length", document.Data.LongLength.ToString());

                System.Web.HttpContext.Current.Response.BinaryWrite(document.Data);
            }

Hope that saves someone somewhere some pain!

A: I was running into a similar issue with attempting to stream a PDF over SSL and put this inside an iframe or object. I was finding that my aspx page would keep redirecting to the non-secure version of the URL, and the browser would block it.
I found switching from an ASPX page to a ASHX handler fixed my redirection problem.


text:
Q: Android ViewPager fakeDragBy I'm attempting to make my ViewPager bounce a few times on first load to indicate to the user that what they are looking at is a horizontally scrollable view. I've tried to use fakeDragBy but my app will crash when I attempt to do this. What is the recommended way to use fakeDragBy properly to achieve what I am seeking?
Here is the code I am running inside my Activity:
@Override
public void onStart(){
    super.onStart();
    mViewPager.setCurrentItem(0);

    mViewPager.beginFakeDrag();
    mViewPager.fakeDragBy(25);
    mViewPager.endFakeDrag();
}

Here is the stack trace:
09-24 12:21:49.702  28243-28243/com.company E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.company, PID: 28243
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.company/com.company.onboarding.OnboardingActivity}: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
     Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
            at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
            at java.util.ArrayList.get(ArrayList.java:308)
            at android.support.v4.view.ViewPager.fakeDragBy(ViewPager.java:2431)
            at com.company.onboarding.OnboardingActivity.onStart(OnboardingActivity.java:100)
            at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1220)
            at android.app.Activity.performStart(Activity.java:5949)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2261)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

A: If you pay close attention to the error log:
Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
            at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
            at java.util.ArrayList.get(ArrayList.java:308)
            at android.support.v4.view.ViewPager.fakeDragBy(ViewPager.java:2431)

Your view pager has zero items at the time of the fakeDragBy. That means that the Adapter is not giving your view pager any data, so the ViewPager is not ready to do anything.
We'd need to see how/when you are initializing your ViewPager. Without those bits of information, it's impossible to tell why you're getting an Out of Bounds exception.
Please add more code.
The issue could be else where, it's hard to tell, since you seem to be able to setCurrentItem(0) without problems.
As a side note, the Google's recommendation of wiggling the view pager upon startup to help discovery, mentions that this should only be done once. Since you're adding code to onStart() I guess you intend to do it every time you start the Activity, careful with that ;)


text:
Q: run .exe file and parsing of its output.txt file I want to call an .exe file in my code (vb.net), then i have to execute it. After execution i want to call my output file in that same code to parse the file and collect the data for plotting the graphs.
I have done only first part and I could not be able to call an output file . as I have to manually call it .
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Process.Start("C:\rs40dk\RunRelap.exe")
    End Sub
End Class

its output is .txt file. I am thinking to apply check first if Process.Start = ok then proceeds further pick the file but I couldn't be able to put a generic name

A: While the process is running
Do nothing
End while
Now pull data.
https://msdn.microsoft.com/en-us/library/53ezey2s(v=vs.110).aspx
I believe that link should have the method to do the status. I'm in a car or I'd find the correct line instead of a Pseudocode while loop.


text:
Q: flash as3 drag and drop with inertia I want to imitate the iPhone scroll behavior in a Flash app I am developing. The idea is to enable drag-drop with a certain amount of inertia/deceleration (you know, when you drop something while your cursor is still moving and the thing would continue moving for a moment and then stop).
I am using the TweenMax library for my animations.
Any ideas will be appreciated.
Thanks

A: When I recently created something like this, I simply listened for MOUSE_DOWN and MOUSE_UP, and whenever I reckoned that the mouse button was pressed (i.e. in-between those two events, also respecting Event.MOUSE_LEAVE) I would flag it as such, e.g. using a _mouseIsDown class-scope variable.
Then I would have an ENTER_FRAME event handler, or a timer, that would behave differently depending on whether the button was pressed or not.
When the mouse button is down, the ENTER_FRAME handler simply moves the target object to the new mouse position. It will also subtract the current mouse position from the previous one, to get a speed vector. Finally, it would log the current mouse position to allow the above to happen again the next frame.
If the mouse button is released however, it will not just move the target object using a 1:1 mapping to the mouse position, but rather, move it according to the speed vector. It would also decrease the length of the speed vector each tick, until it's close enough to zero for the entire system to be put into idle state to save up resources.
A simplified solution would look like this, ignoring the setting and resetting of the mouseIsDown flag.
private function _handleEnterFrame(ev : Event) : void
{
  if (_mouseIsDown) {
    // Set speed here, but don't use it while mouse is pressed
    _speed.x = stage.mouseX - _prev_mouse_pos.x;
    _speed.y = stage.mouseY - _prev_mouse_pos.y;

    // Instead, just move target object accordingly
    _targetObject.x = stage.mouseX;
    _targetObject.y = stage.mouseY;
  }
  else {
    // Mouse is released, meaning that it has been tossed, so move
    // object according to speed vector, and decrease speed.
    _targetObject.x += _speed.x;
    _targetObject.y += _speed.y;

    _speed.x *= 0.8;
    _speed.y *= 0.8;

    // Negligible speed, so stop the processing to save resources
    if (_speed.length < 0.05) {
      this.removeEventListener(Event.ENTER_FRAME, _handleEnterFrame);
    }
  }

  _prev_mouse_pos.x = stage.mouseX;
  _prev_mouse_pos.y = stage.mouseY;
}

Obviously, you will need to start listening for the ENTER_FRAME event whenever the mouse is pressed. Also, you need to have the appropriate class-scope variables _prev_mouse_pos and _speed, both instances of flash.geom.Point, as well as the _targetObject which is whatever display object you wish to affect by dragging.


text:
Q: How do I get my app added to the OneLogin App Catalog? I created a OneLogin dev account and have done the work to integrate my site (a dashboard for Signal Sciences, a security company) with OneLogin via SAML.  I'd now like to add my site to the official OneLogin App Catalog.  Does anyone have any pointers on getting that done?
I've been here:
https://developers.onelogin.com/saml/app-catalog
and filled out the form, but got no confirmation and no response and have no idea how long I might need to wait for a response (if any).
I'd love any advice from someone who's been through this process.

A: Thank you for your patience and for checking in. We did indeed receive your connector request--I believe the creation process is underway. Please let me know if you have not heard from a support rep as of yet.
When you initially submitted the request form, you should have received a confirmation email---but that did not happen. I apologize. We are investigating and will fix that issue.


text:
Q: Grails Set Up Environment Variables I have followed the documentation with regards to setting Grails up on Windows, but for some reason it is not working. Any help would be much appreciated

A: Check out this solution:
shortly: just run once grails create-app myApp


text:
Q: Checkbox not being checked when running function I have a checkbox that when it is clicked it submits the form to the server to store the detail. All works fine except that after the form is submitted I update a div to say submitted but the checkbox isn't ticked. The page isn't refreshed of course and upon page refresh it is ticked.
I thought I might be able to check the box myself as I'm using jQuery but I have a lot of these checkboxes each with a dynamic name so I'm not sure how I would call them. I thought something like:
$('input[name=("favourite" + id)]').attr('checked', true);

might work but no luck. If I don't call the function on the checkbox being ticked the checkbox behaves normally.
Thanks for anything that could help.

A: You should break your string in order to introduce the value of the id variable into your selector, you can do it like this:
$('input[name="favourite' + id + '"]').attr('checked', true);

A: Try doing
$('input[name=("favourite" + id)]').checked = true;

instead.
The issue may be that setting the attribute is not automatically interpreted by your browser as changing the DOM property. This is a bit confusing, but on browsers like Firefox, etc, HTML attributes and DOM properties are stored separately (most are named the same, but there are exceptions - such as the class attribute being represented by the className property).
Changing properties affects the behavior of the Elements, while attributes do not always have the same effect - on some browsers they are only parsed during initial render.


text:
Q: Boot and grub problem I have dell inspiron 14 3493. There was preinstall windows in it. later, i dual booted with ubuntu and after that I installed Ubuntu alone.
after that i have been getting that "minimal bash editing..." grub screen for most of the time. I poweroff device and gain boot 1 or 2 time to get rid of that grub screen . Also , lately, dell logo appears two time before booting. I need help.
I tried boot-repair tool but no improvement.


text:
Q: OneSignal push notifications don't link correctly to my GoNative app I am answering my own question here in case anyone runs into a similar problem.
I recently have been working with GoNative to spin up a hybrid native application for DoneDone, a task management and shared inbox tool.
I am also using OneSignal's push notification integration with GoNative to handle native push notifications to the user. In addition, I am sending out push notification messages from the server-side (C#/.NET in my case, but the server-side platform is irrelevant here).
I have already set up the necessary files to get universal links to open up in the native app rather than the browser (e.g. the apple-app-association-file). I am getting push notifications created and sent correctly.
However, I cannot get the push notification to link to a specific page on the application via the server-side API.
In OneSignal's Create Notification API doc, it seems like you would send across either the url, web_url, or app_url parameter in your JSON request. However, none of these work correctly if you are using GoNative's push notification integration with OneSignal.
For instance, if you use the url or app_url parameter, you get a secondary browser pop-up inside your native app, instead of a load from just your native app.

A: You need to set your own url value in the "Additional Data" property of your push notification. GoNative has documentation on this if you are creating push notifications from within OneSignal's web platform, but not specific guidance if you are programmatically creating push notifications via their API.
To do this via JSON, you add a targetUrl value to the data property.
{
   "app_id":"3baaa656-8832-4733-a88b-b83aba2598a7",
   "include_player_ids":[
      "3baaa656-8832-4733-a88b-b83aba2598a7",
      "3baaa656-8832-4733-a88b-b83aba2598a7"
   ],
   "headings":{
      "en":"DoneDone Project"
   },
   "subtitle":{
      "en":"#123: This is a bug!"
   },
   "contents":{
      "en":"Ka Wai Cheung created the task."
   },
   "data":{
      "targetUrl":"[LINK TO THE WEB APP]"
   }
}

Once you specify the targetUrl, it works. I hope this saves someone time one day!


text:
Q: google map api and socket.io I am getting lat and lng to my browser from a gps unit via socket.io like so:
        socket.on("web_latitude", function(msg) {
            document.getElementById("latitude").innerHTML = msg
        })

        socket.on("web_longitude", function(msg) {
            document.getElementById("longitude").innerHTML = msg
        })

I have a google map like so:

    function initialize() {

      var mapOptions = {
        center: { lat: -46.85, lng: 150.644},
        marker: {lat: client_lat, lng:client_lng},
        zoom: 8
      };

      var map = new google.maps.Map(document.getElementById('map-canvas'),
          mapOptions);
      }

      google.maps.event.addDomListener(window, 'load', initialize);

How in the world do I inject lat and lng into the map? I have tried combining functions however google maps seems to break if I add anything special to it which rules out scoping variables. Any help is appreciated!

A: *

*make the map global

*Check and see if both the latitude and longitude div's have useful values

*Use those values to set the map position

var map;
function initialize() {

  var mapOptions = {
    center: { lat: -46.85, lng: 150.644},
    marker: {lat: client_lat, lng:client_lng},
    zoom: 8
  };

  map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);
}
socket.on("web_latitude", function (msg) {
  document.getElementById("latitude").innerHTML = msg;
  setMap();
});

socket.on("web_longitude", function (msg) {
  document.getElementById("longitude").innerHTML = msg;
  setMap();
});

function setMap() {
  if ((document.getElementById('latitude') != '') && (document.getElementById('longitude') != '')) {
    map.setCenter(new google.maps.LatLng(
      parseFloat(document.getElementById('latitude').innerHTML),
      parseFloat(document.getElementById('longitude').innerHTML)));
  }
}
google.maps.event.addDomListener(window, 'load', initialize);