text:
Q: How to code a BAT file to always run as admin mode? I have this line inside my BAT file:
"Example1Server.exe"

I would like to execute this in Administrator mode. How to modify the bat code to run this as admin?
Is this correct? Do I need to put the quotes?
runas /user:Administrator invis.vbs Example1Server.exe

A: You use runas to launch a program as a specific user:
runas /user:Administrator Example1Server.exe

A: Just add this to the top of your bat file:
set "params=%*"
cd /d "%~dp0" && ( if exist "%temp%\getadmin.vbs" del "%temp%\getadmin.vbs" ) && fsutil dirty query %systemdrive% 1>nul 2>nul || (  echo Set UAC = CreateObject^("Shell.Application"^) : UAC.ShellExecute "cmd.exe", "/k cd ""%~sdp0"" && %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs" && "%temp%\getadmin.vbs" && exit /B )

It will elevate to admin and also stay in the correct directory. Tested on Windows 10.

A: go get github.com/mattn/sudo

Then
sudo Example1Server.exe

A: convert your batch file into .exe with this tool: http://www.battoexeconverter.com/ then you can run it as administrator

A: When you use the /savecred argument, it asks for the password once, and than never asks for it again.  Even if you put it onto another program, it will not ask for the password.  Example for your question:
runas /user:Administrator /savecred Example1Server.exe

A: *

*My experimenting indicates that the runas command must include the admin user's domain (at least it does in my organization's environmental setup):
runas /user:AdminDomain\AdminUserName ExampleScript.bat

If you don't already know the admin user's domain, run an instance of Command Prompt as the admin user, and enter the following command:
echo %userdomain%

*The answers provided by both Kerrek SB and Ed Greaves will execute the target file under the admin user but, if the file is a Command script (.bat file) or VB script (.vbs file) which attempts to operate on the normal-login user's environment (such as changing registry entries), you may not get the desired results because the environment under which the script actually runs will be that of the admin user, not the normal-login user!  For example, if the file is a script that operates on the registry's HKEY_CURRENT_USER hive, the affected "current-user" will be the admin user, not the normal-login user.

A: The other answer requires that you enter the Administrator account password. Also, running under an account in the Administrator Group is not the same as run as administrator see: UAC on Wikipedia
Windows 7 Instructions
In order to run as an Administrator, create a shortcut for the batch file.

*

*Right click the batch file and click copy

*Navigate to where you want the shortcut

*Right click the background of the directory

*Select Paste Shortcut

Then you can set the shortcut to run as administrator:

*

*Right click the shortcut

*Choose Properties

*In the Shortcut tab, click Advanced

*Select the checkbox "Run as administrator"

*Click OK, OK

Now when you double click the shortcut it will prompt you for UAC confirmation and then Run as administrator (which as I said above is different than running under an account in the Administrator Group)
Check the screenshot below

Note:
When you do so to Run As Administrator, the current directory (path) will not be same as the bat file. This can cause some problems in many cases that the bat file refer to relative files beside it. For example, in my Windows 7 the cur dir will be SYSTEM32 instead of bat file location!
To workaround it, you should use
cd "%~dp0"
or better
pushd "%~dp0"
to ensure cur dir is at the same path where the bat file is.

A: I Tested @Sire's answer on Windows 11, and it works like a charm. It's worth mentioning that using cmd /k - as @Sire has used - will keep the Administrator CMD open after it finishes running. Using cmd /c instead will close the window when it's over with the batch file.
set "params=%*"
cd /d "%~dp0" && ( if exist "%temp%\getadmin.vbs" del "%temp%\getadmin.vbs" ) && fsutil dirty query %systemdrive% 1>nul 2>nul || (  echo Set UAC = CreateObject^("Shell.Application"^) : UAC.ShellExecute "cmd.exe", "/c cd ""%~sdp0"" && %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs" && "%temp%\getadmin.vbs" && exit /B )

A: If you can use a third party utility, here is an elevate command line utility.
The source and binaries are available on GitHub.
This is the usage description:
Usage: Elevate [-?|-wait|-k] prog [args]
-?    - Shows this help
-wait - Waits until prog terminates
-k    - Starts the the %COMSPEC% environment variable value and
                executes prog in it (CMD.EXE, 4NT.EXE, etc.)
prog  - The program to execute
args  - Optional command line arguments to prog

A: You can use nircmd.exe's elevate command
NirCmd Command Reference - elevate
elevate [Program] {Command-Line Parameters}

For Windows Vista/7/2008 only: Run a program with administrator rights. When the [Program] contains one or more space characters, you must put it in quotes.
Examples:
elevate notepad.exe
elevate notepad.exe C:\Windows\System32\Drivers\etc\HOSTS
elevate "c:\program files\my software\abc.exe"

PS: I use it on win 10 and it works

A: I found there is possible to use powershell. The powershell will show the default Windows UAC Dialog.
powershell Start -File Example1Server.exe -Verb RunAs

For execute BAT file with admin rights, the content of the BAT file can look as this:
@echo off
if "%1"=="runas" (
  cd %~dp0
  echo Hello from admin mode
  pause
) else (
  powershell Start -File "cmd '/K %~f0 runas'" -Verb RunAs
)

where:

*

*%1 First input argument assigned to BAT file.

*%~f0  expands to full path to the executed BAT file

*%~dp0 expands to full directory path from where the BAT file is executed

*cmd -C <commands> Execute command in terminal and close

A: Use the complete physical drive\path to your Target batch file in the shortcut Properties.
This does not work in Windows 10 if you use subst drives like I tried to do at first...


text:
Q: How to make the div height dynamic How to make the div height dynamic so that it increases the height automatically when data inserted exceed the size of div?

CA Ritesh

 learn how to setup video calls learn how to setup video calls learn how to setup video callslearn how to setup video callslearn how to setup video callslearn how to setup video callslearn how to setup video callslearn how to setup video calls Kandivali, Mumbai Kandivali, Mumbai Kandivali, Mumbai Kandivali, Mumbai Kandivali, Mumbai Kandivali, Mumbai

2 yrs Experience

Open Today

                      0
                      Call

A: You need to use CSS height property to make the div height dynamic.
Use height:auto; Example
And here is a sample of your code.

.caphtdtail {
  border: 2px solid;
  height: auto;
}

CA Ritesh

learn how to setup video calls learn how to setup video calls learn how to setup video callslearn how to setup video callslearn how to setup video callslearn how to setup video callslearn how to setup video callslearn how to setup video calls Kandivali,
        Mumbai Kandivali, Mumbai Kandivali, Mumbai Kandivali, Mumbai Kandivali, Mumbai Kandivali, Mumbai

2 yrs Experience

Open Today

     0
    Call

redpajama_set_name: RedPajamaStackExchange


text:
Q: Running a mpkg installer through python and subprocess.Popen objects I'm trying to run a .mpkg installer on UNIX and when I run this code:
p = subprocess.Popen(['/Path/to/File.mpkg'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
return p

The output is this:
<subprocess.Popen object at 0x11384xxx>

My first question is - Is there an easier way to run a mpkg installer on UNIX?
Secondly - I can't seem to figure out how to use the subprocess.Popen object to my benefit.

A: Sadly I'm not sure what mpkg is, but there are two options.

*

*Either it is a self-running package, perhaps a shell script, akin to the .run format sometimes used for Unix software. In this case, your invocation of Popen is correct, as long as you have the execute permission on File.mpkg (check with ls -l /Path/to/File.mpkg). The installer should be running fine.

*Or, it is intended to be processed by a system tool, like .deb packages are handled with the dpkg program. In this case, you need something like this:
p = subprocess.Popen(['/usr/bin/dpkg', '-i', '/Path/to/File.deb'], ...)

or, alternatively:
p = subprocess.Popen('dpkg -i /Path/to/File.deb', ..., shell=True)

Now, what you do with this Popen object depends on what you want to achieve. If you wish to get the output of the process, you need to call Popen.communicate, like this:
p = subprocess.Popen(
    ['/Path/to/File.mpkg'],
    stdout=subprocess.PIPE, stderr=subprocess.PIPE,
    stdin=subprocess.PIPE)
(out, err) = p.communicate()

Now out contains the standard output and err the standard error.
If you just want to invoke the command and wait until it completes, you can also use the subprocess.call shortcut.


text:
Q: Proving a subgroup is normal from the given conditions The following are definition from Finite Soluble Groups by Doerk and Hawkes.
Defintion 1: A subgroup $H$ of a finite group $G$ is said to be normally embedded in $G$ if each Sylow subgroup of $H$ is a Sylow subgroup of some normal subgroup of $G$.
Defintion 2: A subgroup $H$ of $G$ is said to be pronormal in $G$ if for all $g\in G$, $H$ and $H^g$ are conjugate in $\langle H, H^g \rangle$
Definition 3: A subgroup $H$ of a finite group $G$ is said to be locally pronormal in $G$, if each Sylow subgroup of $H$ is pronormal in $G$.
It is clear from the definitions that a normally embedded subgroup of a finite group is locally pronormal, as Sylow subgroups of a normal subgroup of $G$ are pronormal in $G$.

Proposition: Let $G$ be a finite group and $H$ is normally embedded subgroup of $G$. If $H$ is subnormal in $G$, then $H \unlhd G$

Since $H$ is subnormal in $G$, we may assume that $H \unlhd K \leq G$. Let $P$ be a Sylow $p$-subgroup of $G$. Since $H$ is normally embedded in $G$, it it locally pronormal, and so $P$ is pronormal in $G$. We then get that $G = N_G(P)K$ (follows from properties of pronormal subgroups)
Let $g\in G$. Then $g = ab$ where $a\in N_G(P)$ and $b\in K$. Now $P^g = P^{ab} = P^b \leq H^b = H$. I'm not sure how to proceed to show that $g\in N_G(H)$.

A:
Note: This is an answer to an earlier version of this question.

I don't think this claim is true. Or, some key assumption is missing.
For example, if we select a prime $p$ such that $p\nmid |H|$, then $P=\{1_G\}$.
Hence $N_G(P)=G$, so the assumption $G=N_G(P)K$ holds trivially.
But you have surely seen occasions where $H$ is not a normal subgroup of $G$.
Simply assuming that $P$ is non-trivial is not going to fix this problem. For example, we could have $G=G_1\times P$ and similarly adjust $K,H$ from a counterexample with a trivial $P$.

A: Here is a proof of the proposition in the revised question.
Lemma. If $H$ is subnormal in $K$ and the prime $p$ does not divide $|K:H|$, then all Sylow $p$-subgroups of $K$ are contained in $H$.
I will leave the proof of the lemma  to you. You can do it by induction on the  length of the subnormal chain from $H$ to $K$.
Now suppose that $H$ is normally embedded and subnormal in $G$. Let $P$ be a Sylow $p$-subgroup of $H$ for some $p$. Then $P \in {\rm Syl}_p(K)$ for some $K$ with $H \le K \unlhd G$. Since $H$ is subnormal in$G$, it is subnormal in $K$ and, by the lemma, all Sylow $p$-subgroups of $K$ are contained in $H$.
Now, for $g \in G$, $P^g \in {\rm Syl}_p(K)$, so $P^g \in H$. Since this is true for all Sylow subgroups of $H$, and $H$ is generated by its Sylow subgroups, it follows that $H \unlhd G$.


text:
Q: JavaScript libraries for touch screen devices I know there are a number of frameworks to help make web applications on Mobile Safari/Webkit look and behave like native applications (eg, jQTouch), but are there any more light-weight libraries that help out at a slightly lower-level?
eg, I might want to add some animations on certain touch events to reproduce an iPhone style swipe.
I don't want to create an iPhone web application as such, just enhance an existing site with a few special touch events.
It's not so difficult to create this stuff by directly using the touch events that the device provides, but some of the iPhone animation styles are quite complex to reproduce. eg, the bounce when you get to the end of a scroll bar, etc... Just wondering if anyone has done the work and wrapped it up into an open source library.

A: This doesn't answer your question completely, but since you mentioned bounce scrolling specifically, TouchScroll was just released on Tuesday.

A: I am looking for the same thing, JavaScript frameworks free from IE stuff..
So far
XUI
http://code.google.com/p/xui-js/
SLY
http://github.com/digitarald/sly
Coming Soon
jQuery for touch devices (not jqtouch) http://jquerymobile.com/2010/08/announcing-the-jquery-mobile-project/

A: http://zeptojs.com/ is all you want.
It's jQuery trimmed for webkit mobile. Excellent library with (brand new) great documentation. Handles ajax, dom selection, touch events. Does not have UI components.
Very lightweight.


text:
Q: Calling of move constructor in c++ I have following code:
struct Base
{
    std::vector<int> a;
}

struct Derived : public Base
{
    Derived(Base && rhs):
        Base( std::forward<Base>(rhs))
    {
    }
    //some more fields
}
//...
Base a;
Derived b(std::move(a));

Does calling of Derived constructor will lead calling of move constructor of std::vector that contained in Base class?

A: Yes, the implicitly-defined move constructor of Base is called, it will perform move on its data member a.

For non-union class types (class and struct), the move constructor performs full member-wise move of the object's bases and non-static members, in their initialization order, using direct initialization with an xvalue argument.

LIVE for confirming


text:
Q: Accepting an answer on a migrated question My question, Why is bash everywhere? was migrated to Super User and there is a really good answer there that I would like to accept.
But I seem to have lost control over the question. Is there some way to associate my account with this migrated question so I can accept an answer?

A: *

*create a SU account using your OpenID

*associate your SO account to your SU account (in the 'accounts' tab of your user profile)

*flag the SU question that is "yours" (that was yours on SO) and ask the moderator to associate it with your account.

You could do the same here on metaSO to get ownership of this question as well. :)


text:
Q: Why Admob SDK sample project needs Navigationcontroller to work? I created a new project based on the Admob SDK sample project but stripped out of the rootviewcontroller (UINavigationcontroller). However, it doesn't work.
It keeps on complaining it cannot receieve an Ad from network.
When I runs the original project (using UINavigationcontroller) the ads popped up.
That doesn't make sense!!
And check out admobviewprotocol.h. it says the following. Is admob expects the viewcontroller be returned to UINavigationController?? If I don't have that it won't work? How odd!
// Return the current view controller (AdMobView should be part of its view hierarchy).
// Make sure to return the root view controller (e.g. a UINavigationController, not
// the UIViewController attached to it) .
- (UIViewController *)currentViewControllerForAdAdMobView *)adView;

