text:
Q: keep user logged in ios app swift I have made app which include login and signup functionality. When I run my app at that time login and other functionality everything is going ok but when I stop my app and run it again login page showing again can I make user logged in when again app launch. Below is my code which I have used in my app.
override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(true)

    let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
    let isLoggedIn:Int = prefs.integerForKey("ISLOGGEDIN") as Int
    if (isLoggedIn != 1) {
        self.performSegueWithIdentifier("goto_login", sender: self)
    } else {
        self.usernameLabel.text = prefs.valueForKey("USERNAME") as? String
    }
}

import UIKit

@UIApplicationMain

class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

        // Override point for customization after application launch.

        /*

        var rootViewController = self.window!.rootViewController

        let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main" , bundle: nil)

        var isUserLoggedIn:Bool = NSUserDefaults.standardUserDefaults().boolForKey("isUserLoggedIn")
        if(!isUserLoggedIn){
            var loginViewController = mainStoryboard.instantiateViewControllerWithIdentifier("loginview") as! LoginViewController

            window!.rootViewController = loginViewController
            window!.makeKeyAndVisible()

        }else{
            var protectedPage = mainStoryboard.instantiateViewControllerWithIdentifier("profail") as! ProfailViewController
            window!.rootViewController = protectedPage
            window!.makeKeyAndVisible()

        }

        */

        return true
    }

    func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {

        return true
    }
}

A: In "didFinishLaunchingWithOptions" method check for user already logged in or not, if yes that set the ProfailViewController to window rootViewController
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    let isUserLoggedIn:Bool = NSUserDefaults.standardUserDefaults().boolForKey("isUserLoggedIn")
    if(isUserLoggedIn) {
        let mainStoryboard = UIStoryboard(name: "Main" , bundle: nil)
        let protectedPage = mainStoryboard.instantiateViewControllerWithIdentifier("profail") as! ProfailViewController
        window!.rootViewController = protectedPage
        window!.makeKeyAndVisible()
    }
    return true
}

A: Within AppDelegate:-
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.
    let userLoginStatus = UserDefaults.standard.bool(forKey: "isUserLoggedIn")

if(userLoginStatus)
{

    let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    .
    .

}

Within LoginViewController(Where you have placed business logic for login validation):-
UserDefaults.standard.set(true, forKey: "isUserLoggedIn")
UserDefaults.standard.synchronize()

Within OtherViewController(Where IBAction for Logout is kept):-
   UserDefaults.standard.set(false, forKey: "isUserLoggedIn")
   UserDefaults.standard.synchronize()


text:
Q: cookieService.deleteAll() deletes all cookies except this one Image

I have two angular apps one running at localhost:4200 and other on localhost xampp it is laravel angular app.
Clicking on a link in the first app opens the link to the second app where the user is authenticated based on a token. There is a logout button in the first app which should logout user from the second as well the first app and for that, I need to clear all cookies.
The laravel_session cookie is set by the second app when the user clicks on a link from the first app.
The last cookie laravel_session stays while all the others get deleted.
import { CookieService } from 'ngx-cookie-service';

constructor( private cookieService: CookieService )

logout(){
    this.cookieService.deleteAll();
}

A: You are trying to delete an Http Only cookie from your client code.
It's simply not possible.
Using the HttpOnly flag when generating a cookie helps mitigate the risk of client-side script accessing the protected cookie.
Therefore, if the HttpOnly flag (optional) is included in the HTTP response header, the cookie cannot be accessed through client-side script

A: In the development environment localhost; any client side app using Angular or other UI frameworks will need to tweak the server session cookie code as below.
Note: On your backend server you need to turn the cookie setting for httpOnly to False as below code
cookie: {
       secure: false, //set this to true in production over https
       httpOnly: false, //set this to false in development to test delete
       ....
       ....
}

Later, in your Angular service/component code for logout method use as below:
logout(){

this.cookieService.delete('<your-cookie-name>', '/', 'localhost', false, 'Lax');

}

See ngx-cookie-service documentation
For individual delete:
delete( name: string, path?: string, domain?: string, secure?: boolean, sameSite: 'Lax' | 'None' | 'Strict' = 'Lax'): void;

For Batch delete:
deleteAll( path?: string, domain?: string, secure?: boolean, sameSite: 'Lax' | 'None' | 'Strict' = 'Lax' ): void;

Important: On production both should be set as True | httpOnly & Secure | for a Cookie

redpajama_set_name: RedPajamaStackExchange


text:
Q: MATLAB eig(A,B) of a positive semi-definite matrix pair (A,B) gives complex eigenvalues A and B both are 151 by 151 psd matrices, I want to solve the generalized eigenvalue proplem
A * v = Lambda * B * v
when using MATLAB function eig()
[V,D] = eig(A,B)
I get complex numbers in both V and D.Why did this happen and is it possible to avoid it?


text:
Q: Retrofit change multipart entries Content-Type I'm using Retrofit 2, and I have following method in my service:
@Multipart
@POST("avatar.ashx")
Call<ResponseBody> getAvatar(@Header("Authorization") String auth,
                             @Part(value = "l", encoding = "8bit") String login,
                             @Part(value = "p", encoding = "8bit") String password);

The server is expecting request with parts with
Content-Type: text/plain; charset=UTF-8

But what retrofit produces in request is
Content-Type: application/json; charset=UTF-8

Is there any way to change the Content-Type?

A: Maybe someone needs that, so I will post workaround I've found:
Method in my service:
    @Multipart
    @POST("avatar.ashx")
    Call<ResponseBody> getAvatar(@Header("Authorization") String auth,
                             @PartMap() Map<String, RequestBody> requestData);

And usage of the method:
    LinkedHashMap<String, RequestBody> requestData = new LinkedHashMap<>();
    RequestBody rb;
    rb = RequestBody.create(MediaType.parse("text/plain"), getSettings().getUserName());
    requestData.put("l", rb);
    rb = RequestBody.create(MediaType.parse("text/plain"), getSettings().getPassword());
    requestData.put("p", rb);
    mCall = getAvatarApiService().getAvatar(auth, requestData);


text:
Q: is there a way to combine multiple jupyter notebooks into one? i am trying to combine multiple jupyter notebooks into one.
for instance, copy the content of nb1.ipynb and nb2.ipynb to nb_all.ipynb.
I've searched jupyter doc.
there seems to be not an existing api to do this.
any clues?

A: nbmerge allows you to do that (install via pip)
nbmerge nb1.ipynb nb2.ipynb > nb_all.ipynb


text:
Q: How do I remove the indent in the output returned by CodeCogs? This is the output when I use print code (in CodeCogs) in one line:

If I do the same with multiple lines, this is the output:

How do I remove the indent on the first line?

A: *

*My assumption is that the tool is not made for multi-line equations.

*See here for a solution in LaTeX.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Welcome to Overleaf --- just edit your LaTeX on the left,
% and we'll compile it for you on the right. If you open the
% 'Share' menu, you can invite other users to edit at the same
% time. See www.overleaf.com/learn for more info. Enjoy!
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\documentclass{article}
\usepackage{amsmath}
\title{Amsmath example}
\author{Overleaf}
\date{May 2021}
\begin{document}
\maketitle
\section{Introduction}
\begin{align*}
2x - 5y &=  8 \\
3x + 9y &=  -12
\end{align*}
\end{document}


text:
Q: How to read Whatsapp email file in R? Whatsapp has an option to email the group conversation to yourself. I did that and now want to explore it in R. The problem is that it seems to have multiple separators which I don't know how to handle in R.
Here is what I tried:
library(readr)
library(dplyr)
> gf <- read_delim('df.txt', col_names = F, skip = 2, delim='\t')
Warning message:
15 problems parsing 'df.txt'. See problems(...) for more details.
> head(gf)
Source: local data frame [6 x 12]

       X1       X2                           X3 X4 X5 X6 X7 X8 X9 X10 X11 X12
1  9:14pm  Mar 31                  umair: Great       NA NA NA NA  NA  NA  NA
2  9:14pm  Mar 31              umair: I am back       NA NA NA NA  NA  NA  NA
3  9:15pm  Mar 31                     umair: ??       NA NA NA NA  NA  NA  NA
4 10:27pm  Mar 31      umair: Kon kon zinda hay       NA NA NA NA  NA  NA  NA
5 10:49pm  Mar 31   Kazim: Sab zinda hain .....       NA NA NA NA  NA  NA  NA
6 10:50pm  Mar 31              umair: Very good       NA NA NA NA  NA  NA  NA

Can you help me read this file so that the "sender:message" is separated into 2 columns? And the first 2 columns are read as separate columns as shown. Obviously I don't want columns X4 to X12.
Edit:
Here are the first few lines of the raw file:
9:14pm, Mar 31 - umair: Great
9:14pm, Mar 31 - umair: I am back
9:15pm, Mar 31 - umair:
10:27pm, Mar 31 - umair: Kon kon zinda hay
10:49pm, Mar 31 - Kazim: Sab zinda hain .....
10:50pm, Mar 31 - umair: Very good
10:52pm, Mar 31 - umair: Abid agaya dobara?
10:54pm, Mar 31 - Kazim: Nai wo nai aya
10:54pm, Mar 31 - umair: Hmmmmmmmmm

A: This question is old, yet when I wanted to do the same thing, my google search lead me here. I figured it out and put it into an R package. Install and read in the data:
devtools::install_github("JBGruber/rwhatsapp")
library(rwhatsapp)
gf <- rwa_read("df.txt")

Or you can directly paste in the lines
> lines <- c(
  "9:14pm, Mar 31 - umair: Great",
  "9:14pm, Mar 31 - umair: I am back",
  "9:15pm, Mar 31 - umair:  ",
  "10:27pm, Mar 31 - umair: Kon kon zinda hay",
  "10:49pm, Mar 31 - Kazim: Sab zinda hain .....",
  "10:50pm, Mar 31 - umair: Very good",
  "10:52pm, Mar 31 - umair: Abid agaya dobara?",
  "10:54pm, Mar 31 - Kazim: Nai wo nai aya",
  "10:54pm, Mar 31 - umair: Hmmmmmmmmm"
)
> rwa_read(lines)
# A tibble: 9 x 3
  time                author text
  <dttm>              <fct>  <chr>
1 2018-03-31 21:14:13 umair  Great
2 2018-03-31 21:14:13 umair  I am back
3 2018-03-31 21:15:13 umair  " "
4 2018-03-31 22:27:13 umair  Kon kon zinda hay
5 2018-03-31 22:49:13 Kazim  Sab zinda hain .....
6 2018-03-31 22:50:13 umair  Very good
7 2018-03-31 22:52:13 umair  Abid agaya dobara?
8 2018-03-31 22:54:13 Kazim  Nai wo nai aya
9 2018-03-31 22:54:13 umair  Hmmmmmmmmm


