text:
Q: Correct use of Java 8 supplier consumer I'm still strugling with Suppliers and Consumers for Java 8, I have this:
final Set<String> roles = new HashSet<>();
user.getRoleGroups().forEach(rg -> rg.getRoles().forEach(r -> roles.add(r.getName())));

To get a Set from role names that are inside a list of Roles inside a list of RoleGroups.
Pretty sure I could use something in one line with .stream().map() and RoleGroup::getRoles and Role::getName to get this Set. But I don't know how.

A: You are pretty close! To use a Stream instead, do something like this:
final Set<String> roles = user.getRoleGroups().stream()
   .flatMap(g -> g.getRoles().stream())
   .map(Role::getName)
   .collect(Collectors.toSet());

Use of flatMap() is the only tricky part here. The flatMap() operation transforms an element to a Stream, which is concatenated with the Streams from the other elements.


text:
Q: rails nested resources handle edit path as id I have the following routes
resources :users, path: '/' do
   resources :posts, path: '/'
end

the problem is that the inner route override the outer route for user's edit path.
http://localhost/user/edit refer to posts#show instead users#edit
EDIT
Singular resource is not the solution, I want to access the user via his ID.
lets say I have user with id "Jo" and post with id "My-First-Post", then the corresponding route should be http://localhost/Jo/My-First-Post. that's work just fine with my current solution.
the problem is that when I access /Jo/edit I get exception that there is no post with id "edit" while I want this route to refer to Jo's edit page (users#edit)

A: What are you trying to achieve? It sort of looks like you want a singular resource. If that's the case, you can just do:
routes.rb
resource :user

So just make the word resource and user singular. Then you'll get singular routes, like user/edit.
See the Rails guide for more information: http://guides.rubyonrails.org/routing.html#singular-resources

redpajama_set_name: RedPajamaStackExchange


text:
Q: Datastudio: Blended Data: Datetime can't be aggregated I have two tables case and party. Both of them are from BigQuery. In the case table, there is a date field in the DATETIME type in BigQuery. I want to plot a chart to show the number of cases per month. It works perfectly when I only use the case table.

However, when I blend the case table with the party table, the aggregation doesn't apply on the date field anymore.

This is how I join the tables.

How do make the aggregation of date & time fields in blends work as normal?
Update
I have tried to create a custom field with TODATE(date, 'RFC_3339', '%Y-%m-%d'), but the aggregation is still not applied to the custom field.
minimal example

*

*Create a.csv in local.

a_id,date
1,2022-05-25T00:00:00
2,2022-05-25T00:00:00
3,2022-06-01T00:00:00
4,2022-06-02T00:00:00

*Create b.csv in local.

a_id,b_id
1,1
1,2
2,3
3,4
4,5
4,6

*Upload a.csv and b.csv into a Data Studio report.

*Blend a.csv and b.csv with inner joining on a_id field. I removed "Record Count" from metrics in both tables and added all fields as dimensions.

*Add a "Table" type chart using the blend created in the previous step.

*Put date field as the only one dimension and select "Year Month" as the type.

*Put a_id field as the only one metrics and select "Count Distinct" as aggregation.

actual result

date (Year Month)
a_id

May 2022
2

Jun 2022
1

Jun 2022
1

expected result

date (Year Month)
a_id

May 2022
2

Jun 2022
2

example report
Here

A: This is a bug, and it was already reported in Google's DataStudio IssueTracker.

*

*https://issuetracker.google.com/issues/179280180
You probably want to star the issue (Google prioritize issues by the number of affected users).
Also, in the same thread, the reporting user suggests to use the above formula as a workaround.
YearMonthAsDate = DATE(YEAR(date_tran),MONTH(date_tran),1)

It worth a try.

A: You are changing the Date dimension in the table but in order to aggregate it on a monthly basis but joins the rows on a date base.
The solution is to change the Dimension to Month year inside the blend settings, you can do this just the same way you change a field type inside a table.


text:
Q: How to access the review board site from other system via browser? I have set-up all prerequisites and all the installation required for local  reviewboard along with rb-site, server is apache httpd with mod_wsi. Can any one help me on how to access the review bpoard which I have installed locally from different systems via web browser.
Below are the steps detailed:
yum -y install zlib zlib-devel
yum -y install openssl-devel
yum -y install memcached
yum -y install python-devel
yum -y install python-setuptools
yum -y install patch
easy_install mysql-python
yum -y install git-core
easy_install ReviewBoard
rb-site install /var/www/ReviewBoard
While Installing rb-site :
 Domain name localhost:80
 Root Path : reviews
And other configurations are default.
All steps are executed successfully.
But I do not know how can I access the review board over browser.
Please help me?


text:
Q: ffmpeg video not working in JWPlayer I have created a video from mixing an audio and a video. By using
 ffmpeg -i video.mp4 -i a.mp3  -vcodec copy -acodec copy -map 0.0 -map 1.0 -shortest output.mp4

Its working fine in VLC player but no sound in JWPlayer. Its also buffering the whole video before starting the video.
How to resolve this issue .
Here is output of ffmpeg command.
 FFmpeg version 0.6.5, Copyright (c) 2000-2010 the FFmpeg developers
 built on Jan 29 2012 23:55:02 with gcc 4.1.2 20080704 (Red Hat 4.1.2-51)
 configuration: --prefix=/usr --libdir=/usr/lib64 --shlibdir=/usr/lib64 --    mandir=/usr/share/man --incdir=/usr/include --disable-avisynth --extra-cflags='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -fPIC' --enable-avfilter --enable-avfilter-lavf --enable-  libdirac --enable-libfaac --enable-libfaad --enable-libfaadbin --enable-libgsm --enable- libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libx264 -- enable-gpl --enable-nonfree --enable-postproc --enable-pthreads --enable-shared -- enable-swscale --enable-vdpau --enable-version3 --enable-x11grab
 libavutil     50.15. 1 / 50.15. 1
 libavcodec    52.72. 2 / 52.72. 2
 libavformat   52.64. 2 / 52.64. 2
 libavdevice   52. 2. 0 / 52. 2. 0
 libavfilter    1.19. 0 /  1.19. 0
 libswscale     0.11. 0 /  0.11. 0
 libpostproc   51. 2. 0 / 51. 2. 0
 Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'video.mp4':
 Metadata:
   major_brand     : mp42
   minor_version   : 0
   compatible_brands: isommp42
 Duration: 00:01:17.48, start: 0.000000, bitrate: 614 kb/s
   Stream #0.0(und): Video: h264, yuv420p, 640x360, 515 kb/s, 29.97 fps, 29.97 tbr, 60k tbn, 59.94 tbc
   Stream #0.1(und): Audio: aac, 44100 Hz, stereo, s16, 96 kb/s
 [mp3 @ 0x1258e440]max_analyze_duration reached
 [mp3 @ 0x1258e440]Estimating duration from bitrate, this may be inaccurate
 Input #1, mp3, from 'a.mp3':
  Metadata:
   TSSE            : Lavf52.64.2
  Duration: 00:06:53.52, start: 0.000000, bitrate: 64 kb/s
    Stream #1.0: Audio: mp3, 44100 Hz, 2 channels, s16, 64 kb/s
 File 'output.mp4' already exists. Overwrite ? [y/N] y
 Output #0, mp4, to 'output.mp4':
  Metadata:
    encoder         : Lavf52.64.2
    Stream #0.0(und): Video: libx264, yuv420p, 640x360, q=2-31, 515 kb/s, 60k tbn, 29.97 tbc
    Stream #0.1: Audio: libmp3lame, 44100 Hz, 2 channels, 64 kb/s
  Stream mapping:
    Stream #0.0 -> #0.0
    Stream #1.0 -> #0.1
  Press [q] to stop encoding
  frame= 2322 fps=  0 q=-1.0 Lsize=    5526kB time=77.48 bitrate= 584.3kbits/s
  video:4878kB audio:605kB global headers:0kB muxing overhead 0.777738%


text:
Q: Replacing the Last Ten Blanks With Tabs I have a file in which each line contains data separated by a single space.  The total number of spaces varies from line to line but is always greater than 10.  I wish to replace only the last ten spaces with tabs.  Any spaces that exist before the last ten are to be left untouched.
How can I do that using vi?

A: You can make use of regular expressions for this purpose.
Regex can be:
<Ten Spaces>$

or
[ ]{10}$

$ indicates search from the end.


text:
Q: Receiving no translated text from an https request to translate.google.com Now I tried to make like a translator through Roblox Studio using Https service by sending a request to the translate.google.com link the thing is that anything I get in return does not give me the translated text.
I put what I received in a google doc and tried to find it by pressing ctrl + f to try to find it but no luck the only thing I could find is that text that was supposed to be translated. Here is the code in case you want to try it for yourself but I do warn you that running this might make Roblox unresponsive for a while since it is a lot of info they gave back.
I don't know if I am doing something wrong or not someone please help! I just want it to give me what 'Hello world' would be in french, there are also no error messages.
local http = game:GetService("HttpService")

local Message = "Hello world"

http:UrlEncode(Message) -- 'Hello world' -> 'Hello%20world'

local response = http:RequestAsync(
    {
        Url = "https://translate.google.com/?sl=en&tl=fr&text=" .. Message .. "!&op=translate";
        Method = "GET"
    }
    )

if response.Success then
    print(response.StatusMessage)
    print(response.StatusCode)
    print(response.Body)
    --print(response.Headers)
else
    print("The request failed: ", response.StatusCode, response.StatusMessage)
end

A: When visiting on your browser (for example) the url https://translate.google.com/?sl=en&tl=fr&text=Hello%20World!&op=translate, the translation you see is fetched using Javascript code executed by the browser after loading the page.
The browser retrieves the html body of the page (like you did in your code) and then executes the javascript in the html body which retrieves the translation and updates the page.
Unless you use a browser driver like Selenium I don't see how you can do what you want in a simple way.
Plus, I'm sure that Google has some protection against automatic bots, so after too many request your program will probably will be blocked by ReCaptcha.
The correct way to translate the text is to use the Google Cloud Translate API which I think is free up to 500k requests per month. There is also Azure Translator from Microsoft which also has a free tier.

A: Your issue is likely in how you are URL Encoding the string.
http:UrlEncode(Message)

HttpService.UrlEncode returns the encoded string as a new value. It doesn't mutate the existing value. So you just need to store the result of the function call.
Message = http:UrlEncode(Message)

EDIT : Just as @Mohamed AMAZIRH pointed out, hitting this URL will only return HTML.


text:
Q: How to create Sub Domains using Cake PHP? I am building a site ,which requires a unique sub-domain for each profile. The technology which I am using is Cake PHP + MongoDB. I need to know the feasibility of the same. Whether I can create a Physical DNS or I can simply route the Profile page of the User , by the help of Routes Class in Cake PHP. Please suggest what will be better and easy way to implement along with feasibility of the same.
Thanks in Advance.