A: After iOS 5,  building apps without having a root view controller is strongly discouraged. As we can see it in the warning message "Applications are expected to have a root view controller at the end of application launch".
Just like this, AdMob guys too, want a view controller for being able to receive ads from their network.
If your app doesn't have any view controller, you can just silence your GADBannerView with something like this:
GADBannerView *myGADBannerView;
myGADBannerView.rootViewController = [UIViewController new];


text:
Q: Some limit questions around $1$
*

*Does $0.9 \times 0.99 \times 0.999 \times \dots$ have a limit, and if so, what?

*Does $1 \times 1.01 \times 1.001 \times 1.0001 \times \dots$ have a limit and if so, what?

A: Hint: 1. It can also be written as $\prod\limits_{i}{(a_i)}=\prod\limits_{i}{(1-10^{-i})}$ - all numbers $0 < a_i < 1$, therefore it must stop somewhere between 0 and 1.

*It can also be written as $\prod\limits_{i}{(1+10^{-i})}$

For both, write down and try multiplying first few terms, you can observe a generality, it will lead you to the limit!


text:
Q: CI accessing property on interface I'm using scrutinizer to analyze my code. And almost everything has been fixed but I can't seem to fix this issue.
Accessing id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?

I see the problem beceause it's an interface that propery does not exist, but my code works just fine. So how can I let this code pass when I analyze my code?
Thanks
Edit
Got the error on these lines (and some other files are almost the same)
$this->tracert->log(
            'users',
            $this->auth->user()->id,
            $this->auth->user()->id,
            'Login'
        );

The constructor of that class
 /**
 * @param \Illuminate\Contracts\Auth\Guard $auth
 * @param \jorenvanhocht\Tracert\Tracert $tracert
 */
public function __construct(Guard $auth, Tracert $tracert)
{
    parent::__construct($auth);
    $this->tracert = $tracert;
}

constructor of my base controller:
public function __construct(Guard $auth)
{
    $this->auth = $auth;
    $this->config = objectify(config('blogify'));
    $this->auth_user = $this->auth->check() ? $this->auth->user() : false;
}

The used contract https://github.com/illuminate/contracts/blob/master/Auth/Guard.php

A: To fix the problem for the id of the authenticated user, you should use:
$this->auth->user()->getAuthIdentifier()

Interface consists of methods. You are accessing attribute directly. eg $foo->id instead of $foo->getId(). And you have to add new method to interface of course.
The workaround is to say to scrutinizer, that $object is instance of desired class.
if ($object instanceof MyClass) {
    //
}


text:
Q: Read DOCx,PPTx,XLSx Files from Android using Apache POI libs - Android I am creating android app that is reading microsoft files without any third party application, I have used Apache POI lib. for reading/Open office files , I am able to open doc,ppt and xls file but not able to open DOCx,PPTx,XLSx , I had tried below code to read
FileInputStream inputStream = new FileInputStream(new File(getIntent().getStringExtra(Constants.FILEPATH)));
        // getResources().getAssets().open("doc2.doc");

        XWPFDocument xwpfDocument = new XWPFDocument(inputStream);

        xwpfDocument.getXWPFDocument();
        xwpfDocument.getBodyElements();

It throws exception as below
04-08 05:34:20.407: E/AndroidRuntime(1222): FATAL EXCEPTION: main
04-08 05:34:20.407: E/AndroidRuntime(1222): java.lang.ExceptionInInitializerError
04-08 05:34:20.407: E/AndroidRuntime(1222):     at      org.apache.poi.openxml4j.opc.OPCPackage.init(OPCPackage.java:154)
04-08 05:34:20.407: E/AndroidRuntime(1222):     at org.apache.poi.openxml4j.opc.OPCPackage.<init>(OPCPackage.java:141)
04-08 05:34:20.407: E/AndroidRuntime(1222):     at org.apache.poi.openxml4j.opc.Package.<init>(Package.java:37)
04-08 05:34:20.407: E/AndroidRuntime(1222):     at org.apache.poi.openxml4j.opc.ZipPackage.<init>(ZipPackage.java:83)
04-08 05:34:20.407: E/AndroidRuntime(1222):     at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:272)
04-08 05:34:20.407: E/AndroidRuntime(1222):     at org.apache.poi.util.PackageHelper.open(PackageHelper.java:39)
04-08 05:34:20.407: E/AndroidRuntime(1222):     at org.apache.poi.xwpf.usermodel.XWPFDocument.<init>(XWPFDocument.java:121)
04-08 05:34:20.407: E/AndroidRuntime(1222):     at com.narola.yujidownloader.OfficeActivity.populateWordX(OfficeActivity.java:605)
04-08 05:34:20.407: E/AndroidRuntime(1222):     at com.narola.yujidownloader.OfficeActivity.populate(OfficeActivity.java:139)
04-08 05:34:20.407: E/AndroidRuntime(1222):     at com.narola.yujidownloader.OfficeActivity.initialize(OfficeActivity.java:111)
04-08 05:34:20.407: E/AndroidRuntime(1222):     at com.narola.yujidownloader.OfficeActivity.onCreate(OfficeActivity.java:96)
04-08 05:34:20.407: E/AndroidRuntime(1222):     at android.app.Activity.performCreate(Activity.java:5008)
04-08 05:34:20.407: E/AndroidRuntime(1222):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
04-08 05:34:20.407: E/AndroidRuntime(1222):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
04-08 05:34:20.407: E/AndroidRuntime(1222):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
04-08 05:34:20.407: E/AndroidRuntime(1222):     at android.app.ActivityThread.access$600(ActivityThread.java:130)
04-08 05:34:20.407: E/AndroidRuntime(1222):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
04-08 05:34:20.407: E/AndroidRuntime(1222):     at android.os.Handler.dispatchMessage(Handler.java:99)
04-08 05:34:20.407: E/AndroidRuntime(1222):     at android.os.Looper.loop(Looper.java:137)
04-08 05:34:20.407: E/AndroidRuntime(1222):     at android.app.ActivityThread.main(ActivityThread.java:4745)
04-08 05:34:20.407: E/AndroidRuntime(1222):     at java.lang.reflect.Method.invokeNative(Native Method)
04-08 05:34:20.407: E/AndroidRuntime(1222):     at java.lang.reflect.Method.invoke(Method.java:511)
04-08 05:34:20.407: E/AndroidRuntime(1222):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
04-08 05:34:20.407: E/AndroidRuntime(1222):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
04-08 05:34:20.407: E/AndroidRuntime(1222):     at dalvik.system.NativeStart.main(Native Method)
04-08 05:34:20.407: E/AndroidRuntime(1222): Caused by: java.lang.NoClassDefFoundError: org.dom4j.Namespace
04-08 05:34:20.407: E/AndroidRuntime(1222):     at org.apache.poi.openxml4j.opc.internal.unmarshallers.PackagePropertiesUnmarshaller.<clinit>(PackagePropertiesUnmarshaller.java:49)

I have referred Apchae POI docx
Please guide me


text:
Q: Beginner Here Needing Some Direction I've done some coding in the past but not for a long, long time.
In setting up our message system I want something with the least amount of coding required.
We're looking to send simple SMS messages only on a notification basis. There may be an occasional picture to send as well.
What do you recommend from the list below?
C# with .NET Framework
C# with .NET Core
Java
Node.js
PHP
Python
Ruby

Just getting started


text:
Q: Getting started with Shell Scripting? I'm not familiar with shell scripting, so I'm not sure how to do it or if it is possible.  If you can give me links or advice, that would be great.
What I want to do is:

*

*Create a file, simple text file
EX:
param1  (RANDOMVALUE)
Where randomvalue is a random number generated.

*run a program with that file we just created and output to a file
./program filewejustcreated > A
The program has already been created and it takes a filename as a parameter, no need to worry about that stuff.