text: Q: The distance it will take a car to reach a certain speed, constant acceleration In 10 seconds car can accelerate to 100km/h. Let's say acceleration is constant, calculate the distance it will take the car to reach 90 km/h after leaving a built-up area where it was moving 60km/h. $60\frac {km}{h}=16\frac{4}{6}\frac{m}{s}$$90\frac {km}{h}=25\frac{m}{s}$I calculated acceleration using $a=\frac {Vp-Vk}{t}=\frac {27\frac{7}{9}-0}{10}=2\frac{7}{9}$$t=\frac{Vk-Vp}{a}=3$and distance using $s=\frac {V1+V2}{2}\cdot(t2-t1)=\frac {16\frac{4}{6}+25}{2}\cdot3=[62\frac{1}{2}m]$I think I got everything right but the result is slightly off, it should be [61,8m] (according to notes)$s=Vp\cdot t+\frac{a\cdot t^2}{2}$ gives me the same result What am I doing wrong?


text:
Q: Why doesn't ps aux show *everything*? I recently had a problem with sluggish computer and I live in the terminal, so for me, when something's running slow, "top -o cpu" and "ps aux" are my bread and butter.
However, I recently came to realize "ps ax" or "ps aux" or even "sudo ps aux" does not report everything that is running!  Here's a screenshot
09:19:59:4.x >> sudo ps aux | grep ruby
mwlang          56026   0.0  0.0  2432784    544 s000  S+    9:20AM   0:00.00 grep ruby

while "top -o cpu" shows many more ruby processes than ps revealed:
PID    COMMAND      %CPU      TIME     #TH    #WQ  #PORT #MREGS  MEM    RPRVT  PURG   CMPRS  VPRVT  VSIZE  PGRP  PPID  STATE    UID  FAULTS      COW       MSGSENT     MSGRECV     SYSBSD
98759  ruby         97.0      146 hrs  4/1    0    26    2166    6746M- 6690M- 0B     4912M+ 14G    16G    98759 95937 running  501  1825673706+ 433946    27876       21          3657509626+
56121  top          30.6      00:37.98 1/1    0    32    50      4556K  4424K  0B     992K   81M    2440M  56121 56065 running  0    141726+     77        37015730+   18507741+   61005+
65751  firefox      26.5      27:21:28 327    2    1620  127495+ 665M+  494M+  0B     2072M- 2097M+ 6568M+ 65751 209   sleeping 501  337985127+  7365361   1438232150+ 728384120+  1310190547+
0      kernel_task  24.7      17:30:56 114/8  0    2     2264-   1554M+ 42M    0B     0B     353M   15G+   0     0     running  0    230799      0         2395811265+ 2205539103+ 0
67397  VirtualBoxVM 9.5       14:16:44 33     2    414   3388    3752M- 3749M- 0B     311M+  3966M  6906M  67397 67389 sleeping 501  5936410+    1677      33684108+   9575366+    1482333672+
66114  iTerm2       3.9       37:01.21 15     7    300+  3953    69M-   52M-   0B     383M+  3754M- 6384M  66114 209   sleeping 501  34791264+   482207    2951194+    2480745+    19502768+
155    WindowServer 0.8       03:38:00 6      2    548   8392    41M-   8652K- 6240K  297M+  289M-  3931M  155   1     sleeping 88   414771723+  180974    712680590+  322777826+  22182449+
53761  ruby         0.4       52:23.73 4      0    25    199     35M+   35M+   0B     136M-  229M   2622M  53761 38807 sleeping 501  65088356+   295       517         14          402881351+
53760  ruby         0.4       52:07.68 4      0    25    204     84M+   84M+   0B     82M-   219M   2612M  53760 38807 sleeping 501  57778074+   297       547         14          402886484+
88414  ruby         0.4       22:43.84 4      0    29    285     26M+   26M+   0B     104M-  202M   2582M  88414 88413 sleeping 501  40989091+   13357     455         15          181255583+
52438  ruby         0.3       52:04.74 4      0    25    198     34M+   33M+   0B     132M-  221M   2614M  52438 13687 sleeping 501  61304412+   292       563         14          404946477+
98760  ruby         0.3       28:41.28 4      0    22    212     26M+   26M+   0B     140M-  202M   2591M  98760 1894  sleeping 501  50362241+   292       332         14          214106774+
98761  ruby         0.2       29:14.84 4      0    22    220     69M+   69M+   0B     102M-  217M+  2606M  98761 1894  sleeping 501  51711254+   289       366         14          214109097+
16594  ruby         0.2       37:33.18 4      0    23    172     19M+   19M+   0B     127M-  201M   2586M  16594 91713 sleeping 501  54332633+   14464     611         12          225383424+
91714  ruby         0.2       42:44.88 4      0    23    170     22M+   22M+   0B     117M-  191M   2576M  91714 91713 sleeping 501  51527159+   663       669         12          253234882+
56139  Atom         0.2       00:01.70 29     2    306   418     26M-   25M-   32K    29M+   355M-  3486M  56139 209   sleeping 501  41846       1829      6374+       2383+       24316+
67389  VBoxSVC      0.2       21:02.13 15     1    174   150     1164K  1004K  0B     27M    114M   2498M  67389 1     sleeping 501  1644959+    466       75656222+   28298673+   121873928+
72668  ruby         0.1       15:01.58 4      0    22    170     16M+   16M+   0B     101M-  159M   2549M  72668 71643 sleeping 501  37670120+   306       308         14          90096237+
94786  Dropbox      0.1       15:56.10 102    2    376   1276    15M-   15M-   0B     138M+  788M   4249M  376   1     sleeping 501  6420536     2758      1205105+    180822      68686708+
103    hidd         0.1       17:53.13 4      1    103   61      684K   456K   0B     5928K  98M    2456M  103   1     sleeping 0    298514      131       78071816+   41250277+   3510198
...

EDIT: After reading the comments, I continued sleuthing.  I finally realized I just needed to drop the "grep ruby" and see just what was reported altogether without filtering.  It turns out "ruby" is being spawned or forked from another app, called "spring" so for example the above ruby job with PID 98759 top would be reported by ps as:
09:25:41:~ >> ps ax | grep 98759
98759   ??  Rs   8807:46.18 spring app    | 4.x | started 189 hours ago | test mode
56180 s001  R+     0:00.00 grep 98759

I'm still a bit surprised top and ps would not have the same COMMAND reported.  Is this a "feature" of OSX or does Linux behave the same?


text:
Q: related items in loop creates many duplicate queries Rendering a page gets really slow when related objects are requested in a template.
class Item(models.Model):
   name =  models.CharField(max_length=160)
   ...

class Box(models.Model):
   ...
   items = models.ForeignKey(Item, on_delete=models.CASCADE, null=True)

#template
{% for item in items %}
   {{ item.box_set.first }}
   {{ item.box_set.latest }}
{% endfor %}

Debug toolbar shows there many duplicate queries.
Why is this happening? Is there a way to speed this up?

A: The Django ORM has to make a request to the database when accessing a related field unless it's already cached. The main ways of caching the related objects are via select_related and prefetch_related.
What you're trying to do is a bit more difficult; you're trying to get two specific items from a collection. You can use .annotate() and Subquery to pull singular fields from a related model. This would be useful if you just wanted to display single field from box, but if you need the whole box instance this won't work.


text:
Q: "Reference package not found. Device Connectivity Component" when delopying C# program to Windows Mobile 6.5 device I'm working on a C# project for windows mobile 6.5 and as of this morning I'm getting "Reference package not found. Device Connectivity Component" whenever I try to deploy.
It builds without errors and was working up until today. I did a bit of looking around and only found dead ends online. As far as I can see there are no clues about that component or package this is a reference to. I think it may be related to Windows CE SQL Compact but that's based on nothing. I've rolled back to an earlier version of my code and cleaned a few times. I'm stumped.
I would greatly appreciate any help even diagnosing this a bit further. I'm using Visual Studio 2008 3.5 SP1

Update: When I disable "Deploy latest version of the .NET Compact Framework (including Service Packs)" it does deploy but then throws errors related to the SQL database which worked previously. assumedly because it doesn't have access to the correct SQL packages.
Update: I also get the same error with the emulator, it builds, the emulator starts but can't deploy, giving the same error.
Update: I think this might have something to do with it. Note the double slashes in the path. I keep removing them. It keeps coming back.

Update/Correction: I can now deploy to the emulator, I had a problem before but it seems to be ok now. I still can't beploy to the device, same error.

A: For anyone who was pulling their hair out like me. I couldn't figure out what was wrong although I still suspect it was something to do with the .NET compact package. Eventually I created a new project, set up the references and copied and pasted the code over. It's not a nice solution but it worked after days of being stuck.

A: HA! I found it! This may not be your solution, but this was how I did it.
See this REF: http://msdn.microsoft.com/en-us/library/aa983326(v=vs.90).aspx
Since Microsoft is bad about deleting their old info, I'm going to post it here, too. But basically, if you select a Private Deployment, then Microsoft Updates will not influence your project or update your 3.5 databases to ...whatever the newest stuff from Microsoft is.
How to: Deploy a SQL Server Compact 3.5 Database with an Application
You have two deployment options for applications that contain SQL Server Compact 3.5 databases. The method of deployment you choose depends on the servicing requirements of your application and whether your users will need administrative credentials on the computer on which the application will be installed.
Following are the deployment options for SQL Server Compact 3.5 databases:

*

*Traditional Microsoft Windows Installer (Microsoft setup technology)

*

*Users need administrative credentials to install the application.

*SQL Server Compact 3.5 will be serviced by Microsoft Update.

*Can use ClickOnce deployment.

-or-

*

*Private file–based deployment (deploying the SQL Server Compact 3.5 DLLs as part of the project)

*

*Users do not need administrative credentials to install the application.

*SQL Server Compact 3.5 will not be serviced by Microsoft Update.

*Can also use ClickOnce deployment.

Traditional Windows Installer
Traditional Windows Installer technology is used in both standard Setup and Deployment projects and in ClickOnce deployment. When you deploy a SQL Server Compact 3.5 database, ClickOnce deployment provides an option that automatically installs SQL Server Compact 3.5 if it is not detected on the target computer. For this reason, ClickOnce is the preferred method of deployment for applications that include SQL Server Compact 3.5 databases (as opposed to creating a custom action in a Setup and Deployment project).
ClickOnce deployment has been updated so that it automatically includes the SQL Server Compact 3.5 runtime as a prerequisite for applications that include SQL Server Compact 3.5 databases. It also recognizes .sdf files as data files and sets these to the correct publish status.
Creating a ClickOnce deployment for an application that contains a SQL Server Compact 3.5 database consists of configuring the proper publish information in the Project Designer.
To use Windows Installer technology for ClickOnce deployment of an application that contains a SQL Server Compact 3.5 database

*