A: If you are using CakePHP for each of the websites, you do not need to worry about multiple subdomain creation for each site, you can simply create a wildcard DNS record. This removes a lot of the hassle from the server and DNS administration.
Wild-Card DNS Record(Wiki)
With the wildcard DNS record in place, you can then use HTTP_HOST, or the CakePHP way, $request->host() to determine the hostname (subdomain) being used to access your system. You can then load the correct profile details in the beforeFilter() method of AppController and move forward from there.
I do something simila:
class User extends AppModel
{
     public $belongsTo = array(
          'Profile'
     );

     public function findByProfileHostname($hostname) {
         return $this->find('first', array('conditions' => array(
             'Profile.hostname' => $hostname
         ));
     }
};

class AppController extends Controller
{
    public function beforeFilter () {
        $this->ActiveUser = $this->User->findByProfileHostname($this->request->host());
        if (!$this->ActiveUser) {
            throw new InvalidArgumentsException(__('%s is not active here', $this->request->host()));
        }
    }
}

*disclaimer: Above code has been typed from memory and may not work directly through copy/paste.
Hope this helps.

A: It's easily doable! A little bit of scripting and hosting configuration is all thats needed:
Let's assume, ignoring the subdomains for now, that you can access the user profiles at yoursite.com/users/view/id - standard convention.
All we then need to do is map username.yoursite.com to the correct yoursite.com/users/view/id - and this should happen any time a user signs up. So in the users/add - we need to write a script that can access your servers 'users' / 'sites-available' (or equivalent) - and either append to the end of the already existing 'yoursite.com' configuration, or make new 'username.yoursite.com' every time a user signs up.
Now the annoying bit - on the server your app will need permission to read/write to the servers configuration folder, plus server also need to be restarted for a new conf file - my sysadmin skills only go so far and you'll have to find out; by running a bash script or something else on how to get the server to read the new conf files without getting it to restart.
Also make sure the server files update if the username is changed or the user is deleted.

A: In short:
Auto-create subdomains using Cake PHP? Sorry, but that won't work.
Longer:
You won't get where you want to go using the Routes Class in Cake PHP. "Routes" allow configuration of paths, but it won't create paths or subdomains. As said: you're talking two different things: Cake PHP's Routes Class = PHP based rewrites, a subdomain = DNS configuration of the server.
Before you even waste time thinking about DNS, be aware that new DNS entries may take up to 24 hours to kick in. Before a new (sub)domain can be used, it has to be propagated. Are you sure that's what you want? It could mean (thinking about user registration) that new users could register but not use or even reach their "new" subdomain, because it simply isn't known to several DNS servers yet.
But... you could try to make wildcard subdomains work if the waiting time is no problem to you. But that heavily depends on your web-hosting provider and what they allow you to do. In case of doubt, contact them (after you've learned what wildcard DNS does and if you really want to use it).
Similar questions and answers can be found here:

*

*how do i create personal sub domain programmatically with php

*How would you create sub-domains with DNS automatically?
But I can only give you a good tip: think twice before starting to go down this road. It might get too bumpy for you and your users and then you'll have wasted valuable time you could've invested better in working out alternate options. Besides, what's wrong with a decent directory structure? You know, search-engines are known to love decent directory structures more than subdomain-setups as directory structures are more logic when all the data is related to a single website. Even if that website is something big... like Facebook or Twitter. ;)

A: First of all.
The creation of subdomains has nothing to do with Cake, Mongo or PHP. This is a DNS thing and you need to create correct DNS entries. Ex:
subdomain1 IN CNAME domain.com.
subdomain1 IN A 123.2.33.45.

As @e-sushi was pointing out this takes time. You can automatize this process, but not with PHP but with root access (you can actually do it in PHP with shell_exec but that is another story). Depending on your hosting this can be actually quite complicated and unreliable in terms of time.
Imagine that following scenario. A user is created, but he will be able to access is webpage  somewhere between 6 and 24 hours after. You will have to create some temporary path for the time being and a full scenario with what happens with the data and how the links are pointing... etc. Too complicated.
The routing mechanisms from Cake is a helper mechanism that can transform a request and solve it to another path using an internal logic. So it can take something like:
yourwebsite.com/user/1

And transform it to:
joe.yourwebsite.com

But this process is independent of the creation and maintenance of the subdomains.


text:
Q: A question about the space $c_0$ Suppose $x,x_n\in c_0$ with norm 1 such that $\|x_n+x\|\to 2$. Let $f\in c_0^*$ with $\|f\|=1$ such that $f(x)=1$. I want to check if $$d(x_n,A)\to 0, \text{ where }A=\{y\in c_0: \|y\|=1, f(y)=1\}$$
I tried to find a counterexample to disprove it, but could not do so. Neither can I prove it. Any suggestion please!

A: Counterexample:
\begin{align*}
x &= (1, 1, 0, 0, \ldots) \\
x_n &= \begin{cases}(1, 0, 0, 0, \ldots) & \text{if } n \text{ is even} \\ (0, 1, 0, 0, \ldots) & \text{if } n \text{ is odd}.\end{cases}
\end{align*}
Note that $\|x + x_n\| = 2$.
Further, let $f(y)$ be the first coordinate of $y \in c_0$. Note that $f \in c_0^*$. It corresponds to the sequence $(1, 0, 0, \ldots)$ in $\ell^1$, and has norm $1$. We also have $f(x) = 1$.
However, $f(x + x_n)$ oscillates between $1$ and $2$. In particular, if $n$ is odd, then $f(x_n) = 0$, and if $y \in A$, then $\|y - x_n\|$ is at least $1$. Thus, $d(x_n, A)$ does not tend to $0$.


text:
Q: Exim sync emails from AWS SES I would like to build a new email server.
I am familiar with Exim+Dovecot solution. But it's a bit complicated to set up.
So I would like to try AWS SES because it's much simpler to start and has nice integration with mainstream mail servers.
The problem I am having is how do I recieve emails. It seems SES will put all the received mails in a S3 bucket. But I want to receive mails on my phone, ipad, laptop, so I still need an imap server. Is it possible to have a script to sync the s3 bucket to my exim server so that exim can forward the email to dovecot?


text: Q: How do I get all links of a Wikipedia page, not including the ones in the navbox at the bottom? I want to get all the links on the Wikipedia page Charles Maurice de Talleyrand-Périgord, but without all the links within the navboxes at the bottom of the page. I've been using the links prop (e.g. https://en.wikipedia.org/w/api.php?origin=*&action=query&prop=links&titles=Charles%20Maurice%20de%20Talleyrand-Périgord&pllimit=max), but it includes the navboxes, and I haven't found another property that pertains to my concern. Is there a way to exclude them?


text:
Q: MySQL Foreign Key syntax error CREATE TABLE DEPARTMENT ( Dname VARCHAR(15) NOT NULL,
Dnumber INT NOT NULL,
Mgr_ssn CHAR(9) NOT NULL,
 Mgr_start_Date DATE,
PRIMARY KEY(Dnumber),
UNIQUE(Dname),
FOREIGN KEY(Mgr_ssn) REFERENCES EMPLOYEE (Ssn)
ON DELETE SET DEFAULT ON UPDATE CASCADE);

I am a beginner in MySQL. The command above gives me this:

Cannot add foreign key constraint

I have tried SHOW ENGINE INNODB STATUS;
I checked EMPLOYEE.Ssn's data type.
Please help.
Edit: My EMPLOYEE table
| employee | CREATE TABLE `employee` (
  `Fname` varchar(10) DEFAULT NULL,
  `Minit` char(1) DEFAULT NULL,
  `Lname` varchar(10) DEFAULT NULL,
  `Ssn` char(9) NOT NULL,
  `Bdate` date DEFAULT NULL,
  `Address` varchar(40) DEFAULT NULL,
  `Sex` char(1) DEFAULT NULL,
  `Salary` int(11) DEFAULT NULL,
  `Super_ssn` char(9) DEFAULT NULL,
  `Dno` int(11) DEFAULT NULL,
  PRIMARY KEY (`Ssn`),
  KEY `Super_ssn` (`Super_ssn`),
  CONSTRAINT `employee_ibfk_1` FOREIGN KEY (`Super_ssn`) REFERENCES `EMPLOYEE` (`Ssn`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |

A: According to the MySQL docs at https://dev.mysql.com/doc/refman/5.7/en/create-table-foreign-keys.html , you can't use SET DEFAULT with INNODB :
SET DEFAULT: This action is recognized by the MySQL parser, but both InnoDB and NDB reject table definitions containing ON DELETE SET DEFAULT or ON UPDATE SET DEFAULT clauses


text:
Q: Log all instruction with intel pintool I have written this pintool:
#include "pin.H"
#include <iostream>
#include <fstream>

VOID Instruction(INS ins, VOID *v)
{
        cout << INS_Disassemble(ins) << endl;
}

VOID Fini(INT32 code, VOID *v)
{
        cout << "Fin" << endl;
}

int main(int argc, char *argv[])
{
    if( PIN_Init(argc,argv) )
    {
            cout << "Erreur PIN_Init" << endl;
            return 0;
    }

    INS_AddInstrumentFunction(Instruction, 0);
    PIN_AddFiniFunction(Fini, 0);
    PIN_StartProgram();

    return 0;
}

I am printing all instructions.
What i want to do now is to display instructions address (EIP)
How can i do this ?
Thanks

A: #include "pin.H"
#include <iostream>
#include <fstream>
#include <string>

VOID DisplayInstruction(ADDRINT instructionAddress,string assemblyCode)
{
    cout<<std::hex<<instructionAddress<<":"<<std::dec<<assemblyCode<<"\n";
}

VOID Instruction(INS ins, VOID *v)
{
    INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)DisplayInstruction,
                   IARG_INST_PTR, IARG_REG_VALUE,
                   new string(INS_Assemble(ins)), IARG_END);
}

VOID Fini(INT32 code, VOID *v)
{
    cout << "Fin" << endl;
}

int main(int argc, char *argv[])
{
    if( PIN_Init(argc,argv) )
    {
        cout << "Erreur PIN_Init" << endl;
        return 0;
    }

    INS_AddInstrumentFunction(Instruction, 0);
    PIN_AddFiniFunction(Fini, 0);
    PIN_StartProgram();

    return 0;
}

A: You will need to add an analysis routine, and to pass IARG_REG_VALUE to that routine.
 VOID your_analysis_function(VOID * ip)
   {
        out << "ip:" << ip << endl;
   }
   VOID Instruction(INS ins, VOID *v)
   {
       INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)your_analysis_function,
        IARG_INST_PTR, IARG_REG_VALUE, IARG_END);
   }


text:
Q: Spring Boot https redirect I deployed a Spring Boot web application to AWS and configured SSL certificate for a domain. Every time I click a Login button mapped to:
@RequestMapping("/login")
public String login(){
   return "login";
}

I'm redirected to https login page. However, when a user tries to access a page that requires authorization, he is redirected to unsecured http login page.
My Spring Security look like follows:
http
.authorizeRequests()
.antMatchers(HttpMethod.GET,"/","/css/**","/images/**","/js/**").permitAll()
.antMatchers("/").permitAll()
.antMatchers("/index").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.deleteCookies("remember-me")
.logoutSuccessUrl("/login?logout")
.permitAll();

Here is live example: test4test.io