*

*run another program with the file we just created, the program already exists and out put it to a file

./Anotherprogram filewejustcreated > B

*

*run a diff comamand on A, B
diff A B
Display what diff returns...
Thanks
[Edit] I am using shell: tcsh

A: You have almost written the script already. The only missing thing is the random number; I'll do it with Perl. Here is a quick & dirty solution in sh (or bash; I'm presuming you're on a Linux/Unix system):
#!/bin/sh
perl -e 'print "TheWord (", int(rand(1000)), ")\n"' > tempfile
./program tempfile > A
./Anotherprogram tempfile > B
# rm tempfile  # this would delete 'tempfile' if uncommented
diff A B

Now save this in a file (say, script.sh) and in a shell execute:
chmod +x script.sh

to make it executable, and
./script.sh

to run it.

A: I am not sure about the function to generate a random number in tcsh. However, in a more common shell like BASH, references to the variable $RANDOM, generates random numbers.
So, in your shell script (a BASH shell script here), the contents would be:
#Pick the first argument to the call as the file name
FILE_NAME=shift
echo "param1 $RANDOM" > $FILE_NAME
./program $FILE_NAME > $FILE1
./Anotherprogram $FILE_NAME > $FILE2
diff $FILE1 $FILE2

A: Shell scripting is mostly just putting together different programs in ways that get the job done.  There are a lot of programs that do just one simple thing and can be combined to accomplish larger tasks that you will learn of as you get into the shell scripting world.
An example of a large shell script is perl's Configure script.  In the first bit you see (along with some humorous comments) cat, true, sh, rm, test, sed, uname, and grep used.


text:
Q: Getting Wrong Output from Operations Performed Between Two Pipe Delimited Files Converted to 2D Arrays I'm new to coding and my instructions for this problem are:
"Given pipe-delimited files F1 and F2 where F1 contains accounts with fields ACCOUNT NUM|PIN|BALANCE and F2 contains transaction instructions COMMAND|AMOUNT|ACCOUNT NUM|PIN, execute the transactions, storing the results back in F1.
The COMMAND field will be add or sub indicating addition or subtraction from the account.
Transactions which do not provide the correct PIN code or attempt to put the account below zero should be ignored."
My output is:
1000|1234|10000
1020|2222|0
3000|3344|1000
2020|1234|90000

The correct output is:
1000|1234|11000
1020|2222|0
3000|3344|0
2020|1234|90000

The code I've written is:
import sys
F1= sys.argv[1]
F2= sys.argv[2]

records=[]
with open(F1,'r') as fp:
  content=fp.readlines()
  for row in content:
    recList=row.strip("\n").split('|')
    records.append(recList)

records2=[]
with open(F2,'r') as fp:
  content=fp.readlines()
  for row in content:
    recList2=row.strip("\n").split('|')
    records2.append(recList2)

for i in range(len(records)):
  row=records[i]
for i in range(len(records2)):
  row=records2[i]
for row in records and records2:
  if records[i][1]==records2[i][3]:
    if records2[i][0]=="add":
      records[i][2]=int(records[i][2])+int(records2[i][1])
    elif records2[i][0]=="sub":
      if int(records[i][2])>=int(records2[i][1]):
        records[i][2]=int(records[i][2])-int(records2[i][1])
      else:
        records[i][2]=records[i][2]
  else:
    break
print(records)

A: You haven't included the COMMANDS. The last numbers displayed in your output rows are without the addition or subtraction, which is why they are wrong.

A: # Create a function that turns pipe-delimited strings into 2d arrays
def pipe2a(text):
  records= text.split("\n")
  for i in range(0, len(records)):
    records[i]= records[i].split("|")
  return records

# Create a function that turns 2d arrays into pipe-delimited strings.
def a2pipe(a):
  text= ""
  for i in range(0, len(a)):
    account= a[i]
    for j in range(0, len(account)):
      account[j]= str(account[j])
     text = text + "|".join(account) + "\n"
  return text;

# Read in the accounts and transactions
accounts= pipe2a(open(F1, 'r').read())
transactions= pipe2a(open(F2, 'r').read())

# Main Section
# for each transaction
for transactionIndex in range(0, len(transactions)):
  transaction= transactions[transactionIndex]
  if(len(transaction) >= 4):
    # look through the accounts for the matching account
    for accountIndex in range(0,len(accounts)):
      account= accounts[accountIndex]
      if(len(account) >= 3):                      # make sure we have
        balance= int(account[2])                  # enough fields
        transactionAmount= int(transaction[1])
        if(account[0] == transaction[2]):         # account matches?
          if(account[1] == transaction[3]):       # pin code matches?
            if(transaction[0] == 'add'):
              accounts[accountIndex][2]= balance + transactionAmount
            elif (transaction[0] == 'sub' and transactionAmount <= balance):
              accounts[accountIndex][2]= balance - transactionAmount

# Write the answer back out to the original file
open(F1, 'w').write(a2pipe(accounts))

It works


text:
Q: Python MD5 cracker improvement I was just writing a very simple MD5 cracker in python. What it does is loads 2 wordlists. 1 wordlist from pass.txt in clear text and other list from hash.txt with all MD5 hashes. It takes the clear text passwords and generates a MD5 hash line by line and compares to all MD5 in hash.txt. The cracker works fine, so far it works as intended, but my question is if it can be improved. Let's say can it be faster or if I load a huge list in it with millions of passwords, can that be an issue on resources? Etc. Or even the mechanics of comparing the strings.
Code:
def clear_pass():
with open("pass.txt", "r", encoding="latin-1") as file:
    for x in file:
        x = x.strip()
        #print(x)
        str2hash = (x)
        result = hashlib.md5(str2hash.encode())
        final_result = (result.hexdigest())
        #print(final_result)
        with open("hash.txt", "r") as hash_file:
            for z in hash_file:
                z = z.strip()
                if z == final_result:
                    print("[+] " + final_result+ " :", x)
clear_pass()

A: Your program is a doubly nested for loop.  That's pretty terrible.  For each word that you calculate that hash value of, you're then reading the entire file hash.txt.  You're reading that file over and over again.
You should instead do something like:
hash_to_string = {}
with open("pass.txt", "r", encoding="latin-1") as file:
    for x in file:
        ... strip it.  Generate md5.  Call results hash...
        hash_to_string[hash] = x
with open("hash.txt") as hash_file:
    for x in file:
        if x.strip() is a key in the hash_to_string table, you've got the plain text
        otherwise, you're done.

Your code is now linear rather than O(n^2).


text:
Q: Is it efficient to store images inside MongoDB using GridFS? I know how to do it, but I wonder if it's effective. As I know MongoDB has very efficient clusters and I can flexibly control the collections and the servers they reside on. The only problem is the size of the files and the speed of accessing them through MongoDB.
Should I explore something like Apache Hadoop or if I intelligently cluster MongoDB, will I get similar access speed results?

A: GridFS is provided for convenience, it is not designed to be the ultimate binary blob storage platform.
MongoDB imposes a limit of 16 MB on each document it stores. This is unlike, for example, many relational databases which permit much larger values to be stored.
Since many applications deal with large binary blobs, MongoDB's solution to this problem is GridFS, which roughly works like this:

*

*For each blob to be inserted, a metadata document is inserted into the metadata collection.

*Then, the actual blob is split into 16 MB chunks and uploaded as a sequence of documents into the blob collection.

*MongoDB drivers provide helpers for writing and reading the blobs and the metadata.

Thus, on first glance, the problem is solved - the application can store arbitrarily large blobs in a straightforward manner. However, digging deeper, GridFS has the following issues/limitations:

*

*On the server side, documents storing blob chunks aren't stored separately from other documents. As such they compete for cache space with the actual documents. A database which has both content documents and blobs is likely to perform worse than a database that has only content documents.

*At the same time, since the blob chunks are stored in the same way as content documents, storing them is generally expensive. For example, S3 is much cheaper than EBS storage, and GridFS would put all data on EBS.

*To my knowledge there is no support for parallel writes or parallel reads of the blobs (writing/reading several chunks of the same blob at a time). This can in principle be implemented, either in MongoDB drivers or in an application, but as far as I know this isn't provided out of the box by any driver. This limits I/O performance when the blobs are large.

*Similarly, if a read or write fails, the entire blob must be re-read or re-written as opposed to just the missing fragment.

Despite these issues, GridFS may be a fine solution for many use cases:

*

*If the overall data size isn't very large, the negative cache effects are limited.

*If most of the blobs fit in a single document, their storage should be quite efficient.

*The blobs are backed up and otherwise transfered together with the content documents in the database, improving data consistency and reducing the risk of data loss/inconsistencies.

A: The good practice is to upload image somewhere (your server or cloud), and then only store image url in MongoDB.

A: Anyway, I did a little investigating. The short conclusion is: if you need to store user avatars you can use MongoDB, but only if it's a single avatar (You can't store many blobs inside MongoDB) and if you need to store videos or just many and heavy files, then you need something like CephFS.
Why do I think so? The thing is, when I was testing with MongoDB and media files on a slow instance, files weighing up to 10mb(Usually about 1 megabyte) were coming back at up to 3000 milliseconds. That's an unacceptably long time. When there were a lot of files (100+), it could turn into a pain. A real pain.
Ceph is designed just for storing files. To store petabytes of information. That's what's needed.
How do you implement this in a real project? If you use the OOP implementation of MongoDB(Mongoose), you can just add methods to the database objects that access Ceph and do what you need. You can make methods "load file", "delete file", "count quantity" and so on, and then just use it all together as usual. Don't forget to maintain Ceph, add servers as needed, and everything will work perfectly. The files themselves should be accessed only through your web server, not directly, i.e. the web server should throw a request to Ceph when the user needs to give the file and return the response from Ceph to the user.
I hope I helped more than just myself. I'll go add Ceph to my tags. Good luck!
GridFS
Ceph File System
More Ceph


text:
Q: Notepad++ how to add a fixed number to different numbers in mysql database I have a mysql database with over 1500 "x" and "y" map coordinates like 2744,6822 and 3252,7030.
I would like to add a fixed amount of 3000 to each "x" coordinate and 6000 to each "y" coordinate.
Is it possible to do this with Notepad++ or with phpmyadmin?
Thanks

A: Here is the way to do it with mysql query.This will update your whole column by adding 1500 to each element in your column named x and 3000 to column named y.
UPDATE table_name SET x = x + 1500;
UPDATE table_name SET x = 1500 WHERE x IS NULL;

UPDATE table_name SET y = y + 3000;
UPDATE table_name SET y = 3000 WHERE y IS NULL;


text:
Q: XML document got already a DocumentElement node when i try to load XMLReader object into XMLDocument I want to create in an app - coded with C# - a copy of the actual element of a XMLReader object by using a XMLDocument instance.
The purpose is to get a copy of the actual reader element, so i can read the inner XML from the actual XML element without moving in the original reader.
When i try to load the reader into the XMLDocument i get the error "The document already has a 'DocumentElement' node.".
Any help would be appreciated.
XmlDocument xmlDocument = new XmlDocument();
MemoryStream streamFromReader = new MemoryStream();
xmlDocument.Load(reader); //Here i get the error
xmlDocument.Save(streamFromReader);
streamFromReader.Position = 0;
XmlReader copyReader = XmlReader.Create(streamFromReader);
sb.Append(copyReader.ReadInnerXml());
copyReader.Close();