*To open the Project Designer, in Solution Explorer/Database Explorer, double-click My Project if you are working on a Visual Basic project (or Properties if you are working on a C# project).

*Click the Publish tab.

*Click Application Files and set the .sdf file to Data File (Auto). (This setting notifies the installer to treat this as a local data file and to put it in the Data Directory.)

*Click Prerequisites and select SQL Server Compact 3.5. (This setting notifies the installer to check whether the SQL Server Compact 3.5 runtime exists and to install it from the Internet if it is not found.)
Creating the Installer After the publish information is configured, create the installer.
To create the installer

*

*In the Publishing Location box, type the Web site, FTP server, or file path to publish the installer to.

*Click Publish Now to create the installer.

The application is ready to be installed. Go to the location you published to, and install the application to verify.
Private File-Based Deployment
Private file–based deployment refers to the process of including the required SQL Server Compact 3.5 DLLs as files in the project (as opposed to a reference to DLLs already on the target computer). If you include the necessary DLLs with the application, the requirement to install SQL Server Compact 3.5 is removed. Therefore, the administrative credentials are no longer needed.
You can use ClickOnce deployment technology for private file–based deployment. If you do, you must remember to clear the SQL Server Compact 3.5 prerequisite so that the Setup program does not install it.
To deploy a SQL Server Compact 3.5 database by using private file–based deployment

*

*To open the Project Designer, in Solution Explorer/Database Explorer, double-click My Project if you are working on a Visual Basic project (or Properties if you are working on a C# project).

*Click the Publish tab.

*Click Prerequisites and then clear the check box for SQL Server Compact 3.5.

*Close the Project Designer.

*Go to the directory that contains the SQL Server Compact 3.5 DLLs. These are located in C:\Program Files\Microsoft SQL Server Compact Edition\v3.5.

*Select the seven SQL Server Compact 3.5 DLLs and copy them:

*

*sqlceca35.dll

*sqlcecompact35.dll

*sqlceer35EN.dll

*sqlceme35.dll

*sqlceoledb35.dll

*sqlceqp35.dll

*sqlcese35.dll

*Paste the DLLs into the project in Solution Explorer/Database Explorer.

*Select all seven DLLs in Solution Explorer/Database Explorer and open the Properties window.

*Set the Copy to Output Directory property to Copy if newer. (This will replace any earlier DLLs in an existing application with the newer ones if the application is updated.)

*Click the Show All Files button in Solution Explorer/Database Explorer.

*Expand the References node.

*Select System.Data.SqlServerCe.

*Set the Copy Local property to True. (Because your development computer has the SqlServerCe DLLs in the global assembly cache, you must configure the application to use the DLLs in the output directory.)

*Right-click the project in Solution Explorer/Database Explorer and select Publish to open the Publish Wizard.

*Complete the wizard to publish the application.

The application is ready to be installed. Go to the location you published to, and install the application to verify.

A: I had the same problem.  I got it to work by closing visual studio, renaming the directory:

C:\Documents and Settings\\Local Settings\Application
  Data\Microsoft\CoreCon

Then reopening visual studio and the deploy worked.


text:
Q: How to import third party react library in ruby on rails I want to use react-infinite-scroller in a rails project. And I followed these two links https://github.com/reactjs/react-rails/issues/510#issuecomment-207790440
http://rmosolgo.github.io/blog/2016/05/19/how-i-use-sprockets/
Here is what I did:

I imported it using //= require ./vendor/InfiniteScroll-v1.0.0
in application.js and I used it like this:
 <InfiniteScroll pageStart={0}>
      <ContentTable
        data={this.state.tableData}
        filterText={this.state.filterText}
        onUserClick={this.handleUserClick}
        dataType={this.props.dataType}
        showPublic={this.state.publicCheckbox}
      />
 </InfiniteScroll>

But there is still an error "ReferenceError: InfiniteScroll is not defined". What should I do to make it work?

A: There is code missing here. How did you reference it? I can't see how you referenced it, so I will take an educated guess.
The error is saying you did not reference it correctly.
This link should serve as a clue:
https://github.com/seatgeek/react-infinite
and this one:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError


text:
Q: Revoke token generated by UserTokenProvider in ASP.NET Identity 2.0 Is there a way to revoke for example an email conformation token generated by an usermanager in ASP NET Identity 2.0?
Context
I would like to give the user the possibility to resend an confirmation email. To do this I generate a new token with: UserManager.GenerateEmailConfirmationTokenAsync(user.Id), and send an email with the new generated token. Unfortunately when I do this the previously generated tokens are still working, is there a way to revoke them?
Example code
In the UserManager class:
manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(options.DataProtectionProvider.Create("ASP.NET Identity"));

In the AccountController:
var user = await UserManager.FindByEmailAsync("email");

// All generated tokens below will work to confirm the email.
// I only want the last token to be valid when confirming the email address.
var token1 = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
var token2 = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
var token3 = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
var token4 = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
var token5 = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

var result = await UserManager.ConfirmEmailAsync(user.Id, token5);

Information about the storage location of the generated token and how these tokens are generated are also welcome!
I will be grateful if you can send me this information.

A: The default UserTokenProvider generates tokens based on the users's SecurityStamp, so until that changes(like when the user's password changes), the tokens will always be the same, and remain valid.  So if you want to simply invalidate old tokens, just call
manager.UpdateSecurityStampAsync();


text:
Q: Coproducts and direct products Is the arbitrary direct sum of modules a submodule of their coproduct?
Ie is $\underset{i \in I}{\coprod} M_i \cong \underset{i \in I}{\bigoplus} M_i$... if not then if each $M_i$ where to be isomorphic whould the isomorphism hold?

A: The direct sum of modules is their coproduct.
In general the underlying set of a coproduct of modules is not the coproduct (i.e. disjoint union) of their underlying sets.
(It doesn't make sense to talk about $\coprod_{i \in I} M_i$ as being a module until you endow it with the structure of a module.)


text:
Q: Python Requests library GET/POST gives ConnectionError: HTTPConnectionPool with proxy I'm using the Python library Requests to write an API wrapper for my company's server software. I'm writing a test script using Python 2.7 on Windows 7 64. We use a proxy to connect to my work network, we'll call the IP x.x.x.x:8080. My script is as follows:
import requests

ssHost = 'localhost'
ssPort = 3700
aci_Action = 'GetStatus'

aci_params = {'Action':aci_Action}
aci_RequestUrl = 'http://' + ssHost + ':' + str(ssPort)

aci_response = requests.get(aci_RequestUrl, params=aci_params)

print(aci_response.text)

This is supposed to send a GET request to http://localhost:3700/Action=GetStatus and it works fine when I'm on my work network. However, when I get home and I am not using a proxy to connect, I get the following when I run the script:

ConnectionError: HTTPConnectionPool(host='x.x.x.x', port=8080):
  Max retries exceeded with url: http://localhost:3700/?Action=GetStatus
  (Caused by : [Errno 10060] A connection attempt
  failed because the connected party did not properly respond after a
  period of time, or established connection failed because connected
  host has failed to respond)

I'm sure I've turned off the proxy using the settings in Internet Explorer but I'm still getting this error. The thing is, the proxy address that the error displays is an old one that I don't use anymore. I'm trying to figure out where this proxy is set. There are things going on here that I don't understand and if anyone can point me in the right direction as far as troubleshooting I would be grateful. Thanks!

A: Double-check the proxy settings in the Internet Options, and also check if an environment variable http_proxy exists.


text:
Q: Run multiple commands in individual terminal tabs I'm developping some rails apps on Mac 10.8.5, and often times, I have a terminal window with a few tabs running commands:
rails s
rails c
mongod
bundle exec guard start
each of which in its own tab. when I switch project, I have to close them all and when I return to this project, I have to rerun these commands all over again. Is there a shortcut or another terminal tool that I can use to run them all in a prepackaged way?
Thank you!

A: To run the commands in the bachground you can use the & operator. For example you can use
myfirstcommand &

and it gives you the pid of the process.
If you want to have the log of each command, you can pipe the output of each command, and use the tail command to watch the log whenever you want to:
myfirstcommand  & >> myfirstlog
mysecondcommand & >> mysecondlog

and whenever you want to watch the log of each one you can use the tail like following:
tail -f myfirstlog

or
tail -numberoflines myfirstlog


text:
Q: How to set limits (1 or 2) When wanting a random number? I am attempting to create a method where a user predicts if a simulated coin toss will be heads or tails. I am having trouble getting the random number to assign to just 1 or 2 (for heads of tails). I believe my attempt(code below) is giving me 0, 1 and 2.
public static void coinToss(String call){
        //setting up random
        Random random = new Random();

        //set user guess to numeric value
        int guessNo=0;

        if (call.equalsIgnoreCase("heads")){
            guessNo=1;
        }else if (call.equalsIgnoreCase("tails")){
            guessNo=2;
        }else System.out.println("Invalid. Enter either heads or tails");

        //setting result for coin toss
        **int result = random.nextInt(2);**
        System.out.println("Trace: numberic result is:" + result);

        //if...else statement to print results of coin toss
        if (result==1){
            System.out.println("Result: heads");
        }else if (result==2){
            System.out.println("Result: Tails");
        }else System.out.println("Invalid result");

        if (guessNo==result){
            System.out.println("Guess Correct");
        }else System.out.println("Guess incorrect");

    }//method end

I am a relative java newbie (obviously!) so Many thanks in advance for any help!

A: The answers suggesting adding one to the nextInt(2) result are correct, but may not be the right long term strategy. In many ways, Java prefers sequences of numbers to start, whenever possible, at 0. For example, array index values run from 0 through length-1.
It may be better to change your internal encoding of the heads/tails to use [0,1] rather than [1,2], and use the nextInt result directly.

A: int result = (random.nextInt(2))+1; is what you might want to try.

A: As documented, Random::nextInt supplies a random number between 0 (inclusive) and the specified upper limit (exclusive). You must therefore first obtain a random number from the range [0,2> and then add 1 to that.


text:
Q: Can 'The Beloved Farmer' achievement be obtained even if you're married? So there's this achievement 'The Beloved Farmer' which requires you to reach a 10-heart friend level with 8 people. I'm not sure if you're still required to give bouquets to people when you're at a 8 heart level with another person to reach 10 hearts (since that's how you reach 10 hearts with a prospect romance/future spouse).
Would it still be possible to reach 10 hearts with others even if you're married?

A: It is still possible to reach 10 hearts with all other Stardew Valley residents, which does not require giving them a bouquet. After marriage, your significant other will be able to have up to 13 of 12 hearts.
Oddly enough, you are still able to give bouquets to other marriageable candidates after marrying with no direct consequences that I've been able to observe.


text:
Q: Procedure Returning Blank Data Table from ASP.NET I'm having issues with a stored procedure I'm attempting to run from an ASP.NET console application.
This is how I'm attempting to get the results in the code:
public static DataTable PerformStoredProcedure(int PracticeID, string CommandName)
    {

        DataTable dt = new DataTable();

        try
        {
            using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["DbConnString"].ToString()))
            {
                conn.Open();

                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = CommandName;
                    cmd.Parameters.AddWithValue("@practiceID", PracticeID);

                    using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                    {
                        da.Fill(dt);
                    }
                }

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    for (int j = 0; j < dt.Rows[i].ItemArray.Length; j++)
                    {
                        Console.Write(dt.Rows[i].ItemArray[j] + ",");
                    }
                    Console.WriteLine();
                }
            }
        }