A: Assuming that connection is secure until it hits application, you will have to add following to security config to make all requests secure.
http.requiresChannel().anyRequest().requiresSecure();

If the tls is terminating at the load balancer(which may not be ideal but there are cases) then this may not work. In such circumstances, in aws alb/nlb, a listener can be added on port 80 which can redirect to port 443. This would not require any change in the application as the redirection happens from hte load balancer before the application gets the request.


text:
Q: Check value in dictionary of dictionaries foob = {1:{'url':'www.abc.com', 'name':'abc'}, 2:{'url':'www.def.com', 'name':'def'}}
item = {'url':'www.abc.com', 'name':'wrong name'}

if item in foob.values():
    print 'yes'
else:
    print 'no'

I want to change item in list.values() so that it only compares url values and not whole dictionary. Is it possible to do that without iterating through whole dictionary there a simple way to do this without writing a separate for loop?

A: Use any and a generator expression:
if any(i['url'] == item['url'] for i in dict.values()):
    print 'yes'
else:
    print 'no'

A: I think this code will work, but I don't think there is a way can avoid some kind of iterate.
dict = {1:{'url':'www.abc.com', 'name':'abc'}, 2:{'url':'www.def.com', 'name':'def'}}
item = {'url':'www.abc.com', 'name':'wrong name'}

if item['url'] in [i['url'] for i in dict.values()]:
    print 'yes'
else:
    print 'no'

I agree deceze's code, use any


text:
Q: How to convert a number into a string and use it as an array key in Javascript? I'm trying to convert a number to a string to use as a key. But the problem is, when I the newly converted string, it still acts like a number. Is there a right way of doing this?
JAVASCRIPT
var arr = [];

var num = 3;

var key = String(''+num); //Convert number into string

//var key = ''  +num;         //Tried this
//var key = num.toString(); //Tried this also

array[key] = true;

console.log(arr); //Returns [, , true]
console.log(arr.length); //Returns 3

Basically, I want it to return just:
console.log(arr); //Return [true]
console.log(arr.length); //Return 1

A: What you're looking for is an Object ({}) not an Array ([]). Use this instead:
var obj = {};
var key = 3;
obj[key] = true; // no need to convert the key to string

EXAMPLE:

var obj = {};
var key = 3;
obj[key] = true;

console.log(obj);


text:
Q: Using Mandrill for sending notification mails in PHP Iam planning to send daily notification mails to my website users using Mandrill with PHP. I have some list of users in mailchimp lists and my database also. Now Iam following the method as sail in this link : http://lvsclasses.blogspot.in/2013/12/mandrill-api-to-send-mails-with.html. I tried to send mails as prescribed and it is working fine. But Iam not able to implement for loop based conditions for displaying the contents and also dont know hoow to send this mail to mailchimp lists.
 The documentations given by Mailchimp and Mandrill is not giving me an idea. Can you please help me to implement this requirement : sending notification mails to users(content is taking from website) and send to users in mailchimp list?


text:
Q: Which approach promises better performance - a megaquery or several targeted queries? I am creating an SSRS report that returns data for several "Units", which are all to be displayed on a row, with Unit 1 first, to its right Unit 2 data, etc.
I can either get all this data using a Stored Proc that queries the database using an "IN" clause, or with multiple targeted ("Unit = Bla") queries.
So I'm thinking I can either filter each "Unit" segment with something like "=UNIT:[Unit1]" OR I can assign a different Dataset to each segment (witht the targeted data).
Which way would be more "performant" - getting a big chunk of data, and then filtering the same thing in various locations, or getting several instances/datasets of targeted data?
My guess is the latter, but I don't know if maybe SSRS is smart enough to make the former approach work just as well or better by doing some optimizing "behind the scenes"

A: I think it really depends on how big the big chunk of data is. My experience has been that SSRS can process quite a large amount of data after it comes back from the database, and it does it quickly. If the report is going to aggregate the data in the end, I try to do as much of that as I can on the database end. The reason, usually the database server has more resources to do all that work. But, if the detail is needed, and you can aggregate on the report server end easily enough, pull 10K records and do it to it.
I lean toward hitting the database as few times as possible, but sometimes it just makes sense to get the data I need with individual queries. I have built reports with over 20 datasets, each for very specific measures that just didn't union up really well. Breaking it up like this took the report run time from 3 minutes, to 20 seconds.
Not a great answer if you were looking for which exact solution to go with. It depends on the situation. Often, trial and error gets you to the answer for the report in question.

A: SSRS is not going to do any "optimizing" and the rendering requirements sound trivial, so you should probably consider this as SQL query issue, not really SSRS.
I would expect the single SELECT with an IN clause will be faster, as it will require fewer I/Os on the database files.  An SP is not required, you can just write a SELECT statement.
A further benefit is that you will be left with N-times less code to maintain (where N = the number of Units), and can guarantee the consistency of the code/logic across Units.


text:
Q: Unable to Connect to SQL Server 2005 Db From Vista x64 Windows Service I'm trying to connect to a remote SQL Server 2005 db from a .NET Windows service running in Vista Home Premium x64. I can access the remote db from a console app with no problem. I can connect to a local db from the Windows service with no problem. I was able to connect from a service from XP with no problem. There's no firewall or anti-virus running. How do I configure this service to be able to connect to the remote db?
I've tried to connect by running the Windows service as a local admin account, LocalSystem, LocalService, and NetworkService.
The connection string:
Data source=SERVER_NAME;Initial Catalog=DB_NAME;Integrated Security=True;
The error:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
MORE INFO:
I have also tried to connect using SQL Server authentication with no success:
Data Source=SERVER_NAME;User ID=USER_ID;Password=PWD;Initial Catalog=DB_NAME
This connection string works from the console app too.
MORE INFO:
I ran Process Monitor for the Windows Service and the console app. The Windows service showed \SERVER_NAME\pipe\sql\query was ACCESS DENIED but the console app showed SUCCESS when reading/writing files to \SERVER_NAME\pipe\sql\query.

A: Good Lord! Why all the gibberish and complex responses on this site. Create a User Account
Either local or Domain and set the service to use that account. Then go into your SQL Server and Add you new account to the Database and set permissions. Voila!
Oh yeah, dont plague yourself with SQL Authentication. Integrated Security is much easier to maintain and without a password in your web.config your much safer.

A: 1) open a command prompt. Type "ping SERVER_NAME".  Does it respond?  You may have a DNS or connectivity issue if this doesn't work.
2) "telnet SERVER_NAME 1443".  Do you see anything or does it refuse your connection?  This will definitively tell you whether or not someone is listening on the other end.
3) Go into SQL Server Management Studio.  Right click Properties of your server.  Select "Connections" from the left side.  Is "Allow Remote Connections" checked?
4) Since you're running using network service/system, you will need to make sure you have a login configured on your server for the machine account DOMAIN\CLIENTSYSTEMNAME$.  Note the $ sign.  This is your machine account, and this will be the user that SQL Server will see.


text:
Q: Docker continuous deployment workflow I'm planning to set up a jenkins-based CD workflow with Docker at the end.
My idea is to automatically build (by Jenkins) a docker image for every green build, then deploy that image either by jenkins or by 'hand' (I'm not yet sure whether I want to automatically run each green build).
Getting to the point of having a new image built is easy. My question is about the deployment itself. What's the best practice to 'reload' or 'restart' a running docker container? Suppose the image changed for the container, how do I gracefully reload it while having a service running inside? Do I need to do the traditional dance with multiple running containers and load balancing or is there a 'dockery' way?

A:
Suppose the image changed for the container, how do I gracefully reload it while having a service running inside?

You don't want this.
Docker is a simple system for managing apps and their dependencies. It's simple and robust because ALL dependencies of an application are bundled with it.  If your app runs today on your laptop, it will run tomorrow on your server.  This is because we have captured 100% of the "inputs" for your application.
As soon as you introduce concepts like "upgrade" and "restart", your application can (accidentally) store state internally. That means it might behave differently tomorrow than it does today (after being restarted and upgraded 100 times).
It's better use a load balancer (or similar) to transition between your versions than to try and muck with the philosophy of Docker.

A: The Docker machine itself should always be immutable as you have to replace it for a new deployment. Storing state inside the Docker container will not work when you want to ship new releases often that you've built on your CI.
Docker supports Volumes which will let you write files that are permanent into some folder on the host. When you then upgrade the Docker container you use the same volume so you've got access to the same files written by the old container:
https://docs.docker.com/userguide/dockervolumes/


text:
Q: How to translate a qsort from C to Java? I'm a fairly new coder. I'm trying to understand the following C code:
int compar (const void *a, const void *b)
{
  return ((int *) a)[0] - ((int *) b)[0];
}

that is used in:
qsort (&tree[0][0], 8, 3 * sizeof (int), &compar);

the tree is a 2D array that's specifically an 8x3 for this case (it gets filled with possible moves, but I think that's irrelevant for the purpose of learning this). I understand the first three parameters of qsort (though a bit iffy as to why the first one calls the address but I think that's just how C calls the array), but not the fourth. I don't understand how qsort is using compar. I want to design a Java sorting method that does same as the aforementioned qsort, though I don't really care for it to be quick sort per se (as in I'm free to utilize whatever Java may offer and it doesn't have to be a quick sort. Because this isn't an assignment, I just want a sorting method that can sort fast so a nlogn or something would be helpful as this project involves a lot of recursion and calls this a lot of times). I'm struggling to understand what the compar is doing and then how qsort utilizes that to sort.
unorderStart
 0     -2      1
 0     -1      2
 5      1      2
 5      2      1
 0      2     -1
 0      1     -2
 0     -1     -2
 0     -2     -1
unorderEnd
orderStart
 0     -2      1
 0     -1      2
 0      2     -1
 0      1     -2
 0     -1     -2
 0     -2     -1
 5      1      2
 5      2      1
orderEnd

unorderStart
 0     -1      3
 1      0      4
 3      2      4
 3      3      3
 3      3      1
 3      2      0
 0      0      0
 0     -1      1
unorderEnd
orderStart
 0     -1      3
 0      0      0
 0     -1      1
 1      0      4
 3      2      4
 3      3      3
 3      3      1
 3      2      0
orderEnd

unorderStart
 0     -2      5
 0     -1      6
 0      1      6
 0      2      5
 5      2      3
 0      1      2
 0     -1      2
 0     -2      3
unorderEnd
orderStart
 0     -2      5
 0     -1      6
 0      1      6
 0      2      5
 0      1      2
 0     -1      2
 0     -2      3
 5      2      3
orderEnd

unorderStart
 0      0      4
 0      1      5
 0      3      5
 1      4      4
 3      4      2
 2      3      1
 3      1      1
 3      0      2
unorderEnd
orderStart
 0      0      4
 0      1      5
 0      3      5
 1      4      4
 2      3      1
 3      4      2
 3      1      1
 3      0      2
orderEnd

unorderStart
 0      2      5
 0      3      6
 0      5      6
 0      6      5
 0      6      3
 0      5      2
 5      3      2
 0      2      3
unorderEnd
orderStart
 0      2      5
 0      3      6
 0      5      6
 0      6      5
 0      6      3
 0      5      2
 0      2      3
 5      3      2