A: The problem is that the reader is already positioned somewhere in the middle of the XML file, e.g.:
<Parent>            <---- Position of the reader
  <Child></Child>
  <Child></Child>
</Parent>
<Parent>
  <Child></Child>
  <Child></Child>
</Parent>

The Load method starts to read the current node and also reads the siblings of the node. This leads to an invalid XML structure, because the document can only have one root element. The docs describe this behavior in the remarks section.
As for the original purpose of the code, I understand you want to perform a Peek (check the contents without advancing the reader) on the XmlReader. There are limited options to achieve this because an XmlReader operates forward-only. The answers to this question describe some options on how to read from an XmlReader without advancing it.

A: The answer of Markus helped me to get to the solution.
When the XMLReader is getting to an element which has subitems, i must get first the actual position within the file using the interface IXmlLineInfo.
IXmlLineInfo lineInfo = (IXmlLineInfo)reader;
int lineNumber = lineInfo.LineNumber;
int linePosition = lineInfo.LinePosition;

Then i create an instance of XmlTextReader, which reads the file to that position.
When the reminded position was arrived, the XmlTextReader contains the element and i can get the inner XML from it.
Stream stream = new MemoryStream(myFile.FileBytes);
XmlTextReader textReader = new XmlTextReader(stream);
while (textReader.LineNumber < lineNumber)
{
    textReader.Read();
}
string innerXml = textReader.ReadInnerXml());
textReader.Close();


text:
Q: Highchart (Column Chart) : Few data labels are not appearing for a series I am creating a column chart using High Charts -- I am not able to show all the data labels for all the series in the chart. I have two series in a column chart while the first series shows all the data labels the second series do not displays few of the data labels while displaying others.
Prompt help will highly be appreciated.
Please refer the Fiddle Sample to have hands on.
"chart": {
        "type": "column",
        "plotShadow": false,
        "polar": false,
        "renderTo": ""
    },
    "credits": {
        "enabled": false
    },
    "title": {
        "text": ""
    },
    "xAxis": {
        "categories": ["Category 1", "Category 2", "Category 3", "Category 4", "Category 5", "Category 6", "Category 7", "Category 8", "Category 9"],
        "labels": {
            "enabled": true,
            "style": {
                "fontSize": "8px",
                "fontFamily": "Arial"
            }
        },
        "lineWidth": 1,
        "tickWidth": 0,
        "title": {
            "text": "",
            "style": {
                "fontFamily": "Arial"
            }
        }
    },
    "yAxis": {
        "lineWidth": 1,
        "title": {
            "text": "",
            "style": {
                "fontFamily": "Arial"
            }
        },
        "gridLineWidth": 0,
        "labels": {
            "enabled": true,
            "format": "{value:.0f}",
            "style": {
                "fontSize": "8px",
                "fontFamily": "Arial"
            }
        },
        "startOnTick": true,
        "endOnTick": true
    },
    "series": [{
        "name": "Company Value",
        "data": [{
            "name": "Adidas Group",
            "color": "#f1b11d",
            "y": 63.0,
            "showInLegend": false,
            "dataLabels": {
                "align": "center",
                "enabled": true,
                "borderColor": "",
                "rotation": 0,
                "style": {
                    "fontSize": "8px",
                    "fontFamily": "Arial"
                }
            },
            "borderColor": "#ffffff",
            "enableMouseTracking": false,
            "sliced": false,
            "selected": false
        }, {
            "name": "Adidas Group",
            "color": "#f1b11d",
            "y": 24.0,
            "showInLegend": false,
            "dataLabels": {
                "align": "center",
                "enabled": true,
                "borderColor": "",
                "rotation": 0,
                "style": {
                    "fontSize": "8px",
                    "fontFamily": "Arial"
                }
            },
            "borderColor": "#ffffff",
            "enableMouseTracking": false,
            "sliced": false,
            "selected": false
        }, {
            "name": "Adidas Group",
            "color": "#f1b11d",
            "y": 177.0,
            "showInLegend": false,
            "dataLabels": {
                "align": "center",
                "enabled": true,
                "borderColor": "",
                "rotation": 0,
                "style": {
                    "fontSize": "8px",
                    "fontFamily": "Arial"
                }
            },
            "borderColor": "#ffffff",
            "enableMouseTracking": false,
            "sliced": false,
            "selected": false
        }, {
            "name": "Adidas Group",
            "color": "#f1b11d",
            "y": 197.0,
            "showInLegend": false,
            "dataLabels": {
                "align": "center",
                "enabled": true,
                "borderColor": "",
                "rotation": 0,
                "style": {
                    "fontSize": "8px",
                    "fontFamily": "Arial"
                }
            },
            "borderColor": "#ffffff",
            "enableMouseTracking": false,
            "sliced": false,
            "selected": false
        }, {
            "name": "Adidas Group",
            "color": "#f1b11d",
            "y": 224.0,
            "showInLegend": false,
            "dataLabels": {
                "align": "center",
                "enabled": true,
                "borderColor": "",
                "rotation": 0,
                "style": {
                    "fontSize": "8px",
                    "fontFamily": "Arial"
                }
            },
            "borderColor": "#ffffff",
            "enableMouseTracking": false,
            "sliced": false,
            "selected": false
        }, {
            "name": "Adidas Group",
            "color": "#f1b11d",
            "y": 297.0,
            "showInLegend": false,
            "dataLabels": {
                "align": "center",
                "enabled": true,
                "borderColor": "",
                "rotation": 0,
                "style": {
                    "fontSize": "8px",
                    "fontFamily": "Arial"
                }
            },
            "borderColor": "#ffffff",
            "enableMouseTracking": false,
            "sliced": false,
            "selected": false
        }, {
            "name": "Adidas Group",
            "color": "#f1b11d",
            "y": 349.0,
            "showInLegend": false,
            "dataLabels": {
                "align": "center",
                "enabled": true,
                "borderColor": "",
                "rotation": 0,
                "style": {
                    "fontSize": "8px",
                    "fontFamily": "Arial"
                }
            },
            "borderColor": "#ffffff",
            "enableMouseTracking": false,
            "sliced": false,
            "selected": false
        }, {
            "name": "Adidas Group",
            "color": "#f1b11d",
            "y": 903.0,
            "showInLegend": false,
            "dataLabels": {
                "align": "center",
                "enabled": true,
                "borderColor": "",
                "rotation": 0,
                "style": {
                    "fontSize": "8px",
                    "fontFamily": "Arial"
                }
            },
            "borderColor": "#ffffff",
            "enableMouseTracking": false,
            "sliced": false,
            "selected": false
        }, {
            "name": "Adidas Group",
            "color": "#f1b11d",
            "y": 20.0,
            "showInLegend": false,
            "dataLabels": {
                "align": "center",
                "enabled": true,
                "borderColor": "",
                "rotation": 0,
                "style": {
                    "fontSize": "8px",
                    "fontFamily": "Arial"
                }
            },
            "borderColor": "#ffffff",
            "enableMouseTracking": false,
            "sliced": false,
            "selected": false
        }],
        "regression": false,
        "enableMouseTracking": true,
        "color": "#f1b11d",
        "showInLegend": false
    }, {
        "name": "All Companies Average Score",
        "data": [{
            "name": "All Companies",
            "color": "#00aeef",
            "y": 25.0,
            "showInLegend": false,
            "dataLabels": {
                "align": "center",
                "enabled": true,
                "borderColor": "",
                "rotation": 0,
                "style": {
                    "fontSize": "8px",
                    "fontFamily": "Arial"
                }
            },
            "borderColor": "#ffffff",
            "enableMouseTracking": false,
            "sliced": false,
            "selected": false
        }, {
            "name": "All Companies",
            "color": "#00aeef",
            "y": 18.0,
            "showInLegend": false,
            "dataLabels": {
                "align": "center",
                "enabled": true,
                "borderColor": "",
                "rotation": 0,
                "style": {
                    "fontSize": "8px",
                    "fontFamily": "Arial"
                }
            },
            "borderColor": "#ffffff",
            "enableMouseTracking": false,
            "sliced": false,
            "selected": false
        }, {
            "name": "All Companies",
            "color": "#00aeef",
            "y": 90.0,
            "showInLegend": false,
            "dataLabels": {
                "align": "center",
                "enabled": true,
                "borderColor": "",
                "rotation": 0,
                "style": {
                    "fontSize": "8px",
                    "fontFamily": "Arial"
                }
            },
            "borderColor": "#ffffff",
            "enableMouseTracking": false,
            "sliced": false,
            "selected": false
        }, {
            "name": "All Companies",
            "color": "#00aeef",
            "y": 1821.0,
            "showInLegend": false,
            "dataLabels": {
                "align": "center",
                "enabled": true,
                "borderColor": "",
                "rotation": 0,
                "style": {
                    "fontSize": "8px",
                    "fontFamily": "Arial"
                }
            },
            "borderColor": "#ffffff",
            "enableMouseTracking": false,
            "sliced": false,
            "selected": false
        }, {
            "name": "All Companies",
            "color": "#00aeef",
            "y": 84.0,
            "showInLegend": false,
            "dataLabels": {
                "align": "center",
                "enabled": true,
                "borderColor": "",
                "rotation": 0,
                "style": {
                    "fontSize": "8px",
                    "fontFamily": "Arial"
                }
            },
            "borderColor": "#ffffff",
            "enableMouseTracking": false,
            "sliced": false,
            "selected": false
        }, {
            "name": "All Companies",
            "color": "#00aeef",
            "y": 83.0,
            "showInLegend": false,
            "dataLabels": {
                "align": "center",
                "enabled": true,
                "borderColor": "",
                "rotation": 0,
                "style": {
                    "fontSize": "8px",
                    "fontFamily": "Arial"
                }
            },
            "borderColor": "#ffffff",
            "enableMouseTracking": false,
            "sliced": false,
            "selected": false
        }, {
            "name": "All Companies",
            "color": "#00aeef",
            "y": 97.0,
            "showInLegend": false,
            "dataLabels": {
                "align": "center",
                "enabled": true,
                "borderColor": "",
                "rotation": 0,
                "style": {
                    "fontSize": "8px",
                    "fontFamily": "Arial"
                }
            },
            "borderColor": "#ffffff",
            "enableMouseTracking": false,
            "sliced": false,
            "selected": false
        }, {
            "name": "All Companies",
            "color": "#00aeef",
            "y": 241.0,
            "showInLegend": false,
            "dataLabels": {
                "align": "center",
                "enabled": true,
                "borderColor": "",
                "rotation": 0,
                "style": {
                    "fontSize": "8px",
                    "fontFamily": "Arial"
                }
            },
            "borderColor": "#ffffff",
            "enableMouseTracking": false,
            "sliced": false,
            "selected": false
        }, {
            "name": "All Companies",
            "color": "#00aeef",
            "y": 12.0,
            "showInLegend": false,
            "dataLabels": {
                "align": "center",
                "enabled": true,
                "borderColor": "",
                "rotation": 0,
                "style": {
                    "fontSize": "8px",
                    "fontFamily": "Arial"
                }
            },
            "borderColor": "#ffffff",
            "enableMouseTracking": false,
            "sliced": false,
            "selected": false
        }],
        "regression": false,
        "enableMouseTracking": true,
        "color": "#00aeef",
        "showInLegend": false
    }],
    "plotOptions": {
        "series": {
            "enableMouseTracking": false,
            "dataLabels": {
                "color": "#000000",
                "enabled": true,
                "borderColor": "",
                "format": "{y:.0f}"
            }
        },
        "column": {
            "pointWidth": 20
        }
    },
    "exporting": {
        "enabled": false
    },
    "tooltip": {
        "enabled": true,
        "pointFormat": "{series.name}: {point.y:.0f}",
        "shared": false,
        "headerFormat": ""
    },
    "legend": {
        "enabled": false,
        "x": 0,
        "floating": false,
        "shadow": false,
        "reversed": false,
        "y": 0
    }