After the procedure is run I get returned with a blank data set with no errors. However, when I run the procedure in SQL Server Management Studio I works just fine.
You may notice I don't use the new SqlCommand() constructor when initiating the SqlCommand cmd. That is because the query is enormous and takes a while to run so I figured it was a timeout issue.
Following the suggestion here, I made the following class in order to adjust the execution timeout limit.
class CommandFactory
{
            public static int CommandTimeout
            {
                get
                {
                    int commandTimeout = 0;
                    var configValue = ConfigurationManager.AppSettings["commandTimeout"];

                    if (int.TryParse(configValue, out commandTimeout))
                        return commandTimeout;

                    return 120;
                }
            }

Figured I'd include that just to avoid confusion about whether the SqlCommand was being initialized correctly. After that adjustment, I began getting the issue where the command returns a blank data table. I assumed it could have to do with the minimum capacity of the data table dt, so I adjusted that as you can see in the original code.
I've done additional research and made the suggested fixes that are suggested to no avail:
1. Set nocount on
2. Use data adapter instead of data reader
3. This is the most detailed answer. There are several suggestions made with in the forum but the eventual resolution has to do with views being used by the database as a default and blocking access to desired data. I have already confirmed with our DBA that we do not do this.
Like I mentioned before, the query encompassed in the stored procedure is enormous and I haven't included it here because of its sheer size and because this post is long enough as it is. Again, I did confirm that the procedure is working in SSMS.
I also haven't included an example result set because the data contains restricted information.
I appreciate any help you can give.
UPDATE:
I added another method that calls a stored procedure to see if the problem was particular to the particular procedure being called. That second stored procedure also returned a blank data table so the problem is not specific to either procedure. (I also confirmed the second procedure was working and returning rows in SSMS)
That led me to believe there was something wrong with the app.config file for that project. I then added a third method that called a stored procedure on another project in the solution. However, even that returned a blank data table.
Figured I'd provide clues as I happen upon them.

A: You're quite close. Here are a few pointers:

*

*The SqlConnection is never opened. You need to call .Open() in order
for the connection to be established.

*If you set
a breakpoint on the .Fill() line and hover over the DataTable
object, it will appear as if the DataTable is empty (as you've seen), but .Fill() actually fills the Rows of the DataTable for you
automatically (see MSDN). I bet that if you loop through the Rows, you'll find
that your query has actually been returning data all along.

*You could use using statements which automatically call .Dispose() for you as well as close the SqlConnection.

Here's an updated version of your method:
public static DataTable getAllModifiedChargesToday(int practiceID)
{
    DataTable dt = new DataTable();

    try
    {
        using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["DbConnString"].ToString()))
        {
            conn.Open();

            using (SqlCommand cmd = conn.CreateCommand())
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "ch_getAllModifiedChargesToday";
                cmd.Parameters.AddWithValue("@practiceID", practiceID);

                using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                {
                    da.Fill(dt);
                }
            }
        }
    }
    catch (Exception ex)
    {
        LogError(ex);
    }

    return dt;
}

And here's a test you can run to view the data returned:
for (int i = 0; i < dt.Rows.Count; i++)
{
    for (int j = 0; j < dt.Rows[i].ItemArray.Length; j++)
    {
        Console.Write(dt.Rows[i].ItemArray[j] + ",");
    }
    Console.WriteLine();
}

Also, you mentioned setting a timeout... I usually set my in my connection string, like so:
"Server=SERVER;Database=DATABASE;User ID=USER;Password=PASSWORD;Trusted_Connection=False;Asynchronous Processing=true;Timeout=60;"

You don't need that extra CommandFactory class at all, and you don't need to set a MinimumCapacity (MSDN) unless you are really trying to optimize performance and have a guesstimate of how many records will be returned. This property isn't used very often.


text:
Q: Laggy youtube videos I have problem with youtube videos. I am using lubuntu 22.04. My specs of laptop are
CPU: amd e350 dual core 1.60 GHZ
Graphics: Ati radeon hd 6310
RAM: 6gb
Everyting other works fluently, surfing on the net, etc... but just youtube videos making problem. It's not smooth as on windows for example. I mention that while i am watching videos, sound is going ok, but videos making problem. I am using Chrome on Lubuntu instead of Mozilla. I installed ubuntu-restricted-extras package, mesa repository etc..., and i really haven't idea what could be problem. I also tried to play youtube videos via VLC, but it's the same result, even worse. So any suggestions will be helpfull and i will be gratefull.
Thanks in Advance.
Mihajlov Nenad. :)

A: For YouTube playback via the browser on the E-350, an extension like h.264ify and making sure gpu acceleration for video decoding is enabled for the browser can help. A player like MPV is recommended though.
Regards,


text:
Q: Add a new page to Volttron Central I have a standalone HTML page with jQuery. The jQuery is used to do AJAX call to the Python backend. I need to integrate it with Volttron Central. I have looked at the documentation but there is no section talking about this. I think it would be nice to have this kind of info in the doc.
My current approach is to convert the backend Python to be a Volttron agent but I don't know how to integrate the front end HTML page with VC.
Any suggestion where to start? Thanks.

A: When you have an agent that is going to register its own endpoint you should do that during the onstart signal.  The following was extracted from the volttron central agent.  It shows how to register an endpoint that is dynamic(uses volttron rpc as the endpoint) as well as static(where the html is simply served).  I have removed the un-necessary bits for this example.
onstart volttron central code
For clarity MASTER_WEB and VOLTTRON_CENTRAL are unique identifiers for those specific agents running on the volttron instance.
@Core.receiver('onstart')
def _starting(self, sender, **kwargs):
    """ Starting of the platform
    :param sender:
    :param kwargs:
    :return:
    """

    ...

    # Registers dynamic route.
    self.vip.rpc.call(MASTER_WEB, 'register_agent_route',
                      r'^/jsonrpc.*',
                      self.core.identity,
                      'jsonrpc').get(timeout=30)

    # Registers static route.
    self.vip.rpc.call(MASTER_WEB, 'register_path_route', VOLTTRON_CENTRAL,
                      r'^/.*', self._webroot).get(timeout=30)

Since you added the route onstart you should also remove it when the agent is stopped. onstop referenced code
@Core.receiver("onstop")
def stopping(self, sender, **kwargs):
    '''
    Release subscription to the message bus because we are no longer able
    to respond to messages now.
    '''
    try:
        # unsubscribes to all topics that we are subscribed to.
        self.vip.pubsub.unsubscribe(peer='pubsub', prefix=None, callback=None)
    except KeyError:
        # means that the agent didn't start up properly so the pubsub
        # subscriptions never got finished.
        pass


text:
Q: Eclipse : Converting a project to Dynamic Web Project Run on server option is not displaying in eclipse .
The solution for it that i found is " check Project properties / Project Facets / Dynamic Web module" .
For this we need to unlock utility module and then check Dynamic Web Module.
But , Utility module is also necessary for Java EE Application. So how to select both Utility and Dynamic Web Module to make it Dynamic Web Project so that we can get Run On server Option.
Note : I have already copied necessary things in .project file and files in .settings folder.
Update
Its not a maven project. Actually utility Module is already checked in the project Facet.
The problem is that I am not getting "Run On Server"optionto run the project .to get this i need to make it a "Dynamic Web Module" .
As utility Module is already checked so i need to unlock it to check "Dynamic Web Module". Now, I cant check "Dynamic Web Module" as "utility Module" is already checked and both cant exist at same time.
If I uncheck Utility Module and check "Dynamic Web Module" then after clicking apply button I get Error "Failed in uninstalling the Utility Module".
So still left with same "utility Module" checked & "Dynamic Web Module" unchecked.
and not got the "Run On Server" Option.


text:
Q: It is possible to secure my react-native application from MITM attacks? I wish I could protect my application from MITM attacks over HTTPS, I know I can use HPKP to protect the application.
Is it possible to do this from react-native?

A: There is a package that seems to implement certificate pinning: https://github.com/localz/react-native-pinch. I haven't used it too extensively so I cannot comment on how convenient it is.
There's also a long write-up at How can I implement SSL Certificate Pinning while using React Native that walks you through implementing this yourself, based in part on https://github.com/Kudo/react-native-ssl-pinning-proposal.