orderEnd

unorderStart
 3      1      3
 2      2      4
 0      4      4
 0      5      3
 0      5      1
 1      4      0
 2      2      0
 2      1      1
unorderEnd
orderStart
 0      4      4
 0      5      3
 0      5      1
 1      4      0
 2      2      4
 2      2      0
 2      1      1
 3      1      3
orderEnd

unorderStart
 4      2      1
 0      3      2
 0      5      2
 0      6      1
 0      6     -1
 0      5     -2
 0      3     -2
 0      2     -1
unorderEnd
orderStart
 0      3      2
 0      5      2
 0      6      1
 0      6     -1
 0      5     -2
 0      3     -2
 0      2     -1
 4      2      1
orderEnd

unorderStart
 2      0      2
 2      1      3
 2      3      3
 2      4      2
 0      4      0
 0      3     -1
 0      1     -1
 0      0      0
unorderEnd
orderStart
 0      4      0
 0      3     -1
 0      1     -1
 0      0      0
 2      0      2
 2      1      3
 2      3      3
 2      4      2
orderEnd

unorderStart
 0     -2      3
 0     -1      4
 2      1      4
 0      2      3
 0      2      1
 2      1      0
 0     -1      0
 0     -2      1
unorderEnd
orderStart
 0     -2      3
 0     -1      4
 0      2      3
 0      2      1
 0     -1      0
 0     -2      1
 2      1      4
 2      1      0
orderEnd

unorderStart
 0     -1      5
 0      0      6
 0      2      6
 0      3      5
 1      3      3
 7      2      2
 0      0      2
 0     -1      3
unorderEnd
orderStart
 0     -1      5
 0      0      6
 0      2      6
 0      3      5
 0      0      2
 0     -1      3
 1      3      3
 7      2      2
orderEnd

unorderStart
 0      1      4
 0      2      5
 0      4      5
 0      5      4
 0      5      2
 2      4      1
 0      2      1
 0      1      2
unorderEnd
orderStart
 0      1      4
 0      2      5
 0      4      5
 0      5      4
 0      5      2
 0      2      1
 0      1      2
 2      4      1
orderEnd

unorderStart
 6      2      2
 0      3      3
 0      5      3
 0      6      2
 0      6      0
 0      5     -1
 0      3     -1
 1      2      0
unorderEnd
orderStart
 0      3      3
 0      5      3
 0      6      2
 0      6      0
 0      5     -1
 0      3     -1
 1      2      0
 6      2      2
orderEnd

unorderStart
 2      0      1
 0      1      2
 0      3      2
 0      4      1
 0      4     -1
 0      3     -2
 0      1     -2
 0      0     -1
unorderEnd
orderStart
 0      1      2
 0      3      2
 0      4      1
 0      4     -1
 0      3     -2
 0      1     -2
 0      0     -1
 2      0      1
orderEnd

unorderStart
 0     -2      2
 0     -1      3
 1      1      3
 5      2      2
 0      2      0
 0      1     -1
 0     -1     -1
 0     -2      0
unorderEnd
orderStart
 0     -2      2
 0     -1      3
 0      2      0
 0      1     -1
 0     -1     -1
 0     -2      0
 1      1      3
 5      2      2
orderEnd

unorderStart
 0     -1      4
 0      0      5
 0      2      5
 2      3      4
 0      3      2
 0      2      1
 0      0      1
 0     -1      2
unorderEnd
orderStart
 0     -1      4
 0      0      5
 0      2      5
 0      3      2
 0      2      1
 0      0      1
 0     -1      2
 2      3      4
orderEnd

unorderStart
 0      1      5
 0      2      6
 0      4      6
 0      5      5
 0      5      3
 1      4      2
 4      2      2
 0      1      3
unorderEnd
orderStart
 0      1      5
 0      2      6
 0      4      6
 0      5      5
 0      5      3
 0      1      3
 1      4      2
 4      2      2
orderEnd

unorderStart
 0      2      3
 0      3      4
 0      5      4
 0      6      3
 0      6      1
 0      5      0
 2      3      0
 0      2      1
unorderEnd
orderStart
 0      2      3
 0      3      4
 0      5      4
 0      6      3
 0      6      1
 0      5      0
 0      2      1
 2      3      0
orderEnd

unorderStart
 1      1      1
 3      2      2
 0      4      2
 0      5      1
 0      5     -1
 0      4     -2
 0      2     -2
 0      1     -1
unorderEnd
orderStart
 0      4      2
 0      5      1
 0      5     -1
 0      4     -2
 0      2     -2
 0      1     -1
 1      1      1
 3      2      2
orderEnd

unorderStart
 0     -1      2
 2      0      3
 0      2      3
 0      3      2
 0      3      0
 0      2     -1
 0      0     -1
 0     -1      0
unorderEnd
orderStart
 0     -1      2
 0      2      3
 0      3      2
 0      3      0
 0      2     -1
 0      0     -1
 0     -1      0
 2      0      3
orderEnd

unorderStart
 0     -2      4
 0     -1      5
 0      1      5
 1      2      4
 2      2      2
 0      1      1
 0     -1      1
 0     -2      2
unorderEnd
orderStart
 0     -2      4
 0     -1      5
 0      1      5
 0      1      1
 0     -1      1
 0     -2      2
 1      2      4
 2      2      2
orderEnd

unorderStart
 0      0      5
 0      1      6
 0      3      6
 0      4      5
 2      4      3
 0      3      2
 0      1      2
 0      0      3
unorderEnd
orderStart
 0      0      5
 0      1      6
 0      3      6
 0      4      5
 0      3      2
 0      1      2
 0      0      3
 2      4      3
orderEnd

unorderStart
 0      2      4
 0      3      5
 0      5      5
 0      6      4
 0      6      2
 0      5      1
 1      3      1
 1      2      2
unorderEnd
orderStart
 0      2      4
 0      3      5
 0      5      5
 0      6      4
 0      6      2
 0      5      1
 1      3      1
 1      2      2
orderEnd

unorderStart
 0      1      2
 0      2      3
 0      4      3
 0      5      2
 0      5      0
 0      4     -1
 0      2     -1
 1      1      0
unorderEnd
orderStart
 0      1      2
 0      2      3
 0      4      3
 0      5      2
 0      5      0
 0      4     -1
 0      2     -1
 1      1      0
orderEnd

unorderStart
 0     -1      1
 0      0      2
 0      2      2
 0      3      1
 0      3     -1
 0      2     -2
 0      0     -2
 0     -1     -1
unorderEnd
orderStart
 0     -1      1
 0      0      2
 0      2      2
 0      3      1
 0      3     -1
 0      2     -2
 0      0     -2
 0     -1     -1
orderEnd

I think that the first column is sorted in a descending fashion, but what is happening to the other two columns? The rows? The Java code doesn't have to utilize generics or anything, as a matter a fact, the simpler the code, the better. Any help would be appreciated and if you would, please explain the code? Thanks

A: Turns out that Arrays.sort can use a comparator that the coder can customize. Note this is basically the end product I made based off of mostly everything commented (everything that attempted to help me understand at least). Thanks so much!
public static void reorder(int[][] a){
Arrays.sort(a, new Comparator<int[]>() {
    @Override
    public int compare(final int[] a, final int[] b) {
         Integer c = Integer.valueOf(a[0]);
         Integer d = Integer.valueOf(b[0]);
        return c.compareTo(d);
    }
    });
}


text:
Q: Laravel FCM Channel Driver not working when queued I have implemented FCM notification channel on my laravel app.
The notifications have to be sent via mail and broadcast and because I'm using the mail channel, I have added the ShouldQueue contract in my notification class, but the FCM broadcast then stopped working.
If I remove the ShouldQueue implementation the notification is sent without problems.
I don't know what could it be or how to get this working without creating a specific notification for broadcast and without disabling queuing.
Any advice would help.
I've posted this as an issue in the fcm github but they haven't answered so I'm turning to stackoverflow.


text:
Q: Accessing the user folder from a previous Windows installation (content on a read-only image) Before upgrading from Windows 7 to Windows 10 I imaged the Windows 7 system using O&O DiskImage Professional. After a clean upgrade (wiped the original installation) I started restoring content, and eventually came across something I had forgotten to pull from my old personal folder before reinstall. To my surprise I couldn't access the \Users\MyOldFolder on the image, apparently because its Admin and user UUIDs were now different. As an admin on a new install I would normally just assume ownership of the old content and would be good to go, but the image is read-only so I can't alter the permissions on it.
My question is: Is there any way to access that content – i.e. as an admin of the Windows 10 Pro installation make Windows to ignore the offending old permissions? Or is my only option to write the image onto a disk so that I can modify the permissions as needed? I tried to turn UAC off but that did not make a difference.

A: I'm answering my own question that I had already written, but hadn't yet posted by the time I came across the answer. There was a ~duplicate (How to gain access to Windows Users folders on a read-only backup medium), but its answer did not help because turning UAC off made no difference in my case.
There was a solution, however:

*

*Download and install SysInternals Suite (specifically PsExec, which is part of the suite).

*Start PowerShell with elevated privileges.

*If SysInternals suite (and specifically PsExec.exe) isn't on the path, navigate to the folder you installed it in.

*Now execute cmd as SYSTEM:
psexec -s cmd.exe

*You're now able to access the content whose Administrator and USER UUIDs have changed due to the system reinstall (but which you can't modify because of the read-only media). You're now accessing it as the SYSTEM which does not change from install to install.

Simply navigate to the mounted read-only media, and walk right in to the folder you were previously denied access to, like R:\Users\MyOldFolder (a user folder of the old Windows installation).

You can then copy files out. I used xxcopy to copy my entire old profile folder from the read-only media into a folder on my hard drive so that I can easily retrieve missing program config files as I configure my new Windows 10 installation. 2022 update: xxcopy was discontinued a few years ago, but you can use instead Windows' built-in robocopy to accomplish the same, like so: robocopy c:/path/to/source d:/path/to/target *.* /COPY:D, where D implies "Data only" (and no attributes, or the owner), as outlined in  this superuser.com thread.
I found the critical details for the above from a TechNet thread.


text:
Q: How to avoid that "%2500" gets added to string after encryption? After a token decryption with the PHP function below, a number of %2500 (are they called null bytes?) are added to the end of the decrypted token string. Where does they come from and how to avoid that?
Encryption and decryption:
$decrKey = "1234567890000000";
$decrIV = "ABCDEFGHIJKLMNOP";

function encryptAES($data,$key,$iv)
{
$encr = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, $iv));
return $encr;
}

function decryptAES($data,$key,$iv)
{
$decr= mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, base64_decode($data), MCRYPT_MODE_CBC, $iv);
return $decr;
}

Decrypt token:
$oauthToken  = $_POST["serviceToken"];
// $oauthToken = 123424154-MUOfpNu9abcYIMEDIGAf4zMdefMlm5nI7d6ocCqi
$oauthToken = decryptAES($oauthToken,$decrKey,$decrIV);