A: Set plotOptions.series.dataLabels.allowOverlap option to true. See : http://jsfiddle.net/cthzmsg0/1


text:
Q: React TypeError: this.setState is not a function despite having bound handler Before flagging this as a duplicate of React this.setState is not a function, I have seen and read that.
My problem is that I'm getting this error message even though I've bound the handler.
class EditAccount extends Component {
    constructor(props) {
        super(props);
        this.onClick = this.onClick.bind(this);
    }

    state = {
        showForm: false
    }

    componentWillMount() {
        this.setState = {
            showForm: false
        }
    }

    render() {
        return (

                <button onClick={this.onClick}>Edit</button>
                {this.state.showForm ? ( <Stuff/> ): null }

        )
     }

    //toggle form visibility
    onClick(e) {
        const showing = this.state.showForm;
        if (showing) {
            this.setState({ showForm: false });
        } else {
            this.setState({ showForm: true });
        }
    }
}

Any ideas?

A: The issue is in your componentWillMount. You are changing setState to no longer be a function but rather an object with the value showForm. You shouldn't be setting state in will mount as react advises against it. Drop that whole function and the code will work as you expect.
meaning this.setState = { showForm: false } is changing setState to be the object { showForm: false } instead of a function. So yes your error message is correct in that setState is not a function
Try dropping the whole componentWillMount function
class EditAccount extends Component {
    constructor(props) {
        super(props);
        this.onClick = this.onClick.bind(this);
    }

    state = {
        showForm: false
    }

    render() {
        return (

                <button onClick={this.onClick}>Edit</button>
                {this.state.showForm ? ( <Stuff/> ): null }

        )
     }

    //toggle form visibility
    onClick(e) {
        const showing = this.state.showForm;
        if (showing) {
            this.setState({ showForm: false });
        } else {
            this.setState({ showForm: true });
        }
    }
}

some optimizations.. you should be able to clean up the code a bit
class EditAccount extends Component {
    state = {
        showForm: false
    }
    render() {
        return (

                <button onClick={this.handleClick }>Edit</button>
                {this.state.showForm ? <Stuff/> : null }

        )
     }
    handleClick = (e) => {
        this.setState((old) => ({ showForm: !old.showForm }) )
    }
}

A:
componentWillMount() is invoked just before mounting occurs. It is called before render(), therefore calling setState() synchronously in this method will not trigger an extra rendering.

The reason to not use setState inside compomentWillMount,
React will use the initial state value from constructor or initialized default state  for  the first render instead of re-render. It not wait for componentWillMount to complete setState call asynchronously.
So,there is no point in making setState call inside componentWillMount. It's nothing more than  that state handler processing which do nothing when setState is called.


text:
Q: Detect Left or Right Swipe and Call Function Every Valid Swipe In PageView Using Flutter I want to call a function on every valid page swipe.

*

*At first i am shown 'A'.

enter image description here

*Then If i drag the page in horizontal of small amount then it shows some part of next page like above picture...

Till now it is OK, I also want this.
Here Is My Code
homepage.dart
import 'package:flutter/material.dart';

List<String> dataList = ["A", "B", "C", "D", "E", "F", "G"];
int pointer = (-1);

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);
  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("THIS IS APPBAR"),
      ),
        body: PageView.builder(
            itemCount: dataList.length,
            itemBuilder: (BuildContext context, int index) {
              print("Page No. $index");
              return MyPage(index: index,);
            })
    );
  }
}

class MyPage extends StatelessWidget {
  final int index;

  const MyPage({super.key, required this.index});

  @override
  Widget build(BuildContext context) {
    pointer += 1;
    return Scaffold(
      body: Container(
        margin: const EdgeInsets.all(15.0),
        padding: const EdgeInsets.all(3.0),
        decoration: BoxDecoration(
            border: Border.all(color: Colors.blueAccent)
        ),
        child: Center(
          child: Text(dataList[pointer], style: const TextStyle(fontSize: 30),),
        ),
      ),
    );

  }
}

main.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'my_provider.dart';
import 'home_page.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const HomePage(),
    );
  }
}

BUT, in next swipe it shows me 'C' instead of 'B' on next valid swipe (as pointer value is increased).
As well as in output it shows me Page No. 0 Page No. 0 Page No. 1 but i am at page 0.
How to do this in smooth way.. Thank you

A: I'm Try To Solve You problem
Here is Code:
  import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

List<String> dataList = ["A", "B", "C", "D", "E", "F", "G"];

int pointer = 0;

class Swipefunctions extends StatefulWidget {
  const Swipefunctions({Key? key}) : super(key: key);
  @override
  State<Swipefunctions> createState() => _SwipefunctionsState();
}

class _SwipefunctionsState extends State<Swipefunctions> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text("THIS IS APPBAR"),
        ),
        body: PageView.builder(
            onPageChanged: (int index) {
              print("prinetd");
              setState(() {
              pointer++;
              pointer=index;
              });
            },
            itemCount: dataList.length,
            itemBuilder: (BuildContext context, int index) {
              return MyPage(index: index,);
            })
    );
  }
}

class MyPage extends StatefulWidget {
  final int index;

  const MyPage({super.key, required this.index});

  @override
  State<MyPage> createState() => _MyPageState();
}

class _MyPageState extends State<MyPage> {

  @override
  Widget build(BuildContext context) {
    print("pointer at $pointer");
    return Scaffold(
      body: Container(
        margin: const EdgeInsets.all(15.0),
        padding: const EdgeInsets.all(3.0),
        decoration: BoxDecoration(
            border: Border.all(color: Colors.blueAccent)
        ),
        child: Center(
          child: Text(dataList[pointer], style: const TextStyle(fontSize: 30),),
        ),
      ),
    );

  }
}

Video Link

A: import 'package:flutter/material.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const HomePage(),
    );
  }
}

List<String> dataList = ["A", "B", "C", "D", "E", "F", "G"];

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);
  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("THIS IS APPBAR"),
      ),
        body: PageView.builder(
            itemCount: dataList.length,
            itemBuilder: (BuildContext context, int index) {
              return MyPage(index: index,);
            })
    );
  }
}

class MyPage extends StatelessWidget {
  final int index;

  const MyPage({super.key, required this.index});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        margin: const EdgeInsets.all(15.0),
        padding: const EdgeInsets.all(3.0),
        decoration: BoxDecoration(
            border: Border.all(color: Colors.blueAccent)
        ),
        child: Center(
          child: Text(dataList[index], style: const TextStyle(fontSize: 30),),
        ),
      ),
    );

  }
}

Have edited your code, please check.
Hope this helps


text:
Q: HTML5 video as base64 encode data URI not working in iPad and iPhone browser I need to play the video as base64 data URI format using HTML5 video tag on iPad and iPhone, which eventually helps me to make the video offline by storing it in websql,
I got a link which helped me to study the feasibility - http://iandevlin.com/html5/data-uri/video.php (if you take the view source of the link, you will see its well encoded in base64 format)
I tried this on most of the modern browser's like chrome & firefox in windows machine and safari in mac os, there it worked well.
So my hoped increased and I tried it in iPhone and iPad, Well its NOT working there! I am just getting a blank BLACK screen in place of the video control.
Also I am not getting any error in the safari debug mode as well. I would like to know whether we can play base 64 encoded video or it just a known issue for ipad and iphone...

A: to play video under HTML5 tag you need to provide its content source like images and video/audio files name without any path then only it works well i t

A: When Base64 media encoding is used you need to take in mind that memory consumption increases substantially, it's not the same as external media inclusion once media is not inside document and may be load in frames consuming only memory you really need.
Using Base64 need to load all the data to perform a decryption, and most mobile browsers take a lot of time to show video because their useful memory is very small (usually most of memory is consumed by operational system) and conversion take a long, when a processes take a long in mobile system, garbage collection know that as a zombie thread and kill it.
Actually is not a good idea assume you can use base64 for video in mobile browser, it should not work.

A: I have found iOS Safari to be pickier than desktop browsers regarding having the correct Mime type in the data uri.  You should make sure you are using the correct one.


text:
Q:  not working in angular 5 I have an input element, when I type a character it will give some suggestion and I can select it, I want to access the item that I selected, for this I defined a method "selectedItem($event)"
<input type="text" (selectItem)="selecteditem($event)">

and my method is :
selectedItem (items: any) {
    console.log('selected item is ' + items)
}

on my console I am getting:
selected item is [object Object]

It should show selected item but it is showing array of object.
If i try to print items[0] I will get undefined on console.
What is the problem with this ?

A: What does 'selectItem' represent ? Because its obviously not a native input element listener, and a custom directive. This is something you need to provide more context around next time.
I am assuming items represents an object, and your console.log is adding a string to an object will cast the object to a string (Try "" + {}) in your console.
To solve this problem you want to pass the items as a second parameter to console.log so your object is not casted to a string. You can do so like this
console.log('selected item is ', items)

obj = {name: 'realappie'}

console.log("name is" + obj);

console.log("name is", obj);


text:
Q: Horizontal Continuous Slider I am looking for a jquery horizontal slider that moves to the right and left by using arrows, touch events and mouse click. The slider must contain one single item, which is scrolled horizontally with the events I mentioned. Do you know any I can use with those characteristics?

A: Have a look at this : http://bxslider.com/examples/carousel-demystified
It supports Mouse Click, Touch based movement directly. And you can capture Keypress events manually and use its API to move between slides. Like this:
slider = $('.bxslider').bxSlider();
document.addEventListener('keypress', function (e) {
    if (e.charCode === 39) {
        slider.goToNextSlide();
        e.preventDefault();
    } else if (e.charCode === 37) {
        slider.goToPrevSlide();
        e.preventDefault();
    }
});


text:
Q: Performance of Jquery draggable for 1000s of elements vs re-rendering the elements I am working on an app which allows an image to be dragged using the draggable utility from Jquery. There are numerous overlay divs associated with the image with many components positioned by pixel location. The numbers could easily be in the 1000s.
Has anyone done the performance numbers on dragging all these elements vs dragging only the image then re-rendering the other elements following the drag?
I'm favoring the later approach but wanted to see if someone has more insight.