text:
Q: I want to run a for loop that creates a list, then loops to scan for changes to it in a 2nd list I have a pre-existing condition so I am trying to find a vaccine, many of the websites say "check back for updates" this checks for changes in the site hash and sends an email when a change is detected. I found an old python 2 script that checked for a change in a site, it would print that to the console, so I adapted it to Python 3 (successfully!) and added code to send an email (successfully!) but now I want it to do the whole thing to a list of URLs, and I am struggling (this is the first real piece of code I have ever worked on, I'm halfway through the Udemy Python Masterclass).
I want it to iterate through a list of URLs with a for loop, put all of the url hashs into a list, then wait 60 seconds, do it again, and compare the 2 lists, if one of the sites has a change, I want that URL emailed to me. I know I am close but I would truly appreciate some help <3 I think it all works except for the code around the 2 #TODO comments.
def get_hash(current_url):  # this function works
    opener = urllib.request.build_opener()
    opener.add_headers = [('User-agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11')]
    response = opener.open(current_url)
    the_page = response.read()
    return hashlib.sha224(the_page).hexdigest()

current_hash = get_hash()  # This works - Get the current hash, which is what the website is now.

while True:  # run forever, I am struggling below here...
    for provider in providers_list:  # Loops through URL list
        provider_url = provider  # set the current URL to a variable
        provider_hash_1 = get_hash(provider_url)  # set changed provider url to variable

        # TODO: define the old vs new somehow

        providers_hash_1 = []
        providers_hash_2 = []

        # TODO: I'm STRUGGLING

        # email everyone in list the provider url, everything after this works.
        if provider_hash_2 != provider_hash_1:  # get hash of url(i) != previous_hash(i)
            print("{0} changed at {1}".format(provider_url, datetime.datetime.now()))
            # send email
            context = ssl.create_default_context()  # creates secure SSL context
            email_message = """\
            Subject: Stay Healthy!

            Try {}""".format(provider_url)
            with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
                server.login("EMAIL@EMAIL.COM", "PASSWORD")
                server.sendmail("SEND_EMAIL@EMAIL.COM", "RECEIVING_EMAIL@EMAIL.COM",
                                email_message)

    time.sleep(60)

NEW CODE BELOW
providers_dict = {
    'provider_url':
        [
            "https://vaccine.heb.com/",
            "https://request.austinregionalclinic.com/",
            "https://www.haysinformed.com/covid-19",
            "https://www.hillcountrymemorial.org/covid-19-updates/",
            "http://www.tsfm.cc/",
            "https://www.bellcountyhealth.org/covid-19_vaccine/index.php",
            "https://www.brookshirebrothers.com/covid-19",
            "https://www.dshs.texas.gov/coronavirus/immunize/vaccine-hubs.aspx",
            "http://www.umhtx.org/patient/covid-10-update/"
        ],
    'provider_cache': [],
    'provider_hash': []
}

provider_cache = {provider_url: None for provider_url in providers_dict}

def get_hash(current_url):
    opener = urllib.request.build_opener()
    opener.add_headers = [('User-agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11')]
    response = opener.open(current_url)
    the_page = response.read()
    return hashlib.sha224(the_page).hexdigest()

while True:
    for provider_url, provider_hash in provider_cache.items():
        current_hash = get_hash(provider_url)  # Get the current hash, which is what the website is now

        # email everyone in list the provider url
        if provider_hash != current_hash:  # get hash of url(i) != previous_hash(i)
            provider_cache[provider_url] = current_hash
            print("{0} changed at {1}".format(provider_url, datetime.datetime.now()))

            # send email

    time.sleep(60)

A: So what you need is some sort of cache to store hashes in. I would suggest that the provider_list and providers_hash_1 & 2 are exchanged for one dictionary.
Say for instance you have a list of providers like:
providers = ["URL://provider1.com", "URL://provider2.com", ...]

Then before entering your end-less while you could do something like the following for initialisation:
provider_cache = {provider_url: None for provider_url in providers}

In the inner for loop, you can now iterate over the items of the dictionary like:
for provider_url, provider_hash in provider_cache.items():
    current_hash = get_hash(provider_url)

    if provider_hash != current_hash:
        provider_cache[provider_url] = current_hash

        [And do whatever else you need to do for notifications, etc.]

Hope this eases the task of making a notification system. Did not want to type up the full solution but rather the headlines.


text:
Q: CSS Parallax Backgrpund Header in Firefox I've wrote a little experiment for a parallax background header using only CSS: http://codepen.io/Kageetai/pen/yIdAq?editors=110
It's works very well in Chrome but in Firefox the header has a strange behaviour, even though Codepen uses -prefix-free. The background images shoves itself on top of the content below and the jumbs after scrolling down a bit.
It uses the technique found here, which I think is very elegant. So I copied most of it and wanted to apply it for a header.
I suppose it has something to do with that part, which mainly makes the parallax happening:
.parallax {
  position: relative;
  //padding: 25vh 10%;
  padding: 0.1px; // strange behaviour with padding 0
  min-height: 100vh;
  width: 100vw;
  box-sizing: border-box;
  transform-style: inherit;
  background: 50% 50% / cover;

   &:before {
    content: "";
    position: absolute;
    top: 0;
    bottom: 0;
    left:0;
    right:0;
    background: 50% 50% / cover;
  }
}

header {
  text-align: center;
  color: whitesmoke;

  &:before {
    background-image: url(http://www.theloftberlin.com/wp-content/uploads/2013/09/2013-berlin.jpg) !important;
  transform: translateZ(-1px) scale(2);
  z-index:-1;
  }
}

And furthermore the fixed navigation isn't fixed at all on Chrome and Firefox.
Anyone any ideas?
Thanks!

A: Add position:relative to your #wrapper that will fix overlapping of image on the text.

A: add z-index="2" to .nav
check the codepen here Code pen


text:
Q: Elastic beanstalk rails application with git source and deploy hooks I want to setup Elastic Beanstalk for my existing rails application.
I was successful in doing the sample foo app.
These are the questions I have
I need the deployment to happen from my git repository and not from my local path where I am deploying. How do I do that for the sample foo app.
The git aws.push command seems to deploy on the new ec2 instance. However, it did not push the changes to my git repository. Should I do a git push separately before doing a git aws.push ? Notice that my branch is ahead by 1 commit when I do a git status.  Does aws maintain a separate git repository ? How can I get it to use my git repository instead ?
[mymac:~/Projects/new/foo(master)]$ git aws.push
Counting objects: 4949, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (1115/1115), done.
Writing objects: 100% (4949/4949), 14.11 MiB | 1.90 MiB/s, done.
Total 4949 (delta 3800), reused 4944 (delta 3798)
remote:
To https://AKIAJZT3WFY2WLO6CHQQ:20121127T030627Zf56675b2f4c9c731ca6f51b11d36a438e8bcee25c5171061ce5ac681495318c9@git.elasticbeanstalk.ap-southeast-1.amazonaws.com/v1/repos/617069/commitid/39396162666436346439656465313537613561343561626465643931393366623762386265303138/environment/6170692d656e76
 * [new branch]      HEAD -> master

[mymac:~/Projects/new/foo(master)]$ git status
# On branch master
# Your branch is ahead of 'origin/master' by 1 commit.
#
nothing to commit (working directory clean)

Below is the result of just a git push.
[mymac:~/Projects/new/foo(master)]$ git push
Counting objects: 5, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 340 bytes, done.
Total 3 (delta 2), reused 0 (delta 0)
To git@github.com:xxxx/foo.git
   885cc33..99abfd6  master -> master

Separately, I need to have a before_symlink deploy hook. How can I do this ?

A: It wasn't clear from your question if you have already tried the git aws.push option. You could refer a blog post on AWSBlog for deploying Rack based applications to AWS Elastic Beanstalk. To summarize the same, you can do it in the following easy steps:

*

*eb init

*eb start

*git aws.push
This, of course, requires you to download AWS Elastic Beanstalk command line tools.
AFAIK, AWS Elastic Beanstalk does not have an integration with Git deploy hooks yet, but it's pretty simple if you are already using a CI Server like Jenkins. Github can very well integrate with most CI servers. You could achieve a git push triggering git aws.push from your CI server by adding a new Jenkins job with custom Shell commands. You may also want to execute a test harness before pushing a fresh build out there. Jenkins or Travis CI will do the job for you!
Regarding the execution of before_symlink type tasks, the way AWS Elastic Beanstalk works is different from a traditional Capistrano deployment. It bundles all your code into an executable archive and simply copies it over to load-balanced nodes. For executing before_symlink like tasks, you might want to write some custom configuration files and place them under .ebextensions in the root path of your Git repository. The way I did it is by adding a .ebextensions/symlink.config file. Here's a sample code for symlinking your database.yml file on the server.
container_commands:
  symlink-db:
    command: ln -sf /var/app/shared/database.yml $EB_CONFIG_APP_ONDECK/config/database.yml

Please note that I am running a custom AMI with a /var/app/shared/ directory which, otherwise, is not present when you launch a vanilla Ruby container. Further, $EB_CONFIG_APP_ONDECK environment variable holds the current deployment directory name (typically /var/app/ondeck) which is moved to /var/app/current once the deployment is through and before restarting the Rails (Passenger) server, thus making it available for serving requests. Read more on Customizing AWS Elastic Beanstalk containers.
Hope this helps.

A: I was able to integrate Travis CI test builds with Amazon Beanstalk deployments. In order to do this i had to automate eb tools, because the current version 2.5.1 only runs in an interactive way, so I edited EB tools code on some python files and then created a .travis.yml file with the appropriate instructions to deploy the app to AWS Beanstalk.
Here is a link to my blog that gives a complete description of the process:
http://www.sysadminops.com/amazon-beanstalk-and-travis-ci-integration/


text:
Q: How to identify and remove newline and white spaces? I am making an nsmutable array by separating a string by component it is causing a lot of new line and white spaces to be inserted in the array how to identify and remove them?
for (int i=0;i<contentsOfFile.count; i++)
 {
        if(!([[contentsOfFile objectAtIndex:i]isEqual:@"\n"]||[[contentsOfFile     objectAtIndex:i]isEqual:@""]))
       [arrayToBereturned addObject:[contentsOfFile objectAtIndex:i]];
 }

this code which i am using cannot identify all new line charectors
thanks

A: To remove all extra space and \n from your string-
NSString* result = [yourString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

than prepare your contentsOfFile Array.

A: If you want an array without whitespace:
NSString *string = @"Hello, World!";
NSCharacterSet *separator = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSArray *stringComponents = [string componentsSeparatedByCharactersInSet:separator];

A: stringByTrimmingCharachersInSet: only removes desired characters from the end and the beginning of the string. To remove all occurences you should use stringByReplacingOccurrencesOfString:

A: Swift 5 version
    let string = "Hello, stack overflow!"
    let components = string.components(separatedBy: .whitespacesAndNewlines)
    print(components) // prints ["Hello,", "stack", "overflow!"]

Also regarding string.replacingOccurrences
    let string = " Hello, stack overflow     ! "
    let noSpacingsString = string.replacingOccurrences(of: " ", with: "")
    print(components) // prints "Hello,stackoverflow!"


text:
Q: why contains keyword is not working on rally api query I am trying to query on rally api by using below
req.Query = new Query("User.ObjectID", Query.Operator.Equals, loggedinUser.ToString()).And(new Query("Role", Query.Operator.Contains, Role).And(new Query("Workspace.ObjectID", Query.Operator.Contains, workspaceID)).And(new Query("Project.ObjectID", Query.Operator.Equals, projectObjectID)));

But it is throwing error as
The operator [ contains ] is not supported for this attribute type. The available operators are [ =, !=, >, <, >=, <=, in ]

is it contains key word is deprecated? please help me alternative in such case.

A: You can't use contains for an object id- that attribute is numeric.  contains is reserved for strings and collections.
It's the Workspace.ObjectID specifically that's ruining your day.  Change it to equals and you should be good to go.

A: As per
https://communities.ca.com/thread/241816885-why-contains-keyword-is-not-working-on-rally-api-query?et=watches.email.outcome
contains no longer supports in such type of queries but previously it is worked.
Its working when I replaced 'Contains' with 'Equals' as
 req.Query = new Query("User.ObjectID", Query.Operator.Equals, loggedinUser.ToString()).And(new Query("Role", Query.Operator.Equals, Role).And(new Query("Workspace.ObjectID", Query.Operator.Equals, workspaceID)).And(new Query("Project.ObjectID", Query.Operator.Equals, projectObjectID)));


text:
Q: MySQL query generating different results on different servers I've set up a custom ORDER BY clause for a query that The Events Calendar using the posts_where filter. It looks like this:
// $compareTimeToday is the result of strtotime('today');
// $compareTimeTomorrow is the result of strtotime('tomorrow');
// MIN(wp_postmeta.meta_value) ultimately fetches the _EventStartDate
// post meta, which is in MySQL format (YYYY-MM-DD H:i:s)
// This query forces events happening today ahead of events that are
// happening today but are multi-day and started in the past
$orderby = "CASE
            WHEN MIN(wp_postmeta.meta_value) BETWEEN FROM_UNIXTIME($compareTimeToday) AND FROM_UNIXTIME($compareTimeTomorrow)
              THEN 1
            ELSE 2
          END ASC, " . $orderby;

Things seemed fine, but the client added a couple of events that did manage to mess this up. After the client added those events, I pulled a copy of the database, so my local database matches the staging on exactly.
On my local environment, here is the result:

So events that started today, and then all other upcoming events in order of date (starting with an event that started in August, in this case). At the bottom of that list is a multi-day event that started yesterday and goes through November, and it's the last event on the site. You'll see it in the next screenshot.
Here's what the staging environment shows:

The item from the bottom of the list is now at the top (undesired).
Why am I getting different results between the two machines on the exact same codeset and database?
Local PHP: 7.1.0
Local MySQL: 5.7.16
Staging PHP: 7.0.2
Staging MySQL: 5.7.18
If I dump date_default_timezone_get() on them, they both show plain 'ol UTC.
Any idea why I'm getting different results between the two?
EDIT: The client's server management team has told me that the staging server itself may be in Eastern time, despite PHP spitting out UTC. If the PHP variables going into the query and the contents of the database are all the same between the two environments, would this matter?

A: Thanks to @Shadow for the right direction. MySQL timezone was indeed America\New York it seems and was running some conversions on FROM_UNIXTIME, while dev is plain 'ol UTC
This is further complicated in that WordPress allows you to set a timezone in the admin, but doesn't force that at the PHP level, and further operates assuming UTC, so you have to set and then reset the timezone when the admin setting is important.


text:
Q: Few xml files in my android studio is showing some weird text Have a Look at my xml file

I don't know why many of my xml files are showing weird text in my android project I tried to uninstall and install the android studio and facing the same problem.
����   4  com/example/hibengaluru/R$menu  java/lang/Object  com/example/hibengaluru/R  menu cart I
 ()V
ConstantValue Code InnerClasses 1


text:
Q: Rails SimpleForm with nested models: submission redirects to parent model I have a User that has_many :recipes. I'm using simple_form, and trying to use a form to create a new recipe. Simple, right? I've looked through a dozen SO questions, and I thought I had fixed all the gotchas, including accepts_nested_attributes_for and everything.
Now, when I submit the form to create a new recipe, it redirects me to the user edit form with errors about the user. Here's the relevant code.
class User < ActiveRecord::Base
  ...
  attr_accessible ..., :recipes_attributes

  has_many :recipes
  accepts_nested_attributes_for :recipes
end

class Recipe < ActiveRecord::Base
  ...
  belongs_to :user

end

And recipes/new.html.haml
= simple_nested_form_for @user do |f|

  = f.simple_fields_for :recipes, @user.recipes do |rf|
    = rf.input :name
    = rf.input :source
    = rf.input :link
    = rf.input :season, collection: %w(spring summer fall winter), prompt: 'Choose season', required: false
    = rf.input :protein, as: :radio_buttons, required: false
    = rf.input :course, collection: ['appeteizer', 'soup', 'dessert', 'entrée', 'side', 'salad'], prompt: 'Choose course', required: false
    = rf.input :featured, as: :boolean, required: false
    = rf.input :directions, as: :text
    .actions
      = f.submit 'Save'
      or
      = link_to 'Cancel', user_recipes_path(@user)

I also tried  = f.simple_fields_for :recipe do |rf|
And here's the new method of RecipesController
  def new
    @user = User.find(params[:user_id])
    @recipe = @user.recipes.build || @recipe.new

    respond_to do |format|
      format.html
      format.json { render json: @recipe }
    end
  end

It looks like it's trying to post to the users controller instead of the recipes controller, which explains why it redirects me to editing a user. Here's the log of the put request:
Started PUT "/users/4" for 127.0.0.1 at 2013-05-19 22:31:07 -0700
Processing by UsersController#update as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"QmCo025nqR9vJt49To1gQ7/edv4MSlvuwHYotEihI2E=", "user"=>{"recipes_attributes"=>{"0"=>{"name"=>"dffd", "source"=>"dfswer", "link"=>"ewrre", "season"=>"", "course"=>"", "featured"=>"0", "directions"=>"werew"}}}, "commit"=>"Save", "id"=>"4"}

I know it is technically a form_for @user, but since it's creating a recipe, how would I make that put go to recipes to create a new recipe? And do I want it to put recipes_attributes, or recipe_attributes? It's for a new recipe, and I tried getting it to accept nested attributes for recipe or recipes (I made the forms match accordingly). I guess I'm confused about that, too.

A: You have created a form for User simple_nested_form_for @user . Thats why the form gets submitted to users_controller.
If you dont have any user related fields in the form, create a form for recipes
form_for([@user, @recipe]) do


text:
Q: How can we write a function List multiPop(int k) that pops k elements from the stack or until the stack is empty? I am trying to write a method that pops k elements from the stack. Any help would be appreciated.
This is what I have tried:
    public void multipop(int k) {
    List l = nil();
    while (true) {
    for(int i =0; i < k; i++) {
    }

A: Translate the following concept in to Java:
create a list to store the popped members in.
while (the stack is not empty and we have to pop more elements) {
    add a popped member from the stack to the list
}
return the list.

Done

A: list multipop(int k, list stack){

   int increment = 0;
   while(stack.next() != null && k < increment){
      stack.pop();
      increment++;
   }
}
return stack;

I'm sorting assuming you have the methods .next() and .pop() already created.


text:
Q: Checking if np.nan is inside an array returns non expected values Why an array element arr[i][j] when equal to nan, is not being validated as np.nan?
I have ran some tests with the variable and was not able to found why that is hapenning.
In : nval
Out: array([  0.,  nan])

In : type(nval)
Out: numpy.ndarray

In : type(nval[0])
Out: numpy.float64

In : type(nval[1])
Out: numpy.float64

In : arr[15][4]
Out: nan

In : type(arr[15][4])
Out: numpy.float64
# Expected True
In : arr[15][4] == np.nan
Out: False

# Expected True
In:  nval[1] == np.nan
Out: False

# Expected True
In:  arr[15][4] == nval[1]
Out: False

# Expected True
In:  arr[15][4] in nval
Out: False

In:  0 in nval
Out: True

# Expected True
In:  np.nan in nval
Out: False

I think all are failing by the same reason, just can't figure out where.
Code:
import numpy as np
import numpy.ma as ma
import matplotlib.pyplot as plt

def spill(arr, nval=[0,np.nan], metric=1):
    m=metric
    narr=np.copy(arr)
    nval=np.asarray(nval)
    for i in range(arr.shape[0]):
        for j in range(arr.shape[1]):
            if arr[i][j] not in nval:
                # This helps to check what is happening
                # print "{0},{1}: {2}".format(i,j,arr[i][j])
                # print narr[i-m:i+m+1:1,j-m:j+m+1:1]
                narr[i-m:i+m+1:1,j-m:j+m+1:1]=arr[i][j]
    return narr

msize=50
rrange=10
jump=10
start=5
dpi=96
h=500
w=500

X,Y=np.meshgrid(range(0,msize),range(0,msize))
dat=np.random.rand(msize,msize)*rrange

msk=np.zeros_like(dat)
msk[start::jump,start::jump].fill(1)
mdat=msk*dat
mdat[mdat==0]=np.nan

# If I run spill over the `mdat` before the np.nan, all works fine
# as expected by the tests above. But I wish to be able to check
# also against `np.nan`.
sdat = spill(mdat)

mmdat = ma.masked_where(np.isnan(mdat),mdat)
smdat = ma.masked_where(np.isnan(sdat),sdat)

print mmdat[5]
# I expected similar output except smdat[5][4] and smdat[5][6] should
# be equal to smdat[5][5].
print smdat[5]

A: Try to use np.isnan according to documentation


text:
Q: basic li rotator displaying two "li"s instead of one I have a simple image slider that rotates through a ul and displays each li one after the other.  Recently, it has started displaying two images instead of one.  It displays images in a pattern of (there are 5 "li"s): none&1, 1&2, 2&3, 3&4, 4&5, and then 1&5, then 1&2, 2&3, and so on. I have an example in the footer of my site here: http://kunkelwe.kodingen.com/Site/?page_id=25/
My code is this:
function fadingSlider(currentListItem, startListItem, fadeInDuration, displayDuration, fadeOutDuration) {
  if(!currentListItem) {
    startListItem.fadeIn(fadeInDuration).delay(displayDuration).fadeOut(fadeOutDuration, function() {
            fadingSlider(startListItem, startListItem, fadeInDuration, displayDuration, fadeOutDuration);
        }); //#webmaster fade in, fade out, then recurse with start
    return;
  }
  else {
    currentListItem = currentListItem.next("li");
    if ((currentListItem.get(0)) === (currentListItem.parent().last("li").get(0))) {
      startListItem.fadeIn(fadeInDuration).delay(displayDuration).fadeOut(fadeOutDuration, function() {
          fadingSlider(startListItem, startListItem, fadeInDuration, displayDuration, fadeOutDuration);
    });
    return;
    }
    else {
        currentListItem.fadeIn(fadeInDuration).delay(displayDuration).fadeOut(fadeOutDuration, function() {
        fadingSlider(currentListItem, startListItem, fadeInDuration, displayDuration, fadeOutDuration);
        });
        return;
    }
  }
}

jQuery(window).load(function() {
  fadingSlider(null, jQuery("ul.sponsorSlider > li:first-child"), 300, 5000, 300);
});

EDIT: I have tried rewriting the script, to make it simpler and possibly eliminate the error, but unfortunately the error is still occurring.  Here's the new version:
function fadingSlider(currentListItem, list, fadeInDuration, displayDuration, fadeOutDuration) {
    if(currentListItem){
        currentListItem = currentListItem.next("li");
    }
    if(!currentListItem || currentListItem.length === 0) {
    currentListItem=list.children("li:first-child");
    }
    currentListItem.fadeIn(fadeInDuration).delay(displayDuration).fadeOut(fadeOutDuration, function() {
        fadingSlider(currentListItem, list, fadeInDuration, displayDuration, fadeOutDuration);
    });
    return;
}

jQuery(window).load(function() {
  fadingSlider(null, jQuery("ul.sponsorSlider"), 300, 5000, 300);
});

and the html is this:

Sponsors

EDIT: I have traced the problem, oddly enough, to the use of jQuery(window).load().  For some reason, this event was firing twice.  I changed it to window.onload and the thing worked like a charm.  I assume this is a bug with jQuery, but it just seems odd.

A: I see in your script 'sponsor.js:'
startListItem.fadeIn(fadeInDuration).delay(displayDuration).fadeOut(fadeOutDuration, function() {
        fadingSlider(startListItem, startListItem, fadeInDuration, displayDuration, fadeOutDuration);

...in that second line, you are passing startListItem in twice, as the next iteration's currentListItem and startListItem. (This happens twice in your code.)
Try this instead:
startListItem.fadeIn(fadeInDuration).delay(displayDuration).fadeOut(fadeOutDuration, function() {
        fadingSlider(startListItem, startListItem.next(), fadeInDuration, displayDuration, fadeOutDuration);

A: Try adding currentListItem into the first parameter like:
...
    currentListItem = currentListItem.next("li");
    if ((currentListItem.get(0)) === (currentListItem.parent().last("li").get(0))) {
      startListItem.fadeIn(fadeInDuration).delay(displayDuration).fadeOut(fadeOutDuration, function() {
          fadingSlider(currentListItem, startListItem, fadeInDuration, displayDuration, fadeOutDuration);
...

EDIT:
you may need to set the old currentListItem as the startListItem like:
startListItem = currentListItem;
currentListItem = currentListItem.next("li");

ALSO:
Why do you have href="" as an attribute of img?

A: Look at what I've used here:
http://ladogana.eu/
http://ladogana.eu/cs_slide.js
It may not be the best way but it works nicely, and could be a good starting point! :D

A: The problem is with jQuery(window).load().  For some reason, this event is firing twice.  Using window.onload instead fixes the problem.


text:
Q: Saving and restoring text when rotating I have seen a few examples on how to achieve this but still I can't get it working.
I followed this example, but the TextView is empty in OnCreate and when I rotate the screen. Here is how I implemented it:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_image_viewer);

    displayFileName = (TextView) findViewById(R.id.displayFileName);

    //Getting the fileName
    Bundle extras = getIntent().getExtras();
    uri = extras.getString("uriAsString");
    Uri myUri = Uri.parse(uri);
    filename = uri.substring(uri.lastIndexOf("/") + 1);
    nameWitoutExtention = filename.substring(0, filename.lastIndexOf('.'));

    //Checking if Text was stored
    if (savedInstanceState != null) {
        CharSequence savedText = savedInstanceState.getCharSequence(KEY_TEXT_VALUE);
        displayFileName.setText(savedText);
    }

}

@Override
protected void onSaveInstanceState (Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putCharSequence(KEY_TEXT_VALUE, displayFileName.getText());
}

What I'm trying to achieve is to set nameWitoutExtention to displayFileName and when the device is rotated to let the text remain.
I got a null pointer on the text and that is why I'm trying this, any help on what I'm doing wrong?

EDIT:
This is how my implementation looks like at the moment:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_image_viewer);

    displayFileName = (TextView) findViewById(R.id.displayFileName);

    if(savedInstanceState != null){
        CharSequence savedText = savedInstanceState.getCharSequence(KEY_TEXT_VALUE);

        //When displaying this toast the correct filename gets displayed
        //Toast.makeText(getApplicationContext(), savedText, Toast.LENGTH_LONG).show();

        displayFileName.setText(savedText+"");
    }
    else{
        //Getting the fileName
        Bundle extrsas = getIntent().getExtras();
        uri = extrsas.getString("selectedStudentVid");
        Uri mUri = Uri.parse(uri);
        filename = uri.substring(uri.lastIndexOf("/") + 1);
        nameWitoutExtention = filename.substring(0, filename.lastIndexOf('.'));
        displayFileName.setText(nameWitoutExtention);
    }

@Override
protected void onSaveInstanceState (Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putCharSequence(KEY_TEXT_VALUE, displayFileName.getText());
}

I have also tried onRestoreInstanceState() as suggested by @PorasBhardwaj
The exception I'm getting is:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference

A: Try using onRestoreInstanceState() callback method to get saved data.
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
 // TODO Auto-generated method stub
 super.onRestoreInstanceState(savedInstanceState);
 CharSequence savedText = savedInstanceState.getCharSequence(KEY_TEXT_VALUE);
 displayFileName.setText(savedText);
}

As per official documentation.

Most implementations will simply use onCreate(Bundle) to restore their
  state, but it is sometimes convenient to do it here after all of the
  initialization has been done or to allow subclasses to decide whether
  to use your default implementation.

So for best practice, keep your view hierarchy in onCreate and restore the previous state in onRestoreInstanceState.

A: Try doing it this way:
//Checking if Text was stored
 if(savedInstanceState != null){
       CharSequence savedText =
      savedInstanceState.getCharSequence(KEY_TEXT_VALUE);
      displayFileName.setText(savedText + "");
 }
else{
 //Getting the fileName
Bundle extras = getIntent().getExtras();
uri = extras.getString("uriAsString");
Uri myUri = Uri.parse(uri);
filename = uri.substring(uri.lastIndexOf("/") + 1);
nameWitoutExtention = filename.substring(0, filename.lastIndexOf('.'));
}

What you are doing wrong is. Whenever the orientation changes it gets the value again from extras which is null after the rotation change and it passes the same value to it. That's why you are getting the exception.
try this hope it will help you.


text:
Q: Get the content of siblings elements with jQuery I need to get the content of some specific elements using jquery, the problem is that i have the same element repeating on my page:

Lorem ipsum dolor sit amet, consectetur adipisicing elit.

Lorem ipsum dolor...

Test

So, the div.content repeat on my page many times and I want to get only the contents of the div that holds the button was clicked. I've added a onclick event on the .uiButton and tried to use parent(".txt") or siblings(".txt"), but dont seems to work...
$(".uiButton").click(function(){
  var txt = $(this).parent(".txt").text();
}

A: .txt isn't a parent, and even then it has to be a direct parent (.parent() matches the immediate parent if it matches the selector), instead you need:
$(".uiButton").click(function(){
  var txt = $(this).closest("ul").siblings(".txt").text();
});

The alternative is to go all the way up to .content (via .closest()) to be safe then traverse down with .find():
$(".uiButton").click(function(){
  var txt = $(this).closest(".content").find(".txt").text();
});

A: You need to go up to the wrapper and down, you can go to siblings, but in this case it will be harder.
$(".uiButton").click(function(){
  var txt = $(this).closest('.content').find('.txt').text();
}

A: $(this).closest('p.txt');

Might work.


text:
Q: How to access a saved image displayed on qlabel using pyqt5? i design a user interface for browsing, and saving an image. i want the user to be able to save it in any desire folder, the read function works fine but the save function after saving the image i get an error on my IDE ( Process finished with exit code -1073740791 (0xC0000409) ),also i am unable to view the saved image from the folder. here is my code
from PyQt5 import QtCore, QtGui, QtWidgets

from PyQt5.QtWidgets import QFileDialog
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
    MainWindow.setObjectName("MainWindow")
    MainWindow.resize(1314, 1327)
    self.centralwidget = QtWidgets.QWidget(MainWindow)
    self.centralwidget.setObjectName("centralwidget")
    self.Read_Button = QtWidgets.QPushButton(self.centralwidget)
    self.Read_Button.setGeometry(QtCore.QRect(70, 140, 75, 23))
    self.Read_Button.setObjectName("Read_Button")
    self.Write_Button = QtWidgets.QPushButton(self.centralwidget)
    self.Write_Button.clicked.connect(self.saveFileDialog)
    self.Write_Button.setGeometry(QtCore.QRect(70, 180, 75, 23))
    self.Write_Button.setObjectName("Write_Button")
self.retranslateUi(MainWindow)
    self.tabWidget.setCurrentIndex(0)
    QtCore.QMetaObject.connectSlotsByName(MainWindow)
    self.Read_Button.clicked.connect(self.setImage)
    #self.Write_Button.setEnabled(True)

def setImage(self):
    fileName, _ = QtWidgets.QFileDialog.getOpenFileName(None, "Read", "", "Image Files (*.png *.jpg *jpeg *.bmp);;All Files (*)") # Ask for file
    if fileName: # If the user gives a file
        pixmap = QtGui.QPixmap(fileName) # Setup pixmap with the provided image
        pixmap = pixmap.scaled(self.imglabl.width(), self.imglabl.height(), QtCore.Qt.KeepAspectRatio) # Scale pixmap
        self.imglabl.setPixmap(pixmap) # Set the pixmap onto the label
        self.imglabl.setAlignment(QtCore.Qt.AlignCenter) # Align the label to center

def saveFileDialog(self, file_name):
    option=QFileDialog.Options()
    option|=QFileDialog.DontUseNativeDialog

    file= QFileDialog.getSaveFileName(None, "Save", "", "All Files (*);;JPG Files (*.jpg);;PNG Files (*.png)" )

    if file[0]:
      print ("File saved as" + file)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())


text:
Q: Как запушить свой массив на работающий сайт? помогите составить такой скрипт
Чтобы он вводил в веб форму путем подбора цифрового кода такого вида от 00000 до 99999 код 5-значный пока не найдет нужный.
Примечания:
Скрипт ввел код нажал ENTER не подошел начал второй вводить и так пока не попадет нужный код
Заранее благодарен за помощь !
Вот то что я сам написал

var arr = [],
    track = [],
    min = 10000,
    max = 99999,
    qty = 10000,
    ii = 0,
    rnd;

while (ii < qty) {
    rnd = Math.floor(Math.random() * (max - min + 1)) + min;
    if (!track[rnd]) {
        arr[ii] = track[rnd] = rnd;
        ii += 1;
    }
}

Заранее спасибо.

A: Написание подобного рода кода очень сильно привязано к сайту, на котором он запускается, поэтому я собрал тестовый стенд и возможное решение задачи

  window.onload= function(){
    // Часть симулирующая работу сайта для проверки работоспособности кода
    let lie = 1;
    document.getElementById("btn").addEventListener('click', function (event) {
      var secretcode = '00078'; // Секретный код, который мы будет подбирать
      if(document.getElementById("input").value==secretcode){document.getElementById("log").innerText="Доступ разрешен"}else{
       document.getElementById("log").innerText="Данный код ошибочный уже "+lie+" раз!";
       lie = lie + 1;
      }
    });
    //////////////////////////////
    // Само решение задачи
    var input = document.getElementById("input");//Находим поле для ввода
    var btn = document.getElementById("btn")//Находим кнопку для отправки сообщения
    var interv;
    document.getElementById("btn2").addEventListener('click', function (event) {
     interv = setInterval(brute,100) //Повторяем функцию, которая будет осуществлять попытку ввода кода
    })
    var num= -1;
    function brute(){//функция, которая вводит код

      num = num + 1;
      var str = num+"";
      var checknumber=''
      if(str.length < 5){
        for(let i = 0; i < 5-str.length; i++){
          checknumber = checknumber + "0";

        }
        checknumber = checknumber + num;
      }else{checknumber = checknumber + num;}
      input.value = checknumber;

      btn.click();//жмем на кнопку отправки

      if(document.getElementById("log").innerText=="Доступ разрешен"){clearInterval(interv)} // прекращаем работу если угадали с кодом
    }
    }
<input type="text" id = "input">
<button id = "btn">Отправить</button>
<button style = "color: red" id = "btn2">Старт</button>


text:
Q: getDeclaredMethods() in Class class public Method[] getDeclaredMethods() throws SecurityException

has documentation as below.
/**
     *
     * Returns an array containing {@code Method} objects reflecting all the
     * declared methods of the class or interface represented by this {@code
     * Class} object, including public, protected, default (package)
     * access, and private methods, but excluding inherited methods.

<p> If this {@code Class} object represents a type that has multiple
             * declared methods with the same name and parameter types, but different
             * return types, then the returned array has a {@code Method} object for
             * each such method.
         *

how can a single class have two [declared] methods with different return types, same name and same parameter types?

A: It's not possible in the Java language to declare two methods with same names and parameter types but different return types.
The Java Virtual Machine (JVM) however has no problem handling methods like that.
There is a way to create such methods implicitly, by overriding a base class method with a more specific return type.
If a base class has a method Object foo() and your class overrides it with a method String foo() then the .class file of your class will have a synthetic (and thus not "visible") method Object foo() and a "normal" method String foo(). The Object foo() method exists for compatibility with classes that want to treat your class as an instance of the base class and don't know about the String foo() override.
Additionally some non-Java languages might let you create classes with those kinds of method explicitly.

A: A simple example:
import java.lang.reflect.Method;
import java.util.concurrent.Callable;

public class MultipleMethods implements Callable<String> {
    public static void main(String[] args) {
        for(Method m: MultipleMethods.class.getDeclaredMethods()) {
            System.out.println(m);
        }
    }

    @Override
    public String call() {
        return "just an example";
    }
}

Test on ideone.com
public static void MultipleMethods.main(java.lang.String[])
public java.lang.Object MultipleMethods.call() throws java.lang.Exception
public java.lang.String MultipleMethods.call()

Due to type erasure, the interface Callable has a method java.lang.Object call() and code trying to invoke that method will look for exactly that method only, therefore, a so-called bridge method has been inserted to fulfill the protocol and delegate to the actual implementation method String call(). You can identify bridge methods via Method.isBridge().
The same kind of bridge methods are created when using covariant return types without Generics, as described by this answer. Also, as already said by this answer, class files could have been created by other means than Java source code and since the JVM can handle methods only differing in return type, such methods could appear in such classes without having bridge semantics.
By the way, on the bytecode level, even declared fields are distinguished by name and type, thus, do not need to have unique names if they differ in type. There is no way to generate class files with declared fields of the same name with Java source code, but, as said, that's not the only way to create class files.

A: You are probably confusing getDeclaredMethod() : Method vs getDeclaredMethods() : Method[] or privateGetDeclaredMethods() : Method[], that have a different name.
However you can have methods with the same name, same return type but different parameters. This is possible because of method overloading in Java.

For simplicity, this is a very legal piece of code:
public class Test {
    public int get(int a) {
        return a;
    }

    public int get() {
        return 0;
    }
}

This isn't:
public class Test {
    public int get() {
        return 0;
    }

    public long get() {
        return 0;
    }
}


text:
Q: How to make image rotation and 3D transform simultaneously? I am working on image editing application(resize, rotation, 3d transform). If I am rotate the image and then make 3D transform. Its going to initial image. Otherwise I am change the 3D transform then make rotation, Its also goes to the initial state.
For image 3D Transform I am using below code :
- (void)moveImage:(UIPanGestureRecognizer *)recognizer
{
        if ([recognizer respondsToSelector:@selector(translationInView:)]) {
            CGPoint translation = [(UIPanGestureRecognizer *)recognizer translationInView:recognizer.view.superview];

            CALayer *layer = self.layer;
            CATransform3D rotationAndPerspectiveTransform = CATransform3DIdentity;
            rotationAndPerspectiveTransform.m34 = 1.0 / 500.0;
            rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, - self.xTranslation / 50.0 * M_PI / 180.0f, 0.0f, 1.0f, 0.0f);
            layer.transform = rotationAndPerspectiveTransform;
            rotationAndPerspectiveTransform.m34 = - 1.0 / 500.0;
            rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, - self.yTranslation / 50.0 * M_PI / 180.0f, 1.0f, 0.0f, 0.0f);
            layer.transform = rotationAndPerspectiveTransform;
        }
 }

For image Rotation I am using below code :
- (void)rotateImage:(UIRotationGestureRecognizer *)recognizer
{
    if (state == RSImageViewStateResizing) {
        recognizer.view.transform = CGAffineTransformRotate(recognizer.view.transform, recognizer.rotation);
        recognizer.rotation = 0;
    }
}

How to I fix this issue. Always welcome your suggestions, sample code, Sample project, any App store applications. Thanks in advance. Any one help me.

A: Use CAAnimationGroup to combine multiple animation into one
CAAnimationGroup *theGroup = [CAAnimationGroup animation];
theGroup.animations=[NSArray arrayWithObject:resizeAnimation, rotationAnimation, 3d transformAnimation];// add here your CAAnimation reference and CATransform3D reference
[layer addAnimation:theGroup forKey:@"animatePosition"];


text:
Q: Is this a good way to store XML data in SQL Server 2008? I'm doing a feasibility study for storing data in the following structure with SQL Server 2008:
-MYTABLE
|ID|RECORDS|BRANCH_OFFICE|MONTH|YEAR

The RECORDS column has the XML data type and it will look like:
<visits>
  <visit id="000112233">
    <costumer>Mr. One Costumer</costumer>
    <date>2011-02-10</date>
    <employee>MAT01234</employee>
  </visit>
  <visit id="000112234">
    <costumer>Mr. Another Costumer</costumer>
    <date>2011-02-12</date>
    <employee>MAT01235</employee>
  </visit>
  <visit id="000112235">
    <costumer>Mr. Some Costumer</costumer>
    <date>2011-02-12</date>
    <employee>MAT01234</employee>
  </visit>
  <visit id="000112236">
    <costumer>Mr. Some Costumer</costumer>
    <date>2011-02-15</date>
    <employee>MAT01235</employee>
  </visit>
</visits>

I'm intending to query the xml column with xquery, is this a good way to store this data?
If I want to get the list of visits occurring in 2011-10, adding a tag with the difference of days between the "date" tag and now, how could it be?

A: A query against your XML could look something like this and I think your structure is just fine. There is no need to do any fancy XML stuff to get the information you need.
declare @T table
(
  ID int identity primary key,
  Records xml
)

insert into @T values('
<visits>
  <visit id="000112233">
    <costumer>Mr. One Costumer</costumer>
    <date>2011-02-10</date>
    <employee>MAT01234</employee>
  </visit>
  <visit id="000112234">
    <costumer>Mr. Another Costumer</costumer>
    <date>2011-02-12</date>
    <employee>MAT01235</employee>
  </visit>
  <visit id="000112235">
    <costumer>Mr. Some Costumer</costumer>
    <date>2011-02-12</date>
    <employee>MAT01234</employee>
  </visit>
  <visit id="000112236">
    <costumer>Mr. Some Costumer</costumer>
    <date>2011-02-15</date>
    <employee>MAT01235</employee>
  </visit>
</visits>')

select T.ID,
       V.X.value('@id', 'nvarchar(10)') as VisitID,
       V.X.value('costumer[1]', 'nvarchar(50)') as Costumer,
       V.X.value('date[1]', 'date') as [Date],
       V.X.value('employee[1]', 'nvarchar(50)') as Employee
from @T as T
  cross apply T.Records.nodes('/visits/visit') as V(X)

Result:
ID          VisitID    Costumer             Date       Employee
----------- ---------- -------------------- ---------- --------------------
1           000112233  Mr. One Costumer     2011-02-10 MAT01234
1           000112234  Mr. Another Costumer 2011-02-12 MAT01235
1           000112235  Mr. Some Costumer    2011-02-12 MAT01234
1           000112236  Mr. Some Costumer    2011-02-15 MAT01235


text:
Q: Erro de lista está nula mas eu estou preenchendo Tenho essa Action em minha controller
[HttpGet]
        public ActionResult Details(AzureDiscountGroupModel modelD)
        {
            var discount = _azureDiscountGroupService.GetAll();
            var list = new ResellerListModel();

            var resellers = _resellerService.QueryAll()
                .Include(r => r.WhiteLabels)
                .ToList();

            foreach(var item in resellers)
            {
                list.Id = item.Id;
                list.Name = item.Name;
                list.Alias = item.Alias;
                list.MpnId = item.ResellerMpnId;
                //list.CreatedOn = item.AcceptContractDate;
                //list.WhiteLabel = item.WhiteLabels
            }

            ViewBag.Desconto = discount.Where(x => x.Id > 0);

            ViewBag.DetailReseller = resellers.Where(x => x.AzureDiscountGroupId == modelD.Id);

            return View(modelD);
        }

Estou preenchendo essa table assim
@foreach (var item in ViewBag.DetailReseller as IEnumerable<ResellerListModel>)
    {

            @item.Name

            @item.Alias

            @item.WhiteLabel

            @item.MpnId

            @item.CreatedOn

    }

No momento em que eu tento preencher, recebo esse erro

System.NullReferenceException: 'Referência de objeto não definida para
  uma instância de um objeto.'

Como faço para iterar por essa model?
EDIT1
Fiz essa alteração, para ver se consigo
[HttpGet]
        public ActionResult Details(AzureDiscountGroupModel modelD)
        {
            var discount = _azureDiscountGroupService.GetAll();
            var list = new List<ResellerListModel>();

            var resellers = _resellerService.QueryAll()
                .Include(r => r.WhiteLabels)
                .ToList();

            foreach(var item in resellers)
            {
                list.Add(CreateListModelFrom(item));
            }

            ViewBag.Desconto = discount.Where(x => x.Id > 0);

            ViewBag.DetailReseller = resellers.Where(x => x.AzureDiscountGroupId == modelD.Id);

            return View(modelD);
        }

e essa aqui
private ResellerListModel CreateListModelFrom(Reseller reseller)
        {
            var model = new ResellerListModel();

            model.Id = reseller.Id;
            model.Name = reseller.Name;
            model.Alias = reseller.Alias;
            model.MpnId = reseller.ResellerMpnId;

            model.WhiteLabel = true;

            var firstWhiteLabel = reseller.WhiteLabels.OrderBy(x => x.CreatedOn).FirstOrDefault();
            model.CreatedOn = firstWhiteLabel.CreatedOn.ToLocalTime();

            return model;
        }

E mesmo assim não consigo iterar pela lista no cshtml
Se faço assim, a lista vem preenchida, mas perco os itens que devem ser mostrados na table
@foreach (var item in ViewBag.DetailReseller as IEnumerable<List<ResellerListModel>>)

Mas se faço assim, dá erro de null
@foreach (var item in ViewBag.DetailReseller as List<ResellerListModel>)

A: Fazendo assim resolveu
[HttpGet]
        public ActionResult Details(AzureDiscountGroupModel modelD)
        {
            var discount = _azureDiscountGroupService.GetAll();
            var list = new List<ResellerListModel>();

            var resellers = _resellerService.QueryAll()
                .Include(r => r.WhiteLabels)
                .ToList();

            foreach(var item in resellers)
            {
                list.Add(CreateListModelFrom(item));
            }

            ViewBag.Desconto = discount.Where(x => x.Id > 0);

            ViewBag.DetailReseller = list.Where(x => x.AzureDiscountGroupId == modelD.Id).ToList();

            return View(modelD);
        }

E na View fiz
@foreach (var item in ViewBag.DetailReseller as List<ResellerListModel>)
    {

            @(item.Name)

            @(item.Alias)

            @(item.WhiteLabel ? "Sim" : "Não")

            @(item.MpnId)

            @(item.CreatedOn)

    }

O método CreateListModelFrom tem por finalidade popular a ResellerListModel


text:
Q: I've made changes to a storyboard after saving a snapshot, now my changes won't reflect when I compile my code. What am I doing wrong? I'm working with xcode 4.2 on a project. I enabled the local git repository on project creation, but hadn't been using snapshots. I decided to make a change that I wasn't sure I wanted to keep, so I stored a snapshot prior to making the code changes.
After making the changes, the running application seems unchanged in the simulator.  The storyboard has changed, replacing some components with others, and these changes aren't even reflected.
I've tried committing the project several times, and it seems to like to recommit my user prefs file each time, however I can't get it to commit the storyboard changes.
Has anyone encountered this? Am I missing something?

A: I've noticed a bug on XCode 4.5, when renaming the storyboard, it gets kind of frozen in time. Any changes after that wont reflect at runtime, not even doing a Clean Build or even removing the app from the simulator or device.
I renamed my storyboard to the old name (MainStoryBoard) and suddenly all my changes were reflected.

A: Try this it worked for me.

*

*go to ~/Library/Developer/Xcode/DerivedData and delete your Application. { appname concatenated {some random number} }

*Reset your Simulator

*Clean your and rebuild it your App

A: You need to clean out the build folder. Command-Option-Shift-K does it.


text:
Q: Is $A-PAP$ positive-semidefinite? I am studying linear algebra.
Let $A$ be a positive-semidefinite matrix and $P$ be a symmetry projection matrix.
I learned that $P$ and $PAP$ are also positive-semidefinite.
I wonder if $A-PAP$ is positive-semidefinite.
I am not able to show it.
Please help.