text:
Q: Angular 7 component redirection without routing With my current Angular 7 and Firebase setup I have the following situation:
I have the main app component which shows the member area if the user is logged in or otherwise the public area. Everything is working fine, but there is a 1-2 second delay until the correct component shows after signing out or in. I don't want to use routing btw. because I want to show everything with the same URL.
Do you have an idea how I can reduce the delay and is this a good practice of doing authentication anyway?
I appreciate all your help!
app.component.html
<div *ngIf="authService.isAuthorized(); else showLogin">
  <app-member></app-member>
</div>
<ng-template #showLogin>
  <app-public></app-public>
</ng-template>
<router-outlet></router-outlet>

And then here the components for the member area and public area:
member.component.html:
<button nz-button [nzSize]="size" nzType="primary (click)="authService.logout()">Logout</button>

public.component.html:
<button nz-button [nzSize]="size" nzType="primary" (click)="authService.login()">Login</button>

A: I do not know how to do it without routing. Why do not you want to use it?
It would be that simple:
Using Angular's canActivate class on your app-routing.module.ts file.
For this, you will need to implement an authentication service that checks whether the user is loged in or not.
Example:
   const routes: Routes = [
      {
        path: '',
        component: MemberComponent,
        canActivate: [YourAuthGuard],
      },
      {
        path: 'public',
        component: PublicComponent
      }
    ];
    @NgModule({
      imports: [...],
      exports: [...],
      providers: [ YourAuthGuard ]
    })
    export class AppRoutingModule { }

Then you can put redirects from one component to another with the navigate () method of the Angular class Router.
Hope this can help you.

A: With your initial approach, I suggest you to use a variable as observable that defines whether the user is authorized in or not, better than call the function authService.isAuthorized().
You can do this defining an observable property in your authservice:
AuthService.ts
isAuthorized() {
    ...
    this.isAuthorized.next(true);
}
isAuthorized$ = this.isAuthorized.asObservable();

In this way, the property will be automatically updated in your main template by doing something like this:
app.component.ts
authService.isAuthorized$.subscribe((response) => {
    this.isAuthorized = response;
});

Then you can use on your main template:
app.component.html
<div *ngIf="isAuthorized" ; else showLogin">
And to handle the possible wait, as AJT_82 has already commented, it would be best to put a spinner until the call has been made.


text:
Q: How is the altitude of MKMapCamera calculated? I've been logging the altitude of an MKMapView's camera as the view is scrolled and I've discovered a strange behavior: the altitude of the viewpoint fluctuates as the user scrolls although the apperance of the map's zoom level stays the same.
After closer inspection, it seems that the altitude decreases as the user scrolls South (toward the equator) and the increases again once the user passes the equator. I thought that it might have something to do with curvature of the Earth and possible involve some trigonometry or cartography knowledge that I don't have.
I am trying to emulate this function. I have a CLLocationCoordinate2D and the current altitude and zoom level and I want to calculate the proper altitude for the MKMapCamera.
Thanks!

A: I found your post when asking the same question.  I then found this post:
How to determine the correct altitude for an MKMapCamera focusing on an MKPolygon
Condensing this into the answer to your question (and mine):
    double distance = MKMetersBetweenMapPoints(MKMapPointForCoordinate(pinCenter.coordinate),
                                               MKMapPointForCoordinate(pinEye.coordinate));
    double altitude = distance / tan(M_PI*(15/180.0));

    MKMapCamera *camera = [MKMapCamera cameraLookingAtCenterCoordinate:pinCenter.coordinate
                                                     fromEyeCoordinate:pinEye.coordinate
                                                           eyeAltitude:altitude];


text:
Q: SQL Server : primary keys advice to my whitepaper needed I've tired to explain to every new junior developer in our r&d team why he should use Primary Keys and how to do that. So I decided to write small whitepaper, which every new developer should read. Here is the draft of it.
DISCLAIMER:

*

*I know and understand the difference between clustered index and primary key

*In the following question PRIMARY KEY means PRIMARY KEY CLUSTERED, and WITHOUT PRIMARY KEY means WITHOUT PK AND CLUSTERED INDEX

*Note that it is a whitepaper for junior and not SQL programmers

*All the things that they do - reviewed before entering to the main development branch

*I'm not going to explain to them - when there will be benefit of using clustered index and NONclustered primary key - else I will fall to premature optimizations hell
The question is - what else should I add to the document? May be - what I should change in it? And what to explain more in detail?
Here comes the draft:

*

*Primary keys have to constrain any table within database.

*Without PK a table considered as a heap and SQL Server has very limited uses of this type of data - the only thing I should say it is suitable - a buffer for fast bulk-loading data from the outside of SQL Server's engine.

*Avoid using natural primary keys. Primarily because of theirs natural (gauss) distributions. For example in PhoneBook table with primary key based on Family and Name will be many Smiths and Wilsons and much fewer Zimmerbergs and this states, that pages containing Smiths and Wilsons will be splitted more often, than other pages, and queried also more often - which multiplies the performance impact. That leads to performance degradation, because of primary key's page fullness and most of searches will hit PK's sparsed pages.

Moreover, even using SSN or ID Number, which have (I hope) flat distribution, as PK does not solve the problem of PK's page splitting, because this numbers are not in any organized order.

*

*Secondary - natural PKs are often composite. That creates composite foreign keys and wide indexes and as a result hurts performance. So, ...

*Avoid using composite PKs. Better using simple surrogate PK and composite UNIQUE index, than all-in-one composite PK because it leads to composite FK and wide indexes due to statement, that every secondary index on table with PK has to include whole PK within.

*Avoid using surrogate primary keys other than integer or uniqueidentifier types

*During database design phase it is very important to identify entities and corresponding tables which may have in perspective "zillions" of rows, or tables which keys have to be NOT ONLY table-wide unique, but DB or even world unique, or which have to be joined with other tables by this key over several hop-tables - this tables better to have UUID PK, others - ordinary integer, because SQL Server very well fine tuned to use integer PKs.

*These two types can guarantee both vector distribution (IDENTITY or NEWSEQUENTIALID()) and monotonous sequence.

*Main database design rule - Twenty minutes spent to well thought-out design will save days or even weeks during production database's maintenance

A: You are confusing various concepts here, the major error being primary key != clustered key. Because of this misunderstanding, the majority of the guidance is incorrect. To be brutally honest, you are probably not well placed to be writing these guidelines.

*

*Primary key != clustered key

*Unique identifiers make for very poor clustered keys

*SQL Server is not "very well fine tuned to use integer PKs". The case for a narrow clustered key is covered in the link above, it is not a matter of SQL Server being optimised for integer clustered keys.

A: Your points are unrelated to database design: choice of natural or surrogate key is an implementation decisions after conceptual and logical models are complete
In addition to comments and other answers:

*

*some natural keys work well such as currency or language codes (CHF, GBP, DE, EN etc)

*avoiding composite keys forces you to always join intermediate tables (rather than simple) parent-grandchild

*adding a surrogate key in unnecessary for link tables

Edit: example of "composite keys"
Assume: t1 has child t2 has child t3

*

*If you had the key of t1 in t3 (composite key) you can join t1 and t3 directly.
t1 key is also the left hand column of t3 key so you don't need an extra index

*With a surrogate key/FK, you have to join via t2
You need extra indexes on the FK columns in t2 and t3 which
This latter option with the "always use surrogate key" dogma

*

*adds complexity

*decreased or reverses disk space "savings"

A: Why not start with the fundamentals of normalization and the ability to enforce relational integrity?
Also, if you are in an environment that uses transactional replication and there is any chance this table will ever be replicated, you'll need a primary key.
Here are some suggested reading materials you can share with these junior programmers:

*

*When i should use primary key or index?

*Worst Practices - Not Using Primary Keys and Clustered Indexes By Andy Warren

*A Normalization Primer By Brian Kelley

*Protecting SQL Server Data By John Magnabosco ISBN: 978-1-906434-26-7 (Available as a free ebook from RedGate;  See the section starting Chapter 3, Protection via Normalization around page 66.)

*Log Shipping vs. Replication By Paul Ibison


text:
Q: Javascript filter array empty objects The 1st set of code works fine and assigns non-empty objects to the var, but the 2nd code with only log the right data but will not return the data. The var just remains undefined.
Any idea on where I am going wrong? Thanks!
var filteredEmpty1 = json_data.children.filter(function(value, index, arr) {
    if (value.children.length != 0) {
        return value//Returns what I need
    } else {
        console.log("EMPTY")
    };
});

json_data = filteredEmpty1;
json_data = {
    "name": "RVs",
    "children": json_data
};

var filteredEmpty2 = json_data.children.forEach(function(value) {
    value.children.filter(function(e) {
        if (e.children.length != 0) {
            console.log(e)//Logs what I need to return
            return(e)//Returns undefined
        } else {
            console.log("EMPTY")
        };
    });
})

A: Use Map instead of forEach because Map returns a value. and Filter function always returns boolean.
var filteredEmpty2 = json_data.children.map(function(value) {
    return value.children.filter(function(e) {
       return e.children.length != 0;
    });
})


text:
Q: Turn off a down arrow within the hand symbol in pdf While reading pdf files (with Adobe Reader XI) the hand symbol entails an arrow, showing down. If I make a click, the page moves. I find it pretty annoying and would like to turn the arrow off, but keep the hand symbol. I can't find any solution to it in the internet. Can someone help me to deactivate this function?

A: This is probably due to the "Make hand tool read articles" setting.
You can switch it of by doing the following:

*

*Open menu item Edit > Preferences > General

*Uncheck "Make hand tool read articles"

A: Some documents allow you to copy the text and have the Select Screen  symbol for a pointer. Some only have the hand. This is document, not software related. Open one of you other documents and the functionality returns.


text:
Q: Search results from specific country in Bing Search API? I want to know is this possible in Bing search API to restrict results from a specific country.

A: Yes. See location::

Returns webpages from a specific country or region. Specify the
  country or region code directly after the location: keyword. For
  language codes, see Bing API Version 2 Documentation. To return
  results for two or more languages, use OR to group the languages.


text:
Q: I Want To Remove GROUP BY From My Query As It Interferes With The Output Good day,
Please I sincerely don't know how to write sub-queries and I need help with that. I discovered that GROUP BY in the query I will post below is interfering with the pagination of the page. Can someone help me re-write the query to exclude GROUP BY?
$select = "SELECT report.id AS id, COUNT(reportUserName) AS reportCount, "
        . " branchName, reportDate";
$from = " FROM report INNER JOIN branches";
$where = " WHERE report.branchUserName = branches.branchUserName GROUP BY reportDate, "
        . "report.branchUserName";

Here is the code that should create the pagination
if (isset($_POST['items_per_page']) && is_numeric($_POST['items_per_page']))
    $_SESSION['items_per_page'] = $_POST['items_per_page'];

    $conn = DatabaseManager::getConnection();
    //get the function
    include_once ('../function.php');

        $page = (int) (!isset($_GET["page"]) ? 1 : $_GET["page"]);

    $limit = $pageNo;