I ended up going with a single svg layer with the Jquery draggable utility active $("#zones_imageSVG").draggable( "enable" ); and multiple rect, circles inside. The svg layer drags about easily without lag or skips. This approach circumvents the multiple div layer solution.
<svg id="zones_imageSVG" class="moveCursor" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg" height="430" width="549.4444444444445" style="position: relative;">
<image id="zones_image" width="549.4444444444445" height="430" y="0" x="0" xlink:href="./images/testCampus1_HQ_floorA.jpg">
<circle id="icon_sensor0" class="handle_svgAttrCirc" cx="91.63777777777779" cy="287.14444444444445" r="1.9111111111111112" fill="red">
<circle id="icon_sensor1" class="handle_svgAttrCirc" cx="272.0466666666667" cy="332.9155555555556" r="1.9111111111111112" fill="red">
<circle id="icon_sensor2" class="handle_svgAttrCirc" cx="412.60888888888894" cy="221.40222222222224" r="1.9111111111111112" fill="red">
<circle id="icon_sensor3" class="handle_svgAttrCirc" cx="410.3155555555556" cy="103.8688888888889" r="1.9111111111111112" fill="red">
<rect id="idAttrRect0" class="handle_svgAttrRect" x="512.1777777777778" y="73.38666666666667" height="74" width="88" fill="#3196bd">
<rect id="idAttrRect1" class="handle_svgAttrRect" x="416.62222222222226" y="54.27555555555556" height="54" width="48" fill="#3196bd">
<rect id="idAttrRect2" class="handle_svgAttrRect" x="321.0666666666667" y="25.60888888888889" height="24" width="38" fill="#3196bd">
<rect id="idAttrRect3" class="handle_svgAttrRect" x="129.95555555555558" y="44.720000000000006" height="44" width="44" fill="#DC143C">
<rect id="idAttrRect4" class="handle_svgAttrRect" x="416.62222222222226" y="35.16444444444445" height="84" width="38" fill="#A1DC14">
</svg>

A: A quick sample shows 1000 subitems do not seem to cause issue. Of course, YMMV depending on how complicated your subitems get.
JSFiddle
Code to generate sample div:
$(function () {
    $(".dragMe").draggable();

    var $dragMe = $(".dragMe.filled");

    var maxTop = 250;
    var maxLeft = 400;

    for (i = 0; i < 1000; i++)
    {
        var $newSubItem = $("<div />")
            .addClass("subItem");

        var randomLeft = Math.random() * maxLeft;
        var randomTop = Math.random() * maxTop;

        $newSubItem.css({
            left: randomLeft,
            top: randomTop
        });

        $dragMe.append($newSubItem);
    }
});


text:
Q: What are the benefits of running a app server in user space, like Unicorn, as opposed to as sudo? I've been using Phusion Passenger + Rails/Sinatra for a lot of projects. Passenger runs under the main Nginx or Apache process.
But I'm interested in Unicorn, partly because it runs in user space. You just set up Nginx to proxy_pass requests to a unix socket that is connected to Unicorn processes that you fire up under a normal user account.
Is there anything to be said as far as advantages and disadvantages of these two alternative approaches to running an web app? I mean in terms of ease of administration, stability, simplicity, etc.

A: I say root here when you say sudo - sudo elevates a user to root privileges, but essentially its the same.
Well, low numbered ports are only available to root users, so in many cases running an application as a regular user may need some firewall changes.
With userspace you have the option of better compartmentalisation (at the minimum per application/stack users so you can set up everything in one place and move it between systems easily), or even chroot. In general avoiding running things as root is good (many applications drop down to 'nobody' upon starting to avoid running as root) since if a process running as root is compromised, you may have an attacker get root privileges.
Running as a regular user is generally better for security, IMO but really depends on your application.

A: Well, Phusion/Nginx/Unicorn all run on user space and kernel space, I think you wanted to say running it as unprivileged user versus privileged/root user. There are some advantages on that:

*

*More security, if your app does something stupid it can't access critical parts of the server

*Portability, the app is compartmentalized on a single space.

*If you use rails you probably use capistrano for the deploy, that means that you can start the unicorn process directly from the deploy process without needing a sudo

Aside from that, I suggest you to use Unicorn's socket option with Nginx, that simplifies a little the deployment process, and read the document about deploying without needing to fully restart the app server

A: As coredump said, what you meant is running as a privileged user vs as a regular user. But Phusion Passenger most definitely does not run as a privileged user.

*

*All application processes spawned by Phusion Passenger are run as regular users. More specifically, as the user that owns config/environment.rb or config.ru, not as the Apache/Nginx user. This is part of the "User Switching" feature, which Phusion Passenger has had since version 1.0.

*With Unicorn, you have to manually start processes as the desired user. Phusion Passenger automatically takes care of this for you.

*Phusion Passenger absolutely refuses to run any application processes as root. You cannot override this behavior. Phusion Passenger takes security very seriously so it has added this security precaution.

*Apache/Nginx do not run as privileged users. On most systems they are configured to run under the www-data account.

*There are some Phusion Passenger helper processes which run as root so that they can spawn processes as other users, but you can disable this by turning user switching off, in which case all Phusion Passenger processes (including app processes) run a user account that you specify.

Phusion Passenger is simpler to administer and to install than Unicorn because it automates more things for you. Phusion Passenger is very stable because of its watchdog architecture. It watches over its internal helper processes and restarts them if any of them fail. Phusion Passenger is used by over 150,000 websites including large brand names such as Pixar, the New York Times, AirBnB, Oakley and Symantec. The upcoming Phusion Passenger 4 will add a bunch more stability- and reliability-related features.


text:
Q: How do we know that some radioactive materials have a half life of millions or even billions of years? If a radioactive material takes a very long time to decay, how is its half life measured or calculated? Do we have to actually observe the radioactive material for a very long time to extrapolate its half life?

A: Lubos has already answered your question comprehensively. I would like to add just one thing. It is one of the funny things of the theory of probability that you need not have to wait for that long to confirm the half life. For example it has been estimated that proton has a half life of approximately $10^{32}$ years in some grand unified theories. Now in order to observe proton decay one does not have to wait for $10^{32}$ years. You just take some material which has $10^{32}$ numbers of protons. According to the theory of probability you should observe at least one proton decay per year (if a proton doest indeed take $10^{32}$ years to decay). For an easier example, suppose you throw a dice 6 times. The probability of a particular outcome is same or equivalent to throwing 6 dices at once.

A: No, one doesn't need to measure the material for years - or even millions or billions of years. It's enough to watch it for a few minutes (for time $t$) and count the number of atoms $\Delta N$ (convention: a positive number) that have decayed. The lifetime $T$ is calculated from
$$ \exp(-t/T) = \frac{N - \Delta N}{N}$$
where $N$ is the total number of atoms in the sample. This $N$ can be calculated as
$$N={\rm mass}_{\rm total} / {\rm mass}_{\rm atom}.$$
If we know that the lifetime is much longer than the time of the measurement, it's legitimate to Taylor-expand the exponential above and only keep the first uncancelled term:
$$ \frac{t}{T} = \frac{\Delta N}{N}.$$
The decay of the material proceeds atom-by-atom and the chances for individual atoms to decay are independent and equal.
To get some idea about the number of decays, consider 1 kilogram of uranium 238. Its atomic mass is $3.95\times 10^{-25}$ kilograms and its lifetime is $T=6.45$ billion years. By inverting the atomic mass, one sees that there are $2.53\times 10^{24}$ atoms in one kilogram. So if you take one kilogram of uranium 238, it will take $2.53\times 10^{24}$ times shorter a time for an average decay, e.g. the typical separation between two decays is
$$t_{\rm average} = \frac{6.45\times 10^9\times 365.2422\times 86400}{2.53\times 10^{24}}{\rm seconds} = 8.05\times 10^{-8} {\rm seconds}. $$
So one gets about 12.4 million decays during one second. (Thanks for the factor of 1000 fix.) These decays may be observed on an individual basis. Just to be sure, $T$ was always a lifetime in the text above. The half-life is simply $\ln(2) T$, about 69 percent of the lifetime, because of some simple maths (switching from the base $e$ to the base $2$ and vice versa).
If we observe $\Delta N$ decays, the typical relative statistical error of the number of decays is proportional to $1/(\Delta N)^{1/2}$. So if you want the accuracy "1 part in 1 thousand", you need to observe at least 1 million decays, and so on.


text:
Q: reshape equivalent of stack in R I have a wide zoo with two variables per individuals (maybe this is a double-wide?), that I would like to convert to a long panel with two columns (one for each variables) so that I can run panel regressions (say with the plm package).
This is trivial with melt and cast from the reshape package, but with the size of these data I run into memory and speed issues. So I'd like to use all base R, but I am having a hard time with the base reshape function. From the (double-)wide zoo object I can get the "melted" long data frame with stack, but I'm afraid that this will fail silently and would prefer the precision of reshape, but I can't get the syntax correct.
Is there a reshape equivalent of stack? The only syntax that I can get to run still leaves me with a (single-)wide data frame with individuals in columns and variables rows?
Below is the relevant code block in case I'm totally off base, but the highlighted block is where I'm stuck and would like to replace stack with reshape.
# similar data
library(zoo)
dates <- seq(as.Date("2004-01-01"), by=7, len=52*10)
tickers <- letters
my.df <- data.frame(dates=as.Date(rep_len(dates, length(dates)*length(tickers))),
                    tickers=rep(tickers, each=length(dates)),
                    SVI=runif(length(dates)*length(tickers), min=0, max=100))
svi <- read.zoo(my.df, index.column="dates", split="tickers")
meansvi <- rollmean(svi, 52, align="right")
my.zoo <- merge(svi, meansvi)

############################################################
# I need help here -- what is the base::reshape equivalent?
############################################################

# reshape to long data frame
my.df2 <- as.data.frame(my.zoo)
my.df2$dates <- index(my.zoo)
my.df3 <- stack(my.df2, select=-dates)
my.df3$dates <- as.Date(rep_len(index(my.zoo), nrow(my.df3)))

# this is close, but still "single-wide"
my.bad <- reshape(my.df2,
                  varying=setdiff(names(my.df2), "dates"),
                  direction="long")

############################################################
# end help region
############################################################

# split "ind" to recover ticker and variable
my.df3$ind <- sub("\\.", " ", my.df3$ind)
inds.list <- strsplit(my.df3$ind, " ")
inds.df <- do.call(rbind.data.frame, inds.list)
names(inds.df) <- c("tickers", "variables")
my.df3 <- cbind(my.df3, inds.df)
my.df3$ind <- NULL

# reshape long data frame with variables in columns
my.df4 <- reshape(my.df3, timevar="variables", idvar=c("dates", "tickers"), direction="wide")
names(my.df4) <- sub("values.", "", names(my.df4))

Edit -- more details.
The output of my stack call has the correct form, but I would like to produce it with base reshape. Here's the head of my.df3, which is the "melted" long version of my data (i.e., date-individual-variables pairs in rows).
> head(my.df3)
    values      dates tickers variables
1 16.32171 2004-01-01       a       svi
2 30.77852 2004-01-08       a       svi
3 14.75164 2004-01-15       a       svi
4 49.77205 2004-01-22       a       svi
5 59.05023 2004-01-29       a       svi
6 55.86036 2004-02-05       a       svi

The reshape call that I show above won't produce the same output as stack and leaves my data as a wide data frame, but with a row for each date-variable combination. This is my.bad in the code above.
> my.bad[1:5, 1:5]
           dates time        a         b        c
1.svi 2004-01-01  svi 16.32171 91.314077 93.19167
2.svi 2004-01-08  svi 30.77852 17.907831 61.73727
3.svi 2004-01-15  svi 14.75164 13.730005 53.04939
4.svi 2004-01-22  svi 49.77205  5.987645 79.19428
5.svi 2004-01-29  svi 59.05023 38.226002 88.26567

I can achieve the overall desired output with the code above, it's just the intermediate step that I would like to replace with reshape instead of stack. Here is the ultimate desired output, which is long with one column per variables with date-individual pairs in the rows.
> head(my.df4)
       dates tickers      svi meansvi
1 2004-01-01       a 16.32171      NA
2 2004-01-08       a 30.77852      NA
3 2004-01-15       a 14.75164      NA
4 2004-01-22       a 49.77205      NA
5 2004-01-29       a 59.05023      NA
6 2004-02-05       a 55.86036      NA

Maybe there's a way to completely skip my concern about stack failing silently?

A: If you are looking for performance , I think you can can't gain a lot from using base reshape. But you can try to use melt.data.table in development version(1.8.11).
## create dt object from zoo
dt <- data.table(index=index(my.zoo),coredata(my.zoo),key='index')
## fast melt and split variable column
melt(dt,id='index')[,c("tickers","variables","variable") := {
  vv <- unlist(strsplit(as.character(variable),'.',fixed=TRUE))
  list(unlist(vv)[c(T,F)],unlist(vv)[c(F,T)],NULL)
}]

         index    value tickers variables
    1: 2004-01-01 65.05146       a       svi
    2: 2004-01-08 52.25760       a       svi
    3: 2004-01-15 24.71477       a       svi
    4: 2004-01-22 94.28517       a       svi
    5: 2004-01-29 11.46672       a       svi
   ---
27036: 2013-11-14 54.44904       z   meansvi
27037: 2013-11-21 54.20244       z   meansvi
27038: 2013-11-28 53.82270       z   meansvi
27039: 2013-12-05 52.66165       z   meansvi
27040: 2013-12-12 50.87973       z   meansvi

A: The first step suggested by @agstudy (bringing the "index" as a column) would be required (as far as I can tell). I would also suggest some renaming of your columns (for convenience mostly).
library(splitstackshape) # also loads the "data.table" package
dt <- data.table(index=index(my.zoo),coredata(my.zoo),key='index')
setnames(dt, gsub("([a-z].*)\\.([a-z].*)", "\\2_\\1", names(dt)))
names(dt)
#  [1] "index"     "svi_a"     "svi_b"     "svi_c"     "svi_d"     "svi_e"     "svi_f"     "svi_g"
#  [9] "svi_h"     "svi_i"     "svi_j"     "svi_k"     "svi_l"     "svi_m"     "svi_n"     "svi_o"
# [17] "svi_p"     "svi_q"     "svi_r"     "svi_s"     "svi_t"     "svi_u"     "svi_v"     "svi_w"
# [25] "svi_x"     "svi_y"     "svi_z"     "meansvi_a" "meansvi_b" "meansvi_c" "meansvi_d" "meansvi_e"
# [33] "meansvi_f" "meansvi_g" "meansvi_h" "meansvi_i" "meansvi_j" "meansvi_k" "meansvi_l" "meansvi_m"
# [41] "meansvi_n" "meansvi_o" "meansvi_p" "meansvi_q" "meansvi_r" "meansvi_s" "meansvi_t" "meansvi_u"
# [49] "meansvi_v" "meansvi_w" "meansvi_x" "meansvi_y" "meansvi_z"

From there, it's a straightforward reshape problem:
reshape(dt, idvar="index", varying=2:ncol(dt), sep="_", direction = "long")
#             index time       svi  meansvi
#     1: 2004-01-01    a 42.037201       NA
#     2: 2004-01-08    a 26.178651       NA
#     3: 2004-01-15    a 22.918586       NA
#     4: 2004-01-22    a 32.408017       NA
#     5: 2004-01-29    a  8.014803       NA
#    ---
# 13516: 2013-11-14    z 18.720031 51.98170
# 13517: 2013-11-21    z 40.362254 52.43208
# 13518: 2013-11-28    z 45.242975 53.18101
# 13519: 2013-12-05    z  9.951862 53.11564
# 13520: 2013-12-12    z 15.520532 52.41540

Or, sticking with "splitstackshape", you can use merged.stack (which will also be faster than reshape):
merged.stack(dt, id.vars="index", var.stubs=c("^svi", "^meansvi"), sep = "_")
#             index .time_1      ^svi ^meansvi
#     1: 2004-01-01       a 42.037201       NA
#     2: 2004-01-01       b  8.121128       NA
#     3: 2004-01-01       c 65.798174       NA
#     4: 2004-01-01       d 31.805462       NA
#     5: 2004-01-01       e  8.002793       NA
#    ---
# 13516: 2013-12-12       v 68.643179 44.87272
# 13517: 2013-12-12       w 48.169667 43.63862
# 13518: 2013-12-12       x 58.160491 53.72554
# 13519: 2013-12-12       y 72.259193 47.61617
# 13520: 2013-12-12       z 15.520532 52.41540

Strictly base R reshape:
You don't have to rename your data to use reshape, but there's a lot more manual work involved if you don't (which I find more likely to introduce errors). Try:
df <- data.frame(index = index(my.zoo), coredata(my.zoo))
reshape(df, direction = "long", idvar="index", varying=2:ncol(df),
        v.names=c("svi", "meansvi"), times = letters)

I've posted some benchmarks here. The summary is that @agstudy leads the way with the speed:
## Unit: milliseconds
##       expr   min     lq median     uq   max neval
##     AM_1() 229.2 236.47 244.66 255.91 334.1    20
##     AM_2()  84.0  86.69  90.08  93.60 176.0    20
##  agstudy()  52.5  52.95  56.09  60.36 133.5    20
##     orig() 268.7 324.58 350.45 440.32 588.6    20

I'm probably biased, but I'm pretty happy with the results from my merged.stack function.


text:
Q: Find element '0' in each rwo of CSV file in Python What I'm trying to do should be so simple,to write a program which reads a CSV or txt file line by line and finds rows which have more than one element equal to zero then highlighting these lines and saving a new version of highlighted CSV file.
I have a CSV file like this:

I have no idea how to find elements = 0 in each row of CSV file and how to change the color of this row. I don know if there is a way to save a copy of changed CSV file.
if self.EnableCalibration.IsChecked():
    try:
        ImportedFile = open('some.csv', 'rb')
        CSVReading= ImportedFile.read(_MAX_LUNGHEZZA_FILE)
        Lenght_CSVReading = len(CSVReading)
        csvFileArray = []
        for row in csv.reader(ImportedFile, delimiter=' '):
            csvFileArray.append(row)
            if TWO_Elements == 0: ?
               Highlight_Row? # this is not a string or python command
               csvFileArray.next() # go to the next row
            if CSVReading.split(-1): # end of csv file
                  csvSave= csv.writer(CSVReading)  #to Save
        ImportedFile.close()
else:
    CSVReading = None
    Lenght_CSVReading = 0

A: Maybe the variable TWO_Elements is a string, so your code:
if TWO_Elements == 0: ?

is comparing "0" == 0: ? ->FALSE
Try to cast:
if int(TWO_Elements) == 0:

A: If you are ok using Pandas, I would use the following code:
First, load the csv into a dataframe:
import pandas as pd
df = pd.read_csv(_MAX_LUNGHEZZA_FILE)

Here, let's take a dummy example of a datafame:
   A  B  C  D  E
0  5  0  1  0  5
1  2  1  4  3  5
2  5  1  4  4  3
3  2  1  0  2  5

Then let's create a new column, 'invalid', which will be True if there is more than one element in the row that has a value of zero:
df['invalid'] = df.apply(lambda x: True if (x == 0).sum() > 1 else False, axis=1)

>df

   A  B  C  D  E invalid
0  5  0  1  0  5    True
1  2  1  4  3  5   False
2  5  1  4  4  3   False
3  2  1  0  2  5   False

To decompose a bit, the apply I'm doing is basically the same as doing:
more_than_one_zero = (df == 0).sum(axis=1) > 1

>more_than_one_zero
0     True
1    False
2    False
3    False
dtype: bool