if (isset($_SESSION['items_per_page']) && is_numeric($_SESSION['items_per_page']))
$limit = intval($_SESSION['items_per_page']);

        $startpoint = ($page * $limit) - $limit;

        //to make pagination
        $statement = "report INNER JOIN branches WHERE report.branchUserName = branches.branchUserName GROUP BY reportDate, report.branchUserName";

$select = "SELECT report.id AS id, COUNT(reportUserName) AS reportCount, "
        . " branchName, reportDate";
$from = " FROM report INNER JOIN branches";
$where = " WHERE report.branchUserName = branches.branchUserName GROUP BY reportDate, report.branchUserName";

            try
                {
                    $sql = $select . $from . $where . " ORDER BY serviceDate DESC LIMIT {$startpoint} , {$limit}";
                    $query = $conn->prepare($sql);
                    $query->execute();
                }
            catch (PDOException $e)
                {
                    $error[] = 'Error performing the operation you wanted.';
                }

Here is function.php used in the code above
function pagination($query, $per_page = 10, $page = 1, $url = '?'){
   include_once ('classes/DatabaseManager.php');
   $conn = DatabaseManager::getConnection();

        $query = "SELECT COUNT(DISTINCT report.reportUserName) as `num` FROM {$query}";
        foreach($conn->query($query) as $row);
        $total = $row['num'];
        $adjacents = "2";

    //Ronald's code begings
    $url = '?';
        foreach($_GET as $k => $v) {
        if($k != 'page') {
        $url .= "{$k}={$v}&";
          }
        }
        //Ronald's code ends

        $page = ($page == 0 ? 1 : $page);
        $start = ($page - 1) * $per_page;

        $prev = $page - 1;
        $next = $page + 1;
        $lastpage = ceil($total/$per_page);
        $lpm1 = $lastpage - 1;

        $pagination = "";
        if($lastpage > 1)
        {
            $pagination .= "
";
                $pagination .= "
Page $page of $lastpage
";
            if ($lastpage < 7 + ($adjacents * 2))
            {
                for ($counter = 1; $counter <= $lastpage; $counter++)
                {
                    if ($counter == $page)
                        $pagination.= "
$counter
";
                    else
                        $pagination.= "
$counter
";
                }
            }
            elseif($lastpage > 5 + ($adjacents * 2))
            {
                if($page < 1 + ($adjacents * 2))
                {
                    for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
                    {
                        if ($counter == $page)
                            $pagination.= "
$counter
";
                        else
                            $pagination.= "
$counter
";
                    }
                    $pagination.= "
...
";
                    $pagination.= "
$lpm1
";
                    $pagination.= "
$lastpage
";
                }
                elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))
                {
                    $pagination.= "
1
";
                    $pagination.= "
2
";
                    $pagination.= "
...
";
                    for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
                    {
                        if ($counter == $page)
                            $pagination.= "
$counter
";
                        else
                            $pagination.= "
$counter
";
                    }
                    $pagination.= "
..
";
                    $pagination.= "
$lpm1
";
                    $pagination.= "
$lastpage
";
                }
                else
                {
                    $pagination.= "
1
";
                    $pagination.= "
2
";
                    $pagination.= "
..
";
                    for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++)
                    {
                        if ($counter == $page)
                            $pagination.= "
$counter
";
                        else
                            $pagination.= "
$counter
";
                    }
                }
            }

            if ($page < $counter - 1){
                $pagination.= "
Next
";
                $pagination.= "
Last
";
            }else{
                $pagination.= "
Next
";
                $pagination.= "
Last
";
            }
            $pagination.= "
\n";
        }

        return $pagination;
    }

Here is the sample data
-- version 5.0.4
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Feb 23, 2021 at 11:53 AM
-- Server version: 10.4.17-MariaDB
-- PHP Version: 7.4.14

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `mydata`
--

-- --------------------------------------------------------

--
-- Table structure for table `report`
--