df[more_than_one_zero, 'invalid'] = True
df[~more_than_one_zero, 'invalid'= False


text:
Q: Print default value if index is not in awk array $ cat file1 #It contains ID:Name
5:John
4:Michel

$ cat file2 #It contains ID
5
4
3

I want to Replace the IDs in file2 with Names from file1, output required
John
Michel
NO MATCH FOUND

I need to expand the below code to reult NO MATCH FOUND text.
awk -F":" 'NR==FNR {a[$1]=$2;next} {print a[$1]}' file1 file2

My current result:
John
Michel
        << empty line

Thanks,

A: You can use a ternary operator for this: print ($1 in a)?a[$1]:"NO MATCH FOUND". That is, if $1 is in the array, print it; otherwise, print the text "NO MATCH FOUND".
All together:
$ awk -F":" 'NR==FNR {a[$1]=$2;next} {print ($1 in a)?a[$1]:"NO MATCH FOUND"}' f1 f2
John
Michel
NO MATCH FOUND

A: You can test whether the index occurs in the array:
$ awk -F":" 'NR==FNR {a[$1]=$2;next} $1 in a {print a[$1]; next} {print "NOT FOUND"}' file1 file2
John
Michel
NOT FOUND

A: if file2 has only digit (no space at the end)
awk -F ':' '$1 in A {print A[$1];next}{if($2~/^$/) print "NOT FOUND";else A[$1]=$2}' file1

if not
awk -F '[:[:blank:]]' '$1 in A {print A[$1];next}{if($2~/^$/) print "NOT FOUND";else A[$1]=$2}' file1 file2


text:
Q: Clarification of the topology lemma "Any continuous and open injection of the open disk extends over the circle" My elementary topology 1 class last semester used the book "Topology:  Point-Set and Geometric" by Paul Schick, and covered through the end of chapter 8.  I am working through the rest of the book on my own, and I came across the following lemma in chapter 10 on the classification of surfaces:

Lemma 10.3.1 Any continuous and open injection of the open unit disk into a subspace of $\mathbb{R}^n$ extends over the circle.  That is, if  $ f \colon B = B_1(\vec{0})_{\mathfrak{U}^2} \rightarrow X_{\tau} $, with $ X_{\tau} \subset \mathbb{R}^n_{\mathfrak{U}^2}$, is a continuous and open injection, then $f$ extends to a continuous injection of the closed unit disk $\overline{f} \colon Cl(B) = D^2 \rightarrow X $.

In the Hint at how to proceed with a proof, the book states:
"Hint:  If $x \in S^1 = \partial B$, then there exists a sequence of points $\{x_n\}_{n \in \mathbb{N}} \subset B$ such that $x_n \rightarrow x$.  Define $\overline{f}(x)$ as $\lim_{n \to \infty} f(x_n)$.  Show $f$ is continuous and $1-1$."
My first question is: Why does the extension $\overline{f}$ still have to have codomain X (can't it be larger than X)?  First, consider the notational examples $f : \mathbb{R} \rightarrow \mathbb{R}$ and $f : \mathbb{R} \rightarrow [-2,\infty)$.  Both are correct (at least in the majority of notations I have seen from most authors, including Schick) for the function f defined by $f(x) = x^2$ where the domain is all reals.
Now back to this lemma in particular, just because every element of the sequence $\{f(x_n)\}$ is in B doesn't mean $\lim_{n \to \infty} f(x_n) \in B$.  In fact, the lemma itself is using the fact that the limit may lie in the set B or in the boundary of B.  Since B is open, the two sets or disjoint.  Therefore if we define $\overline{f}(x)$ as $\lim_{n \to \infty} f(x_n)$, then for $x \in \partial B$, $f(x) \notin B$, and then we may have also $f(x) \notin X$.
For example, let the function $f$ be defined as $f(x) = x$.  Then $f(B) = B$, and we can write $f \colon B \rightarrow B$, but $\overline{f}(Cl(B)) = \overline{f}(D^2) = D^2 \supset B$, then the statement: $\overline{f} \colon Cl(B) = D^2 \rightarrow B $ is incorrect.
So is the notation used in the lemma from the book simply incorrect?  Or is the lemma instead supposed to mean that it holds for some choice of $X$?  I realize this may be notational nit-picking, but it seems rather important to me distinguish the precise extent of what the lemma is claiming.
My second question is hopefully shorter:  The lemma states that "$ X_{\tau} \subset \mathbb{R}^n_{\mathfrak{U}^2}$", but if X is a subspace of $\mathbb{R}^n_{\mathfrak{U}^2}$, then isn't $\tau = \mathfrak{U}^2$ or simply the subspace topology?

A: Here is an example, but to understand it you need some complex analysis.  Let $U$ be the domain in the complex plane bounded by the Warsaw circle $W$:

Then $U$ is bounded and simply connected. Let $f: D\to U$ denote the Riemann mapping, i.e. the (essentially) unique conformal mapping. Then $f$ is a homeomorphism to its image. However, $f$ does not admit a continuous extension to the boundary circle since, otherwise, such extension would define a continuous mapping $g: S^1\to W=g(S^1)$. It would then follow that $W$ is locally connected, but $W$ is not locally connected. qed
I am now puzzled by what the author of the book had in mind. I think, the lesson here is that you cannot always trust to what is written in textbooks.


text:
Q: java : ClassCastException while receiving list of objects using JPA I'm trying to receive a list of objects of type Tempfiles and I'm not sure what has gone wrong in the way of fetching it. and when I receive the list, the size of the list is not zero but when I try to use it, I'm getting a ClassCastException :
Here's the pojo of the class Tempfiles :
@Entity
@Table(name="tempfiles")
@NamedQuery(name="Tempfile.findAll", query="SELECT t FROM Tempfile t")
public class Tempfile implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer tempfilesid;

    private byte[] filestream;

    //bi-directional many-to-one association to Filemetadata
    @ManyToOne
    @JoinColumn(name="documentid")
    private Filemetadata filemetadata;

    public Tempfile() {
    }

    public Integer getTempfilesid() {
        return this.tempfilesid;
    }

    public void setTempfilesid(Integer tempfilesid) {
        this.tempfilesid = tempfilesid;
    }

    public byte[] getFilestream() {
        return this.filestream;
    }

    public void setFilestream(byte[] filestream) {
        this.filestream = filestream;
    }

    public Filemetadata getFilemetadata() {
        return this.filemetadata;
    }

    public void setFilemetadata(Filemetadata filemetadata) {
        this.filemetadata = filemetadata;
    }
}

Here's the method that I use to :
public List getTempFileData()
    {
        String METHOD_NAME = "getTempFileData";
        logger.logEntering(METHOD_NAME);
        String strQueryToGetStream = "select t.tempfilesid, t.filemetadata.documentid, t.filestream from Tempfile t";
        logger.logInfo(strQueryToGetStream);
        Query query = entityManager.createQuery(strQueryToGetStream);
        List <Tempfile>tempFileList = query.getResultList();
        logger.logExiting(METHOD_NAME);
        return tempFileList;
    }

Here's how I receive it :
List <Tempfile>tempFileList = fileDao.getTempFileData();

And I get the exception when I use the list in a loop :
for(Tempfile tempFile : tempFileList)
{
    decryptAndEncryptStream(tempFile, job, publicKey);
}

And this is the exception I'm getting :
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.global.empris.domain.Tempfile

Would greatly appreciate your help and thanks in advance.

A: Your query is returning a list of Object[] instead of TempFile. You are only choosing specific columns, so it won't be mapped to the full object.
Process each Object[] like you would a resultset, or change your query to select a full object (i.e. SELECT t FROM Tempfile t).

A: IMO, you're getting an array of objects from JPA, because you only selected a portion of your entity. If you want your entity, select it and fetch its children collections like so
select t from Tempfile t left join fetch t.filestream

A: The statement List <Tempfile>tempFileList = query.getResultList(); returns a List<Object>. You should us Transformers.aliasToBean(TempFile.class)


text:
Q: Sentence structure and meaning (parallel structure) In the first paragraph of this article about friendship, I encountered the following sentence:

Already the characteristically modern relationship, it [friendship] has in recent
  decades become the universal one: the form of connection in terms of
  which all others are understood, against which they are all measured,
  into which they have all dissolved.

I am struggling to understand what this sentence is trying to convey, especially the bolded part. My guess is that it means
(1) Any other people are considered friend if and only if I understand them.
(2) I always evaluate other people using friendship as the only measure. That is, I always divide all other people into two groups: friends and non-friends, and there exists no third catagory.
(3) Once someone becomes my friend, he/she is integrated(dissolve) into a large homogeneous group, namely friends, and is not treated as a separate person any more.
I am particularly not sure about the second and the third points, while not 100% sure about the first point as well. If anyone understand this sentence I will be grateful for any help.

A: The key to understanding the meaning is by reading the text following the sentence - the sentence on its own is very confusing because there's no context.
So if we read further in the article:

Romantic partners refer to each other as boyfriend and girlfriend.
  Spouses boast that they are each other's best friends. Parents urge
  their young children and beg their teenage ones to think of them as
  friends. Adult siblings, released from competition for parental
  resources that in traditional society made them anything but friends
  (think of Jacob and Esau), now treat one another in exactly those
  terms. Teachers, clergymen, and even bosses seek to mitigate and
  legitimate their authority by asking those they oversee to regard them
  as friends. We're all on a first-name basis, and when we vote for
  president, we ask ourselves whom we'd rather have a beer with. As the
  anthropologist Robert Brain has put it, we're friends with everyone
  now.

Romantic partners also considers as friends, spouses considers as friends, parental relationship considers as friends; and so forth through other relationships.
So as I understand the meaning it is that the the characteristics of the type "friendship" has become the norm for other types of relationships as well.   Note especially the last line of the paragraph:
As the anthropologist Robert Brain has put it, we're friends with everyone now.
So using that:
The form of connection in terms of which all others are understood
We understand relationships based on the way we understand friendships.
against which they are all measured
We measure relationships in the same manner we measure friendship.
into which they have all dissolved.
This speaks to the "we're friends" line; all relationships have dissolved into friendships.


text:
Q: Blocking *.example.com at the OS (Windows) level For privacy and performance reasons, I'd like to prevent my computer from ever communicating with certain Internet hosts. I'd like to do this at the OS level, not through web browser plug-ins (not broad enough), or even through my home router (my laptop travels). I'd prefer to use built-in tools.
I'm running Windows 7 Professional 64-bit. I'm all too familiar with the Windows hosts file - and its limitations. There seems to be some confusion over whether hosts supports wildcards, but my own tests confirm that it does not.
I have experimented with Windows Firewall and the IP Security Policy MMC snap-in. So far as I can tell, both require numeric addresses. I don't want to block specific IP addresses, or ranges of addresses, in part because IP-address-to-hostname mappings can and do change.
Is there any tool in Windows 7 Professional with which I can block (or route to 0.0.0.0) communication with Internet hosts by hostname mask? If not, are there any good, free, third-party tools?

A: Try an IP blocker
http://blocklistpro.com/download-center/protowall/
There are many other IP blockers available, most allow you to make your own block lists and allow for ip ranges
Some do not work with W7 very well, do your homework.

A: The "easiest" way to do this would be to run your own DNS server and add primary zones for the domain(s) you want to block. You wouldn't even need to create 'A' records. any references to hosts within the zone (domain) would be returned unresolved by your DNS server. Posadis is one freeware/open source DNS available that runs under Windows (though I have not used is personally). Of course, if you have just about any version of Windows Server running anywhere, you can use Microsoft's DNS server.
One side "benefit" of this solution is that you could (if you wanted to) redirect requests to the "banned" domains to an internal "not allowed" web page.

A: Taking over the DNS resolver functions is a good solution.  You may want to sign up for an account at OpenDNS and hard code the DNS server settings in Windows to use OpenDNS as your resolver.  They allow you to enter domains that will always be blocked.  Sign up is free but a small fee gets you extra features.

A: Use OpenDNS. They can do category filtering('Nudity', 'Pornography', 'Gambling', 'Adware', etc) in addition to individual domains. Downside is that it requires a little extra setup on the server side for dynamic updates, but it is documented here.


text:
Q: Detect color in image I would like to have R detect a given color in a section of an image.
I've been reading about RGB schemes, but I thought there would maybe a package or a way to have R detect a cluster of pixels where, for example, the color yellow takes place.
Is there a solution or am I just trapped in RGB?
Thanks.

A: Here you go:
install.packages('raster')
library(raster)
#Get some data
duck.jpg<-tempfile()
download.file('http://www.pilgrimshospices.org/wp-content/uploads/Pilgrims-Hospice-Duck.jpg',duck.jpg,mode="wb")

#Plug it into a stack object
duck.raster<-stack(duck.jpg)
names(duck.raster)<-c('r','g','b')
#Look at it
plotRGB(duck.raster)

duck.yellow<-duck.raster

duck.yellow$Yellow_spots<-0
duck.yellow$Yellow_spots[duck.yellow$r<250&duck.yellow$g<250&duck.yellow$b>5]<-1
plot(duck.yellow$Yellow_spots)

So, just a few teachable points here. A digital image is basically a bucket for holding pixel values. So all you need to do to subset a raster (read: digital image), is use some tool to read it into R; decide how you want to subset it; and subset it in the same way you would subset any other data in R.
Another way to think about a raster in R is a stack of same size matrices, with the number of matrices in the stack as the number of bands in the image. In this manner, you can manipulate the data as you would manipulate any other matrix in R.