CREATE TABLE `report` (
  `id` bigint(50) UNSIGNED NOT NULL,
  `branchUserName` varchar(100) NOT NULL,
  `reportUserName` varchar(200) NOT NULL,
  `reportDate` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `report`
--

INSERT INTO `report` (`id`, `branchUserName`, `reportUserName`, `reportDate`) VALUES
(6, 'marketing', 'marketing-jan-10', 2020-10-5),
(7, 'marketing', 'marketing-nov-19', 2020-9-24),
(8, 'production', 'production-nov-16', 2020-12-27),
(9, 'production', 'production-feb-14', 2020-12-27),
(13, 'production', 'production-feb-14', 2020-8-17);

--
-- Indexes for dumped tables
--

--
-- Indexes for table `report`
--
ALTER TABLE `report`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `reportUN` (`reportUserName`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `report`
--
ALTER TABLE `report`
  MODIFY `id` bigint(50) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=14;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

The other table
-- phpMyAdmin SQL Dump
-- version 5.0.4
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Feb 23, 2021 at 11:53 AM
-- Server version: 10.4.17-MariaDB
-- PHP Version: 7.4.14

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `mydata`
--

-- --------------------------------------------------------

--
-- Table structure for table `branches`
--

CREATE TABLE `branches` (
  `id` int(15) UNSIGNED NOT NULL,
  `branchUserName` varchar(50) NOT NULL,
  `branchStatus` varchar(20) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `branches`
--

INSERT INTO `branches` (`id`, `branchUserName`, `branchStatus`) VALUES
(3,  'marketing',  'Active'),
(7,  'production', 'Active'),
(10, 'packaking', 'Active');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `branches`
--
ALTER TABLE `branches`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `branches`
--
ALTER TABLE `branches`
  MODIFY `id` int(15) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

The two tables involved are here. The result gets displayed correctly, the ONLY PROBLEM is that the pagination is not working. The result gets displayed but pagination doesn't get displayed, hence you can't check the second page, you are stucked with only the result on the first page.


text:
Q: Python Script to Run for ArcGIS I want to run python scripts that use geo-processing tools. I do not want to integrate them, instead I want to run scripts outside and not in ArcGIS. Please tell me how to do it with a nice example. I have to do reclassification of 4 maps and then do a weighted sum overlay of the outputs. Below is the script which I am able to write, but I don't know where I am getting an error..
enter code here #

import sys, string, os, arcgisscripting
 gp = arcgisscripting.create()
 gp.CheckOutExtension("spatial")

  gp.AddToolbox("C:/../Spatial Analyst Tools.tbx")

  feature_shp1 = sys.argv[1]
  if feature_shp1 == '#':
   feature_shp1 = "D:\\BRIEFCASE\\media\\new shapefiles\\feature_shp1"
  slope = sys.argv[2]
  if slope == '#':
  slope = "D:\\"

  Reclassification__2_ = sys.argv[3]
  if Reclassification__2_ == '#':
  Reclassification__2_ = "2 1;2 3 2;3 4 3;4 5 4"

  Reclassification = sys.argv[4]
  if Reclassification == '#':
  Reclassification = "0 13 1;13 45 2;45 80 3;80 108 4;108 146 5;146 176;174   195 7;195 231 8;231 255 9"

  Reclass_feat3 = "D:\\"
  Reclass_slop3 = "D:\\3"
  gjh = "C:\"
  Reclass_field = "VALUE"
  Reclass_field__2_ = "VALUE"

  gp.Reclassify_sa(feature_shp1, Reclass_field__2_, Reclassification__2_,            Reclass_feat3, "NODATA")

  gp.Reclassify_sa(slope, Reclass_field, Reclassification, Reclass_slop3, "NODATA")

  gp.WeightedSum_sa("'..Reclass_feat3' VALUE 1;'D:..Reclass_slop3' VALUE 1","ijh")

A: If you are trying to use ArcGIS geoprocessing tools without firing up ArcGIS itself, you'll want to put the following bit of code at the top of your program:
import arcpy
#Rest of Program
#Step 3:Profit!

That should allow you to use various tools from the toolbox, including Weighted sum and Reclassification.  I think arcpy replaced arcgisscripting as the module to import for that purpose, but I'm not sure, since I haven't been using python scripting wtih ArcGIS long enough to have known anything other than arcpy.
As for how to get the toolbox tools to work, the ArcGIS Resource center can be quite helpful.


text:
Q: Subscribing to Firebase realtime database ChildChange event fires event with children not from the subscribed path I'm working with firebase realtime database in Unity and I'm making a chat/inbox system.
The problem/unoptimized thing is that I've subscribed my ChildChanged like this:
FirebaseDatabase.DefaultInstance.GetReference("inbox/" + myUserID).ChildChanged += OnListenerGotChangedInboxItem;

so its supposed to return children that are changed from the path:
"inbox/" + myUserID
and I'm saving data like this for OnMessagePost using UpdateChildrenAsync:
Dictionary<string, object> dictToSend = new Dictionary<string, object>();
        // Set in messages
        dictToSend["/messages/" + myUserID + "/" + otherUser + "/" + key] = entryValues;
        dictToSend["/messages/" + otherUser + "/" + myUserID + "/" + key] = entryValues;

        // Set in inbox
        // Yours
        dictToSend["/inbox/" + myUserID + "/" + otherUser] = userInboxItem.ToDict();

        // Theirs
        dictToSend["/inbox/" + otherUser + "/" + myUserID + "/username"] = UserManager.instance.username;
        dictToSend["/inbox/" + otherUser + "/" + myUserID + "/user_id"] = UserManager.instance.userId;
        dictToSend["/inbox/" + otherUser + "/" + myUserID + "/unread"] = true;
        dictToSend["/inbox/" + otherUser + "/" + myUserID + "/text"] = messagePreviewText;
        dictToSend["/inbox/" + otherUser + "/" + myUserID + "/last_sent_date"] = message.time_sent;

        // Increase their unread count by one
        dictToSend["/unread/" + otherUser + "/" + myUserID] = "true";

        UserManager.instance.rootRef.UpdateChildrenAsync(dictToSend).ContinueWith(task => ...

And the OnChildChanged fires for the path "inbox/myUserID" and also fires for "inbox/otherUser" as well, even tho I'm only subscribed to ChildChanged for "inbox/myUserID"
If you have any better way for my to track incoming messages, Im all ears, but really im just curious why its triggering the event on a path im not subscribed to, but i suspect it has something to do with saving multiple children together on one UpdateChildrenAsync call.
As this is my first ever post on here I appreciate any help(:


text:
Q: Can't find where context is missing I've been refactoring a previous project to use fragments instead of creating separate activities as a school assignment. I've been trying to find out where this error is for close to an hour now and no luck. I get context missing when I add this line canvas.setColor(color, position);
Here's the Main activity:
    public class MainActivity extends AppCompatActivity implements PaletteFragment.SpinnerSelectedInterface {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            PaletteFragment palette = PaletteFragment.newInstance();

            Bundle bundle = new Bundle();
            bundle.putStringArray(KeyData.PASS_COLOR, getResources().getStringArray(R.array.colors));
            bundle.putStringArray(KeyData.PASS_POSITION, getResources().getStringArray(R.array.colorNames));
            palette.setArguments(bundle);

            getSupportFragmentManager().beginTransaction().add(R.id.palette_fragment, palette).commit();
        }

        @Override
        public void setCanvasColor(String color, int position) {
            CanvasFragment canvas = CanvasFragment.newInstance(null);
            getSupportFragmentManager().beginTransaction().add(R.id.canvas_fragment, canvas).addToBackStack(null).commit();
            canvas.setColor(color, position);
        }
    }

And here's the fragment:
public class CanvasFragment extends Fragment {
    private TextView displayColor;
    private View background;

    public CanvasFragment() {
        // Required empty public constructor
    }

    public static CanvasFragment newInstance(Bundle bundle) {
        CanvasFragment fragment = new CanvasFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_canvas, container, false);
        displayColor = (TextView) v.findViewById(R.id.displayColor);
        background = (View) v.findViewById(R.id.canvas_fragment);
        return v;
    }

    public void setColor(String color, int position){
        String[] names = getResources().getStringArray(R.array.colorNames);
        displayColor.setText(names[position]);
        background.setBackgroundColor(Color.parseColor(color));
    }

I've tried override onAttach and onDetach on the canvas fragment and adding a message listener, but still get the error as well. Would appreciate anything that could steer me in the right direction.
Error
java.lang.IllegalStateException: Fragment CanvasFragment{69925d5 (240edefb-318c-4983-bd15-cf45142e849a) id=0x7f080047} not attached to a context.

A: When you call
getSupportFragmentManager()
    .beginTransaction()
    .add(R.id.canvas_fragment, canvas)
    .addToBackStack(null)
    .commit();

You're using commit(). As per its Javadoc:

Schedules a commit of this transaction. The commit does not happen immediately; it will be scheduled as work on the main thread to be done the next time that thread is ready.

So when you immediately call canvas.setColor(color, position) directly afterwards, the Fragment is not attached and it doesn't yet have a Context associated with it.
If you want the Fragment to be immediately added, you want to use commitNow(), which forces the transaction to happen immediately. This ensures that it'll be done before your setColor method is called:
getSupportFragmentManager()
    .beginTransaction()
    .add(R.id.canvas_fragment, canvas)
    .addToBackStack(null)
    .commitNow();


text:
Q: Edge 12 JSON API response is transformed to UTF8 char I got a strange issue occuring only on Edge 12 (Edge 13 is fine). When calling my JSON API, I get a 200 response, yet response body is composed of a single unicode character instead of an expected JSON array.
I am sending header:
Accept: application/json, text/plain, */*

Is there any known issue similar to mine with Edge12? :/


text:
Q: OpenCV - No image shown without waitkey in the capture loop In OpenCV, if I don't include Cv2.WaitKey(1) line in the display loop for captured images, no image is rendered on the screen.
The same happens on C++, phyton, or C#.
What would be the cause for that, and is there another option?
This example is in C# (opencvsharp):
VideoCapture cap = new VideoCapture();

Window w = new Window();

cap.Open("animation.avi");

while (cap.Read(src)) {
    Cv2.WaitKey(1);
    w.ShowImage(src);
}

A: Technically highgui requires waitkey() to be called in order to get time to update the window.
From OpenCV documentation referring to imshow() function (ShowImage in C#):

This function should be followed by waitKey function which displays
  the image for specified milliseconds. Otherwise, it won't display the
  image. For example, waitKey(0) will display the window infinitely
  until any keypress (it is suitable for image display). waitKey(25)
  will display a frame for 25 ms, after which display will be
  automatically closed. (If you put it in a loop to read videos, it will
  display the video frame-by-frame)

And about waitKey() function (WaitKey() in C#):

This function is the only method in HighGUI that can fetch and handle
  events, so it needs to be called periodically for normal event
  processing unless HighGUI is used within an environment that takes
  care of event processing.


text:
Q: Can not stop the loop of importing rows from a sheet to another I have a problem in the loop. I want to import lines that contain "X" in their first cell but :

*

*It doesn't paste them from the first row

*It pastes them too many times

Can someone help me ?
 Sub refresh()
    '
    ' refresh Macro
    '
    ' Touche de raccourci du clavier: Ctrl+y
    '
    Dim LastRow As Integer, i As Integer
    Dim wksSrc As Worksheet, wksDest As Worksheet
    Dim lngRow As Long

    Set wksSrc = ThisWorkbook.Worksheets("Scénarios de menace")
    Set wksDest = ThisWorkbook.Worksheets("Analyse de risque S")
    Application.Calculation = xlAutomatic
    Application.DisplayAlerts = False
    wksDest.Range("A6:AP1000").Delete
    Application.DisplayAlerts = True
    wksDest.Range("A6:AP1000").ClearContents 'Works directly, without selection

    lngRow = wksDest.Cells(wksDest.Rows.Count, 2).End(xlUp).Row + 1

    For i = 2 To wksSrc.Range("A" & wksSrc.Rows.Count).End(xlUp).Row

      If wksSrc.Cells(i, 1) = "X" Then
        wksSrc.Range(wksSrc.Cells(i, 2), wksSrc.Cells(i, 20)).Copy

        wksDest.Range("B" & lngRow).PasteSpecial xlPasteValuesAndNumberFormats
        Application.CutCopyMode = False
        lngRow = lngRow + 1
      End If
    Next i
End Sub

A: sub refresh()
Dim LastRow As Integer, i As Integer
Dim wksSrc As Worksheet, wksDest As Worksheet
Dim lngRow As Long

Set wksSrc = ThisWorkbook.Worksheets("Scénarios de menace")
Set wksDest = ThisWorkbook.Worksheets("Analyse de risque S")

wksDest.Range("A6:AP1000").Delete
wksDest.Range("A6:AP1000").ClearContents 'Works directly, without selection

lngRow = 6
LastRow = wksSrc.Range("A" & wksSrc.Rows.Count).End(xlUp).Row

For i = 2 To LastRow

  If wksSrc.Cells(i, 1) = "X" Then
    wksSrc.Range(wksSrc.Cells(i, 2), wksSrc.Cells(i, 20)).Copy
    wksDest.Range("B" & lngRow).PasteSpecial xlPasteValuesAndNumberFormats
    Application.CutCopyMode = False
    lngRow = lngRow + 1
  End If
Next i
end sub

A: This version is optimized (not using a For loop)
Option Explicit

Public Sub refreshAnalyse()
    Dim ws1 As Worksheet, ws2 As Worksheet, lr1 As Long

    Set ws1 = ThisWorkbook.Worksheets("Scénarios de menace")
    Set ws2 = ThisWorkbook.Worksheets("Analyse de risque S")

    ws2.Range("B6:AP" & ws2.Cells(ws2.Rows.Count, 2).End(xlUp).Row).Clear
    lr1 = ws1.Cells(ws1.Rows.Count, 2).End(xlUp).Row

    Application.ScreenUpdating = False
        ws1.Range("A1:A" & lr1).AutoFilter Field:=1, Criteria1:="x"
        ws1.Range("B2:AP" & lr1).SpecialCells(xlCellTypeVisible).Copy

        ws2.Range("B6").PasteSpecial Paste:=xlPasteValuesAndNumberFormats
        ws1.Range("A6:A" & lr1).AutoFilter
        ws2.Activate: ws2.Cells(1, 1).Activate
    Application.ScreenUpdating = True
End Sub


text:
Q: simple recursion acting oppositely so I'm currently working on a method that should print elements in a list in the forward direction but they are printing in the opposite direction.
for example, if my word that's supposed to be printed is p, e, p, p, e, r what's coming out is r, e, p, p, e, p (which is pepper backwards).
here is my code
 private void replace(RecursList<E> List, int positionChosen,
     int index){

  if(positionChosen >= list.elements.size()+1) return;

  if(index <= this.elements.size()) {

     this.elements.set(positionChosen,  list.elements.get(index));
     replace(list,++positionChosen, ++index);

     return;
  }
}

when I call replace().toString() (I omitted the parameters here) it prints backwards. I know It's not my toString() method because it works for everything else so it must be the structure of my recursive call. any insights as to what might be wrong?
this is my to string method
private String toStringHelper(ArrayList<T> elements, int index){
  if(index>=elements.size())return "";

  String s = toStringHelper(elements, index+1);

  if(index < elements.size()-1) s+=", ";

  s+=elements.get(index).toString();

  return s;
}

A: Your problem is in the toStringHelper method.  The lines String s = toStringHelper(elements, index+1); followed by s+=elements.get(index).toString(); are constructing the answer by appending the current element behind the answer based on all the stuff after it.
Change the concatenation to s = elements.get(index).toString() + s;, i.e., prepend rather than append the current element (and comma).


text:
Q: Incomplete Serial Port Read C# I'm trying to read bytes from a scanner hooked up to a COM port into a byte array.  The Serial Port library in C# already has a Read function, this is the function I use to attempt a read.  I have it setup so that the bytes read in are output to the console.  I'm working with a protocol that is very predictable so I know what kind of byte array I am expecting when I pass that line in the code.  However, if I run the program, I only get a single byte read in.  If I re-run that same instance of the program (by sending the same read command) I get the rest of the expected bytes.  Only after I run this a third time do I get all of the bytes I'm expecting.  This problem is completely avoided though if I simply insert a breakpoint over the read line and step over that line.  If I do this, I get a complete read every time.  My question is, how can I get a complete read every time without inserting a breakpoint?  I've tried using the System Pause approach to halt the execution and let the COM port scan fast enough, which did not work.  I've also tried using a thread (see code below).  This also did not work.  Any suggestions?
    t = new Thread(() => device.Read(buffer));
    t.Start();
    t.Join();

Again, my expected output only comes in a full-packet after re-sending the Read command a few times or by stepping over the above commands with a breakpoint.  Otherwise I get my expected output in small "byte sized samples."  Any help is appreciated!

A: This is expected behaviour with byte streams.  Loop round the read and pump however many bytes received one-by-one into your ProtocolUnit class instance, (or whatever), until it is complete and verified.

A: I recently posted a similar question found here:
SerialPort.DataReceived Returning Strange Results
The problem is, as you know, the program tries to read from the buffer without any guarantee that the device is finished issuing whatever command it's running. My advice is to implement the first answer in this post:
Reading from the serial port in C#
My implementation is as follows in the DataReceived event:
void serialPort_DataReceived(object s, SerialDataReceivedEventArgs e)
    {
        byte[] data = new byte[serialPort.BytesToRead];
        serialPort.Read(data, 0, data.Length);
        Console.Write(System.Text.Encoding.UTF8.GetString(data));
    }

And just to wire it up in the code:
serialPort.DataReceived += serialPort_DataReceived;

A: The best approach to put in while loop and also give 10 millisecond of sleep time in between of byte read. This will give 10 milliseconds to scanner to write data on COM port. Actually, Problem happens when you connect scanner in network port.
You can also write delegate or event which will notify when data is completely read from scanner.


text:
Q: Is an atomic action supposed to be deterministic? I was reading about the at most once property that defines what an atomic action is and I've been curios about this example:
x = 0, y = 0
x = y + 1 || y = y + 1

If we use the 'at most once' definition, we can say that, indeed, x = y + 1 is atomic because

*

*y is only referenced in an another thread and

*x is not being read by any thread

But the result of this action is not deterministic, it could be 1 or 2 depending on which operation is being computed first.
I might be wrong from the start, isn't atomicity suppose to grant some kind of determinism?

A: What is the "at most once" property? If you're discussing the definition of a term, I think it would be most useful to provide it.
As far as I understand it, an atomic action is supposed to guarantee that only two of the possible states are observable: either the action is carried out or it isn't. The operation is not divisible. This is supported by the page over at Wikipedia.
It seems to me that you are making an assumption in your post that some arithmetic or logical operation is atomic, but under general conditions this assumption is false.

A: If you are sharing variables across multiple threads with no thread safety then you're going to have a bad time when it comes to determinacy.
First up. Atomic actions are deterministic unto themselves.
x = y + 1, will always yield you the value of y +1, whatever y happens to be at the time of execution. At a system level, the result of this statement is a possible race condition due to y being updated in a different thread.
This isn't technically a case of "non determinism", as would be if you were to do
x = y + 1 * rand() (without using a set seed). This is more of a straight up race condition because you're making assumptions about the state of variables that may or may not be correct.
The reality of this situation is "dont do that". Dont use shared variables across threads. Copy input information into threads, copy information out. Always ensure that your threads have the data they need to do their work, and ensure they never need to reach outside their local threadspace to do it.
If you absolutely completely and utterly need to hit shared data, you must use synchronization primitives, but it makes things a hell of a lot simpler if you adopt a paradigm where threads do not hit shared memory except to deposit results.
And at that point you can use things like lockless queues and other wonderful bits and pieces to avoid the whole lock/unlock procedure.
For information purposes. if you absolutely must share y between threads. I would advise using a gate style write lock to block access to y while it is being written to by the other thread. all other times y will be able to be read immediately as the gate would be "open" to readers.

A: Yes and no.
Yes, an atomic action should always produce the same result given the same inputs.
No, a set of atomic actions, executed in parallel will not necessarily produce the same overall result. When steps are executed in parallel, the input(s) to a particular step may vary, in which case its output(s) may change accordingly.
Atomic actions are necessary but not sufficient to produce deterministic results.

A: There is no order guaranteed with multithreading, y = y + 1 may be run before or after x = y + 1, which would change the result.
Atomicity avoids any "intermediate" state in a variable. For example, if y is 64-bits long on a 32-bit system, setting it to a value is not naturally atomic, since the processor has to first set the lower 32 bits, then the upper ones. Reading y from another thread in that case would mean that there's a possibility that you'll get a version of y with only the lower 32 bits set.

A: Deterministic is not part of the definition of Atomic, in Computer Science.  It is that simple.  This is a good thing; separation of concerns is as important in CS definitions as in software design.
Why would you want to dictate that all atomic actions be deterministic?  Very few applications can be entirely deterministic, and while it is good practice to isolate the non-deterministic functions, what would you gain by not allowing them to be atomic?

A: Atomic comes from the greek word "Atomos" which means indivisible.
In computer science this commonly refers to an operation which can only ever succeed or fail, or a datatype that can be fully read or written without failure.
In any sufficiently complex device, such as the realm of programming, there are any number of failures modes which aren't accounted for (such as sudden power outages, RAM failure etc.)
This means that any kind of "Atomic" behaviour in modern computing is going to have multiple well defined limits when it comes to determinism. Modern CPUs purposely don't always fully account for time due to caches etc. (we have interrupt timers for that) and this issue is magnified as race conditions when it comes to thread interaction (like in your example).
Many modern RDBs offer the practical illusion of Atomicity using transactions on SQL queries, these guarantees are only offered in so far, that, if it is possible to roll back the changes, the DB will do so. If any part of the system is disrupted, all bets are off.
Of course, it is possible to make hardware and software systems which may come closer to a pure definition of Atomic processes. Think of the "black box recorder" in Airplanes.


text:
Q: Hide seperator when response is empty I am trying to select the address, zipcode, city and country of my customers from the database. I want to show these columns in one column. So I am using CONCAT_WS to select the address details of my customers:
SELECT CONCAT_WS(', ', address, zip, city, country) AS address2 FROM customers

When there is data in my table I get the correct response:
Street, 1234, City, Belgium

When there is no data, The statement shows only the comma`s:
, , , Belgium

I want to hide these commas if there is no data. Does someone know how I can hide these commas?

A: CONCAT_WS() ignores NULLs, but it does not ignore empty strings like ''. These are not the same thing in MySQL.
To work around this, you can use the NULLIF() function. This returns NULL if its two arguments are equal.
SELECT CONCAT_WS(', ',
    NULLIF(address, ''),
    NULLIF(zip, ''),
    NULLIF(city, ''),
    NULLIF(country, '')
  ) AS address2 FROM customers


text:
Q: PHP Cronjob Why doesn't this OAuth request POST my twitter status I have a quite specific question here.
I have been working with Cronjobs to get my Twittermessages automatically POSTed. I found the OAuth library by Abraham Williams.
This is what I did so far on my setup:
require_once ('Abraham/TwitterOAuth/autoloader.php');
use Abraham\TwitterOAuth\TwitterOAuth;

$consumerKey        = "XXXXX"; //add the key from your app
$consumerSecret     = "XXXXX"; //add the secret from your app
$accessToken        = "XXXXX"; //add the access token from your app
$accessSecret       = "XXXXX"; //add the access secret from your app
$message            = "This is another Test";

$connection         = new TwitterOAuth($consumerKey,$consumerSecret,$accessToken,$accessSecret);

$connection->post("statuses/update", array("status" => $message));

My question is here. If I load this into my browser, shouldn't this already automatically send a Tweet?
I have setup my own Twitter app and I also set all permissions to read and write.


text:
Q: Как вернуть в return разные типы данных? Только начинаю изучать Java. Задача про кварталы года, столкнулся с проблемой:
если вводить не валидные значения, что лучше всего возвращать? Хотел изначально вернуть "invalid data", но там тип int, поэтому решил вернуть просто 0.
Как бы вы решили эту задачу с return
Буду благодарен за советы :)
Код:
public static void main (String args[]){

    System.out.println(quarterOf(1));     // First quarter
    System.out.println(quarterOf(4));    // Second quarter
    System.out.println(quarterOf(7));    // Third quarter
    System.out.println(quarterOf(10));     // Fourth quarter
}

public static int quarterOf(int month) {
    if (month >0 && month <=3)
        return 1;
    else if(month >3 && month <=6)
        return 2;
    else if(month >6 && month <=9)
        return 3;
    else if(month >9 && month <=12)
        return 4;
    else
        return 0;
}

A: Это типичная задача и для нее есть много решений в зависимости от того, что именно Вы решаете.
Классическое решение, которое взяли и Вы - сделать некоторое магическое значение, которое будет означать ошибку. А что бы оно не было таким магическим, это можно завернуть в константу (final:) ).
Второе хорошее решение - бросать исключение. Хорошая часть этого - ошибку сложно  проигнорировать в отличии от магического значения. Но некоторые люди не любят исключения. Мне этот способ нравится, особенно, если это идет проверка пользовательского ввода, данных много и не хочется запутаться в сотнях if.
Следующий способ - возвращать не просто int (или что Вам нужно), а завернуть его в отдельный класс (или к примеру в Optional). Преимущество такого способа - теперь можно вернуть не просто "ошибка", а ( в случае своего класса) и некоторые детали ошибки. Я видел, как люди в Java делают свой class Int, у которого есть булевый признак "валиден". И потом его везде используют. И при попытке доступа к данным, когда они не установлены, можно просто бросать исключение. Кому исключения не нравятся - можно проверить валидность ручками. Я такой способ часто использую (правда не в java).
Если посмотреть на Go, то там очень похожая система. Только там с функции возвращается две переменные и одна с них результат, а другая признак успешности.
Ну и для особых случаев, когда все сильно запущенно, можно поступить по "ООП" - делаем базовый класс для результата и несколько наследников в зависимости от результата (ошибка - это тоже результат). У этого способа есть один большой минус - при неправильном подходе появляется куча мест, где происходит проверка типа. Вот этого нужно сильно-сильно избегать.


text:
Q: javascript function doesn't get called The following html-webpage contains a button. If you click the button contained in the page, the color of the button is supposed to turn red (according to the js-code). However, it does not work and I do not understand why it does not work.
In fact, nobody around me understands why it doesn't work. If somebody knows what's going on, please help me!

    <!DOCTYPE html>

Please click the button below, it will turn red.

            <button type="button" onclick="myFunction(this)">Set background color</button>

UPDATE: the above code works, sorry for this. I had simplified my original code before posting it here. My goal was to reduce the code to the essential part.
Below you find the original code. If I press the button twice, it is supposed to turn green. However, it stays red. And I don't understand why.
<!DOCTYPE html>

Please click the button below, it will turn red.

        <button type="button" onclick="setColor(this)">Set background   color</button>

A: The first time you click it, lastField is null, so the background is set to red and lastField is set to the element.
The second time you click it, lastField is the element, so the background is set to green … then the background is immediately set to red and lastField is set to the element.
The third and subsequence times are identical to the second time.
You need an else in there.


text:
Q: Java Supplier/Consumer/Runnable? How to invoke method when it is supplied as a a string argument I need a help. User supplying method with its arguments as a string. My code need to run this method.
How we can we achieve this using Supplier/Consumer/Runnable. This can be done using reflection but I want to avoid it.
import java.util.Scanner;

public class InvokeStringArgument{
    public static Supplier<String> invokeMe(String returnStr){
        return new Supplier<String>(){
            public String get(){
                System.out.println("Success");
                return returnStr;
            }
        };
    }

    public static void main(String[] args){
        //invokeMe("MyValue").get();

        System.out.println("Please enter method to invoke:");
        Scanner sc = new Scanner(System.in);
        String methodName = sc.next();
        //Need a code which will run the method when passed as a string
        //For example user input it as invokeMe("MyValue")
    }
}

A: Ok, got some time today to look into these pending things. Achieved solution which at this time confirms to my requirement. Used BeanShell and reflection to get this done as below
package beanshell;

import java.util.Scanner;
import java.util.function.Supplier;

import bsh.EvalError;
import bsh.Interpreter;

public class InvokeStringArgument{
    public static Supplier<String> invokeMe(String returnStr){
        return new Supplier<String>(){
            public String get(){
                System.out.println("Success: Received string '"+returnStr+"'");
                return returnStr;
            }
        };
    }

    public static void main(String[] args) throws EvalError {
        //invokeMe("MyValue").get();

        System.out.println("Please enter string to evaluate:");
        Scanner sc = new Scanner(System.in);
        String userInput = sc.next();

        Interpreter i = new Interpreter();

        Object evalSource = i.eval("public class EvalUserInput extends beanshell.InvokeStringArgument{"
                + "public void evaluserInput(){"
                + userInput+""
                + "}"
                + "}");
        try{
            Class<?> noparams[] = {};
            Class<?> cls = (Class) evalSource;
            Object obj = cls.newInstance();
            cls.getDeclaredMethod("evaluserInput", noparams).invoke(obj, null);
        } catch(Exception e){

        }
    }
}

From the console:
Please enter string to evaluate:
invokeMe("MyValue").get();
Success: Received string 'MyValue'